repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 218 | func_name stringlengths 5 140 | whole_func_string stringlengths 79 3.99k | language stringclasses 1
value | func_code_string stringlengths 79 3.99k | func_code_tokens listlengths 20 624 | func_documentation_string stringlengths 61 1.96k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 107 339 |
|---|---|---|---|---|---|---|---|---|---|---|
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/GlobalizationPreferences.java | GlobalizationPreferences.setBreakIterator | public GlobalizationPreferences setBreakIterator(int type, BreakIterator iterator) {
if (type < BI_CHARACTER || type >= BI_LIMIT) {
throw new IllegalArgumentException("Illegal break iterator type");
}
if (isFrozen()) {
throw new UnsupportedOperationException("Attempt to modify immutable object");
}
if (breakIterators == null)
breakIterators = new BreakIterator[BI_LIMIT];
breakIterators[type] = (BreakIterator) iterator.clone(); // clone for safety
return this;
} | java | public GlobalizationPreferences setBreakIterator(int type, BreakIterator iterator) {
if (type < BI_CHARACTER || type >= BI_LIMIT) {
throw new IllegalArgumentException("Illegal break iterator type");
}
if (isFrozen()) {
throw new UnsupportedOperationException("Attempt to modify immutable object");
}
if (breakIterators == null)
breakIterators = new BreakIterator[BI_LIMIT];
breakIterators[type] = (BreakIterator) iterator.clone(); // clone for safety
return this;
} | [
"public",
"GlobalizationPreferences",
"setBreakIterator",
"(",
"int",
"type",
",",
"BreakIterator",
"iterator",
")",
"{",
"if",
"(",
"type",
"<",
"BI_CHARACTER",
"||",
"type",
">=",
"BI_LIMIT",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Illegal ... | Explicitly set the break iterator for this object.
@param type break type - BI_CHARACTER or BI_WORD, BI_LINE, BI_SENTENCE, BI_TITLE
@param iterator a break iterator
@return this, for chaining
@hide draft / provisional / internal are hidden on Android | [
"Explicitly",
"set",
"the",
"break",
"iterator",
"for",
"this",
"object",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/GlobalizationPreferences.java#L514-L525 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/guid/Guid.java | Guid.append | public Guid append(byte[]... byteArrays) throws IOException {
if (byteArrays == null || byteArrays.length == 0) {
return this;
}
return fromByteArrays(ArrayUtils.add(byteArrays, this.sha));
} | java | public Guid append(byte[]... byteArrays) throws IOException {
if (byteArrays == null || byteArrays.length == 0) {
return this;
}
return fromByteArrays(ArrayUtils.add(byteArrays, this.sha));
} | [
"public",
"Guid",
"append",
"(",
"byte",
"[",
"]",
"...",
"byteArrays",
")",
"throws",
"IOException",
"{",
"if",
"(",
"byteArrays",
"==",
"null",
"||",
"byteArrays",
".",
"length",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"return",
"fromByteArray... | Creates a new {@link Guid} which is a unique, replicable representation of the pair (this, byteArrays).
@param byteArrays an array of byte arrays.
@return a new {@link Guid}.
@throws IOException | [
"Creates",
"a",
"new",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/guid/Guid.java#L148-L153 |
spring-projects/spring-social | spring-social-security/src/main/java/org/springframework/social/security/SocialAuthenticationFilter.java | SocialAuthenticationFilter.requiresAuthentication | @Deprecated
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
String providerId = getRequestedProviderId(request);
if (providerId != null){
Set<String> authProviders = authServiceLocator.registeredAuthenticationProviderIds();
return authProviders.contains(providerId);
}
return false;
} | java | @Deprecated
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
String providerId = getRequestedProviderId(request);
if (providerId != null){
Set<String> authProviders = authServiceLocator.registeredAuthenticationProviderIds();
return authProviders.contains(providerId);
}
return false;
} | [
"@",
"Deprecated",
"protected",
"boolean",
"requiresAuthentication",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"String",
"providerId",
"=",
"getRequestedProviderId",
"(",
"request",
")",
";",
"if",
"(",
"providerId",
"!=",... | Indicates whether this filter should attempt to process a social network login request for the current invocation.
<p>Check if request URL matches filterProcessesUrl with valid providerId.
The URL must be like {filterProcessesUrl}/{providerId}.
@return <code>true</code> if the filter should attempt authentication, <code>false</code> otherwise. | [
"Indicates",
"whether",
"this",
"filter",
"should",
"attempt",
"to",
"process",
"a",
"social",
"network",
"login",
"request",
"for",
"the",
"current",
"invocation",
".",
"<p",
">",
"Check",
"if",
"request",
"URL",
"matches",
"filterProcessesUrl",
"with",
"valid"... | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-security/src/main/java/org/springframework/social/security/SocialAuthenticationFilter.java#L225-L233 |
davidcarboni/cryptolite-java | src/main/java/com/github/davidcarboni/cryptolite/KeyWrapper.java | KeyWrapper.unwrapKeyPair | public KeyPair unwrapKeyPair(String wrappedPrivateKey, String encodedPublicKey) {
PrivateKey privateKey = unwrapPrivateKey(wrappedPrivateKey);
PublicKey publicKey = decodePublicKey(encodedPublicKey);
return new KeyPair(publicKey, privateKey);
} | java | public KeyPair unwrapKeyPair(String wrappedPrivateKey, String encodedPublicKey) {
PrivateKey privateKey = unwrapPrivateKey(wrappedPrivateKey);
PublicKey publicKey = decodePublicKey(encodedPublicKey);
return new KeyPair(publicKey, privateKey);
} | [
"public",
"KeyPair",
"unwrapKeyPair",
"(",
"String",
"wrappedPrivateKey",
",",
"String",
"encodedPublicKey",
")",
"{",
"PrivateKey",
"privateKey",
"=",
"unwrapPrivateKey",
"(",
"wrappedPrivateKey",
")",
";",
"PublicKey",
"publicKey",
"=",
"decodePublicKey",
"(",
"enco... | Convenience method to unwrap a public-private key pain in a single call.
@param wrappedPrivateKey The wrapped key, base-64 encoded, as returned by
{@link #wrapPrivateKey(PrivateKey)}.
@param encodedPublicKey The public key, base-64 encoded, as returned by
{@link #encodePublicKey(PublicKey)}.
@return A {@link KeyPair} containing the unwrapped {@link PrivateKey} and the decoded {@link PublicKey}. | [
"Convenience",
"method",
"to",
"unwrap",
"a",
"public",
"-",
"private",
"key",
"pain",
"in",
"a",
"single",
"call",
"."
] | train | https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/KeyWrapper.java#L264-L269 |
openbase/jul | extension/protobuf/src/main/java/org/openbase/jul/extension/protobuf/processing/ProtoBufJSonProcessor.java | ProtoBufJSonProcessor.getServiceStateClassName | public String getServiceStateClassName(final Object serviceState) throws CouldNotPerformException {
// todo: move to dal or any bco component. Jul should be independent from bco architecture.
if (serviceState.getClass().getName().startsWith("org.openbase.type")) {
return serviceState.getClass().getName();
}
if (serviceState.getClass().isEnum()) {
logger.info(serviceState.getClass().getName());
return serviceState.getClass().getName();
}
logger.debug("Simple class name of attribute to upper case [" + serviceState.getClass().getSimpleName().toUpperCase() + "]");
JavaTypeToProto javaToProto;
try {
javaToProto = JavaTypeToProto.valueOf(serviceState.getClass().getSimpleName().toUpperCase());
} catch (IllegalArgumentException ex) {
throw new CouldNotPerformException("ServiceState is not a supported java primitive nor a supported rst type", ex);
}
logger.debug("According proto type [" + javaToProto.getProtoType().name() + "]");
return javaToProto.getProtoType().name();
} | java | public String getServiceStateClassName(final Object serviceState) throws CouldNotPerformException {
// todo: move to dal or any bco component. Jul should be independent from bco architecture.
if (serviceState.getClass().getName().startsWith("org.openbase.type")) {
return serviceState.getClass().getName();
}
if (serviceState.getClass().isEnum()) {
logger.info(serviceState.getClass().getName());
return serviceState.getClass().getName();
}
logger.debug("Simple class name of attribute to upper case [" + serviceState.getClass().getSimpleName().toUpperCase() + "]");
JavaTypeToProto javaToProto;
try {
javaToProto = JavaTypeToProto.valueOf(serviceState.getClass().getSimpleName().toUpperCase());
} catch (IllegalArgumentException ex) {
throw new CouldNotPerformException("ServiceState is not a supported java primitive nor a supported rst type", ex);
}
logger.debug("According proto type [" + javaToProto.getProtoType().name() + "]");
return javaToProto.getProtoType().name();
} | [
"public",
"String",
"getServiceStateClassName",
"(",
"final",
"Object",
"serviceState",
")",
"throws",
"CouldNotPerformException",
"{",
"// todo: move to dal or any bco component. Jul should be independent from bco architecture.",
"if",
"(",
"serviceState",
".",
"getClass",
"(",
... | Get the string representation for a given serviceState which can be a
proto message, enumeration or a java primitive.
@param serviceState the serviceState
@return a string representation of the serviceState type
@throws CouldNotPerformException | [
"Get",
"the",
"string",
"representation",
"for",
"a",
"given",
"serviceState",
"which",
"can",
"be",
"a",
"proto",
"message",
"enumeration",
"or",
"a",
"java",
"primitive",
"."
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/protobuf/src/main/java/org/openbase/jul/extension/protobuf/processing/ProtoBufJSonProcessor.java#L91-L111 |
networknt/light-4j | config/src/main/java/com/networknt/config/CentralizedManagement.java | CentralizedManagement.mergeObject | public static Object mergeObject(Object config, Class clazz) {
merge(config);
return convertMapToObj((Map<String, Object>) config, clazz);
} | java | public static Object mergeObject(Object config, Class clazz) {
merge(config);
return convertMapToObj((Map<String, Object>) config, clazz);
} | [
"public",
"static",
"Object",
"mergeObject",
"(",
"Object",
"config",
",",
"Class",
"clazz",
")",
"{",
"merge",
"(",
"config",
")",
";",
"return",
"convertMapToObj",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"config",
",",
"clazz",
")",
... | Merge map config with values generated by ConfigInjection.class and return mapping object | [
"Merge",
"map",
"config",
"with",
"values",
"generated",
"by",
"ConfigInjection",
".",
"class",
"and",
"return",
"mapping",
"object"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/config/src/main/java/com/networknt/config/CentralizedManagement.java#L42-L45 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java | DefinitionsDocument.definitionRef | private void definitionRef(MarkupDocBuilder markupDocBuilder, String definitionName) {
buildDefinitionTitle(markupDocBuilder, crossReference(markupDocBuilder, definitionDocumentResolverDefault.apply(definitionName), definitionName, definitionName), "ref-" + definitionName);
} | java | private void definitionRef(MarkupDocBuilder markupDocBuilder, String definitionName) {
buildDefinitionTitle(markupDocBuilder, crossReference(markupDocBuilder, definitionDocumentResolverDefault.apply(definitionName), definitionName, definitionName), "ref-" + definitionName);
} | [
"private",
"void",
"definitionRef",
"(",
"MarkupDocBuilder",
"markupDocBuilder",
",",
"String",
"definitionName",
")",
"{",
"buildDefinitionTitle",
"(",
"markupDocBuilder",
",",
"crossReference",
"(",
"markupDocBuilder",
",",
"definitionDocumentResolverDefault",
".",
"apply... | Builds a cross-reference to a separated definition file.
@param definitionName definition name to target | [
"Builds",
"a",
"cross",
"-",
"reference",
"to",
"a",
"separated",
"definition",
"file",
"."
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L171-L173 |
waldheinz/fat32-lib | src/main/java/de/waldheinz/fs/fat/LittleEndian.java | LittleEndian.getUInt16 | public static int getUInt16(byte[] src, int offset) {
final int v0 = src[offset + 0] & 0xFF;
final int v1 = src[offset + 1] & 0xFF;
return ((v1 << 8) | v0);
} | java | public static int getUInt16(byte[] src, int offset) {
final int v0 = src[offset + 0] & 0xFF;
final int v1 = src[offset + 1] & 0xFF;
return ((v1 << 8) | v0);
} | [
"public",
"static",
"int",
"getUInt16",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"offset",
")",
"{",
"final",
"int",
"v0",
"=",
"src",
"[",
"offset",
"+",
"0",
"]",
"&",
"0xFF",
";",
"final",
"int",
"v1",
"=",
"src",
"[",
"offset",
"+",
"1",
"... | Gets a 16-bit unsigned integer from the given byte array at the given offset.
@param src
@param offset | [
"Gets",
"a",
"16",
"-",
"bit",
"unsigned",
"integer",
"from",
"the",
"given",
"byte",
"array",
"at",
"the",
"given",
"offset",
"."
] | train | https://github.com/waldheinz/fat32-lib/blob/3d8f1a986339573576e02eb0b6ea49bfdc9cce26/src/main/java/de/waldheinz/fs/fat/LittleEndian.java#L50-L54 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/classify/LinearClassifierFactory.java | LinearClassifierFactory.heldOutSetSigma | public double[] heldOutSetSigma(final GeneralDataset<L, F> trainSet, final GeneralDataset<L, F> devSet, final Scorer<L> scorer, LineSearcher minimizer) {
featureIndex = trainSet.featureIndex;
labelIndex = trainSet.labelIndex;
//double[] resultWeights = null;
Timing timer = new Timing();
NegativeScorer negativeScorer = new NegativeScorer(trainSet,devSet,scorer,timer);
timer.start();
double bestSigma = minimizer.minimize(negativeScorer);
System.err.println("##best sigma: " + bestSigma);
setSigma(bestSigma);
return ArrayUtils.flatten(trainWeights(trainSet,negativeScorer.weights,true)); // make sure it's actually the interim weights from best sigma
} | java | public double[] heldOutSetSigma(final GeneralDataset<L, F> trainSet, final GeneralDataset<L, F> devSet, final Scorer<L> scorer, LineSearcher minimizer) {
featureIndex = trainSet.featureIndex;
labelIndex = trainSet.labelIndex;
//double[] resultWeights = null;
Timing timer = new Timing();
NegativeScorer negativeScorer = new NegativeScorer(trainSet,devSet,scorer,timer);
timer.start();
double bestSigma = minimizer.minimize(negativeScorer);
System.err.println("##best sigma: " + bestSigma);
setSigma(bestSigma);
return ArrayUtils.flatten(trainWeights(trainSet,negativeScorer.weights,true)); // make sure it's actually the interim weights from best sigma
} | [
"public",
"double",
"[",
"]",
"heldOutSetSigma",
"(",
"final",
"GeneralDataset",
"<",
"L",
",",
"F",
">",
"trainSet",
",",
"final",
"GeneralDataset",
"<",
"L",
",",
"F",
">",
"devSet",
",",
"final",
"Scorer",
"<",
"L",
">",
"scorer",
",",
"LineSearcher",... | Sets the sigma parameter to a value that optimizes the held-out score given by <code>scorer</code>. Search for an optimal value
is carried out by <code>minimizer</code>
dataset the data set to optimize sigma on.
kfold
@return an interim set of optimal weights: the weights | [
"Sets",
"the",
"sigma",
"parameter",
"to",
"a",
"value",
"that",
"optimizes",
"the",
"held",
"-",
"out",
"score",
"given",
"by",
"<code",
">",
"scorer<",
"/",
"code",
">",
".",
"Search",
"for",
"an",
"optimal",
"value",
"is",
"carried",
"out",
"by",
"<... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LinearClassifierFactory.java#L647-L662 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/AssetsInner.java | AssetsInner.getEncryptionKey | public StorageEncryptedAssetDecryptionDataInner getEncryptionKey(String resourceGroupName, String accountName, String assetName) {
return getEncryptionKeyWithServiceResponseAsync(resourceGroupName, accountName, assetName).toBlocking().single().body();
} | java | public StorageEncryptedAssetDecryptionDataInner getEncryptionKey(String resourceGroupName, String accountName, String assetName) {
return getEncryptionKeyWithServiceResponseAsync(resourceGroupName, accountName, assetName).toBlocking().single().body();
} | [
"public",
"StorageEncryptedAssetDecryptionDataInner",
"getEncryptionKey",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"assetName",
")",
"{",
"return",
"getEncryptionKeyWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
... | Gets the Asset storage key.
Gets the Asset storage encryption keys used to decrypt content created by version 2 of the Media Services API.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param assetName The Asset name.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the StorageEncryptedAssetDecryptionDataInner object if successful. | [
"Gets",
"the",
"Asset",
"storage",
"key",
".",
"Gets",
"the",
"Asset",
"storage",
"encryption",
"keys",
"used",
"to",
"decrypt",
"content",
"created",
"by",
"version",
"2",
"of",
"the",
"Media",
"Services",
"API",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/AssetsInner.java#L895-L897 |
Azure/azure-sdk-for-java | mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/ConfigurationsInner.java | ConfigurationsInner.getAsync | public Observable<ConfigurationInner> getAsync(String resourceGroupName, String serverName, String configurationName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, configurationName).map(new Func1<ServiceResponse<ConfigurationInner>, ConfigurationInner>() {
@Override
public ConfigurationInner call(ServiceResponse<ConfigurationInner> response) {
return response.body();
}
});
} | java | public Observable<ConfigurationInner> getAsync(String resourceGroupName, String serverName, String configurationName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, configurationName).map(new Func1<ServiceResponse<ConfigurationInner>, ConfigurationInner>() {
@Override
public ConfigurationInner call(ServiceResponse<ConfigurationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ConfigurationInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"configurationName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
... | Gets information about a configuration of server.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param configurationName The name of the server configuration.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ConfigurationInner object | [
"Gets",
"information",
"about",
"a",
"configuration",
"of",
"server",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/ConfigurationsInner.java#L300-L307 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/redis/Cache.java | Cache.migrate | public String migrate(String host, int port, Object key, int destinationDb, int timeout) {
Jedis jedis = getJedis();
try {
return jedis.migrate(valueToBytes(host), port, keyToBytes(key), destinationDb, timeout);
}
finally {close(jedis);}
} | java | public String migrate(String host, int port, Object key, int destinationDb, int timeout) {
Jedis jedis = getJedis();
try {
return jedis.migrate(valueToBytes(host), port, keyToBytes(key), destinationDb, timeout);
}
finally {close(jedis);}
} | [
"public",
"String",
"migrate",
"(",
"String",
"host",
",",
"int",
"port",
",",
"Object",
"key",
",",
"int",
"destinationDb",
",",
"int",
"timeout",
")",
"{",
"Jedis",
"jedis",
"=",
"getJedis",
"(",
")",
";",
"try",
"{",
"return",
"jedis",
".",
"migrate... | 将 key 原子性地从当前实例传送到目标实例的指定数据库上,一旦传送成功, key 保证会出现在目标实例上,而当前实例上的 key 会被删除。 | [
"将",
"key",
"原子性地从当前实例传送到目标实例的指定数据库上,一旦传送成功,",
"key",
"保证会出现在目标实例上,而当前实例上的",
"key",
"会被删除。"
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/redis/Cache.java#L289-L295 |
craterdog/java-smart-objects | src/main/java/craterdog/smart/SmartObjectMapper.java | SmartObjectMapper.writeValueAsString | String writeValueAsString(Object value, String indentation) throws JsonProcessingException {
PrettyPrinter printer = new BetterPrettyPrinter(indentation).withArrayIndenter(new DefaultIndenter());
return writer(printer).writeValueAsString(value);
} | java | String writeValueAsString(Object value, String indentation) throws JsonProcessingException {
PrettyPrinter printer = new BetterPrettyPrinter(indentation).withArrayIndenter(new DefaultIndenter());
return writer(printer).writeValueAsString(value);
} | [
"String",
"writeValueAsString",
"(",
"Object",
"value",
",",
"String",
"indentation",
")",
"throws",
"JsonProcessingException",
"{",
"PrettyPrinter",
"printer",
"=",
"new",
"BetterPrettyPrinter",
"(",
"indentation",
")",
".",
"withArrayIndenter",
"(",
"new",
"DefaultI... | This method behaves similarly to the <code>writeValueAsString(Object value)</code> method
except that it includes an indentation prefix that will be prepended to each line of the
resulting string (except the first line).
@param value The smart object to be written out as a string.
@param indentation The indentation string to be prepended to each line.
@return The formatted string.
@throws JsonProcessingException The JSON object mapper was not able to serialize the object. | [
"This",
"method",
"behaves",
"similarly",
"to",
"the",
"<code",
">",
"writeValueAsString",
"(",
"Object",
"value",
")",
"<",
"/",
"code",
">",
"method",
"except",
"that",
"it",
"includes",
"an",
"indentation",
"prefix",
"that",
"will",
"be",
"prepended",
"to... | train | https://github.com/craterdog/java-smart-objects/blob/6d11e2f345e4d2836e3aca3990c8ed2db330d856/src/main/java/craterdog/smart/SmartObjectMapper.java#L91-L94 |
structr/structr | structr-core/src/main/java/org/structr/module/JarConfigurationProvider.java | JarConfigurationProvider.registerPropertySet | @Override
public void registerPropertySet(Class type, String propertyView, PropertyKey... propertySet) {
Map<String, Set<PropertyKey>> propertyViewMap = getPropertyViewMapForType(type);
Set<PropertyKey> properties = propertyViewMap.get(propertyView);
if (properties == null) {
properties = new LinkedHashSet<>();
propertyViewMap.put(propertyView, properties);
}
// allow properties to override existing ones as they
// are most likely from a more concrete class.
for (final PropertyKey key : propertySet) {
// property keys are referenced by their names,
// that's why we seemingly remove the existing
// key, but the set does not differentiate
// between different keys
if (properties.contains(key)) {
properties.remove(key);
}
properties.add(key);
}
} | java | @Override
public void registerPropertySet(Class type, String propertyView, PropertyKey... propertySet) {
Map<String, Set<PropertyKey>> propertyViewMap = getPropertyViewMapForType(type);
Set<PropertyKey> properties = propertyViewMap.get(propertyView);
if (properties == null) {
properties = new LinkedHashSet<>();
propertyViewMap.put(propertyView, properties);
}
// allow properties to override existing ones as they
// are most likely from a more concrete class.
for (final PropertyKey key : propertySet) {
// property keys are referenced by their names,
// that's why we seemingly remove the existing
// key, but the set does not differentiate
// between different keys
if (properties.contains(key)) {
properties.remove(key);
}
properties.add(key);
}
} | [
"@",
"Override",
"public",
"void",
"registerPropertySet",
"(",
"Class",
"type",
",",
"String",
"propertyView",
",",
"PropertyKey",
"...",
"propertySet",
")",
"{",
"Map",
"<",
"String",
",",
"Set",
"<",
"PropertyKey",
">",
">",
"propertyViewMap",
"=",
"getPrope... | Registers the given set of property keys for the view with name
<code>propertyView</code> and the given prefix of entities with the
given type.
@param type the type of the entities for which the view will be
registered
@param propertyView the name of the property view for which the
property set will be registered
@param propertySet the set of property keys to register for the given
view | [
"Registers",
"the",
"given",
"set",
"of",
"property",
"keys",
"for",
"the",
"view",
"with",
"name",
"<code",
">",
"propertyView<",
"/",
"code",
">",
"and",
"the",
"given",
"prefix",
"of",
"entities",
"with",
"the",
"given",
"type",
"."
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/module/JarConfigurationProvider.java#L841-L866 |
apache/incubator-atlas | repository/src/main/java/org/apache/atlas/gremlin/GremlinExpressionFactory.java | GremlinExpressionFactory.generateAdjacentVerticesExpression | public GroovyExpression generateAdjacentVerticesExpression(GroovyExpression parent, AtlasEdgeDirection dir,
String label) {
return new FunctionCallExpression(TraversalStepType.FLAT_MAP_TO_ELEMENTS, parent, getGremlinFunctionName(dir), new LiteralExpression(label));
} | java | public GroovyExpression generateAdjacentVerticesExpression(GroovyExpression parent, AtlasEdgeDirection dir,
String label) {
return new FunctionCallExpression(TraversalStepType.FLAT_MAP_TO_ELEMENTS, parent, getGremlinFunctionName(dir), new LiteralExpression(label));
} | [
"public",
"GroovyExpression",
"generateAdjacentVerticesExpression",
"(",
"GroovyExpression",
"parent",
",",
"AtlasEdgeDirection",
"dir",
",",
"String",
"label",
")",
"{",
"return",
"new",
"FunctionCallExpression",
"(",
"TraversalStepType",
".",
"FLAT_MAP_TO_ELEMENTS",
",",
... | Generates an expression that gets the vertices adjacent to the vertex in 'parent'
in the specified direction, following only edges with the given label.
@param parent
@param dir
@return | [
"Generates",
"an",
"expression",
"that",
"gets",
"the",
"vertices",
"adjacent",
"to",
"the",
"vertex",
"in",
"parent",
"in",
"the",
"specified",
"direction",
"following",
"only",
"edges",
"with",
"the",
"given",
"label",
"."
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/gremlin/GremlinExpressionFactory.java#L489-L492 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPUtility.java | MPPUtility.getByteArray | public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)
{
System.arraycopy(data, offset, buffer, bufferOffset, size);
} | java | public static final void getByteArray(byte[] data, int offset, int size, byte[] buffer, int bufferOffset)
{
System.arraycopy(data, offset, buffer, bufferOffset, size);
} | [
"public",
"static",
"final",
"void",
"getByteArray",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"int",
"size",
",",
"byte",
"[",
"]",
"buffer",
",",
"int",
"bufferOffset",
")",
"{",
"System",
".",
"arraycopy",
"(",
"data",
",",
"offset",... | This method extracts a portion of a byte array and writes it into
another byte array.
@param data Source data
@param offset Offset into source data
@param size Required size to be extracted from the source data
@param buffer Destination buffer
@param bufferOffset Offset into destination buffer | [
"This",
"method",
"extracts",
"a",
"portion",
"of",
"a",
"byte",
"array",
"and",
"writes",
"it",
"into",
"another",
"byte",
"array",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L155-L158 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/core/Parser.java | Parser.parseValuesKeyword | public static boolean parseValuesKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'v'
&& (query[offset + 1] | 32) == 'a'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'u'
&& (query[offset + 4] | 32) == 'e'
&& (query[offset + 5] | 32) == 's';
} | java | public static boolean parseValuesKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'v'
&& (query[offset + 1] | 32) == 'a'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'u'
&& (query[offset + 4] | 32) == 'e'
&& (query[offset + 5] | 32) == 's';
} | [
"public",
"static",
"boolean",
"parseValuesKeyword",
"(",
"final",
"char",
"[",
"]",
"query",
",",
"int",
"offset",
")",
"{",
"if",
"(",
"query",
".",
"length",
"<",
"(",
"offset",
"+",
"6",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
... | Parse string to check presence of VALUES keyword regardless of case.
@param query char[] of the query statement
@param offset position of query to start checking
@return boolean indicates presence of word | [
"Parse",
"string",
"to",
"check",
"presence",
"of",
"VALUES",
"keyword",
"regardless",
"of",
"case",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L683-L694 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/trees/MDA.java | MDA.walkCorruptedPath | private TreeNodeVisitor walkCorruptedPath(TreeLearner model, DataPoint dp, int j, Random rand)
{
TreeNodeVisitor curNode = model.getTreeNodeVisitor();
while(!curNode.isLeaf())
{
int path = curNode.getPath(dp);
int numChild = curNode.childrenCount();
if(curNode.featuresUsed().contains(j))//corrupt the feature!
{
//this gets us a random OTHER path, wont be the same b/c we would need to wrap around 1 farther
path = (path + rand.nextInt(numChild)) % numChild;
}
if(curNode.isPathDisabled(path))
break;
else
curNode = curNode.getChild(path);
}
return curNode;
} | java | private TreeNodeVisitor walkCorruptedPath(TreeLearner model, DataPoint dp, int j, Random rand)
{
TreeNodeVisitor curNode = model.getTreeNodeVisitor();
while(!curNode.isLeaf())
{
int path = curNode.getPath(dp);
int numChild = curNode.childrenCount();
if(curNode.featuresUsed().contains(j))//corrupt the feature!
{
//this gets us a random OTHER path, wont be the same b/c we would need to wrap around 1 farther
path = (path + rand.nextInt(numChild)) % numChild;
}
if(curNode.isPathDisabled(path))
break;
else
curNode = curNode.getChild(path);
}
return curNode;
} | [
"private",
"TreeNodeVisitor",
"walkCorruptedPath",
"(",
"TreeLearner",
"model",
",",
"DataPoint",
"dp",
",",
"int",
"j",
",",
"Random",
"rand",
")",
"{",
"TreeNodeVisitor",
"curNode",
"=",
"model",
".",
"getTreeNodeVisitor",
"(",
")",
";",
"while",
"(",
"!",
... | walks the tree down to a leaf node, adding corruption for a specific feature
@param model the tree model to walk
@param dp the data point to push down the tree
@param j the feature index to corrupt
@param rand source of randomness
@return the leaf node | [
"walks",
"the",
"tree",
"down",
"to",
"a",
"leaf",
"node",
"adding",
"corruption",
"for",
"a",
"specific",
"feature"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/trees/MDA.java#L139-L158 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java | ReadMatrixCsv.readZDRM | public ZMatrixRMaj readZDRM(int numRows, int numCols) throws IOException {
ZMatrixRMaj A = new ZMatrixRMaj(numRows,numCols);
int wordsCol = numCols*2;
for( int i = 0; i < numRows; i++ ) {
List<String> words = extractWords();
if( words == null )
throw new IOException("Too few rows found. expected "+numRows+" actual "+i);
if( words.size() != wordsCol )
throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+wordsCol);
for( int j = 0; j < wordsCol; j += 2 ) {
double real = Double.parseDouble(words.get(j));
double imaginary = Double.parseDouble(words.get(j+1));
A.set(i, j, real, imaginary);
}
}
return A;
} | java | public ZMatrixRMaj readZDRM(int numRows, int numCols) throws IOException {
ZMatrixRMaj A = new ZMatrixRMaj(numRows,numCols);
int wordsCol = numCols*2;
for( int i = 0; i < numRows; i++ ) {
List<String> words = extractWords();
if( words == null )
throw new IOException("Too few rows found. expected "+numRows+" actual "+i);
if( words.size() != wordsCol )
throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+wordsCol);
for( int j = 0; j < wordsCol; j += 2 ) {
double real = Double.parseDouble(words.get(j));
double imaginary = Double.parseDouble(words.get(j+1));
A.set(i, j, real, imaginary);
}
}
return A;
} | [
"public",
"ZMatrixRMaj",
"readZDRM",
"(",
"int",
"numRows",
",",
"int",
"numCols",
")",
"throws",
"IOException",
"{",
"ZMatrixRMaj",
"A",
"=",
"new",
"ZMatrixRMaj",
"(",
"numRows",
",",
"numCols",
")",
";",
"int",
"wordsCol",
"=",
"numCols",
"*",
"2",
";",... | Reads in a {@link ZMatrixRMaj} from the IO stream where the user specifies the matrix dimensions.
@param numRows Number of rows in the matrix
@param numCols Number of columns in the matrix
@return ZMatrixRMaj
@throws IOException | [
"Reads",
"in",
"a",
"{",
"@link",
"ZMatrixRMaj",
"}",
"from",
"the",
"IO",
"stream",
"where",
"the",
"user",
"specifies",
"the",
"matrix",
"dimensions",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java#L183-L206 |
Alluxio/alluxio | core/common/src/main/java/alluxio/collections/LockCache.java | LockCache.get | public LockResource get(K key, LockMode mode) {
ValNode valNode = getValNode(key);
ReentrantReadWriteLock lock = valNode.mValue;
switch (mode) {
case READ:
return new RefCountLockResource(lock.readLock(), true, valNode.mRefCount);
case WRITE:
return new RefCountLockResource(lock.writeLock(), true, valNode.mRefCount);
default:
throw new IllegalStateException("Unknown lock mode: " + mode);
}
} | java | public LockResource get(K key, LockMode mode) {
ValNode valNode = getValNode(key);
ReentrantReadWriteLock lock = valNode.mValue;
switch (mode) {
case READ:
return new RefCountLockResource(lock.readLock(), true, valNode.mRefCount);
case WRITE:
return new RefCountLockResource(lock.writeLock(), true, valNode.mRefCount);
default:
throw new IllegalStateException("Unknown lock mode: " + mode);
}
} | [
"public",
"LockResource",
"get",
"(",
"K",
"key",
",",
"LockMode",
"mode",
")",
"{",
"ValNode",
"valNode",
"=",
"getValNode",
"(",
"key",
")",
";",
"ReentrantReadWriteLock",
"lock",
"=",
"valNode",
".",
"mValue",
";",
"switch",
"(",
"mode",
")",
"{",
"ca... | Locks the specified key in the specified mode.
@param key the key to lock
@param mode the mode to lock in
@return a lock resource which must be closed to unlock the key | [
"Locks",
"the",
"specified",
"key",
"in",
"the",
"specified",
"mode",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L123-L134 |
evandor/unitprofiler | unitprofiler.core/src/main/java/de/twenty11/unitprofile/callback/ProfilerCallback.java | ProfilerCallback.start | public static MethodInvocation start(String objectName, String methodName, int lineNumber) {
bigMessage("Starting profiling... " + objectName + "#" + methodName + " (" + lineNumber + ")");
if (profiling()) {
logger.error("Profiling was already started for '{}'", callstack.getFirst().getCls() + "#"
+ callstack.getFirst().getMethod());
throw new IllegalStateException();
}
MethodDescriptor methodDescriptor = new MethodDescriptor(objectName, methodName, lineNumber);
MethodInvocation rootInvocation = new MethodInvocation(methodDescriptor);
invocations.add(rootInvocation);
callstack.add(rootInvocation);
Agent.setRootInvocation(rootInvocation);
return rootInvocation;
} | java | public static MethodInvocation start(String objectName, String methodName, int lineNumber) {
bigMessage("Starting profiling... " + objectName + "#" + methodName + " (" + lineNumber + ")");
if (profiling()) {
logger.error("Profiling was already started for '{}'", callstack.getFirst().getCls() + "#"
+ callstack.getFirst().getMethod());
throw new IllegalStateException();
}
MethodDescriptor methodDescriptor = new MethodDescriptor(objectName, methodName, lineNumber);
MethodInvocation rootInvocation = new MethodInvocation(methodDescriptor);
invocations.add(rootInvocation);
callstack.add(rootInvocation);
Agent.setRootInvocation(rootInvocation);
return rootInvocation;
} | [
"public",
"static",
"MethodInvocation",
"start",
"(",
"String",
"objectName",
",",
"String",
"methodName",
",",
"int",
"lineNumber",
")",
"{",
"bigMessage",
"(",
"\"Starting profiling... \"",
"+",
"objectName",
"+",
"\"#\"",
"+",
"methodName",
"+",
"\" (\"",
"+",
... | the first invocation for this profiling session.
@param objectName
@param methodName
@return | [
"the",
"first",
"invocation",
"for",
"this",
"profiling",
"session",
"."
] | train | https://github.com/evandor/unitprofiler/blob/a875635d0f45ca7f9694c5e9c815109877d056b5/unitprofiler.core/src/main/java/de/twenty11/unitprofile/callback/ProfilerCallback.java#L40-L54 |
aalmiray/Json-lib | src/main/java/net/sf/json/JSONObject.java | JSONObject.element | public JSONObject element( String key, Map value, JsonConfig jsonConfig ) {
verifyIsNull();
if( value instanceof JSONObject ){
return setInternal( key, value, jsonConfig );
}else{
return element( key, JSONObject.fromObject( value, jsonConfig ), jsonConfig );
}
} | java | public JSONObject element( String key, Map value, JsonConfig jsonConfig ) {
verifyIsNull();
if( value instanceof JSONObject ){
return setInternal( key, value, jsonConfig );
}else{
return element( key, JSONObject.fromObject( value, jsonConfig ), jsonConfig );
}
} | [
"public",
"JSONObject",
"element",
"(",
"String",
"key",
",",
"Map",
"value",
",",
"JsonConfig",
"jsonConfig",
")",
"{",
"verifyIsNull",
"(",
")",
";",
"if",
"(",
"value",
"instanceof",
"JSONObject",
")",
"{",
"return",
"setInternal",
"(",
"key",
",",
"val... | Put a key/value pair in the JSONObject, where the value will be a
JSONObject which is produced from a Map.
@param key A key string.
@param value A Map value.
@return this.
@throws JSONException | [
"Put",
"a",
"key",
"/",
"value",
"pair",
"in",
"the",
"JSONObject",
"where",
"the",
"value",
"will",
"be",
"a",
"JSONObject",
"which",
"is",
"produced",
"from",
"a",
"Map",
"."
] | train | https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONObject.java#L1667-L1674 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectPropertyDomainAxiomImpl_CustomFieldSerializer.java | OWLObjectPropertyDomainAxiomImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectPropertyDomainAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectPropertyDomainAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLObjectPropertyDomainAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}... | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectPropertyDomainAxiomImpl_CustomFieldSerializer.java#L98-L101 |
google/truth | core/src/main/java/com/google/common/truth/FailureMetadata.java | FailureMetadata.withMessage | FailureMetadata withMessage(String format, Object[] args) {
ImmutableList<LazyMessage> messages = append(this.messages, new LazyMessage(format, args));
return derive(messages, steps);
} | java | FailureMetadata withMessage(String format, Object[] args) {
ImmutableList<LazyMessage> messages = append(this.messages, new LazyMessage(format, args));
return derive(messages, steps);
} | [
"FailureMetadata",
"withMessage",
"(",
"String",
"format",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"ImmutableList",
"<",
"LazyMessage",
">",
"messages",
"=",
"append",
"(",
"this",
".",
"messages",
",",
"new",
"LazyMessage",
"(",
"format",
",",
"args",
... | Returns a new instance whose failures will contain the given message. The way for Truth users
to set a message is {@code check().withMessage(...).that(...)} (for calls from within a {@code
Subject}) or {@link Truth#assertWithMessage} (for most other calls). | [
"Returns",
"a",
"new",
"instance",
"whose",
"failures",
"will",
"contain",
"the",
"given",
"message",
".",
"The",
"way",
"for",
"Truth",
"users",
"to",
"set",
"a",
"message",
"is",
"{"
] | train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/FailureMetadata.java#L163-L166 |
VoltDB/voltdb | src/frontend/org/voltdb/types/VoltDecimalHelper.java | VoltDecimalHelper.roundToScale | static private final BigDecimal roundToScale(BigDecimal bd, int scale, RoundingMode mode) throws RuntimeException
{
int lostScaleDigits = bd.scale() - scale;
if (lostScaleDigits <= 0) {
return bd;
}
if (!isRoundingEnabled()) {
throw new RuntimeException(String.format("Decimal scale %d is greater than the maximum %d", bd.scale(), kDefaultScale));
}
int desiredPrecision = Math.max(1, bd.precision() - lostScaleDigits);
MathContext mc = new MathContext(desiredPrecision, mode);
BigDecimal nbd = bd.round(mc);
if (nbd.scale() != scale) {
nbd = nbd.setScale(scale);
}
assert(nbd.scale() == scale);
return nbd;
} | java | static private final BigDecimal roundToScale(BigDecimal bd, int scale, RoundingMode mode) throws RuntimeException
{
int lostScaleDigits = bd.scale() - scale;
if (lostScaleDigits <= 0) {
return bd;
}
if (!isRoundingEnabled()) {
throw new RuntimeException(String.format("Decimal scale %d is greater than the maximum %d", bd.scale(), kDefaultScale));
}
int desiredPrecision = Math.max(1, bd.precision() - lostScaleDigits);
MathContext mc = new MathContext(desiredPrecision, mode);
BigDecimal nbd = bd.round(mc);
if (nbd.scale() != scale) {
nbd = nbd.setScale(scale);
}
assert(nbd.scale() == scale);
return nbd;
} | [
"static",
"private",
"final",
"BigDecimal",
"roundToScale",
"(",
"BigDecimal",
"bd",
",",
"int",
"scale",
",",
"RoundingMode",
"mode",
")",
"throws",
"RuntimeException",
"{",
"int",
"lostScaleDigits",
"=",
"bd",
".",
"scale",
"(",
")",
"-",
"scale",
";",
"if... | Round a BigDecimal number to a scale, given the rounding mode.
Note that the precision of the result can depend not only on its original
precision and scale and the desired scale, but also on its value.
For example, when rounding up with scale 2:<br>
9.1999 with input scale 4 and precision 5 returns 9.20 with precision 3 (down 2).<br>
9.9999 with input scale 4 and precision 5 returns 10.00 with precision 4 (down 1).<br>
91.9999 with input scale 4 and precision 6 returns 92.00 with precision 4 (down 2).
@param bd the input value of arbitrary scale and precision
@param scale the desired scale of the return value
@param mode the rounding algorithm to use
@return the rounded value approximately equal to bd, but having the desired scale | [
"Round",
"a",
"BigDecimal",
"number",
"to",
"a",
"scale",
"given",
"the",
"rounding",
"mode",
".",
"Note",
"that",
"the",
"precision",
"of",
"the",
"result",
"can",
"depend",
"not",
"only",
"on",
"its",
"original",
"precision",
"and",
"scale",
"and",
"the"... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/types/VoltDecimalHelper.java#L208-L225 |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/authentication/storage/CryptoUtil.java | CryptoUtil.getAESKey | @VisibleForTesting
byte[] getAESKey() throws IncompatibleDeviceException, CryptoException {
final String encodedEncryptedAES = storage.retrieveString(KEY_ALIAS);
if (encodedEncryptedAES != null) {
//Return existing key
byte[] encryptedAES = Base64.decode(encodedEncryptedAES, Base64.DEFAULT);
return RSADecrypt(encryptedAES);
}
//Key doesn't exist. Generate new AES
try {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM_AES);
keyGen.init(AES_KEY_SIZE);
byte[] aes = keyGen.generateKey().getEncoded();
//Save encrypted encoded version
byte[] encryptedAES = RSAEncrypt(aes);
String encodedEncryptedAESText = new String(Base64.encode(encryptedAES, Base64.DEFAULT));
storage.store(KEY_ALIAS, encodedEncryptedAESText);
return aes;
} catch (NoSuchAlgorithmException e) {
/*
* This exceptions are safe to be ignored:
*
* - NoSuchAlgorithmException:
* Thrown if the Algorithm implementation is not available. AES was introduced in API 1
*
* Read more in https://developer.android.com/reference/javax/crypto/KeyGenerator
*/
Log.e(TAG, "Error while creating the AES key.", e);
throw new IncompatibleDeviceException(e);
}
} | java | @VisibleForTesting
byte[] getAESKey() throws IncompatibleDeviceException, CryptoException {
final String encodedEncryptedAES = storage.retrieveString(KEY_ALIAS);
if (encodedEncryptedAES != null) {
//Return existing key
byte[] encryptedAES = Base64.decode(encodedEncryptedAES, Base64.DEFAULT);
return RSADecrypt(encryptedAES);
}
//Key doesn't exist. Generate new AES
try {
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM_AES);
keyGen.init(AES_KEY_SIZE);
byte[] aes = keyGen.generateKey().getEncoded();
//Save encrypted encoded version
byte[] encryptedAES = RSAEncrypt(aes);
String encodedEncryptedAESText = new String(Base64.encode(encryptedAES, Base64.DEFAULT));
storage.store(KEY_ALIAS, encodedEncryptedAESText);
return aes;
} catch (NoSuchAlgorithmException e) {
/*
* This exceptions are safe to be ignored:
*
* - NoSuchAlgorithmException:
* Thrown if the Algorithm implementation is not available. AES was introduced in API 1
*
* Read more in https://developer.android.com/reference/javax/crypto/KeyGenerator
*/
Log.e(TAG, "Error while creating the AES key.", e);
throw new IncompatibleDeviceException(e);
}
} | [
"@",
"VisibleForTesting",
"byte",
"[",
"]",
"getAESKey",
"(",
")",
"throws",
"IncompatibleDeviceException",
",",
"CryptoException",
"{",
"final",
"String",
"encodedEncryptedAES",
"=",
"storage",
".",
"retrieveString",
"(",
"KEY_ALIAS",
")",
";",
"if",
"(",
"encode... | Attempts to recover the existing AES Key or generates a new one if none is found.
@return a valid AES Key bytes
@throws IncompatibleDeviceException in the event the device can't understand the cryptographic settings required
@throws CryptoException if the stored RSA keys can't be recovered and should be deemed invalid | [
"Attempts",
"to",
"recover",
"the",
"existing",
"AES",
"Key",
"or",
"generates",
"a",
"new",
"one",
"if",
"none",
"is",
"found",
"."
] | train | https://github.com/auth0/Auth0.Android/blob/ee37b7f94d989c1fbab2cb1378c87fdcaf7a8156/auth0/src/main/java/com/auth0/android/authentication/storage/CryptoUtil.java#L339-L369 |
wildfly/wildfly-core | patching/src/main/java/org/jboss/as/patching/metadata/ModificationBuilderTarget.java | ModificationBuilderTarget.modifyFile | public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {
return modifyFile(name, path, existingHash, newHash, isDirectory, null);
} | java | public T modifyFile(final String name, final List<String> path, final byte[] existingHash, final byte[] newHash, final boolean isDirectory) {
return modifyFile(name, path, existingHash, newHash, isDirectory, null);
} | [
"public",
"T",
"modifyFile",
"(",
"final",
"String",
"name",
",",
"final",
"List",
"<",
"String",
">",
"path",
",",
"final",
"byte",
"[",
"]",
"existingHash",
",",
"final",
"byte",
"[",
"]",
"newHash",
",",
"final",
"boolean",
"isDirectory",
")",
"{",
... | Modify a misc file.
@param name the file name
@param path the relative path
@param existingHash the existing hash
@param newHash the new hash of the modified content
@param isDirectory whether the file is a directory or not
@return the builder | [
"Modify",
"a",
"misc",
"file",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/metadata/ModificationBuilderTarget.java#L136-L138 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java | SegmentsUtil.setInt | public static void setInt(MemorySegment[] segments, int offset, int value) {
if (inFirstSegment(segments, offset, 4)) {
segments[0].putInt(offset, value);
} else {
setIntMultiSegments(segments, offset, value);
}
} | java | public static void setInt(MemorySegment[] segments, int offset, int value) {
if (inFirstSegment(segments, offset, 4)) {
segments[0].putInt(offset, value);
} else {
setIntMultiSegments(segments, offset, value);
}
} | [
"public",
"static",
"void",
"setInt",
"(",
"MemorySegment",
"[",
"]",
"segments",
",",
"int",
"offset",
",",
"int",
"value",
")",
"{",
"if",
"(",
"inFirstSegment",
"(",
"segments",
",",
"offset",
",",
"4",
")",
")",
"{",
"segments",
"[",
"0",
"]",
".... | set int from segments.
@param segments target segments.
@param offset value offset. | [
"set",
"int",
"from",
"segments",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java#L664-L670 |
jamesagnew/hapi-fhir | hapi-fhir-narrativegenerator/src/main/java/ca/uhn/fhir/narrative/template/filters/Escape_Once.java | Escape_Once.apply | @Override
public Object apply(Object value, Object... params) {
String str = super.asString(value);
return str.replaceAll("&(?!([a-zA-Z]+|#[0-9]+|#x[0-9A-Fa-f]+);)", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """);
} | java | @Override
public Object apply(Object value, Object... params) {
String str = super.asString(value);
return str.replaceAll("&(?!([a-zA-Z]+|#[0-9]+|#x[0-9A-Fa-f]+);)", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """);
} | [
"@",
"Override",
"public",
"Object",
"apply",
"(",
"Object",
"value",
",",
"Object",
"...",
"params",
")",
"{",
"String",
"str",
"=",
"super",
".",
"asString",
"(",
"value",
")",
";",
"return",
"str",
".",
"replaceAll",
"(",
"\"&(?!([a-zA-Z]+|#[0-9]+|#x[0-9A... | /*
escape_once(input)
returns an escaped version of html without affecting
existing escaped entities | [
"/",
"*",
"escape_once",
"(",
"input",
")"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-narrativegenerator/src/main/java/ca/uhn/fhir/narrative/template/filters/Escape_Once.java#L11-L20 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java | DateFunctions.datePartStr | public static Expression datePartStr(Expression expression, DatePartExt part) {
return x("DATE_PART_STR(" + expression.toString() + ", \"" + part.toString() + "\")");
} | java | public static Expression datePartStr(Expression expression, DatePartExt part) {
return x("DATE_PART_STR(" + expression.toString() + ", \"" + part.toString() + "\")");
} | [
"public",
"static",
"Expression",
"datePartStr",
"(",
"Expression",
"expression",
",",
"DatePartExt",
"part",
")",
"{",
"return",
"x",
"(",
"\"DATE_PART_STR(\"",
"+",
"expression",
".",
"toString",
"(",
")",
"+",
"\", \\\"\"",
"+",
"part",
".",
"toString",
"("... | Returned expression results in Date part as an integer.
The date expression is a string in a supported format, and part is one of the supported date part strings. | [
"Returned",
"expression",
"results",
"in",
"Date",
"part",
"as",
"an",
"integer",
".",
"The",
"date",
"expression",
"is",
"a",
"string",
"in",
"a",
"supported",
"format",
"and",
"part",
"is",
"one",
"of",
"the",
"supported",
"date",
"part",
"strings",
"."
... | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L156-L158 |
threerings/narya | core/src/main/java/com/threerings/presents/client/Client.java | Client.moveToServer | public void moveToServer (
String hostname, int[] ports, int[] datagramPorts, InvocationService.ConfirmListener obs)
{
// the server switcher will take care of everything for us
new ServerSwitcher(hostname, ports, datagramPorts, obs).switchServers();
} | java | public void moveToServer (
String hostname, int[] ports, int[] datagramPorts, InvocationService.ConfirmListener obs)
{
// the server switcher will take care of everything for us
new ServerSwitcher(hostname, ports, datagramPorts, obs).switchServers();
} | [
"public",
"void",
"moveToServer",
"(",
"String",
"hostname",
",",
"int",
"[",
"]",
"ports",
",",
"int",
"[",
"]",
"datagramPorts",
",",
"InvocationService",
".",
"ConfirmListener",
"obs",
")",
"{",
"// the server switcher will take care of everything for us",
"new",
... | Transitions a logged on client from its current server to the specified new server.
Currently this simply logs the client off of its current server (if it is logged on) and
logs it onto the new server, but in the future we may aim to do something fancier.
<p> If we fail to connect to the new server, the client <em>will not</em> be automatically
reconnected to the old server. It will be in a logged off state. However, it will be
reconfigured with the hostname and ports of the old server so that the caller can notify the
user of the failure and then simply call {@link #logon} to attempt to reconnect to the old
server.
@param obs an observer that will be notified when we have successfully logged onto the
other server, or if the move failed. | [
"Transitions",
"a",
"logged",
"on",
"client",
"from",
"its",
"current",
"server",
"to",
"the",
"specified",
"new",
"server",
".",
"Currently",
"this",
"simply",
"logs",
"the",
"client",
"off",
"of",
"its",
"current",
"server",
"(",
"if",
"it",
"is",
"logge... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/client/Client.java#L572-L577 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/SubnetsInner.java | SubnetsInner.beginDelete | public void beginDelete(String resourceGroupName, String virtualNetworkName, String subnetName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String virtualNetworkName, String subnetName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkName",
",",
"String",
"subnetName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualNetworkName",
",",
"subnetName",
")",
".",
"toB... | Deletes the specified subnet.
@param resourceGroupName The name of the resource group.
@param virtualNetworkName The name of the virtual network.
@param subnetName The name of the subnet.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Deletes",
"the",
"specified",
"subnet",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/SubnetsInner.java#L177-L179 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/BasicAuthAuthenticator.java | BasicAuthAuthenticator.handleBasicAuth | private AuthenticationResult handleBasicAuth(String inRealm, HttpServletRequest req, HttpServletResponse res) {
AuthenticationResult result = null;
String hdrValue = req.getHeader(BASIC_AUTH_HEADER_NAME);
if (hdrValue == null || !hdrValue.startsWith("Basic ")) {
result = new AuthenticationResult(AuthResult.SEND_401, inRealm, AuditEvent.CRED_TYPE_BASIC, null, AuditEvent.OUTCOME_CHALLENGE);
return result;
}
// Parse the username & password from the header.
String encoding = req.getHeader("Authorization-Encoding");
hdrValue = decodeBasicAuth(hdrValue.substring(6), encoding);
int idx = hdrValue.indexOf(':');
if (idx < 0) {
result = new AuthenticationResult(AuthResult.SEND_401, inRealm, AuditEvent.CRED_TYPE_BASIC, null, AuditEvent.OUTCOME_CHALLENGE);
return result;
}
String username = hdrValue.substring(0, idx);
String password = hdrValue.substring(idx + 1);
return basicAuthenticate(inRealm, username, password, req, res);
} | java | private AuthenticationResult handleBasicAuth(String inRealm, HttpServletRequest req, HttpServletResponse res) {
AuthenticationResult result = null;
String hdrValue = req.getHeader(BASIC_AUTH_HEADER_NAME);
if (hdrValue == null || !hdrValue.startsWith("Basic ")) {
result = new AuthenticationResult(AuthResult.SEND_401, inRealm, AuditEvent.CRED_TYPE_BASIC, null, AuditEvent.OUTCOME_CHALLENGE);
return result;
}
// Parse the username & password from the header.
String encoding = req.getHeader("Authorization-Encoding");
hdrValue = decodeBasicAuth(hdrValue.substring(6), encoding);
int idx = hdrValue.indexOf(':');
if (idx < 0) {
result = new AuthenticationResult(AuthResult.SEND_401, inRealm, AuditEvent.CRED_TYPE_BASIC, null, AuditEvent.OUTCOME_CHALLENGE);
return result;
}
String username = hdrValue.substring(0, idx);
String password = hdrValue.substring(idx + 1);
return basicAuthenticate(inRealm, username, password, req, res);
} | [
"private",
"AuthenticationResult",
"handleBasicAuth",
"(",
"String",
"inRealm",
",",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
")",
"{",
"AuthenticationResult",
"result",
"=",
"null",
";",
"String",
"hdrValue",
"=",
"req",
".",
"getHeader",
"("... | handleBasicAuth generates AuthenticationResult
This routine invokes basicAuthenticate which also generates AuthenticationResult. | [
"handleBasicAuth",
"generates",
"AuthenticationResult",
"This",
"routine",
"invokes",
"basicAuthenticate",
"which",
"also",
"generates",
"AuthenticationResult",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/BasicAuthAuthenticator.java#L95-L118 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/workspace/TargetsApi.java | TargetsApi.getTarget | public Target getTarget(long id, TargetType type) throws WorkspaceApiException {
try {
TargetsResponse resp = targetsApi.getTarget(new BigDecimal(id), type.getValue());
Util.throwIfNotOk(resp.getStatus());
Target target = null;
if(resp.getData() != null) {
List<com.genesys.internal.workspace.model.Target> targets = resp.getData().getTargets();
if(targets != null && targets.size() > 0) {
target = Target.fromTarget(targets.get(0));
}
}
return target;
}
catch(ApiException ex) {
throw new WorkspaceApiException("Cannot get target", ex);
}
} | java | public Target getTarget(long id, TargetType type) throws WorkspaceApiException {
try {
TargetsResponse resp = targetsApi.getTarget(new BigDecimal(id), type.getValue());
Util.throwIfNotOk(resp.getStatus());
Target target = null;
if(resp.getData() != null) {
List<com.genesys.internal.workspace.model.Target> targets = resp.getData().getTargets();
if(targets != null && targets.size() > 0) {
target = Target.fromTarget(targets.get(0));
}
}
return target;
}
catch(ApiException ex) {
throw new WorkspaceApiException("Cannot get target", ex);
}
} | [
"public",
"Target",
"getTarget",
"(",
"long",
"id",
",",
"TargetType",
"type",
")",
"throws",
"WorkspaceApiException",
"{",
"try",
"{",
"TargetsResponse",
"resp",
"=",
"targetsApi",
".",
"getTarget",
"(",
"new",
"BigDecimal",
"(",
"id",
")",
",",
"type",
"."... | Get a specific target by type and ID. Targets can be agents, agent groups, queues, route points, skills, and custom contacts.
@param id The ID of the target.
@param type The type of target to retrieve. The possible values are AGENT, AGENT_GROUP, ACD_QUEUE, ROUTE_POINT, SKILL, and CUSTOM_CONTACT.
@return Target | [
"Get",
"a",
"specific",
"target",
"by",
"type",
"and",
"ID",
".",
"Targets",
"can",
"be",
"agents",
"agent",
"groups",
"queues",
"route",
"points",
"skills",
"and",
"custom",
"contacts",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/TargetsApi.java#L188-L207 |
fcrepo4/fcrepo4 | fcrepo-http-commons/src/main/java/org/fcrepo/http/commons/responses/ViewHelpers.java | ViewHelpers.getVersionLabel | public String getVersionLabel(final Graph graph, final Node subject) {
final Instant datetime = getVersionDate(graph, subject);
return MEMENTO_RFC_1123_FORMATTER.format(datetime);
} | java | public String getVersionLabel(final Graph graph, final Node subject) {
final Instant datetime = getVersionDate(graph, subject);
return MEMENTO_RFC_1123_FORMATTER.format(datetime);
} | [
"public",
"String",
"getVersionLabel",
"(",
"final",
"Graph",
"graph",
",",
"final",
"Node",
"subject",
")",
"{",
"final",
"Instant",
"datetime",
"=",
"getVersionDate",
"(",
"graph",
",",
"subject",
")",
";",
"return",
"MEMENTO_RFC_1123_FORMATTER",
".",
"format"... | Get the date time as the version label.
@param graph the graph
@param subject the subject
@return the datetime in RFC 1123 format. | [
"Get",
"the",
"date",
"time",
"as",
"the",
"version",
"label",
"."
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-commons/src/main/java/org/fcrepo/http/commons/responses/ViewHelpers.java#L155-L158 |
kaazing/gateway | util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java | Asn1Utils.encodeIA5String | public static int encodeIA5String(String value, ByteBuffer buf) {
int pos = buf.position();
byte[] data = (value == null) ? new byte[0] : value.getBytes();
for (int i = data.length - 1; i >= 0; i--) {
pos--;
buf.put(pos, data[i]);
}
buf.position(buf.position() - data.length);
int headerLength = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE,
ASN1_IA5STRING_TAG_NUM, data.length, buf);
return headerLength + data.length;
} | java | public static int encodeIA5String(String value, ByteBuffer buf) {
int pos = buf.position();
byte[] data = (value == null) ? new byte[0] : value.getBytes();
for (int i = data.length - 1; i >= 0; i--) {
pos--;
buf.put(pos, data[i]);
}
buf.position(buf.position() - data.length);
int headerLength = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE,
ASN1_IA5STRING_TAG_NUM, data.length, buf);
return headerLength + data.length;
} | [
"public",
"static",
"int",
"encodeIA5String",
"(",
"String",
"value",
",",
"ByteBuffer",
"buf",
")",
"{",
"int",
"pos",
"=",
"buf",
".",
"position",
"(",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"(",
"value",
"==",
"null",
")",
"?",
"new",
"byte",
... | Encode an ASN.1 IA5String.
@param value
the value to be encoded
@param buf
the buffer with space to the left of current position where the value will be encoded
@return the length of the encoded data | [
"Encode",
"an",
"ASN",
".",
"1",
"IA5String",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java#L308-L319 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata/calibration/CalibratedCurves.java | CalibratedCurves.getCloneShifted | public CalibratedCurves getCloneShifted(String symbol, double shift) throws SolverException, CloneNotSupportedException {
// Clone calibration specs, shifting the desired symbol
List<CalibrationSpec> calibrationSpecsShifted = new ArrayList<>();
for(CalibrationSpec calibrationSpec : calibrationSpecs) {
if(calibrationSpec.symbol.equals(symbol)) {
calibrationSpecsShifted.add(calibrationSpec.getCloneShifted(shift));
}
else {
calibrationSpecsShifted.add(calibrationSpec);
}
}
return new CalibratedCurves(calibrationSpecsShifted, model, evaluationTime, calibrationAccuracy);
} | java | public CalibratedCurves getCloneShifted(String symbol, double shift) throws SolverException, CloneNotSupportedException {
// Clone calibration specs, shifting the desired symbol
List<CalibrationSpec> calibrationSpecsShifted = new ArrayList<>();
for(CalibrationSpec calibrationSpec : calibrationSpecs) {
if(calibrationSpec.symbol.equals(symbol)) {
calibrationSpecsShifted.add(calibrationSpec.getCloneShifted(shift));
}
else {
calibrationSpecsShifted.add(calibrationSpec);
}
}
return new CalibratedCurves(calibrationSpecsShifted, model, evaluationTime, calibrationAccuracy);
} | [
"public",
"CalibratedCurves",
"getCloneShifted",
"(",
"String",
"symbol",
",",
"double",
"shift",
")",
"throws",
"SolverException",
",",
"CloneNotSupportedException",
"{",
"// Clone calibration specs, shifting the desired symbol",
"List",
"<",
"CalibrationSpec",
">",
"calibra... | Returns the set curves calibrated to "shifted" market data, that is,
the market date of <code>this</code> object, modified by the shifts
provided to this methods.
@param symbol The symbol to shift. All other symbols remain unshifted.
@param shift The shift to apply to the symbol.
@return A new set of calibrated curves, calibrated to shifted market data.
@throws SolverException The likely cause of this exception is a failure of the solver used in the calibration.
@throws CloneNotSupportedException The likely cause of this exception is the inability to clone or modify a curve. | [
"Returns",
"the",
"set",
"curves",
"calibrated",
"to",
"shifted",
"market",
"data",
"that",
"is",
"the",
"market",
"date",
"of",
"<code",
">",
"this<",
"/",
"code",
">",
"object",
"modified",
"by",
"the",
"shifts",
"provided",
"to",
"this",
"methods",
"."
... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/calibration/CalibratedCurves.java#L568-L581 |
seedstack/seed | security/core/src/main/java/org/seedstack/seed/security/internal/securityexpr/SecurityExpressionUtils.java | SecurityExpressionUtils.hasPermissionOn | public static boolean hasPermissionOn(String permission, String simpleScope) {
return securitySupport.isPermitted(permission, new SimpleScope(simpleScope));
} | java | public static boolean hasPermissionOn(String permission, String simpleScope) {
return securitySupport.isPermitted(permission, new SimpleScope(simpleScope));
} | [
"public",
"static",
"boolean",
"hasPermissionOn",
"(",
"String",
"permission",
",",
"String",
"simpleScope",
")",
"{",
"return",
"securitySupport",
".",
"isPermitted",
"(",
"permission",
",",
"new",
"SimpleScope",
"(",
"simpleScope",
")",
")",
";",
"}"
] | Checks the current user permission.
@param permission the permission to check
@param simpleScope the simple scope to check this permission on.
@return true if user has the given permission for the given simple scope. | [
"Checks",
"the",
"current",
"user",
"permission",
"."
] | train | https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/core/src/main/java/org/seedstack/seed/security/internal/securityexpr/SecurityExpressionUtils.java#L66-L68 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/ScanAPI.java | ScanAPI.productGetlist | public static ProductGetlistResult productGetlist(String accessToken, ProductGetlist productGetlist) {
return productGetlist(accessToken, JsonUtil.toJSONString(productGetlist));
} | java | public static ProductGetlistResult productGetlist(String accessToken, ProductGetlist productGetlist) {
return productGetlist(accessToken, JsonUtil.toJSONString(productGetlist));
} | [
"public",
"static",
"ProductGetlistResult",
"productGetlist",
"(",
"String",
"accessToken",
",",
"ProductGetlist",
"productGetlist",
")",
"{",
"return",
"productGetlist",
"(",
"accessToken",
",",
"JsonUtil",
".",
"toJSONString",
"(",
"productGetlist",
")",
")",
";",
... | 批量查询商品信息
@param accessToken accessToken
@param productGetlist productGetlist
@return ProductGetlistResult | [
"批量查询商品信息"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/ScanAPI.java#L191-L193 |
synchronoss/cpo-api | cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java | CassandraCpoAdapter.retrieveBean | @Override
public <T> T retrieveBean(T bean) throws CpoException {
return processSelectGroup(bean, null, null, null, null);
} | java | @Override
public <T> T retrieveBean(T bean) throws CpoException {
return processSelectGroup(bean, null, null, null, null);
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"T",
"retrieveBean",
"(",
"T",
"bean",
")",
"throws",
"CpoException",
"{",
"return",
"processSelectGroup",
"(",
"bean",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}"
] | Retrieves the bean from the datasource. The assumption is that the bean exists in the datasource. If the retrieve
function defined for this beans returns more than one row, an exception will be thrown.
@param bean This is an bean that has been defined within the metadata of the datasource. If the class is not
defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. The
input bean is used to specify the search criteria, the output bean is populated with the results of the function.
@return An bean of the same type as the result argument that is filled in as specified the metadata for the
retireve.
@throws CpoException Thrown if there are errors accessing the datasource | [
"Retrieves",
"the",
"bean",
"from",
"the",
"datasource",
".",
"The",
"assumption",
"is",
"that",
"the",
"bean",
"exists",
"in",
"the",
"datasource",
".",
"If",
"the",
"retrieve",
"function",
"defined",
"for",
"this",
"beans",
"returns",
"more",
"than",
"one"... | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L1342-L1345 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsPushButton.java | CmsPushButton.setButtonStyle | public void setButtonStyle(I_CmsButton.ButtonStyle style, I_CmsButton.ButtonColor color) {
if (m_buttonStyle != null) {
for (String styleName : m_buttonStyle.getAdditionalClasses()) {
removeStyleName(styleName);
}
}
if (style == ButtonStyle.TRANSPARENT) {
setSize(null);
}
addStyleName(style.getCssClassName());
m_buttonStyle = style;
if (m_color != null) {
removeStyleName(m_color.getClassName());
}
if (color != null) {
addStyleName(color.getClassName());
}
m_color = color;
} | java | public void setButtonStyle(I_CmsButton.ButtonStyle style, I_CmsButton.ButtonColor color) {
if (m_buttonStyle != null) {
for (String styleName : m_buttonStyle.getAdditionalClasses()) {
removeStyleName(styleName);
}
}
if (style == ButtonStyle.TRANSPARENT) {
setSize(null);
}
addStyleName(style.getCssClassName());
m_buttonStyle = style;
if (m_color != null) {
removeStyleName(m_color.getClassName());
}
if (color != null) {
addStyleName(color.getClassName());
}
m_color = color;
} | [
"public",
"void",
"setButtonStyle",
"(",
"I_CmsButton",
".",
"ButtonStyle",
"style",
",",
"I_CmsButton",
".",
"ButtonColor",
"color",
")",
"{",
"if",
"(",
"m_buttonStyle",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"styleName",
":",
"m_buttonStyle",
".",
... | Sets the button style.<p>
@param style the style to set
@param color the color to set | [
"Sets",
"the",
"button",
"style",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsPushButton.java#L278-L298 |
alkacon/opencms-core | src/org/opencms/db/CmsUserSettings.java | CmsUserSettings.setAdditionalPreference | public static void setAdditionalPreference(CmsObject cms, String key, String value) {
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsUserSettings settings = new CmsUserSettings(user);
settings.setAdditionalPreference(key, value);
try {
settings.save(cms);
} catch (CmsException e) {
LOG.error("Could not store preference " + key + ": " + e.getLocalizedMessage(), e);
}
} | java | public static void setAdditionalPreference(CmsObject cms, String key, String value) {
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsUserSettings settings = new CmsUserSettings(user);
settings.setAdditionalPreference(key, value);
try {
settings.save(cms);
} catch (CmsException e) {
LOG.error("Could not store preference " + key + ": " + e.getLocalizedMessage(), e);
}
} | [
"public",
"static",
"void",
"setAdditionalPreference",
"(",
"CmsObject",
"cms",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"CmsUser",
"user",
"=",
"cms",
".",
"getRequestContext",
"(",
")",
".",
"getCurrentUser",
"(",
")",
";",
"CmsUserSettings",
... | Sets a configured preference.<p>
@param cms the Cms context
@param key the setting name
@param value the value | [
"Sets",
"a",
"configured",
"preference",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsUserSettings.java#L469-L479 |
venmo/cursor-utils | cursor-utils/src/main/java/com/venmo/cursor/CursorUtils.java | CursorUtils.consumeToArrayList | public static <T> ArrayList<T> consumeToArrayList(IterableCursor<T> cursor) {
return consumeToCollection(cursor, new ArrayList<T>(cursor.getCount()));
} | java | public static <T> ArrayList<T> consumeToArrayList(IterableCursor<T> cursor) {
return consumeToCollection(cursor, new ArrayList<T>(cursor.getCount()));
} | [
"public",
"static",
"<",
"T",
">",
"ArrayList",
"<",
"T",
">",
"consumeToArrayList",
"(",
"IterableCursor",
"<",
"T",
">",
"cursor",
")",
"{",
"return",
"consumeToCollection",
"(",
"cursor",
",",
"new",
"ArrayList",
"<",
"T",
">",
"(",
"cursor",
".",
"ge... | Returns an {@link java.util.ArrayList} of the {@link android.database.Cursor} and closes it. | [
"Returns",
"an",
"{"
] | train | https://github.com/venmo/cursor-utils/blob/52cf91c4253346632fe70b8d7b7eab8bbcc9b248/cursor-utils/src/main/java/com/venmo/cursor/CursorUtils.java#L42-L44 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.stringTemplate | @Deprecated
public static StringTemplate stringTemplate(Template template, ImmutableList<?> args) {
return new StringTemplate(template, args);
} | java | @Deprecated
public static StringTemplate stringTemplate(Template template, ImmutableList<?> args) {
return new StringTemplate(template, args);
} | [
"@",
"Deprecated",
"public",
"static",
"StringTemplate",
"stringTemplate",
"(",
"Template",
"template",
",",
"ImmutableList",
"<",
"?",
">",
"args",
")",
"{",
"return",
"new",
"StringTemplate",
"(",
"template",
",",
"args",
")",
";",
"}"
] | Create a new Template expression
@deprecated Use {@link #stringTemplate(Template, List)} instead.
@param template template
@param args template parameters
@return template expression | [
"Create",
"a",
"new",
"Template",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L937-L940 |
lessthanoptimal/BoofCV | examples/src/main/java/boofcv/examples/calibration/ExampleFisheyeToEquirectangular.java | ExampleFisheyeToEquirectangular.createMask | public static GrayU8 createMask( CameraUniversalOmni model ,
LensDistortionWideFOV distortion , double fov ) {
GrayU8 mask = new GrayU8(model.width,model.height);
Point2Transform3_F64 p2s = distortion.undistortPtoS_F64();
Point3D_F64 ref = new Point3D_F64(0,0,1);
Point3D_F64 X = new Point3D_F64();
p2s.compute(model.cx,model.cy,X);
for (int y = 0; y < model.height; y++) {
for (int x = 0; x < model.width; x++) {
p2s.compute(x,y,X);
if( Double.isNaN(X.x) || Double.isNaN(X.y) || Double.isNaN(X.z)) {
continue;
}
double angle = UtilVector3D_F64.acute(ref,X);
if( Double.isNaN(angle)) {
continue;
}
if( angle <= fov/2.0 )
mask.unsafe_set(x,y,1);
}
}
return mask;
} | java | public static GrayU8 createMask( CameraUniversalOmni model ,
LensDistortionWideFOV distortion , double fov ) {
GrayU8 mask = new GrayU8(model.width,model.height);
Point2Transform3_F64 p2s = distortion.undistortPtoS_F64();
Point3D_F64 ref = new Point3D_F64(0,0,1);
Point3D_F64 X = new Point3D_F64();
p2s.compute(model.cx,model.cy,X);
for (int y = 0; y < model.height; y++) {
for (int x = 0; x < model.width; x++) {
p2s.compute(x,y,X);
if( Double.isNaN(X.x) || Double.isNaN(X.y) || Double.isNaN(X.z)) {
continue;
}
double angle = UtilVector3D_F64.acute(ref,X);
if( Double.isNaN(angle)) {
continue;
}
if( angle <= fov/2.0 )
mask.unsafe_set(x,y,1);
}
}
return mask;
} | [
"public",
"static",
"GrayU8",
"createMask",
"(",
"CameraUniversalOmni",
"model",
",",
"LensDistortionWideFOV",
"distortion",
",",
"double",
"fov",
")",
"{",
"GrayU8",
"mask",
"=",
"new",
"GrayU8",
"(",
"model",
".",
"width",
",",
"model",
".",
"height",
")",
... | Creates a mask telling the algorithm which pixels are valid and which are not. The field-of-view (FOV) of the
camera is known so we will use that information to do a better job of filtering out invalid pixels than
it can do alone. | [
"Creates",
"a",
"mask",
"telling",
"the",
"algorithm",
"which",
"pixels",
"are",
"valid",
"and",
"which",
"are",
"not",
".",
"The",
"field",
"-",
"of",
"-",
"view",
"(",
"FOV",
")",
"of",
"the",
"camera",
"is",
"known",
"so",
"we",
"will",
"use",
"th... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/calibration/ExampleFisheyeToEquirectangular.java#L71-L98 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/url/WicketUrlExtensions.java | WicketUrlExtensions.toBaseUrl | public static String toBaseUrl(final Class<? extends Page> pageClass,
final PageParameters parameters)
{
return getBaseUrl(pageClass, parameters).canonical().toString();
} | java | public static String toBaseUrl(final Class<? extends Page> pageClass,
final PageParameters parameters)
{
return getBaseUrl(pageClass, parameters).canonical().toString();
} | [
"public",
"static",
"String",
"toBaseUrl",
"(",
"final",
"Class",
"<",
"?",
"extends",
"Page",
">",
"pageClass",
",",
"final",
"PageParameters",
"parameters",
")",
"{",
"return",
"getBaseUrl",
"(",
"pageClass",
",",
"parameters",
")",
".",
"canonical",
"(",
... | Gets the base ur as String.
@param pageClass
the page class
@param parameters
the parameters
@return the base url as String. | [
"Gets",
"the",
"base",
"ur",
"as",
"String",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/url/WicketUrlExtensions.java#L416-L420 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/ExpressionUtils.java | ExpressionUtils.predicateTemplate | public static PredicateTemplate predicateTemplate(Template template, List<?> args) {
return new PredicateTemplate(template, ImmutableList.copyOf(args));
} | java | public static PredicateTemplate predicateTemplate(Template template, List<?> args) {
return new PredicateTemplate(template, ImmutableList.copyOf(args));
} | [
"public",
"static",
"PredicateTemplate",
"predicateTemplate",
"(",
"Template",
"template",
",",
"List",
"<",
"?",
">",
"args",
")",
"{",
"return",
"new",
"PredicateTemplate",
"(",
"template",
",",
"ImmutableList",
".",
"copyOf",
"(",
"args",
")",
")",
";",
"... | Create a new Template expression
@param template template
@param args template parameters
@return template expression | [
"Create",
"a",
"new",
"Template",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/ExpressionUtils.java#L201-L203 |
akarnokd/akarnokd-xml | src/main/java/hu/akarnokd/xml/XNSerializables.java | XNSerializables.storeList | public static XNElement storeList(String container, String item, Iterable<? extends XNSerializable> source) {
XNElement result = new XNElement(container);
for (XNSerializable e : source) {
e.save(result.add(item));
}
return result;
} | java | public static XNElement storeList(String container, String item, Iterable<? extends XNSerializable> source) {
XNElement result = new XNElement(container);
for (XNSerializable e : source) {
e.save(result.add(item));
}
return result;
} | [
"public",
"static",
"XNElement",
"storeList",
"(",
"String",
"container",
",",
"String",
"item",
",",
"Iterable",
"<",
"?",
"extends",
"XNSerializable",
">",
"source",
")",
"{",
"XNElement",
"result",
"=",
"new",
"XNElement",
"(",
"container",
")",
";",
"for... | Create an XNElement with the given name and items stored from the source sequence.
@param container the container name
@param item the item name
@param source the source of items
@return the list in XNElement | [
"Create",
"an",
"XNElement",
"with",
"the",
"given",
"name",
"and",
"items",
"stored",
"from",
"the",
"source",
"sequence",
"."
] | train | https://github.com/akarnokd/akarnokd-xml/blob/57466a5a9cb455a13d7121557c165287b31ee870/src/main/java/hu/akarnokd/xml/XNSerializables.java#L92-L98 |
WiQuery/wiquery | wiquery-core/src/main/java/org/odlabs/wiquery/core/options/Options.java | Options.putBoolean | public Options putBoolean(String key, IModel<Boolean> value)
{
putOption(key, new BooleanOption(value));
return this;
} | java | public Options putBoolean(String key, IModel<Boolean> value)
{
putOption(key, new BooleanOption(value));
return this;
} | [
"public",
"Options",
"putBoolean",
"(",
"String",
"key",
",",
"IModel",
"<",
"Boolean",
">",
"value",
")",
"{",
"putOption",
"(",
"key",
",",
"new",
"BooleanOption",
"(",
"value",
")",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Put an boolean value for the given option name.
</p>
@param key
the option name.
@param value
the boolean value. | [
"<p",
">",
"Put",
"an",
"boolean",
"value",
"for",
"the",
"given",
"option",
"name",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-core/src/main/java/org/odlabs/wiquery/core/options/Options.java#L355-L359 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/Medias.java | Medias.getWithSuffix | public static synchronized Media getWithSuffix(Media media, String suffix)
{
Check.notNull(media);
Check.notNull(suffix);
final String path = media.getPath();
final int dotIndex = path.lastIndexOf(Constant.DOT);
if (dotIndex > -1)
{
return Medias.create(path.substring(0, dotIndex) + Constant.UNDERSCORE + suffix + path.substring(dotIndex));
}
return Medias.create(path + Constant.UNDERSCORE + suffix);
} | java | public static synchronized Media getWithSuffix(Media media, String suffix)
{
Check.notNull(media);
Check.notNull(suffix);
final String path = media.getPath();
final int dotIndex = path.lastIndexOf(Constant.DOT);
if (dotIndex > -1)
{
return Medias.create(path.substring(0, dotIndex) + Constant.UNDERSCORE + suffix + path.substring(dotIndex));
}
return Medias.create(path + Constant.UNDERSCORE + suffix);
} | [
"public",
"static",
"synchronized",
"Media",
"getWithSuffix",
"(",
"Media",
"media",
",",
"String",
"suffix",
")",
"{",
"Check",
".",
"notNull",
"(",
"media",
")",
";",
"Check",
".",
"notNull",
"(",
"suffix",
")",
";",
"final",
"String",
"path",
"=",
"me... | Get the media with an additional suffix, just before the dot of the extension if has.
@param media The current media reference (must not be <code>null</code>).
@param suffix The suffix to add (must not be <code>null</code>).
@return The new media with suffix added.
@throws LionEngineException If invalid parameters. | [
"Get",
"the",
"media",
"with",
"an",
"additional",
"suffix",
"just",
"before",
"the",
"dot",
"of",
"the",
"extension",
"if",
"has",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/Medias.java#L192-L204 |
google/error-prone | check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java | BugChecker.describeMatch | @CheckReturnValue
protected Description describeMatch(JCTree node, Fix fix) {
return describeMatch((Tree) node, fix);
} | java | @CheckReturnValue
protected Description describeMatch(JCTree node, Fix fix) {
return describeMatch((Tree) node, fix);
} | [
"@",
"CheckReturnValue",
"protected",
"Description",
"describeMatch",
"(",
"JCTree",
"node",
",",
"Fix",
"fix",
")",
"{",
"return",
"describeMatch",
"(",
"(",
"Tree",
")",
"node",
",",
"fix",
")",
";",
"}"
] | Helper to create a Description for the common case where there is a fix. | [
"Helper",
"to",
"create",
"a",
"Description",
"for",
"the",
"common",
"case",
"where",
"there",
"is",
"a",
"fix",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java#L117-L120 |
jbossws/jbossws-common | src/main/java/org/jboss/ws/common/JavaUtils.java | JavaUtils.isAssignableFrom | public static boolean isAssignableFrom(Class<?> dest, Class<?> src)
{
if (dest == null || src == null)
throw MESSAGES.cannotCheckClassIsAssignableFrom(dest, src);
boolean isAssignable = dest.isAssignableFrom(src);
if (isAssignable == false && dest.getName().equals(src.getName()))
{
ClassLoader destLoader = dest.getClassLoader();
ClassLoader srcLoader = src.getClassLoader();
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.notAssignableDueToConflictingClassLoaders(dest, src, destLoader, srcLoader);
}
if (isAssignable == false && isPrimitive(dest))
{
dest = getWrapperType(dest);
isAssignable = dest.isAssignableFrom(src);
}
if (isAssignable == false && isPrimitive(src))
{
src = getWrapperType(src);
isAssignable = dest.isAssignableFrom(src);
}
return isAssignable;
} | java | public static boolean isAssignableFrom(Class<?> dest, Class<?> src)
{
if (dest == null || src == null)
throw MESSAGES.cannotCheckClassIsAssignableFrom(dest, src);
boolean isAssignable = dest.isAssignableFrom(src);
if (isAssignable == false && dest.getName().equals(src.getName()))
{
ClassLoader destLoader = dest.getClassLoader();
ClassLoader srcLoader = src.getClassLoader();
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.notAssignableDueToConflictingClassLoaders(dest, src, destLoader, srcLoader);
}
if (isAssignable == false && isPrimitive(dest))
{
dest = getWrapperType(dest);
isAssignable = dest.isAssignableFrom(src);
}
if (isAssignable == false && isPrimitive(src))
{
src = getWrapperType(src);
isAssignable = dest.isAssignableFrom(src);
}
return isAssignable;
} | [
"public",
"static",
"boolean",
"isAssignableFrom",
"(",
"Class",
"<",
"?",
">",
"dest",
",",
"Class",
"<",
"?",
">",
"src",
")",
"{",
"if",
"(",
"dest",
"==",
"null",
"||",
"src",
"==",
"null",
")",
"throw",
"MESSAGES",
".",
"cannotCheckClassIsAssignable... | Return true if the dest class is assignable from the src.
Also handles arrays and primitives. | [
"Return",
"true",
"if",
"the",
"dest",
"class",
"is",
"assignable",
"from",
"the",
"src",
".",
"Also",
"handles",
"arrays",
"and",
"primitives",
"."
] | train | https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/JavaUtils.java#L454-L478 |
cogroo/cogroo4 | cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/util/TagMaskUtils.java | TagMaskUtils.createTagMaskFromToken | public static TagMask createTagMaskFromToken(Token token, String text) {
TagMask tm = new TagMask();
Matcher m = REPLACE_R2.matcher(text);
while (m.find()) {
String property = m.group(1);
switch (property) {
case "number":
tm.setNumber(token.getMorphologicalTag().getNumberE());
break;
case "gender":
tm.setGender(token.getMorphologicalTag().getGenderE());
break;
case "class":
tm.setClazz(token.getMorphologicalTag().getClazzE());
break;
case "person":
tm.setPerson(token.getMorphologicalTag().getPersonE());
break;
case "tense":
tm.setTense(token.getMorphologicalTag().getTense());
break;
case "mood":
tm.setMood(token.getMorphologicalTag().getMood());
break;
default:
break;
}
}
return tm;
} | java | public static TagMask createTagMaskFromToken(Token token, String text) {
TagMask tm = new TagMask();
Matcher m = REPLACE_R2.matcher(text);
while (m.find()) {
String property = m.group(1);
switch (property) {
case "number":
tm.setNumber(token.getMorphologicalTag().getNumberE());
break;
case "gender":
tm.setGender(token.getMorphologicalTag().getGenderE());
break;
case "class":
tm.setClazz(token.getMorphologicalTag().getClazzE());
break;
case "person":
tm.setPerson(token.getMorphologicalTag().getPersonE());
break;
case "tense":
tm.setTense(token.getMorphologicalTag().getTense());
break;
case "mood":
tm.setMood(token.getMorphologicalTag().getMood());
break;
default:
break;
}
}
return tm;
} | [
"public",
"static",
"TagMask",
"createTagMaskFromToken",
"(",
"Token",
"token",
",",
"String",
"text",
")",
"{",
"TagMask",
"tm",
"=",
"new",
"TagMask",
"(",
")",
";",
"Matcher",
"m",
"=",
"REPLACE_R2",
".",
"matcher",
"(",
"text",
")",
";",
"while",
"("... | Returns a TagMask with the attributes collected from the given token.
@param token
the token whose attributes will be collected.
@param text
a string containing the attributes to get from the token,
e.g., "number gender"
@returna a TagMask object with the attributes collected | [
"Returns",
"a",
"TagMask",
"with",
"the",
"attributes",
"collected",
"from",
"the",
"given",
"token",
"."
] | train | https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/util/TagMaskUtils.java#L115-L146 |
betfair/cougar | cougar-framework/net-util/src/main/java/com/betfair/cougar/netutil/InetSocketAddressUtils.java | InetSocketAddressUtils.createInetSocketAddress | public static InetSocketAddress createInetSocketAddress(String address, int defaultPort) {
String original = address.trim();
String host = original;
int port = defaultPort;
if (host.startsWith("[")) {
// it is an address in [host] or [host]port format
String[] s = original.split("\\]");
if (s.length > 1) {
if (s[1].startsWith(":")) {
s[1] = s[1].substring(1);
}
port = computePort(s[1], 0);
}
host = s[0].substring(1);
}
if (host.indexOf(":") == host.lastIndexOf(":") && (host.indexOf(":") > -1)) {
//There is exactly 1 ':' in the string, hence this is an IP4 address which includes a port
String[] s = original.split("\\:");
host = s[0];
if (s.length > 1) {
port = computePort(s[1], 0);
}
}
return new InetSocketAddress(host, port);
} | java | public static InetSocketAddress createInetSocketAddress(String address, int defaultPort) {
String original = address.trim();
String host = original;
int port = defaultPort;
if (host.startsWith("[")) {
// it is an address in [host] or [host]port format
String[] s = original.split("\\]");
if (s.length > 1) {
if (s[1].startsWith(":")) {
s[1] = s[1].substring(1);
}
port = computePort(s[1], 0);
}
host = s[0].substring(1);
}
if (host.indexOf(":") == host.lastIndexOf(":") && (host.indexOf(":") > -1)) {
//There is exactly 1 ':' in the string, hence this is an IP4 address which includes a port
String[] s = original.split("\\:");
host = s[0];
if (s.length > 1) {
port = computePort(s[1], 0);
}
}
return new InetSocketAddress(host, port);
} | [
"public",
"static",
"InetSocketAddress",
"createInetSocketAddress",
"(",
"String",
"address",
",",
"int",
"defaultPort",
")",
"{",
"String",
"original",
"=",
"address",
".",
"trim",
"(",
")",
";",
"String",
"host",
"=",
"original",
";",
"int",
"port",
"=",
"... | <p>Creates an InetSocketAddress given a host and optional port in a single String
<p/>
<p>This allows either IP4 or IP6 addresses (including port) to be provided as Strings as per rfc2732</p>
@param address the address in one of the following formats (the braces '[]'and colon ':' are literal here):
host<br>
[host]<br>
[host]:port<br>
[host]port<br>
ip4host:port<br>
@param defaultPort The default port to be used ONLY IF the string does not specify a port
@see java.net.InetSocketAddress | [
"<p",
">",
"Creates",
"an",
"InetSocketAddress",
"given",
"a",
"host",
"and",
"optional",
"port",
"in",
"a",
"single",
"String",
"<p",
"/",
">",
"<p",
">",
"This",
"allows",
"either",
"IP4",
"or",
"IP6",
"addresses",
"(",
"including",
"port",
")",
"to",
... | train | https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/net-util/src/main/java/com/betfair/cougar/netutil/InetSocketAddressUtils.java#L95-L122 |
autermann/yaml | src/main/java/com/github/autermann/yaml/Yaml.java | Yaml.dumpAll | public void dumpAll(Iterable<? extends YamlNode> data, OutputStream output) {
dumpAll(data.iterator(), output);
} | java | public void dumpAll(Iterable<? extends YamlNode> data, OutputStream output) {
dumpAll(data.iterator(), output);
} | [
"public",
"void",
"dumpAll",
"(",
"Iterable",
"<",
"?",
"extends",
"YamlNode",
">",
"data",
",",
"OutputStream",
"output",
")",
"{",
"dumpAll",
"(",
"data",
".",
"iterator",
"(",
")",
",",
"output",
")",
";",
"}"
] | Dumps {@code data} into a {@code OutputStream} using a {@code UTF-8}
encoding.
@param data the data
@param output the output stream | [
"Dumps",
"{",
"@code",
"data",
"}",
"into",
"a",
"{",
"@code",
"OutputStream",
"}",
"using",
"a",
"{",
"@code",
"UTF",
"-",
"8",
"}",
"encoding",
"."
] | train | https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/Yaml.java#L198-L200 |
Ekryd/sortpom | sorter/src/main/java/sortpom/wrapper/WrapperFactoryImpl.java | WrapperFactoryImpl.addElementsToSortOrderMap | private void addElementsToSortOrderMap(final Element element, int baseSortOrder) {
elementSortOrderMap.addElement(element, baseSortOrder);
final List<Element> castToChildElementList = castToChildElementList(element);
// Increments the sort order index for each element
int sortOrder = baseSortOrder;
for (Element child : castToChildElementList) {
sortOrder += SORT_ORDER_INCREMENT;
addElementsToSortOrderMap(child, sortOrder);
}
} | java | private void addElementsToSortOrderMap(final Element element, int baseSortOrder) {
elementSortOrderMap.addElement(element, baseSortOrder);
final List<Element> castToChildElementList = castToChildElementList(element);
// Increments the sort order index for each element
int sortOrder = baseSortOrder;
for (Element child : castToChildElementList) {
sortOrder += SORT_ORDER_INCREMENT;
addElementsToSortOrderMap(child, sortOrder);
}
} | [
"private",
"void",
"addElementsToSortOrderMap",
"(",
"final",
"Element",
"element",
",",
"int",
"baseSortOrder",
")",
"{",
"elementSortOrderMap",
".",
"addElement",
"(",
"element",
",",
"baseSortOrder",
")",
";",
"final",
"List",
"<",
"Element",
">",
"castToChildE... | Processes the chosen sort order. Adds sort order element and sort index to
a map. | [
"Processes",
"the",
"chosen",
"sort",
"order",
".",
"Adds",
"sort",
"order",
"element",
"and",
"sort",
"index",
"to",
"a",
"map",
"."
] | train | https://github.com/Ekryd/sortpom/blob/27056420803ed04001e4149b04a719fbac774c5d/sorter/src/main/java/sortpom/wrapper/WrapperFactoryImpl.java#L84-L93 |
alkacon/opencms-core | src/org/opencms/util/PrintfFormat.java | PrintfFormat.nonControl | private String nonControl(String s, int start) {
m_cPos = s.indexOf("%", start);
if (m_cPos == -1) {
m_cPos = s.length();
}
return s.substring(start, m_cPos);
} | java | private String nonControl(String s, int start) {
m_cPos = s.indexOf("%", start);
if (m_cPos == -1) {
m_cPos = s.length();
}
return s.substring(start, m_cPos);
} | [
"private",
"String",
"nonControl",
"(",
"String",
"s",
",",
"int",
"start",
")",
"{",
"m_cPos",
"=",
"s",
".",
"indexOf",
"(",
"\"%\"",
",",
"start",
")",
";",
"if",
"(",
"m_cPos",
"==",
"-",
"1",
")",
"{",
"m_cPos",
"=",
"s",
".",
"length",
"(",... | Return a substring starting at
<code>start</code> and ending at either the end
of the String <code>s</code>, the next unpaired
percent sign, or at the end of the String if the
last character is a percent sign.
@param s Control string.
@param start Position in the string
<code>s</code> to begin looking for the start
of a control string.
@return the substring from the start position
to the beginning of the control string. | [
"Return",
"a",
"substring",
"starting",
"at",
"<code",
">",
"start<",
"/",
"code",
">",
"and",
"ending",
"at",
"either",
"the",
"end",
"of",
"the",
"String",
"<code",
">",
"s<",
"/",
"code",
">",
"the",
"next",
"unpaired",
"percent",
"sign",
"or",
"at"... | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/PrintfFormat.java#L3681-L3688 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java | PerceptronClassifier.trainNaivePerceptron | private static LinearModel trainNaivePerceptron(Instance[] instanceList, FeatureMap featureMap, int maxIteration)
{
LinearModel model = new LinearModel(featureMap, new float[featureMap.size()]);
for (int it = 0; it < maxIteration; ++it)
{
Utility.shuffleArray(instanceList);
for (Instance instance : instanceList)
{
int y = model.decode(instance.x);
if (y != instance.y) // 误差反馈
model.update(instance.x, instance.y);
}
}
return model;
} | java | private static LinearModel trainNaivePerceptron(Instance[] instanceList, FeatureMap featureMap, int maxIteration)
{
LinearModel model = new LinearModel(featureMap, new float[featureMap.size()]);
for (int it = 0; it < maxIteration; ++it)
{
Utility.shuffleArray(instanceList);
for (Instance instance : instanceList)
{
int y = model.decode(instance.x);
if (y != instance.y) // 误差反馈
model.update(instance.x, instance.y);
}
}
return model;
} | [
"private",
"static",
"LinearModel",
"trainNaivePerceptron",
"(",
"Instance",
"[",
"]",
"instanceList",
",",
"FeatureMap",
"featureMap",
",",
"int",
"maxIteration",
")",
"{",
"LinearModel",
"model",
"=",
"new",
"LinearModel",
"(",
"featureMap",
",",
"new",
"float",... | 朴素感知机训练算法
@param instanceList 训练实例
@param featureMap 特征函数
@param maxIteration 训练迭代次数 | [
"朴素感知机训练算法"
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java#L57-L71 |
vkostyukov/la4j | src/main/java/org/la4j/Matrix.java | Matrix.eachInColumn | public void eachInColumn(int j, VectorProcedure procedure) {
VectorIterator it = iteratorOfColumn(j);
while (it.hasNext()) {
double x = it.next();
int i = it.index();
procedure.apply(i, x);
}
} | java | public void eachInColumn(int j, VectorProcedure procedure) {
VectorIterator it = iteratorOfColumn(j);
while (it.hasNext()) {
double x = it.next();
int i = it.index();
procedure.apply(i, x);
}
} | [
"public",
"void",
"eachInColumn",
"(",
"int",
"j",
",",
"VectorProcedure",
"procedure",
")",
"{",
"VectorIterator",
"it",
"=",
"iteratorOfColumn",
"(",
"j",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"double",
"x",
"=",
"it",
"."... | Applies given {@code procedure} to each element of specified column of this matrix.
@param j the column index
@param procedure the vector procedure | [
"Applies",
"given",
"{",
"@code",
"procedure",
"}",
"to",
"each",
"element",
"of",
"specified",
"column",
"of",
"this",
"matrix",
"."
] | train | https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrix.java#L1400-L1408 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnDivisiveNormalizationForward | public static int cudnnDivisiveNormalizationForward(
cudnnHandle handle,
cudnnLRNDescriptor normDesc,
int mode,
Pointer alpha,
cudnnTensorDescriptor xDesc, /** same desc for means, temp, temp2 */
Pointer x,
Pointer means, /** if NULL, means are assumed to be zero */
Pointer temp,
Pointer temp2,
Pointer beta,
cudnnTensorDescriptor yDesc,
Pointer y)
{
return checkResult(cudnnDivisiveNormalizationForwardNative(handle, normDesc, mode, alpha, xDesc, x, means, temp, temp2, beta, yDesc, y));
} | java | public static int cudnnDivisiveNormalizationForward(
cudnnHandle handle,
cudnnLRNDescriptor normDesc,
int mode,
Pointer alpha,
cudnnTensorDescriptor xDesc, /** same desc for means, temp, temp2 */
Pointer x,
Pointer means, /** if NULL, means are assumed to be zero */
Pointer temp,
Pointer temp2,
Pointer beta,
cudnnTensorDescriptor yDesc,
Pointer y)
{
return checkResult(cudnnDivisiveNormalizationForwardNative(handle, normDesc, mode, alpha, xDesc, x, means, temp, temp2, beta, yDesc, y));
} | [
"public",
"static",
"int",
"cudnnDivisiveNormalizationForward",
"(",
"cudnnHandle",
"handle",
",",
"cudnnLRNDescriptor",
"normDesc",
",",
"int",
"mode",
",",
"Pointer",
"alpha",
",",
"cudnnTensorDescriptor",
"xDesc",
",",
"/** same desc for means, temp, temp2 */",
"Pointer"... | LCN/divisive normalization functions: y = alpha * normalize(x) + beta * y | [
"LCN",
"/",
"divisive",
"normalization",
"functions",
":",
"y",
"=",
"alpha",
"*",
"normalize",
"(",
"x",
")",
"+",
"beta",
"*",
"y"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2114-L2129 |
Metatavu/edelphi | rest/src/main/java/fi/metatavu/edelphi/queries/QueryController.java | QueryController.isPanelsQuery | public boolean isPanelsQuery(Query query, Panel panel) {
Panel queryPanel = resourceController.getResourcePanel(query);
if (queryPanel == null || panel == null) {
return false;
}
return queryPanel.getId().equals(panel.getId());
} | java | public boolean isPanelsQuery(Query query, Panel panel) {
Panel queryPanel = resourceController.getResourcePanel(query);
if (queryPanel == null || panel == null) {
return false;
}
return queryPanel.getId().equals(panel.getId());
} | [
"public",
"boolean",
"isPanelsQuery",
"(",
"Query",
"query",
",",
"Panel",
"panel",
")",
"{",
"Panel",
"queryPanel",
"=",
"resourceController",
".",
"getResourcePanel",
"(",
"query",
")",
";",
"if",
"(",
"queryPanel",
"==",
"null",
"||",
"panel",
"==",
"null... | Returns whether query belongs to given panel
@param query query
@param panel panel
@return whether query belongs to given panel | [
"Returns",
"whether",
"query",
"belongs",
"to",
"given",
"panel"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/rest/src/main/java/fi/metatavu/edelphi/queries/QueryController.java#L106-L113 |
super-csv/super-csv | super-csv/src/main/java/org/supercsv/cellprocessor/FmtDate.java | FmtDate.execute | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
if( !(value instanceof Date) ) {
throw new SuperCsvCellProcessorException(Date.class, value, context, this);
}
final SimpleDateFormat formatter;
try {
formatter = new SimpleDateFormat(dateFormat);
}
catch(IllegalArgumentException e) {
throw new SuperCsvCellProcessorException(String.format("'%s' is not a valid date format", dateFormat),
context, this, e);
}
String result = formatter.format((Date) value);
return next.execute(result, context);
} | java | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
if( !(value instanceof Date) ) {
throw new SuperCsvCellProcessorException(Date.class, value, context, this);
}
final SimpleDateFormat formatter;
try {
formatter = new SimpleDateFormat(dateFormat);
}
catch(IllegalArgumentException e) {
throw new SuperCsvCellProcessorException(String.format("'%s' is not a valid date format", dateFormat),
context, this, e);
}
String result = formatter.format((Date) value);
return next.execute(result, context);
} | [
"public",
"Object",
"execute",
"(",
"final",
"Object",
"value",
",",
"final",
"CsvContext",
"context",
")",
"{",
"validateInputNotNull",
"(",
"value",
",",
"context",
")",
";",
"if",
"(",
"!",
"(",
"value",
"instanceof",
"Date",
")",
")",
"{",
"throw",
"... | {@inheritDoc}
@throws SuperCsvCellProcessorException
if value is null or is not a Date, or if dateFormat is not a valid date format | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/FmtDate.java#L96-L114 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_cluster.java | ns_cluster.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ns_cluster_responses result = (ns_cluster_responses) service.get_payload_formatter().string_to_resource(ns_cluster_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_cluster_response_array);
}
ns_cluster[] result_ns_cluster = new ns_cluster[result.ns_cluster_response_array.length];
for(int i = 0; i < result.ns_cluster_response_array.length; i++)
{
result_ns_cluster[i] = result.ns_cluster_response_array[i].ns_cluster[0];
}
return result_ns_cluster;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ns_cluster_responses result = (ns_cluster_responses) service.get_payload_formatter().string_to_resource(ns_cluster_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_cluster_response_array);
}
ns_cluster[] result_ns_cluster = new ns_cluster[result.ns_cluster_response_array.length];
for(int i = 0; i < result.ns_cluster_response_array.length; i++)
{
result_ns_cluster[i] = result.ns_cluster_response_array[i].ns_cluster[0];
}
return result_ns_cluster;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"ns_cluster_responses",
"result",
"=",
"(",
"ns_cluster_responses",
")",
"service",
".",
"get_payload_formatte... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_cluster.java#L737-L754 |
phax/ph-schedule | ph-mini-quartz/src/main/java/com/helger/quartz/TriggerBuilder.java | TriggerBuilder.withIdentity | @Nonnull
public TriggerBuilder <T> withIdentity (final String name, final String group)
{
m_aKey = new TriggerKey (name, group);
return this;
} | java | @Nonnull
public TriggerBuilder <T> withIdentity (final String name, final String group)
{
m_aKey = new TriggerKey (name, group);
return this;
} | [
"@",
"Nonnull",
"public",
"TriggerBuilder",
"<",
"T",
">",
"withIdentity",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"group",
")",
"{",
"m_aKey",
"=",
"new",
"TriggerKey",
"(",
"name",
",",
"group",
")",
";",
"return",
"this",
";",
"}"
] | Use a TriggerKey with the given name and group to identify the Trigger.
<p>
If none of the 'withIdentity' methods are set on the TriggerBuilder, then a
random, unique TriggerKey will be generated.
</p>
@param name
the name element for the Trigger's TriggerKey
@param group
the group element for the Trigger's TriggerKey
@return the updated TriggerBuilder
@see TriggerKey
@see ITrigger#getKey() | [
"Use",
"a",
"TriggerKey",
"with",
"the",
"given",
"name",
"and",
"group",
"to",
"identify",
"the",
"Trigger",
".",
"<p",
">",
"If",
"none",
"of",
"the",
"withIdentity",
"methods",
"are",
"set",
"on",
"the",
"TriggerBuilder",
"then",
"a",
"random",
"unique"... | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/TriggerBuilder.java#L154-L159 |
jlinn/quartz-redis-jobstore | src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java | AbstractRedisStorage.setTriggerState | public boolean setTriggerState(final RedisTriggerState state, final double score, final String triggerHashKey, T jedis) throws JobPersistenceException{
boolean success = false;
if(state != null){
unsetTriggerState(triggerHashKey, jedis);
success = jedis.zadd(redisSchema.triggerStateKey(state), score, triggerHashKey) == 1;
}
return success;
} | java | public boolean setTriggerState(final RedisTriggerState state, final double score, final String triggerHashKey, T jedis) throws JobPersistenceException{
boolean success = false;
if(state != null){
unsetTriggerState(triggerHashKey, jedis);
success = jedis.zadd(redisSchema.triggerStateKey(state), score, triggerHashKey) == 1;
}
return success;
} | [
"public",
"boolean",
"setTriggerState",
"(",
"final",
"RedisTriggerState",
"state",
",",
"final",
"double",
"score",
",",
"final",
"String",
"triggerHashKey",
",",
"T",
"jedis",
")",
"throws",
"JobPersistenceException",
"{",
"boolean",
"success",
"=",
"false",
";"... | Set a trigger state by adding the trigger to the relevant sorted set, using its next fire time as the score.
@param state the new state to be set
@param score the trigger's next fire time
@param triggerHashKey the trigger hash key
@param jedis a thread-safe Redis connection
@return true if set, false if the trigger was already a member of the given state's sorted set and its score was updated
@throws JobPersistenceException if the set operation fails | [
"Set",
"a",
"trigger",
"state",
"by",
"adding",
"the",
"trigger",
"to",
"the",
"relevant",
"sorted",
"set",
"using",
"its",
"next",
"fire",
"time",
"as",
"the",
"score",
"."
] | train | https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java#L338-L345 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.setTranslation | public Matrix4d setTranslation(double x, double y, double z) {
m30 = x;
m31 = y;
m32 = z;
properties &= ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY);
return this;
} | java | public Matrix4d setTranslation(double x, double y, double z) {
m30 = x;
m31 = y;
m32 = z;
properties &= ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY);
return this;
} | [
"public",
"Matrix4d",
"setTranslation",
"(",
"double",
"x",
",",
"double",
"y",
",",
"double",
"z",
")",
"{",
"m30",
"=",
"x",
";",
"m31",
"=",
"y",
";",
"m32",
"=",
"z",
";",
"properties",
"&=",
"~",
"(",
"PROPERTY_PERSPECTIVE",
"|",
"PROPERTY_IDENTIT... | Set only the translation components <code>(m30, m31, m32)</code> of this matrix to the given values <code>(x, y, z)</code>.
<p>
To build a translation matrix instead, use {@link #translation(double, double, double)}.
To apply a translation, use {@link #translate(double, double, double)}.
@see #translation(double, double, double)
@see #translate(double, double, double)
@param x
the units to translate in x
@param y
the units to translate in y
@param z
the units to translate in z
@return this | [
"Set",
"only",
"the",
"translation",
"components",
"<code",
">",
"(",
"m30",
"m31",
"m32",
")",
"<",
"/",
"code",
">",
"of",
"this",
"matrix",
"to",
"the",
"given",
"values",
"<code",
">",
"(",
"x",
"y",
"z",
")",
"<",
"/",
"code",
">",
".",
"<p"... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L3173-L3179 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldTracker.java | TldTracker.hypothesisFusion | protected boolean hypothesisFusion( boolean trackingWorked , boolean detectionWorked ) {
valid = false;
boolean uniqueDetection = detectionWorked && !detection.isAmbiguous();
TldRegion detectedRegion = detection.getBest();
double confidenceTarget;
if( trackingWorked ) {
// get the scores from tracking and detection
double scoreTrack = template.computeConfidence(trackerRegion_I32);
double scoreDetected = 0;
if( uniqueDetection ) {
scoreDetected = detectedRegion.confidence;
}
double adjustment = strongMatch ? 0.07 : 0.02;
if( uniqueDetection && scoreDetected > scoreTrack + adjustment ) {
// if there is a unique detection and it has higher confidence than the
// track region, use the detected region
TldHelperFunctions.convertRegion(detectedRegion.rect, targetRegion);
confidenceTarget = detectedRegion.confidence;
// if it's far away from the current track, re-evaluate if it's a strongMatch
checkNewTrackStrong(scoreDetected);
} else {
// Otherwise use the tracker region
targetRegion.set(trackerRegion);
confidenceTarget = scoreTrack;
strongMatch |= confidenceTarget > config.confidenceThresholdStrong;
// see if the most likely detected region overlaps the track region
if( strongMatch && confidenceTarget >= config.confidenceThresholdLower ) {
valid = true;
}
}
} else if( uniqueDetection ) {
// just go with the best detected region
detectedRegion = detection.getBest();
TldHelperFunctions.convertRegion(detectedRegion.rect, targetRegion);
confidenceTarget = detectedRegion.confidence;
strongMatch = confidenceTarget > config.confidenceThresholdStrong;
} else {
return false;
}
return confidenceTarget >= config.confidenceAccept;
} | java | protected boolean hypothesisFusion( boolean trackingWorked , boolean detectionWorked ) {
valid = false;
boolean uniqueDetection = detectionWorked && !detection.isAmbiguous();
TldRegion detectedRegion = detection.getBest();
double confidenceTarget;
if( trackingWorked ) {
// get the scores from tracking and detection
double scoreTrack = template.computeConfidence(trackerRegion_I32);
double scoreDetected = 0;
if( uniqueDetection ) {
scoreDetected = detectedRegion.confidence;
}
double adjustment = strongMatch ? 0.07 : 0.02;
if( uniqueDetection && scoreDetected > scoreTrack + adjustment ) {
// if there is a unique detection and it has higher confidence than the
// track region, use the detected region
TldHelperFunctions.convertRegion(detectedRegion.rect, targetRegion);
confidenceTarget = detectedRegion.confidence;
// if it's far away from the current track, re-evaluate if it's a strongMatch
checkNewTrackStrong(scoreDetected);
} else {
// Otherwise use the tracker region
targetRegion.set(trackerRegion);
confidenceTarget = scoreTrack;
strongMatch |= confidenceTarget > config.confidenceThresholdStrong;
// see if the most likely detected region overlaps the track region
if( strongMatch && confidenceTarget >= config.confidenceThresholdLower ) {
valid = true;
}
}
} else if( uniqueDetection ) {
// just go with the best detected region
detectedRegion = detection.getBest();
TldHelperFunctions.convertRegion(detectedRegion.rect, targetRegion);
confidenceTarget = detectedRegion.confidence;
strongMatch = confidenceTarget > config.confidenceThresholdStrong;
} else {
return false;
}
return confidenceTarget >= config.confidenceAccept;
} | [
"protected",
"boolean",
"hypothesisFusion",
"(",
"boolean",
"trackingWorked",
",",
"boolean",
"detectionWorked",
")",
"{",
"valid",
"=",
"false",
";",
"boolean",
"uniqueDetection",
"=",
"detectionWorked",
"&&",
"!",
"detection",
".",
"isAmbiguous",
"(",
")",
";",
... | Combines hypotheses from tracking and detection.
@param trackingWorked If the sequential tracker updated the track region successfully or not
@return true a hypothesis was found, false if it failed to find a hypothesis | [
"Combines",
"hypotheses",
"from",
"tracking",
"and",
"detection",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldTracker.java#L332-L385 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectSomeValuesFromImpl_CustomFieldSerializer.java | OWLObjectSomeValuesFromImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectSomeValuesFromImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectSomeValuesFromImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLObjectSomeValuesFromImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
] | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectSomeValuesFromImpl_CustomFieldSerializer.java#L93-L96 |
xdcrafts/flower | flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java | MapApi.getString | public static Optional<String> getString(final Map map, final Object... path) {
return get(map, String.class, path);
} | java | public static Optional<String> getString(final Map map, final Object... path) {
return get(map, String.class, path);
} | [
"public",
"static",
"Optional",
"<",
"String",
">",
"getString",
"(",
"final",
"Map",
"map",
",",
"final",
"Object",
"...",
"path",
")",
"{",
"return",
"get",
"(",
"map",
",",
"String",
".",
"class",
",",
"path",
")",
";",
"}"
] | Get string value by path.
@param map subject
@param path nodes to walk in map
@return value | [
"Get",
"string",
"value",
"by",
"path",
"."
] | train | https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java#L167-L169 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/SessionDataManager.java | SessionDataManager.readItem | protected ItemImpl readItem(ItemData itemData, boolean pool) throws RepositoryException
{
return readItem(itemData, null, pool, true);
} | java | protected ItemImpl readItem(ItemData itemData, boolean pool) throws RepositoryException
{
return readItem(itemData, null, pool, true);
} | [
"protected",
"ItemImpl",
"readItem",
"(",
"ItemData",
"itemData",
",",
"boolean",
"pool",
")",
"throws",
"RepositoryException",
"{",
"return",
"readItem",
"(",
"itemData",
",",
"null",
",",
"pool",
",",
"true",
")",
";",
"}"
] | Read ItemImpl of given ItemData.
Will call postRead Action and check permissions.
@param itemData ItemData
@param pool boolean, if true will reload pooled ItemImpl
@return ItemImpl
@throws RepositoryException if errro occurs | [
"Read",
"ItemImpl",
"of",
"given",
"ItemData",
".",
"Will",
"call",
"postRead",
"Action",
"and",
"check",
"permissions",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/SessionDataManager.java#L579-L582 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restoreconfig.java | br_restoreconfig.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_restoreconfig_responses result = (br_restoreconfig_responses) service.get_payload_formatter().string_to_resource(br_restoreconfig_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_restoreconfig_response_array);
}
br_restoreconfig[] result_br_restoreconfig = new br_restoreconfig[result.br_restoreconfig_response_array.length];
for(int i = 0; i < result.br_restoreconfig_response_array.length; i++)
{
result_br_restoreconfig[i] = result.br_restoreconfig_response_array[i].br_restoreconfig[0];
}
return result_br_restoreconfig;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_restoreconfig_responses result = (br_restoreconfig_responses) service.get_payload_formatter().string_to_resource(br_restoreconfig_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_restoreconfig_response_array);
}
br_restoreconfig[] result_br_restoreconfig = new br_restoreconfig[result.br_restoreconfig_response_array.length];
for(int i = 0; i < result.br_restoreconfig_response_array.length; i++)
{
result_br_restoreconfig[i] = result.br_restoreconfig_response_array[i].br_restoreconfig[0];
}
return result_br_restoreconfig;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"br_restoreconfig_responses",
"result",
"=",
"(",
"br_restoreconfig_responses",
")",
"service",
".",
"get_payl... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restoreconfig.java#L157-L174 |
apache/reef | lang/java/reef-bridge-client/src/main/java/org/apache/reef/bridge/client/YarnClusterSubmissionFromCS.java | YarnClusterSubmissionFromCS.fromJobSubmissionParametersFile | static YarnClusterSubmissionFromCS fromJobSubmissionParametersFile(final File yarnClusterAppSubmissionParametersFile,
final File yarnClusterJobSubmissionParametersFile)
throws IOException {
try (final FileInputStream appFileInputStream = new FileInputStream(yarnClusterAppSubmissionParametersFile)) {
try (final FileInputStream jobFileInputStream = new FileInputStream(yarnClusterJobSubmissionParametersFile)) {
// this is mainly a test hook
return readYarnClusterSubmissionFromCSFromInputStream(appFileInputStream, jobFileInputStream);
}
}
} | java | static YarnClusterSubmissionFromCS fromJobSubmissionParametersFile(final File yarnClusterAppSubmissionParametersFile,
final File yarnClusterJobSubmissionParametersFile)
throws IOException {
try (final FileInputStream appFileInputStream = new FileInputStream(yarnClusterAppSubmissionParametersFile)) {
try (final FileInputStream jobFileInputStream = new FileInputStream(yarnClusterJobSubmissionParametersFile)) {
// this is mainly a test hook
return readYarnClusterSubmissionFromCSFromInputStream(appFileInputStream, jobFileInputStream);
}
}
} | [
"static",
"YarnClusterSubmissionFromCS",
"fromJobSubmissionParametersFile",
"(",
"final",
"File",
"yarnClusterAppSubmissionParametersFile",
",",
"final",
"File",
"yarnClusterJobSubmissionParametersFile",
")",
"throws",
"IOException",
"{",
"try",
"(",
"final",
"FileInputStream",
... | Takes the YARN cluster job submission configuration file, deserializes it, and creates submission object. | [
"Takes",
"the",
"YARN",
"cluster",
"job",
"submission",
"configuration",
"file",
"deserializes",
"it",
"and",
"creates",
"submission",
"object",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-bridge-client/src/main/java/org/apache/reef/bridge/client/YarnClusterSubmissionFromCS.java#L255-L264 |
DiUS/pact-jvm | pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java | PactDslJsonArray.maxArrayLike | public PactDslJsonArray maxArrayLike(Integer size, PactDslJsonRootValue value, int numberExamples) {
if (numberExamples > size) {
throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d",
numberExamples, size));
}
matchers.addRule(rootPath + appendArrayIndex(1), matchMax(size));
PactDslJsonArray parent = new PactDslJsonArray(rootPath, "", this, true);
parent.setNumberExamples(numberExamples);
parent.putObject(value);
return (PactDslJsonArray) parent.closeArray();
} | java | public PactDslJsonArray maxArrayLike(Integer size, PactDslJsonRootValue value, int numberExamples) {
if (numberExamples > size) {
throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d",
numberExamples, size));
}
matchers.addRule(rootPath + appendArrayIndex(1), matchMax(size));
PactDslJsonArray parent = new PactDslJsonArray(rootPath, "", this, true);
parent.setNumberExamples(numberExamples);
parent.putObject(value);
return (PactDslJsonArray) parent.closeArray();
} | [
"public",
"PactDslJsonArray",
"maxArrayLike",
"(",
"Integer",
"size",
",",
"PactDslJsonRootValue",
"value",
",",
"int",
"numberExamples",
")",
"{",
"if",
"(",
"numberExamples",
">",
"size",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
... | Array of values with a maximum size that are not objects where each item must match the provided example
@param size maximum size of the array
@param value Value to use to match each item
@param numberExamples number of examples to generate | [
"Array",
"of",
"values",
"with",
"a",
"maximum",
"size",
"that",
"are",
"not",
"objects",
"where",
"each",
"item",
"must",
"match",
"the",
"provided",
"example"
] | train | https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L1089-L1099 |
finmath/finmath-lib | src/main/java/net/finmath/time/FloatingpointDate.java | FloatingpointDate.getFloatingPointDateFromDate | public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {
Duration duration = Duration.between(referenceDate, date);
return ((double)duration.getSeconds()) / SECONDS_PER_DAY;
} | java | public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {
Duration duration = Duration.between(referenceDate, date);
return ((double)duration.getSeconds()) / SECONDS_PER_DAY;
} | [
"public",
"static",
"double",
"getFloatingPointDateFromDate",
"(",
"LocalDateTime",
"referenceDate",
",",
"LocalDateTime",
"date",
")",
"{",
"Duration",
"duration",
"=",
"Duration",
".",
"between",
"(",
"referenceDate",
",",
"date",
")",
";",
"return",
"(",
"(",
... | Convert a given date to a floating point date using a given reference date.
@param referenceDate The reference date associated with \( t=0 \).
@param date The given date to be associated with the return value \( T \).
@return The value T measuring the distance of reference date and date by ACT/365 with SECONDS_PER_DAY seconds used as the smallest time unit and SECONDS_PER_DAY is a constant 365*24*60*60. | [
"Convert",
"a",
"given",
"date",
"to",
"a",
"floating",
"point",
"date",
"using",
"a",
"given",
"reference",
"date",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/time/FloatingpointDate.java#L83-L86 |
paypal/SeLion | dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelReader.java | ExcelReader.getRowIndex | public int getRowIndex(String sheetName, String key) {
logger.entering(new Object[] { sheetName, key });
int index = -1;
Sheet sheet = fetchSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
String cellValue = row.getCell(0).toString();
if ((key.compareTo(cellValue) == 0) && (!cellValue.contains("#"))) {
index = i;
break;
}
}
logger.exiting(index);
return index;
} | java | public int getRowIndex(String sheetName, String key) {
logger.entering(new Object[] { sheetName, key });
int index = -1;
Sheet sheet = fetchSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
String cellValue = row.getCell(0).toString();
if ((key.compareTo(cellValue) == 0) && (!cellValue.contains("#"))) {
index = i;
break;
}
}
logger.exiting(index);
return index;
} | [
"public",
"int",
"getRowIndex",
"(",
"String",
"sheetName",
",",
"String",
"key",
")",
"{",
"logger",
".",
"entering",
"(",
"new",
"Object",
"[",
"]",
"{",
"sheetName",
",",
"key",
"}",
")",
";",
"int",
"index",
"=",
"-",
"1",
";",
"Sheet",
"sheet",
... | Search for the input key from the specified sheet name and return the index position of the row that contained
the key
@param sheetName
- A String that represents the Sheet name from which data is to be read
@param key
- A String that represents the key for the row for which search is being done.
@return - An int that represents the row number for which the key matches. Returns -1 if the search did not yield
any results. | [
"Search",
"for",
"the",
"input",
"key",
"from",
"the",
"specified",
"sheet",
"name",
"and",
"return",
"the",
"index",
"position",
"of",
"the",
"row",
"that",
"contained",
"the",
"key"
] | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelReader.java#L240-L259 |
rzwitserloot/lombok | src/launch/lombok/launch/ShadowClassLoader.java | ShadowClassLoader.inOwnBase | private boolean inOwnBase(String item, String name) {
if (item == null) return false;
return (item.length() == SELF_BASE_LENGTH + name.length()) && SELF_BASE.regionMatches(0, item, 0, SELF_BASE_LENGTH);
} | java | private boolean inOwnBase(String item, String name) {
if (item == null) return false;
return (item.length() == SELF_BASE_LENGTH + name.length()) && SELF_BASE.regionMatches(0, item, 0, SELF_BASE_LENGTH);
} | [
"private",
"boolean",
"inOwnBase",
"(",
"String",
"item",
",",
"String",
"name",
")",
"{",
"if",
"(",
"item",
"==",
"null",
")",
"return",
"false",
";",
"return",
"(",
"item",
".",
"length",
"(",
")",
"==",
"SELF_BASE_LENGTH",
"+",
"name",
".",
"length... | Checks if the stated item is located inside the same classpath root as the jar that hosts ShadowClassLoader.class. {@code item} and {@code name} refer to the same thing. | [
"Checks",
"if",
"the",
"stated",
"item",
"is",
"located",
"inside",
"the",
"same",
"classpath",
"root",
"as",
"the",
"jar",
"that",
"hosts",
"ShadowClassLoader",
".",
"class",
".",
"{"
] | train | https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/launch/lombok/launch/ShadowClassLoader.java#L308-L311 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/lang/ServiceLoaderHelper.java | ServiceLoaderHelper.getAllSPIImplementations | @Nonnull
@ReturnsMutableCopy
public static <T> ICommonsList <T> getAllSPIImplementations (@Nonnull final Class <T> aSPIClass,
@Nullable final Logger aLogger)
{
return getAllSPIImplementations (aSPIClass, ClassLoaderHelper.getDefaultClassLoader (), aLogger);
} | java | @Nonnull
@ReturnsMutableCopy
public static <T> ICommonsList <T> getAllSPIImplementations (@Nonnull final Class <T> aSPIClass,
@Nullable final Logger aLogger)
{
return getAllSPIImplementations (aSPIClass, ClassLoaderHelper.getDefaultClassLoader (), aLogger);
} | [
"@",
"Nonnull",
"@",
"ReturnsMutableCopy",
"public",
"static",
"<",
"T",
">",
"ICommonsList",
"<",
"T",
">",
"getAllSPIImplementations",
"(",
"@",
"Nonnull",
"final",
"Class",
"<",
"T",
">",
"aSPIClass",
",",
"@",
"Nullable",
"final",
"Logger",
"aLogger",
")... | Uses the {@link ServiceLoader} to load all SPI implementations of the
passed class
@param <T>
The implementation type to be loaded
@param aSPIClass
The SPI interface class. May not be <code>null</code>.
@param aLogger
An optional logger to use. May be <code>null</code>.
@return A list of all currently available plugins | [
"Uses",
"the",
"{",
"@link",
"ServiceLoader",
"}",
"to",
"load",
"all",
"SPI",
"implementations",
"of",
"the",
"passed",
"class"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/ServiceLoaderHelper.java#L103-L109 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java | BootstrapConfig.mergeProperties | protected void mergeProperties(Map<String, String> target, URL baseURL, String urlStr) {
String includes = null;
URL url;
try {
if (baseURL != null && urlStr == null)
url = baseURL;
else
url = new URL(baseURL, urlStr);
// Read properties from file then trim trailing white spaces
Properties props = KernelUtils.getProperties(url.openStream());
includes = (String) props.remove(BootstrapConstants.BOOTPROP_INCLUDE);
// First value to be set wins. Add values in the current file before
// looking at included files.
addMissingProperties(props, target);
if (includes != null)
processIncludes(target, url, includes);
} catch (MalformedURLException e) {
Debug.printStackTrace(e);
throw new LocationException("Bad bootstrap.properties URI: " + urlStr, MessageFormat.format(BootstrapConstants.messages.getString("error.bootPropsURI"), urlStr, e), e);
} catch (IOException e) {
throw new LocationException("IOException reading bootstrap.properties: " + urlStr, MessageFormat.format(BootstrapConstants.messages.getString("error.bootPropsStream"),
urlStr, e), e);
}
} | java | protected void mergeProperties(Map<String, String> target, URL baseURL, String urlStr) {
String includes = null;
URL url;
try {
if (baseURL != null && urlStr == null)
url = baseURL;
else
url = new URL(baseURL, urlStr);
// Read properties from file then trim trailing white spaces
Properties props = KernelUtils.getProperties(url.openStream());
includes = (String) props.remove(BootstrapConstants.BOOTPROP_INCLUDE);
// First value to be set wins. Add values in the current file before
// looking at included files.
addMissingProperties(props, target);
if (includes != null)
processIncludes(target, url, includes);
} catch (MalformedURLException e) {
Debug.printStackTrace(e);
throw new LocationException("Bad bootstrap.properties URI: " + urlStr, MessageFormat.format(BootstrapConstants.messages.getString("error.bootPropsURI"), urlStr, e), e);
} catch (IOException e) {
throw new LocationException("IOException reading bootstrap.properties: " + urlStr, MessageFormat.format(BootstrapConstants.messages.getString("error.bootPropsStream"),
urlStr, e), e);
}
} | [
"protected",
"void",
"mergeProperties",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"target",
",",
"URL",
"baseURL",
",",
"String",
"urlStr",
")",
"{",
"String",
"includes",
"=",
"null",
";",
"URL",
"url",
";",
"try",
"{",
"if",
"(",
"baseURL",
"!="... | Merge properties from resource specified by urlStr (which is resolved
against the given
baseURL, in the case of relative paths) into the target map.
@param target
Target map to populate with new properties
@param baseURL
Base location used for resolving relative paths
@param urlStr
URL string describing the properties resource to load
@param recurse
Whether or not to follow any included bootstrap resources
(bootstrap.includes). | [
"Merge",
"properties",
"from",
"resource",
"specified",
"by",
"urlStr",
"(",
"which",
"is",
"resolved",
"against",
"the",
"given",
"baseURL",
"in",
"the",
"case",
"of",
"relative",
"paths",
")",
"into",
"the",
"target",
"map",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java#L666-L693 |
finmath/finmath-lib | src/main/java6/net/finmath/marketdata/products/SwapAnnuity.java | SwapAnnuity.getSwapAnnuity | public static double getSwapAnnuity(double evaluationTime, ScheduleInterface schedule, DiscountCurveInterface discountCurve, AnalyticModelInterface model) {
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex);
if(paymentDate <= evaluationTime) {
continue;
}
double periodLength = schedule.getPeriodLength(periodIndex);
double discountFactor = discountCurve.getDiscountFactor(model, paymentDate);
value += periodLength * discountFactor;
}
return value / discountCurve.getDiscountFactor(model, evaluationTime);
} | java | public static double getSwapAnnuity(double evaluationTime, ScheduleInterface schedule, DiscountCurveInterface discountCurve, AnalyticModelInterface model) {
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex);
if(paymentDate <= evaluationTime) {
continue;
}
double periodLength = schedule.getPeriodLength(periodIndex);
double discountFactor = discountCurve.getDiscountFactor(model, paymentDate);
value += periodLength * discountFactor;
}
return value / discountCurve.getDiscountFactor(model, evaluationTime);
} | [
"public",
"static",
"double",
"getSwapAnnuity",
"(",
"double",
"evaluationTime",
",",
"ScheduleInterface",
"schedule",
",",
"DiscountCurveInterface",
"discountCurve",
",",
"AnalyticModelInterface",
"model",
")",
"{",
"double",
"value",
"=",
"0.0",
";",
"for",
"(",
"... | Function to calculate an (idealized) swap annuity for a given schedule and discount curve.
Note that, the value returned is divided by the discount factor at evaluation.
This matters, if the discount factor at evaluationTime is not equal to 1.0.
@param evaluationTime The evaluation time as double. Cash flows prior and including this time are not considered.
@param schedule The schedule discretization, i.e., the period start and end dates. End dates are considered payment dates and start of the next period.
@param discountCurve The discount curve.
@param model The model, needed only in case the discount curve evaluation depends on an additional curve.
@return The swap annuity. | [
"Function",
"to",
"calculate",
"an",
"(",
"idealized",
")",
"swap",
"annuity",
"for",
"a",
"given",
"schedule",
"and",
"discount",
"curve",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/marketdata/products/SwapAnnuity.java#L117-L130 |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/GeoParserFactory.java | GeoParserFactory.getDefault | public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow, boolean fuzzy)
throws ClavinException {
try {
// instantiate default LocationExtractor
LocationExtractor extractor = new ApacheExtractor();
return getDefault(pathToLuceneIndex, extractor, maxHitDepth, maxContentWindow, fuzzy);
} catch (IOException ioe) {
throw new ClavinException("Error creating ApacheExtractor", ioe);
}
} | java | public static GeoParser getDefault(String pathToLuceneIndex, int maxHitDepth, int maxContentWindow, boolean fuzzy)
throws ClavinException {
try {
// instantiate default LocationExtractor
LocationExtractor extractor = new ApacheExtractor();
return getDefault(pathToLuceneIndex, extractor, maxHitDepth, maxContentWindow, fuzzy);
} catch (IOException ioe) {
throw new ClavinException("Error creating ApacheExtractor", ioe);
}
} | [
"public",
"static",
"GeoParser",
"getDefault",
"(",
"String",
"pathToLuceneIndex",
",",
"int",
"maxHitDepth",
",",
"int",
"maxContentWindow",
",",
"boolean",
"fuzzy",
")",
"throws",
"ClavinException",
"{",
"try",
"{",
"// instantiate default LocationExtractor",
"Locatio... | Get a GeoParser with defined values for maxHitDepth and
maxContentWindow, and fuzzy matching explicitly turned on or off.
@param pathToLuceneIndex Path to the local Lucene index.
@param maxHitDepth Number of candidate matches to consider
@param maxContentWindow How much context to consider when resolving
@param fuzzy Should fuzzy matching be used?
@return GeoParser
@throws ClavinException If the index cannot be created. | [
"Get",
"a",
"GeoParser",
"with",
"defined",
"values",
"for",
"maxHitDepth",
"and",
"maxContentWindow",
"and",
"fuzzy",
"matching",
"explicitly",
"turned",
"on",
"or",
"off",
"."
] | train | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/GeoParserFactory.java#L94-L103 |
aalmiray/Json-lib | src/main/java/net/sf/json/JSONArray.java | JSONArray._fromArray | private static JSONArray _fromArray( boolean[] array, JsonConfig jsonConfig ) {
if( !addInstance( array ) ){
try{
return jsonConfig.getCycleDetectionStrategy()
.handleRepeatedReferenceAsArray( array );
}catch( JSONException jsone ){
removeInstance( array );
fireErrorEvent( jsone, jsonConfig );
throw jsone;
}catch( RuntimeException e ){
removeInstance( array );
JSONException jsone = new JSONException( e );
fireErrorEvent( jsone, jsonConfig );
throw jsone;
}
}
fireArrayStartEvent( jsonConfig );
JSONArray jsonArray = new JSONArray();
for( int i = 0; i < array.length; i++ ){
Boolean b = array[i] ? Boolean.TRUE : Boolean.FALSE;
jsonArray.addValue( b, jsonConfig );
fireElementAddedEvent( i, b, jsonConfig );
}
removeInstance( array );
fireArrayEndEvent( jsonConfig );
return jsonArray;
} | java | private static JSONArray _fromArray( boolean[] array, JsonConfig jsonConfig ) {
if( !addInstance( array ) ){
try{
return jsonConfig.getCycleDetectionStrategy()
.handleRepeatedReferenceAsArray( array );
}catch( JSONException jsone ){
removeInstance( array );
fireErrorEvent( jsone, jsonConfig );
throw jsone;
}catch( RuntimeException e ){
removeInstance( array );
JSONException jsone = new JSONException( e );
fireErrorEvent( jsone, jsonConfig );
throw jsone;
}
}
fireArrayStartEvent( jsonConfig );
JSONArray jsonArray = new JSONArray();
for( int i = 0; i < array.length; i++ ){
Boolean b = array[i] ? Boolean.TRUE : Boolean.FALSE;
jsonArray.addValue( b, jsonConfig );
fireElementAddedEvent( i, b, jsonConfig );
}
removeInstance( array );
fireArrayEndEvent( jsonConfig );
return jsonArray;
} | [
"private",
"static",
"JSONArray",
"_fromArray",
"(",
"boolean",
"[",
"]",
"array",
",",
"JsonConfig",
"jsonConfig",
")",
"{",
"if",
"(",
"!",
"addInstance",
"(",
"array",
")",
")",
"{",
"try",
"{",
"return",
"jsonConfig",
".",
"getCycleDetectionStrategy",
"(... | Construct a JSONArray from an boolean[].<br>
@param array An boolean[] array. | [
"Construct",
"a",
"JSONArray",
"from",
"an",
"boolean",
"[]",
".",
"<br",
">"
] | train | https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONArray.java#L540-L568 |
apache/incubator-gobblin | gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/store/hdfs/SimpleHadoopFilesystemConfigStore.java | SimpleHadoopFilesystemConfigStore.getOwnImports | public List<ConfigKeyPath> getOwnImports(ConfigKeyPath configKey, String version, Optional<Config> runtimeConfig)
throws VersionDoesNotExistException {
Preconditions.checkNotNull(configKey, "configKey cannot be null!");
Preconditions.checkArgument(!Strings.isNullOrEmpty(version), "version cannot be null or empty!");
List<ConfigKeyPath> configKeyPaths = new ArrayList<>();
Path datasetDir = getDatasetDirForKey(configKey, version);
Path includesFile = new Path(datasetDir, INCLUDES_CONF_FILE_NAME);
try {
if (!this.fs.exists(includesFile)) {
return configKeyPaths;
}
FileStatus includesFileStatus = this.fs.getFileStatus(includesFile);
if (!includesFileStatus.isDirectory()) {
try (InputStream includesConfInStream = this.fs.open(includesFileStatus.getPath())) {
configKeyPaths.addAll(getResolvedConfigKeyPaths(includesConfInStream, runtimeConfig));
}
}
} catch (IOException e) {
throw new RuntimeException(String.format("Error while getting config for configKey: \"%s\"", configKey), e);
}
return configKeyPaths;
} | java | public List<ConfigKeyPath> getOwnImports(ConfigKeyPath configKey, String version, Optional<Config> runtimeConfig)
throws VersionDoesNotExistException {
Preconditions.checkNotNull(configKey, "configKey cannot be null!");
Preconditions.checkArgument(!Strings.isNullOrEmpty(version), "version cannot be null or empty!");
List<ConfigKeyPath> configKeyPaths = new ArrayList<>();
Path datasetDir = getDatasetDirForKey(configKey, version);
Path includesFile = new Path(datasetDir, INCLUDES_CONF_FILE_NAME);
try {
if (!this.fs.exists(includesFile)) {
return configKeyPaths;
}
FileStatus includesFileStatus = this.fs.getFileStatus(includesFile);
if (!includesFileStatus.isDirectory()) {
try (InputStream includesConfInStream = this.fs.open(includesFileStatus.getPath())) {
configKeyPaths.addAll(getResolvedConfigKeyPaths(includesConfInStream, runtimeConfig));
}
}
} catch (IOException e) {
throw new RuntimeException(String.format("Error while getting config for configKey: \"%s\"", configKey), e);
}
return configKeyPaths;
} | [
"public",
"List",
"<",
"ConfigKeyPath",
">",
"getOwnImports",
"(",
"ConfigKeyPath",
"configKey",
",",
"String",
"version",
",",
"Optional",
"<",
"Config",
">",
"runtimeConfig",
")",
"throws",
"VersionDoesNotExistException",
"{",
"Preconditions",
".",
"checkNotNull",
... | Retrieves all the {@link ConfigKeyPath}s that are imported by the given {@link ConfigKeyPath}. This method does this
by reading the {@link #INCLUDES_CONF_FILE_NAME} file associated with the dataset specified by the given
{@link ConfigKeyPath}. If the {@link Path} described by the {@link ConfigKeyPath} does not exist, then an empty
{@link List} is returned.
@param configKey the config key path whose tags are needed
@param version the configuration version in the configuration store.
@return a {@link List} of {@link ConfigKeyPath}s where each entry is a {@link ConfigKeyPath} imported by the dataset
specified by the configKey.
@throws VersionDoesNotExistException if the version specified cannot be found in the {@link ConfigStore}. | [
"Retrieves",
"all",
"the",
"{",
"@link",
"ConfigKeyPath",
"}",
"s",
"that",
"are",
"imported",
"by",
"the",
"given",
"{",
"@link",
"ConfigKeyPath",
"}",
".",
"This",
"method",
"does",
"this",
"by",
"reading",
"the",
"{",
"@link",
"#INCLUDES_CONF_FILE_NAME",
... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/store/hdfs/SimpleHadoopFilesystemConfigStore.java#L251-L276 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java | BytecodeUtils.firstNonNull | public static Expression firstNonNull(final Expression left, final Expression right) {
checkArgument(left.resultType().getSort() == Type.OBJECT);
checkArgument(right.resultType().getSort() == Type.OBJECT);
Features features = Features.of();
if (Expression.areAllCheap(left, right)) {
features = features.plus(Feature.CHEAP);
}
if (right.isNonNullable()) {
features = features.plus(Feature.NON_NULLABLE);
}
return new Expression(left.resultType(), features) {
@Override
protected void doGen(CodeBuilder cb) {
Label leftIsNonNull = new Label();
left.gen(cb); // Stack: L
cb.dup(); // Stack: L, L
cb.ifNonNull(leftIsNonNull); // Stack: L
// pop the extra copy of left
cb.pop(); // Stack:
right.gen(cb); // Stack: R
cb.mark(leftIsNonNull); // At this point the stack has an instance of L or R
}
};
} | java | public static Expression firstNonNull(final Expression left, final Expression right) {
checkArgument(left.resultType().getSort() == Type.OBJECT);
checkArgument(right.resultType().getSort() == Type.OBJECT);
Features features = Features.of();
if (Expression.areAllCheap(left, right)) {
features = features.plus(Feature.CHEAP);
}
if (right.isNonNullable()) {
features = features.plus(Feature.NON_NULLABLE);
}
return new Expression(left.resultType(), features) {
@Override
protected void doGen(CodeBuilder cb) {
Label leftIsNonNull = new Label();
left.gen(cb); // Stack: L
cb.dup(); // Stack: L, L
cb.ifNonNull(leftIsNonNull); // Stack: L
// pop the extra copy of left
cb.pop(); // Stack:
right.gen(cb); // Stack: R
cb.mark(leftIsNonNull); // At this point the stack has an instance of L or R
}
};
} | [
"public",
"static",
"Expression",
"firstNonNull",
"(",
"final",
"Expression",
"left",
",",
"final",
"Expression",
"right",
")",
"{",
"checkArgument",
"(",
"left",
".",
"resultType",
"(",
")",
".",
"getSort",
"(",
")",
"==",
"Type",
".",
"OBJECT",
")",
";",... | Returns an expression that evaluates to {@code left} if left is non null, and evaluates to
{@code right} otherwise. | [
"Returns",
"an",
"expression",
"that",
"evaluates",
"to",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L635-L658 |
rapidpro/expressions | java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java | ExcelFunctions.randbetween | public static int randbetween(EvaluationContext ctx, Object bottom, Object top) {
int _bottom = Conversions.toInteger(bottom, ctx);
int _top = Conversions.toInteger(top, ctx);
return (int)(Math.random() * (_top + 1 - _bottom)) + _bottom;
} | java | public static int randbetween(EvaluationContext ctx, Object bottom, Object top) {
int _bottom = Conversions.toInteger(bottom, ctx);
int _top = Conversions.toInteger(top, ctx);
return (int)(Math.random() * (_top + 1 - _bottom)) + _bottom;
} | [
"public",
"static",
"int",
"randbetween",
"(",
"EvaluationContext",
"ctx",
",",
"Object",
"bottom",
",",
"Object",
"top",
")",
"{",
"int",
"_bottom",
"=",
"Conversions",
".",
"toInteger",
"(",
"bottom",
",",
"ctx",
")",
";",
"int",
"_top",
"=",
"Conversion... | Returns a random integer number between the numbers you specify | [
"Returns",
"a",
"random",
"integer",
"number",
"between",
"the",
"numbers",
"you",
"specify"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/ExcelFunctions.java#L442-L447 |
kuujo/vertigo | core/src/main/java/net/kuujo/vertigo/Vertigo.java | Vertigo.deployNetwork | public Vertigo deployNetwork(String cluster, NetworkConfig network) {
return deployNetwork(cluster, network, null);
} | java | public Vertigo deployNetwork(String cluster, NetworkConfig network) {
return deployNetwork(cluster, network, null);
} | [
"public",
"Vertigo",
"deployNetwork",
"(",
"String",
"cluster",
",",
"NetworkConfig",
"network",
")",
"{",
"return",
"deployNetwork",
"(",
"cluster",
",",
"network",
",",
"null",
")",
";",
"}"
] | Deploys a network to a specific cluster.<p>
If the given network configuration's name matches the name of a network
that is already running in the cluster then the given configuration will
be <b>merged</b> with the running network's configuration. This allows networks
to be dynamically updated with partial configurations. If the configuration
matches the already running configuration then no changes will occur, so it's
not necessary to check whether a network is already running if the configuration
has not been altered.
@param cluster The cluster to which to deploy the network.
@param network The configuration of the network to deploy.
@return The Vertigo instance. | [
"Deploys",
"a",
"network",
"to",
"a",
"specific",
"cluster",
".",
"<p",
">"
] | train | https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/Vertigo.java#L549-L551 |
jnidzwetzki/bitfinex-v2-wss-api-java | src/main/java/com/github/jnidzwetzki/bitfinex/v2/BitfinexApiCallbackListeners.java | BitfinexApiCallbackListeners.onCandlesticksEvent | public Closeable onCandlesticksEvent(final BiConsumer<BitfinexCandlestickSymbol, Collection<BitfinexCandle>> listener) {
candlesConsumers.offer(listener);
return () -> candlesConsumers.remove(listener);
} | java | public Closeable onCandlesticksEvent(final BiConsumer<BitfinexCandlestickSymbol, Collection<BitfinexCandle>> listener) {
candlesConsumers.offer(listener);
return () -> candlesConsumers.remove(listener);
} | [
"public",
"Closeable",
"onCandlesticksEvent",
"(",
"final",
"BiConsumer",
"<",
"BitfinexCandlestickSymbol",
",",
"Collection",
"<",
"BitfinexCandle",
">",
">",
"listener",
")",
"{",
"candlesConsumers",
".",
"offer",
"(",
"listener",
")",
";",
"return",
"(",
")",
... | registers listener for candlesticks info updates
@param listener of event
@return hook of this listener | [
"registers",
"listener",
"for",
"candlesticks",
"info",
"updates"
] | train | https://github.com/jnidzwetzki/bitfinex-v2-wss-api-java/blob/2e6adf1eb6f8cd4c8722f1619f78ab2cc3c600ee/src/main/java/com/github/jnidzwetzki/bitfinex/v2/BitfinexApiCallbackListeners.java#L148-L151 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java | GaliosFieldTableOps.polyScale | public void polyScale(GrowQueue_I8 input , int scale , GrowQueue_I8 output) {
output.resize(input.size);
for (int i = 0; i < input.size; i++) {
output.data[i] = (byte)multiply(input.data[i]&0xFF, scale);
}
} | java | public void polyScale(GrowQueue_I8 input , int scale , GrowQueue_I8 output) {
output.resize(input.size);
for (int i = 0; i < input.size; i++) {
output.data[i] = (byte)multiply(input.data[i]&0xFF, scale);
}
} | [
"public",
"void",
"polyScale",
"(",
"GrowQueue_I8",
"input",
",",
"int",
"scale",
",",
"GrowQueue_I8",
"output",
")",
"{",
"output",
".",
"resize",
"(",
"input",
".",
"size",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"input",
".",
... | Scales the polynomial.
<p>Coefficients for largest powers are first, e.g. 2*x**3 + 8*x**2+1 = [2,8,0,1]</p>
@param input Input polynomial.
@param scale scale
@param output Output polynomial. | [
"Scales",
"the",
"polynomial",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java#L129-L136 |
jbundle/jbundle | thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java | BaseApplet.loadImageIcon | public ImageIcon loadImageIcon(String filename, String description)
{
filename = Util.getImageFilename(filename, "buttons");
URL url = null;
if (this.getApplication() != null)
url = this.getApplication().getResourceURL(filename, this);
if (url == null)
{ // Not a resource, try reading it from the disk.
try {
return new ImageIcon(filename, description);
} catch (Exception ex) { // File not found - try a fully qualified URL.
ex.printStackTrace();
return null;
}
}
return new ImageIcon(url, description);
} | java | public ImageIcon loadImageIcon(String filename, String description)
{
filename = Util.getImageFilename(filename, "buttons");
URL url = null;
if (this.getApplication() != null)
url = this.getApplication().getResourceURL(filename, this);
if (url == null)
{ // Not a resource, try reading it from the disk.
try {
return new ImageIcon(filename, description);
} catch (Exception ex) { // File not found - try a fully qualified URL.
ex.printStackTrace();
return null;
}
}
return new ImageIcon(url, description);
} | [
"public",
"ImageIcon",
"loadImageIcon",
"(",
"String",
"filename",
",",
"String",
"description",
")",
"{",
"filename",
"=",
"Util",
".",
"getImageFilename",
"(",
"filename",
",",
"\"buttons\"",
")",
";",
"URL",
"url",
"=",
"null",
";",
"if",
"(",
"this",
"... | Get this image.
@param filename The filename of this image (if no path, assumes images/buttons; if not ext assumes .gif).
@param description The image description.
@return The image. | [
"Get",
"this",
"image",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L655-L671 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/abst/geo/bundle/SceneStructureMetric.java | SceneStructureMetric.setView | public void setView(int which , boolean fixed , Se3_F64 worldToView ) {
views[which].known = fixed;
views[which].worldToView.set(worldToView);
} | java | public void setView(int which , boolean fixed , Se3_F64 worldToView ) {
views[which].known = fixed;
views[which].worldToView.set(worldToView);
} | [
"public",
"void",
"setView",
"(",
"int",
"which",
",",
"boolean",
"fixed",
",",
"Se3_F64",
"worldToView",
")",
"{",
"views",
"[",
"which",
"]",
".",
"known",
"=",
"fixed",
";",
"views",
"[",
"which",
"]",
".",
"worldToView",
".",
"set",
"(",
"worldToVi... | Specifies the spacial transform for a view.
@param which Which view is being specified/
@param fixed If these parameters are fixed or not
@param worldToView The transform from world to view reference frames | [
"Specifies",
"the",
"spacial",
"transform",
"for",
"a",
"view",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/abst/geo/bundle/SceneStructureMetric.java#L154-L157 |
apollographql/apollo-android | apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/CodegenGenerationTaskCommandArgsBuilder.java | CodegenGenerationTaskCommandArgsBuilder.codeGenArgs | private List<ApolloCodegenIRArgs> codeGenArgs(Set<File> files) {
final List<File> schemaFiles = getSchemaFilesFrom(files);
if (schemaFiles.isEmpty()) {
throw new GradleException("Couldn't find schema files for the variant " + Utils.capitalize(variant) + ". Please" +
" ensure a valid schema.json exists under the varian't source sets");
}
if (illegalSchemasFound(schemaFiles)) {
throw new GradleException("Found an ancestor directory to a schema file that contains another schema file." +
" Please ensure no schema files exist on the path to another one");
}
ImmutableMap.Builder<String, ApolloCodegenIRArgs> schemaQueryMap = ImmutableMap.builder();
for (final File f : schemaFiles) {
final String normalizedSchemaFileName = getPathRelativeToSourceSet(f);
// ensures that only the highest priority schema file is used
if (schemaQueryMap.build().containsKey(normalizedSchemaFileName)) {
continue;
}
schemaQueryMap.put(normalizedSchemaFileName, new ApolloCodegenIRArgs(f, FluentIterable.from(files).filter(new Predicate<File>() {
@Override public boolean apply(@Nullable File file) {
return file != null && !schemaFiles.contains(file) && file.getParent().contains(getPathRelativeToSourceSet(f.getParentFile()));
}
}).transform(new Function<File, String>() {
@Nullable @Override public String apply(@Nullable File file) {
return file.getAbsolutePath();
}
}).toSet(), new File(outputFolder.getAbsolutePath() + File.separator + task.getProject().relativePath(f.getParent()
))));
}
return schemaQueryMap.build().values().asList();
} | java | private List<ApolloCodegenIRArgs> codeGenArgs(Set<File> files) {
final List<File> schemaFiles = getSchemaFilesFrom(files);
if (schemaFiles.isEmpty()) {
throw new GradleException("Couldn't find schema files for the variant " + Utils.capitalize(variant) + ". Please" +
" ensure a valid schema.json exists under the varian't source sets");
}
if (illegalSchemasFound(schemaFiles)) {
throw new GradleException("Found an ancestor directory to a schema file that contains another schema file." +
" Please ensure no schema files exist on the path to another one");
}
ImmutableMap.Builder<String, ApolloCodegenIRArgs> schemaQueryMap = ImmutableMap.builder();
for (final File f : schemaFiles) {
final String normalizedSchemaFileName = getPathRelativeToSourceSet(f);
// ensures that only the highest priority schema file is used
if (schemaQueryMap.build().containsKey(normalizedSchemaFileName)) {
continue;
}
schemaQueryMap.put(normalizedSchemaFileName, new ApolloCodegenIRArgs(f, FluentIterable.from(files).filter(new Predicate<File>() {
@Override public boolean apply(@Nullable File file) {
return file != null && !schemaFiles.contains(file) && file.getParent().contains(getPathRelativeToSourceSet(f.getParentFile()));
}
}).transform(new Function<File, String>() {
@Nullable @Override public String apply(@Nullable File file) {
return file.getAbsolutePath();
}
}).toSet(), new File(outputFolder.getAbsolutePath() + File.separator + task.getProject().relativePath(f.getParent()
))));
}
return schemaQueryMap.build().values().asList();
} | [
"private",
"List",
"<",
"ApolloCodegenIRArgs",
">",
"codeGenArgs",
"(",
"Set",
"<",
"File",
">",
"files",
")",
"{",
"final",
"List",
"<",
"File",
">",
"schemaFiles",
"=",
"getSchemaFilesFrom",
"(",
"files",
")",
";",
"if",
"(",
"schemaFiles",
".",
"isEmpty... | Extracts schema files from the task inputs and sorts them in a way similar to the Gradle lookup priority. That is,
build variant source set, build type source set, product flavor source set and finally main source set.
The schema file under the source set with the highest priority is used and all the graphql query files under the
schema file's subdirectories from all source sets are used to generate the IR.
If any of the schema file's ancestor directories contain a schema file, a GradleException is thrown. This is
considered to be an ambiguous case.
@param files - task input files which consist of .graphql query files and schema.json files
@return - a map with schema files as a key and associated query files as a value | [
"Extracts",
"schema",
"files",
"from",
"the",
"task",
"inputs",
"and",
"sorts",
"them",
"in",
"a",
"way",
"similar",
"to",
"the",
"Gradle",
"lookup",
"priority",
".",
"That",
"is",
"build",
"variant",
"source",
"set",
"build",
"type",
"source",
"set",
"pro... | train | https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-gradle-plugin/src/main/java/com/apollographql/apollo/gradle/CodegenGenerationTaskCommandArgsBuilder.java#L116-L148 |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/UriTemplate.java | UriTemplate.appendToBuilder | private static void appendToBuilder(UriComponentsBuilder builder, TemplateVariable variable, @Nullable Object value) {
if (value == null) {
if (variable.isRequired()) {
throw new IllegalArgumentException(
String.format("Template variable %s is required but no value was given!", variable.getName()));
}
return;
}
switch (variable.getType()) {
case COMPOSITE_PARAM:
appendComposite(builder, variable.getName(), value);
break;
case REQUEST_PARAM:
case REQUEST_PARAM_CONTINUED:
builder.queryParam(variable.getName(), value);
break;
case PATH_VARIABLE:
case SEGMENT:
builder.pathSegment(value.toString());
break;
case FRAGMENT:
builder.fragment(value.toString());
break;
}
} | java | private static void appendToBuilder(UriComponentsBuilder builder, TemplateVariable variable, @Nullable Object value) {
if (value == null) {
if (variable.isRequired()) {
throw new IllegalArgumentException(
String.format("Template variable %s is required but no value was given!", variable.getName()));
}
return;
}
switch (variable.getType()) {
case COMPOSITE_PARAM:
appendComposite(builder, variable.getName(), value);
break;
case REQUEST_PARAM:
case REQUEST_PARAM_CONTINUED:
builder.queryParam(variable.getName(), value);
break;
case PATH_VARIABLE:
case SEGMENT:
builder.pathSegment(value.toString());
break;
case FRAGMENT:
builder.fragment(value.toString());
break;
}
} | [
"private",
"static",
"void",
"appendToBuilder",
"(",
"UriComponentsBuilder",
"builder",
",",
"TemplateVariable",
"variable",
",",
"@",
"Nullable",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"if",
"(",
"variable",
".",
"isRequired"... | Appends the value for the given {@link TemplateVariable} to the given {@link UriComponentsBuilder}.
@param builder must not be {@literal null}.
@param variable must not be {@literal null}.
@param value can be {@literal null}. | [
"Appends",
"the",
"value",
"for",
"the",
"given",
"{",
"@link",
"TemplateVariable",
"}",
"to",
"the",
"given",
"{",
"@link",
"UriComponentsBuilder",
"}",
"."
] | train | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/UriTemplate.java#L312-L340 |
alkacon/opencms-core | src/org/opencms/main/OpenCms.java | OpenCms.fireCmsEvent | public static void fireCmsEvent(int type, Map<String, Object> data) {
OpenCmsCore.getInstance().getEventManager().fireEvent(type, data);
} | java | public static void fireCmsEvent(int type, Map<String, Object> data) {
OpenCmsCore.getInstance().getEventManager().fireEvent(type, data);
} | [
"public",
"static",
"void",
"fireCmsEvent",
"(",
"int",
"type",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
")",
"{",
"OpenCmsCore",
".",
"getInstance",
"(",
")",
".",
"getEventManager",
"(",
")",
".",
"fireEvent",
"(",
"type",
",",
"data",
... | Notify all event listeners that a particular event has occurred.<p>
The event will be given to all registered <code>{@link I_CmsEventListener}</code> objects.<p>
@param type event type
@param data event data | [
"Notify",
"all",
"event",
"listeners",
"that",
"a",
"particular",
"event",
"has",
"occurred",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/OpenCms.java#L170-L173 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV1ClientState.java | PaymentChannelV1ClientState.provideRefundSignature | public synchronized void provideRefundSignature(byte[] theirSignature, @Nullable KeyParameter userKey)
throws SignatureDecodeException, VerificationException {
checkNotNull(theirSignature);
stateMachine.checkState(State.WAITING_FOR_SIGNED_REFUND);
TransactionSignature theirSig = TransactionSignature.decodeFromBitcoin(theirSignature, true, false);
if (theirSig.sigHashMode() != Transaction.SigHash.NONE || !theirSig.anyoneCanPay())
throw new VerificationException("Refund signature was not SIGHASH_NONE|SIGHASH_ANYONECANPAY");
// Sign the refund transaction ourselves.
final TransactionOutput multisigContractOutput = multisigContract.getOutput(0);
try {
multisigScript = multisigContractOutput.getScriptPubKey();
} catch (ScriptException e) {
throw new RuntimeException(e); // Cannot happen: we built this ourselves.
}
TransactionSignature ourSignature =
refundTx.calculateSignature(0, myKey.maybeDecrypt(userKey),
multisigScript, Transaction.SigHash.ALL, false);
// Insert the signatures.
Script scriptSig = ScriptBuilder.createMultiSigInputScript(ourSignature, theirSig);
log.info("Refund scriptSig: {}", scriptSig);
log.info("Multi-sig contract scriptPubKey: {}", multisigScript);
TransactionInput refundInput = refundTx.getInput(0);
refundInput.setScriptSig(scriptSig);
refundInput.verify(multisigContractOutput);
stateMachine.transition(State.SAVE_STATE_IN_WALLET);
} | java | public synchronized void provideRefundSignature(byte[] theirSignature, @Nullable KeyParameter userKey)
throws SignatureDecodeException, VerificationException {
checkNotNull(theirSignature);
stateMachine.checkState(State.WAITING_FOR_SIGNED_REFUND);
TransactionSignature theirSig = TransactionSignature.decodeFromBitcoin(theirSignature, true, false);
if (theirSig.sigHashMode() != Transaction.SigHash.NONE || !theirSig.anyoneCanPay())
throw new VerificationException("Refund signature was not SIGHASH_NONE|SIGHASH_ANYONECANPAY");
// Sign the refund transaction ourselves.
final TransactionOutput multisigContractOutput = multisigContract.getOutput(0);
try {
multisigScript = multisigContractOutput.getScriptPubKey();
} catch (ScriptException e) {
throw new RuntimeException(e); // Cannot happen: we built this ourselves.
}
TransactionSignature ourSignature =
refundTx.calculateSignature(0, myKey.maybeDecrypt(userKey),
multisigScript, Transaction.SigHash.ALL, false);
// Insert the signatures.
Script scriptSig = ScriptBuilder.createMultiSigInputScript(ourSignature, theirSig);
log.info("Refund scriptSig: {}", scriptSig);
log.info("Multi-sig contract scriptPubKey: {}", multisigScript);
TransactionInput refundInput = refundTx.getInput(0);
refundInput.setScriptSig(scriptSig);
refundInput.verify(multisigContractOutput);
stateMachine.transition(State.SAVE_STATE_IN_WALLET);
} | [
"public",
"synchronized",
"void",
"provideRefundSignature",
"(",
"byte",
"[",
"]",
"theirSignature",
",",
"@",
"Nullable",
"KeyParameter",
"userKey",
")",
"throws",
"SignatureDecodeException",
",",
"VerificationException",
"{",
"checkNotNull",
"(",
"theirSignature",
")"... | <p>When the servers signature for the refund transaction is received, call this to verify it and sign the
complete refund ourselves.</p>
<p>If this does not throw an exception, we are secure against the loss of funds and can safely provide the server
with the multi-sig contract to lock in the agreement. In this case, both the multisig contract and the refund
transaction are automatically committed to wallet so that it can handle broadcasting the refund transaction at
the appropriate time if necessary.</p> | [
"<p",
">",
"When",
"the",
"servers",
"signature",
"for",
"the",
"refund",
"transaction",
"is",
"received",
"call",
"this",
"to",
"verify",
"it",
"and",
"sign",
"the",
"complete",
"refund",
"ourselves",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV1ClientState.java#L229-L254 |
allure-framework/allure1 | allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java | AllureResultsUtils.createMarshallerForClass | public static Marshaller createMarshallerForClass(Class<?> clazz) {
try {
return JAXBContext.newInstance(clazz).createMarshaller();
} catch (JAXBException e) {
throw new AllureException("Can't create marshaller for class " + clazz, e);
}
} | java | public static Marshaller createMarshallerForClass(Class<?> clazz) {
try {
return JAXBContext.newInstance(clazz).createMarshaller();
} catch (JAXBException e) {
throw new AllureException("Can't create marshaller for class " + clazz, e);
}
} | [
"public",
"static",
"Marshaller",
"createMarshallerForClass",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"try",
"{",
"return",
"JAXBContext",
".",
"newInstance",
"(",
"clazz",
")",
".",
"createMarshaller",
"(",
")",
";",
"}",
"catch",
"(",
"JAXBExceptio... | Creates a new {@link javax.xml.bind.Marshaller} for given class.
@param clazz specified class
@return a created marshaller
@throws AllureException if can't create marshaller for given class. | [
"Creates",
"a",
"new",
"{",
"@link",
"javax",
".",
"xml",
".",
"bind",
".",
"Marshaller",
"}",
"for",
"given",
"class",
"."
] | train | https://github.com/allure-framework/allure1/blob/9a816fa05d8b894a917b7ebb7fd1a4056dee4693/allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java#L179-L185 |
sarl/sarl | docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/references/SarlLinkFactory.java | SarlLinkFactory.getLinkForWildcard | protected void getLinkForWildcard(Content link, LinkInfo linkInfo, Type type) {
linkInfo.isTypeBound = true;
link.addContent("?"); //$NON-NLS-1$
final WildcardType wildcardType = type.asWildcardType();
final Type[] extendsBounds = wildcardType.extendsBounds();
final SARLFeatureAccess kw = Utils.getKeywords();
for (int i = 0; i < extendsBounds.length; i++) {
link.addContent(i > 0 ? kw.getCommaKeyword() + " " //$NON-NLS-1$
: " " + kw.getExtendsKeyword() + " "); //$NON-NLS-1$ //$NON-NLS-2$
setBoundsLinkInfo(linkInfo, extendsBounds[i]);
link.addContent(getLink(linkInfo));
}
final Type[] superBounds = wildcardType.superBounds();
for (int i = 0; i < superBounds.length; i++) {
link.addContent(i > 0 ? kw.getCommaKeyword() + " " //$NON-NLS-1$
: " " + kw.getSuperKeyword() + " "); //$NON-NLS-1$ //$NON-NLS-2$
setBoundsLinkInfo(linkInfo, superBounds[i]);
link.addContent(getLink(linkInfo));
}
} | java | protected void getLinkForWildcard(Content link, LinkInfo linkInfo, Type type) {
linkInfo.isTypeBound = true;
link.addContent("?"); //$NON-NLS-1$
final WildcardType wildcardType = type.asWildcardType();
final Type[] extendsBounds = wildcardType.extendsBounds();
final SARLFeatureAccess kw = Utils.getKeywords();
for (int i = 0; i < extendsBounds.length; i++) {
link.addContent(i > 0 ? kw.getCommaKeyword() + " " //$NON-NLS-1$
: " " + kw.getExtendsKeyword() + " "); //$NON-NLS-1$ //$NON-NLS-2$
setBoundsLinkInfo(linkInfo, extendsBounds[i]);
link.addContent(getLink(linkInfo));
}
final Type[] superBounds = wildcardType.superBounds();
for (int i = 0; i < superBounds.length; i++) {
link.addContent(i > 0 ? kw.getCommaKeyword() + " " //$NON-NLS-1$
: " " + kw.getSuperKeyword() + " "); //$NON-NLS-1$ //$NON-NLS-2$
setBoundsLinkInfo(linkInfo, superBounds[i]);
link.addContent(getLink(linkInfo));
}
} | [
"protected",
"void",
"getLinkForWildcard",
"(",
"Content",
"link",
",",
"LinkInfo",
"linkInfo",
",",
"Type",
"type",
")",
"{",
"linkInfo",
".",
"isTypeBound",
"=",
"true",
";",
"link",
".",
"addContent",
"(",
"\"?\"",
")",
";",
"//$NON-NLS-1$",
"final",
"Wil... | Build the link for the wildcard.
@param link the link.
@param linkInfo the information on the link.
@param type the type. | [
"Build",
"the",
"link",
"for",
"the",
"wildcard",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/references/SarlLinkFactory.java#L87-L106 |
CloudSlang/cs-actions | cs-commons/src/main/java/io/cloudslang/content/utils/StringEscapeUtilities.java | StringEscapeUtilities.unescapeChar | @NotNull
public static String unescapeChar(@NotNull final String string, final char toUnescape) {
final String toUnescapeStr = String.valueOf(toUnescape);
return string.replaceAll("\\\\" + toUnescapeStr, toUnescapeStr);
} | java | @NotNull
public static String unescapeChar(@NotNull final String string, final char toUnescape) {
final String toUnescapeStr = String.valueOf(toUnescape);
return string.replaceAll("\\\\" + toUnescapeStr, toUnescapeStr);
} | [
"@",
"NotNull",
"public",
"static",
"String",
"unescapeChar",
"(",
"@",
"NotNull",
"final",
"String",
"string",
",",
"final",
"char",
"toUnescape",
")",
"{",
"final",
"String",
"toUnescapeStr",
"=",
"String",
".",
"valueOf",
"(",
"toUnescape",
")",
";",
"ret... | Unescape all the occurrences of the <toUnescape> character from the <string>
@param string the string from which to unescape the character
@param toUnescape the character to unescape
@return a new string with the unescaped <toUnescape> character | [
"Unescape",
"all",
"the",
"occurrences",
"of",
"the",
"<toUnescape",
">",
"character",
"from",
"the",
"<string",
">"
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/StringEscapeUtilities.java#L52-L56 |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java | BermudanSwaption.getConditionalExpectationEstimator | public ConditionalExpectationEstimator getConditionalExpectationEstimator(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
RandomVariable[] regressionBasisFunctions = regressionBasisFunctionsProvider != null ? regressionBasisFunctionsProvider.getBasisFunctions(fixingDate, model) : getBasisFunctions(fixingDate, model);
MonteCarloConditionalExpectationRegression condExpEstimator = new MonteCarloConditionalExpectationRegression(regressionBasisFunctions);
return condExpEstimator;
} | java | public ConditionalExpectationEstimator getConditionalExpectationEstimator(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
RandomVariable[] regressionBasisFunctions = regressionBasisFunctionsProvider != null ? regressionBasisFunctionsProvider.getBasisFunctions(fixingDate, model) : getBasisFunctions(fixingDate, model);
MonteCarloConditionalExpectationRegression condExpEstimator = new MonteCarloConditionalExpectationRegression(regressionBasisFunctions);
return condExpEstimator;
} | [
"public",
"ConditionalExpectationEstimator",
"getConditionalExpectationEstimator",
"(",
"double",
"fixingDate",
",",
"LIBORModelMonteCarloSimulationModel",
"model",
")",
"throws",
"CalculationException",
"{",
"RandomVariable",
"[",
"]",
"regressionBasisFunctions",
"=",
"regressio... | Return the conditional expectation estimator suitable for this product.
@param fixingDate The condition time.
@param model The model
@return The conditional expectation estimator suitable for this product
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. | [
"Return",
"the",
"conditional",
"expectation",
"estimator",
"suitable",
"for",
"this",
"product",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java#L181-L186 |
deeplearning4j/deeplearning4j | datavec/datavec-api/src/main/java/org/datavec/api/util/ReflectionUtils.java | ReflectionUtils.setJobConf | private static void setJobConf(Object theObject, Configuration conf) {
//If JobConf and JobConfigurable are in classpath, AND
//theObject is of type JobConfigurable AND
//conf is of type JobConf then
//invoke configure on theObject
try {
Class<?> jobConfClass = conf.getClassByName("org.apache.hadoop.mapred.JobConf");
Class<?> jobConfigurableClass = conf.getClassByName("org.apache.hadoop.mapred.JobConfigurable");
if (jobConfClass.isAssignableFrom(conf.getClass())
&& jobConfigurableClass.isAssignableFrom(theObject.getClass())) {
Method configureMethod = jobConfigurableClass.getMethod("configure", jobConfClass);
configureMethod.invoke(theObject, conf);
}
} catch (ClassNotFoundException e) {
//JobConf/JobConfigurable not in classpath. no need to configure
} catch (Exception e) {
throw new RuntimeException("Error in configuring object", e);
}
} | java | private static void setJobConf(Object theObject, Configuration conf) {
//If JobConf and JobConfigurable are in classpath, AND
//theObject is of type JobConfigurable AND
//conf is of type JobConf then
//invoke configure on theObject
try {
Class<?> jobConfClass = conf.getClassByName("org.apache.hadoop.mapred.JobConf");
Class<?> jobConfigurableClass = conf.getClassByName("org.apache.hadoop.mapred.JobConfigurable");
if (jobConfClass.isAssignableFrom(conf.getClass())
&& jobConfigurableClass.isAssignableFrom(theObject.getClass())) {
Method configureMethod = jobConfigurableClass.getMethod("configure", jobConfClass);
configureMethod.invoke(theObject, conf);
}
} catch (ClassNotFoundException e) {
//JobConf/JobConfigurable not in classpath. no need to configure
} catch (Exception e) {
throw new RuntimeException("Error in configuring object", e);
}
} | [
"private",
"static",
"void",
"setJobConf",
"(",
"Object",
"theObject",
",",
"Configuration",
"conf",
")",
"{",
"//If JobConf and JobConfigurable are in classpath, AND",
"//theObject is of type JobConfigurable AND",
"//conf is of type JobConf then",
"//invoke configure on theObject",
... | This code is to support backward compatibility and break the compile
time dependency of core on mapred.
This should be made deprecated along with the mapred package HADOOP-1230.
Should be removed when mapred package is removed. | [
"This",
"code",
"is",
"to",
"support",
"backward",
"compatibility",
"and",
"break",
"the",
"compile",
"time",
"dependency",
"of",
"core",
"on",
"mapred",
".",
"This",
"should",
"be",
"made",
"deprecated",
"along",
"with",
"the",
"mapred",
"package",
"HADOOP",
... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/util/ReflectionUtils.java#L88-L106 |
ThreeTen/threeten-extra | src/main/java/org/threeten/extra/scale/TaiInstant.java | TaiInstant.ofTaiSeconds | public static TaiInstant ofTaiSeconds(long taiSeconds, long nanoAdjustment) {
long secs = Math.addExact(taiSeconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); // safe cast
return new TaiInstant(secs, nos);
} | java | public static TaiInstant ofTaiSeconds(long taiSeconds, long nanoAdjustment) {
long secs = Math.addExact(taiSeconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); // safe cast
return new TaiInstant(secs, nos);
} | [
"public",
"static",
"TaiInstant",
"ofTaiSeconds",
"(",
"long",
"taiSeconds",
",",
"long",
"nanoAdjustment",
")",
"{",
"long",
"secs",
"=",
"Math",
".",
"addExact",
"(",
"taiSeconds",
",",
"Math",
".",
"floorDiv",
"(",
"nanoAdjustment",
",",
"NANOS_PER_SECOND",
... | Obtains an instance of {@code TaiInstant} from the number of seconds from
the TAI epoch of 1958-01-01T00:00:00(TAI) with a nanosecond fraction of second.
<p>
This method allows an arbitrary number of nanoseconds to be passed in.
The factory will alter the values of the second and nanosecond in order
to ensure that the stored nanosecond is in the range 0 to 999,999,999.
For example, the following will result in the exactly the same instant:
<pre>
TaiInstant.ofTaiSeconds(3, 1);
TaiInstant.ofTaiSeconds(4, -999999999);
TaiInstant.ofTaiSeconds(2, 1000000001);
</pre>
@param taiSeconds the number of seconds from the epoch of 1958-01-01T00:00:00(TAI)
@param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
@return the TAI instant, not null
@throws ArithmeticException if numeric overflow occurs | [
"Obtains",
"an",
"instance",
"of",
"{",
"@code",
"TaiInstant",
"}",
"from",
"the",
"number",
"of",
"seconds",
"from",
"the",
"TAI",
"epoch",
"of",
"1958",
"-",
"01",
"-",
"01T00",
":",
"00",
":",
"00",
"(",
"TAI",
")",
"with",
"a",
"nanosecond",
"fra... | train | https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/scale/TaiInstant.java#L137-L141 |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java | UpdateConfigAction.setAttributes | public void setAttributes(Map<String, String> actions)
{
this.actions = actions;
this.actionCounter = actions.keySet().size();
} | java | public void setAttributes(Map<String, String> actions)
{
this.actions = actions;
this.actionCounter = actions.keySet().size();
} | [
"public",
"void",
"setAttributes",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"actions",
")",
"{",
"this",
".",
"actions",
"=",
"actions",
";",
"this",
".",
"actionCounter",
"=",
"actions",
".",
"keySet",
"(",
")",
".",
"size",
"(",
")",
";",
"}"... | You may use this field to directly, programmatically add your own Map of
key,value pairs that you would like to send for this command. Setting
your own map will reset the command index to the number of keys in the
Map
@see org.asteriskjava.manager.action.UpdateConfigAction#addCommand
@param actions the actions to set | [
"You",
"may",
"use",
"this",
"field",
"to",
"directly",
"programmatically",
"add",
"your",
"own",
"Map",
"of",
"key",
"value",
"pairs",
"that",
"you",
"would",
"like",
"to",
"send",
"for",
"this",
"command",
".",
"Setting",
"your",
"own",
"map",
"will",
... | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java#L238-L242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.