repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
twitter/cloudhopper-commons | ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteUtil.java | ByteUtil.encodeHex | @Deprecated
public static String encodeHex(byte[] data, char delimiter) {
// the result
StringBuilder result = new StringBuilder();
short val = 0;
// encode each byte into a hex dump
for (int i = 0; i < data.length; i++) {
val = decodeUnsigned(data[i]);
result.append(padLeading(Integer.toHexString((int) val), 2));
result.append(delimiter);
}
// return encoded text
return result.toString();
} | java | @Deprecated
public static String encodeHex(byte[] data, char delimiter) {
// the result
StringBuilder result = new StringBuilder();
short val = 0;
// encode each byte into a hex dump
for (int i = 0; i < data.length; i++) {
val = decodeUnsigned(data[i]);
result.append(padLeading(Integer.toHexString((int) val), 2));
result.append(delimiter);
}
// return encoded text
return result.toString();
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"encodeHex",
"(",
"byte",
"[",
"]",
"data",
",",
"char",
"delimiter",
")",
"{",
"// the result",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"short",
"val",
"=",
"0",
";",
"// enco... | Encodes a byte array into a hex string (hex dump).
@deprecated Please see class HexUtil | [
"Encodes",
"a",
"byte",
"array",
"into",
"a",
"hex",
"string",
"(",
"hex",
"dump",
")",
"."
] | train | https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteUtil.java#L156-L172 |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/ImmutableList.java | ImmutableList.from | @Nonnull
@SafeVarargs
public static <A> ImmutableList<A> from(@Nonnull A... el) {
return fromBounded(el, 0, el.length);
} | java | @Nonnull
@SafeVarargs
public static <A> ImmutableList<A> from(@Nonnull A... el) {
return fromBounded(el, 0, el.length);
} | [
"@",
"Nonnull",
"@",
"SafeVarargs",
"public",
"static",
"<",
"A",
">",
"ImmutableList",
"<",
"A",
">",
"from",
"(",
"@",
"Nonnull",
"A",
"...",
"el",
")",
"{",
"return",
"fromBounded",
"(",
"el",
",",
"0",
",",
"el",
".",
"length",
")",
";",
"}"
] | A helper constructor to create a potentially empty {@link ImmutableList}.
@param el Elements of the list
@param <A> The type of elements
@return a <code>ImmutableList</code> of type <code>A</code>. | [
"A",
"helper",
"constructor",
"to",
"create",
"a",
"potentially",
"empty",
"{",
"@link",
"ImmutableList",
"}",
"."
] | train | https://github.com/shapesecurity/shape-functional-java/blob/02edea5a901b8603f6a852478ec009857fa012d6/src/main/java/com/shapesecurity/functional/data/ImmutableList.java#L170-L174 |
dlemmermann/CalendarFX | CalendarFXRecurrence/src/main/java/com/google/ical/values/PeriodValueImpl.java | PeriodValueImpl.createFromDuration | public static PeriodValue createFromDuration(DateValue start, DateValue dur) {
DateValue end = TimeUtils.add(start, dur);
if (end instanceof TimeValue && !(start instanceof TimeValue)) {
start = TimeUtils.dayStart(start);
}
return new PeriodValueImpl(start, end);
} | java | public static PeriodValue createFromDuration(DateValue start, DateValue dur) {
DateValue end = TimeUtils.add(start, dur);
if (end instanceof TimeValue && !(start instanceof TimeValue)) {
start = TimeUtils.dayStart(start);
}
return new PeriodValueImpl(start, end);
} | [
"public",
"static",
"PeriodValue",
"createFromDuration",
"(",
"DateValue",
"start",
",",
"DateValue",
"dur",
")",
"{",
"DateValue",
"end",
"=",
"TimeUtils",
".",
"add",
"(",
"start",
",",
"dur",
")",
";",
"if",
"(",
"end",
"instanceof",
"TimeValue",
"&&",
... | returns a period with the given start date and duration.
@param start non null.
@param dur a positive duration represented as a DateValue. | [
"returns",
"a",
"period",
"with",
"the",
"given",
"start",
"date",
"and",
"duration",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXRecurrence/src/main/java/com/google/ical/values/PeriodValueImpl.java#L49-L55 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java | ValueEnforcer.isBetweenExclusive | public static float isBetweenExclusive (final float fValue,
final String sName,
final float fLowerBoundExclusive,
final float fUpperBoundExclusive)
{
if (isEnabled ())
return isBetweenExclusive (fValue, () -> sName, fLowerBoundExclusive, fUpperBoundExclusive);
return fValue;
} | java | public static float isBetweenExclusive (final float fValue,
final String sName,
final float fLowerBoundExclusive,
final float fUpperBoundExclusive)
{
if (isEnabled ())
return isBetweenExclusive (fValue, () -> sName, fLowerBoundExclusive, fUpperBoundExclusive);
return fValue;
} | [
"public",
"static",
"float",
"isBetweenExclusive",
"(",
"final",
"float",
"fValue",
",",
"final",
"String",
"sName",
",",
"final",
"float",
"fLowerBoundExclusive",
",",
"final",
"float",
"fUpperBoundExclusive",
")",
"{",
"if",
"(",
"isEnabled",
"(",
")",
")",
... | Check if
<code>nValue > nLowerBoundInclusive && nValue < nUpperBoundInclusive</code>
@param fValue
Value
@param sName
Name
@param fLowerBoundExclusive
Lower bound
@param fUpperBoundExclusive
Upper bound
@return The value | [
"Check",
"if",
"<code",
">",
"nValue",
">",
";",
"nLowerBoundInclusive",
"&",
";",
"&",
";",
"nValue",
"<",
";",
"nUpperBoundInclusive<",
"/",
"code",
">"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L2899-L2907 |
Cornutum/tcases | tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java | SystemInputJson.addAnnotations | private static JsonObjectBuilder addAnnotations( JsonObjectBuilder builder, IAnnotated annotated)
{
JsonObjectBuilder annotations = Json.createObjectBuilder();
toStream( annotated.getAnnotations()).forEach( name -> annotations.add( name, annotated.getAnnotation( name)));
JsonObject json = annotations.build();
if( !json.isEmpty())
{
builder.add( HAS_KEY, json);
}
return builder;
} | java | private static JsonObjectBuilder addAnnotations( JsonObjectBuilder builder, IAnnotated annotated)
{
JsonObjectBuilder annotations = Json.createObjectBuilder();
toStream( annotated.getAnnotations()).forEach( name -> annotations.add( name, annotated.getAnnotation( name)));
JsonObject json = annotations.build();
if( !json.isEmpty())
{
builder.add( HAS_KEY, json);
}
return builder;
} | [
"private",
"static",
"JsonObjectBuilder",
"addAnnotations",
"(",
"JsonObjectBuilder",
"builder",
",",
"IAnnotated",
"annotated",
")",
"{",
"JsonObjectBuilder",
"annotations",
"=",
"Json",
".",
"createObjectBuilder",
"(",
")",
";",
"toStream",
"(",
"annotated",
".",
... | Add any annotatations from the given Annotated object to the given JsonObjectBuilder. | [
"Add",
"any",
"annotatations",
"from",
"the",
"given",
"Annotated",
"object",
"to",
"the",
"given",
"JsonObjectBuilder",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java#L142-L154 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/db/SQLUtils.java | SQLUtils.closeResultSet | public static void closeResultSet(ResultSet resultSet, String sql) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql,
e);
}
}
} | java | public static void closeResultSet(ResultSet resultSet, String sql) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql,
e);
}
}
} | [
"public",
"static",
"void",
"closeResultSet",
"(",
"ResultSet",
"resultSet",
",",
"String",
"sql",
")",
"{",
"if",
"(",
"resultSet",
"!=",
"null",
")",
"{",
"try",
"{",
"resultSet",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
"... | Close the ResultSet
@param resultSet
result set
@param sql
sql statement | [
"Close",
"the",
"ResultSet"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/db/SQLUtils.java#L553-L562 |
apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/config/ConfigBuilder.java | ConfigBuilder.loadProps | public ConfigBuilder loadProps(Properties props, String scopePrefix) {
Preconditions.checkNotNull(props);
Preconditions.checkNotNull(scopePrefix);
int scopePrefixLen = scopePrefix.length();
for (Map.Entry<Object, Object> propEntry : props.entrySet()) {
String propName = propEntry.getKey().toString();
if (propName.startsWith(scopePrefix)) {
String scopedName = propName.substring(scopePrefixLen);
if (scopedName.isEmpty()) {
throw new RuntimeException("Illegal scoped property:" + propName);
}
if (!Character.isAlphabetic(scopedName.charAt(0))) {
throw new RuntimeException(
"Scoped name for property " + propName + " should start with a character: " + scopedName);
}
this.primitiveProps.put(scopedName, propEntry.getValue());
}
}
return this;
} | java | public ConfigBuilder loadProps(Properties props, String scopePrefix) {
Preconditions.checkNotNull(props);
Preconditions.checkNotNull(scopePrefix);
int scopePrefixLen = scopePrefix.length();
for (Map.Entry<Object, Object> propEntry : props.entrySet()) {
String propName = propEntry.getKey().toString();
if (propName.startsWith(scopePrefix)) {
String scopedName = propName.substring(scopePrefixLen);
if (scopedName.isEmpty()) {
throw new RuntimeException("Illegal scoped property:" + propName);
}
if (!Character.isAlphabetic(scopedName.charAt(0))) {
throw new RuntimeException(
"Scoped name for property " + propName + " should start with a character: " + scopedName);
}
this.primitiveProps.put(scopedName, propEntry.getValue());
}
}
return this;
} | [
"public",
"ConfigBuilder",
"loadProps",
"(",
"Properties",
"props",
",",
"String",
"scopePrefix",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"props",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"scopePrefix",
")",
";",
"int",
"scopePrefixLen",
... | Loads properties which have a given name prefix into the config. The following restrictions
apply:
<ul>
<li>No property can have a name that is equal to the prefix
<li>After removal of the prefix, the remaining property name should start with a letter.
</ul>
@param props the collection from where to load the properties
@param scopePrefix only properties with this prefix will be considered. The prefix will be
removed from the names of the keys added to the {@link Config} object.
The prefix can be an empty string but cannot be null. | [
"Loads",
"properties",
"which",
"have",
"a",
"given",
"name",
"prefix",
"into",
"the",
"config",
".",
"The",
"following",
"restrictions",
"apply",
":",
"<ul",
">",
"<li",
">",
"No",
"property",
"can",
"have",
"a",
"name",
"that",
"is",
"equal",
"to",
"th... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/config/ConfigBuilder.java#L56-L78 |
JoeKerouac/utils | src/main/java/com/joe/utils/reflect/ReflectUtil.java | ReflectUtil.getMethod | public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Assert.notNull(clazz, "类型不能为空");
Assert.notNull(methodName, "方法名不能为空");
return METHOD_CACHE.compute(new MethodKey(methodName, clazz, parameterTypes), (k, v) -> {
if (v == null) {
try {
return allowAccess(clazz.getDeclaredMethod(methodName, parameterTypes));
} catch (NoSuchMethodException e) {
log.error(
StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName,
parameterTypes == null ? "null" : Arrays.toString(parameterTypes)));
throw new ReflectException(
StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName,
parameterTypes == null ? "null" : Arrays.toString(parameterTypes)),
e);
}
} else {
return v;
}
});
} | java | public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Assert.notNull(clazz, "类型不能为空");
Assert.notNull(methodName, "方法名不能为空");
return METHOD_CACHE.compute(new MethodKey(methodName, clazz, parameterTypes), (k, v) -> {
if (v == null) {
try {
return allowAccess(clazz.getDeclaredMethod(methodName, parameterTypes));
} catch (NoSuchMethodException e) {
log.error(
StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName,
parameterTypes == null ? "null" : Arrays.toString(parameterTypes)));
throw new ReflectException(
StringUtils.format("类[{0}]中不存在方法名为[{1}]、方法列表为[{2}]的方法", clazz, methodName,
parameterTypes == null ? "null" : Arrays.toString(parameterTypes)),
e);
}
} else {
return v;
}
});
} | [
"public",
"static",
"Method",
"getMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"parameterTypes",
")",
"{",
"Assert",
".",
"notNull",
"(",
"clazz",
",",
"\"类型不能为空\");",
"",
"",
"Assert",
... | 获取指定类型中指定的方法(无法获取本类未覆写过的父类方法)
@param clazz 类型
@param methodName 方法名
@param parameterTypes 方法参数类型
@return 指定方法,获取不到时会抛出异常 | [
"获取指定类型中指定的方法(无法获取本类未覆写过的父类方法)"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/ReflectUtil.java#L214-L235 |
loldevs/riotapi | rtmp/src/main/java/net/boreeas/riotapi/rtmp/services/LoginService.java | LoginService.performLcdsHeartBeat | public String performLcdsHeartBeat(long accountId, String sessionToken, int heartBeatCount) {
return performLcdsHeartBeat(accountId, sessionToken, heartBeatCount, new Date());
} | java | public String performLcdsHeartBeat(long accountId, String sessionToken, int heartBeatCount) {
return performLcdsHeartBeat(accountId, sessionToken, heartBeatCount, new Date());
} | [
"public",
"String",
"performLcdsHeartBeat",
"(",
"long",
"accountId",
",",
"String",
"sessionToken",
",",
"int",
"heartBeatCount",
")",
"{",
"return",
"performLcdsHeartBeat",
"(",
"accountId",
",",
"sessionToken",
",",
"heartBeatCount",
",",
"new",
"Date",
"(",
")... | Perform a heartbeat
@param accountId The user id
@param sessionToken The token for the current session
@param heartBeatCount The amount of heartbeats that have been sent
@return A string | [
"Perform",
"a",
"heartbeat"
] | train | https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rtmp/src/main/java/net/boreeas/riotapi/rtmp/services/LoginService.java#L57-L59 |
paypal/SeLion | client/src/main/java/com/paypal/selion/internal/platform/pageyaml/YamlV2Reader.java | YamlV2Reader.getGuiMap | @Override
public Map<String, String> getGuiMap(String locale) {
return getGuiMap(locale, WebDriverPlatform.UNDEFINED);
} | java | @Override
public Map<String, String> getGuiMap(String locale) {
return getGuiMap(locale, WebDriverPlatform.UNDEFINED);
} | [
"@",
"Override",
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getGuiMap",
"(",
"String",
"locale",
")",
"{",
"return",
"getGuiMap",
"(",
"locale",
",",
"WebDriverPlatform",
".",
"UNDEFINED",
")",
";",
"}"
] | The user needs to provide the locale for which data needs to be read. After successfully reading the data from
the input stream, it is placed in the hash map and returned to the users.
If the locale provided is not set for a certain element it will fall back to the default locale that is set in
the Yaml. If default locale is not provided in the Yaml it will use US.
@param locale
Signifies the language or site language to read. | [
"The",
"user",
"needs",
"to",
"provide",
"the",
"locale",
"for",
"which",
"data",
"needs",
"to",
"be",
"read",
".",
"After",
"successfully",
"reading",
"the",
"data",
"from",
"the",
"input",
"stream",
"it",
"is",
"placed",
"in",
"the",
"hash",
"map",
"an... | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/platform/pageyaml/YamlV2Reader.java#L64-L67 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.findAll | public static <T> Collection<T> findAll(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
Collection<T> answer = new ArrayList<T>();
return findAll(condition, answer, new ArrayIterator<T>(self));
} | java | public static <T> Collection<T> findAll(T[] self, @ClosureParams(FirstParam.Component.class) Closure condition) {
Collection<T> answer = new ArrayList<T>();
return findAll(condition, answer, new ArrayIterator<T>(self));
} | [
"public",
"static",
"<",
"T",
">",
"Collection",
"<",
"T",
">",
"findAll",
"(",
"T",
"[",
"]",
"self",
",",
"@",
"ClosureParams",
"(",
"FirstParam",
".",
"Component",
".",
"class",
")",
"Closure",
"condition",
")",
"{",
"Collection",
"<",
"T",
">",
"... | Finds all elements of the array matching the given Closure condition.
<pre class="groovyTestCase">
def items = [1,2,3,4] as Integer[]
assert [2,4] == items.findAll { it % 2 == 0 }
</pre>
@param self an array
@param condition a closure condition
@return a list of matching values
@since 2.0 | [
"Finds",
"all",
"elements",
"of",
"the",
"array",
"matching",
"the",
"given",
"Closure",
"condition",
".",
"<pre",
"class",
"=",
"groovyTestCase",
">",
"def",
"items",
"=",
"[",
"1",
"2",
"3",
"4",
"]",
"as",
"Integer",
"[]",
"assert",
"[",
"2",
"4",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L4792-L4795 |
astrapi69/mystic-crypt | crypt-core/src/main/java/de/alpharogroup/crypto/core/AbstractFileEncryptor.java | AbstractFileEncryptor.newCipher | @Override
protected Cipher newCipher(final String privateKey, final String algorithm, final byte[] salt,
final int iterationCount, final int operationMode)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
final KeySpec keySpec = newKeySpec(privateKey, salt, iterationCount);
final SecretKeyFactory factory = newSecretKeyFactory(algorithm);
final SecretKey key = factory.generateSecret(keySpec);
final AlgorithmParameterSpec paramSpec = newAlgorithmParameterSpec(salt, iterationCount);
return newCipher(operationMode, key, paramSpec, key.getAlgorithm());
} | java | @Override
protected Cipher newCipher(final String privateKey, final String algorithm, final byte[] salt,
final int iterationCount, final int operationMode)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
final KeySpec keySpec = newKeySpec(privateKey, salt, iterationCount);
final SecretKeyFactory factory = newSecretKeyFactory(algorithm);
final SecretKey key = factory.generateSecret(keySpec);
final AlgorithmParameterSpec paramSpec = newAlgorithmParameterSpec(salt, iterationCount);
return newCipher(operationMode, key, paramSpec, key.getAlgorithm());
} | [
"@",
"Override",
"protected",
"Cipher",
"newCipher",
"(",
"final",
"String",
"privateKey",
",",
"final",
"String",
"algorithm",
",",
"final",
"byte",
"[",
"]",
"salt",
",",
"final",
"int",
"iterationCount",
",",
"final",
"int",
"operationMode",
")",
"throws",
... | Factory method for creating a new {@link Cipher} from the given parameters. This method is
invoked in the constructor from the derived classes and can be overridden so users can
provide their own version of a new {@link Cipher} from the given parameters.
@param privateKey
the private key
@param algorithm
the algorithm
@param salt
the salt.
@param iterationCount
the iteration count
@param operationMode
the operation mode for the new cipher object
@return the cipher
@throws NoSuchAlgorithmException
is thrown if instantiation of the SecretKeyFactory object fails.
@throws InvalidKeySpecException
is thrown if generation of the SecretKey object fails.
@throws NoSuchPaddingException
is thrown if instantiation of the cypher object fails.
@throws InvalidKeyException
is thrown if initialization of the cypher object fails.
@throws InvalidAlgorithmParameterException
is thrown if initialization of the cypher object fails.
@throws UnsupportedEncodingException
is thrown if the named charset is not supported. | [
"Factory",
"method",
"for",
"creating",
"a",
"new",
"{",
"@link",
"Cipher",
"}",
"from",
"the",
"given",
"parameters",
".",
"This",
"method",
"is",
"invoked",
"in",
"the",
"constructor",
"from",
"the",
"derived",
"classes",
"and",
"can",
"be",
"overridden",
... | train | https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-core/src/main/java/de/alpharogroup/crypto/core/AbstractFileEncryptor.java#L177-L188 |
synchronoss/cpo-api | cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java | CassandraCpoAdapter.updateObjects | @Override
public <T> long updateObjects(String name, Collection<T> coll, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException {
return processUpdateGroup(coll, CpoAdapter.UPDATE_GROUP, name, wheres, orderBy, nativeExpressions);
} | java | @Override
public <T> long updateObjects(String name, Collection<T> coll, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException {
return processUpdateGroup(coll, CpoAdapter.UPDATE_GROUP, name, wheres, orderBy, nativeExpressions);
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"long",
"updateObjects",
"(",
"String",
"name",
",",
"Collection",
"<",
"T",
">",
"coll",
",",
"Collection",
"<",
"CpoWhere",
">",
"wheres",
",",
"Collection",
"<",
"CpoOrderBy",
">",
"orderBy",
",",
"Collection",
... | Updates a collection of Objects in the datasource. The assumption is that the objects contained in the collection
exist in the datasource. This method stores the object in the datasource. The objects in the collection will be
treated as one transaction, meaning that if one of the objects fail being updated in the datasource then the entire
collection will be rolled back, if supported by the datasource.
<p/>
<pre>Example:
<code>
<p/>
class SomeObject so = null;
class CpoAdapter cpo = null;
<p/>
try {
cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false));
} catch (CpoException ce) {
// Handle the error
cpo = null;
}
<p/>
if (cpo!=null) {
ArrayList al = new ArrayList();
for (int i=0; i<3; i++){
so = new SomeObject();
so.setId(1);
so.setName("SomeName");
al.add(so);
}
try{
cpo.updateObjects("myUpdate",al);
} catch (CpoException ce) {
// Handle the error
}
}
</code>
</pre>
@param name The String name of the UPDATE Function Group that will be used to create the object in the datasource.
null signifies that the default rules will be used.
@param coll This is a collection of objects that have been defined within the metadata of the datasource. If the
class is not defined an exception will be thrown.
@param wheres A collection of CpoWhere objects to be used by the function
@param orderBy A collection of CpoOrderBy objects to be used by the function
@param nativeExpressions A collection of CpoNativeFunction objects to be used by the function
@return The number of objects updated in the datasource
@throws CpoException Thrown if there are errors accessing the datasource | [
"Updates",
"a",
"collection",
"of",
"Objects",
"in",
"the",
"datasource",
".",
"The",
"assumption",
"is",
"that",
"the",
"objects",
"contained",
"in",
"the",
"collection",
"exist",
"in",
"the",
"datasource",
".",
"This",
"method",
"stores",
"the",
"object",
... | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L1907-L1910 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/api/API.java | API.responseToXml | static String responseToXml(String endpointName, ApiResponse response) throws ApiException {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(endpointName);
doc.appendChild(rootElement);
response.toXML(doc, rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
return sw.toString();
} catch (Exception e) {
logger.error("Failed to convert API response to XML: " + e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
}
} | java | static String responseToXml(String endpointName, ApiResponse response) throws ApiException {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(endpointName);
doc.appendChild(rootElement);
response.toXML(doc, rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
return sw.toString();
} catch (Exception e) {
logger.error("Failed to convert API response to XML: " + e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e);
}
} | [
"static",
"String",
"responseToXml",
"(",
"String",
"endpointName",
",",
"ApiResponse",
"response",
")",
"throws",
"ApiException",
"{",
"try",
"{",
"DocumentBuilderFactory",
"docFactory",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
";",
"DocumentBuild... | Gets the XML representation of the given API {@code response}.
<p>
An XML element named with name of the endpoint and with child elements as given by
{@link ApiResponse#toXML(Document, Element)}.
@param endpointName the name of the API endpoint, must not be {@code null}.
@param response the API response, must not be {@code null}.
@return the XML representation of the given response.
@throws ApiException if an error occurred while converting the response. | [
"Gets",
"the",
"XML",
"representation",
"of",
"the",
"given",
"API",
"{",
"@code",
"response",
"}",
".",
"<p",
">",
"An",
"XML",
"element",
"named",
"with",
"name",
"of",
"the",
"endpoint",
"and",
"with",
"child",
"elements",
"as",
"given",
"by",
"{",
... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/api/API.java#L703-L727 |
lessthanoptimal/BoofCV | main/boofcv-simulation/src/main/java/boofcv/simulation/SimulatePlanarWorld.java | SimulatePlanarWorld.addSurface | public void addSurface(Se3_F64 rectToWorld , double widthWorld , GrayF32 texture ) {
SurfaceRect s = new SurfaceRect();
s.texture = texture.clone();
s.width3D = widthWorld;
s.rectToWorld = rectToWorld;
ImageMiscOps.flipHorizontal(s.texture);
scene.add(s);
} | java | public void addSurface(Se3_F64 rectToWorld , double widthWorld , GrayF32 texture ) {
SurfaceRect s = new SurfaceRect();
s.texture = texture.clone();
s.width3D = widthWorld;
s.rectToWorld = rectToWorld;
ImageMiscOps.flipHorizontal(s.texture);
scene.add(s);
} | [
"public",
"void",
"addSurface",
"(",
"Se3_F64",
"rectToWorld",
",",
"double",
"widthWorld",
",",
"GrayF32",
"texture",
")",
"{",
"SurfaceRect",
"s",
"=",
"new",
"SurfaceRect",
"(",
")",
";",
"s",
".",
"texture",
"=",
"texture",
".",
"clone",
"(",
")",
";... | <p>Adds a surface to the simulation. The center of the surface's coordinate system will be the image
center. Width is the length along the image's width. the world length along the image height is
width*texture.height/texture.width.</p>
<p>NOTE: The image is flipped horizontally internally so that when it is rendered it appears the same way
it is displayed on the screen as usual.</p>
@param rectToWorld Transform from surface to world coordinate systems
@param widthWorld Size of surface as measured along its width
@param texture Image describing the surface's appearance and shape. | [
"<p",
">",
"Adds",
"a",
"surface",
"to",
"the",
"simulation",
".",
"The",
"center",
"of",
"the",
"surface",
"s",
"coordinate",
"system",
"will",
"be",
"the",
"image",
"center",
".",
"Width",
"is",
"the",
"length",
"along",
"the",
"image",
"s",
"width",
... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-simulation/src/main/java/boofcv/simulation/SimulatePlanarWorld.java#L156-L165 |
wildfly/wildfly-core | protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java | AbstractMessageHandler.handleMessage | protected <T, A> void handleMessage(final Channel channel, final DataInput message, final ManagementRequestHeader header, ManagementRequestHandler<T, A> handler) throws IOException {
final ActiveOperation<T, A> support = getActiveOperation(header);
if(support == null) {
throw ProtocolLogger.ROOT_LOGGER.responseHandlerNotFound(header.getBatchId());
}
handleMessage(channel, message, header, support, handler);
} | java | protected <T, A> void handleMessage(final Channel channel, final DataInput message, final ManagementRequestHeader header, ManagementRequestHandler<T, A> handler) throws IOException {
final ActiveOperation<T, A> support = getActiveOperation(header);
if(support == null) {
throw ProtocolLogger.ROOT_LOGGER.responseHandlerNotFound(header.getBatchId());
}
handleMessage(channel, message, header, support, handler);
} | [
"protected",
"<",
"T",
",",
"A",
">",
"void",
"handleMessage",
"(",
"final",
"Channel",
"channel",
",",
"final",
"DataInput",
"message",
",",
"final",
"ManagementRequestHeader",
"header",
",",
"ManagementRequestHandler",
"<",
"T",
",",
"A",
">",
"handler",
")"... | Handle a message.
@param channel the channel
@param message the message
@param header the protocol header
@param handler the request handler
@throws IOException | [
"Handle",
"a",
"message",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java#L298-L304 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/raster/RasterImage.java | RasterImage.loadRasters | public void loadRasters(int imageHeight, boolean save, String prefix)
{
Check.notNull(prefix);
final Raster raster = Raster.load(rasterFile);
final int max = UtilConversion.boolToInt(rasterSmooth) + 1;
for (int m = 0; m < max; m++)
{
for (int i = 0; i < MAX_RASTERS; i++)
{
final String folder = prefix + Constant.UNDERSCORE + UtilFile.removeExtension(rasterFile.getName());
final String file = String.valueOf(i + m * MAX_RASTERS) + Constant.DOT + ImageFormat.PNG;
final Media rasterMedia = Medias.create(rasterFile.getParentPath(), folder, file);
final ImageBuffer rasterBuffer = createRaster(rasterMedia, raster, i, save);
rasters.add(rasterBuffer);
}
}
} | java | public void loadRasters(int imageHeight, boolean save, String prefix)
{
Check.notNull(prefix);
final Raster raster = Raster.load(rasterFile);
final int max = UtilConversion.boolToInt(rasterSmooth) + 1;
for (int m = 0; m < max; m++)
{
for (int i = 0; i < MAX_RASTERS; i++)
{
final String folder = prefix + Constant.UNDERSCORE + UtilFile.removeExtension(rasterFile.getName());
final String file = String.valueOf(i + m * MAX_RASTERS) + Constant.DOT + ImageFormat.PNG;
final Media rasterMedia = Medias.create(rasterFile.getParentPath(), folder, file);
final ImageBuffer rasterBuffer = createRaster(rasterMedia, raster, i, save);
rasters.add(rasterBuffer);
}
}
} | [
"public",
"void",
"loadRasters",
"(",
"int",
"imageHeight",
",",
"boolean",
"save",
",",
"String",
"prefix",
")",
"{",
"Check",
".",
"notNull",
"(",
"prefix",
")",
";",
"final",
"Raster",
"raster",
"=",
"Raster",
".",
"load",
"(",
"rasterFile",
")",
";",... | Load rasters.
@param imageHeight The local image height.
@param save <code>true</code> to save generated (if) rasters, <code>false</code> else.
@param prefix The folder prefix, if save is <code>true</code> (must not be <code>null</code>).
@throws LionEngineException If the raster data from the media are invalid. | [
"Load",
"rasters",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/raster/RasterImage.java#L138-L157 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/machinelearning/preprocessing/MinMaxScaler.java | MinMaxScaler.scale | private Double scale(Double value, Double min, Double max) {
if(min.equals(max)) {
if(value>max) {
return 1.0;
}
else if(value==max && value!=0.0) {
return 1.0;
}
else {
return 0.0;
}
}
else {
return (value-min)/(max-min);
}
} | java | private Double scale(Double value, Double min, Double max) {
if(min.equals(max)) {
if(value>max) {
return 1.0;
}
else if(value==max && value!=0.0) {
return 1.0;
}
else {
return 0.0;
}
}
else {
return (value-min)/(max-min);
}
} | [
"private",
"Double",
"scale",
"(",
"Double",
"value",
",",
"Double",
"min",
",",
"Double",
"max",
")",
"{",
"if",
"(",
"min",
".",
"equals",
"(",
"max",
")",
")",
"{",
"if",
"(",
"value",
">",
"max",
")",
"{",
"return",
"1.0",
";",
"}",
"else",
... | Performs the actual rescaling handling corner cases.
@param value
@param min
@param max
@return | [
"Performs",
"the",
"actual",
"rescaling",
"handling",
"corner",
"cases",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/machinelearning/preprocessing/MinMaxScaler.java#L208-L223 |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/holder/ImageHolder.java | ImageHolder.decideIcon | public Drawable decideIcon(Context ctx, int iconColor, boolean tint) {
Drawable icon = mIcon;
if (mIconRes != -1) {
icon = ContextCompat.getDrawable(ctx, mIconRes);
} else if (mUri != null) {
try {
InputStream inputStream = ctx.getContentResolver().openInputStream(mUri);
icon = Drawable.createFromStream(inputStream, mUri.toString());
} catch (FileNotFoundException e) {
//no need to handle this
}
}
//if we got an icon AND we have auto tinting enabled AND it is no IIcon, tint it ;)
if (icon != null && tint) {
icon = icon.mutate();
icon.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN);
}
return icon;
} | java | public Drawable decideIcon(Context ctx, int iconColor, boolean tint) {
Drawable icon = mIcon;
if (mIconRes != -1) {
icon = ContextCompat.getDrawable(ctx, mIconRes);
} else if (mUri != null) {
try {
InputStream inputStream = ctx.getContentResolver().openInputStream(mUri);
icon = Drawable.createFromStream(inputStream, mUri.toString());
} catch (FileNotFoundException e) {
//no need to handle this
}
}
//if we got an icon AND we have auto tinting enabled AND it is no IIcon, tint it ;)
if (icon != null && tint) {
icon = icon.mutate();
icon.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN);
}
return icon;
} | [
"public",
"Drawable",
"decideIcon",
"(",
"Context",
"ctx",
",",
"int",
"iconColor",
",",
"boolean",
"tint",
")",
"{",
"Drawable",
"icon",
"=",
"mIcon",
";",
"if",
"(",
"mIconRes",
"!=",
"-",
"1",
")",
"{",
"icon",
"=",
"ContextCompat",
".",
"getDrawable"... | this only handles Drawables
@param ctx
@param iconColor
@param tint
@return | [
"this",
"only",
"handles",
"Drawables"
] | train | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/holder/ImageHolder.java#L128-L149 |
kazocsaba/matrix | src/main/java/hu/kazocsaba/math/matrix/MatrixFactory.java | MatrixFactory.createVector | public static Vector2 createVector(double x, double y) {
Vector2 v=new Vector2Impl();
v.setX(x);
v.setY(y);
return v;
} | java | public static Vector2 createVector(double x, double y) {
Vector2 v=new Vector2Impl();
v.setX(x);
v.setY(y);
return v;
} | [
"public",
"static",
"Vector2",
"createVector",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"Vector2",
"v",
"=",
"new",
"Vector2Impl",
"(",
")",
";",
"v",
".",
"setX",
"(",
"x",
")",
";",
"v",
".",
"setY",
"(",
"y",
")",
";",
"return",
"v",
... | Creates and initializes a new 2D column vector.
@param x the x coordinate of the new vector
@param y the y coordinate of the new vector
@return the new vector | [
"Creates",
"and",
"initializes",
"a",
"new",
"2D",
"column",
"vector",
"."
] | train | https://github.com/kazocsaba/matrix/blob/018570db945fe616b25606fe605fa6e0c180ab5b/src/main/java/hu/kazocsaba/math/matrix/MatrixFactory.java#L20-L25 |
pip-services3-java/pip-services3-components-java | src/org/pipservices3/components/config/JsonConfigReader.java | JsonConfigReader.readObject | public Object readObject(String correlationId, ConfigParams parameters) throws ApplicationException {
if (_path == null)
throw new ConfigException(correlationId, "NO_PATH", "Missing config file path");
try {
Path path = Paths.get(_path);
String json = new String(Files.readAllBytes(path));
json = parameterize(json, parameters);
return jsonMapper.readValue(json, typeRef);
} catch (Exception ex) {
throw new FileException(correlationId, "READ_FAILED", "Failed reading configuration " + _path + ": " + ex)
.withDetails("path", _path).withCause(ex);
}
} | java | public Object readObject(String correlationId, ConfigParams parameters) throws ApplicationException {
if (_path == null)
throw new ConfigException(correlationId, "NO_PATH", "Missing config file path");
try {
Path path = Paths.get(_path);
String json = new String(Files.readAllBytes(path));
json = parameterize(json, parameters);
return jsonMapper.readValue(json, typeRef);
} catch (Exception ex) {
throw new FileException(correlationId, "READ_FAILED", "Failed reading configuration " + _path + ": " + ex)
.withDetails("path", _path).withCause(ex);
}
} | [
"public",
"Object",
"readObject",
"(",
"String",
"correlationId",
",",
"ConfigParams",
"parameters",
")",
"throws",
"ApplicationException",
"{",
"if",
"(",
"_path",
"==",
"null",
")",
"throw",
"new",
"ConfigException",
"(",
"correlationId",
",",
"\"NO_PATH\"",
","... | Reads configuration file, parameterizes its content and converts it into JSON
object.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param parameters values to parameters the configuration.
@return a JSON object with configuration.
@throws ApplicationException when error occured. | [
"Reads",
"configuration",
"file",
"parameterizes",
"its",
"content",
"and",
"converts",
"it",
"into",
"JSON",
"object",
"."
] | train | https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/config/JsonConfigReader.java#L72-L87 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/util/EntityUtils.java | EntityUtils.isEquipped | public static boolean isEquipped(EntityPlayer player, ItemStack itemStack, EnumHand hand)
{
return isEquipped(player, itemStack != null ? itemStack.getItem() : null, hand);
} | java | public static boolean isEquipped(EntityPlayer player, ItemStack itemStack, EnumHand hand)
{
return isEquipped(player, itemStack != null ? itemStack.getItem() : null, hand);
} | [
"public",
"static",
"boolean",
"isEquipped",
"(",
"EntityPlayer",
"player",
",",
"ItemStack",
"itemStack",
",",
"EnumHand",
"hand",
")",
"{",
"return",
"isEquipped",
"(",
"player",
",",
"itemStack",
"!=",
"null",
"?",
"itemStack",
".",
"getItem",
"(",
")",
"... | Checks if is the {@link Item} contained in the {@link ItemStack} is equipped for the player.
@param player the player
@param itemStack the item stack
@return true, if is equipped | [
"Checks",
"if",
"is",
"the",
"{",
"@link",
"Item",
"}",
"contained",
"in",
"the",
"{",
"@link",
"ItemStack",
"}",
"is",
"equipped",
"for",
"the",
"player",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/EntityUtils.java#L213-L216 |
threerings/gwt-utils | src/main/java/com/threerings/gwt/ui/PagedWidget.java | PagedWidget.displayPage | public void displayPage (final int page, boolean forceRefresh)
{
if (_page == page && !forceRefresh) {
return; // NOOP!
}
// Display the now loading widget, if necessary.
configureLoadingNavi(_controls, 0, _infoCol);
_page = Math.max(page, 0);
final boolean overQuery = (_model.getItemCount() < 0);
final int count = _resultsPerPage;
final int start = _resultsPerPage * page;
_model.doFetchRows(start, overQuery ? (count + 1) : count, new AsyncCallback<List<T>>() {
public void onSuccess (List<T> result) {
if (overQuery) {
// if we requested 1 item too many, see if we got it
if (result.size() < (count + 1)) {
// no: this is the last batch of items, woohoo
_lastItem = start + result.size();
} else {
// yes: strip it before anybody else gets to see it
result.remove(count);
_lastItem = -1;
}
} else {
// a valid item count should be available at this point
_lastItem = _model.getItemCount();
}
displayResults(start, count, result);
}
public void onFailure (Throwable caught) {
reportFailure(caught);
}
});
} | java | public void displayPage (final int page, boolean forceRefresh)
{
if (_page == page && !forceRefresh) {
return; // NOOP!
}
// Display the now loading widget, if necessary.
configureLoadingNavi(_controls, 0, _infoCol);
_page = Math.max(page, 0);
final boolean overQuery = (_model.getItemCount() < 0);
final int count = _resultsPerPage;
final int start = _resultsPerPage * page;
_model.doFetchRows(start, overQuery ? (count + 1) : count, new AsyncCallback<List<T>>() {
public void onSuccess (List<T> result) {
if (overQuery) {
// if we requested 1 item too many, see if we got it
if (result.size() < (count + 1)) {
// no: this is the last batch of items, woohoo
_lastItem = start + result.size();
} else {
// yes: strip it before anybody else gets to see it
result.remove(count);
_lastItem = -1;
}
} else {
// a valid item count should be available at this point
_lastItem = _model.getItemCount();
}
displayResults(start, count, result);
}
public void onFailure (Throwable caught) {
reportFailure(caught);
}
});
} | [
"public",
"void",
"displayPage",
"(",
"final",
"int",
"page",
",",
"boolean",
"forceRefresh",
")",
"{",
"if",
"(",
"_page",
"==",
"page",
"&&",
"!",
"forceRefresh",
")",
"{",
"return",
";",
"// NOOP!",
"}",
"// Display the now loading widget, if necessary.",
"co... | Displays the specified page. Does nothing if we are already displaying
that page unless forceRefresh is true. | [
"Displays",
"the",
"specified",
"page",
".",
"Does",
"nothing",
"if",
"we",
"are",
"already",
"displaying",
"that",
"page",
"unless",
"forceRefresh",
"is",
"true",
"."
] | train | https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/PagedWidget.java#L160-L196 |
jbundle/jbundle | thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/CachedRemoteTable.java | CachedRemoteTable.remove | public void remove(Object data, int iOpenMode) throws DBException, RemoteException
{
this.checkCurrentCacheIsPhysical(null);
m_tableRemote.remove(data, iOpenMode);
if (m_objCurrentCacheRecord != null)
{
if (m_mapCache != null)
m_mapCache.set(((Integer)m_objCurrentCacheRecord).intValue(), NONE);
else if (m_htCache != null)
m_htCache.remove(m_objCurrentCacheRecord);
}
m_objCurrentPhysicalRecord = NONE;
m_objCurrentLockedRecord = NONE;
m_objCurrentCacheRecord = NONE;
} | java | public void remove(Object data, int iOpenMode) throws DBException, RemoteException
{
this.checkCurrentCacheIsPhysical(null);
m_tableRemote.remove(data, iOpenMode);
if (m_objCurrentCacheRecord != null)
{
if (m_mapCache != null)
m_mapCache.set(((Integer)m_objCurrentCacheRecord).intValue(), NONE);
else if (m_htCache != null)
m_htCache.remove(m_objCurrentCacheRecord);
}
m_objCurrentPhysicalRecord = NONE;
m_objCurrentLockedRecord = NONE;
m_objCurrentCacheRecord = NONE;
} | [
"public",
"void",
"remove",
"(",
"Object",
"data",
",",
"int",
"iOpenMode",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"this",
".",
"checkCurrentCacheIsPhysical",
"(",
"null",
")",
";",
"m_tableRemote",
".",
"remove",
"(",
"data",
",",
"iOpenMo... | Delete the current record.
@param - This is a dummy param, because this call conflicts with a call in EJBHome.
@exception Exception File exception. | [
"Delete",
"the",
"current",
"record",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/CachedRemoteTable.java#L265-L279 |
aol/cyclops | cyclops/src/main/java/cyclops/control/Future.java | Future.fold | public <R> R fold(Function<? super T,? extends R> success, Function<? super Throwable,? extends R> failure){
try {
return success.apply(future.join());
}catch(Throwable t){
return failure.apply(t);
}
} | java | public <R> R fold(Function<? super T,? extends R> success, Function<? super Throwable,? extends R> failure){
try {
return success.apply(future.join());
}catch(Throwable t){
return failure.apply(t);
}
} | [
"public",
"<",
"R",
">",
"R",
"fold",
"(",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"R",
">",
"success",
",",
"Function",
"<",
"?",
"super",
"Throwable",
",",
"?",
"extends",
"R",
">",
"failure",
")",
"{",
"try",
"{",
"return",
"s... | Blocking analogue to visitAsync. Visit the state of this Future, block until ready.
<pre>
{@code
Future.ofResult(10)
.visit(i->i*2, e->-1);
20
Future.<Integer>ofError(new RuntimeException())
.visit(i->i*2, e->-1)
[-1]
}
</pre>
@param success Function to execute if the previous stage completes successfully
@param failure Function to execute if this Future fails
@return Result of the executed Function | [
"Blocking",
"analogue",
"to",
"visitAsync",
".",
"Visit",
"the",
"state",
"of",
"this",
"Future",
"block",
"until",
"ready",
"."
] | train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/control/Future.java#L788-L795 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/CertificatesImpl.java | CertificatesImpl.listNext | public PagedList<Certificate> listNext(final String nextPageLink) {
ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<Certificate>(response.body()) {
@Override
public Page<Certificate> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink, null).toBlocking().single().body();
}
};
} | java | public PagedList<Certificate> listNext(final String nextPageLink) {
ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<Certificate>(response.body()) {
@Override
public Page<Certificate> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink, null).toBlocking().single().body();
}
};
} | [
"public",
"PagedList",
"<",
"Certificate",
">",
"listNext",
"(",
"final",
"String",
"nextPageLink",
")",
"{",
"ServiceResponseWithHeaders",
"<",
"Page",
"<",
"Certificate",
">",
",",
"CertificateListHeaders",
">",
"response",
"=",
"listNextSinglePageAsync",
"(",
"ne... | Lists all of the certificates that have been added to the specified account.
@param nextPageLink The NextLink from the previous successful call to List operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PagedList<Certificate> object if successful. | [
"Lists",
"all",
"of",
"the",
"certificates",
"that",
"have",
"been",
"added",
"to",
"the",
"specified",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/CertificatesImpl.java#L1201-L1209 |
minio/minio-java | api/src/main/java/io/minio/ServerSideEncryption.java | ServerSideEncryption.copyWithCustomerKey | public static ServerSideEncryption copyWithCustomerKey(SecretKey key)
throws InvalidKeyException, NoSuchAlgorithmException {
if (!isCustomerKeyValid(key)) {
throw new InvalidKeyException("The secret key is not a 256 bit AES key");
}
return new ServerSideEncryptionCopyWithCustomerKey(key, MessageDigest.getInstance(("MD5")));
} | java | public static ServerSideEncryption copyWithCustomerKey(SecretKey key)
throws InvalidKeyException, NoSuchAlgorithmException {
if (!isCustomerKeyValid(key)) {
throw new InvalidKeyException("The secret key is not a 256 bit AES key");
}
return new ServerSideEncryptionCopyWithCustomerKey(key, MessageDigest.getInstance(("MD5")));
} | [
"public",
"static",
"ServerSideEncryption",
"copyWithCustomerKey",
"(",
"SecretKey",
"key",
")",
"throws",
"InvalidKeyException",
",",
"NoSuchAlgorithmException",
"{",
"if",
"(",
"!",
"isCustomerKeyValid",
"(",
"key",
")",
")",
"{",
"throw",
"new",
"InvalidKeyExceptio... | Create a new server-side-encryption object for encryption with customer
provided keys (a.k.a. SSE-C).
@param key The secret AES-256 key.
@return An instance of ServerSideEncryption implementing SSE-C.
@throws InvalidKeyException if the provided secret key is not a 256 bit AES key.
@throws NoSuchAlgorithmException if the crypto provider does not implement MD5. | [
"Create",
"a",
"new",
"server",
"-",
"side",
"-",
"encryption",
"object",
"for",
"encryption",
"with",
"customer",
"provided",
"keys",
"(",
"a",
".",
"k",
".",
"a",
".",
"SSE",
"-",
"C",
")",
"."
] | train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/ServerSideEncryption.java#L117-L123 |
apache/incubator-druid | extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java | ApproximateHistogram.fromBytesDense | public static ApproximateHistogram fromBytesDense(ByteBuffer buf)
{
int size = buf.getInt();
int binCount = buf.getInt();
float[] positions = new float[size];
long[] bins = new long[size];
buf.asFloatBuffer().get(positions);
buf.position(buf.position() + Float.BYTES * positions.length);
buf.asLongBuffer().get(bins);
buf.position(buf.position() + Long.BYTES * bins.length);
float min = buf.getFloat();
float max = buf.getFloat();
return new ApproximateHistogram(binCount, positions, bins, min, max);
} | java | public static ApproximateHistogram fromBytesDense(ByteBuffer buf)
{
int size = buf.getInt();
int binCount = buf.getInt();
float[] positions = new float[size];
long[] bins = new long[size];
buf.asFloatBuffer().get(positions);
buf.position(buf.position() + Float.BYTES * positions.length);
buf.asLongBuffer().get(bins);
buf.position(buf.position() + Long.BYTES * bins.length);
float min = buf.getFloat();
float max = buf.getFloat();
return new ApproximateHistogram(binCount, positions, bins, min, max);
} | [
"public",
"static",
"ApproximateHistogram",
"fromBytesDense",
"(",
"ByteBuffer",
"buf",
")",
"{",
"int",
"size",
"=",
"buf",
".",
"getInt",
"(",
")",
";",
"int",
"binCount",
"=",
"buf",
".",
"getInt",
"(",
")",
";",
"float",
"[",
"]",
"positions",
"=",
... | Constructs an ApproximateHistogram object from the given dense byte-buffer representation
@param buf ByteBuffer to construct an ApproximateHistogram from
@return ApproximateHistogram constructed from the given ByteBuffer | [
"Constructs",
"an",
"ApproximateHistogram",
"object",
"from",
"the",
"given",
"dense",
"byte",
"-",
"buffer",
"representation"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java#L1310-L1327 |
JOML-CI/JOML | src/org/joml/Matrix4x3d.java | Matrix4x3d.setOrthoSymmetric | public Matrix4x3d setOrthoSymmetric(double width, double height, double zNear, double zFar, boolean zZeroToOne) {
m00 = 2.0 / width;
m01 = 0.0;
m02 = 0.0;
m10 = 0.0;
m11 = 2.0 / height;
m12 = 0.0;
m20 = 0.0;
m21 = 0.0;
m22 = (zZeroToOne ? 1.0 : 2.0) / (zNear - zFar);
m30 = 0.0;
m31 = 0.0;
m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar);
properties = 0;
return this;
} | java | public Matrix4x3d setOrthoSymmetric(double width, double height, double zNear, double zFar, boolean zZeroToOne) {
m00 = 2.0 / width;
m01 = 0.0;
m02 = 0.0;
m10 = 0.0;
m11 = 2.0 / height;
m12 = 0.0;
m20 = 0.0;
m21 = 0.0;
m22 = (zZeroToOne ? 1.0 : 2.0) / (zNear - zFar);
m30 = 0.0;
m31 = 0.0;
m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar);
properties = 0;
return this;
} | [
"public",
"Matrix4x3d",
"setOrthoSymmetric",
"(",
"double",
"width",
",",
"double",
"height",
",",
"double",
"zNear",
",",
"double",
"zFar",
",",
"boolean",
"zZeroToOne",
")",
"{",
"m00",
"=",
"2.0",
"/",
"width",
";",
"m01",
"=",
"0.0",
";",
"m02",
"=",... | Set this matrix to be a symmetric orthographic projection transformation for a right-handed coordinate system
using the given NDC z range.
<p>
This method is equivalent to calling {@link #setOrtho(double, double, double, double, double, double, boolean) setOrtho()} with
<code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>.
<p>
In order to apply the symmetric orthographic projection to an already existing transformation,
use {@link #orthoSymmetric(double, double, double, double, boolean) orthoSymmetric()}.
<p>
Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a>
@see #orthoSymmetric(double, double, double, double, boolean)
@param width
the distance between the right and left frustum edges
@param height
the distance between the top and bottom frustum edges
@param zNear
near clipping plane distance
@param zFar
far clipping plane distance
@param zZeroToOne
whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code>
or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code>
@return this | [
"Set",
"this",
"matrix",
"to",
"be",
"a",
"symmetric",
"orthographic",
"projection",
"transformation",
"for",
"a",
"right",
"-",
"handed",
"coordinate",
"system",
"using",
"the",
"given",
"NDC",
"z",
"range",
".",
"<p",
">",
"This",
"method",
"is",
"equivale... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L7391-L7406 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/cors/CorsService.java | CorsService.handleCorsPreflight | private HttpResponse handleCorsPreflight(ServiceRequestContext ctx, HttpRequest req) {
final HttpHeaders headers = HttpHeaders.of(HttpStatus.OK);
final CorsPolicy policy = setCorsOrigin(ctx, req, headers);
if (policy != null) {
policy.setCorsAllowMethods(headers);
policy.setCorsAllowHeaders(headers);
policy.setCorsAllowCredentials(headers);
policy.setCorsMaxAge(headers);
policy.setCorsPreflightResponseHeaders(headers);
}
return HttpResponse.of(headers);
} | java | private HttpResponse handleCorsPreflight(ServiceRequestContext ctx, HttpRequest req) {
final HttpHeaders headers = HttpHeaders.of(HttpStatus.OK);
final CorsPolicy policy = setCorsOrigin(ctx, req, headers);
if (policy != null) {
policy.setCorsAllowMethods(headers);
policy.setCorsAllowHeaders(headers);
policy.setCorsAllowCredentials(headers);
policy.setCorsMaxAge(headers);
policy.setCorsPreflightResponseHeaders(headers);
}
return HttpResponse.of(headers);
} | [
"private",
"HttpResponse",
"handleCorsPreflight",
"(",
"ServiceRequestContext",
"ctx",
",",
"HttpRequest",
"req",
")",
"{",
"final",
"HttpHeaders",
"headers",
"=",
"HttpHeaders",
".",
"of",
"(",
"HttpStatus",
".",
"OK",
")",
";",
"final",
"CorsPolicy",
"policy",
... | Handles CORS preflight by setting the appropriate headers.
@param req the decoded HTTP request | [
"Handles",
"CORS",
"preflight",
"by",
"setting",
"the",
"appropriate",
"headers",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/cors/CorsService.java#L109-L121 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getConcatenatedOnDemand | @Nonnull
public static String getConcatenatedOnDemand (@Nullable final String sFront, @Nullable final String sEnd)
{
if (sFront == null)
return sEnd == null ? "" : sEnd;
if (sEnd == null)
return sFront;
return sFront + sEnd;
} | java | @Nonnull
public static String getConcatenatedOnDemand (@Nullable final String sFront, @Nullable final String sEnd)
{
if (sFront == null)
return sEnd == null ? "" : sEnd;
if (sEnd == null)
return sFront;
return sFront + sEnd;
} | [
"@",
"Nonnull",
"public",
"static",
"String",
"getConcatenatedOnDemand",
"(",
"@",
"Nullable",
"final",
"String",
"sFront",
",",
"@",
"Nullable",
"final",
"String",
"sEnd",
")",
"{",
"if",
"(",
"sFront",
"==",
"null",
")",
"return",
"sEnd",
"==",
"null",
"... | Concatenate the strings sFront and sEnd. If either front or back is
<code>null</code> or empty only the other element is returned. If both
strings are <code>null</code> or empty and empty String is returned.
@param sFront
Front string. May be <code>null</code>.
@param sEnd
May be <code>null</code>.
@return The concatenated string. Never <code>null</code>. | [
"Concatenate",
"the",
"strings",
"sFront",
"and",
"sEnd",
".",
"If",
"either",
"front",
"or",
"back",
"is",
"<code",
">",
"null<",
"/",
"code",
">",
"or",
"empty",
"only",
"the",
"other",
"element",
"is",
"returned",
".",
"If",
"both",
"strings",
"are",
... | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2418-L2426 |
wildfly/wildfly-core | deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/ZipCompletionScanner.java | ZipCompletionScanner.isCompleteZip | public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {
FileChannel channel = null;
try {
channel = new FileInputStream(file).getChannel();
long size = channel.size();
if (size < ENDLEN) { // Obvious case
return false;
}
else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment
return true;
}
// Either file is incomplete or the end of central directory record includes an arbitrary length comment
// So, we have to scan backwards looking for an end of central directory record
return scanForEndSig(file, channel);
}
finally {
safeClose(channel);
}
} | java | public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {
FileChannel channel = null;
try {
channel = new FileInputStream(file).getChannel();
long size = channel.size();
if (size < ENDLEN) { // Obvious case
return false;
}
else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment
return true;
}
// Either file is incomplete or the end of central directory record includes an arbitrary length comment
// So, we have to scan backwards looking for an end of central directory record
return scanForEndSig(file, channel);
}
finally {
safeClose(channel);
}
} | [
"public",
"static",
"boolean",
"isCompleteZip",
"(",
"File",
"file",
")",
"throws",
"IOException",
",",
"NonScannableZipException",
"{",
"FileChannel",
"channel",
"=",
"null",
";",
"try",
"{",
"channel",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
".",
"g... | Scans the given file looking for a complete zip file format end of central directory record.
@param file the file
@return true if a complete end of central directory record could be found
@throws IOException | [
"Scans",
"the",
"given",
"file",
"looking",
"for",
"a",
"complete",
"zip",
"file",
"format",
"end",
"of",
"central",
"directory",
"record",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/ZipCompletionScanner.java#L107-L128 |
ops4j/org.ops4j.pax.logging | pax-logging-service/src/main/java/org/apache/log4j/receivers/varia/LogFilePatternReceiver.java | LogFilePatternReceiver.buildMessage | private String buildMessage(String firstMessageLine, int exceptionLine) {
if (additionalLines.size() == 0) {
return firstMessageLine;
}
StringBuffer message = new StringBuffer();
if (firstMessageLine != null) {
message.append(firstMessageLine);
}
int linesToProcess = (exceptionLine == -1?additionalLines.size(): exceptionLine);
for (int i = 0; i < linesToProcess; i++) {
message.append(newLine);
message.append(additionalLines.get(i));
}
return message.toString();
} | java | private String buildMessage(String firstMessageLine, int exceptionLine) {
if (additionalLines.size() == 0) {
return firstMessageLine;
}
StringBuffer message = new StringBuffer();
if (firstMessageLine != null) {
message.append(firstMessageLine);
}
int linesToProcess = (exceptionLine == -1?additionalLines.size(): exceptionLine);
for (int i = 0; i < linesToProcess; i++) {
message.append(newLine);
message.append(additionalLines.get(i));
}
return message.toString();
} | [
"private",
"String",
"buildMessage",
"(",
"String",
"firstMessageLine",
",",
"int",
"exceptionLine",
")",
"{",
"if",
"(",
"additionalLines",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"return",
"firstMessageLine",
";",
"}",
"StringBuffer",
"message",
"=",
"... | Combine all message lines occuring in the additionalLines list, adding
a newline character between each line
<p>
the event will already have a message - combine this message
with the message lines in the additionalLines list
(all entries prior to the exceptionLine index)
@param firstMessageLine primary message line
@param exceptionLine index of first exception line
@return message | [
"Combine",
"all",
"message",
"lines",
"occuring",
"in",
"the",
"additionalLines",
"list",
"adding",
"a",
"newline",
"character",
"between",
"each",
"line",
"<p",
">",
"the",
"event",
"will",
"already",
"have",
"a",
"message",
"-",
"combine",
"this",
"message",... | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/receivers/varia/LogFilePatternReceiver.java#L400-L416 |
spotify/docgenerator | scanner/src/main/java/com/spotify/docgenerator/JacksonJerseyAnnotationProcessor.java | JacksonJerseyAnnotationProcessor.computeMethod | private ResourceMethod computeMethod(ExecutableElement ee, List<ResourceArgument> arguments) {
final String javaDoc = processingEnv.getElementUtils().getDocComment(ee);
final Path pathAnnotation = ee.getAnnotation(Path.class);
final Produces producesAnnotation = ee.getAnnotation(Produces.class);
return new ResourceMethod(
ee.getSimpleName().toString(),
computeRequestMethod(ee),
(pathAnnotation == null) ? null : pathAnnotation.value(),
(producesAnnotation == null) ? null : Joiner.on(",").join(producesAnnotation.value()),
makeTypeDescriptor(ee.getReturnType()),
arguments,
javaDoc);
} | java | private ResourceMethod computeMethod(ExecutableElement ee, List<ResourceArgument> arguments) {
final String javaDoc = processingEnv.getElementUtils().getDocComment(ee);
final Path pathAnnotation = ee.getAnnotation(Path.class);
final Produces producesAnnotation = ee.getAnnotation(Produces.class);
return new ResourceMethod(
ee.getSimpleName().toString(),
computeRequestMethod(ee),
(pathAnnotation == null) ? null : pathAnnotation.value(),
(producesAnnotation == null) ? null : Joiner.on(",").join(producesAnnotation.value()),
makeTypeDescriptor(ee.getReturnType()),
arguments,
javaDoc);
} | [
"private",
"ResourceMethod",
"computeMethod",
"(",
"ExecutableElement",
"ee",
",",
"List",
"<",
"ResourceArgument",
">",
"arguments",
")",
"{",
"final",
"String",
"javaDoc",
"=",
"processingEnv",
".",
"getElementUtils",
"(",
")",
".",
"getDocComment",
"(",
"ee",
... | Given an {@link ExecutableElement} representing the method, and the already computed list
of arguments to the method, produce a {@link ResourceMethod}. | [
"Given",
"an",
"{"
] | train | https://github.com/spotify/docgenerator/blob/a7965f6d4a1546864a3f8584b86841cef9ac2f65/scanner/src/main/java/com/spotify/docgenerator/JacksonJerseyAnnotationProcessor.java#L169-L181 |
QSFT/Doradus | doradus-common/src/main/java/com/dell/doradus/common/Utils.java | Utils.formatDate | public static String formatDate(Calendar date, int precision) {
assert date != null;
// Remember that the bloody month field is zero-relative!
switch (precision) {
case Calendar.MILLISECOND:
// YYYY-MM-DD hh:mm:ss.SSS
return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND),
date.get(Calendar.MILLISECOND));
case Calendar.SECOND:
// YYYY-MM-DD hh:mm:ss
return String.format("%04d-%02d-%02d %02d:%02d:%02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND));
case Calendar.MINUTE:
// YYYY-MM-DD hh:mm
return String.format("%04d-%02d-%02d %02d:%02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE));
case Calendar.HOUR:
// YYYY-MM-DD hh
return String.format("%04d-%02d-%02d %02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY));
case Calendar.DATE:
// YYYY-MM-DD
return String.format("%04d-%02d-%02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH));
case Calendar.MONTH:
// YYYY-MM
return String.format("%04d-%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1);
case Calendar.YEAR:
// YYYY
return String.format("%04d", date.get(Calendar.YEAR));
}
throw new IllegalArgumentException("Unknown precision: " + precision);
} | java | public static String formatDate(Calendar date, int precision) {
assert date != null;
// Remember that the bloody month field is zero-relative!
switch (precision) {
case Calendar.MILLISECOND:
// YYYY-MM-DD hh:mm:ss.SSS
return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND),
date.get(Calendar.MILLISECOND));
case Calendar.SECOND:
// YYYY-MM-DD hh:mm:ss
return String.format("%04d-%02d-%02d %02d:%02d:%02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE), date.get(Calendar.SECOND));
case Calendar.MINUTE:
// YYYY-MM-DD hh:mm
return String.format("%04d-%02d-%02d %02d:%02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY), date.get(Calendar.MINUTE));
case Calendar.HOUR:
// YYYY-MM-DD hh
return String.format("%04d-%02d-%02d %02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH),
date.get(Calendar.HOUR_OF_DAY));
case Calendar.DATE:
// YYYY-MM-DD
return String.format("%04d-%02d-%02d",
date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1, date.get(Calendar.DAY_OF_MONTH));
case Calendar.MONTH:
// YYYY-MM
return String.format("%04d-%02d", date.get(Calendar.YEAR), date.get(Calendar.MONTH)+1);
case Calendar.YEAR:
// YYYY
return String.format("%04d", date.get(Calendar.YEAR));
}
throw new IllegalArgumentException("Unknown precision: " + precision);
} | [
"public",
"static",
"String",
"formatDate",
"(",
"Calendar",
"date",
",",
"int",
"precision",
")",
"{",
"assert",
"date",
"!=",
"null",
";",
"// Remember that the bloody month field is zero-relative!\r",
"switch",
"(",
"precision",
")",
"{",
"case",
"Calendar",
".",... | Format a Calendar date with a given precision. 'precision' must be a Calendar
"field" value such as Calendar.MINUTE. The allowed precisions and the corresponding
string formats returned are:
<pre>
Calendar.MILLISECOND: YYYY-MM-DD hh:mm:ss.SSS
Calendar.SECOND: YYYY-MM-DD hh:mm:ss
Calendar.MINUTE: YYYY-MM-DD hh:mm
Calendar.HOUR: YYYY-MM-DD hh
Calendar.DATE: YYYY-MM-DD
Calendar.MONTH: YYYY-MM
Calendar.YEAR: YYYY
</pre>
Note that Calendar.DAY_OF_MONTH is a synonym for Calendar.DATE.
@param date Date as a Calendar to be formatted.
@param precision Calendar field value of desired precision.
@return String formatted to the requested precision. | [
"Format",
"a",
"Calendar",
"date",
"with",
"a",
"given",
"precision",
".",
"precision",
"must",
"be",
"a",
"Calendar",
"field",
"value",
"such",
"as",
"Calendar",
".",
"MINUTE",
".",
"The",
"allowed",
"precisions",
"and",
"the",
"corresponding",
"string",
"f... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L705-L743 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java | ContactsApi.getPublicList | public Contacts getPublicList(String userId, int page, int perPage) throws JinxException {
JinxUtils.validateParams(userId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.contacts.getPublicList");
params.put("user_id", userId);
if (page > 0) {
params.put("page", Integer.toString(page));
}
if (perPage > 0) {
params.put("per_page", Integer.toString(perPage));
}
return jinx.flickrGet(params, Contacts.class);
} | java | public Contacts getPublicList(String userId, int page, int perPage) throws JinxException {
JinxUtils.validateParams(userId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.contacts.getPublicList");
params.put("user_id", userId);
if (page > 0) {
params.put("page", Integer.toString(page));
}
if (perPage > 0) {
params.put("per_page", Integer.toString(perPage));
}
return jinx.flickrGet(params, Contacts.class);
} | [
"public",
"Contacts",
"getPublicList",
"(",
"String",
"userId",
",",
"int",
"page",
",",
"int",
"perPage",
")",
"throws",
"JinxException",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"userId",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"params",
... | Get the contact list for a user.
<br>
This method does not require authentication.
@param userId Required. The NSID of the user to fetch the contact list for.
@param page Optional. The page of results to return. If this argument is ≤= zero, it defaults to 1.
@param perPage Optional. Number of photos to return per page. If this argument is ≤= zero, it defaults to 1000.
The maximum allowed value is 1000.
@return object containing contacts matching the parameters.
@throws JinxException if required parameters are null or empty, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.contacts.getPublicList.html">flickr.contacts.getPublicList</a> | [
"Get",
"the",
"contact",
"list",
"for",
"a",
"user",
".",
"<br",
">",
"This",
"method",
"does",
"not",
"require",
"authentication",
"."
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java#L117-L129 |
threerings/nenya | core/src/main/java/com/threerings/miso/client/MisoScenePanel.java | MisoScenePanel.updateTileCoords | protected boolean updateTileCoords (int sx, int sy, Point tpos)
{
Point npos = MisoUtil.screenToTile(_metrics, sx, sy, new Point());
if (!tpos.equals(npos)) {
tpos.setLocation(npos.x, npos.y);
return true;
} else {
return false;
}
} | java | protected boolean updateTileCoords (int sx, int sy, Point tpos)
{
Point npos = MisoUtil.screenToTile(_metrics, sx, sy, new Point());
if (!tpos.equals(npos)) {
tpos.setLocation(npos.x, npos.y);
return true;
} else {
return false;
}
} | [
"protected",
"boolean",
"updateTileCoords",
"(",
"int",
"sx",
",",
"int",
"sy",
",",
"Point",
"tpos",
")",
"{",
"Point",
"npos",
"=",
"MisoUtil",
".",
"screenToTile",
"(",
"_metrics",
",",
"sx",
",",
"sy",
",",
"new",
"Point",
"(",
")",
")",
";",
"if... | Converts the supplied screen coordinates into tile coordinates, writing the values into the
supplied {@link Point} instance and returning true if the screen coordinates translated
into a different set of tile coordinates than were already contained in the point (so that
the caller can know to update a highlight, for example).
@return true if the tile coordinates have changed. | [
"Converts",
"the",
"supplied",
"screen",
"coordinates",
"into",
"tile",
"coordinates",
"writing",
"the",
"values",
"into",
"the",
"supplied",
"{",
"@link",
"Point",
"}",
"instance",
"and",
"returning",
"true",
"if",
"the",
"screen",
"coordinates",
"translated",
... | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L1196-L1205 |
jbundle/jbundle | thin/base/screen/cal/other/src/main/java/org/jbundle/thin/base/screen/cal/popup/JBasePopupPanel.java | JBasePopupPanel.createComponentButton | public JComponent createComponentButton(String strProductType, BaseApplet applet)
{
ProductTypeInfo productType = ProductTypeInfo.getProductType(strProductType);
if (productType == null)
{
ImageIcon icon = null;
if (applet != null)
icon = applet.loadImageIcon(strProductType, null);
productType = new ProductTypeInfo(strProductType, icon, icon, 0x00c0c0c0, Colors.NULL);
}
JUnderlinedButton button = new JUnderlinedButton(productType.getDescription(), productType.getStartIcon());
String strLink = strProductType;
button.setName(strLink);
button.setOpaque(false);
Color colorBackground = new Color(productType.getSelectColor());
button.setBackground(colorBackground); // Since the button is opaque, this is only needed for those look and feels that want their own background color.
button.setBorderPainted(false);
button.addActionListener(m_actionListener);
button.addActionListener(this);
return button;
} | java | public JComponent createComponentButton(String strProductType, BaseApplet applet)
{
ProductTypeInfo productType = ProductTypeInfo.getProductType(strProductType);
if (productType == null)
{
ImageIcon icon = null;
if (applet != null)
icon = applet.loadImageIcon(strProductType, null);
productType = new ProductTypeInfo(strProductType, icon, icon, 0x00c0c0c0, Colors.NULL);
}
JUnderlinedButton button = new JUnderlinedButton(productType.getDescription(), productType.getStartIcon());
String strLink = strProductType;
button.setName(strLink);
button.setOpaque(false);
Color colorBackground = new Color(productType.getSelectColor());
button.setBackground(colorBackground); // Since the button is opaque, this is only needed for those look and feels that want their own background color.
button.setBorderPainted(false);
button.addActionListener(m_actionListener);
button.addActionListener(this);
return button;
} | [
"public",
"JComponent",
"createComponentButton",
"(",
"String",
"strProductType",
",",
"BaseApplet",
"applet",
")",
"{",
"ProductTypeInfo",
"productType",
"=",
"ProductTypeInfo",
".",
"getProductType",
"(",
"strProductType",
")",
";",
"if",
"(",
"productType",
"==",
... | Create the button/panel for this menu item.
@param record The menu record.
@return The component to add to this panel. | [
"Create",
"the",
"button",
"/",
"panel",
"for",
"this",
"menu",
"item",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/cal/other/src/main/java/org/jbundle/thin/base/screen/cal/popup/JBasePopupPanel.java#L79-L101 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbMovies.java | TmdbMovies.postMovieRating | public StatusCode postMovieRating(int movieId, int rating, String sessionId, String guestSessionId) throws MovieDbException {
if (rating < 0 || rating > RATING_MAX) {
throw new MovieDbException(ApiExceptionType.UNKNOWN_CAUSE, "Rating out of range");
}
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, movieId);
parameters.add(Param.SESSION_ID, sessionId);
parameters.add(Param.GUEST_SESSION_ID, guestSessionId);
URL url = new ApiUrl(apiKey, MethodBase.MOVIE).subMethod(MethodSub.RATING).buildUrl(parameters);
String jsonBody = new PostTools()
.add(PostBody.VALUE, rating)
.build();
String webpage = httpTools.postRequest(url, jsonBody);
try {
return MAPPER.readValue(webpage, StatusCode.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to post rating", url, ex);
}
} | java | public StatusCode postMovieRating(int movieId, int rating, String sessionId, String guestSessionId) throws MovieDbException {
if (rating < 0 || rating > RATING_MAX) {
throw new MovieDbException(ApiExceptionType.UNKNOWN_CAUSE, "Rating out of range");
}
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, movieId);
parameters.add(Param.SESSION_ID, sessionId);
parameters.add(Param.GUEST_SESSION_ID, guestSessionId);
URL url = new ApiUrl(apiKey, MethodBase.MOVIE).subMethod(MethodSub.RATING).buildUrl(parameters);
String jsonBody = new PostTools()
.add(PostBody.VALUE, rating)
.build();
String webpage = httpTools.postRequest(url, jsonBody);
try {
return MAPPER.readValue(webpage, StatusCode.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to post rating", url, ex);
}
} | [
"public",
"StatusCode",
"postMovieRating",
"(",
"int",
"movieId",
",",
"int",
"rating",
",",
"String",
"sessionId",
",",
"String",
"guestSessionId",
")",
"throws",
"MovieDbException",
"{",
"if",
"(",
"rating",
"<",
"0",
"||",
"rating",
">",
"RATING_MAX",
")",
... | This method lets users rate a movie.
A valid session id or guest session id is required.
@param sessionId
@param movieId
@param rating
@param guestSessionId
@return
@throws MovieDbException | [
"This",
"method",
"lets",
"users",
"rate",
"a",
"movie",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbMovies.java#L476-L498 |
apache/incubator-gobblin | gobblin-modules/gobblin-metrics-influxdb/src/main/java/org/apache/gobblin/metrics/influxdb/InfluxDBEventReporter.java | InfluxDBEventReporter.convertValue | private Object convertValue(String field, String value) {
if (value == null) return EMTPY_VALUE;
if (METADATA_DURATION.equals(field)) {
return convertDuration(TimeUnit.MILLISECONDS.toNanos(Long.parseLong(value)));
}
else {
Double doubleValue = Doubles.tryParse(value);
return (doubleValue == null) ? value : doubleValue;
}
} | java | private Object convertValue(String field, String value) {
if (value == null) return EMTPY_VALUE;
if (METADATA_DURATION.equals(field)) {
return convertDuration(TimeUnit.MILLISECONDS.toNanos(Long.parseLong(value)));
}
else {
Double doubleValue = Doubles.tryParse(value);
return (doubleValue == null) ? value : doubleValue;
}
} | [
"private",
"Object",
"convertValue",
"(",
"String",
"field",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"EMTPY_VALUE",
";",
"if",
"(",
"METADATA_DURATION",
".",
"equals",
"(",
"field",
")",
")",
"{",
"return",
"con... | Convert the event value taken from the metadata to double (default type).
It falls back to string type if the value is missing or it is non-numeric
is of string or missing
Metadata entries are emitted as distinct events (see {@link MultiPartEvent})
@param field {@link GobblinTrackingEvent} metadata key
@param value {@link GobblinTrackingEvent} metadata value
@return The converted event value | [
"Convert",
"the",
"event",
"value",
"taken",
"from",
"the",
"metadata",
"to",
"double",
"(",
"default",
"type",
")",
".",
"It",
"falls",
"back",
"to",
"string",
"type",
"if",
"the",
"value",
"is",
"missing",
"or",
"it",
"is",
"non",
"-",
"numeric",
"is... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-metrics-influxdb/src/main/java/org/apache/gobblin/metrics/influxdb/InfluxDBEventReporter.java#L116-L125 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/Preconditions.java | Preconditions.checkState | public static void checkState(boolean condition, @Nullable Object errorMessage) {
if (!condition) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
} | java | public static void checkState(boolean condition, @Nullable Object errorMessage) {
if (!condition) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
} | [
"public",
"static",
"void",
"checkState",
"(",
"boolean",
"condition",
",",
"@",
"Nullable",
"Object",
"errorMessage",
")",
"{",
"if",
"(",
"!",
"condition",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"valueOf",
"(",
"errorMessage",... | Checks the given boolean condition, and throws an {@code IllegalStateException} if
the condition is not met (evaluates to {@code false}). The exception will have the
given error message.
@param condition The condition to check
@param errorMessage The message for the {@code IllegalStateException} that is thrown if the check fails.
@throws IllegalStateException Thrown, if the condition is violated. | [
"Checks",
"the",
"given",
"boolean",
"condition",
"and",
"throws",
"an",
"{",
"@code",
"IllegalStateException",
"}",
"if",
"the",
"condition",
"is",
"not",
"met",
"(",
"evaluates",
"to",
"{",
"@code",
"false",
"}",
")",
".",
"The",
"exception",
"will",
"ha... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/Preconditions.java#L193-L197 |
OpenLiberty/open-liberty | dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/bci/ClassAvailableTransformer.java | ClassAvailableTransformer.transformCandidate | byte[] transformCandidate(byte[] classfileBuffer) {
// reader --> serial version uid adder --> process candidate hook adapter --> tracing --> writer
ClassReader reader = new ClassReader(classfileBuffer);
ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
ClassVisitor visitor = writer;
StringWriter stringWriter = null;
if (tc.isDumpEnabled()) {
stringWriter = new StringWriter();
visitor = new CheckClassAdapter(visitor);
visitor = new TraceClassVisitor(visitor, new PrintWriter(stringWriter));
}
visitor = new ClassAvailableHookClassAdapter(visitor);
visitor = new SerialVersionUIDAdder(visitor);
// Process the class
reader.accept(visitor, 0);
if (stringWriter != null && tc.isDumpEnabled()) {
Tr.dump(tc, "Transformed class", stringWriter);
}
return writer.toByteArray();
} | java | byte[] transformCandidate(byte[] classfileBuffer) {
// reader --> serial version uid adder --> process candidate hook adapter --> tracing --> writer
ClassReader reader = new ClassReader(classfileBuffer);
ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
ClassVisitor visitor = writer;
StringWriter stringWriter = null;
if (tc.isDumpEnabled()) {
stringWriter = new StringWriter();
visitor = new CheckClassAdapter(visitor);
visitor = new TraceClassVisitor(visitor, new PrintWriter(stringWriter));
}
visitor = new ClassAvailableHookClassAdapter(visitor);
visitor = new SerialVersionUIDAdder(visitor);
// Process the class
reader.accept(visitor, 0);
if (stringWriter != null && tc.isDumpEnabled()) {
Tr.dump(tc, "Transformed class", stringWriter);
}
return writer.toByteArray();
} | [
"byte",
"[",
"]",
"transformCandidate",
"(",
"byte",
"[",
"]",
"classfileBuffer",
")",
"{",
"// reader --> serial version uid adder --> process candidate hook adapter --> tracing --> writer",
"ClassReader",
"reader",
"=",
"new",
"ClassReader",
"(",
"classfileBuffer",
")",
";"... | Inject the byte code required to call the {@code processCandidate} proxy
after class initialization.
@param classfileBuffer the source class file
@return the modified class file | [
"Inject",
"the",
"byte",
"code",
"required",
"to",
"call",
"the",
"{",
"@code",
"processCandidate",
"}",
"proxy",
"after",
"class",
"initialization",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/bci/ClassAvailableTransformer.java#L106-L129 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/ClosableCharArrayWriter.java | ClosableCharArrayWriter.toCharArrayReader | public synchronized CharArrayReader toCharArrayReader()
throws IOException {
checkFreed();
CharArrayReader reader = new CharArrayReader(buf, 0, count);
//System.out.println("toCharArrayReader::buf.length: " + buf.length);
free();
return reader;
} | java | public synchronized CharArrayReader toCharArrayReader()
throws IOException {
checkFreed();
CharArrayReader reader = new CharArrayReader(buf, 0, count);
//System.out.println("toCharArrayReader::buf.length: " + buf.length);
free();
return reader;
} | [
"public",
"synchronized",
"CharArrayReader",
"toCharArrayReader",
"(",
")",
"throws",
"IOException",
"{",
"checkFreed",
"(",
")",
";",
"CharArrayReader",
"reader",
"=",
"new",
"CharArrayReader",
"(",
"buf",
",",
"0",
",",
"count",
")",
";",
"//System.out.println(\... | Performs an effecient (zero-copy) conversion of the character data
accumulated in this writer to a reader. <p>
To ensure the integrity of the resulting reader, {@link #free()
free} is invoked upon this writer as a side-effect.
@return a reader representing this writer's accumulated
character data
@throws java.io.IOException if an I/O error occurs.
In particular, an <tt>IOException</tt> may be thrown
if this writer has been {@link #free() freed}. | [
"Performs",
"an",
"effecient",
"(",
"zero",
"-",
"copy",
")",
"conversion",
"of",
"the",
"character",
"data",
"accumulated",
"in",
"this",
"writer",
"to",
"a",
"reader",
".",
"<p",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/ClosableCharArrayWriter.java#L354-L365 |
aws/aws-sdk-java | jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathContainsFunction.java | JmesPathContainsFunction.doesStringContain | private static BooleanNode doesStringContain(JsonNode subject, JsonNode search) {
if (subject.asText().contains(search.asText())) {
return BooleanNode.TRUE;
}
return BooleanNode.FALSE;
} | java | private static BooleanNode doesStringContain(JsonNode subject, JsonNode search) {
if (subject.asText().contains(search.asText())) {
return BooleanNode.TRUE;
}
return BooleanNode.FALSE;
} | [
"private",
"static",
"BooleanNode",
"doesStringContain",
"(",
"JsonNode",
"subject",
",",
"JsonNode",
"search",
")",
"{",
"if",
"(",
"subject",
".",
"asText",
"(",
")",
".",
"contains",
"(",
"search",
".",
"asText",
"(",
")",
")",
")",
"{",
"return",
"Bo... | If the provided subject is a string, this function returns
true if the string contains the provided search argument.
@param subject String
@param search JmesPath expression
@return True string contains search;
False otherwise | [
"If",
"the",
"provided",
"subject",
"is",
"a",
"string",
"this",
"function",
"returns",
"true",
"if",
"the",
"string",
"contains",
"the",
"provided",
"search",
"argument",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathContainsFunction.java#L99-L104 |
jamesagnew/hapi-fhir | hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/model/Period.java | Period.setEnd | public Period setEnd( Date theDate, TemporalPrecisionEnum thePrecision) {
end = new DateTimeType(theDate, thePrecision);
return this;
} | java | public Period setEnd( Date theDate, TemporalPrecisionEnum thePrecision) {
end = new DateTimeType(theDate, thePrecision);
return this;
} | [
"public",
"Period",
"setEnd",
"(",
"Date",
"theDate",
",",
"TemporalPrecisionEnum",
"thePrecision",
")",
"{",
"end",
"=",
"new",
"DateTimeType",
"(",
"theDate",
",",
"thePrecision",
")",
";",
"return",
"this",
";",
"}"
] | Sets the value for <b>end</b> ()
<p>
<b>Definition:</b>
The end of the period. The boundary is inclusive.
</p> | [
"Sets",
"the",
"value",
"for",
"<b",
">",
"end<",
"/",
"b",
">",
"()"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/model/Period.java#L190-L193 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/jboss/logging/Logger.java | Logger.getLogger | public static Logger getLogger(String name, String suffix) {
return getLogger(name == null || name.length() == 0 ? suffix : name + "." + suffix);
} | java | public static Logger getLogger(String name, String suffix) {
return getLogger(name == null || name.length() == 0 ? suffix : name + "." + suffix);
} | [
"public",
"static",
"Logger",
"getLogger",
"(",
"String",
"name",
",",
"String",
"suffix",
")",
"{",
"return",
"getLogger",
"(",
"name",
"==",
"null",
"||",
"name",
".",
"length",
"(",
")",
"==",
"0",
"?",
"suffix",
":",
"name",
"+",
"\".\"",
"+",
"s... | Get a Logger instance given the logger name with the given suffix.
<p/>
<p>This will include a logger separator between logger name and suffix.
@param name the logger name
@param suffix a suffix to append to the logger name
@return the logger | [
"Get",
"a",
"Logger",
"instance",
"given",
"the",
"logger",
"name",
"with",
"the",
"given",
"suffix",
".",
"<p",
"/",
">",
"<p",
">",
"This",
"will",
"include",
"a",
"logger",
"separator",
"between",
"logger",
"name",
"and",
"suffix",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L2469-L2471 |
YahooArchive/samoa | samoa-threads/src/main/java/com/yahoo/labs/samoa/topology/impl/ThreadsProcessingItem.java | ThreadsProcessingItem.setupInstances | public void setupInstances() {
this.piInstances = new ArrayList<ThreadsProcessingItemInstance>(this.getParallelism());
for (int i=0; i<this.getParallelism(); i++) {
Processor newProcessor = this.getProcessor().newProcessor(this.getProcessor());
newProcessor.onCreate(i + 1);
this.piInstances.add(new ThreadsProcessingItemInstance(newProcessor, this.offset + i));
}
} | java | public void setupInstances() {
this.piInstances = new ArrayList<ThreadsProcessingItemInstance>(this.getParallelism());
for (int i=0; i<this.getParallelism(); i++) {
Processor newProcessor = this.getProcessor().newProcessor(this.getProcessor());
newProcessor.onCreate(i + 1);
this.piInstances.add(new ThreadsProcessingItemInstance(newProcessor, this.offset + i));
}
} | [
"public",
"void",
"setupInstances",
"(",
")",
"{",
"this",
".",
"piInstances",
"=",
"new",
"ArrayList",
"<",
"ThreadsProcessingItemInstance",
">",
"(",
"this",
".",
"getParallelism",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
... | /*
Setup the replicas of this PI.
This should be called after the topology is set up (all Processors and PIs are
setup and connected to the respective streams) and before events are sent. | [
"/",
"*",
"Setup",
"the",
"replicas",
"of",
"this",
"PI",
".",
"This",
"should",
"be",
"called",
"after",
"the",
"topology",
"is",
"set",
"up",
"(",
"all",
"Processors",
"and",
"PIs",
"are",
"setup",
"and",
"connected",
"to",
"the",
"respective",
"stream... | train | https://github.com/YahooArchive/samoa/blob/540a2c30167ac85c432b593baabd5ca97e7e8a0f/samoa-threads/src/main/java/com/yahoo/labs/samoa/topology/impl/ThreadsProcessingItem.java#L92-L99 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/macro/SarlProcessorInstanceForJvmTypeProvider.java | SarlProcessorInstanceForJvmTypeProvider.filterActiveProcessorType | public static JvmType filterActiveProcessorType(JvmType type, CommonTypeComputationServices services) {
if (AccessorsProcessor.class.getName().equals(type.getQualifiedName())) {
return services.getTypeReferences().findDeclaredType(SarlAccessorsProcessor.class, type);
}
return type;
} | java | public static JvmType filterActiveProcessorType(JvmType type, CommonTypeComputationServices services) {
if (AccessorsProcessor.class.getName().equals(type.getQualifiedName())) {
return services.getTypeReferences().findDeclaredType(SarlAccessorsProcessor.class, type);
}
return type;
} | [
"public",
"static",
"JvmType",
"filterActiveProcessorType",
"(",
"JvmType",
"type",
",",
"CommonTypeComputationServices",
"services",
")",
"{",
"if",
"(",
"AccessorsProcessor",
".",
"class",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"type",
".",
"getQualifiedN... | Filter the type in order to create the correct processor.
@param type the type of the processor specified into the {@code @Active} annotation.
@param services the type services of the framework.
@return the real type of the processor to instance. | [
"Filter",
"the",
"type",
"in",
"order",
"to",
"create",
"the",
"correct",
"processor",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/macro/SarlProcessorInstanceForJvmTypeProvider.java#L59-L64 |
cdapio/tigon | tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java | Bytes.compareTo | public static int compareTo(final byte [] left, final byte [] right) {
return LexicographicalComparerHolder.BEST_COMPARER.
compareTo(left, 0, left.length, right, 0, right.length);
} | java | public static int compareTo(final byte [] left, final byte [] right) {
return LexicographicalComparerHolder.BEST_COMPARER.
compareTo(left, 0, left.length, right, 0, right.length);
} | [
"public",
"static",
"int",
"compareTo",
"(",
"final",
"byte",
"[",
"]",
"left",
",",
"final",
"byte",
"[",
"]",
"right",
")",
"{",
"return",
"LexicographicalComparerHolder",
".",
"BEST_COMPARER",
".",
"compareTo",
"(",
"left",
",",
"0",
",",
"left",
".",
... | Lexicographically compare two arrays.
@param left left operand
@param right right operand
@return 0 if equal, < 0 if left is less than right, etc. | [
"Lexicographically",
"compare",
"two",
"arrays",
"."
] | train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L758-L761 |
undertow-io/undertow | core/src/main/java/io/undertow/protocols/http2/Http2Channel.java | Http2Channel.createStream | public synchronized Http2HeadersStreamSinkChannel createStream(HeaderMap requestHeaders) throws IOException {
if (!isClient()) {
throw UndertowMessages.MESSAGES.headersStreamCanOnlyBeCreatedByClient();
}
if (!isOpen()) {
throw UndertowMessages.MESSAGES.channelIsClosed();
}
sendConcurrentStreamsAtomicUpdater.incrementAndGet(this);
if(sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams) {
throw UndertowMessages.MESSAGES.streamLimitExceeded();
}
int streamId = streamIdCounter;
streamIdCounter += 2;
Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel(this, streamId, requestHeaders);
currentStreams.put(streamId, new StreamHolder(http2SynStreamStreamSinkChannel));
return http2SynStreamStreamSinkChannel;
} | java | public synchronized Http2HeadersStreamSinkChannel createStream(HeaderMap requestHeaders) throws IOException {
if (!isClient()) {
throw UndertowMessages.MESSAGES.headersStreamCanOnlyBeCreatedByClient();
}
if (!isOpen()) {
throw UndertowMessages.MESSAGES.channelIsClosed();
}
sendConcurrentStreamsAtomicUpdater.incrementAndGet(this);
if(sendMaxConcurrentStreams > 0 && sendConcurrentStreams > sendMaxConcurrentStreams) {
throw UndertowMessages.MESSAGES.streamLimitExceeded();
}
int streamId = streamIdCounter;
streamIdCounter += 2;
Http2HeadersStreamSinkChannel http2SynStreamStreamSinkChannel = new Http2HeadersStreamSinkChannel(this, streamId, requestHeaders);
currentStreams.put(streamId, new StreamHolder(http2SynStreamStreamSinkChannel));
return http2SynStreamStreamSinkChannel;
} | [
"public",
"synchronized",
"Http2HeadersStreamSinkChannel",
"createStream",
"(",
"HeaderMap",
"requestHeaders",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"isClient",
"(",
")",
")",
"{",
"throw",
"UndertowMessages",
".",
"MESSAGES",
".",
"headersStreamCanOnlyBe... | Creates a strema using a HEADERS frame
@param requestHeaders
@return
@throws IOException | [
"Creates",
"a",
"strema",
"using",
"a",
"HEADERS",
"frame"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2Channel.java#L881-L898 |
RestComm/media-core | rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpFactory.java | SdpFactory.rejectMediaField | public static void rejectMediaField(SessionDescription answer, MediaDescriptionField media) {
MediaDescriptionField rejected = new MediaDescriptionField();
rejected.setMedia(media.getMedia());
rejected.setPort(0);
rejected.setProtocol(media.getProtocol());
rejected.setPayloadTypes(media.getPayloadTypes());
rejected.setSession(answer);
answer.addMediaDescription(rejected);
} | java | public static void rejectMediaField(SessionDescription answer, MediaDescriptionField media) {
MediaDescriptionField rejected = new MediaDescriptionField();
rejected.setMedia(media.getMedia());
rejected.setPort(0);
rejected.setProtocol(media.getProtocol());
rejected.setPayloadTypes(media.getPayloadTypes());
rejected.setSession(answer);
answer.addMediaDescription(rejected);
} | [
"public",
"static",
"void",
"rejectMediaField",
"(",
"SessionDescription",
"answer",
",",
"MediaDescriptionField",
"media",
")",
"{",
"MediaDescriptionField",
"rejected",
"=",
"new",
"MediaDescriptionField",
"(",
")",
";",
"rejected",
".",
"setMedia",
"(",
"media",
... | Rejects a media description from an SDP offer.
@param answer
The SDP answer to include the rejected media
@param media
The offered media description to be rejected | [
"Rejects",
"a",
"media",
"description",
"from",
"an",
"SDP",
"offer",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpFactory.java#L107-L116 |
cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/persist/HDFSUtil.java | HDFSUtil.isFileClosed | private boolean isFileClosed(final DistributedFileSystem dfs, final Method m, final Path p) {
try {
return (Boolean) m.invoke(dfs, p);
} catch (SecurityException e) {
LOG.warn("No access", e);
} catch (Exception e) {
LOG.warn("Failed invocation for " + p.toString(), e);
}
return false;
} | java | private boolean isFileClosed(final DistributedFileSystem dfs, final Method m, final Path p) {
try {
return (Boolean) m.invoke(dfs, p);
} catch (SecurityException e) {
LOG.warn("No access", e);
} catch (Exception e) {
LOG.warn("Failed invocation for " + p.toString(), e);
}
return false;
} | [
"private",
"boolean",
"isFileClosed",
"(",
"final",
"DistributedFileSystem",
"dfs",
",",
"final",
"Method",
"m",
",",
"final",
"Path",
"p",
")",
"{",
"try",
"{",
"return",
"(",
"Boolean",
")",
"m",
".",
"invoke",
"(",
"dfs",
",",
"p",
")",
";",
"}",
... | Call HDFS-4525 isFileClosed if it is available.
@param dfs Filesystem instance to use.
@param m Method instance to call.
@param p Path of the file to check is closed.
@return True if file is closed. | [
"Call",
"HDFS",
"-",
"4525",
"isFileClosed",
"if",
"it",
"is",
"available",
"."
] | train | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/persist/HDFSUtil.java#L202-L211 |
craterdog/java-security-framework | java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java | CertificateManager.retrieveCertificate | public final X509Certificate retrieveCertificate(KeyStore keyStore, String certificateName) {
try {
logger.entry();
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateName);
logger.exit();
return certificate;
} catch (KeyStoreException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a certificate.", e);
logger.error(exception.toString());
throw exception;
}
} | java | public final X509Certificate retrieveCertificate(KeyStore keyStore, String certificateName) {
try {
logger.entry();
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateName);
logger.exit();
return certificate;
} catch (KeyStoreException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a certificate.", e);
logger.error(exception.toString());
throw exception;
}
} | [
"public",
"final",
"X509Certificate",
"retrieveCertificate",
"(",
"KeyStore",
"keyStore",
",",
"String",
"certificateName",
")",
"{",
"try",
"{",
"logger",
".",
"entry",
"(",
")",
";",
"X509Certificate",
"certificate",
"=",
"(",
"X509Certificate",
")",
"keyStore",... | This method retrieves a public certificate from a key store.
@param keyStore The key store containing the certificate.
@param certificateName The name (alias) of the certificate.
@return The X509 format public certificate. | [
"This",
"method",
"retrieves",
"a",
"public",
"certificate",
"from",
"a",
"key",
"store",
"."
] | train | https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L87-L98 |
Azure/azure-sdk-for-java | containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java | ManagedClustersInner.listClusterUserCredentialsAsync | public Observable<CredentialResultsInner> listClusterUserCredentialsAsync(String resourceGroupName, String resourceName) {
return listClusterUserCredentialsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<CredentialResultsInner>, CredentialResultsInner>() {
@Override
public CredentialResultsInner call(ServiceResponse<CredentialResultsInner> response) {
return response.body();
}
});
} | java | public Observable<CredentialResultsInner> listClusterUserCredentialsAsync(String resourceGroupName, String resourceName) {
return listClusterUserCredentialsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<CredentialResultsInner>, CredentialResultsInner>() {
@Override
public CredentialResultsInner call(ServiceResponse<CredentialResultsInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"CredentialResultsInner",
">",
"listClusterUserCredentialsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"return",
"listClusterUserCredentialsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceNa... | Gets cluster user credential of a managed cluster.
Gets cluster user credential of the managed cluster with a specified resource group and name.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the managed cluster resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CredentialResultsInner object | [
"Gets",
"cluster",
"user",
"credential",
"of",
"a",
"managed",
"cluster",
".",
"Gets",
"cluster",
"user",
"credential",
"of",
"the",
"managed",
"cluster",
"with",
"a",
"specified",
"resource",
"group",
"and",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ManagedClustersInner.java#L688-L695 |
mockito/mockito | src/main/java/org/mockito/internal/util/reflection/Fields.java | Fields.allDeclaredFieldsOf | public static InstanceFields allDeclaredFieldsOf(Object instance) {
List<InstanceField> instanceFields = new ArrayList<InstanceField>();
for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields()));
}
return new InstanceFields(instance, instanceFields);
} | java | public static InstanceFields allDeclaredFieldsOf(Object instance) {
List<InstanceField> instanceFields = new ArrayList<InstanceField>();
for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields()));
}
return new InstanceFields(instance, instanceFields);
} | [
"public",
"static",
"InstanceFields",
"allDeclaredFieldsOf",
"(",
"Object",
"instance",
")",
"{",
"List",
"<",
"InstanceField",
">",
"instanceFields",
"=",
"new",
"ArrayList",
"<",
"InstanceField",
">",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"cla... | Instance fields declared in the class and superclasses of the given instance.
@param instance Instance from which declared fields will be retrieved.
@return InstanceFields of this object instance. | [
"Instance",
"fields",
"declared",
"in",
"the",
"class",
"and",
"superclasses",
"of",
"the",
"given",
"instance",
"."
] | train | https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/util/reflection/Fields.java#L29-L35 |
Talend/tesb-rt-se | locator/src/main/java/org/talend/esb/servicelocator/cxf/internal/CXFEndpointProvider.java | CXFEndpointProvider.createEPR | private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {
EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();
EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);
WSAEndpointReferenceUtils.setAddress(targetEPR, address);
if (props != null) {
addProperties(targetEPR, props);
}
return targetEPR;
} | java | private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {
EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();
EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);
WSAEndpointReferenceUtils.setAddress(targetEPR, address);
if (props != null) {
addProperties(targetEPR, props);
}
return targetEPR;
} | [
"private",
"static",
"EndpointReferenceType",
"createEPR",
"(",
"Server",
"server",
",",
"String",
"address",
",",
"SLProperties",
"props",
")",
"{",
"EndpointReferenceType",
"sourceEPR",
"=",
"server",
".",
"getEndpoint",
"(",
")",
".",
"getEndpointInfo",
"(",
")... | Creates an endpoint reference by duplicating the endpoint reference of a given server.
@param server
@param address
@param props
@return | [
"Creates",
"an",
"endpoint",
"reference",
"by",
"duplicating",
"the",
"endpoint",
"reference",
"of",
"a",
"given",
"server",
"."
] | train | https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/locator/src/main/java/org/talend/esb/servicelocator/cxf/internal/CXFEndpointProvider.java#L294-L303 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java | BoxApiFile.getDownloadRepresentationRequest | public BoxRequestsFile.DownloadRepresentation getDownloadRepresentationRequest(String id, File targetFile, BoxRepresentation representation) {
return new BoxRequestsFile.DownloadRepresentation(id, targetFile, representation, mSession);
} | java | public BoxRequestsFile.DownloadRepresentation getDownloadRepresentationRequest(String id, File targetFile, BoxRepresentation representation) {
return new BoxRequestsFile.DownloadRepresentation(id, targetFile, representation, mSession);
} | [
"public",
"BoxRequestsFile",
".",
"DownloadRepresentation",
"getDownloadRepresentationRequest",
"(",
"String",
"id",
",",
"File",
"targetFile",
",",
"BoxRepresentation",
"representation",
")",
"{",
"return",
"new",
"BoxRequestsFile",
".",
"DownloadRepresentation",
"(",
"i... | Gets a request to download a representation object for a given file representation
@param id id of the file to get the representation from
@param targetFile file to store the thumbnail
@param representation the representation to be downloaded
@return request to download the representation | [
"Gets",
"a",
"request",
"to",
"download",
"a",
"representation",
"object",
"for",
"a",
"given",
"file",
"representation"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L442-L444 |
aws/aws-sdk-java | aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/AWSJavaMailTransport.java | AWSJavaMailTransport.sendEmail | private void sendEmail(Message m, SendRawEmailRequest req)
throws SendFailedException, MessagingException {
Address[] sent = null;
Address[] unsent = null;
Address[] invalid = null;
try {
appendUserAgent(req, USER_AGENT);
SendRawEmailResult resp = this.emailService.sendRawEmail(req);
lastMessageId = resp.getMessageId();
sent = m.getAllRecipients();
unsent = new Address[0];
invalid = new Address[0];
super.notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED,
sent, unsent, invalid, m);
} catch (Exception e) {
sent = new Address[0];
unsent = m.getAllRecipients();
invalid = new Address[0];
super.notifyTransportListeners(
TransportEvent.MESSAGE_NOT_DELIVERED, sent, unsent,
invalid, m);
throw new SendFailedException("Unable to send email", e, sent,
unsent, invalid);
}
} | java | private void sendEmail(Message m, SendRawEmailRequest req)
throws SendFailedException, MessagingException {
Address[] sent = null;
Address[] unsent = null;
Address[] invalid = null;
try {
appendUserAgent(req, USER_AGENT);
SendRawEmailResult resp = this.emailService.sendRawEmail(req);
lastMessageId = resp.getMessageId();
sent = m.getAllRecipients();
unsent = new Address[0];
invalid = new Address[0];
super.notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED,
sent, unsent, invalid, m);
} catch (Exception e) {
sent = new Address[0];
unsent = m.getAllRecipients();
invalid = new Address[0];
super.notifyTransportListeners(
TransportEvent.MESSAGE_NOT_DELIVERED, sent, unsent,
invalid, m);
throw new SendFailedException("Unable to send email", e, sent,
unsent, invalid);
}
} | [
"private",
"void",
"sendEmail",
"(",
"Message",
"m",
",",
"SendRawEmailRequest",
"req",
")",
"throws",
"SendFailedException",
",",
"MessagingException",
"{",
"Address",
"[",
"]",
"sent",
"=",
"null",
";",
"Address",
"[",
"]",
"unsent",
"=",
"null",
";",
"Add... | Sends an email using AWS E-mail Service and notifies listeners
@param m
Message used to notify users
@param req
Raw email to be sent | [
"Sends",
"an",
"email",
"using",
"AWS",
"E",
"-",
"mail",
"Service",
"and",
"notifies",
"listeners"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/AWSJavaMailTransport.java#L260-L286 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java | StyleUtils.createPolygonOptions | public static PolygonOptions createPolygonOptions(StyleRow style, float density) {
PolygonOptions polygonOptions = new PolygonOptions();
setStyle(polygonOptions, style, density);
return polygonOptions;
} | java | public static PolygonOptions createPolygonOptions(StyleRow style, float density) {
PolygonOptions polygonOptions = new PolygonOptions();
setStyle(polygonOptions, style, density);
return polygonOptions;
} | [
"public",
"static",
"PolygonOptions",
"createPolygonOptions",
"(",
"StyleRow",
"style",
",",
"float",
"density",
")",
"{",
"PolygonOptions",
"polygonOptions",
"=",
"new",
"PolygonOptions",
"(",
")",
";",
"setStyle",
"(",
"polygonOptions",
",",
"style",
",",
"densi... | Create new polygon options populated with the style
@param style style row
@param density display density: {@link android.util.DisplayMetrics#density}
@return polygon options populated with the style | [
"Create",
"new",
"polygon",
"options",
"populated",
"with",
"the",
"style"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L587-L593 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java | WordVectorSerializer.writeWordVectors | public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable,
OutputStream stream) throws IOException {
val vocabCache = lookupTable.getVocabCache();
try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) {
// saving header as "NUM_WORDS VECTOR_SIZE NUM_DOCS"
val str = vocabCache.numWords() + " " + lookupTable.layerSize() + " " + vocabCache.totalNumberOfDocs();
log.debug("Saving header: {}", str);
writer.println(str);
// saving vocab content
val num = vocabCache.numWords();
for (int x = 0; x < num; x++) {
T element = vocabCache.elementAtIndex(x);
val builder = new StringBuilder();
val l = element.getLabel();
builder.append(encodeB64(l)).append(" ");
val vec = lookupTable.vector(element.getLabel());
for (int i = 0; i < vec.length(); i++) {
builder.append(vec.getDouble(i));
if (i < vec.length() - 1)
builder.append(" ");
}
writer.println(builder.toString());
}
}
} | java | public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable,
OutputStream stream) throws IOException {
val vocabCache = lookupTable.getVocabCache();
try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8))) {
// saving header as "NUM_WORDS VECTOR_SIZE NUM_DOCS"
val str = vocabCache.numWords() + " " + lookupTable.layerSize() + " " + vocabCache.totalNumberOfDocs();
log.debug("Saving header: {}", str);
writer.println(str);
// saving vocab content
val num = vocabCache.numWords();
for (int x = 0; x < num; x++) {
T element = vocabCache.elementAtIndex(x);
val builder = new StringBuilder();
val l = element.getLabel();
builder.append(encodeB64(l)).append(" ");
val vec = lookupTable.vector(element.getLabel());
for (int i = 0; i < vec.length(); i++) {
builder.append(vec.getDouble(i));
if (i < vec.length() - 1)
builder.append(" ");
}
writer.println(builder.toString());
}
}
} | [
"public",
"static",
"<",
"T",
"extends",
"SequenceElement",
">",
"void",
"writeWordVectors",
"(",
"WeightLookupTable",
"<",
"T",
">",
"lookupTable",
",",
"OutputStream",
"stream",
")",
"throws",
"IOException",
"{",
"val",
"vocabCache",
"=",
"lookupTable",
".",
"... | This method writes word vectors to the given OutputStream.
Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network.
@param lookupTable
@param stream
@param <T>
@throws IOException | [
"This",
"method",
"writes",
"word",
"vectors",
"to",
"the",
"given",
"OutputStream",
".",
"Please",
"note",
":",
"this",
"method",
"doesn",
"t",
"load",
"whole",
"vocab",
"/",
"lookupTable",
"into",
"memory",
"so",
"it",
"s",
"able",
"to",
"process",
"larg... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L339-L367 |
haifengl/smile | math/src/main/java/smile/math/Math.java | Math.row | private static int row(int[] r, int f) {
int i = 0;
while (i < r.length && r[i] < f) {
++i;
}
return ((i < r.length && r[i] == f) ? i : -1);
} | java | private static int row(int[] r, int f) {
int i = 0;
while (i < r.length && r[i] < f) {
++i;
}
return ((i < r.length && r[i] == f) ? i : -1);
} | [
"private",
"static",
"int",
"row",
"(",
"int",
"[",
"]",
"r",
",",
"int",
"f",
")",
"{",
"int",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"r",
".",
"length",
"&&",
"r",
"[",
"i",
"]",
"<",
"f",
")",
"{",
"++",
"i",
";",
"}",
"return",
... | Returns the index of given frequency.
@param r the frequency list.
@param f the given frequency.
@return the index of given frequency or -1 if it doesn't exist in the list. | [
"Returns",
"the",
"index",
"of",
"given",
"frequency",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Math.java#L3258-L3266 |
agmip/ace-lookup | src/main/java/org/agmip/ace/util/AcePathfinderUtil.java | AcePathfinderUtil.insertValue | public static void insertValue(HashMap m, String var, String val) {
insertValue(m, var, val, null);
} | java | public static void insertValue(HashMap m, String var, String val) {
insertValue(m, var, val, null);
} | [
"public",
"static",
"void",
"insertValue",
"(",
"HashMap",
"m",
",",
"String",
"var",
",",
"String",
"val",
")",
"{",
"insertValue",
"(",
"m",
",",
"var",
",",
"val",
",",
"null",
")",
";",
"}"
] | Inserts the variable in the appropriate place in a {@link HashMap},
according to the AcePathfinder.
@param m the HashMap to add the variable to.
@param var Variable to lookup
@param val the value to insert into the HashMap | [
"Inserts",
"the",
"variable",
"in",
"the",
"appropriate",
"place",
"in",
"a",
"{",
"@link",
"HashMap",
"}",
"according",
"to",
"the",
"AcePathfinder",
"."
] | train | https://github.com/agmip/ace-lookup/blob/d8224a231cb8c01729e63010916a2a85517ce4c1/src/main/java/org/agmip/ace/util/AcePathfinderUtil.java#L90-L92 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java | TransformerIdentityImpl.getOutputProperty | public String getOutputProperty(String name) throws IllegalArgumentException
{
String value = null;
OutputProperties props = m_outputFormat;
value = props.getProperty(name);
if (null == value)
{
if (!OutputProperties.isLegalPropertyKey(name))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{name})); //"output property not recognized: "
// + name);
}
return value;
} | java | public String getOutputProperty(String name) throws IllegalArgumentException
{
String value = null;
OutputProperties props = m_outputFormat;
value = props.getProperty(name);
if (null == value)
{
if (!OutputProperties.isLegalPropertyKey(name))
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{name})); //"output property not recognized: "
// + name);
}
return value;
} | [
"public",
"String",
"getOutputProperty",
"(",
"String",
"name",
")",
"throws",
"IllegalArgumentException",
"{",
"String",
"value",
"=",
"null",
";",
"OutputProperties",
"props",
"=",
"m_outputFormat",
";",
"value",
"=",
"props",
".",
"getProperty",
"(",
"name",
... | Get an output property that is in effect for the
transformation. The property specified may be a property
that was set with setOutputProperty, or it may be a
property specified in the stylesheet.
@param name A non-null String that specifies an output
property name, which may be namespace qualified.
@return The string value of the output property, or null
if no property was found.
@throws IllegalArgumentException If the property is not supported.
@see javax.xml.transform.OutputKeys | [
"Get",
"an",
"output",
"property",
"that",
"is",
"in",
"effect",
"for",
"the",
"transformation",
".",
"The",
"property",
"specified",
"may",
"be",
"a",
"property",
"that",
"was",
"set",
"with",
"setOutputProperty",
"or",
"it",
"may",
"be",
"a",
"property",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java#L762-L778 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/AVA.java | AVA.toRFC1779String | public String toRFC1779String(Map<String, String> oidMap) {
return toKeywordValueString(toKeyword(RFC1779, oidMap));
} | java | public String toRFC1779String(Map<String, String> oidMap) {
return toKeywordValueString(toKeyword(RFC1779, oidMap));
} | [
"public",
"String",
"toRFC1779String",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"oidMap",
")",
"{",
"return",
"toKeywordValueString",
"(",
"toKeyword",
"(",
"RFC1779",
",",
"oidMap",
")",
")",
";",
"}"
] | Returns a printable form of this attribute, using RFC 1779
syntax for individual attribute/value assertions. It
emits standardised keywords, as well as keywords contained in the
OID/keyword map. | [
"Returns",
"a",
"printable",
"form",
"of",
"this",
"attribute",
"using",
"RFC",
"1779",
"syntax",
"for",
"individual",
"attribute",
"/",
"value",
"assertions",
".",
"It",
"emits",
"standardised",
"keywords",
"as",
"well",
"as",
"keywords",
"contained",
"in",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/AVA.java#L711-L713 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/lss/LssClient.java | LssClient.getAllDomainsPlayCount | public GetAllDomainsPlayCountResponse getAllDomainsPlayCount(GetAllDomainsStatisticsRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getTimeInterval(), "timeInterval should NOT be null");
checkStringNotEmpty(request.getStartTime(), "startTime should NOT be null");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request,
STATISTICS, LIVE_DOMAIN, "playcount");
internalRequest.addParameter("timeInterval", request.getTimeInterval());
internalRequest.addParameter("startTime", request.getStartTime());
if (request.getEndTime() != null) {
internalRequest.addParameter("endTime", request.getEndTime());
}
return invokeHttpClient(internalRequest, GetAllDomainsPlayCountResponse.class);
} | java | public GetAllDomainsPlayCountResponse getAllDomainsPlayCount(GetAllDomainsStatisticsRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getTimeInterval(), "timeInterval should NOT be null");
checkStringNotEmpty(request.getStartTime(), "startTime should NOT be null");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request,
STATISTICS, LIVE_DOMAIN, "playcount");
internalRequest.addParameter("timeInterval", request.getTimeInterval());
internalRequest.addParameter("startTime", request.getStartTime());
if (request.getEndTime() != null) {
internalRequest.addParameter("endTime", request.getEndTime());
}
return invokeHttpClient(internalRequest, GetAllDomainsPlayCountResponse.class);
} | [
"public",
"GetAllDomainsPlayCountResponse",
"getAllDomainsPlayCount",
"(",
"GetAllDomainsStatisticsRequest",
"request",
")",
"{",
"checkNotNull",
"(",
"request",
",",
"\"The parameter request should NOT be null.\"",
")",
";",
"checkStringNotEmpty",
"(",
"request",
".",
"getTime... | get all domains' total play count statistics in the live stream service.
@param request The request object containing all options for getting all domains' play count statistics
@return the response | [
"get",
"all",
"domains",
"total",
"play",
"count",
"statistics",
"in",
"the",
"live",
"stream",
"service",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L1853-L1867 |
kmi/iserve | iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/Util.java | Util.getIntegerValue | public static Integer getIntegerValue(QuerySolution resultRow, String variableName) {
if (resultRow != null) {
Resource res = resultRow.getResource(variableName);
if (res != null && res.isLiteral()) {
Literal val = res.asLiteral();
if (val != null) {
return Integer.valueOf(val.getInt());
}
}
}
return null;
} | java | public static Integer getIntegerValue(QuerySolution resultRow, String variableName) {
if (resultRow != null) {
Resource res = resultRow.getResource(variableName);
if (res != null && res.isLiteral()) {
Literal val = res.asLiteral();
if (val != null) {
return Integer.valueOf(val.getInt());
}
}
}
return null;
} | [
"public",
"static",
"Integer",
"getIntegerValue",
"(",
"QuerySolution",
"resultRow",
",",
"String",
"variableName",
")",
"{",
"if",
"(",
"resultRow",
"!=",
"null",
")",
"{",
"Resource",
"res",
"=",
"resultRow",
".",
"getResource",
"(",
"variableName",
")",
";"... | Given a query result from a SPARQL query, obtain the number value at the
given variable
@param resultRow the result from a SPARQL query
@param variableName the name of the variable to obtain
@return the Integer value, or null otherwise | [
"Given",
"a",
"query",
"result",
"from",
"a",
"SPARQL",
"query",
"obtain",
"the",
"number",
"value",
"at",
"the",
"given",
"variable"
] | train | https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/Util.java#L181-L194 |
geomajas/geomajas-project-client-gwt2 | plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java | TileBasedLayerClient.createDefaultOsmLayer | @Deprecated
public OsmLayer createDefaultOsmLayer(String id, TileConfiguration conf) {
OsmLayer layer = new OsmLayer(id, conf);
layer.addUrls(Arrays.asList(DEFAULT_OSM_URLS));
return layer;
} | java | @Deprecated
public OsmLayer createDefaultOsmLayer(String id, TileConfiguration conf) {
OsmLayer layer = new OsmLayer(id, conf);
layer.addUrls(Arrays.asList(DEFAULT_OSM_URLS));
return layer;
} | [
"@",
"Deprecated",
"public",
"OsmLayer",
"createDefaultOsmLayer",
"(",
"String",
"id",
",",
"TileConfiguration",
"conf",
")",
"{",
"OsmLayer",
"layer",
"=",
"new",
"OsmLayer",
"(",
"id",
",",
"conf",
")",
";",
"layer",
".",
"addUrls",
"(",
"Arrays",
".",
"... | Create a new OSM layer with the given ID and tile configuration. The layer will be configured
with the default OSM tile services so you don't have to specify these URLs yourself.
@param id The unique ID of the layer.
@param conf The tile configuration.
@return A new OSM layer.
@deprecated use {@link #createDefaultOsmLayer(String, int)} | [
"Create",
"a",
"new",
"OSM",
"layer",
"with",
"the",
"given",
"ID",
"and",
"tile",
"configuration",
".",
"The",
"layer",
"will",
"be",
"configured",
"with",
"the",
"default",
"OSM",
"tile",
"services",
"so",
"you",
"don",
"t",
"have",
"to",
"specify",
"t... | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L132-L137 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/core/TraceNLSHelper.java | TraceNLSHelper.getString | public String getString(String key, String defaultString) {
if (tnls != null)
return tnls.getString(key, defaultString);
return defaultString;
} | java | public String getString(String key, String defaultString) {
if (tnls != null)
return tnls.getString(key, defaultString);
return defaultString;
} | [
"public",
"String",
"getString",
"(",
"String",
"key",
",",
"String",
"defaultString",
")",
"{",
"if",
"(",
"tnls",
"!=",
"null",
")",
"return",
"tnls",
".",
"getString",
"(",
"key",
",",
"defaultString",
")",
";",
"return",
"defaultString",
";",
"}"
] | Look for a translated message using the input key. If it is not found, then
the provided default string is returned.
@param key
@param defaultString
@return String | [
"Look",
"for",
"a",
"translated",
"message",
"using",
"the",
"input",
"key",
".",
"If",
"it",
"is",
"not",
"found",
"then",
"the",
"provided",
"default",
"string",
"is",
"returned",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/core/TraceNLSHelper.java#L52-L57 |
FINRAOS/JTAF-ExtWebDriver | src/main/java/org/finra/jtaf/ewd/widget/element/Element.java | Element.getNodeListUsingJavaXPath | private NodeList getNodeListUsingJavaXPath(String xpath) throws Exception {
XPathFactory xpathFac = XPathFactory.newInstance();
XPath theXpath = xpathFac.newXPath();
String html = getGUIDriver().getHtmlSource();
html = html.replaceAll(">\\s+<", "><");
InputStream input = new ByteArrayInputStream(html.getBytes(Charset.forName("UTF-8")));
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, false);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, new InputSource(input)), result);
Node htmlNode = result.getNode(); // This code gets a Node from the
// result.
NodeList nodes = (NodeList) theXpath.evaluate(xpath, htmlNode, XPathConstants.NODESET);
return nodes;
} | java | private NodeList getNodeListUsingJavaXPath(String xpath) throws Exception {
XPathFactory xpathFac = XPathFactory.newInstance();
XPath theXpath = xpathFac.newXPath();
String html = getGUIDriver().getHtmlSource();
html = html.replaceAll(">\\s+<", "><");
InputStream input = new ByteArrayInputStream(html.getBytes(Charset.forName("UTF-8")));
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, false);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, new InputSource(input)), result);
Node htmlNode = result.getNode(); // This code gets a Node from the
// result.
NodeList nodes = (NodeList) theXpath.evaluate(xpath, htmlNode, XPathConstants.NODESET);
return nodes;
} | [
"private",
"NodeList",
"getNodeListUsingJavaXPath",
"(",
"String",
"xpath",
")",
"throws",
"Exception",
"{",
"XPathFactory",
"xpathFac",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
";",
"XPath",
"theXpath",
"=",
"xpathFac",
".",
"newXPath",
"(",
")",
";",... | Get the list of nodes which satisfy the xpath expression passed in
@param xpath
the input xpath expression
@return the nodeset of matching elements
@throws Exception | [
"Get",
"the",
"list",
"of",
"nodes",
"which",
"satisfy",
"the",
"xpath",
"expression",
"passed",
"in"
] | train | https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/widget/element/Element.java#L892-L912 |
cloudant/java-cloudant | cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java | CouchDbClient.executeToInputStream | public InputStream executeToInputStream(HttpConnection connection) throws CouchDbException {
try {
return execute(connection).responseAsInputStream();
} catch (IOException ioe) {
throw new CouchDbException("Error retrieving server response", ioe);
}
} | java | public InputStream executeToInputStream(HttpConnection connection) throws CouchDbException {
try {
return execute(connection).responseAsInputStream();
} catch (IOException ioe) {
throw new CouchDbException("Error retrieving server response", ioe);
}
} | [
"public",
"InputStream",
"executeToInputStream",
"(",
"HttpConnection",
"connection",
")",
"throws",
"CouchDbException",
"{",
"try",
"{",
"return",
"execute",
"(",
"connection",
")",
".",
"responseAsInputStream",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"i... | <p>Execute the HttpConnection request and return the InputStream if there were no errors.</p>
<p>The stream <b>must</b> be closed after use.</p>
@param connection the request HttpConnection
@return InputStream from the HttpConnection response
@throws CouchDbException for HTTP error codes or if there was an IOException | [
"<p",
">",
"Execute",
"the",
"HttpConnection",
"request",
"and",
"return",
"the",
"InputStream",
"if",
"there",
"were",
"no",
"errors",
".",
"<",
"/",
"p",
">",
"<p",
">",
"The",
"stream",
"<b",
">",
"must<",
"/",
"b",
">",
"be",
"closed",
"after",
"... | train | https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/org/lightcouch/CouchDbClient.java#L644-L650 |
phax/ph-oton | ph-oton-uictrls/src/main/java/com/helger/photon/uictrls/fineupload5/FineUploader5DeleteFile.java | FineUploader5DeleteFile.addCustomHeader | @Nonnull
public FineUploader5DeleteFile addCustomHeader (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue)
{
ValueEnforcer.notEmpty (sKey, "Key");
ValueEnforcer.notNull (sValue, "Value");
m_aDeleteFileCustomHeaders.put (sKey, sValue);
return this;
} | java | @Nonnull
public FineUploader5DeleteFile addCustomHeader (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue)
{
ValueEnforcer.notEmpty (sKey, "Key");
ValueEnforcer.notNull (sValue, "Value");
m_aDeleteFileCustomHeaders.put (sKey, sValue);
return this;
} | [
"@",
"Nonnull",
"public",
"FineUploader5DeleteFile",
"addCustomHeader",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sKey",
",",
"@",
"Nonnull",
"final",
"String",
"sValue",
")",
"{",
"ValueEnforcer",
".",
"notEmpty",
"(",
"sKey",
",",
"\"Key\"",
... | Any additional headers to attach to all delete file requests.
@param sKey
Custom header name
@param sValue
Custom header value
@return this | [
"Any",
"additional",
"headers",
"to",
"attach",
"to",
"all",
"delete",
"file",
"requests",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-uictrls/src/main/java/com/helger/photon/uictrls/fineupload5/FineUploader5DeleteFile.java#L98-L106 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/subordinate/SubordinateControlMandatoryExample.java | SubordinateControlMandatoryExample.build | private static WComponent build() {
WContainer root = new WContainer();
WSubordinateControl control = new WSubordinateControl();
root.add(control);
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(25);
layout.setMargin(new com.github.bordertech.wcomponents.Margin(0, 0, 12, 0));
WCheckBox checkBox = new WCheckBox();
layout.addField("Set Mandatory", checkBox);
WTextField text = new WTextField();
layout.addField("Might need this field", text);
WTextField mandatoryField = new WTextField();
layout.addField("Another field always mandatory", mandatoryField);
mandatoryField.setMandatory(true);
final WRadioButtonSelect rbSelect = new WRadioButtonSelect("australian_state");
layout.addField("Select a state", rbSelect);
root.add(layout);
Rule rule = new Rule();
rule.setCondition(new Equal(checkBox, Boolean.TRUE.toString()));
rule.addActionOnTrue(new Mandatory(text));
rule.addActionOnFalse(new Optional(text));
rule.addActionOnTrue(new Mandatory(rbSelect));
rule.addActionOnFalse(new Optional(rbSelect));
control.addRule(rule);
return root;
} | java | private static WComponent build() {
WContainer root = new WContainer();
WSubordinateControl control = new WSubordinateControl();
root.add(control);
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(25);
layout.setMargin(new com.github.bordertech.wcomponents.Margin(0, 0, 12, 0));
WCheckBox checkBox = new WCheckBox();
layout.addField("Set Mandatory", checkBox);
WTextField text = new WTextField();
layout.addField("Might need this field", text);
WTextField mandatoryField = new WTextField();
layout.addField("Another field always mandatory", mandatoryField);
mandatoryField.setMandatory(true);
final WRadioButtonSelect rbSelect = new WRadioButtonSelect("australian_state");
layout.addField("Select a state", rbSelect);
root.add(layout);
Rule rule = new Rule();
rule.setCondition(new Equal(checkBox, Boolean.TRUE.toString()));
rule.addActionOnTrue(new Mandatory(text));
rule.addActionOnFalse(new Optional(text));
rule.addActionOnTrue(new Mandatory(rbSelect));
rule.addActionOnFalse(new Optional(rbSelect));
control.addRule(rule);
return root;
} | [
"private",
"static",
"WComponent",
"build",
"(",
")",
"{",
"WContainer",
"root",
"=",
"new",
"WContainer",
"(",
")",
";",
"WSubordinateControl",
"control",
"=",
"new",
"WSubordinateControl",
"(",
")",
";",
"root",
".",
"add",
"(",
"control",
")",
";",
"WFi... | Creates the component to be added to the validation container. This is doen in a static method because the
component is passed into the superclass constructor.
@return the component to be added to the validation container. | [
"Creates",
"the",
"component",
"to",
"be",
"added",
"to",
"the",
"validation",
"container",
".",
"This",
"is",
"doen",
"in",
"a",
"static",
"method",
"because",
"the",
"component",
"is",
"passed",
"into",
"the",
"superclass",
"constructor",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/subordinate/SubordinateControlMandatoryExample.java#L37-L71 |
phax/ph-oton | ph-oton-html/src/main/java/com/helger/html/hc/html/metadata/HCHead.java | HCHead.addCSSAt | @Nonnull
public final HCHead addCSSAt (@Nonnegative final int nIndex, @Nonnull final IHCNode aCSS)
{
ValueEnforcer.notNull (aCSS, "CSS");
if (!HCCSSNodeDetector.isCSSNode (aCSS))
throw new IllegalArgumentException (aCSS + " is not a valid CSS node!");
m_aCSS.add (nIndex, aCSS);
return this;
} | java | @Nonnull
public final HCHead addCSSAt (@Nonnegative final int nIndex, @Nonnull final IHCNode aCSS)
{
ValueEnforcer.notNull (aCSS, "CSS");
if (!HCCSSNodeDetector.isCSSNode (aCSS))
throw new IllegalArgumentException (aCSS + " is not a valid CSS node!");
m_aCSS.add (nIndex, aCSS);
return this;
} | [
"@",
"Nonnull",
"public",
"final",
"HCHead",
"addCSSAt",
"(",
"@",
"Nonnegative",
"final",
"int",
"nIndex",
",",
"@",
"Nonnull",
"final",
"IHCNode",
"aCSS",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aCSS",
",",
"\"CSS\"",
")",
";",
"if",
"(",
"!",... | Add a CSS node at the specified index.
@param nIndex
The index to add. Should be ≥ 0.
@param aCSS
The CSS node to be added. May not be <code>null</code>.
@return this for chaining | [
"Add",
"a",
"CSS",
"node",
"at",
"the",
"specified",
"index",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-html/src/main/java/com/helger/html/hc/html/metadata/HCHead.java#L200-L208 |
alibaba/jstorm | example/sequence-split-merge/src/main/java/org/apache/storm/starter/trident/TridentMinMaxOfDevicesTopology.java | TridentMinMaxOfDevicesTopology.buildDevicesTopology | public static StormTopology buildDevicesTopology() {
String deviceID = "device-id";
String count = "count";
Fields allFields = new Fields(deviceID, count);
RandomNumberGeneratorSpout spout = new RandomNumberGeneratorSpout(allFields, 10, 1000);
TridentTopology topology = new TridentTopology();
Stream devicesStream = topology.newStream("devicegen-spout", spout).each(allFields, new Debug("##### devices"));
devicesStream.minBy(deviceID).each(allFields, new Debug("#### device with min id"));
devicesStream.maxBy(count).each(allFields, new Debug("#### device with max count"));
return topology.build();
} | java | public static StormTopology buildDevicesTopology() {
String deviceID = "device-id";
String count = "count";
Fields allFields = new Fields(deviceID, count);
RandomNumberGeneratorSpout spout = new RandomNumberGeneratorSpout(allFields, 10, 1000);
TridentTopology topology = new TridentTopology();
Stream devicesStream = topology.newStream("devicegen-spout", spout).each(allFields, new Debug("##### devices"));
devicesStream.minBy(deviceID).each(allFields, new Debug("#### device with min id"));
devicesStream.maxBy(count).each(allFields, new Debug("#### device with max count"));
return topology.build();
} | [
"public",
"static",
"StormTopology",
"buildDevicesTopology",
"(",
")",
"{",
"String",
"deviceID",
"=",
"\"device-id\"",
";",
"String",
"count",
"=",
"\"count\"",
";",
"Fields",
"allFields",
"=",
"new",
"Fields",
"(",
"deviceID",
",",
"count",
")",
";",
"Random... | Creates a topology with device-id and count (which are whole numbers) as
tuple fields in a stream and it finally generates result stream based on
min amd max with device-id and count values. | [
"Creates",
"a",
"topology",
"with",
"device",
"-",
"id",
"and",
"count",
"(",
"which",
"are",
"whole",
"numbers",
")",
"as",
"tuple",
"fields",
"in",
"a",
"stream",
"and",
"it",
"finally",
"generates",
"result",
"stream",
"based",
"on",
"min",
"amd",
"ma... | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/example/sequence-split-merge/src/main/java/org/apache/storm/starter/trident/TridentMinMaxOfDevicesTopology.java#L55-L70 |
citrusframework/citrus | modules/citrus-zookeeper/src/main/java/com/consol/citrus/zookeeper/server/ZooServer.java | ZooServer.getZooKeeperServer | public ZooKeeperServer getZooKeeperServer() {
if (zooKeeperServer == null) {
String dataDirectory = System.getProperty("java.io.tmpdir");
File dir = new File(dataDirectory, "zookeeper").getAbsoluteFile();
try {
zooKeeperServer = new ZooKeeperServer(dir, dir, 2000);
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to create default zookeeper server", e);
}
}
return zooKeeperServer;
} | java | public ZooKeeperServer getZooKeeperServer() {
if (zooKeeperServer == null) {
String dataDirectory = System.getProperty("java.io.tmpdir");
File dir = new File(dataDirectory, "zookeeper").getAbsoluteFile();
try {
zooKeeperServer = new ZooKeeperServer(dir, dir, 2000);
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to create default zookeeper server", e);
}
}
return zooKeeperServer;
} | [
"public",
"ZooKeeperServer",
"getZooKeeperServer",
"(",
")",
"{",
"if",
"(",
"zooKeeperServer",
"==",
"null",
")",
"{",
"String",
"dataDirectory",
"=",
"System",
".",
"getProperty",
"(",
"\"java.io.tmpdir\"",
")",
";",
"File",
"dir",
"=",
"new",
"File",
"(",
... | Gets the value of the zooKeeperServer property.
@return the zooKeeperServer | [
"Gets",
"the",
"value",
"of",
"the",
"zooKeeperServer",
"property",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-zookeeper/src/main/java/com/consol/citrus/zookeeper/server/ZooServer.java#L85-L97 |
cryptomator/cryptofs | src/main/java/org/cryptomator/cryptofs/CryptoFileSystemProvider.java | CryptoFileSystemProvider.containsVault | public static boolean containsVault(Path pathToVault, String masterkeyFilename) {
Path masterKeyPath = pathToVault.resolve(masterkeyFilename);
Path dataDirPath = pathToVault.resolve(Constants.DATA_DIR_NAME);
return Files.isReadable(masterKeyPath) && Files.isDirectory(dataDirPath);
} | java | public static boolean containsVault(Path pathToVault, String masterkeyFilename) {
Path masterKeyPath = pathToVault.resolve(masterkeyFilename);
Path dataDirPath = pathToVault.resolve(Constants.DATA_DIR_NAME);
return Files.isReadable(masterKeyPath) && Files.isDirectory(dataDirPath);
} | [
"public",
"static",
"boolean",
"containsVault",
"(",
"Path",
"pathToVault",
",",
"String",
"masterkeyFilename",
")",
"{",
"Path",
"masterKeyPath",
"=",
"pathToVault",
".",
"resolve",
"(",
"masterkeyFilename",
")",
";",
"Path",
"dataDirPath",
"=",
"pathToVault",
".... | Checks if the folder represented by the given path exists and contains a valid vault structure.
@param pathToVault A directory path
@param masterkeyFilename Name of the masterkey file
@return <code>true</code> if the directory seems to contain a vault.
@since 1.1.0 | [
"Checks",
"if",
"the",
"folder",
"represented",
"by",
"the",
"given",
"path",
"exists",
"and",
"contains",
"a",
"valid",
"vault",
"structure",
"."
] | train | https://github.com/cryptomator/cryptofs/blob/67fc1a4950dd1c150cd2e2c75bcabbeb7c9ac82e/src/main/java/org/cryptomator/cryptofs/CryptoFileSystemProvider.java#L183-L187 |
NLPchina/elasticsearch-sql | src/main/java/org/nlpcn/es4sql/query/maker/AggMaker.java | AggMaker.makeCountAgg | private ValuesSourceAggregationBuilder makeCountAgg(MethodField field) {
// Cardinality is approximate DISTINCT.
if ("DISTINCT".equals(field.getOption())) {
if (field.getParams().size() == 1) {
return AggregationBuilders.cardinality(field.getAlias()).field(field.getParams().get(0).value.toString());
} else {
Integer precision_threshold = (Integer) (field.getParams().get(1).value);
return AggregationBuilders.cardinality(field.getAlias()).precisionThreshold(precision_threshold).field(field.getParams().get(0).value.toString());
}
}
String fieldName = field.getParams().get(0).value.toString();
/*
zhongshu-comment count(1) count(0)这种应该是查不到东西的,除非你的字段名就叫做1、0这样
es的count是针对某个字段做count的,见下面的dsl,对os这个字段做count
"aggregations": {
"COUNT(os)": {
"value_count": {
"field": "os"
}
}
}
假如你是写count(*),那es-sql就帮你转成对"_index"字段做count,每一条数据都会有"_index"字段,该字段存储的是索引的名字
*/
// In case of count(*) we use '_index' as field parameter to count all documents
if ("*".equals(fieldName)) {
KVValue kvValue = new KVValue(null, "_index");
field.getParams().set(0, kvValue);
/*
zhongshu-comment 这个看起来有点多此一举:先将"_index"字符串封装到KVValue中,然后再kv.toString()得到"_index"字符串,还不如直接将"_index"传进去AggregationBuilders.count(field.getAlias()).field("_index");
其实目的是为了改变形参MethodField field的params参数中的值,由"*"改为"_index"
*/
return AggregationBuilders.count(field.getAlias()).field(kvValue.toString());
} else {
return AggregationBuilders.count(field.getAlias()).field(fieldName);
}
} | java | private ValuesSourceAggregationBuilder makeCountAgg(MethodField field) {
// Cardinality is approximate DISTINCT.
if ("DISTINCT".equals(field.getOption())) {
if (field.getParams().size() == 1) {
return AggregationBuilders.cardinality(field.getAlias()).field(field.getParams().get(0).value.toString());
} else {
Integer precision_threshold = (Integer) (field.getParams().get(1).value);
return AggregationBuilders.cardinality(field.getAlias()).precisionThreshold(precision_threshold).field(field.getParams().get(0).value.toString());
}
}
String fieldName = field.getParams().get(0).value.toString();
/*
zhongshu-comment count(1) count(0)这种应该是查不到东西的,除非你的字段名就叫做1、0这样
es的count是针对某个字段做count的,见下面的dsl,对os这个字段做count
"aggregations": {
"COUNT(os)": {
"value_count": {
"field": "os"
}
}
}
假如你是写count(*),那es-sql就帮你转成对"_index"字段做count,每一条数据都会有"_index"字段,该字段存储的是索引的名字
*/
// In case of count(*) we use '_index' as field parameter to count all documents
if ("*".equals(fieldName)) {
KVValue kvValue = new KVValue(null, "_index");
field.getParams().set(0, kvValue);
/*
zhongshu-comment 这个看起来有点多此一举:先将"_index"字符串封装到KVValue中,然后再kv.toString()得到"_index"字符串,还不如直接将"_index"传进去AggregationBuilders.count(field.getAlias()).field("_index");
其实目的是为了改变形参MethodField field的params参数中的值,由"*"改为"_index"
*/
return AggregationBuilders.count(field.getAlias()).field(kvValue.toString());
} else {
return AggregationBuilders.count(field.getAlias()).field(fieldName);
}
} | [
"private",
"ValuesSourceAggregationBuilder",
"makeCountAgg",
"(",
"MethodField",
"field",
")",
"{",
"// Cardinality is approximate DISTINCT.",
"if",
"(",
"\"DISTINCT\"",
".",
"equals",
"(",
"field",
".",
"getOption",
"(",
")",
")",
")",
"{",
"if",
"(",
"field",
".... | Create count aggregation.
@param field The count function
@return AggregationBuilder use to count result | [
"Create",
"count",
"aggregation",
"."
] | train | https://github.com/NLPchina/elasticsearch-sql/blob/eaab70b4bf1729978911b83eb96e816ebcfe6e7f/src/main/java/org/nlpcn/es4sql/query/maker/AggMaker.java#L686-L727 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/thumbnail/ThumbnailRenderer.java | ThumbnailRenderer.encodeBegin | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
Thumbnail thumbnail = (Thumbnail) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = thumbnail.getClientId();
Tooltip.generateTooltip(context, thumbnail, rw);
beginResponsiveWrapper(component, rw);
rw.startElement("div", thumbnail);
rw.writeAttribute("id", clientId, "id");
Tooltip.generateTooltip(context, thumbnail, rw);
String style = thumbnail.getStyle();
if (null != style) {
rw.writeAttribute("style", style, null);
}
String styleClass = thumbnail.getStyleClass();
if (null == styleClass)
styleClass = "thumbnail";
else
styleClass = "thumbnail " + styleClass;
rw.writeAttribute("class", styleClass, "class");
} | java | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
Thumbnail thumbnail = (Thumbnail) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = thumbnail.getClientId();
Tooltip.generateTooltip(context, thumbnail, rw);
beginResponsiveWrapper(component, rw);
rw.startElement("div", thumbnail);
rw.writeAttribute("id", clientId, "id");
Tooltip.generateTooltip(context, thumbnail, rw);
String style = thumbnail.getStyle();
if (null != style) {
rw.writeAttribute("style", style, null);
}
String styleClass = thumbnail.getStyleClass();
if (null == styleClass)
styleClass = "thumbnail";
else
styleClass = "thumbnail " + styleClass;
rw.writeAttribute("class", styleClass, "class");
} | [
"@",
"Override",
"public",
"void",
"encodeBegin",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"Thumbnail",
"thumbn... | This methods generates the HTML code of the current b:thumbnail.
<code>encodeBegin</code> generates the start of the component. After the, the JSF framework calls <code>encodeChildren()</code>
to generate the HTML code between the beginning and the end of the component. For instance, in the case of a panel component
the content of the panel is generated by <code>encodeChildren()</code>. After that, <code>encodeEnd()</code> is called
to generate the rest of the HTML code.
@param context the FacesContext.
@param component the current b:thumbnail.
@throws IOException thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"thumbnail",
".",
"<code",
">",
"encodeBegin<",
"/",
"code",
">",
"generates",
"the",
"start",
"of",
"the",
"component",
".",
"After",
"the",
"the",
"JSF",
"framework"... | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/thumbnail/ThumbnailRenderer.java#L45-L72 |
ArcBees/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/MousePlugin.java | MousePlugin.mouseUp | protected boolean mouseUp(Element element, GqEvent event) {
unbindOtherEvents();
if (started) {
started = false;
preventClickEvent = event.getCurrentEventTarget() == startEvent.getCurrentEventTarget();
mouseStop(element, event);
}
return true;
} | java | protected boolean mouseUp(Element element, GqEvent event) {
unbindOtherEvents();
if (started) {
started = false;
preventClickEvent = event.getCurrentEventTarget() == startEvent.getCurrentEventTarget();
mouseStop(element, event);
}
return true;
} | [
"protected",
"boolean",
"mouseUp",
"(",
"Element",
"element",
",",
"GqEvent",
"event",
")",
"{",
"unbindOtherEvents",
"(",
")",
";",
"if",
"(",
"started",
")",
"{",
"started",
"=",
"false",
";",
"preventClickEvent",
"=",
"event",
".",
"getCurrentEventTarget",
... | Method called when mouse is released..
You should not override this method. Instead, override {@link #mouseStop(Element, GqEvent)}
method. | [
"Method",
"called",
"when",
"mouse",
"is",
"released",
".."
] | train | https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/MousePlugin.java#L204-L214 |
spring-projects/spring-boot | spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptor.java | LombokPropertyDescriptor.hasLombokPublicAccessor | private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env,
boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION
: LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(),
annotation);
if (lombokMethodAnnotationOnField != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnField);
}
AnnotationMirror lombokMethodAnnotationOnElement = env
.getAnnotation(getOwnerElement(), annotation);
if (lombokMethodAnnotationOnElement != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnElement);
}
return (env.getAnnotation(getOwnerElement(), LOMBOK_DATA_ANNOTATION) != null);
} | java | private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env,
boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION
: LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(),
annotation);
if (lombokMethodAnnotationOnField != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnField);
}
AnnotationMirror lombokMethodAnnotationOnElement = env
.getAnnotation(getOwnerElement(), annotation);
if (lombokMethodAnnotationOnElement != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnElement);
}
return (env.getAnnotation(getOwnerElement(), LOMBOK_DATA_ANNOTATION) != null);
} | [
"private",
"boolean",
"hasLombokPublicAccessor",
"(",
"MetadataGenerationEnvironment",
"env",
",",
"boolean",
"getter",
")",
"{",
"String",
"annotation",
"=",
"(",
"getter",
"?",
"LOMBOK_GETTER_ANNOTATION",
":",
"LOMBOK_SETTER_ANNOTATION",
")",
";",
"AnnotationMirror",
... | Determine if the current {@link #getField() field} defines a public accessor using
lombok annotations.
@param env the {@link MetadataGenerationEnvironment}
@param getter {@code true} to look for the read accessor, {@code false} for the
write accessor
@return {@code true} if this field has a public accessor of the specified type | [
"Determine",
"if",
"the",
"current",
"{"
] | train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptor.java#L96-L111 |
ReactiveX/RxJavaComputationExpressions | src/main/java/rx/Statement.java | Statement.switchCase | public static <K, R> Observable<R> switchCase(Func0<? extends K> caseSelector,
Map<? super K, ? extends Observable<? extends R>> mapOfCases) {
return switchCase(caseSelector, mapOfCases, Observable.<R> empty());
} | java | public static <K, R> Observable<R> switchCase(Func0<? extends K> caseSelector,
Map<? super K, ? extends Observable<? extends R>> mapOfCases) {
return switchCase(caseSelector, mapOfCases, Observable.<R> empty());
} | [
"public",
"static",
"<",
"K",
",",
"R",
">",
"Observable",
"<",
"R",
">",
"switchCase",
"(",
"Func0",
"<",
"?",
"extends",
"K",
">",
"caseSelector",
",",
"Map",
"<",
"?",
"super",
"K",
",",
"?",
"extends",
"Observable",
"<",
"?",
"extends",
"R",
">... | Return a particular one of several possible Observables based on a case
selector.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchCase.png" alt="">
@param <K>
the case key type
@param <R>
the result value type
@param caseSelector
the function that produces a case key when an
Observer subscribes
@param mapOfCases
a map that maps a case key to an Observable
@return a particular Observable chosen by key from the map of
Observables, or an empty Observable if no Observable matches the
key | [
"Return",
"a",
"particular",
"one",
"of",
"several",
"possible",
"Observables",
"based",
"on",
"a",
"case",
"selector",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"... | train | https://github.com/ReactiveX/RxJavaComputationExpressions/blob/f9d04ab762223b36fad47402ac36ce7969320d69/src/main/java/rx/Statement.java#L49-L52 |
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor | SurveyorCore/src/main/java/org/wwarn/surveyor/client/core/SortedCellTable.java | SortedCellTable.setComparator | public void setComparator(Column<T, ?> column, Comparator<T> comparator) {
columnSortHandler.setComparator(column, comparator);
} | java | public void setComparator(Column<T, ?> column, Comparator<T> comparator) {
columnSortHandler.setComparator(column, comparator);
} | [
"public",
"void",
"setComparator",
"(",
"Column",
"<",
"T",
",",
"?",
">",
"column",
",",
"Comparator",
"<",
"T",
">",
"comparator",
")",
"{",
"columnSortHandler",
".",
"setComparator",
"(",
"column",
",",
"comparator",
")",
";",
"}"
] | Sets a comparator to use when sorting the given column
@param column
@param comparator | [
"Sets",
"a",
"comparator",
"to",
"use",
"when",
"sorting",
"the",
"given",
"column"
] | train | https://github.com/WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor/blob/224280bcd6e8045bda6b673584caf0aea5e4c841/SurveyorCore/src/main/java/org/wwarn/surveyor/client/core/SortedCellTable.java#L174-L176 |
elki-project/elki | elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java | DBIDUtil.randomSample | public static ModifiableDBIDs randomSample(DBIDs source, int k, Random random) {
if(k < 0 || k > source.size()) {
throw new IllegalArgumentException("Illegal value for size of random sample: " + k + " > " + source.size() + " or < 0");
}
// Fast, and we're single-threaded here anyway.
random = (random != null) ? random : new FastNonThreadsafeRandom();
// TODO: better balancing for different sizes
// Two methods: constructive vs. destructive
if(k < source.size() >> 2) {
ArrayDBIDs aids = DBIDUtil.ensureArray(source);
DBIDArrayIter iter = aids.iter();
final int size = aids.size();
HashSetModifiableDBIDs sample = DBIDUtil.newHashSet(k);
while(sample.size() < k) {
sample.add(iter.seek(random.nextInt(size)));
}
return sample;
}
else {
ArrayModifiableDBIDs sample = DBIDUtil.newArray(source);
randomShuffle(sample, random, k);
// Delete trailing elements
for(int i = sample.size() - 1; i >= k; i--) {
sample.remove(i);
}
return sample;
}
} | java | public static ModifiableDBIDs randomSample(DBIDs source, int k, Random random) {
if(k < 0 || k > source.size()) {
throw new IllegalArgumentException("Illegal value for size of random sample: " + k + " > " + source.size() + " or < 0");
}
// Fast, and we're single-threaded here anyway.
random = (random != null) ? random : new FastNonThreadsafeRandom();
// TODO: better balancing for different sizes
// Two methods: constructive vs. destructive
if(k < source.size() >> 2) {
ArrayDBIDs aids = DBIDUtil.ensureArray(source);
DBIDArrayIter iter = aids.iter();
final int size = aids.size();
HashSetModifiableDBIDs sample = DBIDUtil.newHashSet(k);
while(sample.size() < k) {
sample.add(iter.seek(random.nextInt(size)));
}
return sample;
}
else {
ArrayModifiableDBIDs sample = DBIDUtil.newArray(source);
randomShuffle(sample, random, k);
// Delete trailing elements
for(int i = sample.size() - 1; i >= k; i--) {
sample.remove(i);
}
return sample;
}
} | [
"public",
"static",
"ModifiableDBIDs",
"randomSample",
"(",
"DBIDs",
"source",
",",
"int",
"k",
",",
"Random",
"random",
")",
"{",
"if",
"(",
"k",
"<",
"0",
"||",
"k",
">",
"source",
".",
"size",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentExce... | Produce a random sample of the given DBIDs.
@param source Original DBIDs, no duplicates allowed
@param k k Parameter
@param random Random generator
@return new DBIDs | [
"Produce",
"a",
"random",
"sample",
"of",
"the",
"given",
"DBIDs",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L598-L626 |
imsweb/naaccr-xml | src/main/java/com/imsweb/naaccrxml/NaaccrXmlDictionaryUtils.java | NaaccrXmlDictionaryUtils.writeDictionaryToCsv | public static void writeDictionaryToCsv(NaaccrDictionary dictionary, File file) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.US_ASCII))) {
writer.write("NAACCR XML ID,NAACCR Number,Name,Start Column,Length,Record Types,Parent XML Element,Data Type");
writer.newLine();
dictionary.getItems().stream()
.sorted(Comparator.comparing(NaaccrDictionaryItem::getNaaccrId))
.forEach(item -> {
try {
writer.write(item.getNaaccrId());
writer.write(",");
writer.write(item.getNaaccrNum() == null ? "" : item.getNaaccrNum().toString());
writer.write(",\"");
writer.write(item.getNaaccrName() == null ? "" : item.getNaaccrName());
writer.write("\",");
writer.write(item.getStartColumn() == null ? "" : item.getStartColumn().toString());
writer.write(",");
writer.write(item.getLength().toString());
writer.write(",\"");
writer.write(item.getRecordTypes() == null ? "" : item.getRecordTypes());
writer.write("\",");
writer.write(item.getParentXmlElement() == null ? "" : item.getParentXmlElement());
writer.write(",");
writer.write(item.getDataType() == null ? NaaccrXmlDictionaryUtils.NAACCR_DATA_TYPE_TEXT : item.getDataType());
writer.newLine();
}
catch (IOException | RuntimeException ex1) {
throw new RuntimeException(ex1); // doing that to make sure the loop is broken...
}
});
}
catch (RuntimeException ex2) {
throw new IOException(ex2);
}
} | java | public static void writeDictionaryToCsv(NaaccrDictionary dictionary, File file) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.US_ASCII))) {
writer.write("NAACCR XML ID,NAACCR Number,Name,Start Column,Length,Record Types,Parent XML Element,Data Type");
writer.newLine();
dictionary.getItems().stream()
.sorted(Comparator.comparing(NaaccrDictionaryItem::getNaaccrId))
.forEach(item -> {
try {
writer.write(item.getNaaccrId());
writer.write(",");
writer.write(item.getNaaccrNum() == null ? "" : item.getNaaccrNum().toString());
writer.write(",\"");
writer.write(item.getNaaccrName() == null ? "" : item.getNaaccrName());
writer.write("\",");
writer.write(item.getStartColumn() == null ? "" : item.getStartColumn().toString());
writer.write(",");
writer.write(item.getLength().toString());
writer.write(",\"");
writer.write(item.getRecordTypes() == null ? "" : item.getRecordTypes());
writer.write("\",");
writer.write(item.getParentXmlElement() == null ? "" : item.getParentXmlElement());
writer.write(",");
writer.write(item.getDataType() == null ? NaaccrXmlDictionaryUtils.NAACCR_DATA_TYPE_TEXT : item.getDataType());
writer.newLine();
}
catch (IOException | RuntimeException ex1) {
throw new RuntimeException(ex1); // doing that to make sure the loop is broken...
}
});
}
catch (RuntimeException ex2) {
throw new IOException(ex2);
}
} | [
"public",
"static",
"void",
"writeDictionaryToCsv",
"(",
"NaaccrDictionary",
"dictionary",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"try",
"(",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
"... | Write the given dictionary to the give target file using the CSV format.
<br/><br/>
Columns:
<ol>
<li>NAACCR ID</li>
<li>NAACCR number</li>
<li>Name</li>
<li>Start Column</li>
<li>Length</li>
<li>Record Types</li>
<li>Parent XML Element</li>
<li>Data Type</li>
</ol>
@param dictionary dictionary to write
@param file target CSV file | [
"Write",
"the",
"given",
"dictionary",
"to",
"the",
"give",
"target",
"file",
"using",
"the",
"CSV",
"format",
".",
"<br",
"/",
">",
"<br",
"/",
">",
"Columns",
":",
"<ol",
">",
"<li",
">",
"NAACCR",
"ID<",
"/",
"li",
">",
"<li",
">",
"NAACCR",
"nu... | train | https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/NaaccrXmlDictionaryUtils.java#L732-L765 |
zxing/zxing | android/src/com/google/zxing/client/android/camera/CameraManager.java | CameraManager.buildLuminanceSource | public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview();
if (rect == null) {
return null;
}
// Go ahead and assume it's YUV rather than die.
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height(), false);
} | java | public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRectInPreview();
if (rect == null) {
return null;
}
// Go ahead and assume it's YUV rather than die.
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height(), false);
} | [
"public",
"PlanarYUVLuminanceSource",
"buildLuminanceSource",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"Rect",
"rect",
"=",
"getFramingRectInPreview",
"(",
")",
";",
"if",
"(",
"rect",
"==",
"null",
")",
"{",
"ret... | A factory method to build the appropriate LuminanceSource object based on the format
of the preview buffers, as described by Camera.Parameters.
@param data A preview frame.
@param width The width of the image.
@param height The height of the image.
@return A PlanarYUVLuminanceSource instance. | [
"A",
"factory",
"method",
"to",
"build",
"the",
"appropriate",
"LuminanceSource",
"object",
"based",
"on",
"the",
"format",
"of",
"the",
"preview",
"buffers",
"as",
"described",
"by",
"Camera",
".",
"Parameters",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/android/src/com/google/zxing/client/android/camera/CameraManager.java#L321-L329 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/SchedulerForType.java | SchedulerForType.addSession | public void addSession(String id, Session session) {
poolGroupManager.addSession(id, session);
LOG.info("Session " + id +
" has been added to " + type + " scheduler");
} | java | public void addSession(String id, Session session) {
poolGroupManager.addSession(id, session);
LOG.info("Session " + id +
" has been added to " + type + " scheduler");
} | [
"public",
"void",
"addSession",
"(",
"String",
"id",
",",
"Session",
"session",
")",
"{",
"poolGroupManager",
".",
"addSession",
"(",
"id",
",",
"session",
")",
";",
"LOG",
".",
"info",
"(",
"\"Session \"",
"+",
"id",
"+",
"\" has been added to \"",
"+",
"... | Add a session to this scheduler.
@param id The session ID.
@param session The session. | [
"Add",
"a",
"session",
"to",
"this",
"scheduler",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/SchedulerForType.java#L784-L788 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java | JobContext.setTaskOutputDir | private void setTaskOutputDir() {
if (this.jobState.contains(ConfigurationKeys.WRITER_OUTPUT_DIR)) {
LOG.warn(String.format("Property %s is deprecated. No need to use it if %s is specified.",
ConfigurationKeys.WRITER_OUTPUT_DIR, ConfigurationKeys.TASK_DATA_ROOT_DIR_KEY));
} else {
String workingDir = this.jobState.getProp(ConfigurationKeys.TASK_DATA_ROOT_DIR_KEY);
this.jobState.setProp(ConfigurationKeys.WRITER_OUTPUT_DIR, new Path(workingDir, TASK_OUTPUT_DIR_NAME).toString());
LOG.info(String
.format("Writer Output Directory is set to %s.", this.jobState.getProp(ConfigurationKeys.WRITER_OUTPUT_DIR)));
}
} | java | private void setTaskOutputDir() {
if (this.jobState.contains(ConfigurationKeys.WRITER_OUTPUT_DIR)) {
LOG.warn(String.format("Property %s is deprecated. No need to use it if %s is specified.",
ConfigurationKeys.WRITER_OUTPUT_DIR, ConfigurationKeys.TASK_DATA_ROOT_DIR_KEY));
} else {
String workingDir = this.jobState.getProp(ConfigurationKeys.TASK_DATA_ROOT_DIR_KEY);
this.jobState.setProp(ConfigurationKeys.WRITER_OUTPUT_DIR, new Path(workingDir, TASK_OUTPUT_DIR_NAME).toString());
LOG.info(String
.format("Writer Output Directory is set to %s.", this.jobState.getProp(ConfigurationKeys.WRITER_OUTPUT_DIR)));
}
} | [
"private",
"void",
"setTaskOutputDir",
"(",
")",
"{",
"if",
"(",
"this",
".",
"jobState",
".",
"contains",
"(",
"ConfigurationKeys",
".",
"WRITER_OUTPUT_DIR",
")",
")",
"{",
"LOG",
".",
"warn",
"(",
"String",
".",
"format",
"(",
"\"Property %s is deprecated. N... | If {@link ConfigurationKeys#WRITER_OUTPUT_DIR} (which is deprecated) is specified, use its value.
Otherwise, if {@link ConfigurationKeys#TASK_DATA_ROOT_DIR_KEY} is specified, use its value
plus {@link #TASK_OUTPUT_DIR_NAME}. | [
"If",
"{",
"@link",
"ConfigurationKeys#WRITER_OUTPUT_DIR",
"}",
"(",
"which",
"is",
"deprecated",
")",
"is",
"specified",
"use",
"its",
"value",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java#L364-L374 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/ie/crf/CRFBiasedClassifier.java | CRFBiasedClassifier.adjustBias | public void adjustBias(List<List<IN>> develData, Function<Double,Double> evalFunction, double low, double high) {
LineSearcher ls = new GoldenSectionLineSearch(true,1e-2,low,high);
CRFBiasedClassifierOptimizer optimizer = new CRFBiasedClassifierOptimizer(this, evalFunction);
double optVal = ls.minimize(optimizer);
int bi = featureIndex.indexOf(BIAS);
System.err.println("Class bias of "+weights[bi][0]+" reaches optimial value "+optVal);
} | java | public void adjustBias(List<List<IN>> develData, Function<Double,Double> evalFunction, double low, double high) {
LineSearcher ls = new GoldenSectionLineSearch(true,1e-2,low,high);
CRFBiasedClassifierOptimizer optimizer = new CRFBiasedClassifierOptimizer(this, evalFunction);
double optVal = ls.minimize(optimizer);
int bi = featureIndex.indexOf(BIAS);
System.err.println("Class bias of "+weights[bi][0]+" reaches optimial value "+optVal);
} | [
"public",
"void",
"adjustBias",
"(",
"List",
"<",
"List",
"<",
"IN",
">",
">",
"develData",
",",
"Function",
"<",
"Double",
",",
"Double",
">",
"evalFunction",
",",
"double",
"low",
",",
"double",
"high",
")",
"{",
"LineSearcher",
"ls",
"=",
"new",
"Go... | /*
Adjust the bias parameter to optimize some objective function.
Note that this function only tunes the bias parameter of one class
(class of index 0), and is thus only useful for binary classification
problems. | [
"/",
"*",
"Adjust",
"the",
"bias",
"parameter",
"to",
"optimize",
"some",
"objective",
"function",
".",
"Note",
"that",
"this",
"function",
"only",
"tunes",
"the",
"bias",
"parameter",
"of",
"one",
"class",
"(",
"class",
"of",
"index",
"0",
")",
"and",
"... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/crf/CRFBiasedClassifier.java#L132-L138 |
wildfly/wildfly-build-tools | provisioning/src/main/java/org/wildfly/build/util/ZipFileSubsystemInputStreamSources.java | ZipFileSubsystemInputStreamSources.addSubsystemFileSource | public void addSubsystemFileSource(String subsystemFileName, File zipFile, ZipEntry zipEntry) {
inputStreamSourceMap.put(subsystemFileName, new ZipEntryInputStreamSource(zipFile, zipEntry));
} | java | public void addSubsystemFileSource(String subsystemFileName, File zipFile, ZipEntry zipEntry) {
inputStreamSourceMap.put(subsystemFileName, new ZipEntryInputStreamSource(zipFile, zipEntry));
} | [
"public",
"void",
"addSubsystemFileSource",
"(",
"String",
"subsystemFileName",
",",
"File",
"zipFile",
",",
"ZipEntry",
"zipEntry",
")",
"{",
"inputStreamSourceMap",
".",
"put",
"(",
"subsystemFileName",
",",
"new",
"ZipEntryInputStreamSource",
"(",
"zipFile",
",",
... | Creates a zip entry inputstream source and maps it to the specified filename.
@param subsystemFileName
@param zipFile
@param zipEntry | [
"Creates",
"a",
"zip",
"entry",
"inputstream",
"source",
"and",
"maps",
"it",
"to",
"the",
"specified",
"filename",
"."
] | train | https://github.com/wildfly/wildfly-build-tools/blob/520a5f2e58e6a24097d63fd65c51a8fc29847a61/provisioning/src/main/java/org/wildfly/build/util/ZipFileSubsystemInputStreamSources.java#L45-L47 |
spring-projects/spring-credhub | spring-credhub-core/src/main/java/org/springframework/credhub/configuration/CredHubTemplateFactory.java | CredHubTemplateFactory.reactiveCredHubTemplate | public ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
return new ReactiveCredHubTemplate(credHubProperties, clientHttpConnector(clientOptions),
clientRegistrationRepository, authorizedClientRepository);
} | java | public ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties,
ClientOptions clientOptions,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
return new ReactiveCredHubTemplate(credHubProperties, clientHttpConnector(clientOptions),
clientRegistrationRepository, authorizedClientRepository);
} | [
"public",
"ReactiveCredHubOperations",
"reactiveCredHubTemplate",
"(",
"CredHubProperties",
"credHubProperties",
",",
"ClientOptions",
"clientOptions",
",",
"ReactiveClientRegistrationRepository",
"clientRegistrationRepository",
",",
"ServerOAuth2AuthorizedClientRepository",
"authorizedC... | Create a {@link ReactiveCredHubTemplate} for interaction with a CredHub server
using OAuth2 for authentication.
@param credHubProperties connection properties
@param clientOptions connection options
@param clientRegistrationRepository a repository of OAuth2 client registrations
@param authorizedClientRepository a repository of OAuth2 client authorizations
@return a {@code ReactiveCredHubTemplate} | [
"Create",
"a",
"{",
"@link",
"ReactiveCredHubTemplate",
"}",
"for",
"interaction",
"with",
"a",
"CredHub",
"server",
"using",
"OAuth2",
"for",
"authentication",
"."
] | train | https://github.com/spring-projects/spring-credhub/blob/4d82cfa60d6c04e707ff32d78bc5d80cff4e132e/spring-credhub-core/src/main/java/org/springframework/credhub/configuration/CredHubTemplateFactory.java#L91-L97 |
wildfly/wildfly-core | platform-mbean/src/main/java/org/jboss/as/platform/mbean/PlatformMBeanUtil.java | PlatformMBeanUtil.getDetypedThreadInfo | public static ModelNode getDetypedThreadInfo(final ThreadInfo threadInfo, boolean includeBlockedTime) {
final ModelNode result = new ModelNode();
result.get(PlatformMBeanConstants.THREAD_ID).set(threadInfo.getThreadId());
result.get(PlatformMBeanConstants.THREAD_NAME).set(threadInfo.getThreadName());
result.get(PlatformMBeanConstants.THREAD_STATE).set(threadInfo.getThreadState().name());
if (includeBlockedTime) {
result.get(PlatformMBeanConstants.BLOCKED_TIME).set(threadInfo.getBlockedTime());
} else {
result.get(PlatformMBeanConstants.BLOCKED_TIME);
}
result.get(PlatformMBeanConstants.BLOCKED_COUNT).set(threadInfo.getBlockedCount());
result.get(PlatformMBeanConstants.WAITED_TIME).set(threadInfo.getWaitedTime());
result.get(PlatformMBeanConstants.WAITED_COUNT).set(threadInfo.getWaitedCount());
result.get(PlatformMBeanConstants.LOCK_INFO).set(getDetypedLockInfo(threadInfo.getLockInfo()));
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_NAME), threadInfo.getLockName());
result.get(PlatformMBeanConstants.LOCK_OWNER_ID).set(threadInfo.getLockOwnerId());
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_OWNER_NAME), threadInfo.getLockOwnerName());
final ModelNode stack = result.get(PlatformMBeanConstants.STACK_TRACE);
stack.setEmptyList();
for (StackTraceElement ste : threadInfo.getStackTrace()) {
stack.add(getDetypedStackTraceElement(ste));
}
result.get(PlatformMBeanConstants.SUSPENDED).set(threadInfo.isSuspended());
result.get(PlatformMBeanConstants.IN_NATIVE).set(threadInfo.isInNative());
final ModelNode monitors = result.get(PlatformMBeanConstants.LOCKED_MONITORS);
monitors.setEmptyList();
for (MonitorInfo monitor : threadInfo.getLockedMonitors()) {
monitors.add(getDetypedMonitorInfo(monitor));
}
final ModelNode synchronizers = result.get(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS);
synchronizers.setEmptyList();
for (LockInfo lock : threadInfo.getLockedSynchronizers()) {
synchronizers.add(getDetypedLockInfo(lock));
}
return result;
} | java | public static ModelNode getDetypedThreadInfo(final ThreadInfo threadInfo, boolean includeBlockedTime) {
final ModelNode result = new ModelNode();
result.get(PlatformMBeanConstants.THREAD_ID).set(threadInfo.getThreadId());
result.get(PlatformMBeanConstants.THREAD_NAME).set(threadInfo.getThreadName());
result.get(PlatformMBeanConstants.THREAD_STATE).set(threadInfo.getThreadState().name());
if (includeBlockedTime) {
result.get(PlatformMBeanConstants.BLOCKED_TIME).set(threadInfo.getBlockedTime());
} else {
result.get(PlatformMBeanConstants.BLOCKED_TIME);
}
result.get(PlatformMBeanConstants.BLOCKED_COUNT).set(threadInfo.getBlockedCount());
result.get(PlatformMBeanConstants.WAITED_TIME).set(threadInfo.getWaitedTime());
result.get(PlatformMBeanConstants.WAITED_COUNT).set(threadInfo.getWaitedCount());
result.get(PlatformMBeanConstants.LOCK_INFO).set(getDetypedLockInfo(threadInfo.getLockInfo()));
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_NAME), threadInfo.getLockName());
result.get(PlatformMBeanConstants.LOCK_OWNER_ID).set(threadInfo.getLockOwnerId());
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_OWNER_NAME), threadInfo.getLockOwnerName());
final ModelNode stack = result.get(PlatformMBeanConstants.STACK_TRACE);
stack.setEmptyList();
for (StackTraceElement ste : threadInfo.getStackTrace()) {
stack.add(getDetypedStackTraceElement(ste));
}
result.get(PlatformMBeanConstants.SUSPENDED).set(threadInfo.isSuspended());
result.get(PlatformMBeanConstants.IN_NATIVE).set(threadInfo.isInNative());
final ModelNode monitors = result.get(PlatformMBeanConstants.LOCKED_MONITORS);
monitors.setEmptyList();
for (MonitorInfo monitor : threadInfo.getLockedMonitors()) {
monitors.add(getDetypedMonitorInfo(monitor));
}
final ModelNode synchronizers = result.get(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS);
synchronizers.setEmptyList();
for (LockInfo lock : threadInfo.getLockedSynchronizers()) {
synchronizers.add(getDetypedLockInfo(lock));
}
return result;
} | [
"public",
"static",
"ModelNode",
"getDetypedThreadInfo",
"(",
"final",
"ThreadInfo",
"threadInfo",
",",
"boolean",
"includeBlockedTime",
")",
"{",
"final",
"ModelNode",
"result",
"=",
"new",
"ModelNode",
"(",
")",
";",
"result",
".",
"get",
"(",
"PlatformMBeanCons... | Utility for converting {@link java.lang.management.ThreadInfo} to a detyped form.
@param threadInfo the thread information data object
@param includeBlockedTime whether the {@link PlatformMBeanConstants#BLOCKED_TIME} attribute is supported
@return the detyped representation | [
"Utility",
"for",
"converting",
"{",
"@link",
"java",
".",
"lang",
".",
"management",
".",
"ThreadInfo",
"}",
"to",
"a",
"detyped",
"form",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/platform-mbean/src/main/java/org/jboss/as/platform/mbean/PlatformMBeanUtil.java#L129-L166 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/FormatUtilities.java | FormatUtilities.getDateTime | static public long getDateTime(String s, String format)
{
return getDateTime(s, format, true, false);
} | java | static public long getDateTime(String s, String format)
{
return getDateTime(s, format, true, false);
} | [
"static",
"public",
"long",
"getDateTime",
"(",
"String",
"s",
",",
"String",
"format",
")",
"{",
"return",
"getDateTime",
"(",
"s",
",",
"format",
",",
"true",
",",
"false",
")",
";",
"}"
] | Returns the given date parsed using the given format.
@param s The formatted date to be parsed
@param format The format to use when parsing the date
@return The given date parsed using the given format | [
"Returns",
"the",
"given",
"date",
"parsed",
"using",
"the",
"given",
"format",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/FormatUtilities.java#L248-L251 |
googleapis/google-http-java-client | google-http-client/src/main/java/com/google/api/client/json/JsonParser.java | JsonParser.parseAndClose | @Beta
public final <T> T parseAndClose(Class<T> destinationClass, CustomizeJsonParser customizeParser)
throws IOException {
try {
return parse(destinationClass, customizeParser);
} finally {
close();
}
} | java | @Beta
public final <T> T parseAndClose(Class<T> destinationClass, CustomizeJsonParser customizeParser)
throws IOException {
try {
return parse(destinationClass, customizeParser);
} finally {
close();
}
} | [
"@",
"Beta",
"public",
"final",
"<",
"T",
">",
"T",
"parseAndClose",
"(",
"Class",
"<",
"T",
">",
"destinationClass",
",",
"CustomizeJsonParser",
"customizeParser",
")",
"throws",
"IOException",
"{",
"try",
"{",
"return",
"parse",
"(",
"destinationClass",
",",... | {@link Beta} <br>
Parse a JSON object, array, or value into a new instance of the given destination class using
{@link JsonParser#parse(Class, CustomizeJsonParser)}, and then closes the parser.
@param <T> destination class
@param destinationClass destination class that has a public default constructor to use to
create a new instance
@param customizeParser optional parser customizer or {@code null} for none
@return new instance of the parsed destination class | [
"{",
"@link",
"Beta",
"}",
"<br",
">",
"Parse",
"a",
"JSON",
"object",
"array",
"or",
"value",
"into",
"a",
"new",
"instance",
"of",
"the",
"given",
"destination",
"class",
"using",
"{",
"@link",
"JsonParser#parse",
"(",
"Class",
"CustomizeJsonParser",
")",
... | train | https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/json/JsonParser.java#L160-L168 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernelGaussian.java | FactoryKernelGaussian.gaussian1D | public static <T extends ImageGray<T>, K extends Kernel1D>
K gaussian1D(Class<T> imageType, double sigma, int radius )
{
boolean isFloat = GeneralizedImageOps.isFloatingPoint(imageType);
int numBits = GeneralizedImageOps.getNumBits(imageType);
if( numBits < 32 )
numBits = 32;
return gaussian(1,isFloat, numBits, sigma,radius);
} | java | public static <T extends ImageGray<T>, K extends Kernel1D>
K gaussian1D(Class<T> imageType, double sigma, int radius )
{
boolean isFloat = GeneralizedImageOps.isFloatingPoint(imageType);
int numBits = GeneralizedImageOps.getNumBits(imageType);
if( numBits < 32 )
numBits = 32;
return gaussian(1,isFloat, numBits, sigma,radius);
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
",",
"K",
"extends",
"Kernel1D",
">",
"K",
"gaussian1D",
"(",
"Class",
"<",
"T",
">",
"imageType",
",",
"double",
"sigma",
",",
"int",
"radius",
")",
"{",
"boolean",
"isFloat",
"=",
... | Creates a 1D Gaussian kernel of the specified type.
@param imageType The type of image which is to be convolved by this kernel.
@param sigma The distributions stdev. If ≤ 0 then the sigma will be computed from the radius.
@param radius Number of pixels in the kernel's radius. If ≤ 0 then the sigma will be computed from the sigma.
@return The computed Gaussian kernel. | [
"Creates",
"a",
"1D",
"Gaussian",
"kernel",
"of",
"the",
"specified",
"type",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernelGaussian.java#L77-L85 |
dhemery/hartley | src/main/java/com/dhemery/expressing/Expressive.java | Expressive.assertThat | public <S> void assertThat(S subject, Ticker ticker, Feature<? super S, Boolean> feature) {
assertThat(subject, feature, ticker, isQuietlyTrue());
} | java | public <S> void assertThat(S subject, Ticker ticker, Feature<? super S, Boolean> feature) {
assertThat(subject, feature, ticker, isQuietlyTrue());
} | [
"public",
"<",
"S",
">",
"void",
"assertThat",
"(",
"S",
"subject",
",",
"Ticker",
"ticker",
",",
"Feature",
"<",
"?",
"super",
"S",
",",
"Boolean",
">",
"feature",
")",
"{",
"assertThat",
"(",
"subject",
",",
"feature",
",",
"ticker",
",",
"isQuietlyT... | Assert that a polled sample of the feature is {@code true}.
<p>Example:</p>
<pre>
{@code
Page settingsPage = ...;
Feature<Page,Boolean> displayed() { ... }
...
assertThat(settingsPage, eventually(), is(displayed()));
} | [
"Assert",
"that",
"a",
"polled",
"sample",
"of",
"the",
"feature",
"is",
"{",
"@code",
"true",
"}",
".",
"<p",
">",
"Example",
":",
"<",
"/",
"p",
">",
"<pre",
">",
"{",
"@code"
] | train | https://github.com/dhemery/hartley/blob/7754bd6bc12695f2249601b8890da530a61fcf33/src/main/java/com/dhemery/expressing/Expressive.java#L111-L113 |
overturetool/overture | core/interpreter/src/main/java/org/overture/interpreter/runtime/VdmRuntimeError.java | VdmRuntimeError.patternFail | public static Value patternFail(ValueException ve, ILexLocation location)
throws PatternMatchException
{
throw new PatternMatchException(ve.number, ve.getMessage(), location);
} | java | public static Value patternFail(ValueException ve, ILexLocation location)
throws PatternMatchException
{
throw new PatternMatchException(ve.number, ve.getMessage(), location);
} | [
"public",
"static",
"Value",
"patternFail",
"(",
"ValueException",
"ve",
",",
"ILexLocation",
"location",
")",
"throws",
"PatternMatchException",
"{",
"throw",
"new",
"PatternMatchException",
"(",
"ve",
".",
"number",
",",
"ve",
".",
"getMessage",
"(",
")",
",",... | Throw a PatternMatchException with a message from the ValueException.
@param ve
@param location
@return
@throws PatternMatchException | [
"Throw",
"a",
"PatternMatchException",
"with",
"a",
"message",
"from",
"the",
"ValueException",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/runtime/VdmRuntimeError.java#L60-L64 |
validator/validator | src/nu/validator/gnu/xml/aelfred2/XmlParser.java | XmlParser.fatal | private void fatal(String message, String textFound, String textExpected)
throws SAXException {
// smart quotes -- 2005-08-20 hsivonen
if (textFound != null) {
message = message + " (found \u201C" + textFound + "\u201D)";
}
if (textExpected != null) {
message = message + " (expected \u201C" + textExpected + "\u201D)";
}
handler.fatal(message);
// "can't happen"
throw new FatalSAXException(message);
} | java | private void fatal(String message, String textFound, String textExpected)
throws SAXException {
// smart quotes -- 2005-08-20 hsivonen
if (textFound != null) {
message = message + " (found \u201C" + textFound + "\u201D)";
}
if (textExpected != null) {
message = message + " (expected \u201C" + textExpected + "\u201D)";
}
handler.fatal(message);
// "can't happen"
throw new FatalSAXException(message);
} | [
"private",
"void",
"fatal",
"(",
"String",
"message",
",",
"String",
"textFound",
",",
"String",
"textExpected",
")",
"throws",
"SAXException",
"{",
"// smart quotes -- 2005-08-20 hsivonen",
"if",
"(",
"textFound",
"!=",
"null",
")",
"{",
"message",
"=",
"message"... | Report an error.
@param message
The error message.
@param textFound
The text that caused the error (or null).
@see SAXDriver#error
@see #line | [
"Report",
"an",
"error",
"."
] | train | https://github.com/validator/validator/blob/c7b7f85b3a364df7d9944753fb5b2cd0ce642889/src/nu/validator/gnu/xml/aelfred2/XmlParser.java#L555-L568 |
apache/incubator-druid | extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/FixedBucketsHistogram.java | FixedBucketsHistogram.fromByteBuffer | public static FixedBucketsHistogram fromByteBuffer(ByteBuffer buf)
{
byte serializationVersion = buf.get();
Preconditions.checkArgument(
serializationVersion == SERIALIZATION_VERSION,
StringUtils.format("Only serialization version %s is supported.", SERIALIZATION_VERSION)
);
byte mode = buf.get();
if (mode == FULL_ENCODING_MODE) {
return fromByteBufferFullNoSerdeHeader(buf);
} else if (mode == SPARSE_ENCODING_MODE) {
return fromBytesSparse(buf);
} else {
throw new ISE("Invalid histogram serde mode: %s", mode);
}
} | java | public static FixedBucketsHistogram fromByteBuffer(ByteBuffer buf)
{
byte serializationVersion = buf.get();
Preconditions.checkArgument(
serializationVersion == SERIALIZATION_VERSION,
StringUtils.format("Only serialization version %s is supported.", SERIALIZATION_VERSION)
);
byte mode = buf.get();
if (mode == FULL_ENCODING_MODE) {
return fromByteBufferFullNoSerdeHeader(buf);
} else if (mode == SPARSE_ENCODING_MODE) {
return fromBytesSparse(buf);
} else {
throw new ISE("Invalid histogram serde mode: %s", mode);
}
} | [
"public",
"static",
"FixedBucketsHistogram",
"fromByteBuffer",
"(",
"ByteBuffer",
"buf",
")",
"{",
"byte",
"serializationVersion",
"=",
"buf",
".",
"get",
"(",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"serializationVersion",
"==",
"SERIALIZATION_VERSION",... | Deserialization helper method
@param buf Source buffer containing serialized histogram
@return Deserialized object | [
"Deserialization",
"helper",
"method"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/FixedBucketsHistogram.java#L926-L941 |
pugwoo/nimble-orm | src/main/java/com/pugwoo/dbhelper/sql/SQLUtils.java | SQLUtils.insertWhereAndExpression | public static String insertWhereAndExpression(String whereSql, String condExpression)
throws JSQLParserException {
if(condExpression == null || condExpression.trim().isEmpty()) {
return whereSql == null ? "" : whereSql;
}
if(whereSql == null || whereSql.trim().isEmpty()) {
return "WHERE " + condExpression;
}
whereSql = whereSql.trim();
if(!whereSql.toUpperCase().startsWith("WHERE ")) {
return "WHERE " + condExpression + " " + whereSql;
}
// 为解决JSqlParse对复杂的condExpression不支持的问题,这里用替换的形式来达到目的
String magic = "A" + UUID.randomUUID().toString().replace("-", "");
String selectSql = "select * from dual "; // 辅助where sql解析用
Statement statement = CCJSqlParserUtil.parse(selectSql + whereSql);
Select selectStatement = (Select) statement;
PlainSelect plainSelect = (PlainSelect)selectStatement.getSelectBody();
Expression ce = CCJSqlParserUtil.parseCondExpression(magic);
Expression oldWhere = plainSelect.getWhere();
Expression newWhere = new FixedAndExpression(oldWhere, ce);
plainSelect.setWhere(newWhere);
String result = plainSelect.toString().substring(selectSql.length());
return result.replace(magic, condExpression);
} | java | public static String insertWhereAndExpression(String whereSql, String condExpression)
throws JSQLParserException {
if(condExpression == null || condExpression.trim().isEmpty()) {
return whereSql == null ? "" : whereSql;
}
if(whereSql == null || whereSql.trim().isEmpty()) {
return "WHERE " + condExpression;
}
whereSql = whereSql.trim();
if(!whereSql.toUpperCase().startsWith("WHERE ")) {
return "WHERE " + condExpression + " " + whereSql;
}
// 为解决JSqlParse对复杂的condExpression不支持的问题,这里用替换的形式来达到目的
String magic = "A" + UUID.randomUUID().toString().replace("-", "");
String selectSql = "select * from dual "; // 辅助where sql解析用
Statement statement = CCJSqlParserUtil.parse(selectSql + whereSql);
Select selectStatement = (Select) statement;
PlainSelect plainSelect = (PlainSelect)selectStatement.getSelectBody();
Expression ce = CCJSqlParserUtil.parseCondExpression(magic);
Expression oldWhere = plainSelect.getWhere();
Expression newWhere = new FixedAndExpression(oldWhere, ce);
plainSelect.setWhere(newWhere);
String result = plainSelect.toString().substring(selectSql.length());
return result.replace(magic, condExpression);
} | [
"public",
"static",
"String",
"insertWhereAndExpression",
"(",
"String",
"whereSql",
",",
"String",
"condExpression",
")",
"throws",
"JSQLParserException",
"{",
"if",
"(",
"condExpression",
"==",
"null",
"||",
"condExpression",
".",
"trim",
"(",
")",
".",
"isEmpty... | 往where sql里面插入AND关系的表达式。
例如:whereSql为 where a!=3 or a!=2 limit 1
condExpress为 deleted=0
那么返回:where (deleted=0 and (a!=3 or a!=2)) limit 1
@param whereSql 从where起的sql子句,如果有where必须带上where关键字。
@param condExpression 例如a=? 不带where或and关键字。
@return 注意返回字符串前面没有空格
@throws JSQLParserException | [
"往where",
"sql里面插入AND关系的表达式。"
] | train | https://github.com/pugwoo/nimble-orm/blob/dd496f3e57029e4f22f9a2f00d18a6513ef94d08/src/main/java/com/pugwoo/dbhelper/sql/SQLUtils.java#L584-L614 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/UsersInner.java | UsersInner.getAsync | public Observable<UserInner> getAsync(String resourceGroupName, String labAccountName, String labName, String userName) {
return getWithServiceResponseAsync(resourceGroupName, labAccountName, labName, userName).map(new Func1<ServiceResponse<UserInner>, UserInner>() {
@Override
public UserInner call(ServiceResponse<UserInner> response) {
return response.body();
}
});
} | java | public Observable<UserInner> getAsync(String resourceGroupName, String labAccountName, String labName, String userName) {
return getWithServiceResponseAsync(resourceGroupName, labAccountName, labName, userName).map(new Func1<ServiceResponse<UserInner>, UserInner>() {
@Override
public UserInner call(ServiceResponse<UserInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"UserInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"labAccountName",
",",
"String",
"labName",
",",
"String",
"userName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"la... | Get user.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param labName The name of the lab.
@param userName The name of the user.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the UserInner object | [
"Get",
"user",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/UsersInner.java#L416-L423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.