repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
LearnLib/automatalib | util/src/main/java/net/automatalib/util/automata/minimizer/hopcroft/HopcroftMinimization.java | HopcroftMinimization.minimizeDFA | public static <S, I, A extends DFA<S, I> & InputAlphabetHolder<I>> CompactDFA<I> minimizeDFA(A dfa) {
"""
Minimizes the given DFA. The result is returned in the form of a {@link CompactDFA}, using the input alphabet
obtained via <code>dfa.{@link InputAlphabetHolder#getInputAlphabet() getInputAlphabet()}</code>. Pruning (see
above) is performed after computing state equivalences.
@param dfa
the DFA to minimize
@return a minimized version of the specified DFA
"""
return minimizeDFA(dfa, PruningMode.PRUNE_AFTER);
} | java | public static <S, I, A extends DFA<S, I> & InputAlphabetHolder<I>> CompactDFA<I> minimizeDFA(A dfa) {
return minimizeDFA(dfa, PruningMode.PRUNE_AFTER);
} | [
"public",
"static",
"<",
"S",
",",
"I",
",",
"A",
"extends",
"DFA",
"<",
"S",
",",
"I",
">",
"&",
"InputAlphabetHolder",
"<",
"I",
">",
">",
"CompactDFA",
"<",
"I",
">",
"minimizeDFA",
"(",
"A",
"dfa",
")",
"{",
"return",
"minimizeDFA",
"(",
"dfa",... | Minimizes the given DFA. The result is returned in the form of a {@link CompactDFA}, using the input alphabet
obtained via <code>dfa.{@link InputAlphabetHolder#getInputAlphabet() getInputAlphabet()}</code>. Pruning (see
above) is performed after computing state equivalences.
@param dfa
the DFA to minimize
@return a minimized version of the specified DFA | [
"Minimizes",
"the",
"given",
"DFA",
".",
"The",
"result",
"is",
"returned",
"in",
"the",
"form",
"of",
"a",
"{",
"@link",
"CompactDFA",
"}",
"using",
"the",
"input",
"alphabet",
"obtained",
"via",
"<code",
">",
"dfa",
".",
"{",
"@link",
"InputAlphabetHolde... | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/automata/minimizer/hopcroft/HopcroftMinimization.java#L190-L192 |
strator-dev/greenpepper | greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/rpc/runner/XmlRpcRemoteRunner.java | XmlRpcRemoteRunner.getSpecificationHierarchy | public DocumentNode getSpecificationHierarchy(Repository repository, SystemUnderTest systemUnderTest)
throws GreenPepperServerException {
"""
<p>getSpecificationHierarchy.</p>
@param repository a {@link com.greenpepper.server.domain.Repository} object.
@param systemUnderTest a {@link com.greenpepper.server.domain.SystemUnderTest} object.
@return a {@link DocumentNode} object.
@throws com.greenpepper.server.GreenPepperServerException if any.
"""
return xmlRpc.getSpecificationHierarchy(repository, systemUnderTest, getIdentifier());
} | java | public DocumentNode getSpecificationHierarchy(Repository repository, SystemUnderTest systemUnderTest)
throws GreenPepperServerException
{
return xmlRpc.getSpecificationHierarchy(repository, systemUnderTest, getIdentifier());
} | [
"public",
"DocumentNode",
"getSpecificationHierarchy",
"(",
"Repository",
"repository",
",",
"SystemUnderTest",
"systemUnderTest",
")",
"throws",
"GreenPepperServerException",
"{",
"return",
"xmlRpc",
".",
"getSpecificationHierarchy",
"(",
"repository",
",",
"systemUnderTest"... | <p>getSpecificationHierarchy.</p>
@param repository a {@link com.greenpepper.server.domain.Repository} object.
@param systemUnderTest a {@link com.greenpepper.server.domain.SystemUnderTest} object.
@return a {@link DocumentNode} object.
@throws com.greenpepper.server.GreenPepperServerException if any. | [
"<p",
">",
"getSpecificationHierarchy",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/rpc/runner/XmlRpcRemoteRunner.java#L81-L85 |
codelibs/jcifs | src/main/java/jcifs/smb1/smb1/NtlmPasswordAuthentication.java | NtlmPasswordAuthentication.getUserSessionKey | void getUserSessionKey(byte[] challenge, byte[] dest, int offset) throws SmbException {
"""
Calculates the effective user session key.
@param challenge The server challenge.
@param dest The destination array in which the user session key will be
placed.
@param offset The offset in the destination array at which the
session key will start.
"""
if (hashesExternal) return;
try {
MD4 md4 = new MD4();
md4.update(password.getBytes(SmbConstants.UNI_ENCODING));
switch (LM_COMPATIBILITY) {
case 0:
case 1:
case 2:
md4.update(md4.digest());
md4.digest(dest, offset, 16);
break;
case 3:
case 4:
case 5:
if( clientChallenge == null ) {
clientChallenge = new byte[8];
RANDOM.nextBytes( clientChallenge );
}
HMACT64 hmac = new HMACT64(md4.digest());
hmac.update(username.toUpperCase().getBytes(
SmbConstants.UNI_ENCODING));
hmac.update(domain.toUpperCase().getBytes(
SmbConstants.UNI_ENCODING));
byte[] ntlmv2Hash = hmac.digest();
hmac = new HMACT64(ntlmv2Hash);
hmac.update(challenge);
hmac.update(clientChallenge);
HMACT64 userKey = new HMACT64(ntlmv2Hash);
userKey.update(hmac.digest());
userKey.digest(dest, offset, 16);
break;
default:
md4.update(md4.digest());
md4.digest(dest, offset, 16);
break;
}
} catch (Exception e) {
throw new SmbException("", e);
}
} | java | void getUserSessionKey(byte[] challenge, byte[] dest, int offset) throws SmbException {
if (hashesExternal) return;
try {
MD4 md4 = new MD4();
md4.update(password.getBytes(SmbConstants.UNI_ENCODING));
switch (LM_COMPATIBILITY) {
case 0:
case 1:
case 2:
md4.update(md4.digest());
md4.digest(dest, offset, 16);
break;
case 3:
case 4:
case 5:
if( clientChallenge == null ) {
clientChallenge = new byte[8];
RANDOM.nextBytes( clientChallenge );
}
HMACT64 hmac = new HMACT64(md4.digest());
hmac.update(username.toUpperCase().getBytes(
SmbConstants.UNI_ENCODING));
hmac.update(domain.toUpperCase().getBytes(
SmbConstants.UNI_ENCODING));
byte[] ntlmv2Hash = hmac.digest();
hmac = new HMACT64(ntlmv2Hash);
hmac.update(challenge);
hmac.update(clientChallenge);
HMACT64 userKey = new HMACT64(ntlmv2Hash);
userKey.update(hmac.digest());
userKey.digest(dest, offset, 16);
break;
default:
md4.update(md4.digest());
md4.digest(dest, offset, 16);
break;
}
} catch (Exception e) {
throw new SmbException("", e);
}
} | [
"void",
"getUserSessionKey",
"(",
"byte",
"[",
"]",
"challenge",
",",
"byte",
"[",
"]",
"dest",
",",
"int",
"offset",
")",
"throws",
"SmbException",
"{",
"if",
"(",
"hashesExternal",
")",
"return",
";",
"try",
"{",
"MD4",
"md4",
"=",
"new",
"MD4",
"(",... | Calculates the effective user session key.
@param challenge The server challenge.
@param dest The destination array in which the user session key will be
placed.
@param offset The offset in the destination array at which the
session key will start. | [
"Calculates",
"the",
"effective",
"user",
"session",
"key",
"."
] | train | https://github.com/codelibs/jcifs/blob/ac6a8ba2925648ae003ca2508aec32316065dc34/src/main/java/jcifs/smb1/smb1/NtlmPasswordAuthentication.java#L515-L556 |
liferay/com-liferay-commerce | commerce-product-type-grouped-service/src/main/java/com/liferay/commerce/product/type/grouped/service/persistence/impl/CPDefinitionGroupedEntryPersistenceImpl.java | CPDefinitionGroupedEntryPersistenceImpl.removeByUUID_G | @Override
public CPDefinitionGroupedEntry removeByUUID_G(String uuid, long groupId)
throws NoSuchCPDefinitionGroupedEntryException {
"""
Removes the cp definition grouped entry where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the cp definition grouped entry that was removed
"""
CPDefinitionGroupedEntry cpDefinitionGroupedEntry = findByUUID_G(uuid,
groupId);
return remove(cpDefinitionGroupedEntry);
} | java | @Override
public CPDefinitionGroupedEntry removeByUUID_G(String uuid, long groupId)
throws NoSuchCPDefinitionGroupedEntryException {
CPDefinitionGroupedEntry cpDefinitionGroupedEntry = findByUUID_G(uuid,
groupId);
return remove(cpDefinitionGroupedEntry);
} | [
"@",
"Override",
"public",
"CPDefinitionGroupedEntry",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchCPDefinitionGroupedEntryException",
"{",
"CPDefinitionGroupedEntry",
"cpDefinitionGroupedEntry",
"=",
"findByUUID_G",
"(",
"uuid",
"... | Removes the cp definition grouped entry where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the cp definition grouped entry that was removed | [
"Removes",
"the",
"cp",
"definition",
"grouped",
"entry",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-type-grouped-service/src/main/java/com/liferay/commerce/product/type/grouped/service/persistence/impl/CPDefinitionGroupedEntryPersistenceImpl.java#L817-L824 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java | StyleUtils.createMarkerOptions | public static MarkerOptions createMarkerOptions(IconRow icon, float density, IconCache iconCache) {
"""
Create new marker options populated with the icon
@param icon icon row
@param density display density: {@link android.util.DisplayMetrics#density}
@param iconCache icon cache
@return marker options populated with the icon
"""
MarkerOptions markerOptions = new MarkerOptions();
setIcon(markerOptions, icon, density, iconCache);
return markerOptions;
} | java | public static MarkerOptions createMarkerOptions(IconRow icon, float density, IconCache iconCache) {
MarkerOptions markerOptions = new MarkerOptions();
setIcon(markerOptions, icon, density, iconCache);
return markerOptions;
} | [
"public",
"static",
"MarkerOptions",
"createMarkerOptions",
"(",
"IconRow",
"icon",
",",
"float",
"density",
",",
"IconCache",
"iconCache",
")",
"{",
"MarkerOptions",
"markerOptions",
"=",
"new",
"MarkerOptions",
"(",
")",
";",
"setIcon",
"(",
"markerOptions",
","... | Create new marker options populated with the icon
@param icon icon row
@param density display density: {@link android.util.DisplayMetrics#density}
@param iconCache icon cache
@return marker options populated with the icon | [
"Create",
"new",
"marker",
"options",
"populated",
"with",
"the",
"icon"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L235-L241 |
micronaut-projects/micronaut-core | router/src/main/java/io/micronaut/web/router/DefaultRouteBuilder.java | DefaultRouteBuilder.buildRoute | protected UriRoute buildRoute(HttpMethod httpMethod, String uri, Class<?> type, String method, Class... parameterTypes) {
"""
Build a route.
@param httpMethod The HTTP method
@param uri The URI
@param type The type
@param method The method
@param parameterTypes Parameters
@return an {@link UriRoute}
"""
Optional<? extends MethodExecutionHandle<?, Object>> executionHandle = executionHandleLocator.findExecutionHandle(type, method, parameterTypes);
MethodExecutionHandle<?, Object> executableHandle = executionHandle.orElseThrow(() ->
new RoutingException("No such route: " + type.getName() + "." + method)
);
return buildRoute(httpMethod, uri, executableHandle);
} | java | protected UriRoute buildRoute(HttpMethod httpMethod, String uri, Class<?> type, String method, Class... parameterTypes) {
Optional<? extends MethodExecutionHandle<?, Object>> executionHandle = executionHandleLocator.findExecutionHandle(type, method, parameterTypes);
MethodExecutionHandle<?, Object> executableHandle = executionHandle.orElseThrow(() ->
new RoutingException("No such route: " + type.getName() + "." + method)
);
return buildRoute(httpMethod, uri, executableHandle);
} | [
"protected",
"UriRoute",
"buildRoute",
"(",
"HttpMethod",
"httpMethod",
",",
"String",
"uri",
",",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"method",
",",
"Class",
"...",
"parameterTypes",
")",
"{",
"Optional",
"<",
"?",
"extends",
"MethodExecutionHandle... | Build a route.
@param httpMethod The HTTP method
@param uri The URI
@param type The type
@param method The method
@param parameterTypes Parameters
@return an {@link UriRoute} | [
"Build",
"a",
"route",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/router/src/main/java/io/micronaut/web/router/DefaultRouteBuilder.java#L376-L384 |
timehop/sticky-headers-recyclerview | library/src/main/java/com/timehop/stickyheadersrecyclerview/rendering/HeaderRenderer.java | HeaderRenderer.drawHeader | public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) {
"""
Draws a header to a canvas, offsetting by some x and y amount
@param recyclerView the parent recycler view for drawing the header into
@param canvas the canvas on which to draw the header
@param header the view to draw as the header
@param offset a Rect used to define the x/y offset of the header. Specify x/y offset by setting
the {@link Rect#left} and {@link Rect#top} properties, respectively.
"""
canvas.save();
if (recyclerView.getLayoutManager().getClipToPadding()) {
// Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding
initClipRectForHeader(mTempRect, recyclerView, header);
canvas.clipRect(mTempRect);
}
canvas.translate(offset.left, offset.top);
header.draw(canvas);
canvas.restore();
} | java | public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) {
canvas.save();
if (recyclerView.getLayoutManager().getClipToPadding()) {
// Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding
initClipRectForHeader(mTempRect, recyclerView, header);
canvas.clipRect(mTempRect);
}
canvas.translate(offset.left, offset.top);
header.draw(canvas);
canvas.restore();
} | [
"public",
"void",
"drawHeader",
"(",
"RecyclerView",
"recyclerView",
",",
"Canvas",
"canvas",
",",
"View",
"header",
",",
"Rect",
"offset",
")",
"{",
"canvas",
".",
"save",
"(",
")",
";",
"if",
"(",
"recyclerView",
".",
"getLayoutManager",
"(",
")",
".",
... | Draws a header to a canvas, offsetting by some x and y amount
@param recyclerView the parent recycler view for drawing the header into
@param canvas the canvas on which to draw the header
@param header the view to draw as the header
@param offset a Rect used to define the x/y offset of the header. Specify x/y offset by setting
the {@link Rect#left} and {@link Rect#top} properties, respectively. | [
"Draws",
"a",
"header",
"to",
"a",
"canvas",
"offsetting",
"by",
"some",
"x",
"and",
"y",
"amount"
] | train | https://github.com/timehop/sticky-headers-recyclerview/blob/f5a9e9b8f5d96734e20439b0a41381865fa52fb7/library/src/main/java/com/timehop/stickyheadersrecyclerview/rendering/HeaderRenderer.java#L45-L58 |
JCTools/JCTools | jctools-build/src/main/java/org/jctools/queues/atomic/JavaParsingAtomicQueueGenerator.java | JavaParsingAtomicQueueGenerator.fieldDeclarationWithInitialiser | protected FieldDeclaration fieldDeclarationWithInitialiser(Type type, String name, Expression initializer,
Modifier... modifiers) {
"""
Generates something like
<code>private static final AtomicLongFieldUpdater<MpmcAtomicArrayQueueProducerIndexField> P_INDEX_UPDATER = AtomicLongFieldUpdater.newUpdater(MpmcAtomicArrayQueueProducerIndexField.class, "producerIndex");</code>
@param type
@param name
@param initializer
@param modifiers
@return
"""
FieldDeclaration fieldDeclaration = new FieldDeclaration();
VariableDeclarator variable = new VariableDeclarator(type, name, initializer);
fieldDeclaration.getVariables().add(variable);
EnumSet<Modifier> modifierSet = EnumSet.copyOf(Arrays.asList(modifiers));
fieldDeclaration.setModifiers(modifierSet);
return fieldDeclaration;
} | java | protected FieldDeclaration fieldDeclarationWithInitialiser(Type type, String name, Expression initializer,
Modifier... modifiers) {
FieldDeclaration fieldDeclaration = new FieldDeclaration();
VariableDeclarator variable = new VariableDeclarator(type, name, initializer);
fieldDeclaration.getVariables().add(variable);
EnumSet<Modifier> modifierSet = EnumSet.copyOf(Arrays.asList(modifiers));
fieldDeclaration.setModifiers(modifierSet);
return fieldDeclaration;
} | [
"protected",
"FieldDeclaration",
"fieldDeclarationWithInitialiser",
"(",
"Type",
"type",
",",
"String",
"name",
",",
"Expression",
"initializer",
",",
"Modifier",
"...",
"modifiers",
")",
"{",
"FieldDeclaration",
"fieldDeclaration",
"=",
"new",
"FieldDeclaration",
"(",
... | Generates something like
<code>private static final AtomicLongFieldUpdater<MpmcAtomicArrayQueueProducerIndexField> P_INDEX_UPDATER = AtomicLongFieldUpdater.newUpdater(MpmcAtomicArrayQueueProducerIndexField.class, "producerIndex");</code>
@param type
@param name
@param initializer
@param modifiers
@return | [
"Generates",
"something",
"like",
"<code",
">",
"private",
"static",
"final",
"AtomicLongFieldUpdater<MpmcAtomicArrayQueueProducerIndexField",
">",
"P_INDEX_UPDATER",
"=",
"AtomicLongFieldUpdater",
".",
"newUpdater",
"(",
"MpmcAtomicArrayQueueProducerIndexField",
".",
"class",
... | train | https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-build/src/main/java/org/jctools/queues/atomic/JavaParsingAtomicQueueGenerator.java#L229-L237 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormatSymbols.java | DateFormatSymbols.setWeekdays | public void setWeekdays(String[] newWeekdays, int context, int width) {
"""
Sets weekday strings. For example: "Sunday", "Monday", etc.
@param newWeekdays The new weekday strings.
@param context The formatting context, FORMAT or STANDALONE.
@param width The width of the strings,
either WIDE, ABBREVIATED, SHORT, or NARROW.
"""
switch (context) {
case FORMAT :
switch(width) {
case WIDE :
weekdays = duplicate(newWeekdays);
break;
case ABBREVIATED :
shortWeekdays = duplicate(newWeekdays);
break;
case SHORT :
shorterWeekdays = duplicate(newWeekdays);
break;
case NARROW :
narrowWeekdays = duplicate(newWeekdays);
break;
}
break;
case STANDALONE :
switch(width) {
case WIDE :
standaloneWeekdays = duplicate(newWeekdays);
break;
case ABBREVIATED :
standaloneShortWeekdays = duplicate(newWeekdays);
break;
case SHORT :
standaloneShorterWeekdays = duplicate(newWeekdays);
break;
case NARROW :
standaloneNarrowWeekdays = duplicate(newWeekdays);
break;
}
break;
}
} | java | public void setWeekdays(String[] newWeekdays, int context, int width) {
switch (context) {
case FORMAT :
switch(width) {
case WIDE :
weekdays = duplicate(newWeekdays);
break;
case ABBREVIATED :
shortWeekdays = duplicate(newWeekdays);
break;
case SHORT :
shorterWeekdays = duplicate(newWeekdays);
break;
case NARROW :
narrowWeekdays = duplicate(newWeekdays);
break;
}
break;
case STANDALONE :
switch(width) {
case WIDE :
standaloneWeekdays = duplicate(newWeekdays);
break;
case ABBREVIATED :
standaloneShortWeekdays = duplicate(newWeekdays);
break;
case SHORT :
standaloneShorterWeekdays = duplicate(newWeekdays);
break;
case NARROW :
standaloneNarrowWeekdays = duplicate(newWeekdays);
break;
}
break;
}
} | [
"public",
"void",
"setWeekdays",
"(",
"String",
"[",
"]",
"newWeekdays",
",",
"int",
"context",
",",
"int",
"width",
")",
"{",
"switch",
"(",
"context",
")",
"{",
"case",
"FORMAT",
":",
"switch",
"(",
"width",
")",
"{",
"case",
"WIDE",
":",
"weekdays",... | Sets weekday strings. For example: "Sunday", "Monday", etc.
@param newWeekdays The new weekday strings.
@param context The formatting context, FORMAT or STANDALONE.
@param width The width of the strings,
either WIDE, ABBREVIATED, SHORT, or NARROW. | [
"Sets",
"weekday",
"strings",
".",
"For",
"example",
":",
"Sunday",
"Monday",
"etc",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormatSymbols.java#L941-L976 |
eserating/siren4j | src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java | ReflectingConverter.handleTokenReplacement | private String handleTokenReplacement(String str, EntityContext context) throws Siren4JException {
"""
Helper method to do token replacement for strings.
@param str
@param context
@return
@throws Siren4JException
"""
String result = "";
// First resolve parents
result = ReflectionUtils.replaceFieldTokens(
context.getParentObject(), str, context.getParentFieldInfo(), true);
// Now resolve others
result = ReflectionUtils.flattenReservedTokens(ReflectionUtils.replaceFieldTokens(
context.getCurrentObject(), result, context.getCurrentFieldInfo(), false));
return result;
} | java | private String handleTokenReplacement(String str, EntityContext context) throws Siren4JException {
String result = "";
// First resolve parents
result = ReflectionUtils.replaceFieldTokens(
context.getParentObject(), str, context.getParentFieldInfo(), true);
// Now resolve others
result = ReflectionUtils.flattenReservedTokens(ReflectionUtils.replaceFieldTokens(
context.getCurrentObject(), result, context.getCurrentFieldInfo(), false));
return result;
} | [
"private",
"String",
"handleTokenReplacement",
"(",
"String",
"str",
",",
"EntityContext",
"context",
")",
"throws",
"Siren4JException",
"{",
"String",
"result",
"=",
"\"\"",
";",
"// First resolve parents\r",
"result",
"=",
"ReflectionUtils",
".",
"replaceFieldTokens",... | Helper method to do token replacement for strings.
@param str
@param context
@return
@throws Siren4JException | [
"Helper",
"method",
"to",
"do",
"token",
"replacement",
"for",
"strings",
"."
] | train | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L542-L551 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/Sketches.java | Sketches.getLowerBound | public static double getLowerBound(final int numStdDev, final Memory srcMem) {
"""
Gets the approximate lower error bound from a valid memory image of a Sketch
given the specified number of Standard Deviations.
This will return getEstimate() if isEmpty() is true.
@param numStdDev
<a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a>
@param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@return the lower bound.
"""
return Sketch.lowerBound(getRetainedEntries(srcMem), getThetaLong(srcMem), numStdDev, getEmpty(srcMem));
} | java | public static double getLowerBound(final int numStdDev, final Memory srcMem) {
return Sketch.lowerBound(getRetainedEntries(srcMem), getThetaLong(srcMem), numStdDev, getEmpty(srcMem));
} | [
"public",
"static",
"double",
"getLowerBound",
"(",
"final",
"int",
"numStdDev",
",",
"final",
"Memory",
"srcMem",
")",
"{",
"return",
"Sketch",
".",
"lowerBound",
"(",
"getRetainedEntries",
"(",
"srcMem",
")",
",",
"getThetaLong",
"(",
"srcMem",
")",
",",
"... | Gets the approximate lower error bound from a valid memory image of a Sketch
given the specified number of Standard Deviations.
This will return getEstimate() if isEmpty() is true.
@param numStdDev
<a href="{@docRoot}/resources/dictionary.html#numStdDev">See Number of Standard Deviations</a>
@param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@return the lower bound. | [
"Gets",
"the",
"approximate",
"lower",
"error",
"bound",
"from",
"a",
"valid",
"memory",
"image",
"of",
"a",
"Sketch",
"given",
"the",
"specified",
"number",
"of",
"Standard",
"Deviations",
".",
"This",
"will",
"return",
"getEstimate",
"()",
"if",
"isEmpty",
... | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/Sketches.java#L310-L312 |
dashorst/wicket-stuff-markup-validator | isorelax/src/main/java/org/iso_relax/verifier/VerifierFactory.java | VerifierFactory.newVerifier | public Verifier newVerifier(InputStream stream)
throws VerifierConfigurationException, SAXException, IOException {
"""
parses a schema from the specified InputStream and returns a Verifier object
that validates documents by using that schema.
"""
return compileSchema( stream, null ).newVerifier();
} | java | public Verifier newVerifier(InputStream stream)
throws VerifierConfigurationException, SAXException, IOException {
return compileSchema( stream, null ).newVerifier();
} | [
"public",
"Verifier",
"newVerifier",
"(",
"InputStream",
"stream",
")",
"throws",
"VerifierConfigurationException",
",",
"SAXException",
",",
"IOException",
"{",
"return",
"compileSchema",
"(",
"stream",
",",
"null",
")",
".",
"newVerifier",
"(",
")",
";",
"}"
] | parses a schema from the specified InputStream and returns a Verifier object
that validates documents by using that schema. | [
"parses",
"a",
"schema",
"from",
"the",
"specified",
"InputStream",
"and",
"returns",
"a",
"Verifier",
"object",
"that",
"validates",
"documents",
"by",
"using",
"that",
"schema",
"."
] | train | https://github.com/dashorst/wicket-stuff-markup-validator/blob/9e529a4dc8bfdbbe4c794f3132ef400a006560a1/isorelax/src/main/java/org/iso_relax/verifier/VerifierFactory.java#L64-L68 |
osglworks/java-tool | src/main/java/org/osgl/Lang.java | F1.compose | public <X1, X2, X3> F3<X1, X2, X3, R>
compose(final Func3<? super X1, ? super X2, ? super X3, ? extends P1> before) {
"""
Returns an {@code F3<X1, X2, X3, R>>} function by composing the specified
{@code Func3<X1, X2, X3, P1>} function with this function applied last
@param <X1>
the type of first param the new function applied to
@param <X2>
the type of second param the new function applied to
@param <X3>
the type of third param the new function applied to
@param before
the function to be applied first when applying the return function
@return an new function such that f(x1, x2, x3) == apply(f1(x1, x2, x3))
"""
final F1<P1, R> me = this;
return new F3<X1, X2, X3, R>() {
@Override
public R apply(X1 x1, X2 x2, X3 x3) {
return me.apply(before.apply(x1, x2, x3));
}
};
} | java | public <X1, X2, X3> F3<X1, X2, X3, R>
compose(final Func3<? super X1, ? super X2, ? super X3, ? extends P1> before) {
final F1<P1, R> me = this;
return new F3<X1, X2, X3, R>() {
@Override
public R apply(X1 x1, X2 x2, X3 x3) {
return me.apply(before.apply(x1, x2, x3));
}
};
} | [
"public",
"<",
"X1",
",",
"X2",
",",
"X3",
">",
"F3",
"<",
"X1",
",",
"X2",
",",
"X3",
",",
"R",
">",
"compose",
"(",
"final",
"Func3",
"<",
"?",
"super",
"X1",
",",
"?",
"super",
"X2",
",",
"?",
"super",
"X3",
",",
"?",
"extends",
"P1",
">... | Returns an {@code F3<X1, X2, X3, R>>} function by composing the specified
{@code Func3<X1, X2, X3, P1>} function with this function applied last
@param <X1>
the type of first param the new function applied to
@param <X2>
the type of second param the new function applied to
@param <X3>
the type of third param the new function applied to
@param before
the function to be applied first when applying the return function
@return an new function such that f(x1, x2, x3) == apply(f1(x1, x2, x3)) | [
"Returns",
"an",
"{",
"@code",
"F3<",
";",
"X1",
"X2",
"X3",
"R>",
";",
">",
"}",
"function",
"by",
"composing",
"the",
"specified",
"{",
"@code",
"Func3<X1",
"X2",
"X3",
"P1>",
";",
"}",
"function",
"with",
"this",
"function",
"applied",
"last"
... | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/Lang.java#L701-L710 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_easyHunting_serviceName_sound_soundId_GET | public OvhOvhPabxSound billingAccount_easyHunting_serviceName_sound_soundId_GET(String billingAccount, String serviceName, Long soundId) throws IOException {
"""
Get this object properties
REST: GET /telephony/{billingAccount}/easyHunting/{serviceName}/sound/{soundId}
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
@param soundId [required]
"""
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/sound/{soundId}";
StringBuilder sb = path(qPath, billingAccount, serviceName, soundId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOvhPabxSound.class);
} | java | public OvhOvhPabxSound billingAccount_easyHunting_serviceName_sound_soundId_GET(String billingAccount, String serviceName, Long soundId) throws IOException {
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/sound/{soundId}";
StringBuilder sb = path(qPath, billingAccount, serviceName, soundId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOvhPabxSound.class);
} | [
"public",
"OvhOvhPabxSound",
"billingAccount_easyHunting_serviceName_sound_soundId_GET",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"Long",
"soundId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/easyHunting/... | Get this object properties
REST: GET /telephony/{billingAccount}/easyHunting/{serviceName}/sound/{soundId}
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
@param soundId [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L2213-L2218 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/message/HttpCarbonMessage.java | HttpCarbonMessage.setHeader | public void setHeader(String key, Object value) {
"""
Set the header value for the given name.
@param key header name.
@param value header value as object.
"""
this.httpMessage.headers().set(key, value);
} | java | public void setHeader(String key, Object value) {
this.httpMessage.headers().set(key, value);
} | [
"public",
"void",
"setHeader",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"this",
".",
"httpMessage",
".",
"headers",
"(",
")",
".",
"set",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Set the header value for the given name.
@param key header name.
@param value header value as object. | [
"Set",
"the",
"header",
"value",
"for",
"the",
"given",
"name",
"."
] | train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/message/HttpCarbonMessage.java#L228-L230 |
Hygieia/Hygieia | collectors/build/bamboo/src/main/java/com/capitalone/dashboard/collector/DefaultBambooClient.java | DefaultBambooClient.addChangeSets | private void addChangeSets(Build build, JSONObject buildJson) {
"""
Grabs changeset information for the given build.
@param build a Build
@param buildJson the build JSON object
"""
JSONObject changeSet = (JSONObject) buildJson.get("changes");
// Map<String, String> revisionToUrl = new HashMap<>();
// // Build a map of revision to module (scm url). This is not always
// // provided by the Bamboo API, but we can use it if available.
// for (Object revision : getJsonArray(changeSet, "revisions")) {
// JSONObject json = (JSONObject) revision;
// revisionToUrl.put(json.get("revision").toString(), getString(json, "module"));
// }
for (Object item : getJsonArray(changeSet, "change")) {
JSONObject jsonItem = (JSONObject) item;
SCM scm = new SCM();
scm.setScmAuthor(getString(jsonItem, "author"));
scm.setScmCommitLog(getString(jsonItem, "comment"));
scm.setScmCommitTimestamp(getCommitTimestamp(jsonItem));
scm.setScmRevisionNumber(getRevision(jsonItem));
scm.setScmUrl(getString(jsonItem,"commitUrl"));
scm.setNumberOfChanges(getJsonArray((JSONObject)jsonItem.get("files"), "file").size());
build.getSourceChangeSet().add(scm);
}
} | java | private void addChangeSets(Build build, JSONObject buildJson) {
JSONObject changeSet = (JSONObject) buildJson.get("changes");
// Map<String, String> revisionToUrl = new HashMap<>();
// // Build a map of revision to module (scm url). This is not always
// // provided by the Bamboo API, but we can use it if available.
// for (Object revision : getJsonArray(changeSet, "revisions")) {
// JSONObject json = (JSONObject) revision;
// revisionToUrl.put(json.get("revision").toString(), getString(json, "module"));
// }
for (Object item : getJsonArray(changeSet, "change")) {
JSONObject jsonItem = (JSONObject) item;
SCM scm = new SCM();
scm.setScmAuthor(getString(jsonItem, "author"));
scm.setScmCommitLog(getString(jsonItem, "comment"));
scm.setScmCommitTimestamp(getCommitTimestamp(jsonItem));
scm.setScmRevisionNumber(getRevision(jsonItem));
scm.setScmUrl(getString(jsonItem,"commitUrl"));
scm.setNumberOfChanges(getJsonArray((JSONObject)jsonItem.get("files"), "file").size());
build.getSourceChangeSet().add(scm);
}
} | [
"private",
"void",
"addChangeSets",
"(",
"Build",
"build",
",",
"JSONObject",
"buildJson",
")",
"{",
"JSONObject",
"changeSet",
"=",
"(",
"JSONObject",
")",
"buildJson",
".",
"get",
"(",
"\"changes\"",
")",
";",
"// Map<String, String> revisionToUrl = new HashM... | Grabs changeset information for the given build.
@param build a Build
@param buildJson the build JSON object | [
"Grabs",
"changeset",
"information",
"for",
"the",
"given",
"build",
"."
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/build/bamboo/src/main/java/com/capitalone/dashboard/collector/DefaultBambooClient.java#L275-L298 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPUtility.java | MPPUtility.decodeBuffer | public static final void decodeBuffer(byte[] data, byte encryptionCode) {
"""
This method decodes a byte array with the given encryption code
using XOR encryption.
@param data Source data
@param encryptionCode Encryption code
"""
for (int i = 0; i < data.length; i++)
{
data[i] = (byte) (data[i] ^ encryptionCode);
}
} | java | public static final void decodeBuffer(byte[] data, byte encryptionCode)
{
for (int i = 0; i < data.length; i++)
{
data[i] = (byte) (data[i] ^ encryptionCode);
}
} | [
"public",
"static",
"final",
"void",
"decodeBuffer",
"(",
"byte",
"[",
"]",
"data",
",",
"byte",
"encryptionCode",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"data",
"[",
"i",
"]",
... | This method decodes a byte array with the given encryption code
using XOR encryption.
@param data Source data
@param encryptionCode Encryption code | [
"This",
"method",
"decodes",
"a",
"byte",
"array",
"with",
"the",
"given",
"encryption",
"code",
"using",
"XOR",
"encryption",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L64-L70 |
lucee/Lucee | core/src/main/java/lucee/transformer/library/function/FunctionLibFactory.java | FunctionLibFactory.copyFunctions | private static void copyFunctions(FunctionLib extFL, FunctionLib newFL) {
"""
copy function from one FunctionLib to a other
@param extFL
@param newFL
"""
Iterator<Entry<String, FunctionLibFunction>> it = extFL.getFunctions().entrySet().iterator();
FunctionLibFunction flf;
while (it.hasNext()) {
flf = it.next().getValue(); // TODO function must be duplicated because it gets a new FunctionLib assigned
newFL.setFunction(flf);
}
} | java | private static void copyFunctions(FunctionLib extFL, FunctionLib newFL) {
Iterator<Entry<String, FunctionLibFunction>> it = extFL.getFunctions().entrySet().iterator();
FunctionLibFunction flf;
while (it.hasNext()) {
flf = it.next().getValue(); // TODO function must be duplicated because it gets a new FunctionLib assigned
newFL.setFunction(flf);
}
} | [
"private",
"static",
"void",
"copyFunctions",
"(",
"FunctionLib",
"extFL",
",",
"FunctionLib",
"newFL",
")",
"{",
"Iterator",
"<",
"Entry",
"<",
"String",
",",
"FunctionLibFunction",
">",
">",
"it",
"=",
"extFL",
".",
"getFunctions",
"(",
")",
".",
"entrySet... | copy function from one FunctionLib to a other
@param extFL
@param newFL | [
"copy",
"function",
"from",
"one",
"FunctionLib",
"to",
"a",
"other"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/library/function/FunctionLibFactory.java#L463-L470 |
TestFX/Monocle | src/main/java/com/sun/glass/ui/monocle/TouchState.java | TouchState.setPoint | void setPoint(int index, Point p) {
"""
Replaces the touch point data at the given index with the given touch
point data
@param index the index at which to change the touch point data
@param p the data to copy to the given index.
"""
if (index >= pointCount) {
throw new IndexOutOfBoundsException();
}
p.copyTo(points[index]);
} | java | void setPoint(int index, Point p) {
if (index >= pointCount) {
throw new IndexOutOfBoundsException();
}
p.copyTo(points[index]);
} | [
"void",
"setPoint",
"(",
"int",
"index",
",",
"Point",
"p",
")",
"{",
"if",
"(",
"index",
">=",
"pointCount",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"p",
".",
"copyTo",
"(",
"points",
"[",
"index",
"]",
")",
";",
... | Replaces the touch point data at the given index with the given touch
point data
@param index the index at which to change the touch point data
@param p the data to copy to the given index. | [
"Replaces",
"the",
"touch",
"point",
"data",
"at",
"the",
"given",
"index",
"with",
"the",
"given",
"touch",
"point",
"data"
] | train | https://github.com/TestFX/Monocle/blob/267ccba8889cab244bf8c562dbaa0345a612874c/src/main/java/com/sun/glass/ui/monocle/TouchState.java#L209-L214 |
GerdHolz/TOVAL | src/de/invation/code/toval/misc/FormatUtils.java | FormatUtils.getFormat | public static String getFormat(Object o, int precision) {
"""
Returns an appropriate format for the given object, considering the
specified precision in case the object is a non-integer number.<br>
<ul>
<li>case 1: object is of type <code>Float</code> or <code>Double</code>
-> float format with the specified precision</li>
<li>case 2: object is a whole number -> integer format</li>
<li>case 3: object is of any other type -> string format</li>
</ul>
@param o
Object for which a format has to be assigned
@param precision
Desired precision
@return An appropriate format for the given object
"""
if (o instanceof Double || o instanceof Float)
return getFloatFormat(precision);
if (o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof Byte)
return INTEGER_FORMAT;
return STRING_FORMAT;
} | java | public static String getFormat(Object o, int precision) {
if (o instanceof Double || o instanceof Float)
return getFloatFormat(precision);
if (o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof Byte)
return INTEGER_FORMAT;
return STRING_FORMAT;
} | [
"public",
"static",
"String",
"getFormat",
"(",
"Object",
"o",
",",
"int",
"precision",
")",
"{",
"if",
"(",
"o",
"instanceof",
"Double",
"||",
"o",
"instanceof",
"Float",
")",
"return",
"getFloatFormat",
"(",
"precision",
")",
";",
"if",
"(",
"o",
"inst... | Returns an appropriate format for the given object, considering the
specified precision in case the object is a non-integer number.<br>
<ul>
<li>case 1: object is of type <code>Float</code> or <code>Double</code>
-> float format with the specified precision</li>
<li>case 2: object is a whole number -> integer format</li>
<li>case 3: object is of any other type -> string format</li>
</ul>
@param o
Object for which a format has to be assigned
@param precision
Desired precision
@return An appropriate format for the given object | [
"Returns",
"an",
"appropriate",
"format",
"for",
"the",
"given",
"object",
"considering",
"the",
"specified",
"precision",
"in",
"case",
"the",
"object",
"is",
"a",
"non",
"-",
"integer",
"number",
".",
"<br",
">",
"<ul",
">",
"<li",
">",
"case",
"1",
":... | train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/misc/FormatUtils.java#L166-L172 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric_ca/sdk/HFCAClient.java | HFCAClient.getHFCACertificates | public HFCACertificateResponse getHFCACertificates(User registrar, HFCACertificateRequest req) throws HFCACertificateException {
"""
Gets all certificates that the registrar is allowed to see and based on filter parameters that
are part of the certificate request.
@param registrar The identity of the registrar (i.e. who is performing the registration).
@param req The certificate request that contains filter parameters
@return HFCACertificateResponse object
@throws HFCACertificateException Failed to process get certificate request
"""
try {
logger.debug(format("certificate url: %s, registrar: %s", HFCA_CERTIFICATE, registrar.getName()));
JsonObject result = httpGet(HFCA_CERTIFICATE, registrar, req.getQueryParameters());
int statusCode = result.getInt("statusCode");
Collection<HFCACredential> certs = new ArrayList<>();
if (statusCode < 400) {
JsonArray certificates = result.getJsonArray("certs");
if (certificates != null && !certificates.isEmpty()) {
for (int i = 0; i < certificates.size(); i++) {
String certPEM = certificates.getJsonObject(i).getString("PEM");
certs.add(new HFCAX509Certificate(certPEM));
}
}
logger.debug(format("certificate url: %s, registrar: %s done.", HFCA_CERTIFICATE, registrar));
}
return new HFCACertificateResponse(statusCode, certs);
} catch (HTTPException e) {
String msg = format("[Code: %d] - Error while getting certificates from url '%s': %s", e.getStatusCode(), HFCA_CERTIFICATE, e.getMessage());
HFCACertificateException certificateException = new HFCACertificateException(msg, e);
logger.error(msg);
throw certificateException;
} catch (Exception e) {
String msg = format("Error while getting certificates from url '%s': %s", HFCA_CERTIFICATE, e.getMessage());
HFCACertificateException certificateException = new HFCACertificateException(msg, e);
logger.error(msg);
throw certificateException;
}
} | java | public HFCACertificateResponse getHFCACertificates(User registrar, HFCACertificateRequest req) throws HFCACertificateException {
try {
logger.debug(format("certificate url: %s, registrar: %s", HFCA_CERTIFICATE, registrar.getName()));
JsonObject result = httpGet(HFCA_CERTIFICATE, registrar, req.getQueryParameters());
int statusCode = result.getInt("statusCode");
Collection<HFCACredential> certs = new ArrayList<>();
if (statusCode < 400) {
JsonArray certificates = result.getJsonArray("certs");
if (certificates != null && !certificates.isEmpty()) {
for (int i = 0; i < certificates.size(); i++) {
String certPEM = certificates.getJsonObject(i).getString("PEM");
certs.add(new HFCAX509Certificate(certPEM));
}
}
logger.debug(format("certificate url: %s, registrar: %s done.", HFCA_CERTIFICATE, registrar));
}
return new HFCACertificateResponse(statusCode, certs);
} catch (HTTPException e) {
String msg = format("[Code: %d] - Error while getting certificates from url '%s': %s", e.getStatusCode(), HFCA_CERTIFICATE, e.getMessage());
HFCACertificateException certificateException = new HFCACertificateException(msg, e);
logger.error(msg);
throw certificateException;
} catch (Exception e) {
String msg = format("Error while getting certificates from url '%s': %s", HFCA_CERTIFICATE, e.getMessage());
HFCACertificateException certificateException = new HFCACertificateException(msg, e);
logger.error(msg);
throw certificateException;
}
} | [
"public",
"HFCACertificateResponse",
"getHFCACertificates",
"(",
"User",
"registrar",
",",
"HFCACertificateRequest",
"req",
")",
"throws",
"HFCACertificateException",
"{",
"try",
"{",
"logger",
".",
"debug",
"(",
"format",
"(",
"\"certificate url: %s, registrar: %s\"",
",... | Gets all certificates that the registrar is allowed to see and based on filter parameters that
are part of the certificate request.
@param registrar The identity of the registrar (i.e. who is performing the registration).
@param req The certificate request that contains filter parameters
@return HFCACertificateResponse object
@throws HFCACertificateException Failed to process get certificate request | [
"Gets",
"all",
"certificates",
"that",
"the",
"registrar",
"is",
"allowed",
"to",
"see",
"and",
"based",
"on",
"filter",
"parameters",
"that",
"are",
"part",
"of",
"the",
"certificate",
"request",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric_ca/sdk/HFCAClient.java#L1224-L1254 |
opendatatrentino/s-match | src/main/java/it/unitn/disi/common/utils/ClassFactory.java | ClassFactory.getClassInstance | @SuppressWarnings("unchecked")
public static Object getClassInstance(String className,
Class[] attrTypes,
Object[] attrValues) throws DISIException {
"""
Creates an instance of the class whose name is passed as the parameter.
@param className name of the class those instance is to be created
@param attrTypes attrTypes
@param attrValues attrValues
@return instance of the class
@throws DISIException DISIException
"""
Constructor constr;
try {
Class cl = Class.forName(className);
constr = cl.getConstructor(attrTypes);
} catch (ClassNotFoundException e) {
//yep, log and throw...
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
} catch (NoSuchMethodException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
}
Object classInst;
try {
classInst = constr.newInstance(attrValues);
} catch (InstantiationException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
} catch (IllegalAccessException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
} catch (InvocationTargetException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
}
return classInst;
} | java | @SuppressWarnings("unchecked")
public static Object getClassInstance(String className,
Class[] attrTypes,
Object[] attrValues) throws DISIException {
Constructor constr;
try {
Class cl = Class.forName(className);
constr = cl.getConstructor(attrTypes);
} catch (ClassNotFoundException e) {
//yep, log and throw...
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
} catch (NoSuchMethodException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
}
Object classInst;
try {
classInst = constr.newInstance(attrValues);
} catch (InstantiationException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
} catch (IllegalAccessException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
} catch (InvocationTargetException e) {
final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage();
log.error(errMessage, e);
throw new DISIException(errMessage, e);
}
return classInst;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"Object",
"getClassInstance",
"(",
"String",
"className",
",",
"Class",
"[",
"]",
"attrTypes",
",",
"Object",
"[",
"]",
"attrValues",
")",
"throws",
"DISIException",
"{",
"Constructor",
"con... | Creates an instance of the class whose name is passed as the parameter.
@param className name of the class those instance is to be created
@param attrTypes attrTypes
@param attrValues attrValues
@return instance of the class
@throws DISIException DISIException | [
"Creates",
"an",
"instance",
"of",
"the",
"class",
"whose",
"name",
"is",
"passed",
"as",
"the",
"parameter",
"."
] | train | https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/common/utils/ClassFactory.java#L59-L97 |
alkacon/opencms-core | src/org/opencms/ugc/CmsUgcConfigurationReader.java | CmsUgcConfigurationReader.getLongValue | private Optional<Long> getLongValue(String path) {
"""
Parses an optional long value.<p>
@param path the xpath of the content element
@return the optional long value in that field
"""
String stringValue = getStringValue(path);
if (stringValue == null) {
return Optional.absent();
} else {
try {
return Optional.<Long> of(Long.valueOf(stringValue.trim()));
} catch (NumberFormatException e) {
throw new NumberFormatException("Could not read a number from " + path + " ,value= " + stringValue);
}
}
} | java | private Optional<Long> getLongValue(String path) {
String stringValue = getStringValue(path);
if (stringValue == null) {
return Optional.absent();
} else {
try {
return Optional.<Long> of(Long.valueOf(stringValue.trim()));
} catch (NumberFormatException e) {
throw new NumberFormatException("Could not read a number from " + path + " ,value= " + stringValue);
}
}
} | [
"private",
"Optional",
"<",
"Long",
">",
"getLongValue",
"(",
"String",
"path",
")",
"{",
"String",
"stringValue",
"=",
"getStringValue",
"(",
"path",
")",
";",
"if",
"(",
"stringValue",
"==",
"null",
")",
"{",
"return",
"Optional",
".",
"absent",
"(",
"... | Parses an optional long value.<p>
@param path the xpath of the content element
@return the optional long value in that field | [
"Parses",
"an",
"optional",
"long",
"value",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcConfigurationReader.java#L193-L205 |
mijecu25/dsa | src/main/java/com/mijecu25/dsa/algorithms/search/logarithmic/BinarySearch.java | BinarySearch.searchDescending | public static int searchDescending(int[] intArray, int value) {
"""
Search for the value in the reverse sorted int array and return the index.
@param intArray array that we are searching in.
@param value value that is being searched in the array.
@return the index where the value is found in the array, else -1.
"""
int start = 0;
int end = intArray.length - 1;
int middle = 0;
while(start <= end) {
middle = (start + end) >> 1;
if(value == intArray[middle]) {
return middle;
}
if(value > intArray[middle]) {
end = middle - 1 ;
}
else {
start = middle + 1;
}
}
return -1;
} | java | public static int searchDescending(int[] intArray, int value) {
int start = 0;
int end = intArray.length - 1;
int middle = 0;
while(start <= end) {
middle = (start + end) >> 1;
if(value == intArray[middle]) {
return middle;
}
if(value > intArray[middle]) {
end = middle - 1 ;
}
else {
start = middle + 1;
}
}
return -1;
} | [
"public",
"static",
"int",
"searchDescending",
"(",
"int",
"[",
"]",
"intArray",
",",
"int",
"value",
")",
"{",
"int",
"start",
"=",
"0",
";",
"int",
"end",
"=",
"intArray",
".",
"length",
"-",
"1",
";",
"int",
"middle",
"=",
"0",
";",
"while",
"("... | Search for the value in the reverse sorted int array and return the index.
@param intArray array that we are searching in.
@param value value that is being searched in the array.
@return the index where the value is found in the array, else -1. | [
"Search",
"for",
"the",
"value",
"in",
"the",
"reverse",
"sorted",
"int",
"array",
"and",
"return",
"the",
"index",
"."
] | train | https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/logarithmic/BinarySearch.java#L409-L431 |
SonarSource/sonarqube | server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/RemoveUserAction.java | RemoveUserAction.ensureLastAdminIsNotRemoved | private void ensureLastAdminIsNotRemoved(DbSession dbSession, GroupDto group, UserDto user) {
"""
Ensure that there are still users with admin global permission if user is removed from the group.
"""
int remainingAdmins = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroupMember(dbSession,
group.getOrganizationUuid(), OrganizationPermission.ADMINISTER.getKey(), group.getId(), user.getId());
checkRequest(remainingAdmins > 0, "The last administrator user cannot be removed");
} | java | private void ensureLastAdminIsNotRemoved(DbSession dbSession, GroupDto group, UserDto user) {
int remainingAdmins = dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroupMember(dbSession,
group.getOrganizationUuid(), OrganizationPermission.ADMINISTER.getKey(), group.getId(), user.getId());
checkRequest(remainingAdmins > 0, "The last administrator user cannot be removed");
} | [
"private",
"void",
"ensureLastAdminIsNotRemoved",
"(",
"DbSession",
"dbSession",
",",
"GroupDto",
"group",
",",
"UserDto",
"user",
")",
"{",
"int",
"remainingAdmins",
"=",
"dbClient",
".",
"authorizationDao",
"(",
")",
".",
"countUsersWithGlobalPermissionExcludingGroupM... | Ensure that there are still users with admin global permission if user is removed from the group. | [
"Ensure",
"that",
"there",
"are",
"still",
"users",
"with",
"admin",
"global",
"permission",
"if",
"user",
"is",
"removed",
"from",
"the",
"group",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/RemoveUserAction.java#L93-L97 |
Bedework/bw-util | bw-util-misc/src/main/java/org/bedework/util/misc/Util.java | Util.compareStrings | public static int compareStrings(final String s1, final String s2) {
"""
Compare two strings. null is less than any non-null string.
@param s1 first string.
@param s2 second string.
@return int 0 if the s1 is equal to s2;
<0 if s1 is lexicographically less than s2;
>0 if s1 is lexicographically greater than s2.
"""
if (s1 == null) {
if (s2 != null) {
return -1;
}
return 0;
}
if (s2 == null) {
return 1;
}
return s1.compareTo(s2);
} | java | public static int compareStrings(final String s1, final String s2) {
if (s1 == null) {
if (s2 != null) {
return -1;
}
return 0;
}
if (s2 == null) {
return 1;
}
return s1.compareTo(s2);
} | [
"public",
"static",
"int",
"compareStrings",
"(",
"final",
"String",
"s1",
",",
"final",
"String",
"s2",
")",
"{",
"if",
"(",
"s1",
"==",
"null",
")",
"{",
"if",
"(",
"s2",
"!=",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"0",
";",... | Compare two strings. null is less than any non-null string.
@param s1 first string.
@param s2 second string.
@return int 0 if the s1 is equal to s2;
<0 if s1 is lexicographically less than s2;
>0 if s1 is lexicographically greater than s2. | [
"Compare",
"two",
"strings",
".",
"null",
"is",
"less",
"than",
"any",
"non",
"-",
"null",
"string",
"."
] | train | https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-misc/src/main/java/org/bedework/util/misc/Util.java#L643-L657 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/RouteFilterRulesInner.java | RouteFilterRulesInner.listByRouteFilterAsync | public Observable<Page<RouteFilterRuleInner>> listByRouteFilterAsync(final String resourceGroupName, final String routeFilterName) {
"""
Gets all RouteFilterRules in a route filter.
@param resourceGroupName The name of the resource group.
@param routeFilterName The name of the route filter.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RouteFilterRuleInner> object
"""
return listByRouteFilterWithServiceResponseAsync(resourceGroupName, routeFilterName)
.map(new Func1<ServiceResponse<Page<RouteFilterRuleInner>>, Page<RouteFilterRuleInner>>() {
@Override
public Page<RouteFilterRuleInner> call(ServiceResponse<Page<RouteFilterRuleInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<RouteFilterRuleInner>> listByRouteFilterAsync(final String resourceGroupName, final String routeFilterName) {
return listByRouteFilterWithServiceResponseAsync(resourceGroupName, routeFilterName)
.map(new Func1<ServiceResponse<Page<RouteFilterRuleInner>>, Page<RouteFilterRuleInner>>() {
@Override
public Page<RouteFilterRuleInner> call(ServiceResponse<Page<RouteFilterRuleInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"RouteFilterRuleInner",
">",
">",
"listByRouteFilterAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"routeFilterName",
")",
"{",
"return",
"listByRouteFilterWithServiceResponseAsync",
"(",
"resourceGro... | Gets all RouteFilterRules in a route filter.
@param resourceGroupName The name of the resource group.
@param routeFilterName The name of the route filter.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RouteFilterRuleInner> object | [
"Gets",
"all",
"RouteFilterRules",
"in",
"a",
"route",
"filter",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/RouteFilterRulesInner.java#L772-L780 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/util/bloom/RetouchedBloomFilter.java | RetouchedBloomFilter.removeKey | private void removeKey(Key k, List<Key>[] vector) {
"""
Removes a given key from <i>this</i> filer.
@param k The key to remove.
@param vector The counting vector associated to the key.
"""
if (k == null) {
throw new NullPointerException("Key can not be null");
}
if (vector == null) {
throw new NullPointerException("ArrayList<Key>[] can not be null");
}
int[] h = hash.hash(k);
hash.clear();
for (int i = 0; i < nbHash; i++) {
vector[h[i]].remove(k);
}
} | java | private void removeKey(Key k, List<Key>[] vector) {
if (k == null) {
throw new NullPointerException("Key can not be null");
}
if (vector == null) {
throw new NullPointerException("ArrayList<Key>[] can not be null");
}
int[] h = hash.hash(k);
hash.clear();
for (int i = 0; i < nbHash; i++) {
vector[h[i]].remove(k);
}
} | [
"private",
"void",
"removeKey",
"(",
"Key",
"k",
",",
"List",
"<",
"Key",
">",
"[",
"]",
"vector",
")",
"{",
"if",
"(",
"k",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Key can not be null\"",
")",
";",
"}",
"if",
"(",
"ve... | Removes a given key from <i>this</i> filer.
@param k The key to remove.
@param vector The counting vector associated to the key. | [
"Removes",
"a",
"given",
"key",
"from",
"<i",
">",
"this<",
"/",
"i",
">",
"filer",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/bloom/RetouchedBloomFilter.java#L346-L360 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/ValidationUtils.java | ValidationUtils.assertIsPositive | public static int assertIsPositive(int num, String fieldName) {
"""
Asserts that the given number is positive (non-negative and non-zero).
@param num Number to validate
@param fieldName Field name to display in exception message if not positive.
@return Number if positive.
"""
if (num <= 0) {
throw new IllegalArgumentException(String.format("%s must be positive", fieldName));
}
return num;
} | java | public static int assertIsPositive(int num, String fieldName) {
if (num <= 0) {
throw new IllegalArgumentException(String.format("%s must be positive", fieldName));
}
return num;
} | [
"public",
"static",
"int",
"assertIsPositive",
"(",
"int",
"num",
",",
"String",
"fieldName",
")",
"{",
"if",
"(",
"num",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"%s must be positive\"",
",",
"fie... | Asserts that the given number is positive (non-negative and non-zero).
@param num Number to validate
@param fieldName Field name to display in exception message if not positive.
@return Number if positive. | [
"Asserts",
"that",
"the",
"given",
"number",
"is",
"positive",
"(",
"non",
"-",
"negative",
"and",
"non",
"-",
"zero",
")",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/ValidationUtils.java#L63-L68 |
korpling/ANNIS | annis-service/src/main/java/annis/sqlgen/SaltAnnotateExtractor.java | SaltAnnotateExtractor.findOrAddSLayer | private SLayer findOrAddSLayer(String name, SDocumentGraph graph) {
"""
Retrieves an existing layer by it's name or creates and adds a new one if
not existing yet
@param name
@param graph
@return Either the old or the newly created layer
"""
List<SLayer> layerList = graph.getLayerByName(name);
SLayer layer = (layerList != null && layerList.size() > 0)
? layerList.get(0) : null;
if (layer == null)
{
layer = SaltFactory.createSLayer();
layer.setName(name);
graph.addLayer(layer);
}
return layer;
} | java | private SLayer findOrAddSLayer(String name, SDocumentGraph graph)
{
List<SLayer> layerList = graph.getLayerByName(name);
SLayer layer = (layerList != null && layerList.size() > 0)
? layerList.get(0) : null;
if (layer == null)
{
layer = SaltFactory.createSLayer();
layer.setName(name);
graph.addLayer(layer);
}
return layer;
} | [
"private",
"SLayer",
"findOrAddSLayer",
"(",
"String",
"name",
",",
"SDocumentGraph",
"graph",
")",
"{",
"List",
"<",
"SLayer",
">",
"layerList",
"=",
"graph",
".",
"getLayerByName",
"(",
"name",
")",
";",
"SLayer",
"layer",
"=",
"(",
"layerList",
"!=",
"n... | Retrieves an existing layer by it's name or creates and adds a new one if
not existing yet
@param name
@param graph
@return Either the old or the newly created layer | [
"Retrieves",
"an",
"existing",
"layer",
"by",
"it",
"s",
"name",
"or",
"creates",
"and",
"adds",
"a",
"new",
"one",
"if",
"not",
"existing",
"yet"
] | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-service/src/main/java/annis/sqlgen/SaltAnnotateExtractor.java#L1091-L1103 |
lastaflute/lastaflute | src/main/java/org/lastaflute/web/servlet/request/scoped/ScopedMessageHandler.java | ScopedMessageHandler.saveGlobal | public void saveGlobal(String messageKey, Object... args) {
"""
Save message as global user messages. (overriding existing messages) <br>
This message will be deleted immediately after display if you use e.g. la:errors.
@param messageKey The message key to be saved. (NotNull)
@param args The varying array of arguments for the message. (NullAllowed, EmptyAllowed)
"""
assertObjectNotNull("messageKey", messageKey);
doSaveInfo(prepareUserMessages(globalPropertyKey, messageKey, args));
} | java | public void saveGlobal(String messageKey, Object... args) {
assertObjectNotNull("messageKey", messageKey);
doSaveInfo(prepareUserMessages(globalPropertyKey, messageKey, args));
} | [
"public",
"void",
"saveGlobal",
"(",
"String",
"messageKey",
",",
"Object",
"...",
"args",
")",
"{",
"assertObjectNotNull",
"(",
"\"messageKey\"",
",",
"messageKey",
")",
";",
"doSaveInfo",
"(",
"prepareUserMessages",
"(",
"globalPropertyKey",
",",
"messageKey",
"... | Save message as global user messages. (overriding existing messages) <br>
This message will be deleted immediately after display if you use e.g. la:errors.
@param messageKey The message key to be saved. (NotNull)
@param args The varying array of arguments for the message. (NullAllowed, EmptyAllowed) | [
"Save",
"message",
"as",
"global",
"user",
"messages",
".",
"(",
"overriding",
"existing",
"messages",
")",
"<br",
">",
"This",
"message",
"will",
"be",
"deleted",
"immediately",
"after",
"display",
"if",
"you",
"use",
"e",
".",
"g",
".",
"la",
":",
"err... | train | https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/web/servlet/request/scoped/ScopedMessageHandler.java#L64-L67 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.eachDir | public static void eachDir(Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") Closure closure) throws IOException {
"""
Invokes the closure for each subdirectory in this directory,
ignoring regular files.
@param self a Path (that happens to be a folder/directory)
@param closure a closure (the parameter is the Path for the subdirectory file)
@throws java.io.FileNotFoundException if the given directory does not exist
@throws IllegalArgumentException if the provided Path object does not represent a directory
@see #eachFile(Path, groovy.io.FileType, groovy.lang.Closure)
@since 2.3.0
""" // throws FileNotFoundException, IllegalArgumentException {
eachFile(self, FileType.DIRECTORIES, closure);
} | java | public static void eachDir(Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException {
eachFile(self, FileType.DIRECTORIES, closure);
} | [
"public",
"static",
"void",
"eachDir",
"(",
"Path",
"self",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"SimpleType",
".",
"class",
",",
"options",
"=",
"\"java.nio.file.Path\"",
")",
"Closure",
"closure",
")",
"throws",
"IOException",
"{",
"// throws FileNotF... | Invokes the closure for each subdirectory in this directory,
ignoring regular files.
@param self a Path (that happens to be a folder/directory)
@param closure a closure (the parameter is the Path for the subdirectory file)
@throws java.io.FileNotFoundException if the given directory does not exist
@throws IllegalArgumentException if the provided Path object does not represent a directory
@see #eachFile(Path, groovy.io.FileType, groovy.lang.Closure)
@since 2.3.0 | [
"Invokes",
"the",
"closure",
"for",
"each",
"subdirectory",
"in",
"this",
"directory",
"ignoring",
"regular",
"files",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L901-L903 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java | ValueEnforcer.notNull | public static <T> T notNull (final T aValue, final String sName) {
"""
Check that the passed value is not <code>null</code>.
@param <T>
Type to be checked and returned
@param aValue
The value to check.
@param sName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws NullPointerException
if the passed value is <code>null</code>.
"""
if (isEnabled ())
if (aValue == null)
throw new NullPointerException ("The value of '" + sName + "' may not be null!");
return aValue;
} | java | public static <T> T notNull (final T aValue, final String sName)
{
if (isEnabled ())
if (aValue == null)
throw new NullPointerException ("The value of '" + sName + "' may not be null!");
return aValue;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"notNull",
"(",
"final",
"T",
"aValue",
",",
"final",
"String",
"sName",
")",
"{",
"if",
"(",
"isEnabled",
"(",
")",
")",
"if",
"(",
"aValue",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"... | Check that the passed value is not <code>null</code>.
@param <T>
Type to be checked and returned
@param aValue
The value to check.
@param sName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws NullPointerException
if the passed value is <code>null</code>. | [
"Check",
"that",
"the",
"passed",
"value",
"is",
"not",
"<code",
">",
"null<",
"/",
"code",
">",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L273-L279 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/query/impl/getters/AbstractJsonGetter.java | AbstractJsonGetter.findAttribute | private boolean findAttribute(JsonParser parser, JsonPathCursor pathCursor) throws IOException {
"""
Looks for the attribute with the given name only in current
object. If found, parser points to the value of the given
attribute when this method returns. If given path does not exist
in the current level, then parser points to matching
{@code JsonToken.END_OBJECT} of the current object.
Assumes the parser points to a {@code JsonToken.START_OBJECT}
@param parser
@param pathCursor
@return {@code true} if given attribute name exists in the current object
@throws IOException
"""
JsonToken token = parser.getCurrentToken();
if (token != JsonToken.START_OBJECT) {
return false;
}
while (true) {
token = parser.nextToken();
if (token == JsonToken.END_OBJECT) {
return false;
}
if (pathCursor.getCurrent().equals(parser.getCurrentName())) {
parser.nextToken();
return true;
} else {
parser.nextToken();
parser.skipChildren();
}
}
} | java | private boolean findAttribute(JsonParser parser, JsonPathCursor pathCursor) throws IOException {
JsonToken token = parser.getCurrentToken();
if (token != JsonToken.START_OBJECT) {
return false;
}
while (true) {
token = parser.nextToken();
if (token == JsonToken.END_OBJECT) {
return false;
}
if (pathCursor.getCurrent().equals(parser.getCurrentName())) {
parser.nextToken();
return true;
} else {
parser.nextToken();
parser.skipChildren();
}
}
} | [
"private",
"boolean",
"findAttribute",
"(",
"JsonParser",
"parser",
",",
"JsonPathCursor",
"pathCursor",
")",
"throws",
"IOException",
"{",
"JsonToken",
"token",
"=",
"parser",
".",
"getCurrentToken",
"(",
")",
";",
"if",
"(",
"token",
"!=",
"JsonToken",
".",
... | Looks for the attribute with the given name only in current
object. If found, parser points to the value of the given
attribute when this method returns. If given path does not exist
in the current level, then parser points to matching
{@code JsonToken.END_OBJECT} of the current object.
Assumes the parser points to a {@code JsonToken.START_OBJECT}
@param parser
@param pathCursor
@return {@code true} if given attribute name exists in the current object
@throws IOException | [
"Looks",
"for",
"the",
"attribute",
"with",
"the",
"given",
"name",
"only",
"in",
"current",
"object",
".",
"If",
"found",
"parser",
"points",
"to",
"the",
"value",
"of",
"the",
"given",
"attribute",
"when",
"this",
"method",
"returns",
".",
"If",
"given",... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/getters/AbstractJsonGetter.java#L211-L229 |
couchbase/java-dcp-client | src/main/java/com/couchbase/client/dcp/transport/netty/DcpConnectHandler.java | DcpConnectHandler.channelRead0 | @Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
"""
Once we get a response from the connect request, check if it is successful and complete/fail the connect
phase accordingly.
"""
ResponseStatus status = MessageUtil.getResponseStatus(msg);
if (status.isSuccess()) {
step++;
switch (step) {
case HELLO:
hello(ctx, msg);
break;
case SELECT:
select(ctx);
break;
case OPEN:
open(ctx);
break;
case REMOVE:
remove(ctx);
break;
default:
originalPromise().setFailure(new IllegalStateException("Unidentified DcpConnection step " + step));
break;
}
} else {
originalPromise().setFailure(new IllegalStateException("Could not open DCP Connection: Failed in the "
+ toString(step) + " step, response status is " + status));
}
} | java | @Override
protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
ResponseStatus status = MessageUtil.getResponseStatus(msg);
if (status.isSuccess()) {
step++;
switch (step) {
case HELLO:
hello(ctx, msg);
break;
case SELECT:
select(ctx);
break;
case OPEN:
open(ctx);
break;
case REMOVE:
remove(ctx);
break;
default:
originalPromise().setFailure(new IllegalStateException("Unidentified DcpConnection step " + step));
break;
}
} else {
originalPromise().setFailure(new IllegalStateException("Could not open DCP Connection: Failed in the "
+ toString(step) + " step, response status is " + status));
}
} | [
"@",
"Override",
"protected",
"void",
"channelRead0",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"ByteBuf",
"msg",
")",
"throws",
"Exception",
"{",
"ResponseStatus",
"status",
"=",
"MessageUtil",
".",
"getResponseStatus",
"(",
"msg",
")",
";",
"... | Once we get a response from the connect request, check if it is successful and complete/fail the connect
phase accordingly. | [
"Once",
"we",
"get",
"a",
"response",
"from",
"the",
"connect",
"request",
"check",
"if",
"it",
"is",
"successful",
"and",
"complete",
"/",
"fail",
"the",
"connect",
"phase",
"accordingly",
"."
] | train | https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/transport/netty/DcpConnectHandler.java#L132-L158 |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPageLayout.java | WebPageLayout.printSearchOutput | public void printSearchOutput(WebPage page, ChainWriter out, WebSiteRequest req, HttpServletResponse resp, String query, boolean isEntireSite, List<SearchResult> results, String[] words) throws IOException, SQLException {
"""
Prints the content HTML that shows the output of a search. This output must include an
additional search form named <code>"search_two"</code>, with two fields named
<code>"search_query"</code> and <code>"search_target"</code>.
@see WebPage#doPostWithSearch(WebSiteRequest,HttpServletResponse)
"""
startContent(out, req, resp, 1, 600);
printContentTitle(out, req, resp, "Search Results", 1);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
beginLightArea(req, resp, out, "300", true);
out.print(" <form action='' id='search_two' method='post'>\n");
req.printFormFields(out, 4);
out.print(" <table cellspacing='0' cellpadding='0'><tr><td style='white-space:nowrap'>\n"
+ " Word(s) to search for: <input type='text' size='24' name='search_query' value='").encodeXmlAttribute(query).print("' /><br />\n"
+ " Search Location: <input type='radio' name='search_target' value='entire_site'");
if(isEntireSite) out.print(" checked='checked'");
out.print(" /> Entire Site   <input type='radio' name='search_target' value='this_area'");
if(!isEntireSite) out.print(" checked='checked'");
out.print(" /> This Area<br />\n"
+ " <br />\n"
+ " <div style='text-align:center'><input type='submit' class='ao_button' value=' Search ' /></div>\n"
+ " </td></tr></table>\n"
+ " </form>\n"
);
endLightArea(req, resp, out);
endContentLine(out, req, resp, 1, false);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
if (results.isEmpty()) {
if (words.length > 0) {
out.print(
" <b>No matches found</b>\n"
);
}
} else {
beginLightArea(req, resp, out);
out.print(" <table cellspacing='0' cellpadding='0' class='aoLightRow'>\n"
+ " <tr>\n"
+ " <th style='white-space:nowrap'>% Match</th>\n"
+ " <th style='white-space:nowrap'>Title</th>\n"
+ " <th style='white-space:nowrap'> </th>\n"
+ " <th style='white-space:nowrap'>Description</th>\n"
+ " </tr>\n"
);
// Find the highest probability
float highest = results.get(0).getProbability();
// Display the results
int size = results.size();
for (int c = 0; c < size; c++) {
String rowClass= (c & 1) == 0 ? "aoLightRow":"aoDarkRow";
String linkClass = (c & 1) == 0 ? "aoDarkLink":"aoLightLink";
SearchResult result = results.get(c);
String url=result.getUrl();
String title=result.getTitle();
String description=result.getDescription();
out.print(" <tr class='").print(rowClass).print("'>\n"
+ " <td style='white-space:nowrap; text-align:center;'>").print(Math.round(99 * result.getProbability() / highest)).print("%</td>\n"
+ " <td style='white-space:nowrap'><a class='"+linkClass+"' href='").encodeXmlAttribute(resp.encodeURL(url)).print("'>").print(title.length()==0?" ":title).print("</a></td>\n"
+ " <td style='white-space:nowrap'>   </td>\n"
+ " <td style='white-space:nowrap'>").print(description.length()==0?" ":description).print("</td>\n"
+ " </tr>\n");
}
out.print(
" </table>\n"
);
endLightArea(req, resp, out);
}
endContentLine(out, req, resp, 1, false);
endContent(page, out, req, resp, 1);
} | java | public void printSearchOutput(WebPage page, ChainWriter out, WebSiteRequest req, HttpServletResponse resp, String query, boolean isEntireSite, List<SearchResult> results, String[] words) throws IOException, SQLException {
startContent(out, req, resp, 1, 600);
printContentTitle(out, req, resp, "Search Results", 1);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
beginLightArea(req, resp, out, "300", true);
out.print(" <form action='' id='search_two' method='post'>\n");
req.printFormFields(out, 4);
out.print(" <table cellspacing='0' cellpadding='0'><tr><td style='white-space:nowrap'>\n"
+ " Word(s) to search for: <input type='text' size='24' name='search_query' value='").encodeXmlAttribute(query).print("' /><br />\n"
+ " Search Location: <input type='radio' name='search_target' value='entire_site'");
if(isEntireSite) out.print(" checked='checked'");
out.print(" /> Entire Site   <input type='radio' name='search_target' value='this_area'");
if(!isEntireSite) out.print(" checked='checked'");
out.print(" /> This Area<br />\n"
+ " <br />\n"
+ " <div style='text-align:center'><input type='submit' class='ao_button' value=' Search ' /></div>\n"
+ " </td></tr></table>\n"
+ " </form>\n"
);
endLightArea(req, resp, out);
endContentLine(out, req, resp, 1, false);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
if (results.isEmpty()) {
if (words.length > 0) {
out.print(
" <b>No matches found</b>\n"
);
}
} else {
beginLightArea(req, resp, out);
out.print(" <table cellspacing='0' cellpadding='0' class='aoLightRow'>\n"
+ " <tr>\n"
+ " <th style='white-space:nowrap'>% Match</th>\n"
+ " <th style='white-space:nowrap'>Title</th>\n"
+ " <th style='white-space:nowrap'> </th>\n"
+ " <th style='white-space:nowrap'>Description</th>\n"
+ " </tr>\n"
);
// Find the highest probability
float highest = results.get(0).getProbability();
// Display the results
int size = results.size();
for (int c = 0; c < size; c++) {
String rowClass= (c & 1) == 0 ? "aoLightRow":"aoDarkRow";
String linkClass = (c & 1) == 0 ? "aoDarkLink":"aoLightLink";
SearchResult result = results.get(c);
String url=result.getUrl();
String title=result.getTitle();
String description=result.getDescription();
out.print(" <tr class='").print(rowClass).print("'>\n"
+ " <td style='white-space:nowrap; text-align:center;'>").print(Math.round(99 * result.getProbability() / highest)).print("%</td>\n"
+ " <td style='white-space:nowrap'><a class='"+linkClass+"' href='").encodeXmlAttribute(resp.encodeURL(url)).print("'>").print(title.length()==0?" ":title).print("</a></td>\n"
+ " <td style='white-space:nowrap'>   </td>\n"
+ " <td style='white-space:nowrap'>").print(description.length()==0?" ":description).print("</td>\n"
+ " </tr>\n");
}
out.print(
" </table>\n"
);
endLightArea(req, resp, out);
}
endContentLine(out, req, resp, 1, false);
endContent(page, out, req, resp, 1);
} | [
"public",
"void",
"printSearchOutput",
"(",
"WebPage",
"page",
",",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"String",
"query",
",",
"boolean",
"isEntireSite",
",",
"List",
"<",
"SearchResult",
">",
"results",
... | Prints the content HTML that shows the output of a search. This output must include an
additional search form named <code>"search_two"</code>, with two fields named
<code>"search_query"</code> and <code>"search_target"</code>.
@see WebPage#doPostWithSearch(WebSiteRequest,HttpServletResponse) | [
"Prints",
"the",
"content",
"HTML",
"that",
"shows",
"the",
"output",
"of",
"a",
"search",
".",
"This",
"output",
"must",
"include",
"an",
"additional",
"search",
"form",
"named",
"<code",
">",
"search_two",
"<",
"/",
"code",
">",
"with",
"two",
"fields",
... | train | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPageLayout.java#L93-L160 |
IanGClifton/AndroidFloatLabel | FloatLabel/src/com/iangclifton/android/floatlabel/FloatLabel.java | FloatLabel.setTextWithoutAnimation | public void setTextWithoutAnimation(int resid, TextView.BufferType type) {
"""
Sets the EditText's text without animating the label
@param resid int String resource ID
@param type TextView.BufferType
"""
mSkipAnimation = true;
mEditText.setText(resid, type);
} | java | public void setTextWithoutAnimation(int resid, TextView.BufferType type) {
mSkipAnimation = true;
mEditText.setText(resid, type);
} | [
"public",
"void",
"setTextWithoutAnimation",
"(",
"int",
"resid",
",",
"TextView",
".",
"BufferType",
"type",
")",
"{",
"mSkipAnimation",
"=",
"true",
";",
"mEditText",
".",
"setText",
"(",
"resid",
",",
"type",
")",
";",
"}"
] | Sets the EditText's text without animating the label
@param resid int String resource ID
@param type TextView.BufferType | [
"Sets",
"the",
"EditText",
"s",
"text",
"without",
"animating",
"the",
"label"
] | train | https://github.com/IanGClifton/AndroidFloatLabel/blob/b0a39c26f010f17d5f3648331e9784a41e025c0d/FloatLabel/src/com/iangclifton/android/floatlabel/FloatLabel.java#L302-L305 |
apereo/cas | support/cas-server-support-surrogate-authentication/src/main/java/org/apereo/cas/authentication/SurrogatePrincipalBuilder.java | SurrogatePrincipalBuilder.buildSurrogatePrincipal | public Principal buildSurrogatePrincipal(final String surrogate, final Principal primaryPrincipal, final Credential credentials,
final RegisteredService registeredService) {
"""
Build principal.
@param surrogate the surrogate
@param primaryPrincipal the primary principal
@param credentials the credentials
@param registeredService the registered service
@return the principal
"""
val repositories = new HashSet<String>(0);
if (registeredService != null) {
repositories.addAll(registeredService.getAttributeReleasePolicy().getPrincipalAttributesRepository().getAttributeRepositoryIds());
}
val attributes = (Map) CoreAuthenticationUtils.retrieveAttributesFromAttributeRepository(attributeRepository, surrogate, repositories);
val principal = principalFactory.createPrincipal(surrogate, attributes);
return new SurrogatePrincipal(primaryPrincipal, principal);
} | java | public Principal buildSurrogatePrincipal(final String surrogate, final Principal primaryPrincipal, final Credential credentials,
final RegisteredService registeredService) {
val repositories = new HashSet<String>(0);
if (registeredService != null) {
repositories.addAll(registeredService.getAttributeReleasePolicy().getPrincipalAttributesRepository().getAttributeRepositoryIds());
}
val attributes = (Map) CoreAuthenticationUtils.retrieveAttributesFromAttributeRepository(attributeRepository, surrogate, repositories);
val principal = principalFactory.createPrincipal(surrogate, attributes);
return new SurrogatePrincipal(primaryPrincipal, principal);
} | [
"public",
"Principal",
"buildSurrogatePrincipal",
"(",
"final",
"String",
"surrogate",
",",
"final",
"Principal",
"primaryPrincipal",
",",
"final",
"Credential",
"credentials",
",",
"final",
"RegisteredService",
"registeredService",
")",
"{",
"val",
"repositories",
"=",... | Build principal.
@param surrogate the surrogate
@param primaryPrincipal the primary principal
@param credentials the credentials
@param registeredService the registered service
@return the principal | [
"Build",
"principal",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-surrogate-authentication/src/main/java/org/apereo/cas/authentication/SurrogatePrincipalBuilder.java#L35-L44 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRPose.java | GVRPose.getLocalPosition | public void getLocalPosition(int boneindex, Vector3f pos) {
"""
Gets the local position (relative to the parent) of a bone.
<p>
All bones in the skeleton start out at the origin oriented along the bone axis (usually 0,0,1).
The pose orients and positions each bone in the skeleton with respect to this initial state.
The local bone matrix expresses the orientation and position of the bone relative
to it's parent. This function returns the translation component of that matrix.
@param boneindex zero based index of bone whose position is wanted.
@return local translation for the designated bone.
@see #setLocalRotation
@see #setWorldRotations
@see #setWorldMatrix
@see GVRSkeleton#setBoneAxis
"""
pos.x = mBones[boneindex].LocalMatrix.m30();
pos.y = mBones[boneindex].LocalMatrix.m31();
pos.z = mBones[boneindex].LocalMatrix.m32();
} | java | public void getLocalPosition(int boneindex, Vector3f pos)
{
pos.x = mBones[boneindex].LocalMatrix.m30();
pos.y = mBones[boneindex].LocalMatrix.m31();
pos.z = mBones[boneindex].LocalMatrix.m32();
} | [
"public",
"void",
"getLocalPosition",
"(",
"int",
"boneindex",
",",
"Vector3f",
"pos",
")",
"{",
"pos",
".",
"x",
"=",
"mBones",
"[",
"boneindex",
"]",
".",
"LocalMatrix",
".",
"m30",
"(",
")",
";",
"pos",
".",
"y",
"=",
"mBones",
"[",
"boneindex",
"... | Gets the local position (relative to the parent) of a bone.
<p>
All bones in the skeleton start out at the origin oriented along the bone axis (usually 0,0,1).
The pose orients and positions each bone in the skeleton with respect to this initial state.
The local bone matrix expresses the orientation and position of the bone relative
to it's parent. This function returns the translation component of that matrix.
@param boneindex zero based index of bone whose position is wanted.
@return local translation for the designated bone.
@see #setLocalRotation
@see #setWorldRotations
@see #setWorldMatrix
@see GVRSkeleton#setBoneAxis | [
"Gets",
"the",
"local",
"position",
"(",
"relative",
"to",
"the",
"parent",
")",
"of",
"a",
"bone",
".",
"<p",
">",
"All",
"bones",
"in",
"the",
"skeleton",
"start",
"out",
"at",
"the",
"origin",
"oriented",
"along",
"the",
"bone",
"axis",
"(",
"usuall... | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRPose.java#L654-L659 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java | WordVectorSerializer.readSequenceVectors | public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors(
@NonNull SequenceElementFactory<T> factory, @NonNull File file) throws IOException {
"""
This method loads previously saved SequenceVectors model from File
@param factory
@param file
@param <T>
@return
"""
return readSequenceVectors(factory, new FileInputStream(file));
} | java | public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors(
@NonNull SequenceElementFactory<T> factory, @NonNull File file) throws IOException {
return readSequenceVectors(factory, new FileInputStream(file));
} | [
"public",
"static",
"<",
"T",
"extends",
"SequenceElement",
">",
"SequenceVectors",
"<",
"T",
">",
"readSequenceVectors",
"(",
"@",
"NonNull",
"SequenceElementFactory",
"<",
"T",
">",
"factory",
",",
"@",
"NonNull",
"File",
"file",
")",
"throws",
"IOException",
... | This method loads previously saved SequenceVectors model from File
@param factory
@param file
@param <T>
@return | [
"This",
"method",
"loads",
"previously",
"saved",
"SequenceVectors",
"model",
"from",
"File"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L2122-L2125 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java | CacheManager.isTileToBeDownloaded | public boolean isTileToBeDownloaded(final ITileSource pTileSource, final long pMapTileIndex) {
"""
"Should we download this tile?", either because it's not cached yet or because it's expired
@since 5.6.5
"""
final Long expiration = mTileWriter.getExpirationTimestamp(pTileSource, pMapTileIndex);
if (expiration == null) {
return true;
}
final long now = System.currentTimeMillis();
return now > expiration;
} | java | public boolean isTileToBeDownloaded(final ITileSource pTileSource, final long pMapTileIndex) {
final Long expiration = mTileWriter.getExpirationTimestamp(pTileSource, pMapTileIndex);
if (expiration == null) {
return true;
}
final long now = System.currentTimeMillis();
return now > expiration;
} | [
"public",
"boolean",
"isTileToBeDownloaded",
"(",
"final",
"ITileSource",
"pTileSource",
",",
"final",
"long",
"pMapTileIndex",
")",
"{",
"final",
"Long",
"expiration",
"=",
"mTileWriter",
".",
"getExpirationTimestamp",
"(",
"pTileSource",
",",
"pMapTileIndex",
")",
... | "Should we download this tile?", either because it's not cached yet or because it's expired
@since 5.6.5 | [
"Should",
"we",
"download",
"this",
"tile?",
"either",
"because",
"it",
"s",
"not",
"cached",
"yet",
"or",
"because",
"it",
"s",
"expired"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java#L188-L195 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java | FastaAFPChainConverter.fastaStringToAfpChain | public static AFPChain fastaStringToAfpChain(String sequence1, String sequence2, Structure structure1,
Structure structure2) throws StructureException, CompoundNotFoundException {
"""
Returns an AFPChain corresponding to the alignment between {@code structure1} and {@code structure2}, which is given by the gapped protein sequences {@code sequence1} and {@code sequence2}. The
sequences need not correspond to the entire structures, since local alignment is performed to match the sequences to structures.
@throws StructureException
@throws CompoundNotFoundException
"""
ProteinSequence seq1 = new ProteinSequence(sequence1);
ProteinSequence seq2 = new ProteinSequence(sequence2);
return fastaToAfpChain(seq1, seq2, structure1, structure2);
} | java | public static AFPChain fastaStringToAfpChain(String sequence1, String sequence2, Structure structure1,
Structure structure2) throws StructureException, CompoundNotFoundException {
ProteinSequence seq1 = new ProteinSequence(sequence1);
ProteinSequence seq2 = new ProteinSequence(sequence2);
return fastaToAfpChain(seq1, seq2, structure1, structure2);
} | [
"public",
"static",
"AFPChain",
"fastaStringToAfpChain",
"(",
"String",
"sequence1",
",",
"String",
"sequence2",
",",
"Structure",
"structure1",
",",
"Structure",
"structure2",
")",
"throws",
"StructureException",
",",
"CompoundNotFoundException",
"{",
"ProteinSequence",
... | Returns an AFPChain corresponding to the alignment between {@code structure1} and {@code structure2}, which is given by the gapped protein sequences {@code sequence1} and {@code sequence2}. The
sequences need not correspond to the entire structures, since local alignment is performed to match the sequences to structures.
@throws StructureException
@throws CompoundNotFoundException | [
"Returns",
"an",
"AFPChain",
"corresponding",
"to",
"the",
"alignment",
"between",
"{"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java#L213-L218 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/SafeDatasetCommit.java | SafeDatasetCommit.setTaskFailureException | public static void setTaskFailureException(Collection<? extends WorkUnitState> taskStates, Throwable t) {
"""
Sets the {@link ConfigurationKeys#TASK_FAILURE_EXCEPTION_KEY} for each given {@link TaskState} to the given
{@link Throwable}.
Make this method public as this exception catching routine can be reusable in other occasions as well.
"""
for (WorkUnitState taskState : taskStates) {
((TaskState) taskState).setTaskFailureException(t);
}
} | java | public static void setTaskFailureException(Collection<? extends WorkUnitState> taskStates, Throwable t) {
for (WorkUnitState taskState : taskStates) {
((TaskState) taskState).setTaskFailureException(t);
}
} | [
"public",
"static",
"void",
"setTaskFailureException",
"(",
"Collection",
"<",
"?",
"extends",
"WorkUnitState",
">",
"taskStates",
",",
"Throwable",
"t",
")",
"{",
"for",
"(",
"WorkUnitState",
"taskState",
":",
"taskStates",
")",
"{",
"(",
"(",
"TaskState",
")... | Sets the {@link ConfigurationKeys#TASK_FAILURE_EXCEPTION_KEY} for each given {@link TaskState} to the given
{@link Throwable}.
Make this method public as this exception catching routine can be reusable in other occasions as well. | [
"Sets",
"the",
"{",
"@link",
"ConfigurationKeys#TASK_FAILURE_EXCEPTION_KEY",
"}",
"for",
"each",
"given",
"{",
"@link",
"TaskState",
"}",
"to",
"the",
"given",
"{",
"@link",
"Throwable",
"}",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/SafeDatasetCommit.java#L427-L431 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java | MathUtils.sumOfMeanDifferences | public static double sumOfMeanDifferences(double[] vector, double[] vector2) {
"""
Used for calculating top part of simple regression for
beta 1
@param vector the x coordinates
@param vector2 the y coordinates
@return the sum of mean differences for the input vectors
"""
double mean = sum(vector) / vector.length;
double mean2 = sum(vector2) / vector2.length;
double ret = 0;
for (int i = 0; i < vector.length; i++) {
double vec1Diff = vector[i] - mean;
double vec2Diff = vector2[i] - mean2;
ret += vec1Diff * vec2Diff;
}
return ret;
} | java | public static double sumOfMeanDifferences(double[] vector, double[] vector2) {
double mean = sum(vector) / vector.length;
double mean2 = sum(vector2) / vector2.length;
double ret = 0;
for (int i = 0; i < vector.length; i++) {
double vec1Diff = vector[i] - mean;
double vec2Diff = vector2[i] - mean2;
ret += vec1Diff * vec2Diff;
}
return ret;
} | [
"public",
"static",
"double",
"sumOfMeanDifferences",
"(",
"double",
"[",
"]",
"vector",
",",
"double",
"[",
"]",
"vector2",
")",
"{",
"double",
"mean",
"=",
"sum",
"(",
"vector",
")",
"/",
"vector",
".",
"length",
";",
"double",
"mean2",
"=",
"sum",
"... | Used for calculating top part of simple regression for
beta 1
@param vector the x coordinates
@param vector2 the y coordinates
@return the sum of mean differences for the input vectors | [
"Used",
"for",
"calculating",
"top",
"part",
"of",
"simple",
"regression",
"for",
"beta",
"1"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java#L474-L484 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/NotificationsApi.java | NotificationsApi.notificationsHandshakeWithHttpInfo | public ApiResponse<Void> notificationsHandshakeWithHttpInfo() throws ApiException {
"""
CometD handshake
See the [CometD documentation](https://docs.cometd.org/current/reference/#_bayeux_meta_handshake) for details.
@return ApiResponse<Void>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
com.squareup.okhttp.Call call = notificationsHandshakeValidateBeforeCall(null, null);
return apiClient.execute(call);
} | java | public ApiResponse<Void> notificationsHandshakeWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = notificationsHandshakeValidateBeforeCall(null, null);
return apiClient.execute(call);
} | [
"public",
"ApiResponse",
"<",
"Void",
">",
"notificationsHandshakeWithHttpInfo",
"(",
")",
"throws",
"ApiException",
"{",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"notificationsHandshakeValidateBeforeCall",
"(",
"null",
",",
"null",
")",
";... | CometD handshake
See the [CometD documentation](https://docs.cometd.org/current/reference/#_bayeux_meta_handshake) for details.
@return ApiResponse<Void>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"CometD",
"handshake",
"See",
"the",
"[",
"CometD",
"documentation",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"cometd",
".",
"org",
"/",
"current",
"/",
"reference",
"/",
"#_bayeux_meta_handshake",
")",
"for",
"details",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/NotificationsApi.java#L455-L458 |
google/flogger | api/src/main/java/com/google/common/flogger/backend/system/DefaultPlatform.java | DefaultPlatform.resolveAttribute | @Nullable
private static <T> T resolveAttribute(String attributeName, Class<T> type) {
"""
Helper to call a static no-arg getter to obtain an instance of a specified type. This is used
for platform aspects which are optional, but are expected to have a singleton available.
@return the return value of the specified static no-argument method, or null if the method
cannot be called or the returned value is of the wrong type.
"""
String getter = readProperty(attributeName);
if (getter == null) {
return null;
}
int idx = getter.indexOf('#');
if (idx <= 0 || idx == getter.length() - 1) {
error("invalid getter (expected <class>#<method>): %s\n", getter);
return null;
}
return callStaticMethod(getter.substring(0, idx), getter.substring(idx + 1), type);
} | java | @Nullable
private static <T> T resolveAttribute(String attributeName, Class<T> type) {
String getter = readProperty(attributeName);
if (getter == null) {
return null;
}
int idx = getter.indexOf('#');
if (idx <= 0 || idx == getter.length() - 1) {
error("invalid getter (expected <class>#<method>): %s\n", getter);
return null;
}
return callStaticMethod(getter.substring(0, idx), getter.substring(idx + 1), type);
} | [
"@",
"Nullable",
"private",
"static",
"<",
"T",
">",
"T",
"resolveAttribute",
"(",
"String",
"attributeName",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"String",
"getter",
"=",
"readProperty",
"(",
"attributeName",
")",
";",
"if",
"(",
"getter",
"==... | Helper to call a static no-arg getter to obtain an instance of a specified type. This is used
for platform aspects which are optional, but are expected to have a singleton available.
@return the return value of the specified static no-argument method, or null if the method
cannot be called or the returned value is of the wrong type. | [
"Helper",
"to",
"call",
"a",
"static",
"no",
"-",
"arg",
"getter",
"to",
"obtain",
"an",
"instance",
"of",
"a",
"specified",
"type",
".",
"This",
"is",
"used",
"for",
"platform",
"aspects",
"which",
"are",
"optional",
"but",
"are",
"expected",
"to",
"hav... | train | https://github.com/google/flogger/blob/a164967a93a9f4ce92f34319fc0cc7c91a57321c/api/src/main/java/com/google/common/flogger/backend/system/DefaultPlatform.java#L122-L134 |
netty/netty | handler/src/main/java/io/netty/handler/ssl/ConscryptAlpnSslEngine.java | ConscryptAlpnSslEngine.calculateOutNetBufSize | final int calculateOutNetBufSize(int plaintextBytes, int numBuffers) {
"""
Calculates the maximum size of the encrypted output buffer required to wrap the given plaintext bytes. Assumes
as a worst case that there is one TLS record per buffer.
@param plaintextBytes the number of plaintext bytes to be wrapped.
@param numBuffers the number of buffers that the plaintext bytes are spread across.
@return the maximum size of the encrypted output buffer required for the wrap operation.
"""
// Assuming a max of one frame per component in a composite buffer.
long maxOverhead = (long) Conscrypt.maxSealOverhead(getWrappedEngine()) * numBuffers;
// TODO(nmittler): update this to use MAX_ENCRYPTED_PACKET_LENGTH instead of Integer.MAX_VALUE
return (int) min(Integer.MAX_VALUE, plaintextBytes + maxOverhead);
} | java | final int calculateOutNetBufSize(int plaintextBytes, int numBuffers) {
// Assuming a max of one frame per component in a composite buffer.
long maxOverhead = (long) Conscrypt.maxSealOverhead(getWrappedEngine()) * numBuffers;
// TODO(nmittler): update this to use MAX_ENCRYPTED_PACKET_LENGTH instead of Integer.MAX_VALUE
return (int) min(Integer.MAX_VALUE, plaintextBytes + maxOverhead);
} | [
"final",
"int",
"calculateOutNetBufSize",
"(",
"int",
"plaintextBytes",
",",
"int",
"numBuffers",
")",
"{",
"// Assuming a max of one frame per component in a composite buffer.",
"long",
"maxOverhead",
"=",
"(",
"long",
")",
"Conscrypt",
".",
"maxSealOverhead",
"(",
"getW... | Calculates the maximum size of the encrypted output buffer required to wrap the given plaintext bytes. Assumes
as a worst case that there is one TLS record per buffer.
@param plaintextBytes the number of plaintext bytes to be wrapped.
@param numBuffers the number of buffers that the plaintext bytes are spread across.
@return the maximum size of the encrypted output buffer required for the wrap operation. | [
"Calculates",
"the",
"maximum",
"size",
"of",
"the",
"encrypted",
"output",
"buffer",
"required",
"to",
"wrap",
"the",
"given",
"plaintext",
"bytes",
".",
"Assumes",
"as",
"a",
"worst",
"case",
"that",
"there",
"is",
"one",
"TLS",
"record",
"per",
"buffer",
... | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/ConscryptAlpnSslEngine.java#L85-L90 |
maestrano/maestrano-java | src/main/java/com/maestrano/helpers/MnoPropertiesHelper.java | MnoPropertiesHelper.readEnvironment | public static String readEnvironment(String environmentName, String defaultValue) {
"""
Read from the System environment variable, if not found throws a MnoConfigurationException
"""
String property = System.getenv(environmentName);
if (isNullOrEmpty(property)) {
return defaultValue;
}
return property;
} | java | public static String readEnvironment(String environmentName, String defaultValue) {
String property = System.getenv(environmentName);
if (isNullOrEmpty(property)) {
return defaultValue;
}
return property;
} | [
"public",
"static",
"String",
"readEnvironment",
"(",
"String",
"environmentName",
",",
"String",
"defaultValue",
")",
"{",
"String",
"property",
"=",
"System",
".",
"getenv",
"(",
"environmentName",
")",
";",
"if",
"(",
"isNullOrEmpty",
"(",
"property",
")",
... | Read from the System environment variable, if not found throws a MnoConfigurationException | [
"Read",
"from",
"the",
"System",
"environment",
"variable",
"if",
"not",
"found",
"throws",
"a",
"MnoConfigurationException"
] | train | https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/helpers/MnoPropertiesHelper.java#L58-L64 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/kernelized/BOGD.java | BOGD.setMaxCoeff | public void setMaxCoeff(double maxCoeff) {
"""
Sets the maximum allowed value for any support vector allowed. The
original paper suggests values in the range 2<sup>x</sup> for <i>x</i>
∈ {0, 1, 2, 3, 4}
@param maxCoeff the maximum value for any support vector
"""
if(maxCoeff <= 0 || Double.isNaN(maxCoeff) || Double.isInfinite(maxCoeff))
throw new IllegalArgumentException("MaxCoeff must be positive, not " + maxCoeff);
this.maxCoeff = maxCoeff;
} | java | public void setMaxCoeff(double maxCoeff)
{
if(maxCoeff <= 0 || Double.isNaN(maxCoeff) || Double.isInfinite(maxCoeff))
throw new IllegalArgumentException("MaxCoeff must be positive, not " + maxCoeff);
this.maxCoeff = maxCoeff;
} | [
"public",
"void",
"setMaxCoeff",
"(",
"double",
"maxCoeff",
")",
"{",
"if",
"(",
"maxCoeff",
"<=",
"0",
"||",
"Double",
".",
"isNaN",
"(",
"maxCoeff",
")",
"||",
"Double",
".",
"isInfinite",
"(",
"maxCoeff",
")",
")",
"throw",
"new",
"IllegalArgumentExcept... | Sets the maximum allowed value for any support vector allowed. The
original paper suggests values in the range 2<sup>x</sup> for <i>x</i>
∈ {0, 1, 2, 3, 4}
@param maxCoeff the maximum value for any support vector | [
"Sets",
"the",
"maximum",
"allowed",
"value",
"for",
"any",
"support",
"vector",
"allowed",
".",
"The",
"original",
"paper",
"suggests",
"values",
"in",
"the",
"range",
"2<sup",
">",
"x<",
"/",
"sup",
">",
"for",
"<i",
">",
"x<",
"/",
"i",
">",
"&isin"... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/kernelized/BOGD.java#L174-L179 |
zaproxy/zaproxy | src/org/zaproxy/zap/view/StandardFieldsDialog.java | StandardFieldsDialog.setTextAndDiscardEdits | private static void setTextAndDiscardEdits(JTextComponent field, String value) {
"""
Sets the given value to the given field.
<p>
The edits are discarded after setting the value, if the field is a {@link ZapTextField} or {@link ZapTextArea}.
@param field the field to set the value.
@param value the value to set.
"""
if (value == null) {
return;
}
field.setText(value);
if (field instanceof ZapTextField) {
((ZapTextField) field).discardAllEdits();
} else if (field instanceof ZapTextArea) {
((ZapTextArea) field).discardAllEdits();
}
} | java | private static void setTextAndDiscardEdits(JTextComponent field, String value) {
if (value == null) {
return;
}
field.setText(value);
if (field instanceof ZapTextField) {
((ZapTextField) field).discardAllEdits();
} else if (field instanceof ZapTextArea) {
((ZapTextArea) field).discardAllEdits();
}
} | [
"private",
"static",
"void",
"setTextAndDiscardEdits",
"(",
"JTextComponent",
"field",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
";",
"}",
"field",
".",
"setText",
"(",
"value",
")",
";",
"if",
"(",
"field",
... | Sets the given value to the given field.
<p>
The edits are discarded after setting the value, if the field is a {@link ZapTextField} or {@link ZapTextArea}.
@param field the field to set the value.
@param value the value to set. | [
"Sets",
"the",
"given",
"value",
"to",
"the",
"given",
"field",
".",
"<p",
">",
"The",
"edits",
"are",
"discarded",
"after",
"setting",
"the",
"value",
"if",
"the",
"field",
"is",
"a",
"{",
"@link",
"ZapTextField",
"}",
"or",
"{",
"@link",
"ZapTextArea",... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/StandardFieldsDialog.java#L598-L609 |
casbin/jcasbin | src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java | DefaultRoleManager.hasLink | @Override
public boolean hasLink(String name1, String name2, String... domain) {
"""
hasLink determines whether role: name1 inherits role: name2.
domain is a prefix to the roles.
"""
if (domain.length == 1) {
name1 = domain[0] + "::" + name1;
name2 = domain[0] + "::" + name2;
} else if (domain.length > 1) {
throw new Error("error: domain should be 1 parameter");
}
if (name1.equals(name2)) {
return true;
}
if (!hasRole(name1) || !hasRole(name2)) {
return false;
}
Role role1 = createRole(name1);
return role1.hasRole(name2, maxHierarchyLevel);
} | java | @Override
public boolean hasLink(String name1, String name2, String... domain) {
if (domain.length == 1) {
name1 = domain[0] + "::" + name1;
name2 = domain[0] + "::" + name2;
} else if (domain.length > 1) {
throw new Error("error: domain should be 1 parameter");
}
if (name1.equals(name2)) {
return true;
}
if (!hasRole(name1) || !hasRole(name2)) {
return false;
}
Role role1 = createRole(name1);
return role1.hasRole(name2, maxHierarchyLevel);
} | [
"@",
"Override",
"public",
"boolean",
"hasLink",
"(",
"String",
"name1",
",",
"String",
"name2",
",",
"String",
"...",
"domain",
")",
"{",
"if",
"(",
"domain",
".",
"length",
"==",
"1",
")",
"{",
"name1",
"=",
"domain",
"[",
"0",
"]",
"+",
"\"::\"",
... | hasLink determines whether role: name1 inherits role: name2.
domain is a prefix to the roles. | [
"hasLink",
"determines",
"whether",
"role",
":",
"name1",
"inherits",
"role",
":",
"name2",
".",
"domain",
"is",
"a",
"prefix",
"to",
"the",
"roles",
"."
] | train | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java#L107-L126 |
aws/aws-sdk-java | aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/GetIdentityPoliciesResult.java | GetIdentityPoliciesResult.withPolicies | public GetIdentityPoliciesResult withPolicies(java.util.Map<String, String> policies) {
"""
<p>
A map of policy names to policies.
</p>
@param policies
A map of policy names to policies.
@return Returns a reference to this object so that method calls can be chained together.
"""
setPolicies(policies);
return this;
} | java | public GetIdentityPoliciesResult withPolicies(java.util.Map<String, String> policies) {
setPolicies(policies);
return this;
} | [
"public",
"GetIdentityPoliciesResult",
"withPolicies",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"policies",
")",
"{",
"setPolicies",
"(",
"policies",
")",
";",
"return",
"this",
";",
"}"
] | <p>
A map of policy names to policies.
</p>
@param policies
A map of policy names to policies.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"map",
"of",
"policy",
"names",
"to",
"policies",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/GetIdentityPoliciesResult.java#L74-L77 |
Azure/azure-sdk-for-java | containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/AgentPoolsInner.java | AgentPoolsInner.beginCreateOrUpdateAsync | public Observable<AgentPoolInner> beginCreateOrUpdateAsync(String resourceGroupName, String managedClusterName, String agentPoolName, AgentPoolInner parameters) {
"""
Creates or updates an agent pool.
Creates or updates an agent pool in the specified managed cluster.
@param resourceGroupName The name of the resource group.
@param managedClusterName The name of the managed cluster resource.
@param agentPoolName The name of the agent pool.
@param parameters Parameters supplied to the Create or Update an agent pool operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AgentPoolInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName, parameters).map(new Func1<ServiceResponse<AgentPoolInner>, AgentPoolInner>() {
@Override
public AgentPoolInner call(ServiceResponse<AgentPoolInner> response) {
return response.body();
}
});
} | java | public Observable<AgentPoolInner> beginCreateOrUpdateAsync(String resourceGroupName, String managedClusterName, String agentPoolName, AgentPoolInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName, parameters).map(new Func1<ServiceResponse<AgentPoolInner>, AgentPoolInner>() {
@Override
public AgentPoolInner call(ServiceResponse<AgentPoolInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AgentPoolInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"managedClusterName",
",",
"String",
"agentPoolName",
",",
"AgentPoolInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceR... | Creates or updates an agent pool.
Creates or updates an agent pool in the specified managed cluster.
@param resourceGroupName The name of the resource group.
@param managedClusterName The name of the managed cluster resource.
@param agentPoolName The name of the agent pool.
@param parameters Parameters supplied to the Create or Update an agent pool operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AgentPoolInner object | [
"Creates",
"or",
"updates",
"an",
"agent",
"pool",
".",
"Creates",
"or",
"updates",
"an",
"agent",
"pool",
"in",
"the",
"specified",
"managed",
"cluster",
"."
] | 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/AgentPoolsInner.java#L445-L452 |
cdk/cdk | tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java | MmffAtomTypeMatcher.assignPreliminaryTypes | private void assignPreliminaryTypes(IAtomContainer container, String[] symbs) {
"""
Preliminary atom types are assigned using SMARTS definitions.
@param container input structure representation
@param symbs symbolic atom types
"""
// shallow copy
IAtomContainer cpy = container.getBuilder().newInstance(IAtomContainer.class, container);
Cycles.markRingAtomsAndBonds(cpy);
for (AtomTypePattern matcher : patterns) {
for (final int idx : matcher.matches(cpy)) {
if (symbs[idx] == null) {
symbs[idx] = matcher.symb;
}
}
}
} | java | private void assignPreliminaryTypes(IAtomContainer container, String[] symbs) {
// shallow copy
IAtomContainer cpy = container.getBuilder().newInstance(IAtomContainer.class, container);
Cycles.markRingAtomsAndBonds(cpy);
for (AtomTypePattern matcher : patterns) {
for (final int idx : matcher.matches(cpy)) {
if (symbs[idx] == null) {
symbs[idx] = matcher.symb;
}
}
}
} | [
"private",
"void",
"assignPreliminaryTypes",
"(",
"IAtomContainer",
"container",
",",
"String",
"[",
"]",
"symbs",
")",
"{",
"// shallow copy",
"IAtomContainer",
"cpy",
"=",
"container",
".",
"getBuilder",
"(",
")",
".",
"newInstance",
"(",
"IAtomContainer",
".",
... | Preliminary atom types are assigned using SMARTS definitions.
@param container input structure representation
@param symbs symbolic atom types | [
"Preliminary",
"atom",
"types",
"are",
"assigned",
"using",
"SMARTS",
"definitions",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java#L202-L213 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/ui/SeaGlassComboBoxUI.java | SeaGlassComboBoxUI.getDefaultSize | @Override
protected Dimension getDefaultSize() {
"""
Return the default size of an empty display area of the combo box using
the current renderer and font.
This method was overridden to use SynthComboBoxRenderer instead of
DefaultListCellRenderer as the default renderer when calculating the size
of the combo box. This is used in the case of the combo not having any
data.
@return the size of an empty display area
@see #getDisplaySize
"""
SynthComboBoxRenderer r = new SynthComboBoxRenderer();
Dimension d = getSizeForComponent(r.getListCellRendererComponent(listBox, " ", -1, false, false));
return new Dimension(d.width, d.height);
} | java | @Override
protected Dimension getDefaultSize() {
SynthComboBoxRenderer r = new SynthComboBoxRenderer();
Dimension d = getSizeForComponent(r.getListCellRendererComponent(listBox, " ", -1, false, false));
return new Dimension(d.width, d.height);
} | [
"@",
"Override",
"protected",
"Dimension",
"getDefaultSize",
"(",
")",
"{",
"SynthComboBoxRenderer",
"r",
"=",
"new",
"SynthComboBoxRenderer",
"(",
")",
";",
"Dimension",
"d",
"=",
"getSizeForComponent",
"(",
"r",
".",
"getListCellRendererComponent",
"(",
"listBox",... | Return the default size of an empty display area of the combo box using
the current renderer and font.
This method was overridden to use SynthComboBoxRenderer instead of
DefaultListCellRenderer as the default renderer when calculating the size
of the combo box. This is used in the case of the combo not having any
data.
@return the size of an empty display area
@see #getDisplaySize | [
"Return",
"the",
"default",
"size",
"of",
"an",
"empty",
"display",
"area",
"of",
"the",
"combo",
"box",
"using",
"the",
"current",
"renderer",
"and",
"font",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassComboBoxUI.java#L408-L413 |
googleads/googleads-java-lib | examples/adwords_axis/src/main/java/adwords/axis/v201809/misc/GetAllImageAssets.java | GetAllImageAssets.runExample | public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws RemoteException {
"""
Runs the example.
@param adWordsServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
"""
// Get the AdGroupAdService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
int offset = 0;
boolean morePages = true;
// Create the selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector =
builder
.fields(
AssetField.AssetName,
AssetField.AssetStatus,
AssetField.ImageFileSize,
AssetField.ImageWidth,
AssetField.ImageHeight,
AssetField.ImageFullSizeUrl)
.offset(offset)
.limit(PAGE_SIZE)
// Filter for image assets only.
.equals(AssetField.AssetSubtype, AssetType.IMAGE.getValue())
.build();
int totalEntries = 0;
while (morePages) {
// Get the image assets.
AssetPage page = assetService.get(selector);
// Display the results.
if (page.getEntries() != null && page.getEntries().length > 0) {
totalEntries = page.getTotalNumEntries();
int i = selector.getPaging().getStartIndex();
for (Asset asset : page.getEntries()) {
System.out.printf(
"%d) Image asset with ID %d, name '%s', and status '%s' was found.%n",
i, asset.getAssetId(), asset.getAssetName(), asset.getAssetStatus());
}
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
morePages = offset < page.getTotalNumEntries();
}
System.out.printf("Found %d image assets.%n", totalEntries);
} | java | public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws RemoteException {
// Get the AdGroupAdService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
int offset = 0;
boolean morePages = true;
// Create the selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector =
builder
.fields(
AssetField.AssetName,
AssetField.AssetStatus,
AssetField.ImageFileSize,
AssetField.ImageWidth,
AssetField.ImageHeight,
AssetField.ImageFullSizeUrl)
.offset(offset)
.limit(PAGE_SIZE)
// Filter for image assets only.
.equals(AssetField.AssetSubtype, AssetType.IMAGE.getValue())
.build();
int totalEntries = 0;
while (morePages) {
// Get the image assets.
AssetPage page = assetService.get(selector);
// Display the results.
if (page.getEntries() != null && page.getEntries().length > 0) {
totalEntries = page.getTotalNumEntries();
int i = selector.getPaging().getStartIndex();
for (Asset asset : page.getEntries()) {
System.out.printf(
"%d) Image asset with ID %d, name '%s', and status '%s' was found.%n",
i, asset.getAssetId(), asset.getAssetName(), asset.getAssetStatus());
}
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
morePages = offset < page.getTotalNumEntries();
}
System.out.printf("Found %d image assets.%n", totalEntries);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdWordsServicesInterface",
"adWordsServices",
",",
"AdWordsSession",
"session",
")",
"throws",
"RemoteException",
"{",
"// Get the AdGroupAdService.",
"AssetServiceInterface",
"assetService",
"=",
"adWordsServices",
".",
"get",
... | Runs the example.
@param adWordsServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/adwords_axis/src/main/java/adwords/axis/v201809/misc/GetAllImageAssets.java#L108-L155 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/calibration/BinaryCalibration.java | BinaryCalibration.setCalibrationHoldOut | public void setCalibrationHoldOut(double holdOut) {
"""
If the calibration mode is set to {@link CalibrationMode#HOLD_OUT}, this
what portion of the data set is randomly selected to be the hold out set.
The default is 0.3.
@param holdOut the portion in (0, 1) to hold out
"""
if(Double.isNaN(holdOut) || holdOut <= 0 || holdOut >= 1)
throw new IllegalArgumentException("HoldOut must be in (0, 1), not " + holdOut);
this.holdOut = holdOut;
} | java | public void setCalibrationHoldOut(double holdOut)
{
if(Double.isNaN(holdOut) || holdOut <= 0 || holdOut >= 1)
throw new IllegalArgumentException("HoldOut must be in (0, 1), not " + holdOut);
this.holdOut = holdOut;
} | [
"public",
"void",
"setCalibrationHoldOut",
"(",
"double",
"holdOut",
")",
"{",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"holdOut",
")",
"||",
"holdOut",
"<=",
"0",
"||",
"holdOut",
">=",
"1",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"HoldOut mu... | If the calibration mode is set to {@link CalibrationMode#HOLD_OUT}, this
what portion of the data set is randomly selected to be the hold out set.
The default is 0.3.
@param holdOut the portion in (0, 1) to hold out | [
"If",
"the",
"calibration",
"mode",
"is",
"set",
"to",
"{",
"@link",
"CalibrationMode#HOLD_OUT",
"}",
"this",
"what",
"portion",
"of",
"the",
"data",
"set",
"is",
"randomly",
"selected",
"to",
"be",
"the",
"hold",
"out",
"set",
".",
"The",
"default",
"is",... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/calibration/BinaryCalibration.java#L192-L197 |
RestComm/media-core | network/src/main/java/org/restcomm/media/core/network/deprecated/IPAddressCompare.java | IPAddressCompare.isInRangeV6 | public static boolean isInRangeV6(byte[] network,byte[] subnet,byte[] ipAddress) {
"""
Checks whether ipAddress is in IPV6 network with specified subnet
"""
if(network.length!=16 || subnet.length!=16 || ipAddress.length!=16)
return false;
return compareByteValues(network,subnet,ipAddress);
} | java | public static boolean isInRangeV6(byte[] network,byte[] subnet,byte[] ipAddress)
{
if(network.length!=16 || subnet.length!=16 || ipAddress.length!=16)
return false;
return compareByteValues(network,subnet,ipAddress);
} | [
"public",
"static",
"boolean",
"isInRangeV6",
"(",
"byte",
"[",
"]",
"network",
",",
"byte",
"[",
"]",
"subnet",
",",
"byte",
"[",
"]",
"ipAddress",
")",
"{",
"if",
"(",
"network",
".",
"length",
"!=",
"16",
"||",
"subnet",
".",
"length",
"!=",
"16",... | Checks whether ipAddress is in IPV6 network with specified subnet | [
"Checks",
"whether",
"ipAddress",
"is",
"in",
"IPV6",
"network",
"with",
"specified",
"subnet"
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/network/src/main/java/org/restcomm/media/core/network/deprecated/IPAddressCompare.java#L47-L53 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/util/WorkQueue.java | WorkQueue.await | public void await(Object taskGroupId) {
"""
Waits until all the tasks associated with the group identifier have
finished. Once a task group has been successfully waited upon, the group
identifier is removed from the queue and is valid to be reused for a new
task group.
@throws IllegalArgumentException if the {@code taskGroupId} is not
currently associated with any active taskGroup
"""
CountDownLatch latch = taskKeyToLatch.get(taskGroupId);
if (latch == null)
throw new IllegalArgumentException(
"Unknown task group: " + taskGroupId);
try {
while(!latch.await(5, TimeUnit.SECONDS))
;
// Once finished, remove the key so it can be associated with a new
// task
taskKeyToLatch.remove(taskGroupId);
}
catch (InterruptedException ie) {
throw new IllegalStateException("Not all tasks finished", ie);
}
} | java | public void await(Object taskGroupId) {
CountDownLatch latch = taskKeyToLatch.get(taskGroupId);
if (latch == null)
throw new IllegalArgumentException(
"Unknown task group: " + taskGroupId);
try {
while(!latch.await(5, TimeUnit.SECONDS))
;
// Once finished, remove the key so it can be associated with a new
// task
taskKeyToLatch.remove(taskGroupId);
}
catch (InterruptedException ie) {
throw new IllegalStateException("Not all tasks finished", ie);
}
} | [
"public",
"void",
"await",
"(",
"Object",
"taskGroupId",
")",
"{",
"CountDownLatch",
"latch",
"=",
"taskKeyToLatch",
".",
"get",
"(",
"taskGroupId",
")",
";",
"if",
"(",
"latch",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unknown ta... | Waits until all the tasks associated with the group identifier have
finished. Once a task group has been successfully waited upon, the group
identifier is removed from the queue and is valid to be reused for a new
task group.
@throws IllegalArgumentException if the {@code taskGroupId} is not
currently associated with any active taskGroup | [
"Waits",
"until",
"all",
"the",
"tasks",
"associated",
"with",
"the",
"group",
"identifier",
"have",
"finished",
".",
"Once",
"a",
"task",
"group",
"has",
"been",
"successfully",
"waited",
"upon",
"the",
"group",
"identifier",
"is",
"removed",
"from",
"the",
... | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/WorkQueue.java#L160-L175 |
lightblue-platform/lightblue-client | core/src/main/java/com/redhat/lightblue/client/request/data/DataFindRequest.java | DataFindRequest.range | @Deprecated
public DataFindRequest range(Integer begin, Integer end) {
"""
Use {@link #select(List, Integer, Integer)} or
{@link #select(Projection[], Integer, Integer)}.
@param begin - the 'from' parameter to send to lightblue.
@param end - the 'to' parameter to send to lightblue.
"""
this.begin = begin;
if (end != null) {
//'maxResults' should be 1 greater than a 'to' value.
maxResults = end - (begin == null ? 0 : begin) + 1;
}
return this;
} | java | @Deprecated
public DataFindRequest range(Integer begin, Integer end) {
this.begin = begin;
if (end != null) {
//'maxResults' should be 1 greater than a 'to' value.
maxResults = end - (begin == null ? 0 : begin) + 1;
}
return this;
} | [
"@",
"Deprecated",
"public",
"DataFindRequest",
"range",
"(",
"Integer",
"begin",
",",
"Integer",
"end",
")",
"{",
"this",
".",
"begin",
"=",
"begin",
";",
"if",
"(",
"end",
"!=",
"null",
")",
"{",
"//'maxResults' should be 1 greater than a 'to' value.",
"maxRes... | Use {@link #select(List, Integer, Integer)} or
{@link #select(Projection[], Integer, Integer)}.
@param begin - the 'from' parameter to send to lightblue.
@param end - the 'to' parameter to send to lightblue. | [
"Use",
"{",
"@link",
"#select",
"(",
"List",
"Integer",
"Integer",
")",
"}",
"or",
"{",
"@link",
"#select",
"(",
"Projection",
"[]",
"Integer",
"Integer",
")",
"}",
"."
] | train | https://github.com/lightblue-platform/lightblue-client/blob/03790aff34e90d3889f60fd6c603c21a21dc1a40/core/src/main/java/com/redhat/lightblue/client/request/data/DataFindRequest.java#L89-L98 |
JoeKerouac/utils | src/main/java/com/joe/utils/poi/WorkBookAccesser.java | WorkBookAccesser.mergedRegion | public void mergedRegion(int firstRow, int lastRow, int firstCol, int lastCol) {
"""
合并指定sheet指定区域的单元格
@param firstRow 要合并的第一行
@param lastRow 要合并的最后一行
@param firstCol 要合并的第一列
@param lastCol 要合并的最后一列
"""
mergedRegion(workbook.getSheetAt(sheetIndex), firstRow, lastRow, firstCol, lastCol);
} | java | public void mergedRegion(int firstRow, int lastRow, int firstCol, int lastCol) {
mergedRegion(workbook.getSheetAt(sheetIndex), firstRow, lastRow, firstCol, lastCol);
} | [
"public",
"void",
"mergedRegion",
"(",
"int",
"firstRow",
",",
"int",
"lastRow",
",",
"int",
"firstCol",
",",
"int",
"lastCol",
")",
"{",
"mergedRegion",
"(",
"workbook",
".",
"getSheetAt",
"(",
"sheetIndex",
")",
",",
"firstRow",
",",
"lastRow",
",",
"fir... | 合并指定sheet指定区域的单元格
@param firstRow 要合并的第一行
@param lastRow 要合并的最后一行
@param firstCol 要合并的第一列
@param lastCol 要合并的最后一列 | [
"合并指定sheet指定区域的单元格"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/poi/WorkBookAccesser.java#L89-L91 |
lucee/Lucee | core/src/main/java/lucee/runtime/op/Operator.java | Operator.ct | public static boolean ct(Object left, Object right) throws PageException {
"""
check if left is inside right (String-> ignore case)
@param left string to check
@param right substring to find in string
@return return if substring has been found
@throws PageException
"""
return Caster.toString(left).toLowerCase().indexOf(Caster.toString(right).toLowerCase()) != -1;
} | java | public static boolean ct(Object left, Object right) throws PageException {
return Caster.toString(left).toLowerCase().indexOf(Caster.toString(right).toLowerCase()) != -1;
} | [
"public",
"static",
"boolean",
"ct",
"(",
"Object",
"left",
",",
"Object",
"right",
")",
"throws",
"PageException",
"{",
"return",
"Caster",
".",
"toString",
"(",
"left",
")",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"Caster",
".",
"toString",
... | check if left is inside right (String-> ignore case)
@param left string to check
@param right substring to find in string
@return return if substring has been found
@throws PageException | [
"check",
"if",
"left",
"is",
"inside",
"right",
"(",
"String",
"-",
">",
"ignore",
"case",
")"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Operator.java#L793-L795 |
rapid7/conqueso-client-java | src/main/java/com/rapid7/conqueso/client/ConquesoClient.java | ConquesoClient.getRoleInstances | public ImmutableList<InstanceInfo> getRoleInstances(String roleName) {
"""
Retrieve information about instances of a particular role from the Conqueso Server.
@param roleName the role to retrieve
@return the information about the instances of the given role
@throws ConquesoCommunicationException if there's an error communicating with the Conqueso Server.
"""
return getRoleInstancesWithMetadataImpl(roleName, Collections.<String, String>emptyMap());
} | java | public ImmutableList<InstanceInfo> getRoleInstances(String roleName) {
return getRoleInstancesWithMetadataImpl(roleName, Collections.<String, String>emptyMap());
} | [
"public",
"ImmutableList",
"<",
"InstanceInfo",
">",
"getRoleInstances",
"(",
"String",
"roleName",
")",
"{",
"return",
"getRoleInstancesWithMetadataImpl",
"(",
"roleName",
",",
"Collections",
".",
"<",
"String",
",",
"String",
">",
"emptyMap",
"(",
")",
")",
";... | Retrieve information about instances of a particular role from the Conqueso Server.
@param roleName the role to retrieve
@return the information about the instances of the given role
@throws ConquesoCommunicationException if there's an error communicating with the Conqueso Server. | [
"Retrieve",
"information",
"about",
"instances",
"of",
"a",
"particular",
"role",
"from",
"the",
"Conqueso",
"Server",
"."
] | train | https://github.com/rapid7/conqueso-client-java/blob/fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2/src/main/java/com/rapid7/conqueso/client/ConquesoClient.java#L512-L514 |
jboss/jboss-common-beans | src/main/java/org/jboss/common/beans/property/DateEditor.java | DateEditor.initialize | public static void initialize() {
"""
Setup the parsing formats. Offered as a separate static method to allow testing of locale changes, since SimpleDateFormat
will use the default locale upon construction. Should not be normally used!
"""
PrivilegedAction action = new PrivilegedAction() {
public Object run() {
String defaultFormat = System.getProperty("org.jboss.common.beans.property.DateEditor.format", "MMM d, yyyy");
String defaultLocale = System.getProperty("org.jboss.common.beans.property.DateEditor.locale");
DateFormat defaultDateFormat;
if (defaultLocale == null || defaultLocale.length() == 0) {
defaultDateFormat = new SimpleDateFormat(defaultFormat);
} else {
LocaleEditor localeEditor = new LocaleEditor();
localeEditor.setAsText(defaultLocale);
Locale locale = (Locale) localeEditor.getValue();
defaultDateFormat = new SimpleDateFormat(defaultFormat, locale);
}
formats = new DateFormat[] { defaultDateFormat,
// Tue Jan 04 00:00:00 PST 2005
new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"),
// Wed, 4 Jul 2001 12:08:56 -0700
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z") };
return null;
}
};
AccessController.doPrivileged(action);
} | java | public static void initialize() {
PrivilegedAction action = new PrivilegedAction() {
public Object run() {
String defaultFormat = System.getProperty("org.jboss.common.beans.property.DateEditor.format", "MMM d, yyyy");
String defaultLocale = System.getProperty("org.jboss.common.beans.property.DateEditor.locale");
DateFormat defaultDateFormat;
if (defaultLocale == null || defaultLocale.length() == 0) {
defaultDateFormat = new SimpleDateFormat(defaultFormat);
} else {
LocaleEditor localeEditor = new LocaleEditor();
localeEditor.setAsText(defaultLocale);
Locale locale = (Locale) localeEditor.getValue();
defaultDateFormat = new SimpleDateFormat(defaultFormat, locale);
}
formats = new DateFormat[] { defaultDateFormat,
// Tue Jan 04 00:00:00 PST 2005
new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"),
// Wed, 4 Jul 2001 12:08:56 -0700
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z") };
return null;
}
};
AccessController.doPrivileged(action);
} | [
"public",
"static",
"void",
"initialize",
"(",
")",
"{",
"PrivilegedAction",
"action",
"=",
"new",
"PrivilegedAction",
"(",
")",
"{",
"public",
"Object",
"run",
"(",
")",
"{",
"String",
"defaultFormat",
"=",
"System",
".",
"getProperty",
"(",
"\"org.jboss.comm... | Setup the parsing formats. Offered as a separate static method to allow testing of locale changes, since SimpleDateFormat
will use the default locale upon construction. Should not be normally used! | [
"Setup",
"the",
"parsing",
"formats",
".",
"Offered",
"as",
"a",
"separate",
"static",
"method",
"to",
"allow",
"testing",
"of",
"locale",
"changes",
"since",
"SimpleDateFormat",
"will",
"use",
"the",
"default",
"locale",
"upon",
"construction",
".",
"Should",
... | train | https://github.com/jboss/jboss-common-beans/blob/ffb48b1719762534bf92d762eadf91d1815f6748/src/main/java/org/jboss/common/beans/property/DateEditor.java#L60-L84 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/svm/SBP.java | SBP.setNu | public void setNu(double nu) {
"""
The nu parameter for this SVM is not the same as the standard nu-SVM
formulation, though it plays a similar role. It must be in the range
(0, 1), where small values indicate a linearly separable problem (in the
kernel space), and large values mean the problem is less separable. If
the value is too small for the problem, the SVM may fail to converge or
produce good results.
@param nu the value between (0, 1)
"""
if(Double.isNaN(nu) || nu <= 0 || nu >= 1)
throw new IllegalArgumentException("nu must be in the range (0, 1)");
this.nu = nu;
} | java | public void setNu(double nu)
{
if(Double.isNaN(nu) || nu <= 0 || nu >= 1)
throw new IllegalArgumentException("nu must be in the range (0, 1)");
this.nu = nu;
} | [
"public",
"void",
"setNu",
"(",
"double",
"nu",
")",
"{",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"nu",
")",
"||",
"nu",
"<=",
"0",
"||",
"nu",
">=",
"1",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"nu must be in the range (0, 1)\"",
")",
";... | The nu parameter for this SVM is not the same as the standard nu-SVM
formulation, though it plays a similar role. It must be in the range
(0, 1), where small values indicate a linearly separable problem (in the
kernel space), and large values mean the problem is less separable. If
the value is too small for the problem, the SVM may fail to converge or
produce good results.
@param nu the value between (0, 1) | [
"The",
"nu",
"parameter",
"for",
"this",
"SVM",
"is",
"not",
"the",
"same",
"as",
"the",
"standard",
"nu",
"-",
"SVM",
"formulation",
"though",
"it",
"plays",
"a",
"similar",
"role",
".",
"It",
"must",
"be",
"in",
"the",
"range",
"(",
"0",
"1",
")",
... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/svm/SBP.java#L106-L111 |
jhy/jsoup | src/main/java/org/jsoup/nodes/Document.java | Document.createElement | public Element createElement(String tagName) {
"""
Create a new Element, with this document's base uri. Does not make the new element a child of this document.
@param tagName element tag name (e.g. {@code a})
@return new element
"""
return new Element(Tag.valueOf(tagName, ParseSettings.preserveCase), this.baseUri());
} | java | public Element createElement(String tagName) {
return new Element(Tag.valueOf(tagName, ParseSettings.preserveCase), this.baseUri());
} | [
"public",
"Element",
"createElement",
"(",
"String",
"tagName",
")",
"{",
"return",
"new",
"Element",
"(",
"Tag",
".",
"valueOf",
"(",
"tagName",
",",
"ParseSettings",
".",
"preserveCase",
")",
",",
"this",
".",
"baseUri",
"(",
")",
")",
";",
"}"
] | Create a new Element, with this document's base uri. Does not make the new element a child of this document.
@param tagName element tag name (e.g. {@code a})
@return new element | [
"Create",
"a",
"new",
"Element",
"with",
"this",
"document",
"s",
"base",
"uri",
".",
"Does",
"not",
"make",
"the",
"new",
"element",
"a",
"child",
"of",
"this",
"document",
"."
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Document.java#L109-L111 |
line/armeria | core/src/main/java/com/linecorp/armeria/client/limit/ConcurrencyLimitingHttpClient.java | ConcurrencyLimitingHttpClient.newDecorator | public static Function<Client<HttpRequest, HttpResponse>, ConcurrencyLimitingHttpClient>
newDecorator(int maxConcurrency) {
"""
Creates a new {@link Client} decorator that limits the concurrent number of active HTTP requests.
"""
validateMaxConcurrency(maxConcurrency);
return delegate -> new ConcurrencyLimitingHttpClient(delegate, maxConcurrency);
} | java | public static Function<Client<HttpRequest, HttpResponse>, ConcurrencyLimitingHttpClient>
newDecorator(int maxConcurrency) {
validateMaxConcurrency(maxConcurrency);
return delegate -> new ConcurrencyLimitingHttpClient(delegate, maxConcurrency);
} | [
"public",
"static",
"Function",
"<",
"Client",
"<",
"HttpRequest",
",",
"HttpResponse",
">",
",",
"ConcurrencyLimitingHttpClient",
">",
"newDecorator",
"(",
"int",
"maxConcurrency",
")",
"{",
"validateMaxConcurrency",
"(",
"maxConcurrency",
")",
";",
"return",
"dele... | Creates a new {@link Client} decorator that limits the concurrent number of active HTTP requests. | [
"Creates",
"a",
"new",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/limit/ConcurrencyLimitingHttpClient.java#L44-L48 |
CloudSlang/cs-actions | cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java | SendMail.validateDelimiters | protected void validateDelimiters(String rowDelimiter, String columnDelimiter) throws Exception {
"""
This method checks if the delimiters are equal and if the row delimiter is a substring of the column delimiter
and throws an exception with the appropriate message.
@param rowDelimiter
@param columnDelimiter
@throws Exception
"""
if (rowDelimiter.equals(columnDelimiter)) {
throw new Exception(INVALID_DELIMITERS);
}
if (StringUtils.contains(columnDelimiter, rowDelimiter)) {
throw new Exception(INVALID_ROW_DELIMITER);
}
} | java | protected void validateDelimiters(String rowDelimiter, String columnDelimiter) throws Exception {
if (rowDelimiter.equals(columnDelimiter)) {
throw new Exception(INVALID_DELIMITERS);
}
if (StringUtils.contains(columnDelimiter, rowDelimiter)) {
throw new Exception(INVALID_ROW_DELIMITER);
}
} | [
"protected",
"void",
"validateDelimiters",
"(",
"String",
"rowDelimiter",
",",
"String",
"columnDelimiter",
")",
"throws",
"Exception",
"{",
"if",
"(",
"rowDelimiter",
".",
"equals",
"(",
"columnDelimiter",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"INVAL... | This method checks if the delimiters are equal and if the row delimiter is a substring of the column delimiter
and throws an exception with the appropriate message.
@param rowDelimiter
@param columnDelimiter
@throws Exception | [
"This",
"method",
"checks",
"if",
"the",
"delimiters",
"are",
"equal",
"and",
"if",
"the",
"row",
"delimiter",
"is",
"a",
"substring",
"of",
"the",
"column",
"delimiter",
"and",
"throws",
"an",
"exception",
"with",
"the",
"appropriate",
"message",
"."
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-mail/src/main/java/io/cloudslang/content/mail/services/SendMail.java#L460-L467 |
keyboardsurfer/Crouton | library/src/main/java/de/keyboardsurfer/android/widget/crouton/Manager.java | Manager.announceForAccessibilityCompat | public static void announceForAccessibilityCompat(Context context, CharSequence text) {
"""
Generates and dispatches an SDK-specific spoken announcement.
<p>
For backwards compatibility, we're constructing an event from scratch
using the appropriate event type. If your application only targets SDK
16+, you can just call View.announceForAccessibility(CharSequence).
</p>
<p/>
note: AccessibilityManager is only available from API lvl 4.
<p/>
Adapted from https://http://eyes-free.googlecode.com/files/accessibility_codelab_demos_v2_src.zip
via https://github.com/coreform/android-formidable-validation
@param context
Used to get {@link AccessibilityManager}
@param text
The text to announce.
"""
if (Build.VERSION.SDK_INT >= 4) {
AccessibilityManager accessibilityManager = null;
if (null != context) {
accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
if (null == accessibilityManager || !accessibilityManager.isEnabled()) {
return;
}
// Prior to SDK 16, announcements could only be made through FOCUSED
// events. Jelly Bean (SDK 16) added support for speaking text verbatim
// using the ANNOUNCEMENT event type.
final int eventType;
if (Build.VERSION.SDK_INT < 16) {
eventType = AccessibilityEvent.TYPE_VIEW_FOCUSED;
} else {
eventType = AccessibilityEvent.TYPE_ANNOUNCEMENT;
}
// Construct an accessibility event with the minimum recommended
// attributes. An event without a class name or package may be dropped.
final AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
event.getText().add(text);
event.setClassName(Manager.class.getName());
event.setPackageName(context.getPackageName());
// Sends the event directly through the accessibility manager. If your
// application only targets SDK 14+, you should just call
// getParent().requestSendAccessibilityEvent(this, event);
accessibilityManager.sendAccessibilityEvent(event);
}
} | java | public static void announceForAccessibilityCompat(Context context, CharSequence text) {
if (Build.VERSION.SDK_INT >= 4) {
AccessibilityManager accessibilityManager = null;
if (null != context) {
accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
if (null == accessibilityManager || !accessibilityManager.isEnabled()) {
return;
}
// Prior to SDK 16, announcements could only be made through FOCUSED
// events. Jelly Bean (SDK 16) added support for speaking text verbatim
// using the ANNOUNCEMENT event type.
final int eventType;
if (Build.VERSION.SDK_INT < 16) {
eventType = AccessibilityEvent.TYPE_VIEW_FOCUSED;
} else {
eventType = AccessibilityEvent.TYPE_ANNOUNCEMENT;
}
// Construct an accessibility event with the minimum recommended
// attributes. An event without a class name or package may be dropped.
final AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
event.getText().add(text);
event.setClassName(Manager.class.getName());
event.setPackageName(context.getPackageName());
// Sends the event directly through the accessibility manager. If your
// application only targets SDK 14+, you should just call
// getParent().requestSendAccessibilityEvent(this, event);
accessibilityManager.sendAccessibilityEvent(event);
}
} | [
"public",
"static",
"void",
"announceForAccessibilityCompat",
"(",
"Context",
"context",
",",
"CharSequence",
"text",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"4",
")",
"{",
"AccessibilityManager",
"accessibilityManager",
"=",
"null",
... | Generates and dispatches an SDK-specific spoken announcement.
<p>
For backwards compatibility, we're constructing an event from scratch
using the appropriate event type. If your application only targets SDK
16+, you can just call View.announceForAccessibility(CharSequence).
</p>
<p/>
note: AccessibilityManager is only available from API lvl 4.
<p/>
Adapted from https://http://eyes-free.googlecode.com/files/accessibility_codelab_demos_v2_src.zip
via https://github.com/coreform/android-formidable-validation
@param context
Used to get {@link AccessibilityManager}
@param text
The text to announce. | [
"Generates",
"and",
"dispatches",
"an",
"SDK",
"-",
"specific",
"spoken",
"announcement",
".",
"<p",
">",
"For",
"backwards",
"compatibility",
"we",
"re",
"constructing",
"an",
"event",
"from",
"scratch",
"using",
"the",
"appropriate",
"event",
"type",
".",
"I... | train | https://github.com/keyboardsurfer/Crouton/blob/7806b15e4d52793e1f5aeaa4a55b1e220289e619/library/src/main/java/de/keyboardsurfer/android/widget/crouton/Manager.java#L440-L472 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/openal/AiffData.java | AiffData.convertAudioBytes | private static ByteBuffer convertAudioBytes(AudioFormat format, byte[] audio_bytes, boolean two_bytes_data) {
"""
Convert the audio bytes into the stream
@param format The audio format being decoded
@param audio_bytes The audio byts
@param two_bytes_data True if we using double byte data
@return The byte bufer of data
"""
ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(audio_bytes);
src.order(ByteOrder.BIG_ENDIAN);
if (two_bytes_data) {
ShortBuffer dest_short = dest.asShortBuffer();
ShortBuffer src_short = src.asShortBuffer();
while (src_short.hasRemaining())
dest_short.put(src_short.get());
} else {
while (src.hasRemaining()) {
byte b = src.get();
if (format.getEncoding() == Encoding.PCM_SIGNED) {
b = (byte) (b + 127);
}
dest.put(b);
}
}
dest.rewind();
return dest;
} | java | private static ByteBuffer convertAudioBytes(AudioFormat format, byte[] audio_bytes, boolean two_bytes_data) {
ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(audio_bytes);
src.order(ByteOrder.BIG_ENDIAN);
if (two_bytes_data) {
ShortBuffer dest_short = dest.asShortBuffer();
ShortBuffer src_short = src.asShortBuffer();
while (src_short.hasRemaining())
dest_short.put(src_short.get());
} else {
while (src.hasRemaining()) {
byte b = src.get();
if (format.getEncoding() == Encoding.PCM_SIGNED) {
b = (byte) (b + 127);
}
dest.put(b);
}
}
dest.rewind();
return dest;
} | [
"private",
"static",
"ByteBuffer",
"convertAudioBytes",
"(",
"AudioFormat",
"format",
",",
"byte",
"[",
"]",
"audio_bytes",
",",
"boolean",
"two_bytes_data",
")",
"{",
"ByteBuffer",
"dest",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"audio_bytes",
".",
"length... | Convert the audio bytes into the stream
@param format The audio format being decoded
@param audio_bytes The audio byts
@param two_bytes_data True if we using double byte data
@return The byte bufer of data | [
"Convert",
"the",
"audio",
"bytes",
"into",
"the",
"stream"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/openal/AiffData.java#L246-L267 |
jamesagnew/hapi-fhir | hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/validation/InstanceValidator.java | InstanceValidator.validateAnswerCode | private void validateAnswerCode(List<ValidationMessage> errors, Element value, NodeStack stack, Questionnaire qSrc, Reference ref, boolean theOpenChoice) {
"""
/* private void validateAnswerCode(List<ValidationMessage> errors, Element value, NodeStack stack, List<Coding> optionList) {
String system = value.getNamedChildValue("system");
String code = value.getNamedChildValue("code");
boolean found = false;
for (Coding c : optionList) {
if (ObjectUtil.equals(c.getSystem(), system) && ObjectUtil.equals(c.getCode(), code)) {
found = true;
break;
}
}
rule(errors, IssueType.STRUCTURE, value.line(), value.col(), stack.getLiteralPath(), found, "The code "+system+"::"+code+" is not a valid option");
}
"""
ValueSet vs = resolveBindingReference(qSrc, ref);
if (warning(errors, IssueType.CODEINVALID, value.line(), value.col(), stack.getLiteralPath(), vs != null, "ValueSet " + describeReference(ref) + " not found")) {
try {
Coding c = readAsCoding(value);
if (isBlank(c.getCode()) && isBlank(c.getSystem()) && isNotBlank(c.getDisplay())) {
if (theOpenChoice) {
return;
}
}
long t = System.nanoTime();
ValidationResult res = context.validateCode(c, vs);
txTime = txTime + (System.nanoTime() - t);
if (!res.isOk())
rule(errors, IssueType.CODEINVALID, value.line(), value.col(), stack.getLiteralPath(), false, "The value provided ("+c.getSystem()+"::"+c.getCode()+") is not in the options value set in the questionnaire");
} catch (Exception e) {
warning(errors, IssueType.CODEINVALID, value.line(), value.col(), stack.getLiteralPath(), false, "Error " + e.getMessage() + " validating Coding against Questionnaire Options");
}
}
} | java | private void validateAnswerCode(List<ValidationMessage> errors, Element value, NodeStack stack, Questionnaire qSrc, Reference ref, boolean theOpenChoice) {
ValueSet vs = resolveBindingReference(qSrc, ref);
if (warning(errors, IssueType.CODEINVALID, value.line(), value.col(), stack.getLiteralPath(), vs != null, "ValueSet " + describeReference(ref) + " not found")) {
try {
Coding c = readAsCoding(value);
if (isBlank(c.getCode()) && isBlank(c.getSystem()) && isNotBlank(c.getDisplay())) {
if (theOpenChoice) {
return;
}
}
long t = System.nanoTime();
ValidationResult res = context.validateCode(c, vs);
txTime = txTime + (System.nanoTime() - t);
if (!res.isOk())
rule(errors, IssueType.CODEINVALID, value.line(), value.col(), stack.getLiteralPath(), false, "The value provided ("+c.getSystem()+"::"+c.getCode()+") is not in the options value set in the questionnaire");
} catch (Exception e) {
warning(errors, IssueType.CODEINVALID, value.line(), value.col(), stack.getLiteralPath(), false, "Error " + e.getMessage() + " validating Coding against Questionnaire Options");
}
}
} | [
"private",
"void",
"validateAnswerCode",
"(",
"List",
"<",
"ValidationMessage",
">",
"errors",
",",
"Element",
"value",
",",
"NodeStack",
"stack",
",",
"Questionnaire",
"qSrc",
",",
"Reference",
"ref",
",",
"boolean",
"theOpenChoice",
")",
"{",
"ValueSet",
"vs",... | /* private void validateAnswerCode(List<ValidationMessage> errors, Element value, NodeStack stack, List<Coding> optionList) {
String system = value.getNamedChildValue("system");
String code = value.getNamedChildValue("code");
boolean found = false;
for (Coding c : optionList) {
if (ObjectUtil.equals(c.getSystem(), system) && ObjectUtil.equals(c.getCode(), code)) {
found = true;
break;
}
}
rule(errors, IssueType.STRUCTURE, value.line(), value.col(), stack.getLiteralPath(), found, "The code "+system+"::"+code+" is not a valid option");
} | [
"/",
"*",
"private",
"void",
"validateAnswerCode",
"(",
"List<ValidationMessage",
">",
"errors",
"Element",
"value",
"NodeStack",
"stack",
"List<Coding",
">",
"optionList",
")",
"{",
"String",
"system",
"=",
"value",
".",
"getNamedChildValue",
"(",
"system",
")",
... | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-dstu2.1/src/main/java/org/hl7/fhir/dstu2016may/validation/InstanceValidator.java#L1745-L1765 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/helper/JMResources.java | JMResources.getStringWithFilePathOrClasspath | public static String getStringWithFilePathOrClasspath(
String filePathOrClasspath, String charsetName) {
"""
Gets string with file path or classpath.
@param filePathOrClasspath the file path or classpath
@param charsetName the charset name
@return the string with file path or classpath
"""
return getStringAsOptWithFilePath(filePathOrClasspath, charsetName)
.orElseGet(
() -> getStringAsOptWithClasspath(
filePathOrClasspath,
charsetName).orElse(null));
} | java | public static String getStringWithFilePathOrClasspath(
String filePathOrClasspath, String charsetName) {
return getStringAsOptWithFilePath(filePathOrClasspath, charsetName)
.orElseGet(
() -> getStringAsOptWithClasspath(
filePathOrClasspath,
charsetName).orElse(null));
} | [
"public",
"static",
"String",
"getStringWithFilePathOrClasspath",
"(",
"String",
"filePathOrClasspath",
",",
"String",
"charsetName",
")",
"{",
"return",
"getStringAsOptWithFilePath",
"(",
"filePathOrClasspath",
",",
"charsetName",
")",
".",
"orElseGet",
"(",
"(",
")",
... | Gets string with file path or classpath.
@param filePathOrClasspath the file path or classpath
@param charsetName the charset name
@return the string with file path or classpath | [
"Gets",
"string",
"with",
"file",
"path",
"or",
"classpath",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMResources.java#L406-L413 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java | SpiderService.linkColumnName | public static String linkColumnName(FieldDefinition linkDef, String objID) {
"""
Return the column name used to store the given value for the given link. The column
name uses the format:
<pre>
~{link name}/{object ID}
</pre>
This method should be used for unsharded links or link values to that refer to an
object whose shard number is 0.
@param linkDef {@link FieldDefinition} of a link.
@param objID ID of an object referenced by the link.
@return Column name that is used to store a value for the given link and
object ID.
@see #shardedLinkTermRowKey(FieldDefinition, String, int)
"""
assert linkDef.isLinkField();
StringBuilder buffer = new StringBuilder();
buffer.append("~");
buffer.append(linkDef.getName());
buffer.append("/");
buffer.append(objID);
return buffer.toString();
} | java | public static String linkColumnName(FieldDefinition linkDef, String objID) {
assert linkDef.isLinkField();
StringBuilder buffer = new StringBuilder();
buffer.append("~");
buffer.append(linkDef.getName());
buffer.append("/");
buffer.append(objID);
return buffer.toString();
} | [
"public",
"static",
"String",
"linkColumnName",
"(",
"FieldDefinition",
"linkDef",
",",
"String",
"objID",
")",
"{",
"assert",
"linkDef",
".",
"isLinkField",
"(",
")",
";",
"StringBuilder",
"buffer",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"buffer",
".",
... | Return the column name used to store the given value for the given link. The column
name uses the format:
<pre>
~{link name}/{object ID}
</pre>
This method should be used for unsharded links or link values to that refer to an
object whose shard number is 0.
@param linkDef {@link FieldDefinition} of a link.
@param objID ID of an object referenced by the link.
@return Column name that is used to store a value for the given link and
object ID.
@see #shardedLinkTermRowKey(FieldDefinition, String, int) | [
"Return",
"the",
"column",
"name",
"used",
"to",
"store",
"the",
"given",
"value",
"for",
"the",
"given",
"link",
".",
"The",
"column",
"name",
"uses",
"the",
"format",
":",
"<pre",
">",
"~",
"{",
"link",
"name",
"}",
"/",
"{",
"object",
"ID",
"}",
... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java#L282-L290 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java | CacheConfigurationBuilder.withKeyCopier | public CacheConfigurationBuilder<K, V> withKeyCopier(Class<? extends Copier<K>> keyCopierClass) {
"""
Adds by-value semantic using the provided {@link Copier} class for the key on heap.
<p>
{@link Copier}s are what enable control of by-reference / by-value semantics for on-heap tier.
@param keyCopierClass the key copier class to use
@return a new builder with the added key copier
"""
return withCopier(new DefaultCopierConfiguration<>(requireNonNull(keyCopierClass, "Null key copier class"), DefaultCopierConfiguration.Type.KEY));
} | java | public CacheConfigurationBuilder<K, V> withKeyCopier(Class<? extends Copier<K>> keyCopierClass) {
return withCopier(new DefaultCopierConfiguration<>(requireNonNull(keyCopierClass, "Null key copier class"), DefaultCopierConfiguration.Type.KEY));
} | [
"public",
"CacheConfigurationBuilder",
"<",
"K",
",",
"V",
">",
"withKeyCopier",
"(",
"Class",
"<",
"?",
"extends",
"Copier",
"<",
"K",
">",
">",
"keyCopierClass",
")",
"{",
"return",
"withCopier",
"(",
"new",
"DefaultCopierConfiguration",
"<>",
"(",
"requireN... | Adds by-value semantic using the provided {@link Copier} class for the key on heap.
<p>
{@link Copier}s are what enable control of by-reference / by-value semantics for on-heap tier.
@param keyCopierClass the key copier class to use
@return a new builder with the added key copier | [
"Adds",
"by",
"-",
"value",
"semantic",
"using",
"the",
"provided",
"{",
"@link",
"Copier",
"}",
"class",
"for",
"the",
"key",
"on",
"heap",
".",
"<p",
">",
"{",
"@link",
"Copier",
"}",
"s",
"are",
"what",
"enable",
"control",
"of",
"by",
"-",
"refer... | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L420-L422 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/keyboard/ExtensionKeyboard.java | ExtensionKeyboard.hasSameDefaultAccelerator | private static boolean hasSameDefaultAccelerator(KeyboardMapping km, KeyStroke ks) {
"""
Tells whether or not the given keyboard mapping has the given default accelerator.
@param km the keyboard mapping to check.
@param ks the accelerator.
@return {@code true} if the keyboard mapping has the given default accelerator, {@code false} otherwise.
"""
KeyStroke kmKs = km.getDefaultKeyStroke();
if (kmKs == null) {
return false;
}
return kmKs.getKeyCode() == ks.getKeyCode() && kmKs.getModifiers() == ks.getModifiers();
} | java | private static boolean hasSameDefaultAccelerator(KeyboardMapping km, KeyStroke ks) {
KeyStroke kmKs = km.getDefaultKeyStroke();
if (kmKs == null) {
return false;
}
return kmKs.getKeyCode() == ks.getKeyCode() && kmKs.getModifiers() == ks.getModifiers();
} | [
"private",
"static",
"boolean",
"hasSameDefaultAccelerator",
"(",
"KeyboardMapping",
"km",
",",
"KeyStroke",
"ks",
")",
"{",
"KeyStroke",
"kmKs",
"=",
"km",
".",
"getDefaultKeyStroke",
"(",
")",
";",
"if",
"(",
"kmKs",
"==",
"null",
")",
"{",
"return",
"fals... | Tells whether or not the given keyboard mapping has the given default accelerator.
@param km the keyboard mapping to check.
@param ks the accelerator.
@return {@code true} if the keyboard mapping has the given default accelerator, {@code false} otherwise. | [
"Tells",
"whether",
"or",
"not",
"the",
"given",
"keyboard",
"mapping",
"has",
"the",
"given",
"default",
"accelerator",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/keyboard/ExtensionKeyboard.java#L163-L169 |
grails/grails-core | grails-core/src/main/groovy/grails/util/GrailsMetaClassUtils.java | GrailsMetaClassUtils.invokeMethodIfExists | public static Object invokeMethodIfExists(Object instance, String methodName, Object[] args) {
"""
Invokes a method if it exists otherwise returns null
@param instance The instance
@param methodName The method name
@param args The arguments
@return The result of the method call or null
"""
MetaClass metaClass = getMetaClass(instance);
List<MetaMethod> methodList = metaClass.respondsTo(instance, methodName, args);
if (methodList != null && !methodList.isEmpty()) {
return metaClass.invokeMethod(instance, methodName, args);
}
return null;
} | java | public static Object invokeMethodIfExists(Object instance, String methodName, Object[] args) {
MetaClass metaClass = getMetaClass(instance);
List<MetaMethod> methodList = metaClass.respondsTo(instance, methodName, args);
if (methodList != null && !methodList.isEmpty()) {
return metaClass.invokeMethod(instance, methodName, args);
}
return null;
} | [
"public",
"static",
"Object",
"invokeMethodIfExists",
"(",
"Object",
"instance",
",",
"String",
"methodName",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"MetaClass",
"metaClass",
"=",
"getMetaClass",
"(",
"instance",
")",
";",
"List",
"<",
"MetaMethod",
">",
... | Invokes a method if it exists otherwise returns null
@param instance The instance
@param methodName The method name
@param args The arguments
@return The result of the method call or null | [
"Invokes",
"a",
"method",
"if",
"it",
"exists",
"otherwise",
"returns",
"null"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsMetaClassUtils.java#L241-L248 |
libgdx/gdx-ai | gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Hide.java | Hide.getHidingPosition | protected T getHidingPosition (T obstaclePosition, float obstacleRadius, T targetPosition) {
"""
Given the position of a target and the position and radius of an obstacle, this method calculates a position
{@code distanceFromBoundary} away from the object's bounding radius and directly opposite the target. It does this by scaling
the normalized "to obstacle" vector by the required distance away from the center of the obstacle and then adding the result
to the obstacle's position.
@param obstaclePosition
@param obstacleRadius
@param targetPosition
@return the hiding position behind the obstacle.
"""
// Calculate how far away the agent is to be from the chosen
// obstacle's bounding radius
float distanceAway = obstacleRadius + distanceFromBoundary;
// Calculate the normalized vector toward the obstacle from the target
toObstacle.set(obstaclePosition).sub(targetPosition).nor();
// Scale it to size and add to the obstacle's position to get
// the hiding spot.
return toObstacle.scl(distanceAway).add(obstaclePosition);
} | java | protected T getHidingPosition (T obstaclePosition, float obstacleRadius, T targetPosition) {
// Calculate how far away the agent is to be from the chosen
// obstacle's bounding radius
float distanceAway = obstacleRadius + distanceFromBoundary;
// Calculate the normalized vector toward the obstacle from the target
toObstacle.set(obstaclePosition).sub(targetPosition).nor();
// Scale it to size and add to the obstacle's position to get
// the hiding spot.
return toObstacle.scl(distanceAway).add(obstaclePosition);
} | [
"protected",
"T",
"getHidingPosition",
"(",
"T",
"obstaclePosition",
",",
"float",
"obstacleRadius",
",",
"T",
"targetPosition",
")",
"{",
"// Calculate how far away the agent is to be from the chosen",
"// obstacle's bounding radius",
"float",
"distanceAway",
"=",
"obstacleRad... | Given the position of a target and the position and radius of an obstacle, this method calculates a position
{@code distanceFromBoundary} away from the object's bounding radius and directly opposite the target. It does this by scaling
the normalized "to obstacle" vector by the required distance away from the center of the obstacle and then adding the result
to the obstacle's position.
@param obstaclePosition
@param obstacleRadius
@param targetPosition
@return the hiding position behind the obstacle. | [
"Given",
"the",
"position",
"of",
"a",
"target",
"and",
"the",
"position",
"and",
"radius",
"of",
"an",
"obstacle",
"this",
"method",
"calculates",
"a",
"position",
"{"
] | train | https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/behaviors/Hide.java#L161-L172 |
JadiraOrg/jadira | cdt/src/main/java/org/jadira/cdt/exception/WrappedRuntimeException.java | WrappedRuntimeException.constructMessage | protected String constructMessage(String message, Throwable cause) {
"""
Constructs an exception String with the given message and incorporating the
causing exception
@param message The message
@param cause The causing exception
@return The exception String
"""
if (cause != null) {
StringBuilder strBuilder = new StringBuilder();
if (message != null) {
strBuilder.append(message).append(": ");
}
strBuilder.append("Wrapped exception is {").append(cause);
strBuilder.append("}");
return strBuilder.toString();
} else {
return message;
}
} | java | protected String constructMessage(String message, Throwable cause) {
if (cause != null) {
StringBuilder strBuilder = new StringBuilder();
if (message != null) {
strBuilder.append(message).append(": ");
}
strBuilder.append("Wrapped exception is {").append(cause);
strBuilder.append("}");
return strBuilder.toString();
} else {
return message;
}
} | [
"protected",
"String",
"constructMessage",
"(",
"String",
"message",
",",
"Throwable",
"cause",
")",
"{",
"if",
"(",
"cause",
"!=",
"null",
")",
"{",
"StringBuilder",
"strBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"message",
"!=",
"nu... | Constructs an exception String with the given message and incorporating the
causing exception
@param message The message
@param cause The causing exception
@return The exception String | [
"Constructs",
"an",
"exception",
"String",
"with",
"the",
"given",
"message",
"and",
"incorporating",
"the",
"causing",
"exception"
] | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cdt/src/main/java/org/jadira/cdt/exception/WrappedRuntimeException.java#L61-L79 |
line/armeria | examples/saml-service-provider/src/main/java/example/armeria/server/saml/sp/MyAuthHandler.java | MyAuthHandler.loginSucceeded | @Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpMessage req,
MessageContext<Response> message, @Nullable String sessionIndex,
@Nullable String relayState) {
"""
Invoked when the SAML authentication process is finished and a user is authenticated. You can get
information about the authenticated user from the {@link Response}, especially his or her login name.
In this example, an email address is used as a login name. The login name is transferred to a web
browser via {@code Set-Cookie} header.
"""
final String username =
getNameId(message.getMessage(), SamlNameIdFormat.EMAIL).map(NameIDType::getValue)
.orElse(null);
if (username == null) {
return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
"<html><body>Username is not found.</body></html>");
}
logger.info("{} user '{}' has been logged in.", ctx, username);
final Cookie cookie = new DefaultCookie("username", username);
cookie.setHttpOnly(true);
cookie.setDomain("localhost");
cookie.setMaxAge(60);
cookie.setPath("/");
return HttpResponse.of(
HttpHeaders.of(HttpStatus.OK)
.contentType(MediaType.HTML_UTF_8)
.add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie)),
HttpData.ofUtf8("<html><body onLoad=\"window.location.href='/welcome'\"></body></html>"));
} | java | @Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpMessage req,
MessageContext<Response> message, @Nullable String sessionIndex,
@Nullable String relayState) {
final String username =
getNameId(message.getMessage(), SamlNameIdFormat.EMAIL).map(NameIDType::getValue)
.orElse(null);
if (username == null) {
return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
"<html><body>Username is not found.</body></html>");
}
logger.info("{} user '{}' has been logged in.", ctx, username);
final Cookie cookie = new DefaultCookie("username", username);
cookie.setHttpOnly(true);
cookie.setDomain("localhost");
cookie.setMaxAge(60);
cookie.setPath("/");
return HttpResponse.of(
HttpHeaders.of(HttpStatus.OK)
.contentType(MediaType.HTML_UTF_8)
.add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.LAX.encode(cookie)),
HttpData.ofUtf8("<html><body onLoad=\"window.location.href='/welcome'\"></body></html>"));
} | [
"@",
"Override",
"public",
"HttpResponse",
"loginSucceeded",
"(",
"ServiceRequestContext",
"ctx",
",",
"AggregatedHttpMessage",
"req",
",",
"MessageContext",
"<",
"Response",
">",
"message",
",",
"@",
"Nullable",
"String",
"sessionIndex",
",",
"@",
"Nullable",
"Stri... | Invoked when the SAML authentication process is finished and a user is authenticated. You can get
information about the authenticated user from the {@link Response}, especially his or her login name.
In this example, an email address is used as a login name. The login name is transferred to a web
browser via {@code Set-Cookie} header. | [
"Invoked",
"when",
"the",
"SAML",
"authentication",
"process",
"is",
"finished",
"and",
"a",
"user",
"is",
"authenticated",
".",
"You",
"can",
"get",
"information",
"about",
"the",
"authenticated",
"user",
"from",
"the",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/examples/saml-service-provider/src/main/java/example/armeria/server/saml/sp/MyAuthHandler.java#L68-L92 |
threerings/gwt-utils | src/main/java/com/threerings/gwt/util/MessagesLookup.java | MessagesLookup.xlate | public String xlate (String compoundKey) {
"""
Translate a compound key/params string. The compoundKey is compatible with Narya's
MessageBundle, with the exception that qualified keys are not supported.
"""
// to be more efficient about creating unnecessary objects, check before splitting
int tidx = compoundKey.indexOf('|');
if (tidx == -1) {
return get(compoundKey);
} else {
String key = compoundKey.substring(0, tidx);
String[] args = MessageUtil.decompose(compoundKey.substring(tidx+1));
for (int ii = 0; ii < args.length; ii++) {
if (MessageUtil.isTainted(args[ii])) {
args[ii] = MessageUtil.untaint(args[ii]);
} else {
args[ii] = xlate(args[ii]);
}
}
return get(key, (Object[])args);
}
} | java | public String xlate (String compoundKey)
{
// to be more efficient about creating unnecessary objects, check before splitting
int tidx = compoundKey.indexOf('|');
if (tidx == -1) {
return get(compoundKey);
} else {
String key = compoundKey.substring(0, tidx);
String[] args = MessageUtil.decompose(compoundKey.substring(tidx+1));
for (int ii = 0; ii < args.length; ii++) {
if (MessageUtil.isTainted(args[ii])) {
args[ii] = MessageUtil.untaint(args[ii]);
} else {
args[ii] = xlate(args[ii]);
}
}
return get(key, (Object[])args);
}
} | [
"public",
"String",
"xlate",
"(",
"String",
"compoundKey",
")",
"{",
"// to be more efficient about creating unnecessary objects, check before splitting",
"int",
"tidx",
"=",
"compoundKey",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"tidx",
"==",
"-",
"1",
... | Translate a compound key/params string. The compoundKey is compatible with Narya's
MessageBundle, with the exception that qualified keys are not supported. | [
"Translate",
"a",
"compound",
"key",
"/",
"params",
"string",
".",
"The",
"compoundKey",
"is",
"compatible",
"with",
"Narya",
"s",
"MessageBundle",
"with",
"the",
"exception",
"that",
"qualified",
"keys",
"are",
"not",
"supported",
"."
] | train | https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/util/MessagesLookup.java#L41-L60 |
googleapis/google-http-java-client | google-http-client/src/main/java/com/google/api/client/util/Data.java | Data.resolveWildcardTypeOrTypeVariable | public static Type resolveWildcardTypeOrTypeVariable(List<Type> context, Type type) {
"""
Aggressively resolves the given type in such a way that the resolved type is not a wildcard
type or a type variable, returning {@code Object.class} if the type variable cannot be
resolved.
@param context context list, ordering from least specific to most specific type context, for
example container class and then its field
@param type type or {@code null} for {@code null} result
@return resolved type (which may be class, parameterized type, or generic array type, but not
wildcard type or type variable) or {@code null} for {@code null} input
"""
// first deal with a wildcard, e.g. ? extends Number
if (type instanceof WildcardType) {
type = Types.getBound((WildcardType) type);
}
// next deal with a type variable T
while (type instanceof TypeVariable<?>) {
// resolve the type variable
Type resolved = Types.resolveTypeVariable(context, (TypeVariable<?>) type);
if (resolved != null) {
type = resolved;
}
// if unable to fully resolve the type variable, use its bounds, e.g. T extends Number
if (type instanceof TypeVariable<?>) {
type = ((TypeVariable<?>) type).getBounds()[0];
}
// loop in case T extends U and U is also a type variable
}
return type;
} | java | public static Type resolveWildcardTypeOrTypeVariable(List<Type> context, Type type) {
// first deal with a wildcard, e.g. ? extends Number
if (type instanceof WildcardType) {
type = Types.getBound((WildcardType) type);
}
// next deal with a type variable T
while (type instanceof TypeVariable<?>) {
// resolve the type variable
Type resolved = Types.resolveTypeVariable(context, (TypeVariable<?>) type);
if (resolved != null) {
type = resolved;
}
// if unable to fully resolve the type variable, use its bounds, e.g. T extends Number
if (type instanceof TypeVariable<?>) {
type = ((TypeVariable<?>) type).getBounds()[0];
}
// loop in case T extends U and U is also a type variable
}
return type;
} | [
"public",
"static",
"Type",
"resolveWildcardTypeOrTypeVariable",
"(",
"List",
"<",
"Type",
">",
"context",
",",
"Type",
"type",
")",
"{",
"// first deal with a wildcard, e.g. ? extends Number",
"if",
"(",
"type",
"instanceof",
"WildcardType",
")",
"{",
"type",
"=",
... | Aggressively resolves the given type in such a way that the resolved type is not a wildcard
type or a type variable, returning {@code Object.class} if the type variable cannot be
resolved.
@param context context list, ordering from least specific to most specific type context, for
example container class and then its field
@param type type or {@code null} for {@code null} result
@return resolved type (which may be class, parameterized type, or generic array type, but not
wildcard type or type variable) or {@code null} for {@code null} input | [
"Aggressively",
"resolves",
"the",
"given",
"type",
"in",
"such",
"a",
"way",
"that",
"the",
"resolved",
"type",
"is",
"not",
"a",
"wildcard",
"type",
"or",
"a",
"type",
"variable",
"returning",
"{",
"@code",
"Object",
".",
"class",
"}",
"if",
"the",
"ty... | train | https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/util/Data.java#L543-L562 |
mangstadt/biweekly | src/main/java/biweekly/component/ICalComponent.java | ICalComponent.checkRequiredCardinality | protected void checkRequiredCardinality(List<ValidationWarning> warnings, Class<? extends ICalProperty>... classes) {
"""
Utility method for validating that there is exactly one instance of each
of the given properties.
@param warnings the list to add the warnings to
@param classes the properties to check
"""
for (Class<? extends ICalProperty> clazz : classes) {
List<? extends ICalProperty> props = getProperties(clazz);
if (props.isEmpty()) {
warnings.add(new ValidationWarning(2, clazz.getSimpleName()));
continue;
}
if (props.size() > 1) {
warnings.add(new ValidationWarning(3, clazz.getSimpleName()));
continue;
}
}
} | java | protected void checkRequiredCardinality(List<ValidationWarning> warnings, Class<? extends ICalProperty>... classes) {
for (Class<? extends ICalProperty> clazz : classes) {
List<? extends ICalProperty> props = getProperties(clazz);
if (props.isEmpty()) {
warnings.add(new ValidationWarning(2, clazz.getSimpleName()));
continue;
}
if (props.size() > 1) {
warnings.add(new ValidationWarning(3, clazz.getSimpleName()));
continue;
}
}
} | [
"protected",
"void",
"checkRequiredCardinality",
"(",
"List",
"<",
"ValidationWarning",
">",
"warnings",
",",
"Class",
"<",
"?",
"extends",
"ICalProperty",
">",
"...",
"classes",
")",
"{",
"for",
"(",
"Class",
"<",
"?",
"extends",
"ICalProperty",
">",
"clazz",... | Utility method for validating that there is exactly one instance of each
of the given properties.
@param warnings the list to add the warnings to
@param classes the properties to check | [
"Utility",
"method",
"for",
"validating",
"that",
"there",
"is",
"exactly",
"one",
"instance",
"of",
"each",
"of",
"the",
"given",
"properties",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/ICalComponent.java#L512-L526 |
lessthanoptimal/BoofCV | examples/src/main/java/boofcv/examples/segmentation/ExampleSegmentColor.java | ExampleSegmentColor.showSelectedColor | public static void showSelectedColor( String name , BufferedImage image , float hue , float saturation ) {
"""
Selectively displays only pixels which have a similar hue and saturation values to what is provided.
This is intended to be a simple example of color based segmentation. Color based segmentation can be done
in RGB color, but is more problematic due to it not being intensity invariant. More robust techniques
can use Gaussian models instead of a uniform distribution, as is done below.
"""
Planar<GrayF32> input = ConvertBufferedImage.convertFromPlanar(image,null,true,GrayF32.class);
Planar<GrayF32> hsv = input.createSameShape();
// Convert into HSV
ColorHsv.rgbToHsv(input,hsv);
// Euclidean distance squared threshold for deciding which pixels are members of the selected set
float maxDist2 = 0.4f*0.4f;
// Extract hue and saturation bands which are independent of intensity
GrayF32 H = hsv.getBand(0);
GrayF32 S = hsv.getBand(1);
// Adjust the relative importance of Hue and Saturation.
// Hue has a range of 0 to 2*PI and Saturation from 0 to 1.
float adjustUnits = (float)(Math.PI/2.0);
// step through each pixel and mark how close it is to the selected color
BufferedImage output = new BufferedImage(input.width,input.height,BufferedImage.TYPE_INT_RGB);
for( int y = 0; y < hsv.height; y++ ) {
for( int x = 0; x < hsv.width; x++ ) {
// Hue is an angle in radians, so simple subtraction doesn't work
float dh = UtilAngle.dist(H.unsafe_get(x,y),hue);
float ds = (S.unsafe_get(x,y)-saturation)*adjustUnits;
// this distance measure is a bit naive, but good enough for to demonstrate the concept
float dist2 = dh*dh + ds*ds;
if( dist2 <= maxDist2 ) {
output.setRGB(x,y,image.getRGB(x,y));
}
}
}
ShowImages.showWindow(output,"Showing "+name);
} | java | public static void showSelectedColor( String name , BufferedImage image , float hue , float saturation ) {
Planar<GrayF32> input = ConvertBufferedImage.convertFromPlanar(image,null,true,GrayF32.class);
Planar<GrayF32> hsv = input.createSameShape();
// Convert into HSV
ColorHsv.rgbToHsv(input,hsv);
// Euclidean distance squared threshold for deciding which pixels are members of the selected set
float maxDist2 = 0.4f*0.4f;
// Extract hue and saturation bands which are independent of intensity
GrayF32 H = hsv.getBand(0);
GrayF32 S = hsv.getBand(1);
// Adjust the relative importance of Hue and Saturation.
// Hue has a range of 0 to 2*PI and Saturation from 0 to 1.
float adjustUnits = (float)(Math.PI/2.0);
// step through each pixel and mark how close it is to the selected color
BufferedImage output = new BufferedImage(input.width,input.height,BufferedImage.TYPE_INT_RGB);
for( int y = 0; y < hsv.height; y++ ) {
for( int x = 0; x < hsv.width; x++ ) {
// Hue is an angle in radians, so simple subtraction doesn't work
float dh = UtilAngle.dist(H.unsafe_get(x,y),hue);
float ds = (S.unsafe_get(x,y)-saturation)*adjustUnits;
// this distance measure is a bit naive, but good enough for to demonstrate the concept
float dist2 = dh*dh + ds*ds;
if( dist2 <= maxDist2 ) {
output.setRGB(x,y,image.getRGB(x,y));
}
}
}
ShowImages.showWindow(output,"Showing "+name);
} | [
"public",
"static",
"void",
"showSelectedColor",
"(",
"String",
"name",
",",
"BufferedImage",
"image",
",",
"float",
"hue",
",",
"float",
"saturation",
")",
"{",
"Planar",
"<",
"GrayF32",
">",
"input",
"=",
"ConvertBufferedImage",
".",
"convertFromPlanar",
"(",
... | Selectively displays only pixels which have a similar hue and saturation values to what is provided.
This is intended to be a simple example of color based segmentation. Color based segmentation can be done
in RGB color, but is more problematic due to it not being intensity invariant. More robust techniques
can use Gaussian models instead of a uniform distribution, as is done below. | [
"Selectively",
"displays",
"only",
"pixels",
"which",
"have",
"a",
"similar",
"hue",
"and",
"saturation",
"values",
"to",
"what",
"is",
"provided",
".",
"This",
"is",
"intended",
"to",
"be",
"a",
"simple",
"example",
"of",
"color",
"based",
"segmentation",
"... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/segmentation/ExampleSegmentColor.java#L71-L106 |
deeplearning4j/deeplearning4j | datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkExport.java | SparkExport.exportStringLocal | public static void exportStringLocal(File outputFile, JavaRDD<String> data, int rngSeed) throws Exception {
"""
Another quick and dirty CSV export (local). Dumps all values into a single file
"""
List<String> linesList = data.collect(); //Requires all data in memory
if (!(linesList instanceof ArrayList))
linesList = new ArrayList<>(linesList);
Collections.shuffle(linesList, new Random(rngSeed));
FileUtils.writeLines(outputFile, linesList);
} | java | public static void exportStringLocal(File outputFile, JavaRDD<String> data, int rngSeed) throws Exception {
List<String> linesList = data.collect(); //Requires all data in memory
if (!(linesList instanceof ArrayList))
linesList = new ArrayList<>(linesList);
Collections.shuffle(linesList, new Random(rngSeed));
FileUtils.writeLines(outputFile, linesList);
} | [
"public",
"static",
"void",
"exportStringLocal",
"(",
"File",
"outputFile",
",",
"JavaRDD",
"<",
"String",
">",
"data",
",",
"int",
"rngSeed",
")",
"throws",
"Exception",
"{",
"List",
"<",
"String",
">",
"linesList",
"=",
"data",
".",
"collect",
"(",
")",
... | Another quick and dirty CSV export (local). Dumps all values into a single file | [
"Another",
"quick",
"and",
"dirty",
"CSV",
"export",
"(",
"local",
")",
".",
"Dumps",
"all",
"values",
"into",
"a",
"single",
"file"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkExport.java#L153-L160 |
pressgang-ccms/PressGangCCMSContentSpec | src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java | EntityUtilities.findLocaleFromString | public static LocaleWrapper findLocaleFromString(final CollectionWrapper<LocaleWrapper> locales, final String localeString) {
"""
Finds the matching locale entity from a locale string.
@param localeProvider
@param localeString
@return
"""
if (localeString == null) return null;
for (final LocaleWrapper locale : locales.getItems()) {
if (localeString.equals(locale.getValue())) {
return locale;
}
}
return null;
} | java | public static LocaleWrapper findLocaleFromString(final CollectionWrapper<LocaleWrapper> locales, final String localeString) {
if (localeString == null) return null;
for (final LocaleWrapper locale : locales.getItems()) {
if (localeString.equals(locale.getValue())) {
return locale;
}
}
return null;
} | [
"public",
"static",
"LocaleWrapper",
"findLocaleFromString",
"(",
"final",
"CollectionWrapper",
"<",
"LocaleWrapper",
">",
"locales",
",",
"final",
"String",
"localeString",
")",
"{",
"if",
"(",
"localeString",
"==",
"null",
")",
"return",
"null",
";",
"for",
"(... | Finds the matching locale entity from a locale string.
@param localeProvider
@param localeString
@return | [
"Finds",
"the",
"matching",
"locale",
"entity",
"from",
"a",
"locale",
"string",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java#L452-L462 |
networknt/light-4j | dump/src/main/java/com/networknt/dump/RootDumper.java | RootDumper.dumpResponse | public void dumpResponse(Map<String, Object> result) {
"""
create dumpers that can dump http response info, and put http response info into Map<String, Object> result
@param result a Map<String, Object> to put http response info to
"""
if(!dumpConfig.isResponseEnabled()) { return; }
Map<String, Object> responseResult = new LinkedHashMap<>();
for(IResponseDumpable dumper: dumperFactory.createResponseDumpers(dumpConfig, exchange)) {
if (dumper.isApplicableForResponse()) {
dumper.dumpResponse(responseResult);
}
}
result.put(DumpConstants.RESPONSE, responseResult);
} | java | public void dumpResponse(Map<String, Object> result) {
if(!dumpConfig.isResponseEnabled()) { return; }
Map<String, Object> responseResult = new LinkedHashMap<>();
for(IResponseDumpable dumper: dumperFactory.createResponseDumpers(dumpConfig, exchange)) {
if (dumper.isApplicableForResponse()) {
dumper.dumpResponse(responseResult);
}
}
result.put(DumpConstants.RESPONSE, responseResult);
} | [
"public",
"void",
"dumpResponse",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"result",
")",
"{",
"if",
"(",
"!",
"dumpConfig",
".",
"isResponseEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"Map",
"<",
"String",
",",
"Object",
">",
"responseResu... | create dumpers that can dump http response info, and put http response info into Map<String, Object> result
@param result a Map<String, Object> to put http response info to | [
"create",
"dumpers",
"that",
"can",
"dump",
"http",
"response",
"info",
"and",
"put",
"http",
"response",
"info",
"into",
"Map<String",
"Object",
">",
"result"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/dump/src/main/java/com/networknt/dump/RootDumper.java#L59-L69 |
geomajas/geomajas-project-server | common-servlet/src/main/java/org/geomajas/servlet/CacheFilter.java | CacheFilter.checkPrefixes | public boolean checkPrefixes(String uri, String[] patterns) {
"""
Check whether the URL start with one of the given prefixes.
@param uri URI
@param patterns possible prefixes
@return true when URL starts with one of the prefixes
"""
for (String pattern : patterns) {
if (pattern.length() > 0) {
if (uri.startsWith(pattern)) {
return true;
}
}
}
return false;
} | java | public boolean checkPrefixes(String uri, String[] patterns) {
for (String pattern : patterns) {
if (pattern.length() > 0) {
if (uri.startsWith(pattern)) {
return true;
}
}
}
return false;
} | [
"public",
"boolean",
"checkPrefixes",
"(",
"String",
"uri",
",",
"String",
"[",
"]",
"patterns",
")",
"{",
"for",
"(",
"String",
"pattern",
":",
"patterns",
")",
"{",
"if",
"(",
"pattern",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"if",
"(",
"ur... | Check whether the URL start with one of the given prefixes.
@param uri URI
@param patterns possible prefixes
@return true when URL starts with one of the prefixes | [
"Check",
"whether",
"the",
"URL",
"start",
"with",
"one",
"of",
"the",
"given",
"prefixes",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/common-servlet/src/main/java/org/geomajas/servlet/CacheFilter.java#L281-L290 |
killme2008/xmemcached | src/main/java/net/rubyeye/xmemcached/XMemcachedClient.java | XMemcachedClient.addServer | public final void addServer(final String server, final int port, int weight) throws IOException {
"""
add a memcached server to MemcachedClient
@param server
@param port
@param weight
@throws IOException
"""
if (weight <= 0) {
throw new IllegalArgumentException("weight<=0");
}
this.checkServerPort(server, port);
this.connect(new InetSocketAddressWrapper(this.newSocketAddress(server, port),
this.serverOrderCount.incrementAndGet(), weight, null));
} | java | public final void addServer(final String server, final int port, int weight) throws IOException {
if (weight <= 0) {
throw new IllegalArgumentException("weight<=0");
}
this.checkServerPort(server, port);
this.connect(new InetSocketAddressWrapper(this.newSocketAddress(server, port),
this.serverOrderCount.incrementAndGet(), weight, null));
} | [
"public",
"final",
"void",
"addServer",
"(",
"final",
"String",
"server",
",",
"final",
"int",
"port",
",",
"int",
"weight",
")",
"throws",
"IOException",
"{",
"if",
"(",
"weight",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"we... | add a memcached server to MemcachedClient
@param server
@param port
@param weight
@throws IOException | [
"add",
"a",
"memcached",
"server",
"to",
"MemcachedClient"
] | train | https://github.com/killme2008/xmemcached/blob/66150915938813b3e3413de1d7b43b6ff9b1478d/src/main/java/net/rubyeye/xmemcached/XMemcachedClient.java#L391-L398 |
nabedge/mixer2 | src/main/java/org/mixer2/xhtml/AbstractJaxb.java | AbstractJaxb.insertAfterId | public boolean insertAfterId(String id, String insString)
throws TagTypeUnmatchException {
"""
<p>insert String after the element having specified id attribute</p>
@param id
@param insString
@return true if success to insert. if no hit, return false.
@throws TagTypeUnmatchException
"""
return InsertByIdUtil.insertAfterId(id, insString, this);
} | java | public boolean insertAfterId(String id, String insString)
throws TagTypeUnmatchException {
return InsertByIdUtil.insertAfterId(id, insString, this);
} | [
"public",
"boolean",
"insertAfterId",
"(",
"String",
"id",
",",
"String",
"insString",
")",
"throws",
"TagTypeUnmatchException",
"{",
"return",
"InsertByIdUtil",
".",
"insertAfterId",
"(",
"id",
",",
"insString",
",",
"this",
")",
";",
"}"
] | <p>insert String after the element having specified id attribute</p>
@param id
@param insString
@return true if success to insert. if no hit, return false.
@throws TagTypeUnmatchException | [
"<p",
">",
"insert",
"String",
"after",
"the",
"element",
"having",
"specified",
"id",
"attribute<",
"/",
"p",
">"
] | train | https://github.com/nabedge/mixer2/blob/8c2db27cfcd65bf0b1e0242ef9362ebd8033777c/src/main/java/org/mixer2/xhtml/AbstractJaxb.java#L502-L505 |
molgenis/molgenis | molgenis-semantic-mapper/src/main/java/org/molgenis/semanticmapper/repository/impl/MappingTargetRepositoryImpl.java | MappingTargetRepositoryImpl.toMappingTarget | private MappingTarget toMappingTarget(Entity mappingTargetEntity) {
"""
Creates a fully reconstructed MappingProject from an Entity retrieved from the repository.
@param mappingTargetEntity Entity with {@link MappingProjectMetadata} metadata
@return fully reconstructed MappingProject
"""
List<EntityMapping> entityMappings = Collections.emptyList();
String identifier = mappingTargetEntity.getString(MappingTargetMetadata.IDENTIFIER);
if (!dataService.hasRepository(mappingTargetEntity.getString(MappingTargetMetadata.TARGET))) {
return null;
}
EntityType target =
dataService.getEntityType(mappingTargetEntity.getString(MappingTargetMetadata.TARGET));
if (mappingTargetEntity.getEntities(MappingTargetMetadata.ENTITY_MAPPINGS) != null) {
List<Entity> entityMappingEntities =
Lists.newArrayList(
mappingTargetEntity.getEntities(MappingTargetMetadata.ENTITY_MAPPINGS));
entityMappings = entityMappingRepository.toEntityMappings(entityMappingEntities);
}
return new MappingTarget(identifier, target, entityMappings);
} | java | private MappingTarget toMappingTarget(Entity mappingTargetEntity) {
List<EntityMapping> entityMappings = Collections.emptyList();
String identifier = mappingTargetEntity.getString(MappingTargetMetadata.IDENTIFIER);
if (!dataService.hasRepository(mappingTargetEntity.getString(MappingTargetMetadata.TARGET))) {
return null;
}
EntityType target =
dataService.getEntityType(mappingTargetEntity.getString(MappingTargetMetadata.TARGET));
if (mappingTargetEntity.getEntities(MappingTargetMetadata.ENTITY_MAPPINGS) != null) {
List<Entity> entityMappingEntities =
Lists.newArrayList(
mappingTargetEntity.getEntities(MappingTargetMetadata.ENTITY_MAPPINGS));
entityMappings = entityMappingRepository.toEntityMappings(entityMappingEntities);
}
return new MappingTarget(identifier, target, entityMappings);
} | [
"private",
"MappingTarget",
"toMappingTarget",
"(",
"Entity",
"mappingTargetEntity",
")",
"{",
"List",
"<",
"EntityMapping",
">",
"entityMappings",
"=",
"Collections",
".",
"emptyList",
"(",
")",
";",
"String",
"identifier",
"=",
"mappingTargetEntity",
".",
"getStri... | Creates a fully reconstructed MappingProject from an Entity retrieved from the repository.
@param mappingTargetEntity Entity with {@link MappingProjectMetadata} metadata
@return fully reconstructed MappingProject | [
"Creates",
"a",
"fully",
"reconstructed",
"MappingProject",
"from",
"an",
"Entity",
"retrieved",
"from",
"the",
"repository",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-semantic-mapper/src/main/java/org/molgenis/semanticmapper/repository/impl/MappingTargetRepositoryImpl.java#L79-L98 |
Azure/azure-sdk-for-java | locks/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/locks/v2016_09_01/implementation/ManagementLocksInner.java | ManagementLocksInner.getByScopeAsync | public Observable<ManagementLockObjectInner> getByScopeAsync(String scope, String lockName) {
"""
Get a management lock by scope.
@param scope The scope for the lock.
@param lockName The name of lock.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ManagementLockObjectInner object
"""
return getByScopeWithServiceResponseAsync(scope, lockName).map(new Func1<ServiceResponse<ManagementLockObjectInner>, ManagementLockObjectInner>() {
@Override
public ManagementLockObjectInner call(ServiceResponse<ManagementLockObjectInner> response) {
return response.body();
}
});
} | java | public Observable<ManagementLockObjectInner> getByScopeAsync(String scope, String lockName) {
return getByScopeWithServiceResponseAsync(scope, lockName).map(new Func1<ServiceResponse<ManagementLockObjectInner>, ManagementLockObjectInner>() {
@Override
public ManagementLockObjectInner call(ServiceResponse<ManagementLockObjectInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ManagementLockObjectInner",
">",
"getByScopeAsync",
"(",
"String",
"scope",
",",
"String",
"lockName",
")",
"{",
"return",
"getByScopeWithServiceResponseAsync",
"(",
"scope",
",",
"lockName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",... | Get a management lock by scope.
@param scope The scope for the lock.
@param lockName The name of lock.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ManagementLockObjectInner object | [
"Get",
"a",
"management",
"lock",
"by",
"scope",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/locks/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/locks/v2016_09_01/implementation/ManagementLocksInner.java#L625-L632 |
joniles/mpxj | src/main/java/net/sf/mpxj/ProjectProperties.java | ProjectProperties.set | private void set(FieldType field, boolean value) {
"""
This method inserts a name value pair into internal storage.
@param field task field
@param value attribute value
"""
set(field, (value ? Boolean.TRUE : Boolean.FALSE));
} | java | private void set(FieldType field, boolean value)
{
set(field, (value ? Boolean.TRUE : Boolean.FALSE));
} | [
"private",
"void",
"set",
"(",
"FieldType",
"field",
",",
"boolean",
"value",
")",
"{",
"set",
"(",
"field",
",",
"(",
"value",
"?",
"Boolean",
".",
"TRUE",
":",
"Boolean",
".",
"FALSE",
")",
")",
";",
"}"
] | This method inserts a name value pair into internal storage.
@param field task field
@param value attribute value | [
"This",
"method",
"inserts",
"a",
"name",
"value",
"pair",
"into",
"internal",
"storage",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectProperties.java#L2730-L2733 |
threerings/nenya | core/src/main/java/com/threerings/media/sprite/FadableImageSprite.java | FadableImageSprite.moveAndFadeIn | public void moveAndFadeIn (Path path, long pathDuration, float fadePortion) {
"""
Puts this sprite on the specified path and fades it in over the specified duration.
@param path the path to move along
@param fadePortion the portion of time to spend fading in, from 0.0f (no time) to 1.0f (the
entire time)
"""
move(path);
setAlpha(0.0f);
_fadeInDuration = (long)(pathDuration * fadePortion);
} | java | public void moveAndFadeIn (Path path, long pathDuration, float fadePortion)
{
move(path);
setAlpha(0.0f);
_fadeInDuration = (long)(pathDuration * fadePortion);
} | [
"public",
"void",
"moveAndFadeIn",
"(",
"Path",
"path",
",",
"long",
"pathDuration",
",",
"float",
"fadePortion",
")",
"{",
"move",
"(",
"path",
")",
";",
"setAlpha",
"(",
"0.0f",
")",
";",
"_fadeInDuration",
"=",
"(",
"long",
")",
"(",
"pathDuration",
"... | Puts this sprite on the specified path and fades it in over the specified duration.
@param path the path to move along
@param fadePortion the portion of time to spend fading in, from 0.0f (no time) to 1.0f (the
entire time) | [
"Puts",
"this",
"sprite",
"on",
"the",
"specified",
"path",
"and",
"fades",
"it",
"in",
"over",
"the",
"specified",
"duration",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/sprite/FadableImageSprite.java#L89-L96 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java | AdHocCommandManager.registerCommand | public void registerCommand(String node, final String name, LocalCommandFactory factory) {
"""
Registers a new command with this command manager, which is related to a
connection. The <tt>node</tt> is an unique identifier of that
command for the connection related to this command manager. The <tt>name</tt>
is the human readable name of the command. The <tt>factory</tt> generates
new instances of the command.
@param node the unique identifier of the command.
@param name the human readable name of the command.
@param factory a factory to create new instances of the command.
"""
AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection().getUser(), factory);
commands.put(node, commandInfo);
// Set the NodeInformationProvider that will provide information about
// the added command
serviceDiscoveryManager.setNodeInformationProvider(node,
new AbstractNodeInformationProvider() {
@Override
public List<String> getNodeFeatures() {
List<String> answer = new ArrayList<>();
answer.add(NAMESPACE);
// TODO: check if this service is provided by the
// TODO: current connection.
answer.add("jabber:x:data");
return answer;
}
@Override
public List<DiscoverInfo.Identity> getNodeIdentities() {
List<DiscoverInfo.Identity> answer = new ArrayList<>();
DiscoverInfo.Identity identity = new DiscoverInfo.Identity(
"automation", name, "command-node");
answer.add(identity);
return answer;
}
});
} | java | public void registerCommand(String node, final String name, LocalCommandFactory factory) {
AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection().getUser(), factory);
commands.put(node, commandInfo);
// Set the NodeInformationProvider that will provide information about
// the added command
serviceDiscoveryManager.setNodeInformationProvider(node,
new AbstractNodeInformationProvider() {
@Override
public List<String> getNodeFeatures() {
List<String> answer = new ArrayList<>();
answer.add(NAMESPACE);
// TODO: check if this service is provided by the
// TODO: current connection.
answer.add("jabber:x:data");
return answer;
}
@Override
public List<DiscoverInfo.Identity> getNodeIdentities() {
List<DiscoverInfo.Identity> answer = new ArrayList<>();
DiscoverInfo.Identity identity = new DiscoverInfo.Identity(
"automation", name, "command-node");
answer.add(identity);
return answer;
}
});
} | [
"public",
"void",
"registerCommand",
"(",
"String",
"node",
",",
"final",
"String",
"name",
",",
"LocalCommandFactory",
"factory",
")",
"{",
"AdHocCommandInfo",
"commandInfo",
"=",
"new",
"AdHocCommandInfo",
"(",
"node",
",",
"name",
",",
"connection",
"(",
")",... | Registers a new command with this command manager, which is related to a
connection. The <tt>node</tt> is an unique identifier of that
command for the connection related to this command manager. The <tt>name</tt>
is the human readable name of the command. The <tt>factory</tt> generates
new instances of the command.
@param node the unique identifier of the command.
@param name the human readable name of the command.
@param factory a factory to create new instances of the command. | [
"Registers",
"a",
"new",
"command",
"with",
"this",
"command",
"manager",
"which",
"is",
"related",
"to",
"a",
"connection",
".",
"The",
"<tt",
">",
"node<",
"/",
"tt",
">",
"is",
"an",
"unique",
"identifier",
"of",
"that",
"command",
"for",
"the",
"conn... | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java#L225-L251 |
brettwooldridge/HikariCP | src/main/java/com/zaxxer/hikari/pool/PoolBase.java | PoolBase.executeSql | private void executeSql(final Connection connection, final String sql, final boolean isCommit) throws SQLException {
"""
Execute the user-specified init SQL.
@param connection the connection to initialize
@param sql the SQL to execute
@param isCommit whether to commit the SQL after execution or not
@throws SQLException throws if the init SQL execution fails
"""
if (sql != null) {
try (Statement statement = connection.createStatement()) {
// connection was created a few milliseconds before, so set query timeout is omitted (we assume it will succeed)
statement.execute(sql);
}
if (isIsolateInternalQueries && !isAutoCommit) {
if (isCommit) {
connection.commit();
}
else {
connection.rollback();
}
}
}
} | java | private void executeSql(final Connection connection, final String sql, final boolean isCommit) throws SQLException
{
if (sql != null) {
try (Statement statement = connection.createStatement()) {
// connection was created a few milliseconds before, so set query timeout is omitted (we assume it will succeed)
statement.execute(sql);
}
if (isIsolateInternalQueries && !isAutoCommit) {
if (isCommit) {
connection.commit();
}
else {
connection.rollback();
}
}
}
} | [
"private",
"void",
"executeSql",
"(",
"final",
"Connection",
"connection",
",",
"final",
"String",
"sql",
",",
"final",
"boolean",
"isCommit",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"sql",
"!=",
"null",
")",
"{",
"try",
"(",
"Statement",
"statement",... | Execute the user-specified init SQL.
@param connection the connection to initialize
@param sql the SQL to execute
@param isCommit whether to commit the SQL after execution or not
@throws SQLException throws if the init SQL execution fails | [
"Execute",
"the",
"user",
"-",
"specified",
"init",
"SQL",
"."
] | train | https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/pool/PoolBase.java#L564-L581 |
spotify/helios | helios-client/src/main/java/com/spotify/helios/common/JobValidator.java | JobValidator.validateJobImage | private Set<String> validateJobImage(final String image) {
"""
Validate the Job's image by checking it's not null or empty and has the right format.
@param image The image String
@return A set of error Strings
"""
final Set<String> errors = Sets.newHashSet();
if (image == null) {
errors.add("Image was not specified.");
} else {
// Validate image name
validateImageReference(image, errors);
}
return errors;
} | java | private Set<String> validateJobImage(final String image) {
final Set<String> errors = Sets.newHashSet();
if (image == null) {
errors.add("Image was not specified.");
} else {
// Validate image name
validateImageReference(image, errors);
}
return errors;
} | [
"private",
"Set",
"<",
"String",
">",
"validateJobImage",
"(",
"final",
"String",
"image",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"errors",
"=",
"Sets",
".",
"newHashSet",
"(",
")",
";",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"errors",
".... | Validate the Job's image by checking it's not null or empty and has the right format.
@param image The image String
@return A set of error Strings | [
"Validate",
"the",
"Job",
"s",
"image",
"by",
"checking",
"it",
"s",
"not",
"null",
"or",
"empty",
"and",
"has",
"the",
"right",
"format",
"."
] | train | https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-client/src/main/java/com/spotify/helios/common/JobValidator.java#L235-L246 |
gosu-lang/gosu-lang | gosu-core-api/src/main/java/gw/date/GosuDateUtil.java | GosuDateUtil.addWeeks | public static Date addWeeks(Date date, int iWeeks) {
"""
Adds the specified (signed) amount of weeks to the given date. For
example, to subtract 5 weeks from the current date, you can
achieve it by calling: <code>addWeeks(Date, -5)</code>.
@param date The time.
@param iWeeks The amount of weeks to add.
@return A new date with the weeks added.
"""
Calendar dateTime = dateToCalendar(date);
dateTime.add(Calendar.WEEK_OF_YEAR, iWeeks);
return dateTime.getTime();
} | java | public static Date addWeeks(Date date, int iWeeks) {
Calendar dateTime = dateToCalendar(date);
dateTime.add(Calendar.WEEK_OF_YEAR, iWeeks);
return dateTime.getTime();
} | [
"public",
"static",
"Date",
"addWeeks",
"(",
"Date",
"date",
",",
"int",
"iWeeks",
")",
"{",
"Calendar",
"dateTime",
"=",
"dateToCalendar",
"(",
"date",
")",
";",
"dateTime",
".",
"add",
"(",
"Calendar",
".",
"WEEK_OF_YEAR",
",",
"iWeeks",
")",
";",
"ret... | Adds the specified (signed) amount of weeks to the given date. For
example, to subtract 5 weeks from the current date, you can
achieve it by calling: <code>addWeeks(Date, -5)</code>.
@param date The time.
@param iWeeks The amount of weeks to add.
@return A new date with the weeks added. | [
"Adds",
"the",
"specified",
"(",
"signed",
")",
"amount",
"of",
"weeks",
"to",
"the",
"given",
"date",
".",
"For",
"example",
"to",
"subtract",
"5",
"weeks",
"from",
"the",
"current",
"date",
"you",
"can",
"achieve",
"it",
"by",
"calling",
":",
"<code",
... | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/date/GosuDateUtil.java#L93-L97 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/Force.java | Force.addDirection | public void addDirection(double extrp, double fh, double fv) {
"""
Increase forces with input value.
@param extrp The extrapolation value.
@param fh The added horizontal force.
@param fv The added vertical force.
"""
fhLast = fh;
fvLast = fv;
this.fh += fh * extrp;
this.fv += fv * extrp;
fixForce();
} | java | public void addDirection(double extrp, double fh, double fv)
{
fhLast = fh;
fvLast = fv;
this.fh += fh * extrp;
this.fv += fv * extrp;
fixForce();
} | [
"public",
"void",
"addDirection",
"(",
"double",
"extrp",
",",
"double",
"fh",
",",
"double",
"fv",
")",
"{",
"fhLast",
"=",
"fh",
";",
"fvLast",
"=",
"fv",
";",
"this",
".",
"fh",
"+=",
"fh",
"*",
"extrp",
";",
"this",
".",
"fv",
"+=",
"fv",
"*"... | Increase forces with input value.
@param extrp The extrapolation value.
@param fh The added horizontal force.
@param fv The added vertical force. | [
"Increase",
"forces",
"with",
"input",
"value",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Force.java#L206-L213 |
tanhaichao/leopard-lang | leopard-servlet/src/main/java/io/leopard/web/servlet/CookieUtil.java | CookieUtil.setCookie | public static void setCookie(String name, String value, int maxAge, boolean httpOnly, HttpServletRequest request, HttpServletResponse response) {
"""
设置cookie</br>
@param name cookie名称
@param value cookie值
@param maxAge 最大生存时间
@param httpOnly cookie的路径
@param request http请求
@param response http响应
"""
String domain = request.getServerName();
// String domain = serverName;
setCookie(name, value, maxAge, httpOnly, domain, response);
} | java | public static void setCookie(String name, String value, int maxAge, boolean httpOnly, HttpServletRequest request, HttpServletResponse response) {
String domain = request.getServerName();
// String domain = serverName;
setCookie(name, value, maxAge, httpOnly, domain, response);
} | [
"public",
"static",
"void",
"setCookie",
"(",
"String",
"name",
",",
"String",
"value",
",",
"int",
"maxAge",
",",
"boolean",
"httpOnly",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"String",
"domain",
"=",
"request",
... | 设置cookie</br>
@param name cookie名称
@param value cookie值
@param maxAge 最大生存时间
@param httpOnly cookie的路径
@param request http请求
@param response http响应 | [
"设置cookie<",
"/",
"br",
">"
] | train | https://github.com/tanhaichao/leopard-lang/blob/8ab110f6ca4ea84484817a3d752253ac69ea268b/leopard-servlet/src/main/java/io/leopard/web/servlet/CookieUtil.java#L64-L68 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/WaldWolfowitz.java | WaldWolfowitz.checkCriticalValue | private static boolean checkCriticalValue(double score, int n1, int n2, double aLevel) {
"""
Checks the Critical Value to determine if the Hypothesis should be rejected.
@param score
@param n1
@param n2
@param aLevel
@return
"""
boolean rejected=false;
int n=n1+n2;
if(n1<=20 && n2<=20 && aLevel==0.05) { //This works only if we have low values on n1 and n2 and for specific levels of a
int key1=Math.max(n1,n2); //put the maximum in the first key (this is due to the way the table is contructed)
int key2=Math.min(n1,n2); //put the minimum in the second key
Object value = CRITICAL_VALUES.get2d(key1, key2);
if(value!=null) { //check if we have the value in the table
String[] lowuplimit=String.valueOf(value).split(",");
int low = Integer.parseInt(lowuplimit[0]);
int high = n;
if(lowuplimit.length==2) {
high = Integer.parseInt(lowuplimit[1]);
}
if(score<=low || score>=high) { //if the score is outside the confidence intervals reject null hypothesis
rejected=true;
}
return rejected;
}
}
//Estimate the mean and Variance under Null Hypothesis
double mean= 2.0*n1*n2/((double)n1+n2) +1.0;
double variance = 2.0*n1*n2*(2.0*n1*n2 - n1 - n2)/(n*n*(n-1.0));
//Normalize U
double z=(score-mean)/Math.sqrt(variance);
//Get its pvalue
double pvalue=ContinuousDistributions.gaussCdf(z);
double a=aLevel/2; //always tailed test, so split the statistical significance in half
if(pvalue<=a || pvalue>=(1-a)) {
rejected=true;
}
return rejected;
} | java | private static boolean checkCriticalValue(double score, int n1, int n2, double aLevel) {
boolean rejected=false;
int n=n1+n2;
if(n1<=20 && n2<=20 && aLevel==0.05) { //This works only if we have low values on n1 and n2 and for specific levels of a
int key1=Math.max(n1,n2); //put the maximum in the first key (this is due to the way the table is contructed)
int key2=Math.min(n1,n2); //put the minimum in the second key
Object value = CRITICAL_VALUES.get2d(key1, key2);
if(value!=null) { //check if we have the value in the table
String[] lowuplimit=String.valueOf(value).split(",");
int low = Integer.parseInt(lowuplimit[0]);
int high = n;
if(lowuplimit.length==2) {
high = Integer.parseInt(lowuplimit[1]);
}
if(score<=low || score>=high) { //if the score is outside the confidence intervals reject null hypothesis
rejected=true;
}
return rejected;
}
}
//Estimate the mean and Variance under Null Hypothesis
double mean= 2.0*n1*n2/((double)n1+n2) +1.0;
double variance = 2.0*n1*n2*(2.0*n1*n2 - n1 - n2)/(n*n*(n-1.0));
//Normalize U
double z=(score-mean)/Math.sqrt(variance);
//Get its pvalue
double pvalue=ContinuousDistributions.gaussCdf(z);
double a=aLevel/2; //always tailed test, so split the statistical significance in half
if(pvalue<=a || pvalue>=(1-a)) {
rejected=true;
}
return rejected;
} | [
"private",
"static",
"boolean",
"checkCriticalValue",
"(",
"double",
"score",
",",
"int",
"n1",
",",
"int",
"n2",
",",
"double",
"aLevel",
")",
"{",
"boolean",
"rejected",
"=",
"false",
";",
"int",
"n",
"=",
"n1",
"+",
"n2",
";",
"if",
"(",
"n1",
"<=... | Checks the Critical Value to determine if the Hypothesis should be rejected.
@param score
@param n1
@param n2
@param aLevel
@return | [
"Checks",
"the",
"Critical",
"Value",
"to",
"determine",
"if",
"the",
"Hypothesis",
"should",
"be",
"rejected",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/WaldWolfowitz.java#L107-L152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.