repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
jcuda/jcusolver | JCusolverJava/src/main/java/jcuda/jcusolver/JCusolverRf.java | JCusolverRf.cusolverRfAccessBundledFactorsDevice | public static int cusolverRfAccessBundledFactorsDevice(
cusolverRfHandle handle,
/** Output (in the host memory) */
Pointer nnzM,
/** Output (in the device memory) */
Pointer Mp,
Pointer Mi,
Pointer Mx)
{
return checkResult(cusolverRfAccessBundledFactorsDeviceNative(handle, nnzM, Mp, Mi, Mx));
} | java | public static int cusolverRfAccessBundledFactorsDevice(
cusolverRfHandle handle,
/** Output (in the host memory) */
Pointer nnzM,
/** Output (in the device memory) */
Pointer Mp,
Pointer Mi,
Pointer Mx)
{
return checkResult(cusolverRfAccessBundledFactorsDeviceNative(handle, nnzM, Mp, Mi, Mx));
} | [
"public",
"static",
"int",
"cusolverRfAccessBundledFactorsDevice",
"(",
"cusolverRfHandle",
"handle",
",",
"/** Output (in the host memory) */",
"Pointer",
"nnzM",
",",
"/** Output (in the device memory) */",
"Pointer",
"Mp",
",",
"Pointer",
"Mi",
",",
"Pointer",
"Mx",
")",... | CUSOLVERRF extraction: Get L & U packed into a single matrix M | [
"CUSOLVERRF",
"extraction",
":",
"Get",
"L",
"&",
"U",
"packed",
"into",
"a",
"single",
"matrix",
"M"
] | train | https://github.com/jcuda/jcusolver/blob/2600c7eca36a92a60ebcc78cae6e028e0c1d00b9/JCusolverJava/src/main/java/jcuda/jcusolver/JCusolverRf.java#L334-L344 |
pmwmedia/tinylog | tinylog-impl/src/main/java/org/tinylog/writers/RollingFileWriter.java | RollingFileWriter.deleteBackups | private static void deleteBackups(final List<File> files, final int count) {
if (count >= 0) {
for (int i = files.size() - Math.max(0, files.size() - count); i < files.size(); ++i) {
if (!files.get(i).delete()) {
InternalLogger.log(Level.WARN, "Failed to delete log file '" + files.get(i).getAbsolutePath() + "'");
}
}
}
} | java | private static void deleteBackups(final List<File> files, final int count) {
if (count >= 0) {
for (int i = files.size() - Math.max(0, files.size() - count); i < files.size(); ++i) {
if (!files.get(i).delete()) {
InternalLogger.log(Level.WARN, "Failed to delete log file '" + files.get(i).getAbsolutePath() + "'");
}
}
}
} | [
"private",
"static",
"void",
"deleteBackups",
"(",
"final",
"List",
"<",
"File",
">",
"files",
",",
"final",
"int",
"count",
")",
"{",
"if",
"(",
"count",
">=",
"0",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"files",
".",
"size",
"(",
")",
"-",
"Mat... | Deletes old log files.
@param files
All existing log files
@param count
Number of log files to keep | [
"Deletes",
"old",
"log",
"files",
"."
] | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/writers/RollingFileWriter.java#L239-L247 |
RuedigerMoeller/kontraktor | src/main/java/org/nustaq/kontraktor/Actors.java | Actors.AsActor | public static <T extends Actor> T AsActor(Class<T> actorClazz, Scheduler scheduler, int qsize) {
return (T) instance.newProxy(actorClazz,scheduler,qsize);
} | java | public static <T extends Actor> T AsActor(Class<T> actorClazz, Scheduler scheduler, int qsize) {
return (T) instance.newProxy(actorClazz,scheduler,qsize);
} | [
"public",
"static",
"<",
"T",
"extends",
"Actor",
">",
"T",
"AsActor",
"(",
"Class",
"<",
"T",
">",
"actorClazz",
",",
"Scheduler",
"scheduler",
",",
"int",
"qsize",
")",
"{",
"return",
"(",
"T",
")",
"instance",
".",
"newProxy",
"(",
"actorClazz",
","... | create an new actor dispatched in the given DispatcherThread
@param actorClazz
@param <T>
@return | [
"create",
"an",
"new",
"actor",
"dispatched",
"in",
"the",
"given",
"DispatcherThread"
] | train | https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/src/main/java/org/nustaq/kontraktor/Actors.java#L224-L226 |
phax/ph-schedule | ph-schedule/src/main/java/com/helger/schedule/quartz/trigger/JDK8TriggerBuilder.java | JDK8TriggerBuilder.forJob | @Nonnull
public JDK8TriggerBuilder <T> forJob (final String jobName, final String jobGroup)
{
m_aJobKey = new JobKey (jobName, jobGroup);
return this;
} | java | @Nonnull
public JDK8TriggerBuilder <T> forJob (final String jobName, final String jobGroup)
{
m_aJobKey = new JobKey (jobName, jobGroup);
return this;
} | [
"@",
"Nonnull",
"public",
"JDK8TriggerBuilder",
"<",
"T",
">",
"forJob",
"(",
"final",
"String",
"jobName",
",",
"final",
"String",
"jobGroup",
")",
"{",
"m_aJobKey",
"=",
"new",
"JobKey",
"(",
"jobName",
",",
"jobGroup",
")",
";",
"return",
"this",
";",
... | Set the identity of the Job which should be fired by the produced Trigger -
a <code>JobKey</code> will be produced with the given name and group.
@param jobName
the name of the job to fire.
@param jobGroup
the group of the job to fire.
@return the updated JDK8TriggerBuilder
@see ITrigger#getJobKey() | [
"Set",
"the",
"identity",
"of",
"the",
"Job",
"which",
"should",
"be",
"fired",
"by",
"the",
"produced",
"Trigger",
"-",
"a",
"<code",
">",
"JobKey<",
"/",
"code",
">",
"will",
"be",
"produced",
"with",
"the",
"given",
"name",
"and",
"group",
"."
] | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-schedule/src/main/java/com/helger/schedule/quartz/trigger/JDK8TriggerBuilder.java#L352-L357 |
graphql-java/java-dataloader | src/main/java/org/dataloader/DataLoader.java | DataLoader.newMappedDataLoader | public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoader<K, V> batchLoadFunction) {
return newMappedDataLoader(batchLoadFunction, null);
} | java | public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoader<K, V> batchLoadFunction) {
return newMappedDataLoader(batchLoadFunction, null);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"DataLoader",
"<",
"K",
",",
"V",
">",
"newMappedDataLoader",
"(",
"MappedBatchLoader",
"<",
"K",
",",
"V",
">",
"batchLoadFunction",
")",
"{",
"return",
"newMappedDataLoader",
"(",
"batchLoadFunction",
",",
"null... | Creates new DataLoader with the specified batch loader function and default options
(batching, caching and unlimited batch size).
@param batchLoadFunction the batch load function to use
@param <K> the key type
@param <V> the value type
@return a new DataLoader | [
"Creates",
"new",
"DataLoader",
"with",
"the",
"specified",
"batch",
"loader",
"function",
"and",
"default",
"options",
"(",
"batching",
"caching",
"and",
"unlimited",
"batch",
"size",
")",
"."
] | train | https://github.com/graphql-java/java-dataloader/blob/dfdc8133ead10aa723f896b4a1fa4a1cec9a6fbc/src/main/java/org/dataloader/DataLoader.java#L209-L211 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.newlineShowText | public void newlineShowText(float wordSpacing, float charSpacing, String text) {
state.yTLM -= state.leading;
content.append(wordSpacing).append(' ').append(charSpacing);
showText2(text);
content.append("\"").append_i(separator);
// The " operator sets charSpace and wordSpace into graphics state
// (cfr PDF reference v1.6, table 5.6)
state.charSpace = charSpacing;
state.wordSpace = wordSpacing;
} | java | public void newlineShowText(float wordSpacing, float charSpacing, String text) {
state.yTLM -= state.leading;
content.append(wordSpacing).append(' ').append(charSpacing);
showText2(text);
content.append("\"").append_i(separator);
// The " operator sets charSpace and wordSpace into graphics state
// (cfr PDF reference v1.6, table 5.6)
state.charSpace = charSpacing;
state.wordSpace = wordSpacing;
} | [
"public",
"void",
"newlineShowText",
"(",
"float",
"wordSpacing",
",",
"float",
"charSpacing",
",",
"String",
"text",
")",
"{",
"state",
".",
"yTLM",
"-=",
"state",
".",
"leading",
";",
"content",
".",
"append",
"(",
"wordSpacing",
")",
".",
"append",
"(",... | Moves to the next line and shows text string, using the given values of the character and word spacing parameters.
@param wordSpacing a parameter
@param charSpacing a parameter
@param text the text to write | [
"Moves",
"to",
"the",
"next",
"line",
"and",
"shows",
"text",
"string",
"using",
"the",
"given",
"values",
"of",
"the",
"character",
"and",
"word",
"spacing",
"parameters",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L1508-L1518 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.toAsyncThrowing | public static <T1, T2, T3, T4, T5, R> Func5<T1, T2, T3, T4, T5, Observable<R>> toAsyncThrowing(ThrowingFunc5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> func) {
return toAsyncThrowing(func, Schedulers.computation());
} | java | public static <T1, T2, T3, T4, T5, R> Func5<T1, T2, T3, T4, T5, Observable<R>> toAsyncThrowing(ThrowingFunc5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> func) {
return toAsyncThrowing(func, Schedulers.computation());
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"R",
">",
"Func5",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"Observable",
"<",
"R",
">",
">",
"toAsyncThrowing",
"(",
"ThrowingFunc5",
"<",
"?",
... | Convert a synchronous function call into an asynchronous function call through an Observable.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.png" alt="">
@param <T1> the first parameter type
@param <T2> the second parameter type
@param <T3> the third parameter type
@param <T4> the fourth parameter type
@param <T5> the fifth parameter type
@param <R> the result type
@param func the function to convert
@return a function that returns an Observable that executes the {@code func} and emits its returned value
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
@see <a href="http://msdn.microsoft.com/en-us/library/hh229571.aspx">MSDN: Observable.ToAsync</a> | [
"Convert",
"a",
"synchronous",
"function",
"call",
"into",
"an",
"asynchronous",
"function",
"call",
"through",
"an",
"Observable",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki"... | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L441-L443 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java | HttpMessageSecurity.protectRequest | public Request protectRequest(Request request) throws IOException {
try {
Request result = request.newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + clientSecurityToken)
.build();
if (!supportsProtection()) {
return result;
}
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
String currentbody = buffer.readUtf8();
if (currentbody == null || currentbody.length() == 0) {
return result;
}
JsonWebKey clientPublicEncryptionKey = MessageSecurityHelper.getJwkWithPublicKeyOnly(clientEncryptionKey);
String payload = currentbody.substring(0, currentbody.length() - 1) + ",\"rek\":{\"jwk\":"
+ clientPublicEncryptionKey.toString() + "}}";
JWEObject jweObject = protectPayload(payload);
JWSHeader jwsHeader = new JWSHeader("RS256", clientSignatureKey.kid(), clientSecurityToken,
getCurrentTimestamp(), "PoP", null);
String jwsHeaderJsonb64 = MessageSecurityHelper.stringToBase64Url(jwsHeader.serialize());
String protectedPayload = MessageSecurityHelper.stringToBase64Url(jweObject.serialize());
byte[] data = (jwsHeaderJsonb64 + "." + protectedPayload).getBytes(MESSAGE_ENCODING);
RsaKey clientSignatureRsaKey = new RsaKey(clientSignatureKey.kid(), clientSignatureKey.toRSA(true));
Pair<byte[], String> signature = clientSignatureRsaKey.signAsync(getSha256(data), "RS256").get();
JWSObject jwsObject = new JWSObject(jwsHeader, protectedPayload,
MessageSecurityHelper.bytesToBase64Url(signature.getKey()));
RequestBody body = RequestBody.create(MediaType.parse("application/jose+json"), jwsObject.serialize());
return result.newBuilder().method(request.method(), body).build();
} catch (ExecutionException e) {
// unexpected;
return null;
} catch (InterruptedException e) {
// unexpected;
return null;
} catch (NoSuchAlgorithmException e) {
// unexpected;
return null;
}
} | java | public Request protectRequest(Request request) throws IOException {
try {
Request result = request.newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + clientSecurityToken)
.build();
if (!supportsProtection()) {
return result;
}
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
String currentbody = buffer.readUtf8();
if (currentbody == null || currentbody.length() == 0) {
return result;
}
JsonWebKey clientPublicEncryptionKey = MessageSecurityHelper.getJwkWithPublicKeyOnly(clientEncryptionKey);
String payload = currentbody.substring(0, currentbody.length() - 1) + ",\"rek\":{\"jwk\":"
+ clientPublicEncryptionKey.toString() + "}}";
JWEObject jweObject = protectPayload(payload);
JWSHeader jwsHeader = new JWSHeader("RS256", clientSignatureKey.kid(), clientSecurityToken,
getCurrentTimestamp(), "PoP", null);
String jwsHeaderJsonb64 = MessageSecurityHelper.stringToBase64Url(jwsHeader.serialize());
String protectedPayload = MessageSecurityHelper.stringToBase64Url(jweObject.serialize());
byte[] data = (jwsHeaderJsonb64 + "." + protectedPayload).getBytes(MESSAGE_ENCODING);
RsaKey clientSignatureRsaKey = new RsaKey(clientSignatureKey.kid(), clientSignatureKey.toRSA(true));
Pair<byte[], String> signature = clientSignatureRsaKey.signAsync(getSha256(data), "RS256").get();
JWSObject jwsObject = new JWSObject(jwsHeader, protectedPayload,
MessageSecurityHelper.bytesToBase64Url(signature.getKey()));
RequestBody body = RequestBody.create(MediaType.parse("application/jose+json"), jwsObject.serialize());
return result.newBuilder().method(request.method(), body).build();
} catch (ExecutionException e) {
// unexpected;
return null;
} catch (InterruptedException e) {
// unexpected;
return null;
} catch (NoSuchAlgorithmException e) {
// unexpected;
return null;
}
} | [
"public",
"Request",
"protectRequest",
"(",
"Request",
"request",
")",
"throws",
"IOException",
"{",
"try",
"{",
"Request",
"result",
"=",
"request",
".",
"newBuilder",
"(",
")",
".",
"header",
"(",
"AUTHENTICATE",
",",
"BEARER_TOKEP_REFIX",
"+",
"clientSecurity... | Protects existing request. Replaces its body with encrypted version.
@param request
existing request.
@return new request with encrypted body if supported or existing request.
@throws IOException throws IOException | [
"Protects",
"existing",
"request",
".",
"Replaces",
"its",
"body",
"with",
"encrypted",
"version",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java#L154-L204 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java | HawkbitCommonUtil.removePrefix | public static String removePrefix(final String text, final String prefix) {
if (text != null) {
return text.replaceFirst(prefix, "");
}
return null;
} | java | public static String removePrefix(final String text, final String prefix) {
if (text != null) {
return text.replaceFirst(prefix, "");
}
return null;
} | [
"public",
"static",
"String",
"removePrefix",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"prefix",
")",
"{",
"if",
"(",
"text",
"!=",
"null",
")",
"{",
"return",
"text",
".",
"replaceFirst",
"(",
"prefix",
",",
"\"\"",
")",
";",
"}",
"retu... | Remove the prefix from text.
@param text
name
@param prefix
text to be removed
@return String name | [
"Remove",
"the",
"prefix",
"from",
"text",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java#L234-L239 |
podio/podio-java | src/main/java/com/podio/space/SpaceAPI.java | SpaceAPI.updateSpace | public void updateSpace(int spaceId, SpaceUpdate data) {
getResourceFactory().getApiResource("/space/" + spaceId)
.entity(data, MediaType.APPLICATION_JSON_TYPE).put();
} | java | public void updateSpace(int spaceId, SpaceUpdate data) {
getResourceFactory().getApiResource("/space/" + spaceId)
.entity(data, MediaType.APPLICATION_JSON_TYPE).put();
} | [
"public",
"void",
"updateSpace",
"(",
"int",
"spaceId",
",",
"SpaceUpdate",
"data",
")",
"{",
"getResourceFactory",
"(",
")",
".",
"getApiResource",
"(",
"\"/space/\"",
"+",
"spaceId",
")",
".",
"entity",
"(",
"data",
",",
"MediaType",
".",
"APPLICATION_JSON_T... | Updates the space with the given id
@param spaceId
The id of the space to update
@param data
The updated data of the space | [
"Updates",
"the",
"space",
"with",
"the",
"given",
"id"
] | train | https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/space/SpaceAPI.java#L53-L56 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpValidation.java | OpValidation.excludedFromGradientCheckCoverage | private static Set<Class> excludedFromGradientCheckCoverage() {
List list = Arrays.asList(
//Exclude misc
DynamicCustomOp.class,
EqualsWithEps.class,
ConfusionMatrix.class,
Eye.class,
OneHot.class,
BinaryMinimalRelativeError.class,
BinaryMinimalRelativeError.class,
Histogram.class,
InvertPermutation.class, //Uses integer indices
ConfusionMatrix.class, //Integer indices
Linspace.class, //No input array
//Exclude boolean operations:
Any.class,
All.class,
//Exclude index accumulations (index out, not real-valued)
FirstIndex.class,
IAMax.class,
IAMin.class,
IMax.class,
IMin.class,
LastIndex.class,
//Exclude Random ops
RandomStandardNormal.class,
DistributionUniform.class,
AlphaDropOut.class,
BernoulliDistribution.class,
BinomialDistribution.class,
BinomialDistributionEx.class,
Choice.class,
DropOut.class,
DropOutInverted.class,
GaussianDistribution.class,
LogNormalDistribution.class,
ProbablisticMerge.class,
Range.class,
TruncatedNormalDistribution.class,
UniformDistribution.class,
//Other ops we don't intend to be differentiable (only used as part of backprop, etc).
// But we still want a forward/check for these
Col2Im.class,
NormalizeMoments.class, //In principle differentiable. In practice: doesn't make any sense to do so!
CumProdBp.class,
CumSumBp.class,
DotBp.class,
MaxBp.class,
MeanBp.class,
MinBp.class,
Norm1Bp.class,
Norm2Bp.class,
NormMaxBp.class,
ProdBp.class,
StandardDeviationBp.class,
SumBp.class,
VarianceBp.class
);
return new HashSet<>(list);
} | java | private static Set<Class> excludedFromGradientCheckCoverage() {
List list = Arrays.asList(
//Exclude misc
DynamicCustomOp.class,
EqualsWithEps.class,
ConfusionMatrix.class,
Eye.class,
OneHot.class,
BinaryMinimalRelativeError.class,
BinaryMinimalRelativeError.class,
Histogram.class,
InvertPermutation.class, //Uses integer indices
ConfusionMatrix.class, //Integer indices
Linspace.class, //No input array
//Exclude boolean operations:
Any.class,
All.class,
//Exclude index accumulations (index out, not real-valued)
FirstIndex.class,
IAMax.class,
IAMin.class,
IMax.class,
IMin.class,
LastIndex.class,
//Exclude Random ops
RandomStandardNormal.class,
DistributionUniform.class,
AlphaDropOut.class,
BernoulliDistribution.class,
BinomialDistribution.class,
BinomialDistributionEx.class,
Choice.class,
DropOut.class,
DropOutInverted.class,
GaussianDistribution.class,
LogNormalDistribution.class,
ProbablisticMerge.class,
Range.class,
TruncatedNormalDistribution.class,
UniformDistribution.class,
//Other ops we don't intend to be differentiable (only used as part of backprop, etc).
// But we still want a forward/check for these
Col2Im.class,
NormalizeMoments.class, //In principle differentiable. In practice: doesn't make any sense to do so!
CumProdBp.class,
CumSumBp.class,
DotBp.class,
MaxBp.class,
MeanBp.class,
MinBp.class,
Norm1Bp.class,
Norm2Bp.class,
NormMaxBp.class,
ProdBp.class,
StandardDeviationBp.class,
SumBp.class,
VarianceBp.class
);
return new HashSet<>(list);
} | [
"private",
"static",
"Set",
"<",
"Class",
">",
"excludedFromGradientCheckCoverage",
"(",
")",
"{",
"List",
"list",
"=",
"Arrays",
".",
"asList",
"(",
"//Exclude misc",
"DynamicCustomOp",
".",
"class",
",",
"EqualsWithEps",
".",
"class",
",",
"ConfusionMatrix",
"... | Returns a list of classes that are not gradient checkable.
An operation may not be gradient checkable due to, for example:
(a) Having no real-valued arguments<br>
(b) Having random output (dropout, for example)<br>
<p>
Note that hawving non-real-valued output is OK - we still want to test these, as they
should pass back zero gradients! | [
"Returns",
"a",
"list",
"of",
"classes",
"that",
"are",
"not",
"gradient",
"checkable",
".",
"An",
"operation",
"may",
"not",
"be",
"gradient",
"checkable",
"due",
"to",
"for",
"example",
":",
"(",
"a",
")",
"Having",
"no",
"real",
"-",
"valued",
"argume... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/OpValidation.java#L874-L934 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java | ServiceDiscoveryManager.discoverInfo | public DiscoverInfo discoverInfo(Jid entityID, String node) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
// Discover the entity's info
DiscoverInfo disco = new DiscoverInfo();
disco.setType(IQ.Type.get);
disco.setTo(entityID);
disco.setNode(node);
Stanza result = connection().createStanzaCollectorAndSend(disco).nextResultOrThrow();
return (DiscoverInfo) result;
} | java | public DiscoverInfo discoverInfo(Jid entityID, String node) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
// Discover the entity's info
DiscoverInfo disco = new DiscoverInfo();
disco.setType(IQ.Type.get);
disco.setTo(entityID);
disco.setNode(node);
Stanza result = connection().createStanzaCollectorAndSend(disco).nextResultOrThrow();
return (DiscoverInfo) result;
} | [
"public",
"DiscoverInfo",
"discoverInfo",
"(",
"Jid",
"entityID",
",",
"String",
"node",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"// Discover the entity's info",
"DiscoverInfo",
"disco"... | Returns the discovered information of a given XMPP entity addressed by its JID and
note attribute. Use this message only when trying to query information which is not
directly addressable.
@see <a href="http://xmpp.org/extensions/xep-0030.html#info-basic">XEP-30 Basic Protocol</a>
@see <a href="http://xmpp.org/extensions/xep-0030.html#info-nodes">XEP-30 Info Nodes</a>
@param entityID the address of the XMPP entity.
@param node the optional attribute that supplements the 'jid' attribute.
@return the discovered information.
@throws XMPPErrorException if the operation failed for some reason.
@throws NoResponseException if there was no response from the server.
@throws NotConnectedException
@throws InterruptedException | [
"Returns",
"the",
"discovered",
"information",
"of",
"a",
"given",
"XMPP",
"entity",
"addressed",
"by",
"its",
"JID",
"and",
"note",
"attribute",
".",
"Use",
"this",
"message",
"only",
"when",
"trying",
"to",
"query",
"information",
"which",
"is",
"not",
"di... | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java#L524-L534 |
mapsforge/mapsforge | mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java | AndroidUtil.createExternalStorageTileCache | public static TileCache createExternalStorageTileCache(Context c, String id, int firstLevelSize, int tileSize) {
return createExternalStorageTileCache(c, id, firstLevelSize, tileSize, false);
} | java | public static TileCache createExternalStorageTileCache(Context c, String id, int firstLevelSize, int tileSize) {
return createExternalStorageTileCache(c, id, firstLevelSize, tileSize, false);
} | [
"public",
"static",
"TileCache",
"createExternalStorageTileCache",
"(",
"Context",
"c",
",",
"String",
"id",
",",
"int",
"firstLevelSize",
",",
"int",
"tileSize",
")",
"{",
"return",
"createExternalStorageTileCache",
"(",
"c",
",",
"id",
",",
"firstLevelSize",
","... | Utility function to create a two-level tile cache along with its backends.
This is the compatibility version that by default creates a non-persistent cache.
@param c the Android context
@param id name for the directory, which will be created as a subdirectory of the default cache directory (as
returned by {@link android.content.Context#getExternalCacheDir()}).
@param firstLevelSize size of the first level cache (tiles number)
@param tileSize tile size
@return a new cache created on the external storage | [
"Utility",
"function",
"to",
"create",
"a",
"two",
"-",
"level",
"tile",
"cache",
"along",
"with",
"its",
"backends",
".",
"This",
"is",
"the",
"compatibility",
"version",
"that",
"by",
"default",
"creates",
"a",
"non",
"-",
"persistent",
"cache",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L66-L68 |
googleapis/google-http-java-client | google-http-client/src/main/java/com/google/api/client/json/JsonParser.java | JsonParser.parseArrayAndClose | @Beta
public final <T> Collection<T> parseArrayAndClose(
Class<?> destinationCollectionClass,
Class<T> destinationItemClass,
CustomizeJsonParser customizeParser)
throws IOException {
try {
return parseArray(destinationCollectionClass, destinationItemClass, customizeParser);
} finally {
close();
}
} | java | @Beta
public final <T> Collection<T> parseArrayAndClose(
Class<?> destinationCollectionClass,
Class<T> destinationItemClass,
CustomizeJsonParser customizeParser)
throws IOException {
try {
return parseArray(destinationCollectionClass, destinationItemClass, customizeParser);
} finally {
close();
}
} | [
"@",
"Beta",
"public",
"final",
"<",
"T",
">",
"Collection",
"<",
"T",
">",
"parseArrayAndClose",
"(",
"Class",
"<",
"?",
">",
"destinationCollectionClass",
",",
"Class",
"<",
"T",
">",
"destinationItemClass",
",",
"CustomizeJsonParser",
"customizeParser",
")",
... | {@link Beta} <br>
Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into
the given destination collection, optionally using the given parser customizer.
@param destinationCollectionClass class of destination collection (must have a public default
constructor)
@param destinationItemClass class of destination collection item (must have a public default
constructor)
@param customizeParser optional parser customizer or {@code null} for none | [
"{",
"@link",
"Beta",
"}",
"<br",
">",
"Parse",
"a",
"JSON",
"Array",
"from",
"the",
"given",
"JSON",
"parser",
"(",
"which",
"is",
"closed",
"after",
"parsing",
"completes",
")",
"into",
"the",
"given",
"destination",
"collection",
"optionally",
"using",
... | train | https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/json/JsonParser.java#L498-L509 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/activerecord/dialect/Dialect.java | Dialect.processGeneratedBigIntegerKey | protected void processGeneratedBigIntegerKey(Model<?> model, String pKey, Object v) {
if (v instanceof BigInteger) {
model.set(pKey, (BigInteger)v);
} else if (v instanceof Number) {
Number n = (Number)v;
model.set(pKey, BigInteger.valueOf(n.longValue()));
} else {
model.set(pKey, v);
}
} | java | protected void processGeneratedBigIntegerKey(Model<?> model, String pKey, Object v) {
if (v instanceof BigInteger) {
model.set(pKey, (BigInteger)v);
} else if (v instanceof Number) {
Number n = (Number)v;
model.set(pKey, BigInteger.valueOf(n.longValue()));
} else {
model.set(pKey, v);
}
} | [
"protected",
"void",
"processGeneratedBigIntegerKey",
"(",
"Model",
"<",
"?",
">",
"model",
",",
"String",
"pKey",
",",
"Object",
"v",
")",
"{",
"if",
"(",
"v",
"instanceof",
"BigInteger",
")",
"{",
"model",
".",
"set",
"(",
"pKey",
",",
"(",
"BigInteger... | mysql 数据库的 bigint unsigned 对应的 java 类型为 BigInteger
但是 rs.getObject(1) 返回值为 Long 型,造成 model.save() 以后
model.getId() 时的类型转换异常 | [
"mysql",
"数据库的",
"bigint",
"unsigned",
"对应的",
"java",
"类型为",
"BigInteger",
"但是",
"rs",
".",
"getObject",
"(",
"1",
")",
"返回值为",
"Long",
"型,造成",
"model",
".",
"save",
"()",
"以后",
"model",
".",
"getId",
"()",
"时的类型转换异常"
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/dialect/Dialect.java#L174-L183 |
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java | MutableBigInteger.mulsub | private int mulsub(int[] q, int[] a, int x, int len, int offset) {
long xLong = x & LONG_MASK;
long carry = 0;
offset += len;
for (int j=len-1; j >= 0; j--) {
long product = (a[j] & LONG_MASK) * xLong + carry;
long difference = q[offset] - product;
q[offset--] = (int)difference;
carry = (product >>> 32)
+ (((difference & LONG_MASK) >
(((~(int)product) & LONG_MASK))) ? 1:0);
}
return (int)carry;
} | java | private int mulsub(int[] q, int[] a, int x, int len, int offset) {
long xLong = x & LONG_MASK;
long carry = 0;
offset += len;
for (int j=len-1; j >= 0; j--) {
long product = (a[j] & LONG_MASK) * xLong + carry;
long difference = q[offset] - product;
q[offset--] = (int)difference;
carry = (product >>> 32)
+ (((difference & LONG_MASK) >
(((~(int)product) & LONG_MASK))) ? 1:0);
}
return (int)carry;
} | [
"private",
"int",
"mulsub",
"(",
"int",
"[",
"]",
"q",
",",
"int",
"[",
"]",
"a",
",",
"int",
"x",
",",
"int",
"len",
",",
"int",
"offset",
")",
"{",
"long",
"xLong",
"=",
"x",
"&",
"LONG_MASK",
";",
"long",
"carry",
"=",
"0",
";",
"offset",
... | This method is used for division. It multiplies an n word input a by one
word input x, and subtracts the n word product from q. This is needed
when subtracting qhat*divisor from dividend. | [
"This",
"method",
"is",
"used",
"for",
"division",
".",
"It",
"multiplies",
"an",
"n",
"word",
"input",
"a",
"by",
"one",
"word",
"input",
"x",
"and",
"subtracts",
"the",
"n",
"word",
"product",
"from",
"q",
".",
"This",
"is",
"needed",
"when",
"subtra... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java#L637-L651 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java | SparkComputationGraph.calculateScoreMultiDataSet | public double calculateScoreMultiDataSet(JavaRDD<MultiDataSet> data, boolean average, int minibatchSize) {
JavaRDD<Tuple2<Integer, Double>> rdd = data.mapPartitions(new ScoreFlatMapFunctionCGMultiDataSet(conf.toJson(),
sc.broadcast(network.params(false)), minibatchSize));
//Reduce to a single tuple, with example count + sum of scores
Tuple2<Integer, Double> countAndSumScores = rdd.reduce(new IntDoubleReduceFunction());
if (average) {
return countAndSumScores._2() / countAndSumScores._1();
} else {
return countAndSumScores._2();
}
} | java | public double calculateScoreMultiDataSet(JavaRDD<MultiDataSet> data, boolean average, int minibatchSize) {
JavaRDD<Tuple2<Integer, Double>> rdd = data.mapPartitions(new ScoreFlatMapFunctionCGMultiDataSet(conf.toJson(),
sc.broadcast(network.params(false)), minibatchSize));
//Reduce to a single tuple, with example count + sum of scores
Tuple2<Integer, Double> countAndSumScores = rdd.reduce(new IntDoubleReduceFunction());
if (average) {
return countAndSumScores._2() / countAndSumScores._1();
} else {
return countAndSumScores._2();
}
} | [
"public",
"double",
"calculateScoreMultiDataSet",
"(",
"JavaRDD",
"<",
"MultiDataSet",
">",
"data",
",",
"boolean",
"average",
",",
"int",
"minibatchSize",
")",
"{",
"JavaRDD",
"<",
"Tuple2",
"<",
"Integer",
",",
"Double",
">",
">",
"rdd",
"=",
"data",
".",
... | Calculate the score for all examples in the provided {@code JavaRDD<MultiDataSet>}, either by summing
or averaging over the entire data set.
*
@param data Data to score
@param average Whether to sum the scores, or average them
@param minibatchSize The number of examples to use in each minibatch when scoring. If more examples are in a partition than
this, multiple scoring operations will be done (to avoid using too much memory by doing the whole partition
in one go) | [
"Calculate",
"the",
"score",
"for",
"all",
"examples",
"in",
"the",
"provided",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java#L411-L421 |
Azure/azure-sdk-for-java | resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java | ResourcesInner.checkExistenceById | public boolean checkExistenceById(String resourceId, String apiVersion) {
return checkExistenceByIdWithServiceResponseAsync(resourceId, apiVersion).toBlocking().single().body();
} | java | public boolean checkExistenceById(String resourceId, String apiVersion) {
return checkExistenceByIdWithServiceResponseAsync(resourceId, apiVersion).toBlocking().single().body();
} | [
"public",
"boolean",
"checkExistenceById",
"(",
"String",
"resourceId",
",",
"String",
"apiVersion",
")",
"{",
"return",
"checkExistenceByIdWithServiceResponseAsync",
"(",
"resourceId",
",",
"apiVersion",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
... | Checks by ID whether a resource exists.
@param resourceId The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}
@param apiVersion The API version to use for the operation.
@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
@return the boolean object if successful. | [
"Checks",
"by",
"ID",
"whether",
"a",
"resource",
"exists",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L1845-L1847 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security/src/com/ibm/ws/security/krb5/Krb5Common.java | Krb5Common.setPropertyAsNeeded | @SuppressWarnings({ "unchecked", "rawtypes" })
public static String setPropertyAsNeeded(final String propName, final String propValue) {
String previousPropValue = (String) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
@Override
public String run() {
String oldPropValue = System.getProperty(propName);
if (propValue == null) {
System.clearProperty(propName);
} else if (!propValue.equalsIgnoreCase(oldPropValue)) {
System.setProperty(propName, propValue);
}
return oldPropValue;
}
});
if (tc.isDebugEnabled())
Tr.debug(tc, propName + " property previous: " + ((previousPropValue != null) ? previousPropValue : "<null>") + " and now: " + propValue);
return previousPropValue;
} | java | @SuppressWarnings({ "unchecked", "rawtypes" })
public static String setPropertyAsNeeded(final String propName, final String propValue) {
String previousPropValue = (String) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
@Override
public String run() {
String oldPropValue = System.getProperty(propName);
if (propValue == null) {
System.clearProperty(propName);
} else if (!propValue.equalsIgnoreCase(oldPropValue)) {
System.setProperty(propName, propValue);
}
return oldPropValue;
}
});
if (tc.isDebugEnabled())
Tr.debug(tc, propName + " property previous: " + ((previousPropValue != null) ? previousPropValue : "<null>") + " and now: " + propValue);
return previousPropValue;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"rawtypes\"",
"}",
")",
"public",
"static",
"String",
"setPropertyAsNeeded",
"(",
"final",
"String",
"propName",
",",
"final",
"String",
"propValue",
")",
"{",
"String",
"previousPropValue",
"=",
"(",
"S... | This method set the system property if the property is null or property value is not the same with the new value
@param propName
@param propValue
@return | [
"This",
"method",
"set",
"the",
"system",
"property",
"if",
"the",
"property",
"is",
"null",
"or",
"property",
"value",
"is",
"not",
"the",
"same",
"with",
"the",
"new",
"value"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security/src/com/ibm/ws/security/krb5/Krb5Common.java#L76-L95 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/Hud.java | Hud.generateCancel | private void generateCancel(final ActionRef action, Featurable menu)
{
menu.getFeature(Actionable.class).setAction(() ->
{
clearMenus();
final Collection<ActionRef> parents = previous.get(action);
createMenus(parents, parents);
});
} | java | private void generateCancel(final ActionRef action, Featurable menu)
{
menu.getFeature(Actionable.class).setAction(() ->
{
clearMenus();
final Collection<ActionRef> parents = previous.get(action);
createMenus(parents, parents);
});
} | [
"private",
"void",
"generateCancel",
"(",
"final",
"ActionRef",
"action",
",",
"Featurable",
"menu",
")",
"{",
"menu",
".",
"getFeature",
"(",
"Actionable",
".",
"class",
")",
".",
"setAction",
"(",
"(",
")",
"->",
"{",
"clearMenus",
"(",
")",
";",
"fina... | Generate cancel to go back.
@param action The associated action.
@param menu The current menu to check. | [
"Generate",
"cancel",
"to",
"go",
"back",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/Hud.java#L250-L258 |
stripe/stripe-java | src/main/java/com/stripe/model/SubscriptionItem.java | SubscriptionItem.usageRecordSummaries | public UsageRecordSummaryCollection usageRecordSummaries(
Map<String, Object> params, RequestOptions options) throws StripeException {
String url =
String.format(
"%s%s",
Stripe.getApiBase(),
String.format(
"/v1/subscription_items/%s/usage_record_summaries",
ApiResource.urlEncodeId(this.getId())));
return requestCollection(url, params, UsageRecordSummaryCollection.class, options);
} | java | public UsageRecordSummaryCollection usageRecordSummaries(
Map<String, Object> params, RequestOptions options) throws StripeException {
String url =
String.format(
"%s%s",
Stripe.getApiBase(),
String.format(
"/v1/subscription_items/%s/usage_record_summaries",
ApiResource.urlEncodeId(this.getId())));
return requestCollection(url, params, UsageRecordSummaryCollection.class, options);
} | [
"public",
"UsageRecordSummaryCollection",
"usageRecordSummaries",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"params",
",",
"RequestOptions",
"options",
")",
"throws",
"StripeException",
"{",
"String",
"url",
"=",
"String",
".",
"format",
"(",
"\"%s%s\"",
",",... | For the specified subscription item, returns a list of summary objects. Each object in the list
provides usage information that’s been summarized from multiple usage records and over a
subscription billing period (e.g., 15 usage records in the billing plan’s month of September).
<p>The list is sorted in reverse-chronological order (newest first). The first list item
represents the most current usage period that hasn’t ended yet. Since new usage records can
still be added, the returned summary information for the subscription item’s ID should be seen
as unstable until the subscription billing period ends. | [
"For",
"the",
"specified",
"subscription",
"item",
"returns",
"a",
"list",
"of",
"summary",
"objects",
".",
"Each",
"object",
"in",
"the",
"list",
"provides",
"usage",
"information",
"that’s",
"been",
"summarized",
"from",
"multiple",
"usage",
"records",
"and",
... | train | https://github.com/stripe/stripe-java/blob/acfa8becef3e73bfe3e9d8880bea3f3f30dadeac/src/main/java/com/stripe/model/SubscriptionItem.java#L297-L307 |
actframework/actframework | src/main/java/act/util/ReflectedInvokerHelper.java | ReflectedInvokerHelper.tryGetSingleton | public static Object tryGetSingleton(Class<?> invokerClass, App app) {
Object singleton = app.singleton(invokerClass);
if (null == singleton) {
if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) {
singleton = app.getInstance(invokerClass);
}
}
if (null != singleton) {
app.registerSingleton(singleton);
}
return singleton;
} | java | public static Object tryGetSingleton(Class<?> invokerClass, App app) {
Object singleton = app.singleton(invokerClass);
if (null == singleton) {
if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) {
singleton = app.getInstance(invokerClass);
}
}
if (null != singleton) {
app.registerSingleton(singleton);
}
return singleton;
} | [
"public",
"static",
"Object",
"tryGetSingleton",
"(",
"Class",
"<",
"?",
">",
"invokerClass",
",",
"App",
"app",
")",
"{",
"Object",
"singleton",
"=",
"app",
".",
"singleton",
"(",
"invokerClass",
")",
";",
"if",
"(",
"null",
"==",
"singleton",
")",
"{",... | If the `invokerClass` specified is singleton, or without field or all fields are
stateless, then return an instance of the invoker class. Otherwise, return null
@param invokerClass the invoker class
@param app the app
@return an instance of the invokerClass or `null` if invoker class is stateful class | [
"If",
"the",
"invokerClass",
"specified",
"is",
"singleton",
"or",
"without",
"field",
"or",
"all",
"fields",
"are",
"stateless",
"then",
"return",
"an",
"instance",
"of",
"the",
"invoker",
"class",
".",
"Otherwise",
"return",
"null"
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/ReflectedInvokerHelper.java#L56-L67 |
groovy/groovy-core | src/main/groovy/ui/GroovyMain.java | GroovyMain.getText | public String getText(String uriOrFilename) throws IOException {
if (uriPattern.matcher(uriOrFilename).matches()) {
try {
return ResourceGroovyMethods.getText(new URL(uriOrFilename));
} catch (Exception e) {
throw new GroovyRuntimeException("Unable to get script from URL: ", e);
}
}
return ResourceGroovyMethods.getText(huntForTheScriptFile(uriOrFilename));
} | java | public String getText(String uriOrFilename) throws IOException {
if (uriPattern.matcher(uriOrFilename).matches()) {
try {
return ResourceGroovyMethods.getText(new URL(uriOrFilename));
} catch (Exception e) {
throw new GroovyRuntimeException("Unable to get script from URL: ", e);
}
}
return ResourceGroovyMethods.getText(huntForTheScriptFile(uriOrFilename));
} | [
"public",
"String",
"getText",
"(",
"String",
"uriOrFilename",
")",
"throws",
"IOException",
"{",
"if",
"(",
"uriPattern",
".",
"matcher",
"(",
"uriOrFilename",
")",
".",
"matches",
"(",
")",
")",
"{",
"try",
"{",
"return",
"ResourceGroovyMethods",
".",
"get... | Get the text of the Groovy script at the given location.
If the location is a file path and it does not exist as given,
then {@link GroovyMain#huntForTheScriptFile(String)} is called to try
with some Groovy extensions appended.
This method is not used to process scripts and is retained for backward
compatibility. If you want to modify how GroovyMain processes scripts
then use {@link GroovyMain#getScriptSource(boolean, String)}.
@param uriOrFilename
@return the text content at the location
@throws IOException
@deprecated | [
"Get",
"the",
"text",
"of",
"the",
"Groovy",
"script",
"at",
"the",
"given",
"location",
".",
"If",
"the",
"location",
"is",
"a",
"file",
"path",
"and",
"it",
"does",
"not",
"exist",
"as",
"given",
"then",
"{",
"@link",
"GroovyMain#huntForTheScriptFile",
"... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/groovy/ui/GroovyMain.java#L427-L436 |
apache/groovy | subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/TryWithResourcesASTTransformation.java | TryWithResourcesASTTransformation.createFinallyBlockForNewTryCatchStatement | private BlockStatement createFinallyBlockForNewTryCatchStatement(String primaryExcName, String firstResourceIdentifierName) {
BlockStatement finallyBlock = new BlockStatement();
// primaryExc != null
BooleanExpression conditionExpression =
new BooleanExpression(
new BinaryExpression(
new VariableExpression(primaryExcName),
newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1),
new ConstantExpression(null)));
// try-catch statement
TryCatchStatement newTryCatchStatement =
new TryCatchStatement(
astBuilder.createBlockStatement(this.createCloseResourceStatement(firstResourceIdentifierName)), // { Identifier?.close(); }
EmptyStatement.INSTANCE);
String suppressedExcName = this.genSuppressedExcName();
newTryCatchStatement.addCatch(
// catch (Throwable #suppressedExc) { .. }
new CatchStatement(
new Parameter(ClassHelper.make(Throwable.class), suppressedExcName),
astBuilder.createBlockStatement(this.createAddSuppressedStatement(primaryExcName, suppressedExcName)) // #primaryExc.addSuppressed(#suppressedExc);
)
);
// if (#primaryExc != null) { ... }
IfStatement ifStatement =
new IfStatement(
conditionExpression,
newTryCatchStatement,
this.createCloseResourceStatement(firstResourceIdentifierName) // Identifier?.close();
);
astBuilder.appendStatementsToBlockStatement(finallyBlock, ifStatement);
return astBuilder.createBlockStatement(finallyBlock);
} | java | private BlockStatement createFinallyBlockForNewTryCatchStatement(String primaryExcName, String firstResourceIdentifierName) {
BlockStatement finallyBlock = new BlockStatement();
// primaryExc != null
BooleanExpression conditionExpression =
new BooleanExpression(
new BinaryExpression(
new VariableExpression(primaryExcName),
newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1),
new ConstantExpression(null)));
// try-catch statement
TryCatchStatement newTryCatchStatement =
new TryCatchStatement(
astBuilder.createBlockStatement(this.createCloseResourceStatement(firstResourceIdentifierName)), // { Identifier?.close(); }
EmptyStatement.INSTANCE);
String suppressedExcName = this.genSuppressedExcName();
newTryCatchStatement.addCatch(
// catch (Throwable #suppressedExc) { .. }
new CatchStatement(
new Parameter(ClassHelper.make(Throwable.class), suppressedExcName),
astBuilder.createBlockStatement(this.createAddSuppressedStatement(primaryExcName, suppressedExcName)) // #primaryExc.addSuppressed(#suppressedExc);
)
);
// if (#primaryExc != null) { ... }
IfStatement ifStatement =
new IfStatement(
conditionExpression,
newTryCatchStatement,
this.createCloseResourceStatement(firstResourceIdentifierName) // Identifier?.close();
);
astBuilder.appendStatementsToBlockStatement(finallyBlock, ifStatement);
return astBuilder.createBlockStatement(finallyBlock);
} | [
"private",
"BlockStatement",
"createFinallyBlockForNewTryCatchStatement",
"(",
"String",
"primaryExcName",
",",
"String",
"firstResourceIdentifierName",
")",
"{",
"BlockStatement",
"finallyBlock",
"=",
"new",
"BlockStatement",
"(",
")",
";",
"// primaryExc != null",
"BooleanE... | /*
finally {
if (Identifier != null) {
if (#primaryExc != null) {
try {
Identifier.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
} else {
Identifier.close();
}
}
}
We can simplify the above code to a Groovy version as follows:
finally {
if (#primaryExc != null)
try {
Identifier?.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
else
Identifier?.close();
} | [
"/",
"*",
"finally",
"{",
"if",
"(",
"Identifier",
"!",
"=",
"null",
")",
"{",
"if",
"(",
"#primaryExc",
"!",
"=",
"null",
")",
"{",
"try",
"{",
"Identifier",
".",
"close",
"()",
";",
"}",
"catch",
"(",
"Throwable",
"#suppressedExc",
")",
"{",
"#pr... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/TryWithResourcesASTTransformation.java#L299-L336 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java | StyleUtils.setStyle | public static boolean setStyle(PolygonOptions polygonOptions, StyleRow style, float density) {
if (style != null) {
Color color = style.getColorOrDefault();
polygonOptions.strokeColor(color.getColorWithAlpha());
double width = style.getWidthOrDefault();
polygonOptions.strokeWidth((float) width * density);
Color fillColor = style.getFillColor();
if (fillColor != null) {
polygonOptions.fillColor(fillColor.getColorWithAlpha());
}
}
return style != null;
} | java | public static boolean setStyle(PolygonOptions polygonOptions, StyleRow style, float density) {
if (style != null) {
Color color = style.getColorOrDefault();
polygonOptions.strokeColor(color.getColorWithAlpha());
double width = style.getWidthOrDefault();
polygonOptions.strokeWidth((float) width * density);
Color fillColor = style.getFillColor();
if (fillColor != null) {
polygonOptions.fillColor(fillColor.getColorWithAlpha());
}
}
return style != null;
} | [
"public",
"static",
"boolean",
"setStyle",
"(",
"PolygonOptions",
"polygonOptions",
",",
"StyleRow",
"style",
",",
"float",
"density",
")",
"{",
"if",
"(",
"style",
"!=",
"null",
")",
"{",
"Color",
"color",
"=",
"style",
".",
"getColorOrDefault",
"(",
")",
... | Set the style into the polygon options
@param polygonOptions polygon options
@param style style row
@param density display density: {@link android.util.DisplayMetrics#density}
@return true if style was set into the polygon options | [
"Set",
"the",
"style",
"into",
"the",
"polygon",
"options"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L603-L620 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/recordcount/IngestionRecordCountProvider.java | IngestionRecordCountProvider.constructFilePath | public static String constructFilePath(String oldFilePath, long recordCounts) {
return new Path(new Path(oldFilePath).getParent(), Files.getNameWithoutExtension(oldFilePath).toString() + SEPARATOR
+ recordCounts + SEPARATOR + Files.getFileExtension(oldFilePath)).toString();
} | java | public static String constructFilePath(String oldFilePath, long recordCounts) {
return new Path(new Path(oldFilePath).getParent(), Files.getNameWithoutExtension(oldFilePath).toString() + SEPARATOR
+ recordCounts + SEPARATOR + Files.getFileExtension(oldFilePath)).toString();
} | [
"public",
"static",
"String",
"constructFilePath",
"(",
"String",
"oldFilePath",
",",
"long",
"recordCounts",
")",
"{",
"return",
"new",
"Path",
"(",
"new",
"Path",
"(",
"oldFilePath",
")",
".",
"getParent",
"(",
")",
",",
"Files",
".",
"getNameWithoutExtensio... | Construct a new file path by appending record count to the filename of the given file path, separated by SEPARATOR.
For example, given path: "/a/b/c/file.avro" and record count: 123,
the new path returned will be: "/a/b/c/file.123.avro" | [
"Construct",
"a",
"new",
"file",
"path",
"by",
"appending",
"record",
"count",
"to",
"the",
"filename",
"of",
"the",
"given",
"file",
"path",
"separated",
"by",
"SEPARATOR",
".",
"For",
"example",
"given",
"path",
":",
"/",
"a",
"/",
"b",
"/",
"c",
"/"... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/recordcount/IngestionRecordCountProvider.java#L45-L48 |
wildfly/wildfly-build-tools | provisioning/src/main/java/org/wildfly/build/StandaloneAetherArtifactFileResolver.java | StandaloneAetherArtifactFileResolver.newRepositorySystemSession | private static RepositorySystemSession newRepositorySystemSession(RepositorySystem system, File localRepositoryBaseDir) {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
final LocalRepositoryManager localRepositoryManager = system.newLocalRepositoryManager(session, new LocalRepository(localRepositoryBaseDir));
session.setLocalRepositoryManager(localRepositoryManager);
return session;
} | java | private static RepositorySystemSession newRepositorySystemSession(RepositorySystem system, File localRepositoryBaseDir) {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
final LocalRepositoryManager localRepositoryManager = system.newLocalRepositoryManager(session, new LocalRepository(localRepositoryBaseDir));
session.setLocalRepositoryManager(localRepositoryManager);
return session;
} | [
"private",
"static",
"RepositorySystemSession",
"newRepositorySystemSession",
"(",
"RepositorySystem",
"system",
",",
"File",
"localRepositoryBaseDir",
")",
"{",
"final",
"DefaultRepositorySystemSession",
"session",
"=",
"MavenRepositorySystemUtils",
".",
"newSession",
"(",
"... | Retrieves a new instance of a standalone {@link org.eclipse.aether.RepositorySystemSession}, which {@link org.eclipse.aether.repository.LocalRepositoryManager} points to 'target/local-repository' dir.
@param system
@return | [
"Retrieves",
"a",
"new",
"instance",
"of",
"a",
"standalone",
"{"
] | train | https://github.com/wildfly/wildfly-build-tools/blob/520a5f2e58e6a24097d63fd65c51a8fc29847a61/provisioning/src/main/java/org/wildfly/build/StandaloneAetherArtifactFileResolver.java#L109-L114 |
james-hu/jabb-core | src/main/java/net/sf/jabb/spring/rest/AbstractRestClient.java | AbstractRestClient.addBasicAuthHeader | protected void addBasicAuthHeader(HttpHeaders headers, String user, String password){
headers.add(HEADER_AUTHORIZATION, buildBasicAuthValue(user, password));
} | java | protected void addBasicAuthHeader(HttpHeaders headers, String user, String password){
headers.add(HEADER_AUTHORIZATION, buildBasicAuthValue(user, password));
} | [
"protected",
"void",
"addBasicAuthHeader",
"(",
"HttpHeaders",
"headers",
",",
"String",
"user",
",",
"String",
"password",
")",
"{",
"headers",
".",
"add",
"(",
"HEADER_AUTHORIZATION",
",",
"buildBasicAuthValue",
"(",
"user",
",",
"password",
")",
")",
";",
"... | Add HTTP Basic Auth header
@param headers the headers, it must not be a read-only one, if it is, use {@link #copy(HttpHeaders)} to make a writable copy first
@param user the user name, may be null or empty
@param password the password, may be null or empty | [
"Add",
"HTTP",
"Basic",
"Auth",
"header"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/rest/AbstractRestClient.java#L650-L652 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapreduce/server/jobtracker/TaskTracker.java | TaskTracker.unreserveSlots | public void unreserveSlots(TaskType taskType, JobInProgress job) {
JobID jobId = job.getJobID();
if (taskType == TaskType.MAP) {
if (jobForFallowMapSlot == null ||
!jobForFallowMapSlot.getJobID().equals(jobId)) {
throw new RuntimeException(trackerName + " already has " +
"slots reserved for " +
jobForFallowMapSlot + "; being" +
" asked to un-reserve for " + jobId);
}
jobForFallowMapSlot = null;
} else {
if (jobForFallowReduceSlot == null ||
!jobForFallowReduceSlot.getJobID().equals(jobId)) {
throw new RuntimeException(trackerName + " already has " +
"slots reserved for " +
jobForFallowReduceSlot + "; being" +
" asked to un-reserve for " + jobId);
}
jobForFallowReduceSlot = null;
}
job.unreserveTaskTracker(this, taskType);
LOG.info(trackerName + ": Unreserved " + taskType + " slots for " + jobId);
} | java | public void unreserveSlots(TaskType taskType, JobInProgress job) {
JobID jobId = job.getJobID();
if (taskType == TaskType.MAP) {
if (jobForFallowMapSlot == null ||
!jobForFallowMapSlot.getJobID().equals(jobId)) {
throw new RuntimeException(trackerName + " already has " +
"slots reserved for " +
jobForFallowMapSlot + "; being" +
" asked to un-reserve for " + jobId);
}
jobForFallowMapSlot = null;
} else {
if (jobForFallowReduceSlot == null ||
!jobForFallowReduceSlot.getJobID().equals(jobId)) {
throw new RuntimeException(trackerName + " already has " +
"slots reserved for " +
jobForFallowReduceSlot + "; being" +
" asked to un-reserve for " + jobId);
}
jobForFallowReduceSlot = null;
}
job.unreserveTaskTracker(this, taskType);
LOG.info(trackerName + ": Unreserved " + taskType + " slots for " + jobId);
} | [
"public",
"void",
"unreserveSlots",
"(",
"TaskType",
"taskType",
",",
"JobInProgress",
"job",
")",
"{",
"JobID",
"jobId",
"=",
"job",
".",
"getJobID",
"(",
")",
";",
"if",
"(",
"taskType",
"==",
"TaskType",
".",
"MAP",
")",
"{",
"if",
"(",
"jobForFallowM... | Free map slots on this <code>TaskTracker</code> which were reserved for
<code>taskType</code>.
@param taskType {@link TaskType} of the task
@param job job whose slots are being un-reserved | [
"Free",
"map",
"slots",
"on",
"this",
"<code",
">",
"TaskTracker<",
"/",
"code",
">",
"which",
"were",
"reserved",
"for",
"<code",
">",
"taskType<",
"/",
"code",
">",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapreduce/server/jobtracker/TaskTracker.java#L157-L183 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PropertiesUtils.java | PropertiesUtils.extractPropertiesWithPrefix | public static Properties extractPropertiesWithPrefix(Properties properties, Optional<String> prefix) {
Preconditions.checkNotNull(properties);
Preconditions.checkNotNull(prefix);
Properties extractedProperties = new Properties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
if (StringUtils.startsWith(entry.getKey().toString(), prefix.or(StringUtils.EMPTY))) {
extractedProperties.put(entry.getKey().toString(), entry.getValue());
}
}
return extractedProperties;
} | java | public static Properties extractPropertiesWithPrefix(Properties properties, Optional<String> prefix) {
Preconditions.checkNotNull(properties);
Preconditions.checkNotNull(prefix);
Properties extractedProperties = new Properties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
if (StringUtils.startsWith(entry.getKey().toString(), prefix.or(StringUtils.EMPTY))) {
extractedProperties.put(entry.getKey().toString(), entry.getValue());
}
}
return extractedProperties;
} | [
"public",
"static",
"Properties",
"extractPropertiesWithPrefix",
"(",
"Properties",
"properties",
",",
"Optional",
"<",
"String",
">",
"prefix",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"properties",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
... | Extract all the keys that start with a <code>prefix</code> in {@link Properties} to a new {@link Properties}
instance.
@param properties the given {@link Properties} instance
@param prefix of keys to be extracted
@return a {@link Properties} instance | [
"Extract",
"all",
"the",
"keys",
"that",
"start",
"with",
"a",
"<code",
">",
"prefix<",
"/",
"code",
">",
"in",
"{",
"@link",
"Properties",
"}",
"to",
"a",
"new",
"{",
"@link",
"Properties",
"}",
"instance",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PropertiesUtils.java#L80-L92 |
hypercube1024/firefly | firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java | AtomicBiInteger.encodeHi | public static long encodeHi(long encoded, int hi) {
long h = ((long) hi) & 0xFFFF_FFFFL;
long l = encoded & 0xFFFF_FFFFL;
return (h << 32) + l;
} | java | public static long encodeHi(long encoded, int hi) {
long h = ((long) hi) & 0xFFFF_FFFFL;
long l = encoded & 0xFFFF_FFFFL;
return (h << 32) + l;
} | [
"public",
"static",
"long",
"encodeHi",
"(",
"long",
"encoded",
",",
"int",
"hi",
")",
"{",
"long",
"h",
"=",
"(",
"(",
"long",
")",
"hi",
")",
"&",
"0xFFFF_FFFF",
"",
"L",
";",
"long",
"l",
"=",
"encoded",
"&",
"0xFFFF_FFFF",
"",
"L",
";",
"retu... | Sets the hi value into the given encoded value.
@param encoded the encoded value
@param hi the hi value
@return the new encoded value | [
"Sets",
"the",
"hi",
"value",
"into",
"the",
"given",
"encoded",
"value",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java#L224-L228 |
joniles/mpxj | src/main/java/net/sf/mpxj/primavera/PrimaveraReader.java | PrimaveraReader.processActivityCodes | public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)
{
ActivityCodeContainer container = m_project.getActivityCodes();
Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();
for (Row row : types)
{
ActivityCode code = new ActivityCode(row.getInteger("actv_code_type_id"), row.getString("actv_code_type"));
container.add(code);
map.put(code.getUniqueID(), code);
}
for (Row row : typeValues)
{
ActivityCode code = map.get(row.getInteger("actv_code_type_id"));
if (code != null)
{
ActivityCodeValue value = code.addValue(row.getInteger("actv_code_id"), row.getString("short_name"), row.getString("actv_code_name"));
m_activityCodeMap.put(value.getUniqueID(), value);
}
}
for (Row row : assignments)
{
Integer taskID = row.getInteger("task_id");
List<Integer> list = m_activityCodeAssignments.get(taskID);
if (list == null)
{
list = new ArrayList<Integer>();
m_activityCodeAssignments.put(taskID, list);
}
list.add(row.getInteger("actv_code_id"));
}
} | java | public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)
{
ActivityCodeContainer container = m_project.getActivityCodes();
Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();
for (Row row : types)
{
ActivityCode code = new ActivityCode(row.getInteger("actv_code_type_id"), row.getString("actv_code_type"));
container.add(code);
map.put(code.getUniqueID(), code);
}
for (Row row : typeValues)
{
ActivityCode code = map.get(row.getInteger("actv_code_type_id"));
if (code != null)
{
ActivityCodeValue value = code.addValue(row.getInteger("actv_code_id"), row.getString("short_name"), row.getString("actv_code_name"));
m_activityCodeMap.put(value.getUniqueID(), value);
}
}
for (Row row : assignments)
{
Integer taskID = row.getInteger("task_id");
List<Integer> list = m_activityCodeAssignments.get(taskID);
if (list == null)
{
list = new ArrayList<Integer>();
m_activityCodeAssignments.put(taskID, list);
}
list.add(row.getInteger("actv_code_id"));
}
} | [
"public",
"void",
"processActivityCodes",
"(",
"List",
"<",
"Row",
">",
"types",
",",
"List",
"<",
"Row",
">",
"typeValues",
",",
"List",
"<",
"Row",
">",
"assignments",
")",
"{",
"ActivityCodeContainer",
"container",
"=",
"m_project",
".",
"getActivityCodes",... | Read activity code types and values.
@param types activity code type data
@param typeValues activity code value data
@param assignments activity code task assignments | [
"Read",
"activity",
"code",
"types",
"and",
"values",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/PrimaveraReader.java#L184-L217 |
lucee/Lucee | core/src/main/java/lucee/runtime/util/NumberFormat.java | NumberFormat.formatX | public String formatX(Locale locale, double number, String mask) throws InvalidMaskException {
return format(locale, number, convertMask(mask));
} | java | public String formatX(Locale locale, double number, String mask) throws InvalidMaskException {
return format(locale, number, convertMask(mask));
} | [
"public",
"String",
"formatX",
"(",
"Locale",
"locale",
",",
"double",
"number",
",",
"String",
"mask",
")",
"throws",
"InvalidMaskException",
"{",
"return",
"format",
"(",
"locale",
",",
"number",
",",
"convertMask",
"(",
"mask",
")",
")",
";",
"}"
] | format a number with given mask
@param number
@param mask
@return formatted number as string
@throws InvalidMaskException | [
"format",
"a",
"number",
"with",
"given",
"mask"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/util/NumberFormat.java#L59-L61 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/os/BundleUtils.java | BundleUtils.optDoubleArray | @Nullable
public static double[] optDoubleArray(@Nullable Bundle bundle, @Nullable String key) {
return optDoubleArray(bundle, key, new double[0]);
} | java | @Nullable
public static double[] optDoubleArray(@Nullable Bundle bundle, @Nullable String key) {
return optDoubleArray(bundle, key, new double[0]);
} | [
"@",
"Nullable",
"public",
"static",
"double",
"[",
"]",
"optDoubleArray",
"(",
"@",
"Nullable",
"Bundle",
"bundle",
",",
"@",
"Nullable",
"String",
"key",
")",
"{",
"return",
"optDoubleArray",
"(",
"bundle",
",",
"key",
",",
"new",
"double",
"[",
"0",
"... | Returns a optional double array value. In other words, returns the value mapped by key if it exists and is a double array.
The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null.
@param bundle a bundle. If the bundle is null, this method will return null.
@param key a key for the value.
@return a double array value if exists, null otherwise.
@see android.os.Bundle#getDoubleArray(String) | [
"Returns",
"a",
"optional",
"double",
"array",
"value",
".",
"In",
"other",
"words",
"returns",
"the",
"value",
"mapped",
"by",
"key",
"if",
"it",
"exists",
"and",
"is",
"a",
"double",
"array",
".",
"The",
"bundle",
"argument",
"is",
"allowed",
"to",
"be... | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L453-L456 |
apptik/jus | benchmark/src/perf/java/com/android/volley/Request.java | Request.getBody | public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
} | java | public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
} | [
"public",
"byte",
"[",
"]",
"getBody",
"(",
")",
"throws",
"AuthFailureError",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",
"getParams",
"(",
")",
";",
"if",
"(",
"params",
"!=",
"null",
"&&",
"params",
".",
"size",
"(",
")",
">",
... | Returns the raw POST or PUT body to be sent.
<p>By default, the body consists of the request parameters in
application/x-www-form-urlencoded format. When overriding this method, consider overriding
{@link #getBodyContentType()} as well to match the new body format.
@throws AuthFailureError in the event of auth failure | [
"Returns",
"the",
"raw",
"POST",
"or",
"PUT",
"body",
"to",
"be",
"sent",
"."
] | train | https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/benchmark/src/perf/java/com/android/volley/Request.java#L407-L413 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java | MultipleAlignmentScorer.getMCScore | public static double getMCScore(MultipleAlignment alignment,
double gapOpen, double gapExtension, double dCutoff)
throws StructureException {
List<Atom[]> trans = MultipleAlignmentTools.transformAtoms(alignment);
// Calculate d0: same as the one in TM score
int minLen = Integer.MAX_VALUE;
for (Atom[] atoms : alignment.getAtomArrays())
if (atoms.length < minLen)
minLen = atoms.length;
double d0 = 1.24 * Math.cbrt((minLen) - 15.) - 1.8;
// Calculate the distance cutoff penalization
double A = 20.0 / (1 + (dCutoff * dCutoff) / (d0 * d0));
return getMCScore(trans, d0, gapOpen, gapExtension, A);
} | java | public static double getMCScore(MultipleAlignment alignment,
double gapOpen, double gapExtension, double dCutoff)
throws StructureException {
List<Atom[]> trans = MultipleAlignmentTools.transformAtoms(alignment);
// Calculate d0: same as the one in TM score
int minLen = Integer.MAX_VALUE;
for (Atom[] atoms : alignment.getAtomArrays())
if (atoms.length < minLen)
minLen = atoms.length;
double d0 = 1.24 * Math.cbrt((minLen) - 15.) - 1.8;
// Calculate the distance cutoff penalization
double A = 20.0 / (1 + (dCutoff * dCutoff) / (d0 * d0));
return getMCScore(trans, d0, gapOpen, gapExtension, A);
} | [
"public",
"static",
"double",
"getMCScore",
"(",
"MultipleAlignment",
"alignment",
",",
"double",
"gapOpen",
",",
"double",
"gapExtension",
",",
"double",
"dCutoff",
")",
"throws",
"StructureException",
"{",
"List",
"<",
"Atom",
"[",
"]",
">",
"trans",
"=",
"M... | Calculates the MC score, specific for the MultipleAlignment algorithm.
The score function is modified from the original CEMC paper, making it
continuous and differentiable.
<p>
The maximum score of a match is 20, and the penalties for gaps are part
of the input. The half-score distance, d0, is chosen as in the TM-score.
<p>
Complexity: T(n,l) = O(l*n^2), if n=number of structures and l=alignment
length.
@param alignment
@param gapOpen
penalty for gap opening (reasonable values are in the range
(1.0-20.0)
@param gapExtension
penalty for extending a gap (reasonable values are in the
range (0.5-10.0)
@param dCutoff
the distance cutoff
@return the value of the score
@throws StructureException | [
"Calculates",
"the",
"MC",
"score",
"specific",
"for",
"the",
"MultipleAlignment",
"algorithm",
".",
"The",
"score",
"function",
"is",
"modified",
"from",
"the",
"original",
"CEMC",
"paper",
"making",
"it",
"continuous",
"and",
"differentiable",
".",
"<p",
">",
... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java#L400-L417 |
prestodb/presto | presto-hive/src/main/java/com/facebook/presto/hive/util/SerDeUtils.java | SerDeUtils.serializeObject | @VisibleForTesting
public static Block serializeObject(Type type, BlockBuilder builder, Object object, ObjectInspector inspector, boolean filterNullMapKeys)
{
switch (inspector.getCategory()) {
case PRIMITIVE:
serializePrimitive(type, builder, object, (PrimitiveObjectInspector) inspector);
return null;
case LIST:
return serializeList(type, builder, object, (ListObjectInspector) inspector);
case MAP:
return serializeMap(type, builder, object, (MapObjectInspector) inspector, filterNullMapKeys);
case STRUCT:
return serializeStruct(type, builder, object, (StructObjectInspector) inspector);
}
throw new RuntimeException("Unknown object inspector category: " + inspector.getCategory());
} | java | @VisibleForTesting
public static Block serializeObject(Type type, BlockBuilder builder, Object object, ObjectInspector inspector, boolean filterNullMapKeys)
{
switch (inspector.getCategory()) {
case PRIMITIVE:
serializePrimitive(type, builder, object, (PrimitiveObjectInspector) inspector);
return null;
case LIST:
return serializeList(type, builder, object, (ListObjectInspector) inspector);
case MAP:
return serializeMap(type, builder, object, (MapObjectInspector) inspector, filterNullMapKeys);
case STRUCT:
return serializeStruct(type, builder, object, (StructObjectInspector) inspector);
}
throw new RuntimeException("Unknown object inspector category: " + inspector.getCategory());
} | [
"@",
"VisibleForTesting",
"public",
"static",
"Block",
"serializeObject",
"(",
"Type",
"type",
",",
"BlockBuilder",
"builder",
",",
"Object",
"object",
",",
"ObjectInspector",
"inspector",
",",
"boolean",
"filterNullMapKeys",
")",
"{",
"switch",
"(",
"inspector",
... | that contain null map keys. For production, null map keys are not allowed. | [
"that",
"contain",
"null",
"map",
"keys",
".",
"For",
"production",
"null",
"map",
"keys",
"are",
"not",
"allowed",
"."
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-hive/src/main/java/com/facebook/presto/hive/util/SerDeUtils.java#L86-L101 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/handlers/InboundCookiesHandler.java | InboundCookiesHandler.getCookieValue | private String getCookieValue(HttpServerExchange exchange, String cookieName) {
String value = null;
Map<String, Cookie> requestCookies = exchange.getRequestCookies();
if (requestCookies != null) {
Cookie cookie = exchange.getRequestCookies().get(cookieName);
if (cookie != null) {
value = cookie.getValue();
}
}
return value;
} | java | private String getCookieValue(HttpServerExchange exchange, String cookieName) {
String value = null;
Map<String, Cookie> requestCookies = exchange.getRequestCookies();
if (requestCookies != null) {
Cookie cookie = exchange.getRequestCookies().get(cookieName);
if (cookie != null) {
value = cookie.getValue();
}
}
return value;
} | [
"private",
"String",
"getCookieValue",
"(",
"HttpServerExchange",
"exchange",
",",
"String",
"cookieName",
")",
"{",
"String",
"value",
"=",
"null",
";",
"Map",
"<",
"String",
",",
"Cookie",
">",
"requestCookies",
"=",
"exchange",
".",
"getRequestCookies",
"(",
... | Retrieves the value of a cookie with a given name from a HttpServerExchange
@param exchange The exchange containing the cookie
@param cookieName The name of the cookie
@return The value of the cookie or null if none found | [
"Retrieves",
"the",
"value",
"of",
"a",
"cookie",
"with",
"a",
"given",
"name",
"from",
"a",
"HttpServerExchange"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/handlers/InboundCookiesHandler.java#L207-L218 |
Ekryd/sortpom | sorter/src/main/java/sortpom/wrapper/ElementSortOrderMap.java | ElementSortOrderMap.addElement | public void addElement(Element element, int sortOrder) {
final String deepName = getDeepName(element);
elementNameSortOrderMap.put(deepName, sortOrder);
} | java | public void addElement(Element element, int sortOrder) {
final String deepName = getDeepName(element);
elementNameSortOrderMap.put(deepName, sortOrder);
} | [
"public",
"void",
"addElement",
"(",
"Element",
"element",
",",
"int",
"sortOrder",
")",
"{",
"final",
"String",
"deepName",
"=",
"getDeepName",
"(",
"element",
")",
";",
"elementNameSortOrderMap",
".",
"put",
"(",
"deepName",
",",
"sortOrder",
")",
";",
"}"... | Add an Xml element to the map
@param element Xml element
@param sortOrder an index describing the sort order (lower number == element towards the start of the file) | [
"Add",
"an",
"Xml",
"element",
"to",
"the",
"map"
] | train | https://github.com/Ekryd/sortpom/blob/27056420803ed04001e4149b04a719fbac774c5d/sorter/src/main/java/sortpom/wrapper/ElementSortOrderMap.java#L24-L28 |
Azure/azure-sdk-for-java | cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java | DatabaseAccountsInner.listKeysAsync | public Observable<DatabaseAccountListKeysResultInner> listKeysAsync(String resourceGroupName, String accountName) {
return listKeysWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<DatabaseAccountListKeysResultInner>, DatabaseAccountListKeysResultInner>() {
@Override
public DatabaseAccountListKeysResultInner call(ServiceResponse<DatabaseAccountListKeysResultInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseAccountListKeysResultInner> listKeysAsync(String resourceGroupName, String accountName) {
return listKeysWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<DatabaseAccountListKeysResultInner>, DatabaseAccountListKeysResultInner>() {
@Override
public DatabaseAccountListKeysResultInner call(ServiceResponse<DatabaseAccountListKeysResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseAccountListKeysResultInner",
">",
"listKeysAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"return",
"listKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
")",
".",
"map"... | Lists the access keys for the specified Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseAccountListKeysResultInner object | [
"Lists",
"the",
"access",
"keys",
"for",
"the",
"specified",
"Azure",
"Cosmos",
"DB",
"database",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1137-L1144 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cp/internal/raftop/metadata/TriggerDestroyRaftGroupOp.java | TriggerDestroyRaftGroupOp.run | @Override
public Object run(MetadataRaftGroupManager metadataGroupManager, long commitIndex) {
metadataGroupManager.triggerDestroyRaftGroup(targetGroupId);
return targetGroupId;
} | java | @Override
public Object run(MetadataRaftGroupManager metadataGroupManager, long commitIndex) {
metadataGroupManager.triggerDestroyRaftGroup(targetGroupId);
return targetGroupId;
} | [
"@",
"Override",
"public",
"Object",
"run",
"(",
"MetadataRaftGroupManager",
"metadataGroupManager",
",",
"long",
"commitIndex",
")",
"{",
"metadataGroupManager",
".",
"triggerDestroyRaftGroup",
"(",
"targetGroupId",
")",
";",
"return",
"targetGroupId",
";",
"}"
] | Please note that targetGroupId is the Raft group that is being queried | [
"Please",
"note",
"that",
"targetGroupId",
"is",
"the",
"Raft",
"group",
"that",
"is",
"being",
"queried"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/raftop/metadata/TriggerDestroyRaftGroupOp.java#L47-L51 |
phax/ph-commons | ph-jaxb/src/main/java/com/helger/jaxb/JAXBMarshallerHelper.java | JAXBMarshallerHelper.setEncoding | public static void setEncoding (@Nonnull final Marshaller aMarshaller, @Nullable final String sEncoding)
{
_setProperty (aMarshaller, Marshaller.JAXB_ENCODING, sEncoding);
} | java | public static void setEncoding (@Nonnull final Marshaller aMarshaller, @Nullable final String sEncoding)
{
_setProperty (aMarshaller, Marshaller.JAXB_ENCODING, sEncoding);
} | [
"public",
"static",
"void",
"setEncoding",
"(",
"@",
"Nonnull",
"final",
"Marshaller",
"aMarshaller",
",",
"@",
"Nullable",
"final",
"String",
"sEncoding",
")",
"{",
"_setProperty",
"(",
"aMarshaller",
",",
"Marshaller",
".",
"JAXB_ENCODING",
",",
"sEncoding",
"... | Set the standard property for the encoding charset.
@param aMarshaller
The marshaller to set the property. May not be <code>null</code>.
@param sEncoding
the value to be set | [
"Set",
"the",
"standard",
"property",
"for",
"the",
"encoding",
"charset",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-jaxb/src/main/java/com/helger/jaxb/JAXBMarshallerHelper.java#L111-L114 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/render/AbstractRenderer.java | AbstractRenderer.createLabel | public Label createLabel(BaseComponent parent, Object value, String prefix, String style, boolean asFirst) {
Label label = new Label(createLabelText(value, prefix));
label.setStyles(style);
parent.addChild(label, asFirst ? 0 : -1);
return label;
} | java | public Label createLabel(BaseComponent parent, Object value, String prefix, String style, boolean asFirst) {
Label label = new Label(createLabelText(value, prefix));
label.setStyles(style);
parent.addChild(label, asFirst ? 0 : -1);
return label;
} | [
"public",
"Label",
"createLabel",
"(",
"BaseComponent",
"parent",
",",
"Object",
"value",
",",
"String",
"prefix",
",",
"String",
"style",
",",
"boolean",
"asFirst",
")",
"{",
"Label",
"label",
"=",
"new",
"Label",
"(",
"createLabelText",
"(",
"value",
",",
... | Creates a label for a string value.
@param parent BaseComponent that will be the parent of the label.
@param value Value to be used as label text.
@param prefix Value to be used as a prefix for the label text.
@param style Style to be applied to the label.
@param asFirst If true, the label is prepended to the parent. If false, it is appended.
@return The newly created label. | [
"Creates",
"a",
"label",
"for",
"a",
"string",
"value",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/render/AbstractRenderer.java#L114-L119 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/history/diff/CmsValueDiff.java | CmsValueDiff.buildValueComparisonTable | private Table buildValueComparisonTable(
CmsObject cms,
final Component parent,
CmsFile file1,
CmsFile file2,
CmsMacroResolver macroResolver)
throws CmsException {
CmsXmlDocumentComparison comp = new CmsXmlDocumentComparison(cms, file1, file2);
CmsBeanTableBuilder<CmsValueCompareBean> builder = CmsBeanTableBuilder.newInstance(
CmsValueCompareBean.class,
A_CmsUI.get().getDisplayType().toString());
builder.setMacroResolver(macroResolver);
List<CmsValueCompareBean> rows = Lists.newArrayList();
for (CmsElementComparison entry : comp.getElements()) {
final String text1 = entry.getVersion1();
final String text2 = entry.getVersion2();
if (Objects.equal(text1, text2)) {
continue;
}
final CmsValueCompareBean row = new CmsValueCompareBean(cms, entry);
row.getChangeType().addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
public void buttonClick(ClickEvent event) {
CmsTextDiffPanel diffPanel = new CmsTextDiffPanel(text1, text2, true, true);
diffPanel.setSizeFull();
CmsHistoryDialog.openChildDialog(
parent,
diffPanel,
CmsVaadinUtils.getMessageText(Messages.GUI_HISTORY_DIALOG_COMPARE_VALUE_1, row.getXPath()));
}
});
rows.add(row);
}
Table table = builder.buildTable(rows);
table.setSortEnabled(false);
table.setWidth("100%");
table.setPageLength(Math.min(rows.size(), 12));
return table;
} | java | private Table buildValueComparisonTable(
CmsObject cms,
final Component parent,
CmsFile file1,
CmsFile file2,
CmsMacroResolver macroResolver)
throws CmsException {
CmsXmlDocumentComparison comp = new CmsXmlDocumentComparison(cms, file1, file2);
CmsBeanTableBuilder<CmsValueCompareBean> builder = CmsBeanTableBuilder.newInstance(
CmsValueCompareBean.class,
A_CmsUI.get().getDisplayType().toString());
builder.setMacroResolver(macroResolver);
List<CmsValueCompareBean> rows = Lists.newArrayList();
for (CmsElementComparison entry : comp.getElements()) {
final String text1 = entry.getVersion1();
final String text2 = entry.getVersion2();
if (Objects.equal(text1, text2)) {
continue;
}
final CmsValueCompareBean row = new CmsValueCompareBean(cms, entry);
row.getChangeType().addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
public void buttonClick(ClickEvent event) {
CmsTextDiffPanel diffPanel = new CmsTextDiffPanel(text1, text2, true, true);
diffPanel.setSizeFull();
CmsHistoryDialog.openChildDialog(
parent,
diffPanel,
CmsVaadinUtils.getMessageText(Messages.GUI_HISTORY_DIALOG_COMPARE_VALUE_1, row.getXPath()));
}
});
rows.add(row);
}
Table table = builder.buildTable(rows);
table.setSortEnabled(false);
table.setWidth("100%");
table.setPageLength(Math.min(rows.size(), 12));
return table;
} | [
"private",
"Table",
"buildValueComparisonTable",
"(",
"CmsObject",
"cms",
",",
"final",
"Component",
"parent",
",",
"CmsFile",
"file1",
",",
"CmsFile",
"file2",
",",
"CmsMacroResolver",
"macroResolver",
")",
"throws",
"CmsException",
"{",
"CmsXmlDocumentComparison",
"... | Builds the table for the content value comparisons.<p>
@param cms the CMS context
@param parent the parent widget for the table (does not need to be the direct parent)
@param file1 the first file
@param file2 the second file
@param macroResolver the macro resolver to use for building the table
@return the table with the content value comparisons
@throws CmsException if something goes wrong | [
"Builds",
"the",
"table",
"for",
"the",
"content",
"value",
"comparisons",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/history/diff/CmsValueDiff.java#L141-L185 |
Multifarious/MacroManager | src/main/java/com/fasterxml/mama/Cluster.java | Cluster.stopAndWait | public void stopAndWait(final long waitTime, final AtomicBoolean stopFlag) {
if (!waitInProgress.getAndSet(true)) {
stopFlag.set(true);
rejoinExecutor.submit(new Runnable() {
@Override
public void run() {
balancingPolicy.drainToCount(0, false);
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
LOG.warn("Interrupted while waiting.");
}
LOG.info("Back to work.");
stopFlag.set(false);
waitInProgress.set(false);
}
});
}
} | java | public void stopAndWait(final long waitTime, final AtomicBoolean stopFlag) {
if (!waitInProgress.getAndSet(true)) {
stopFlag.set(true);
rejoinExecutor.submit(new Runnable() {
@Override
public void run() {
balancingPolicy.drainToCount(0, false);
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
LOG.warn("Interrupted while waiting.");
}
LOG.info("Back to work.");
stopFlag.set(false);
waitInProgress.set(false);
}
});
}
} | [
"public",
"void",
"stopAndWait",
"(",
"final",
"long",
"waitTime",
",",
"final",
"AtomicBoolean",
"stopFlag",
")",
"{",
"if",
"(",
"!",
"waitInProgress",
".",
"getAndSet",
"(",
"true",
")",
")",
"{",
"stopFlag",
".",
"set",
"(",
"true",
")",
";",
"rejoin... | For handling problematic nodes - drains workers and does not claim work for waitTime seconds | [
"For",
"handling",
"problematic",
"nodes",
"-",
"drains",
"workers",
"and",
"does",
"not",
"claim",
"work",
"for",
"waitTime",
"seconds"
] | train | https://github.com/Multifarious/MacroManager/blob/559785839981f460aaeba3c3fddff7fb667d9581/src/main/java/com/fasterxml/mama/Cluster.java#L421-L439 |
threerings/narya | core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java | PresentsConnectionManager.writeDatagram | protected boolean writeDatagram (PresentsConnection conn, byte[] data)
{
InetSocketAddress target = conn.getDatagramAddress();
if (target == null) {
log.warning("No address to send datagram", "conn", conn);
return false;
}
_databuf.clear();
_databuf.put(data).flip();
try {
return conn.getDatagramChannel().send(_databuf, target) > 0;
} catch (IOException ioe) {
log.warning("Failed to send datagram.", ioe);
return false;
}
} | java | protected boolean writeDatagram (PresentsConnection conn, byte[] data)
{
InetSocketAddress target = conn.getDatagramAddress();
if (target == null) {
log.warning("No address to send datagram", "conn", conn);
return false;
}
_databuf.clear();
_databuf.put(data).flip();
try {
return conn.getDatagramChannel().send(_databuf, target) > 0;
} catch (IOException ioe) {
log.warning("Failed to send datagram.", ioe);
return false;
}
} | [
"protected",
"boolean",
"writeDatagram",
"(",
"PresentsConnection",
"conn",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"InetSocketAddress",
"target",
"=",
"conn",
".",
"getDatagramAddress",
"(",
")",
";",
"if",
"(",
"target",
"==",
"null",
")",
"{",
"log",
"... | Sends a datagram to the specified connection.
@return true if the datagram was sent, false if we failed to send for any reason. | [
"Sends",
"a",
"datagram",
"to",
"the",
"specified",
"connection",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L556-L572 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.escapeUriPathSegment | public static String escapeUriPathSegment(final String text, final String encoding) {
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
return UriEscapeUtil.escape(text, UriEscapeUtil.UriEscapeType.PATH_SEGMENT, encoding);
} | java | public static String escapeUriPathSegment(final String text, final String encoding) {
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
return UriEscapeUtil.escape(text, UriEscapeUtil.UriEscapeType.PATH_SEGMENT, encoding);
} | [
"public",
"static",
"String",
"escapeUriPathSegment",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"encoding",
")",
"{",
"if",
"(",
"encoding",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'encoding' cannot be null\... | <p>
Perform am URI path segment <strong>escape</strong> operation
on a <tt>String</tt> input.
</p>
<p>
The following are the only allowed chars in an URI path segment (will not be escaped):
</p>
<ul>
<li><tt>A-Z a-z 0-9</tt></li>
<li><tt>- . _ ~</tt></li>
<li><tt>! $ & ' ( ) * + , ; =</tt></li>
<li><tt>: @</tt></li>
</ul>
<p>
All other chars will be escaped by converting them to the sequence of bytes that
represents them in the specified <em>encoding</em> and then representing each byte
in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param encoding the encoding to be used for escaping.
@return The escaped result <tt>String</tt>. As a memory-performance improvement, will return the exact
same object as the <tt>text</tt> input argument if no escaping modifications were required (and
no additional <tt>String</tt> objects will be created during processing). Will
return <tt>null</tt> if input is <tt>null</tt>. | [
"<p",
">",
"Perform",
"am",
"URI",
"path",
"segment",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
"p",
">",
"<p",
">",
"The",
"following",
"are",
"the",
"only... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L252-L257 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sw/RepairingNsStreamWriter.java | RepairingNsStreamWriter.findElemPrefix | protected final String findElemPrefix(String nsURI, SimpleOutputElement elem)
throws XMLStreamException
{
/* Special case: empty NS URI can only be bound to the empty
* prefix...
*/
if (nsURI == null || nsURI.length() == 0) {
String currDefNsURI = elem.getDefaultNsUri();
if (currDefNsURI != null && currDefNsURI.length() > 0) {
// Nope; won't do... has to be re-bound, but not here:
return null;
}
return "";
}
return mCurrElem.getPrefix(nsURI);
} | java | protected final String findElemPrefix(String nsURI, SimpleOutputElement elem)
throws XMLStreamException
{
/* Special case: empty NS URI can only be bound to the empty
* prefix...
*/
if (nsURI == null || nsURI.length() == 0) {
String currDefNsURI = elem.getDefaultNsUri();
if (currDefNsURI != null && currDefNsURI.length() > 0) {
// Nope; won't do... has to be re-bound, but not here:
return null;
}
return "";
}
return mCurrElem.getPrefix(nsURI);
} | [
"protected",
"final",
"String",
"findElemPrefix",
"(",
"String",
"nsURI",
",",
"SimpleOutputElement",
"elem",
")",
"throws",
"XMLStreamException",
"{",
"/* Special case: empty NS URI can only be bound to the empty\n * prefix...\n */",
"if",
"(",
"nsURI",
"==",
"... | Method called to find an existing prefix for the given namespace,
if any exists in the scope. If one is found, it's returned (including
"" for the current default namespace); if not, null is returned.
@param nsURI URI of namespace for which we need a prefix | [
"Method",
"called",
"to",
"find",
"an",
"existing",
"prefix",
"for",
"the",
"given",
"namespace",
"if",
"any",
"exists",
"in",
"the",
"scope",
".",
"If",
"one",
"is",
"found",
"it",
"s",
"returned",
"(",
"including",
"for",
"the",
"current",
"default",
"... | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sw/RepairingNsStreamWriter.java#L475-L490 |
liferay/com-liferay-commerce | commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java | CommerceCurrencyPersistenceImpl.findByG_P_A | @Override
public List<CommerceCurrency> findByG_P_A(long groupId, boolean primary,
boolean active, int start, int end) {
return findByG_P_A(groupId, primary, active, start, end, null);
} | java | @Override
public List<CommerceCurrency> findByG_P_A(long groupId, boolean primary,
boolean active, int start, int end) {
return findByG_P_A(groupId, primary, active, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceCurrency",
">",
"findByG_P_A",
"(",
"long",
"groupId",
",",
"boolean",
"primary",
",",
"boolean",
"active",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByG_P_A",
"(",
"groupId",
",",
"pr... | Returns a range of all the commerce currencies where groupId = ? and primary = ? and active = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceCurrencyModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param primary the primary
@param active the active
@param start the lower bound of the range of commerce currencies
@param end the upper bound of the range of commerce currencies (not inclusive)
@return the range of matching commerce currencies | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"currencies",
"where",
"groupId",
"=",
"?",
";",
"and",
"primary",
"=",
"?",
";",
"and",
"active",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L3391-L3395 |
ingwarsw/arquillian-suite-extension | src/main/java/org/eu/ingwar/tools/arquillian/extension/deployment/EarDescriptorBuilder.java | EarDescriptorBuilder.writeWebModule | private void writeWebModule(String filename, String context) {
Element element = writeModule();
Element web = doc.createElement("web");
element.appendChild(web);
Element webUri = doc.createElement("web-uri");
Element contextRoot = doc.createElement("context-root");
web.appendChild(webUri);
web.appendChild(contextRoot);
webUri.setTextContent(filename);
contextRoot.setTextContent(context);
} | java | private void writeWebModule(String filename, String context) {
Element element = writeModule();
Element web = doc.createElement("web");
element.appendChild(web);
Element webUri = doc.createElement("web-uri");
Element contextRoot = doc.createElement("context-root");
web.appendChild(webUri);
web.appendChild(contextRoot);
webUri.setTextContent(filename);
contextRoot.setTextContent(context);
} | [
"private",
"void",
"writeWebModule",
"(",
"String",
"filename",
",",
"String",
"context",
")",
"{",
"Element",
"element",
"=",
"writeModule",
"(",
")",
";",
"Element",
"web",
"=",
"doc",
".",
"createElement",
"(",
"\"web\"",
")",
";",
"element",
".",
"appe... | Writes WEB part to application.xml.
@param filename name of module
@param context context | [
"Writes",
"WEB",
"part",
"to",
"application",
".",
"xml",
"."
] | train | https://github.com/ingwarsw/arquillian-suite-extension/blob/93c9e542ead1d52f45e87b0632bb02ac11f693c8/src/main/java/org/eu/ingwar/tools/arquillian/extension/deployment/EarDescriptorBuilder.java#L191-L201 |
Microsoft/malmo | Minecraft/src/main/java/com/microsoft/Malmo/Utils/JSONWorldDataHelper.java | JSONWorldDataHelper.buildAchievementStats | public static void buildAchievementStats(JsonObject json, EntityPlayerMP player)
{
StatisticsManagerServer sfw = player.getStatFile();
json.addProperty("DistanceTravelled",
sfw.readStat((StatBase)StatList.WALK_ONE_CM)
+ sfw.readStat((StatBase)StatList.SWIM_ONE_CM)
+ sfw.readStat((StatBase)StatList.DIVE_ONE_CM)
+ sfw.readStat((StatBase)StatList.FALL_ONE_CM)
); // TODO: there are many other ways of moving!
json.addProperty("TimeAlive", sfw.readStat((StatBase)StatList.TIME_SINCE_DEATH));
json.addProperty("MobsKilled", sfw.readStat((StatBase)StatList.MOB_KILLS));
json.addProperty("PlayersKilled", sfw.readStat((StatBase)StatList.PLAYER_KILLS));
json.addProperty("DamageTaken", sfw.readStat((StatBase)StatList.DAMAGE_TAKEN));
json.addProperty("DamageDealt", sfw.readStat((StatBase)StatList.DAMAGE_DEALT));
/* Other potential reinforcement signals that may be worth researching:
json.addProperty("BlocksDestroyed", sfw.readStat((StatBase)StatList.objectBreakStats) - but objectBreakStats is an array of 32000 StatBase objects - indexed by block type.);
json.addProperty("Blocked", ev.player.isMovementBlocked()) - but isMovementBlocker() is a protected method (can get round this with reflection)
*/
} | java | public static void buildAchievementStats(JsonObject json, EntityPlayerMP player)
{
StatisticsManagerServer sfw = player.getStatFile();
json.addProperty("DistanceTravelled",
sfw.readStat((StatBase)StatList.WALK_ONE_CM)
+ sfw.readStat((StatBase)StatList.SWIM_ONE_CM)
+ sfw.readStat((StatBase)StatList.DIVE_ONE_CM)
+ sfw.readStat((StatBase)StatList.FALL_ONE_CM)
); // TODO: there are many other ways of moving!
json.addProperty("TimeAlive", sfw.readStat((StatBase)StatList.TIME_SINCE_DEATH));
json.addProperty("MobsKilled", sfw.readStat((StatBase)StatList.MOB_KILLS));
json.addProperty("PlayersKilled", sfw.readStat((StatBase)StatList.PLAYER_KILLS));
json.addProperty("DamageTaken", sfw.readStat((StatBase)StatList.DAMAGE_TAKEN));
json.addProperty("DamageDealt", sfw.readStat((StatBase)StatList.DAMAGE_DEALT));
/* Other potential reinforcement signals that may be worth researching:
json.addProperty("BlocksDestroyed", sfw.readStat((StatBase)StatList.objectBreakStats) - but objectBreakStats is an array of 32000 StatBase objects - indexed by block type.);
json.addProperty("Blocked", ev.player.isMovementBlocked()) - but isMovementBlocker() is a protected method (can get round this with reflection)
*/
} | [
"public",
"static",
"void",
"buildAchievementStats",
"(",
"JsonObject",
"json",
",",
"EntityPlayerMP",
"player",
")",
"{",
"StatisticsManagerServer",
"sfw",
"=",
"player",
".",
"getStatFile",
"(",
")",
";",
"json",
".",
"addProperty",
"(",
"\"DistanceTravelled\"",
... | Builds the basic achievement world data to be used as observation signals by the listener.
@param json a JSON object into which the achievement stats will be added. | [
"Builds",
"the",
"basic",
"achievement",
"world",
"data",
"to",
"be",
"used",
"as",
"observation",
"signals",
"by",
"the",
"listener",
"."
] | train | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Minecraft/src/main/java/com/microsoft/Malmo/Utils/JSONWorldDataHelper.java#L100-L119 |
mygreen/super-csv-annotation | src/main/java/com/github/mygreen/supercsv/builder/FieldAccessor.java | FieldAccessor.hasAnnotationByGroup | public <A extends Annotation> boolean hasAnnotationByGroup(final Class<A> annoClass, final Class<?>... groups) {
return getAnnotationsByGroup(annoClass, groups).size() > 0;
} | java | public <A extends Annotation> boolean hasAnnotationByGroup(final Class<A> annoClass, final Class<?>... groups) {
return getAnnotationsByGroup(annoClass, groups).size() > 0;
} | [
"public",
"<",
"A",
"extends",
"Annotation",
">",
"boolean",
"hasAnnotationByGroup",
"(",
"final",
"Class",
"<",
"A",
">",
"annoClass",
",",
"final",
"Class",
"<",
"?",
">",
"...",
"groups",
")",
"{",
"return",
"getAnnotationsByGroup",
"(",
"annoClass",
",",... | グループを指定して指定したアノテーションを持つかどうか判定します。
@param <A> 取得対象のアノテーションのタイプ
@param annoClass 判定対象のアノテーションのグループ
@param groups グループ(クラスタイプ)による絞り込み。属性groupsが存在する場合に、絞り込みます。
@return 指定したアノテーションが見つからない場合は、サイズ0のリストを返します。 | [
"グループを指定して指定したアノテーションを持つかどうか判定します。"
] | train | https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/FieldAccessor.java#L161-L165 |
litsec/eidas-opensaml | opensaml3/src/main/java/se/litsec/eidas/opensaml/ext/RequestedAttributeTemplates.java | RequestedAttributeTemplates.PERSON_IDENTIFIER | public static RequestedAttribute PERSON_IDENTIFIER(Boolean isRequired, boolean includeFriendlyName) {
return create(AttributeConstants.EIDAS_PERSON_IDENTIFIER_ATTRIBUTE_NAME,
includeFriendlyName ? AttributeConstants.EIDAS_PERSON_IDENTIFIER_ATTRIBUTE_FRIENDLY_NAME : null,
Attribute.URI_REFERENCE, isRequired);
} | java | public static RequestedAttribute PERSON_IDENTIFIER(Boolean isRequired, boolean includeFriendlyName) {
return create(AttributeConstants.EIDAS_PERSON_IDENTIFIER_ATTRIBUTE_NAME,
includeFriendlyName ? AttributeConstants.EIDAS_PERSON_IDENTIFIER_ATTRIBUTE_FRIENDLY_NAME : null,
Attribute.URI_REFERENCE, isRequired);
} | [
"public",
"static",
"RequestedAttribute",
"PERSON_IDENTIFIER",
"(",
"Boolean",
"isRequired",
",",
"boolean",
"includeFriendlyName",
")",
"{",
"return",
"create",
"(",
"AttributeConstants",
".",
"EIDAS_PERSON_IDENTIFIER_ATTRIBUTE_NAME",
",",
"includeFriendlyName",
"?",
"Attr... | Creates a {@code RequestedAttribute} object for the PersonIdentifier attribute.
@param isRequired
flag to tell whether the attribute is required
@param includeFriendlyName
flag that tells whether the friendly name should be included
@return a {@code RequestedAttribute} object representing the PersonIdentifier attribute | [
"Creates",
"a",
"{",
"@code",
"RequestedAttribute",
"}",
"object",
"for",
"the",
"PersonIdentifier",
"attribute",
"."
] | train | https://github.com/litsec/eidas-opensaml/blob/522ba6dba433a9524cb8a02464cc3b087b47a2b7/opensaml3/src/main/java/se/litsec/eidas/opensaml/ext/RequestedAttributeTemplates.java#L41-L45 |
jenkinsci/jenkins | core/src/main/java/hudson/model/RSS.java | RSS.forwardToRss | public static <E> void forwardToRss(String title, String url, Collection<? extends E> entries, FeedAdapter<E> adapter, StaplerRequest req, HttpServletResponse rsp) throws IOException, ServletException {
req.setAttribute("adapter",adapter);
req.setAttribute("title",title);
req.setAttribute("url",url);
req.setAttribute("entries",entries);
req.setAttribute("rootURL", Jenkins.getInstance().getRootUrl());
String flavor = req.getParameter("flavor");
if(flavor==null) flavor="atom";
flavor = flavor.replace('/', '_'); // Don't allow path to any jelly
req.getView(Jenkins.getInstance(),"/hudson/"+flavor+".jelly").forward(req,rsp);
} | java | public static <E> void forwardToRss(String title, String url, Collection<? extends E> entries, FeedAdapter<E> adapter, StaplerRequest req, HttpServletResponse rsp) throws IOException, ServletException {
req.setAttribute("adapter",adapter);
req.setAttribute("title",title);
req.setAttribute("url",url);
req.setAttribute("entries",entries);
req.setAttribute("rootURL", Jenkins.getInstance().getRootUrl());
String flavor = req.getParameter("flavor");
if(flavor==null) flavor="atom";
flavor = flavor.replace('/', '_'); // Don't allow path to any jelly
req.getView(Jenkins.getInstance(),"/hudson/"+flavor+".jelly").forward(req,rsp);
} | [
"public",
"static",
"<",
"E",
">",
"void",
"forwardToRss",
"(",
"String",
"title",
",",
"String",
"url",
",",
"Collection",
"<",
"?",
"extends",
"E",
">",
"entries",
",",
"FeedAdapter",
"<",
"E",
">",
"adapter",
",",
"StaplerRequest",
"req",
",",
"HttpSe... | Sends the RSS feed to the client.
@param title
Title of the feed.
@param url
URL of the model object that owns this feed. Relative to the context root.
@param entries
Entries to be listed in the RSS feed.
@param adapter
Controls how to render entries to RSS. | [
"Sends",
"the",
"RSS",
"feed",
"to",
"the",
"client",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/RSS.java#L75-L87 |
shevek/jarjar | jarjar-gradle/src/main/java/org/anarres/gradle/plugin/jarjar/JarjarTask.java | JarjarTask.from | public void from(@Nonnull String dependencyNotation, Closure configClosure) {
from(getProject().getDependencies().create(dependencyNotation, configClosure));
} | java | public void from(@Nonnull String dependencyNotation, Closure configClosure) {
from(getProject().getDependencies().create(dependencyNotation, configClosure));
} | [
"public",
"void",
"from",
"(",
"@",
"Nonnull",
"String",
"dependencyNotation",
",",
"Closure",
"configClosure",
")",
"{",
"from",
"(",
"getProject",
"(",
")",
".",
"getDependencies",
"(",
")",
".",
"create",
"(",
"dependencyNotation",
",",
"configClosure",
")"... | Processes a dependency specified by name.
@param dependencyNotation The dependency, in a notation described in {@link DependencyHandler}.
@param configClosure The closure to use to configure the dependency.
@see DependencyHandler | [
"Processes",
"a",
"dependency",
"specified",
"by",
"name",
"."
] | train | https://github.com/shevek/jarjar/blob/59b9f04970d078184a0d1ac4eeb548215b8e2bc2/jarjar-gradle/src/main/java/org/anarres/gradle/plugin/jarjar/JarjarTask.java#L188-L190 |
bingoohuang/excel2javabeans | src/main/java/com/github/bingoohuang/excel2beans/BeansToExcelOnTemplate.java | BeansToExcelOnTemplate.writeRows | @SuppressWarnings("unchecked")
private void writeRows(Cell templateCell, List<Object> items) {
val tmplRow = templateCell.getRow();
val fromRow = tmplRow.getRowNum();
val tmplCol = templateCell.getColumnIndex();
for (int i = 0, ii = items.size(); i < ii; ++i) {
val item = items.get(i);
val row = i == 0 ? tmplRow : sheet.createRow(fromRow + i);
if (row != tmplRow) {
row.setHeight(tmplRow.getHeight());
}
val fields = item.getClass().getDeclaredFields();
int cutoff = 0;
for (int j = 0; j < fields.length; ++j) {
val field = fields[j];
if (Fields.shouldIgnored(field, ExcelColIgnore.class)) {
++cutoff;
continue;
}
if (field.getName().endsWith("Tmpl")) {
++cutoff;
continue;
}
val fv = Fields.invokeField(field, item);
val excelCell = field.getAnnotation(ExcelCell.class);
int maxLen = excelCell == null ? 0 : excelCell.maxLineLen();
val cell = newCell(tmplRow, tmplCol + j - cutoff, i, row, fv, maxLen);
applyTemplateCellStyle(field, item, excelCell, cell);
}
emptyEndsCells(tmplRow, tmplCol, i, row, fields.length);
}
} | java | @SuppressWarnings("unchecked")
private void writeRows(Cell templateCell, List<Object> items) {
val tmplRow = templateCell.getRow();
val fromRow = tmplRow.getRowNum();
val tmplCol = templateCell.getColumnIndex();
for (int i = 0, ii = items.size(); i < ii; ++i) {
val item = items.get(i);
val row = i == 0 ? tmplRow : sheet.createRow(fromRow + i);
if (row != tmplRow) {
row.setHeight(tmplRow.getHeight());
}
val fields = item.getClass().getDeclaredFields();
int cutoff = 0;
for (int j = 0; j < fields.length; ++j) {
val field = fields[j];
if (Fields.shouldIgnored(field, ExcelColIgnore.class)) {
++cutoff;
continue;
}
if (field.getName().endsWith("Tmpl")) {
++cutoff;
continue;
}
val fv = Fields.invokeField(field, item);
val excelCell = field.getAnnotation(ExcelCell.class);
int maxLen = excelCell == null ? 0 : excelCell.maxLineLen();
val cell = newCell(tmplRow, tmplCol + j - cutoff, i, row, fv, maxLen);
applyTemplateCellStyle(field, item, excelCell, cell);
}
emptyEndsCells(tmplRow, tmplCol, i, row, fields.length);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"void",
"writeRows",
"(",
"Cell",
"templateCell",
",",
"List",
"<",
"Object",
">",
"items",
")",
"{",
"val",
"tmplRow",
"=",
"templateCell",
".",
"getRow",
"(",
")",
";",
"val",
"fromRow",
"=",... | 根据JavaBean列表,向Excel中写入多行。
@param templateCell 模板单元格。
@param items 写入JavaBean列表。 | [
"根据JavaBean列表,向Excel中写入多行。"
] | train | https://github.com/bingoohuang/excel2javabeans/blob/db136d460b93b649814366c0d84a982698b96dc3/src/main/java/com/github/bingoohuang/excel2beans/BeansToExcelOnTemplate.java#L221-L256 |
meltmedia/cadmium | deployer/src/main/java/com/meltmedia/cadmium/deployer/jboss7/JBossAdminApi.java | JBossAdminApi.uploadWar | public String uploadWar(String warName, File warFile) throws Exception {
HttpPost post = new HttpPost("http://"+host+":"+port+"/management/add-content");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("filename", new StringBody(warName));
entity.addPart("attachment", new FileBody(warFile, ContentType.APPLICATION_OCTET_STREAM.getMimeType()));
post.setEntity(entity);
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String respStr = EntityUtils.toString(response.getEntity());
Map<String, Object> respObj = new Gson().fromJson(respStr, new TypeToken<Map<String, Object>>(){}.getType());
if("success".equals(respObj.get("outcome"))) {
Object resultObj = respObj.get("result");
if(resultObj instanceof Map) {
Map<String, Object> resultMap = (Map<String, Object>) resultObj;
return (String) resultMap.get("BYTES_VALUE");
}
} else {
String failureMessage = (String) respObj.get("failure-description");
if (failureMessage == null) {
failureMessage = "Failed to process request.";
}
logger.warn(failureMessage);
throw new Exception("Received " + failureMessage + " response from management api.");
}
}
} finally {
post.releaseConnection();
}
return null;
} | java | public String uploadWar(String warName, File warFile) throws Exception {
HttpPost post = new HttpPost("http://"+host+":"+port+"/management/add-content");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("filename", new StringBody(warName));
entity.addPart("attachment", new FileBody(warFile, ContentType.APPLICATION_OCTET_STREAM.getMimeType()));
post.setEntity(entity);
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String respStr = EntityUtils.toString(response.getEntity());
Map<String, Object> respObj = new Gson().fromJson(respStr, new TypeToken<Map<String, Object>>(){}.getType());
if("success".equals(respObj.get("outcome"))) {
Object resultObj = respObj.get("result");
if(resultObj instanceof Map) {
Map<String, Object> resultMap = (Map<String, Object>) resultObj;
return (String) resultMap.get("BYTES_VALUE");
}
} else {
String failureMessage = (String) respObj.get("failure-description");
if (failureMessage == null) {
failureMessage = "Failed to process request.";
}
logger.warn(failureMessage);
throw new Exception("Received " + failureMessage + " response from management api.");
}
}
} finally {
post.releaseConnection();
}
return null;
} | [
"public",
"String",
"uploadWar",
"(",
"String",
"warName",
",",
"File",
"warFile",
")",
"throws",
"Exception",
"{",
"HttpPost",
"post",
"=",
"new",
"HttpPost",
"(",
"\"http://\"",
"+",
"host",
"+",
"\":\"",
"+",
"port",
"+",
"\"/management/add-content\"",
")",... | /*
curl -v --digest -u "admin" -F "file=@git/cadmium/test.cadmium.localhost.war;filename=test.cadmium.localhost.war" http://localhost:9990/management/add-content
result: {"outcome" : "success", "result" : { "BYTES_VALUE" : "SbejgggTNOuHdke5k6EeKdB8Zfo=" }} | [
"/",
"*",
"curl",
"-",
"v",
"--",
"digest",
"-",
"u",
"admin",
"-",
"F",
"file",
"="
] | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/deployer/src/main/java/com/meltmedia/cadmium/deployer/jboss7/JBossAdminApi.java#L175-L208 |
jamesagnew/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateRangeParam.java | DateRangeParam.setRangeFromDatesInclusive | public void setRangeFromDatesInclusive(String theLowerBound, String theUpperBound) {
DateParam lowerBound = theLowerBound != null
? new DateParam(GREATERTHAN_OR_EQUALS, theLowerBound)
: null;
DateParam upperBound = theUpperBound != null
? new DateParam(LESSTHAN_OR_EQUALS, theUpperBound)
: null;
if (isNotBlank(theLowerBound) && isNotBlank(theUpperBound) && theLowerBound.equals(theUpperBound)) {
lowerBound.setPrefix(EQUAL);
upperBound.setPrefix(EQUAL);
}
validateAndSet(lowerBound, upperBound);
} | java | public void setRangeFromDatesInclusive(String theLowerBound, String theUpperBound) {
DateParam lowerBound = theLowerBound != null
? new DateParam(GREATERTHAN_OR_EQUALS, theLowerBound)
: null;
DateParam upperBound = theUpperBound != null
? new DateParam(LESSTHAN_OR_EQUALS, theUpperBound)
: null;
if (isNotBlank(theLowerBound) && isNotBlank(theUpperBound) && theLowerBound.equals(theUpperBound)) {
lowerBound.setPrefix(EQUAL);
upperBound.setPrefix(EQUAL);
}
validateAndSet(lowerBound, upperBound);
} | [
"public",
"void",
"setRangeFromDatesInclusive",
"(",
"String",
"theLowerBound",
",",
"String",
"theUpperBound",
")",
"{",
"DateParam",
"lowerBound",
"=",
"theLowerBound",
"!=",
"null",
"?",
"new",
"DateParam",
"(",
"GREATERTHAN_OR_EQUALS",
",",
"theLowerBound",
")",
... | Sets the range from a pair of dates, inclusive on both ends
@param theLowerBound A qualified date param representing the lower date bound (optionally may include time), e.g.
"2011-02-22" or "2011-02-22T13:12:00Z". Will be treated inclusively. Either theLowerBound or
theUpperBound may both be populated, or one may be null, but it is not valid for both to be null.
@param theUpperBound A qualified date param representing the upper date bound (optionally may include time), e.g.
"2011-02-22" or "2011-02-22T13:12:00Z". Will be treated inclusively. Either theLowerBound or
theUpperBound may both be populated, or one may be null, but it is not valid for both to be null. | [
"Sets",
"the",
"range",
"from",
"a",
"pair",
"of",
"dates",
"inclusive",
"on",
"both",
"ends"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateRangeParam.java#L446-L458 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.fillPublishList | public CmsPublishList fillPublishList(CmsRequestContext context, CmsPublishList publishList) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
m_driverManager.fillPublishList(dbc, publishList);
checkPublishPermissions(dbc, publishList);
} catch (CmsTooManyPublishResourcesException e) {
throw e;
} catch (Exception e) {
if (publishList.isDirectPublish()) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_GET_PUBLISH_LIST_DIRECT_1,
CmsFileUtil.formatResourceNames(context, publishList.getDirectPublishResources())),
e);
} else {
dbc.report(
null,
Messages.get().container(
Messages.ERR_GET_PUBLISH_LIST_PROJECT_1,
context.getCurrentProject().getName()),
e);
}
} finally {
dbc.clear();
}
return publishList;
} | java | public CmsPublishList fillPublishList(CmsRequestContext context, CmsPublishList publishList) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
m_driverManager.fillPublishList(dbc, publishList);
checkPublishPermissions(dbc, publishList);
} catch (CmsTooManyPublishResourcesException e) {
throw e;
} catch (Exception e) {
if (publishList.isDirectPublish()) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_GET_PUBLISH_LIST_DIRECT_1,
CmsFileUtil.formatResourceNames(context, publishList.getDirectPublishResources())),
e);
} else {
dbc.report(
null,
Messages.get().container(
Messages.ERR_GET_PUBLISH_LIST_PROJECT_1,
context.getCurrentProject().getName()),
e);
}
} finally {
dbc.clear();
}
return publishList;
} | [
"public",
"CmsPublishList",
"fillPublishList",
"(",
"CmsRequestContext",
"context",
",",
"CmsPublishList",
"publishList",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"try",
"{",
... | Fills the given publish list with the the VFS resources that actually get published.<p>
Please refer to the source code of this method for the rules on how to decide whether a
new/changed/deleted <code>{@link CmsResource}</code> object can be published or not.<p>
@param context the current request context
@param publishList must be initialized with basic publish information (Project or direct publish operation)
@return the given publish list filled with all new/changed/deleted files from the current (offline) project
that will be published actually
@throws CmsException if something goes wrong
@see org.opencms.db.CmsPublishList | [
"Fills",
"the",
"given",
"publish",
"list",
"with",
"the",
"the",
"VFS",
"resources",
"that",
"actually",
"get",
"published",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L1839-L1867 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/channels/ChannelHelper.java | ChannelHelper.writeAll | public static void writeAll(WritableByteChannel ch, ByteBuffer bb) throws IOException
{
int count = 0;
while (bb.hasRemaining())
{
int rc = ch.write(bb);
if (rc == 0)
{
count++;
}
if (count > 100)
{
throw new IOException("Couldn't write all.");
}
}
} | java | public static void writeAll(WritableByteChannel ch, ByteBuffer bb) throws IOException
{
int count = 0;
while (bb.hasRemaining())
{
int rc = ch.write(bb);
if (rc == 0)
{
count++;
}
if (count > 100)
{
throw new IOException("Couldn't write all.");
}
}
} | [
"public",
"static",
"void",
"writeAll",
"(",
"WritableByteChannel",
"ch",
",",
"ByteBuffer",
"bb",
")",
"throws",
"IOException",
"{",
"int",
"count",
"=",
"0",
";",
"while",
"(",
"bb",
".",
"hasRemaining",
"(",
")",
")",
"{",
"int",
"rc",
"=",
"ch",
".... | Writes to ch until no remaining left or throws IOException
@param ch
@param bb
@throws IOException | [
"Writes",
"to",
"ch",
"until",
"no",
"remaining",
"left",
"or",
"throws",
"IOException"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/channels/ChannelHelper.java#L308-L323 |
bazaarvoice/emodb | table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java | TableJson.newMoveStart | Delta newMoveStart(Storage src, String destUuid, String destPlacement, int destShardsLog2) {
return Deltas.mapBuilder()
.update(STORAGE.key(), Deltas.mapBuilder()
.update(src.getUuidString(), Deltas.mapBuilder()
.put(Storage.MOVE_TO.key(), destUuid)
.build())
.put(destUuid, storageAttributesBuilder(destPlacement, destShardsLog2, src.isFacade())
.put(StorageState.MIRROR_CREATED.getMarkerAttribute().key(), now())
.put(Storage.GROUP_ID.key(), src.getGroupId())
.build())
.build())
.build();
} | java | Delta newMoveStart(Storage src, String destUuid, String destPlacement, int destShardsLog2) {
return Deltas.mapBuilder()
.update(STORAGE.key(), Deltas.mapBuilder()
.update(src.getUuidString(), Deltas.mapBuilder()
.put(Storage.MOVE_TO.key(), destUuid)
.build())
.put(destUuid, storageAttributesBuilder(destPlacement, destShardsLog2, src.isFacade())
.put(StorageState.MIRROR_CREATED.getMarkerAttribute().key(), now())
.put(Storage.GROUP_ID.key(), src.getGroupId())
.build())
.build())
.build();
} | [
"Delta",
"newMoveStart",
"(",
"Storage",
"src",
",",
"String",
"destUuid",
",",
"String",
"destPlacement",
",",
"int",
"destShardsLog2",
")",
"{",
"return",
"Deltas",
".",
"mapBuilder",
"(",
")",
".",
"update",
"(",
"STORAGE",
".",
"key",
"(",
")",
",",
... | First step in a move, creates the destination storage and sets up mirroring. | [
"First",
"step",
"in",
"a",
"move",
"creates",
"the",
"destination",
"storage",
"and",
"sets",
"up",
"mirroring",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java#L236-L248 |
Alluxio/alluxio | core/base/src/main/java/alluxio/util/URIUtils.java | URIUtils.appendPathOrDie | public static URI appendPathOrDie(URI base, String path) {
try {
return appendPath(base, path);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
} | java | public static URI appendPathOrDie(URI base, String path) {
try {
return appendPath(base, path);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"URI",
"appendPathOrDie",
"(",
"URI",
"base",
",",
"String",
"path",
")",
"{",
"try",
"{",
"return",
"appendPath",
"(",
"base",
",",
"path",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"throw",
"new",
"RuntimeExc... | Appends the given path to the given base URI. It throws an {@link RuntimeException} if
the inputs are malformed.
@param base the base URI
@param path the path to append
@return the URI resulting from appending the base and the path | [
"Appends",
"the",
"given",
"path",
"to",
"the",
"given",
"base",
"URI",
".",
"It",
"throws",
"an",
"{",
"@link",
"RuntimeException",
"}",
"if",
"the",
"inputs",
"are",
"malformed",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/base/src/main/java/alluxio/util/URIUtils.java#L63-L69 |
datacleaner/AnalyzerBeans | components/javascript/src/main/java/org/eobjects/analyzer/beans/script/JavaScriptUtils.java | JavaScriptUtils.addToScope | public static void addToScope(Scriptable scope, Object object, String... names) {
Object jsObject = Context.javaToJS(object, scope);
for (String name : names) {
name = name.replaceAll(" ", "_");
ScriptableObject.putProperty(scope, name, jsObject);
}
} | java | public static void addToScope(Scriptable scope, Object object, String... names) {
Object jsObject = Context.javaToJS(object, scope);
for (String name : names) {
name = name.replaceAll(" ", "_");
ScriptableObject.putProperty(scope, name, jsObject);
}
} | [
"public",
"static",
"void",
"addToScope",
"(",
"Scriptable",
"scope",
",",
"Object",
"object",
",",
"String",
"...",
"names",
")",
"{",
"Object",
"jsObject",
"=",
"Context",
".",
"javaToJS",
"(",
"object",
",",
"scope",
")",
";",
"for",
"(",
"String",
"n... | Adds an object to the JavaScript scope with a set of variable names
@param scope
@param object
@param names | [
"Adds",
"an",
"object",
"to",
"the",
"JavaScript",
"scope",
"with",
"a",
"set",
"of",
"variable",
"names"
] | train | https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/components/javascript/src/main/java/org/eobjects/analyzer/beans/script/JavaScriptUtils.java#L48-L54 |
facebook/fresco | native-filters/src/main/java/com/facebook/imagepipeline/nativecode/NativeRoundingFilter.java | NativeRoundingFilter.toCircle | public static void toCircle(Bitmap bitmap, boolean antiAliased) {
Preconditions.checkNotNull(bitmap);
nativeToCircleFilter(bitmap, antiAliased);
} | java | public static void toCircle(Bitmap bitmap, boolean antiAliased) {
Preconditions.checkNotNull(bitmap);
nativeToCircleFilter(bitmap, antiAliased);
} | [
"public",
"static",
"void",
"toCircle",
"(",
"Bitmap",
"bitmap",
",",
"boolean",
"antiAliased",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"bitmap",
")",
";",
"nativeToCircleFilter",
"(",
"bitmap",
",",
"antiAliased",
")",
";",
"}"
] | This is a fast, native implementation for rounding a bitmap. It takes the given bitmap and
modifies it to be circular.
<p>This implementation does not change the underlying bitmap dimensions, it only sets pixels
that are outside of the circle to a transparent color.
@param bitmap the bitmap to modify | [
"This",
"is",
"a",
"fast",
"native",
"implementation",
"for",
"rounding",
"a",
"bitmap",
".",
"It",
"takes",
"the",
"given",
"bitmap",
"and",
"modifies",
"it",
"to",
"be",
"circular",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/native-filters/src/main/java/com/facebook/imagepipeline/nativecode/NativeRoundingFilter.java#L35-L38 |
SG-O/miIO | src/main/java/de/sg_o/app/miio/yeelight/Light.java | Light.powerOffAfterTime | public boolean powerOffAfterTime(int minutes) throws CommandExecutionException {
JSONArray col = new JSONArray();
col.put(0);
col.put(minutes);
return sendOk("cron_add", col);
} | java | public boolean powerOffAfterTime(int minutes) throws CommandExecutionException {
JSONArray col = new JSONArray();
col.put(0);
col.put(minutes);
return sendOk("cron_add", col);
} | [
"public",
"boolean",
"powerOffAfterTime",
"(",
"int",
"minutes",
")",
"throws",
"CommandExecutionException",
"{",
"JSONArray",
"col",
"=",
"new",
"JSONArray",
"(",
")",
";",
"col",
".",
"put",
"(",
"0",
")",
";",
"col",
".",
"put",
"(",
"minutes",
")",
"... | Power the device off after some time.
@param minutes The time until the device is turned off in minutes.
@return True if the command was received successfully.
@throws CommandExecutionException When there has been a error during the communication or the response was invalid. | [
"Power",
"the",
"device",
"off",
"after",
"some",
"time",
"."
] | train | https://github.com/SG-O/miIO/blob/f352dbd2a699d2cdb1b412ca5e6cbb0c38ca779b/src/main/java/de/sg_o/app/miio/yeelight/Light.java#L254-L259 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java | IncrementalSAXSource_Filter.startParse | public void startParse(InputSource source) throws SAXException
{
if(fNoMoreEvents)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_INCRSAXSRCFILTER_NOT_RESTARTABLE, null)); //"IncrmentalSAXSource_Filter not currently restartable.");
if(fXMLReader==null)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_XMLRDR_NOT_BEFORE_STARTPARSE, null)); //"XMLReader not before startParse request");
fXMLReaderInputSource=source;
// Xalan thread pooling...
// org.apache.xalan.transformer.TransformerImpl.runTransformThread(this);
ThreadControllerWrapper.runThread(this, -1);
} | java | public void startParse(InputSource source) throws SAXException
{
if(fNoMoreEvents)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_INCRSAXSRCFILTER_NOT_RESTARTABLE, null)); //"IncrmentalSAXSource_Filter not currently restartable.");
if(fXMLReader==null)
throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_XMLRDR_NOT_BEFORE_STARTPARSE, null)); //"XMLReader not before startParse request");
fXMLReaderInputSource=source;
// Xalan thread pooling...
// org.apache.xalan.transformer.TransformerImpl.runTransformThread(this);
ThreadControllerWrapper.runThread(this, -1);
} | [
"public",
"void",
"startParse",
"(",
"InputSource",
"source",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"fNoMoreEvents",
")",
"throw",
"new",
"SAXException",
"(",
"XMLMessages",
".",
"createXMLMessage",
"(",
"XMLErrorResources",
".",
"ER_INCRSAXSRCFILTER_NOT_REST... | Launch a thread that will run an XMLReader's parse() operation within
a thread, feeding events to this IncrementalSAXSource_Filter. Mostly a convenience
routine, but has the advantage that -- since we invoked parse() --
we can halt parsing quickly via a StopException rather than waiting
for the SAX stream to end by itself.
@throws SAXException is parse thread is already in progress
or parsing can not be started. | [
"Launch",
"a",
"thread",
"that",
"will",
"run",
"an",
"XMLReader",
"s",
"parse",
"()",
"operation",
"within",
"a",
"thread",
"feeding",
"events",
"to",
"this",
"IncrementalSAXSource_Filter",
".",
"Mostly",
"a",
"convenience",
"routine",
"but",
"has",
"the",
"a... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/IncrementalSAXSource_Filter.java#L603-L615 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java | FlowController.setLocale | protected void setLocale( HttpServletRequest request, Locale locale )
{
HttpSession session = request.getSession();
if ( locale == null )
{
locale = getDefaultLocale();
}
session.setAttribute( Globals.LOCALE_KEY, locale );
} | java | protected void setLocale( HttpServletRequest request, Locale locale )
{
HttpSession session = request.getSession();
if ( locale == null )
{
locale = getDefaultLocale();
}
session.setAttribute( Globals.LOCALE_KEY, locale );
} | [
"protected",
"void",
"setLocale",
"(",
"HttpServletRequest",
"request",
",",
"Locale",
"locale",
")",
"{",
"HttpSession",
"session",
"=",
"request",
".",
"getSession",
"(",
")",
";",
"if",
"(",
"locale",
"==",
"null",
")",
"{",
"locale",
"=",
"getDefaultLoca... | Set the user's currently selected Locale.
@param request The request we are processing
@param locale The user's selected Locale to be set, or null
to select the server's default Locale
@deprecated Use {@link #setLocale(Locale)}. | [
"Set",
"the",
"user",
"s",
"currently",
"selected",
"Locale",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java#L1934-L1944 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java | SparkComputationGraph.doEvaluation | public IEvaluation[] doEvaluation(JavaRDD<String> data, DataSetLoader loader, IEvaluation... emptyEvaluations) {
return doEvaluation(data, DEFAULT_EVAL_WORKERS, DEFAULT_EVAL_SCORE_BATCH_SIZE, loader, emptyEvaluations);
} | java | public IEvaluation[] doEvaluation(JavaRDD<String> data, DataSetLoader loader, IEvaluation... emptyEvaluations) {
return doEvaluation(data, DEFAULT_EVAL_WORKERS, DEFAULT_EVAL_SCORE_BATCH_SIZE, loader, emptyEvaluations);
} | [
"public",
"IEvaluation",
"[",
"]",
"doEvaluation",
"(",
"JavaRDD",
"<",
"String",
">",
"data",
",",
"DataSetLoader",
"loader",
",",
"IEvaluation",
"...",
"emptyEvaluations",
")",
"{",
"return",
"doEvaluation",
"(",
"data",
",",
"DEFAULT_EVAL_WORKERS",
",",
"DEFA... | Perform evaluation on serialized DataSet objects on disk, (potentially in any format), that are loaded using an {@link DataSetLoader}.<br>
Uses the default number of workers (model replicas per JVM) of {@link #DEFAULT_EVAL_WORKERS} with the default
minibatch size of {@link #DEFAULT_EVAL_SCORE_BATCH_SIZE}
@param data List of paths to the data (that can be loaded as / converted to DataSets)
@param loader Used to load DataSets from their paths
@param emptyEvaluations Evaluations to perform
@return Evaluation | [
"Perform",
"evaluation",
"on",
"serialized",
"DataSet",
"objects",
"on",
"disk",
"(",
"potentially",
"in",
"any",
"format",
")",
"that",
"are",
"loaded",
"using",
"an",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java#L867-L869 |
ZieIony/Carbon | carbon/src/main/java/carbon/internal/Menu.java | Menu.findItemWithShortcutForKey | @SuppressWarnings("deprecation")
MenuItem findItemWithShortcutForKey(int keyCode, KeyEvent event) {
// Get all items that can be associated directly or indirectly with the keyCode
ArrayList<MenuItem> items = mTempShortcutItemList;
items.clear();
findItemsWithShortcutForKey(items, keyCode, event);
if (items.isEmpty()) {
return null;
}
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
event.getKeyData(possibleChars);
// If we have only one element, we can safely returns it
final int size = items.size();
if (size == 1) {
return items.get(0);
}
final boolean qwerty = isQwertyMode();
// If we found more than one item associated with the key,
// we have to return the exact match
for (int i = 0; i < size; i++) {
final MenuItem item = items.get(i);
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() :
item.getNumericShortcut();
if ((shortcutChar == possibleChars.meta[0] &&
(metaState & KeyEvent.META_ALT_ON) == 0)
|| (shortcutChar == possibleChars.meta[2] &&
(metaState & KeyEvent.META_ALT_ON) != 0)
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) {
return item;
}
}
return null;
} | java | @SuppressWarnings("deprecation")
MenuItem findItemWithShortcutForKey(int keyCode, KeyEvent event) {
// Get all items that can be associated directly or indirectly with the keyCode
ArrayList<MenuItem> items = mTempShortcutItemList;
items.clear();
findItemsWithShortcutForKey(items, keyCode, event);
if (items.isEmpty()) {
return null;
}
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
event.getKeyData(possibleChars);
// If we have only one element, we can safely returns it
final int size = items.size();
if (size == 1) {
return items.get(0);
}
final boolean qwerty = isQwertyMode();
// If we found more than one item associated with the key,
// we have to return the exact match
for (int i = 0; i < size; i++) {
final MenuItem item = items.get(i);
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() :
item.getNumericShortcut();
if ((shortcutChar == possibleChars.meta[0] &&
(metaState & KeyEvent.META_ALT_ON) == 0)
|| (shortcutChar == possibleChars.meta[2] &&
(metaState & KeyEvent.META_ALT_ON) != 0)
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) {
return item;
}
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"MenuItem",
"findItemWithShortcutForKey",
"(",
"int",
"keyCode",
",",
"KeyEvent",
"event",
")",
"{",
"// Get all items that can be associated directly or indirectly with the keyCode",
"ArrayList",
"<",
"MenuItem",
">",
"it... | /*
We want to return the menu item associated with the key, but if there is no
ambiguity (i.e. there is only one menu item corresponding to the key) we want
to return it even if it's not an exact match; this allow the user to
_not_ use the ALT key for example, making the use of shortcuts slightly more
user-friendly. An example is on the G1, '!' and '1' are on the same key, and
in Gmail, Menu+1 will trigger Menu+! (the actual shortcut).
On the other hand, if two (or more) shortcuts corresponds to the same key,
we have to only return the exact match. | [
"/",
"*",
"We",
"want",
"to",
"return",
"the",
"menu",
"item",
"associated",
"with",
"the",
"key",
"but",
"if",
"there",
"is",
"no",
"ambiguity",
"(",
"i",
".",
"e",
".",
"there",
"is",
"only",
"one",
"menu",
"item",
"corresponding",
"to",
"the",
"ke... | train | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/internal/Menu.java#L667-L706 |
trustathsh/ifmapj | src/main/java/de/hshannover/f4/trust/ifmapj/identifier/Identifiers.java | Identifiers.createIp | public static IpAddress createIp(IpAddressType type, String value, String admDom) {
return new IpAddress(type, value, admDom);
} | java | public static IpAddress createIp(IpAddressType type, String value, String admDom) {
return new IpAddress(type, value, admDom);
} | [
"public",
"static",
"IpAddress",
"createIp",
"(",
"IpAddressType",
"type",
",",
"String",
"value",
",",
"String",
"admDom",
")",
"{",
"return",
"new",
"IpAddress",
"(",
"type",
",",
"value",
",",
"admDom",
")",
";",
"}"
] | Create an ip-address identifier with the given parameters.
@param type the type of the ip-address identifier
@param value a {@link String} that represents a valid IPv4/6 address
@param admDom the administrative-domain
@return the new ip-address identifier | [
"Create",
"an",
"ip",
"-",
"address",
"identifier",
"with",
"the",
"given",
"parameters",
"."
] | train | https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj/identifier/Identifiers.java#L649-L651 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/ServiceUtils.java | ServiceUtils.getLastByteInPart | public static long getLastByteInPart(AmazonS3 s3, GetObjectRequest getObjectRequest, Integer partNumber) {
ValidationUtils.assertNotNull(s3, "S3 client");
ValidationUtils.assertNotNull(getObjectRequest, "GetObjectRequest");
ValidationUtils.assertNotNull(partNumber, "partNumber");
GetObjectMetadataRequest getObjectMetadataRequest = RequestCopyUtils.createGetObjectMetadataRequestFrom(getObjectRequest)
.withPartNumber(partNumber);
ObjectMetadata metadata = s3.getObjectMetadata(getObjectMetadataRequest);
return metadata.getContentRange()[1];
} | java | public static long getLastByteInPart(AmazonS3 s3, GetObjectRequest getObjectRequest, Integer partNumber) {
ValidationUtils.assertNotNull(s3, "S3 client");
ValidationUtils.assertNotNull(getObjectRequest, "GetObjectRequest");
ValidationUtils.assertNotNull(partNumber, "partNumber");
GetObjectMetadataRequest getObjectMetadataRequest = RequestCopyUtils.createGetObjectMetadataRequestFrom(getObjectRequest)
.withPartNumber(partNumber);
ObjectMetadata metadata = s3.getObjectMetadata(getObjectMetadataRequest);
return metadata.getContentRange()[1];
} | [
"public",
"static",
"long",
"getLastByteInPart",
"(",
"AmazonS3",
"s3",
",",
"GetObjectRequest",
"getObjectRequest",
",",
"Integer",
"partNumber",
")",
"{",
"ValidationUtils",
".",
"assertNotNull",
"(",
"s3",
",",
"\"S3 client\"",
")",
";",
"ValidationUtils",
".",
... | Returns the last byte number in a part of an object.
@param s3
The Amazon s3 client.
@param getObjectRequest
The request to check.
@param partNumber
The part in which we need the last byte number.
@return
The last byte number in the part. | [
"Returns",
"the",
"last",
"byte",
"number",
"in",
"a",
"part",
"of",
"an",
"object",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/ServiceUtils.java#L555-L564 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/gdbscan/LSDBC.java | LSDBC.expandCluster | protected int expandCluster(final int clusterid, final WritableIntegerDataStore clusterids, final KNNQuery<O> knnq, final DBIDs neighbors, final double maxkdist, final FiniteProgress progress) {
int clustersize = 1; // initial seed!
final ArrayModifiableDBIDs activeSet = DBIDUtil.newArray();
activeSet.addDBIDs(neighbors);
// run expandCluster as long as this set is non-empty (non-recursive
// implementation)
DBIDVar id = DBIDUtil.newVar();
while(!activeSet.isEmpty()) {
activeSet.pop(id);
// Assign object to cluster
final int oldclus = clusterids.intValue(id);
if(oldclus == NOISE) {
clustersize += 1;
// Non core point cluster member:
clusterids.putInt(id, -clusterid);
}
else if(oldclus == UNPROCESSED) {
clustersize += 1;
// expandCluster again:
// Evaluate Neighborhood predicate
final KNNList newneighbors = knnq.getKNNForDBID(id, k);
// Evaluate Core-Point predicate
if(newneighbors.getKNNDistance() <= maxkdist) {
activeSet.addDBIDs(newneighbors);
}
clusterids.putInt(id, clusterid);
LOG.incrementProcessed(progress);
}
}
return clustersize;
} | java | protected int expandCluster(final int clusterid, final WritableIntegerDataStore clusterids, final KNNQuery<O> knnq, final DBIDs neighbors, final double maxkdist, final FiniteProgress progress) {
int clustersize = 1; // initial seed!
final ArrayModifiableDBIDs activeSet = DBIDUtil.newArray();
activeSet.addDBIDs(neighbors);
// run expandCluster as long as this set is non-empty (non-recursive
// implementation)
DBIDVar id = DBIDUtil.newVar();
while(!activeSet.isEmpty()) {
activeSet.pop(id);
// Assign object to cluster
final int oldclus = clusterids.intValue(id);
if(oldclus == NOISE) {
clustersize += 1;
// Non core point cluster member:
clusterids.putInt(id, -clusterid);
}
else if(oldclus == UNPROCESSED) {
clustersize += 1;
// expandCluster again:
// Evaluate Neighborhood predicate
final KNNList newneighbors = knnq.getKNNForDBID(id, k);
// Evaluate Core-Point predicate
if(newneighbors.getKNNDistance() <= maxkdist) {
activeSet.addDBIDs(newneighbors);
}
clusterids.putInt(id, clusterid);
LOG.incrementProcessed(progress);
}
}
return clustersize;
} | [
"protected",
"int",
"expandCluster",
"(",
"final",
"int",
"clusterid",
",",
"final",
"WritableIntegerDataStore",
"clusterids",
",",
"final",
"KNNQuery",
"<",
"O",
">",
"knnq",
",",
"final",
"DBIDs",
"neighbors",
",",
"final",
"double",
"maxkdist",
",",
"final",
... | Set-based expand cluster implementation.
@param clusterid ID of the current cluster.
@param clusterids Current object to cluster mapping.
@param knnq kNNQuery
@param neighbors Neighbors acquired by initial getNeighbors call.
@param maxkdist Maximum k-distance
@param progress Progress logging
@return cluster size | [
"Set",
"-",
"based",
"expand",
"cluster",
"implementation",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/gdbscan/LSDBC.java#L243-L273 |
apache/incubator-shardingsphere | sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/DatabaseCommunicationEngineFactory.java | DatabaseCommunicationEngineFactory.newTextProtocolInstance | public DatabaseCommunicationEngine newTextProtocolInstance(final LogicSchema logicSchema, final String sql, final BackendConnection backendConnection) {
return new JDBCDatabaseCommunicationEngine(logicSchema, sql, new JDBCExecuteEngine(backendConnection, new StatementExecutorWrapper(logicSchema)));
} | java | public DatabaseCommunicationEngine newTextProtocolInstance(final LogicSchema logicSchema, final String sql, final BackendConnection backendConnection) {
return new JDBCDatabaseCommunicationEngine(logicSchema, sql, new JDBCExecuteEngine(backendConnection, new StatementExecutorWrapper(logicSchema)));
} | [
"public",
"DatabaseCommunicationEngine",
"newTextProtocolInstance",
"(",
"final",
"LogicSchema",
"logicSchema",
",",
"final",
"String",
"sql",
",",
"final",
"BackendConnection",
"backendConnection",
")",
"{",
"return",
"new",
"JDBCDatabaseCommunicationEngine",
"(",
"logicSc... | Create new instance of text protocol backend handler.
@param logicSchema logic schema
@param sql SQL to be executed
@param backendConnection backend connection
@return instance of text protocol backend handler | [
"Create",
"new",
"instance",
"of",
"text",
"protocol",
"backend",
"handler",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/DatabaseCommunicationEngineFactory.java#L60-L62 |
googleads/googleads-java-lib | extensions/adwords_rate_limiter/src/main/java/com/google/api/ads/adwords/extension/ratelimiter/ReflectionUtil.java | ReflectionUtil.isInstanceOf | public static boolean isInstanceOf(Object obj, String classSimpleName) {
if (obj == null) {
return false;
}
Class<?> currentClass = obj.getClass();
while (currentClass != Object.class) {
if (currentClass.getSimpleName().equals(classSimpleName)) {
return true;
} else {
currentClass = currentClass.getSuperclass();
}
}
return false;
} | java | public static boolean isInstanceOf(Object obj, String classSimpleName) {
if (obj == null) {
return false;
}
Class<?> currentClass = obj.getClass();
while (currentClass != Object.class) {
if (currentClass.getSimpleName().equals(classSimpleName)) {
return true;
} else {
currentClass = currentClass.getSuperclass();
}
}
return false;
} | [
"public",
"static",
"boolean",
"isInstanceOf",
"(",
"Object",
"obj",
",",
"String",
"classSimpleName",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"Class",
"<",
"?",
">",
"currentClass",
"=",
"obj",
".",
"getClass",
... | Check whether an object is an instance of a specified class.
@param obj the object to check
@param classSimpleName the simple name of the specified class.
@return true if the object is an instance of the specified class | [
"Check",
"whether",
"an",
"object",
"is",
"an",
"instance",
"of",
"a",
"specified",
"class",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/extensions/adwords_rate_limiter/src/main/java/com/google/api/ads/adwords/extension/ratelimiter/ReflectionUtil.java#L30-L44 |
nakamura5akihito/six-util | src/main/java/jp/go/aist/six/util/core/web/spring/Http.java | Http.postFrom | public static String postFrom(
final URL to_url,
final Reader from_reader,
final MediaType media_type
)
{
ReaderRequestCallback callback =
new ReaderRequestCallback( from_reader, media_type );
String location = _execute( to_url, HttpMethod.POST, callback,
new LocationHeaderResponseExtractor() );
return location;
} | java | public static String postFrom(
final URL to_url,
final Reader from_reader,
final MediaType media_type
)
{
ReaderRequestCallback callback =
new ReaderRequestCallback( from_reader, media_type );
String location = _execute( to_url, HttpMethod.POST, callback,
new LocationHeaderResponseExtractor() );
return location;
} | [
"public",
"static",
"String",
"postFrom",
"(",
"final",
"URL",
"to_url",
",",
"final",
"Reader",
"from_reader",
",",
"final",
"MediaType",
"media_type",
")",
"{",
"ReaderRequestCallback",
"callback",
"=",
"new",
"ReaderRequestCallback",
"(",
"from_reader",
",",
"m... | HTTP POST: Reads the contents from the specified reader and sends them to the URL.
@return
the location, as an URI, where the resource is created.
@throws HttpException
when an exceptional condition occurred during the HTTP method execution. | [
"HTTP",
"POST",
":",
"Reads",
"the",
"contents",
"from",
"the",
"specified",
"reader",
"and",
"sends",
"them",
"to",
"the",
"URL",
"."
] | train | https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/core/web/spring/Http.java#L267-L279 |
gliga/ekstazi | org.ekstazi.core/src/main/java/org/ekstazi/data/TxtStorer.java | TxtStorer.parseLine | protected RegData parseLine(State state, String line) {
// Note. Initial this method was using String.split, but that method
// seems to be much more expensive than playing with indexOf and
// substring.
int sepIndex = line.indexOf(SEPARATOR);
String urlExternalForm = line.substring(0, sepIndex);
String hash = line.substring(sepIndex + SEPARATOR_LEN);
return new RegData(urlExternalForm, hash);
} | java | protected RegData parseLine(State state, String line) {
// Note. Initial this method was using String.split, but that method
// seems to be much more expensive than playing with indexOf and
// substring.
int sepIndex = line.indexOf(SEPARATOR);
String urlExternalForm = line.substring(0, sepIndex);
String hash = line.substring(sepIndex + SEPARATOR_LEN);
return new RegData(urlExternalForm, hash);
} | [
"protected",
"RegData",
"parseLine",
"(",
"State",
"state",
",",
"String",
"line",
")",
"{",
"// Note. Initial this method was using String.split, but that method",
"// seems to be much more expensive than playing with indexOf and",
"// substring.",
"int",
"sepIndex",
"=",
"line",
... | Parses a single line from the file. This method is never invoked for
magic sequence. The line includes path to file and hash. Subclasses may
include more fields.
This method returns null if the line is of no interest. This can be used
by subclasses to implement different protocols. | [
"Parses",
"a",
"single",
"line",
"from",
"the",
"file",
".",
"This",
"method",
"is",
"never",
"invoked",
"for",
"magic",
"sequence",
".",
"The",
"line",
"includes",
"path",
"to",
"file",
"and",
"hash",
".",
"Subclasses",
"may",
"include",
"more",
"fields",... | train | https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/data/TxtStorer.java#L144-L152 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java | ZipUtil.zip | public static File zip(String srcPath, Charset charset) throws UtilException {
return zip(FileUtil.file(srcPath), charset);
} | java | public static File zip(String srcPath, Charset charset) throws UtilException {
return zip(FileUtil.file(srcPath), charset);
} | [
"public",
"static",
"File",
"zip",
"(",
"String",
"srcPath",
",",
"Charset",
"charset",
")",
"throws",
"UtilException",
"{",
"return",
"zip",
"(",
"FileUtil",
".",
"file",
"(",
"srcPath",
")",
",",
"charset",
")",
";",
"}"
] | 打包到当前目录
@param srcPath 源文件路径
@param charset 编码
@return 打包好的压缩文件
@throws UtilException IO异常 | [
"打包到当前目录"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java#L60-L62 |
tempodb/tempodb-java | src/main/java/com/tempodb/Client.java | Client.deleteSeries | public Result<DeleteSummary> deleteSeries(Filter filter) {
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/series/", API_VERSION));
addFilterToURI(builder, filter);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with input - filter: %s", filter);
throw new IllegalArgumentException(message, e);
}
HttpRequest request = buildRequest(uri.toString(), HttpMethod.DELETE);
Result<DeleteSummary> result = execute(request, DeleteSummary.class);
return result;
} | java | public Result<DeleteSummary> deleteSeries(Filter filter) {
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/series/", API_VERSION));
addFilterToURI(builder, filter);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with input - filter: %s", filter);
throw new IllegalArgumentException(message, e);
}
HttpRequest request = buildRequest(uri.toString(), HttpMethod.DELETE);
Result<DeleteSummary> result = execute(request, DeleteSummary.class);
return result;
} | [
"public",
"Result",
"<",
"DeleteSummary",
">",
"deleteSeries",
"(",
"Filter",
"filter",
")",
"{",
"URI",
"uri",
"=",
"null",
";",
"try",
"{",
"URIBuilder",
"builder",
"=",
"new",
"URIBuilder",
"(",
"String",
".",
"format",
"(",
"\"/%s/series/\"",
",",
"API... | Deletes set of series by a filter.
@param filter The series filter @see Filter
@return A DeleteSummary providing information about the series deleted.
@see DeleteSummary
@see Filter
@since 1.0.0 | [
"Deletes",
"set",
"of",
"series",
"by",
"a",
"filter",
"."
] | train | https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L248-L262 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.findResult | public static <T, U> T findResult(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
return findResult(self.iterator(), condition);
} | java | public static <T, U> T findResult(Iterable<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
return findResult(self.iterator(), condition);
} | [
"public",
"static",
"<",
"T",
",",
"U",
">",
"T",
"findResult",
"(",
"Iterable",
"<",
"U",
">",
"self",
",",
"@",
"ClosureParams",
"(",
"FirstParam",
".",
"FirstGenericType",
".",
"class",
")",
"Closure",
"<",
"T",
">",
"condition",
")",
"{",
"return",... | Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null
result is found and returning that result. If all results are null, null is returned.
@param self an Iterable
@param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
@return the first non-null result from calling the closure, or null
@since 2.5.0 | [
"Iterates",
"through",
"the",
"Iterable",
"calling",
"the",
"given",
"closure",
"condition",
"for",
"each",
"item",
"but",
"stopping",
"once",
"the",
"first",
"non",
"-",
"null",
"result",
"is",
"found",
"and",
"returning",
"that",
"result",
".",
"If",
"all"... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L4547-L4549 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-japanese/src/main/java/com/atilika/kuromoji/viterbi/ViterbiBuilder.java | ViterbiBuilder.repairBrokenLatticeBefore | private void repairBrokenLatticeBefore(ViterbiLattice lattice, int index) {
ViterbiNode[][] nodeStartIndices = lattice.getStartIndexArr();
for (int startIndex = index; startIndex > 0; startIndex--) {
if (nodeStartIndices[startIndex] != null) {
ViterbiNode glueBase = findGlueNodeCandidate(index, nodeStartIndices[startIndex], startIndex);
if (glueBase != null) {
int length = index + 1 - startIndex;
String surface = glueBase.getSurface().substring(0, length);
ViterbiNode glueNode = createGlueNode(startIndex, glueBase, surface);
lattice.addNode(glueNode, startIndex, startIndex + glueNode.getSurface().length());
return;
}
}
}
} | java | private void repairBrokenLatticeBefore(ViterbiLattice lattice, int index) {
ViterbiNode[][] nodeStartIndices = lattice.getStartIndexArr();
for (int startIndex = index; startIndex > 0; startIndex--) {
if (nodeStartIndices[startIndex] != null) {
ViterbiNode glueBase = findGlueNodeCandidate(index, nodeStartIndices[startIndex], startIndex);
if (glueBase != null) {
int length = index + 1 - startIndex;
String surface = glueBase.getSurface().substring(0, length);
ViterbiNode glueNode = createGlueNode(startIndex, glueBase, surface);
lattice.addNode(glueNode, startIndex, startIndex + glueNode.getSurface().length());
return;
}
}
}
} | [
"private",
"void",
"repairBrokenLatticeBefore",
"(",
"ViterbiLattice",
"lattice",
",",
"int",
"index",
")",
"{",
"ViterbiNode",
"[",
"]",
"[",
"]",
"nodeStartIndices",
"=",
"lattice",
".",
"getStartIndexArr",
"(",
")",
";",
"for",
"(",
"int",
"startIndex",
"="... | Tries to repair the lattice by creating and adding an additional Viterbi node to the LEFT of the newly
inserted user dictionary entry by using the substring of the node in the lattice that overlaps the least
@param lattice
@param index | [
"Tries",
"to",
"repair",
"the",
"lattice",
"by",
"creating",
"and",
"adding",
"an",
"additional",
"Viterbi",
"node",
"to",
"the",
"LEFT",
"of",
"the",
"newly",
"inserted",
"user",
"dictionary",
"entry",
"by",
"using",
"the",
"substring",
"of",
"the",
"node",... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-japanese/src/main/java/com/atilika/kuromoji/viterbi/ViterbiBuilder.java#L237-L252 |
apache/incubator-zipkin | zipkin/src/main/java/zipkin2/v1/V1BinaryAnnotation.java | V1BinaryAnnotation.createAddress | public static V1BinaryAnnotation createAddress(String address, Endpoint endpoint) {
if (endpoint == null) throw new NullPointerException("endpoint == null");
return new V1BinaryAnnotation(address, null, endpoint);
} | java | public static V1BinaryAnnotation createAddress(String address, Endpoint endpoint) {
if (endpoint == null) throw new NullPointerException("endpoint == null");
return new V1BinaryAnnotation(address, null, endpoint);
} | [
"public",
"static",
"V1BinaryAnnotation",
"createAddress",
"(",
"String",
"address",
",",
"Endpoint",
"endpoint",
")",
"{",
"if",
"(",
"endpoint",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"endpoint == null\"",
")",
";",
"return",
"new",
... | Creates an address annotation, which is the same as {@link Span#remoteEndpoint()} | [
"Creates",
"an",
"address",
"annotation",
"which",
"is",
"the",
"same",
"as",
"{"
] | train | https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin/src/main/java/zipkin2/v1/V1BinaryAnnotation.java#L39-L42 |
graphhopper/graphhopper | client-hc/src/main/java/com/graphhopper/api/MatrixResponse.java | MatrixResponse.getDistance | public double getDistance(int from, int to) {
if (hasErrors()) {
throw new IllegalStateException("Cannot return distance (" + from + "," + to + ") if errors occured " + getErrors());
}
if (from >= distances.length) {
throw new IllegalStateException("Cannot get 'from' " + from + " from distances with size " + distances.length);
} else if (to >= distances[from].length) {
throw new IllegalStateException("Cannot get 'to' " + to + " from distances with size " + distances[from].length);
}
return distances[from][to];
} | java | public double getDistance(int from, int to) {
if (hasErrors()) {
throw new IllegalStateException("Cannot return distance (" + from + "," + to + ") if errors occured " + getErrors());
}
if (from >= distances.length) {
throw new IllegalStateException("Cannot get 'from' " + from + " from distances with size " + distances.length);
} else if (to >= distances[from].length) {
throw new IllegalStateException("Cannot get 'to' " + to + " from distances with size " + distances[from].length);
}
return distances[from][to];
} | [
"public",
"double",
"getDistance",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"if",
"(",
"hasErrors",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot return distance (\"",
"+",
"from",
"+",
"\",\"",
"+",
"to",
"+",
"\") if ... | Returns the distance for the specific entry (from -> to) in meter. | [
"Returns",
"the",
"distance",
"for",
"the",
"specific",
"entry",
"(",
"from",
"-",
">",
";",
"to",
")",
"in",
"meter",
"."
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/client-hc/src/main/java/com/graphhopper/api/MatrixResponse.java#L117-L128 |
mailin-api/sendinblue-java-mvn | src/main/java/com/sendinblue/Sendinblue.java | Sendinblue.create_child_account | public String create_child_account(Object data) {
Gson gson = new Gson();
String json = gson.toJson(data);
return post("account", json);
} | java | public String create_child_account(Object data) {
Gson gson = new Gson();
String json = gson.toJson(data);
return post("account", json);
} | [
"public",
"String",
"create_child_account",
"(",
"Object",
"data",
")",
"{",
"Gson",
"gson",
"=",
"new",
"Gson",
"(",
")",
";",
"String",
"json",
"=",
"gson",
".",
"toJson",
"(",
"data",
")",
";",
"return",
"post",
"(",
"\"account\"",
",",
"json",
")",... | /*
Create Child Account.
@param {Object} data contains json objects as a key value pair from HashMap.
@options data {String} child_email: Email address of Reseller child [Mandatory]
@options data {String} password: Password of Reseller child to login [Mandatory]
@options data {String} company_org: Name of Reseller child’s company [Mandatory]
@options data {String} first_name: First name of Reseller child [Mandatory]
@options data {String} last_name: Last name of Reseller child [Mandatory]
@options data {Array} credits: Number of email & sms credits respectively, which will be assigned to the Reseller child’s account [Optional]
- email_credit {Integer} number of email credits
- sms_credit {Integer} Number of sms credts
@options data {Array} associate_ip: Associate dedicated IPs to reseller child. You can use commas to separate multiple IPs [Optional] | [
"/",
"*",
"Create",
"Child",
"Account",
"."
] | train | https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L195-L199 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.Struct | public JBBPDslBuilder Struct(final String name) {
final Item item = new Item(BinType.STRUCT, name, this.byteOrder);
this.addItem(item);
this.openedStructCounter++;
return this;
} | java | public JBBPDslBuilder Struct(final String name) {
final Item item = new Item(BinType.STRUCT, name, this.byteOrder);
this.addItem(item);
this.openedStructCounter++;
return this;
} | [
"public",
"JBBPDslBuilder",
"Struct",
"(",
"final",
"String",
"name",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"STRUCT",
",",
"name",
",",
"this",
".",
"byteOrder",
")",
";",
"this",
".",
"addItem",
"(",
"item",
")",
... | Create new named struct.
@param name name of structure, it can be null for anonymous one
@return the builder instance, must not be null | [
"Create",
"new",
"named",
"struct",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L332-L337 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getExplicitListAsync | public Observable<List<ExplicitListItem>> getExplicitListAsync(UUID appId, String versionId, UUID entityId) {
return getExplicitListWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<List<ExplicitListItem>>, List<ExplicitListItem>>() {
@Override
public List<ExplicitListItem> call(ServiceResponse<List<ExplicitListItem>> response) {
return response.body();
}
});
} | java | public Observable<List<ExplicitListItem>> getExplicitListAsync(UUID appId, String versionId, UUID entityId) {
return getExplicitListWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<List<ExplicitListItem>>, List<ExplicitListItem>>() {
@Override
public List<ExplicitListItem> call(ServiceResponse<List<ExplicitListItem>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"ExplicitListItem",
">",
">",
"getExplicitListAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
")",
"{",
"return",
"getExplicitListWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
... | Get the explicit list of the pattern.any entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId The Pattern.Any entity id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ExplicitListItem> object | [
"Get",
"the",
"explicit",
"list",
"of",
"the",
"pattern",
".",
"any",
"entity",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L9926-L9933 |
opsmatters/newrelic-api | src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java | HttpContext.applyQueryParams | private WebTarget applyQueryParams(WebTarget target, List<String> queryParams)
{
if(queryParams != null)
{
for(int i = 0; i < queryParams.size(); i += 2)
{
target = target.queryParam(queryParams.get(i), queryParams.get(i+1));
}
}
return target;
} | java | private WebTarget applyQueryParams(WebTarget target, List<String> queryParams)
{
if(queryParams != null)
{
for(int i = 0; i < queryParams.size(); i += 2)
{
target = target.queryParam(queryParams.get(i), queryParams.get(i+1));
}
}
return target;
} | [
"private",
"WebTarget",
"applyQueryParams",
"(",
"WebTarget",
"target",
",",
"List",
"<",
"String",
">",
"queryParams",
")",
"{",
"if",
"(",
"queryParams",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"queryParams",
".",
"si... | Add the given set of query parameters to the web target.
@param target The web target to add the parameters to
@param queryParams The query parameters to add
@return The updated target | [
"Add",
"the",
"given",
"set",
"of",
"query",
"parameters",
"to",
"the",
"web",
"target",
"."
] | train | https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L590-L601 |
ag-gipp/MathMLTools | mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/distances/Distances.java | Distances.computeEarthMoverAbsoluteDistance | public static double computeEarthMoverAbsoluteDistance(Map<String, Double> h1, Map<String, Double> h2) {
Signature s1 = EarthMoverDistanceWrapper.histogramToSignature(h1);
Signature s2 = EarthMoverDistanceWrapper.histogramToSignature(h2);
return JFastEMD.distance(s1, s2, 0.0);
} | java | public static double computeEarthMoverAbsoluteDistance(Map<String, Double> h1, Map<String, Double> h2) {
Signature s1 = EarthMoverDistanceWrapper.histogramToSignature(h1);
Signature s2 = EarthMoverDistanceWrapper.histogramToSignature(h2);
return JFastEMD.distance(s1, s2, 0.0);
} | [
"public",
"static",
"double",
"computeEarthMoverAbsoluteDistance",
"(",
"Map",
"<",
"String",
",",
"Double",
">",
"h1",
",",
"Map",
"<",
"String",
",",
"Double",
">",
"h2",
")",
"{",
"Signature",
"s1",
"=",
"EarthMoverDistanceWrapper",
".",
"histogramToSignature... | probably only makes sense to compute this on CI
@param h1
@param h2
@return | [
"probably",
"only",
"makes",
"sense",
"to",
"compute",
"this",
"on",
"CI"
] | train | https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/distances/Distances.java#L36-L41 |
loadimpact/loadimpact-sdk-java | src/main/java/com/loadimpact/ApiTokenClient.java | ApiTokenClient.deleteDataStore | public void deleteDataStore(final int id) {
invoke(DATA_STORES, id,
new RequestClosure<JsonStructure>() {
@Override
public JsonStructure call(Invocation.Builder request) {
Response response = request.delete();
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new ResponseParseException(DATA_STORES, id, null, null);
}
return null;
}
},
null
);
} | java | public void deleteDataStore(final int id) {
invoke(DATA_STORES, id,
new RequestClosure<JsonStructure>() {
@Override
public JsonStructure call(Invocation.Builder request) {
Response response = request.delete();
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new ResponseParseException(DATA_STORES, id, null, null);
}
return null;
}
},
null
);
} | [
"public",
"void",
"deleteDataStore",
"(",
"final",
"int",
"id",
")",
"{",
"invoke",
"(",
"DATA_STORES",
",",
"id",
",",
"new",
"RequestClosure",
"<",
"JsonStructure",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"JsonStructure",
"call",
"(",
"Invocation",
... | Deletes a data store.
@param id its id
@throws com.loadimpact.exception.ResponseParseException if it was unsuccessful | [
"Deletes",
"a",
"data",
"store",
"."
] | train | https://github.com/loadimpact/loadimpact-sdk-java/blob/49af80b768c5453266414108b0d30a0fc01b8cef/src/main/java/com/loadimpact/ApiTokenClient.java#L762-L776 |
lukas-krecan/JsonUnit | json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java | JsonUtils.convertToJson | public static Node convertToJson(Object source, String label, boolean lenient) {
if (source instanceof JsonSource) {
return converter.convertToNode(((JsonSource) source).getJson(), label, lenient);
} else {
return converter.convertToNode(source, label, lenient);
}
} | java | public static Node convertToJson(Object source, String label, boolean lenient) {
if (source instanceof JsonSource) {
return converter.convertToNode(((JsonSource) source).getJson(), label, lenient);
} else {
return converter.convertToNode(source, label, lenient);
}
} | [
"public",
"static",
"Node",
"convertToJson",
"(",
"Object",
"source",
",",
"String",
"label",
",",
"boolean",
"lenient",
")",
"{",
"if",
"(",
"source",
"instanceof",
"JsonSource",
")",
"{",
"return",
"converter",
".",
"convertToNode",
"(",
"(",
"(",
"JsonSou... | Converts object to JSON.
@param source
@param label label to be logged in case of error.
@param lenient lenient parser used for expected values. Allows unquoted keys.
@return | [
"Converts",
"object",
"to",
"JSON",
"."
] | train | https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/internal/JsonUtils.java#L52-L58 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/font/effects/EffectUtil.java | EffectUtil.fromString | static public Color fromString (String rgb) {
if (rgb == null || rgb.length() != 6) return Color.white;
return new Color(Integer.parseInt(rgb.substring(0, 2), 16), Integer.parseInt(rgb.substring(2, 4), 16), Integer.parseInt(rgb
.substring(4, 6), 16));
} | java | static public Color fromString (String rgb) {
if (rgb == null || rgb.length() != 6) return Color.white;
return new Color(Integer.parseInt(rgb.substring(0, 2), 16), Integer.parseInt(rgb.substring(2, 4), 16), Integer.parseInt(rgb
.substring(4, 6), 16));
} | [
"static",
"public",
"Color",
"fromString",
"(",
"String",
"rgb",
")",
"{",
"if",
"(",
"rgb",
"==",
"null",
"||",
"rgb",
".",
"length",
"(",
")",
"!=",
"6",
")",
"return",
"Color",
".",
"white",
";",
"return",
"new",
"Color",
"(",
"Integer",
".",
"p... | Converts a string to a color.
@param rgb The string encoding the colour
@return The colour represented by the given encoded string | [
"Converts",
"a",
"string",
"to",
"a",
"color",
"."
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/font/effects/EffectUtil.java#L211-L215 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/styles/GeopaparazziDatabaseProperties.java | GeopaparazziDatabaseProperties.updateStyle | public static void updateStyle( ASpatialDb database, Style style ) throws Exception {
StringBuilder sbIn = new StringBuilder();
sbIn.append("update ").append(PROPERTIESTABLE);
sbIn.append(" set ");
// sbIn.append(NAME).append("='").append(style.name).append("' , ");
sbIn.append(SIZE).append("=?,");
sbIn.append(FILLCOLOR).append("=?,");
sbIn.append(STROKECOLOR).append("=?,");
sbIn.append(FILLALPHA).append("=?,");
sbIn.append(STROKEALPHA).append("=?,");
sbIn.append(SHAPE).append("=?,");
sbIn.append(WIDTH).append("=?,");
sbIn.append(LABELSIZE).append("=?,");
sbIn.append(LABELFIELD).append("=?,");
sbIn.append(LABELVISIBLE).append("=?,");
sbIn.append(ENABLED).append("=?,");
sbIn.append(ORDER).append("=?,");
sbIn.append(DASH).append("=?,");
sbIn.append(MINZOOM).append("=?,");
sbIn.append(MAXZOOM).append("=?,");
sbIn.append(DECIMATION).append("=?,");
sbIn.append(THEME).append("=?");
sbIn.append(" where ");
sbIn.append(NAME);
sbIn.append("='");
sbIn.append(style.name);
sbIn.append("';");
Object[] objects = {style.size, style.fillcolor, style.strokecolor, style.fillalpha, style.strokealpha, style.shape,
style.width, style.labelsize, style.labelfield, style.labelvisible, style.enabled, style.order, style.dashPattern,
style.minZoom, style.maxZoom, style.decimationFactor, style.getTheme()};
String updateQuery = sbIn.toString();
database.executeInsertUpdateDeletePreparedSql(updateQuery, objects);
} | java | public static void updateStyle( ASpatialDb database, Style style ) throws Exception {
StringBuilder sbIn = new StringBuilder();
sbIn.append("update ").append(PROPERTIESTABLE);
sbIn.append(" set ");
// sbIn.append(NAME).append("='").append(style.name).append("' , ");
sbIn.append(SIZE).append("=?,");
sbIn.append(FILLCOLOR).append("=?,");
sbIn.append(STROKECOLOR).append("=?,");
sbIn.append(FILLALPHA).append("=?,");
sbIn.append(STROKEALPHA).append("=?,");
sbIn.append(SHAPE).append("=?,");
sbIn.append(WIDTH).append("=?,");
sbIn.append(LABELSIZE).append("=?,");
sbIn.append(LABELFIELD).append("=?,");
sbIn.append(LABELVISIBLE).append("=?,");
sbIn.append(ENABLED).append("=?,");
sbIn.append(ORDER).append("=?,");
sbIn.append(DASH).append("=?,");
sbIn.append(MINZOOM).append("=?,");
sbIn.append(MAXZOOM).append("=?,");
sbIn.append(DECIMATION).append("=?,");
sbIn.append(THEME).append("=?");
sbIn.append(" where ");
sbIn.append(NAME);
sbIn.append("='");
sbIn.append(style.name);
sbIn.append("';");
Object[] objects = {style.size, style.fillcolor, style.strokecolor, style.fillalpha, style.strokealpha, style.shape,
style.width, style.labelsize, style.labelfield, style.labelvisible, style.enabled, style.order, style.dashPattern,
style.minZoom, style.maxZoom, style.decimationFactor, style.getTheme()};
String updateQuery = sbIn.toString();
database.executeInsertUpdateDeletePreparedSql(updateQuery, objects);
} | [
"public",
"static",
"void",
"updateStyle",
"(",
"ASpatialDb",
"database",
",",
"Style",
"style",
")",
"throws",
"Exception",
"{",
"StringBuilder",
"sbIn",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sbIn",
".",
"append",
"(",
"\"update \"",
")",
".",
"appen... | Update a style definition.
@param database the db to use.
@param style the {@link Style} to set.
@throws Exception if something goes wrong. | [
"Update",
"a",
"style",
"definition",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/geopaparazzi/styles/GeopaparazziDatabaseProperties.java#L156-L190 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/uri/ContentUriChecker.java | ContentUriChecker.analyzeInternal | private <L extends UriBaseListener> void analyzeInternal(final String input, L listener) {
pathSegmentIndex = -1;
walker.walk(listener, prepareUri(input).value0);
} | java | private <L extends UriBaseListener> void analyzeInternal(final String input, L listener) {
pathSegmentIndex = -1;
walker.walk(listener, prepareUri(input).value0);
} | [
"private",
"<",
"L",
"extends",
"UriBaseListener",
">",
"void",
"analyzeInternal",
"(",
"final",
"String",
"input",
",",
"L",
"listener",
")",
"{",
"pathSegmentIndex",
"=",
"-",
"1",
";",
"walker",
".",
"walk",
"(",
"listener",
",",
"prepareUri",
"(",
"inp... | Analyze internal.
@param <L> the generic type
@param input the input
@param listener the listener | [
"Analyze",
"internal",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/uri/ContentUriChecker.java#L110-L113 |
cdk/cdk | app/depict/src/main/java/org/openscience/cdk/depict/Depiction.java | Depiction.writeTo | public final void writeTo(String fmt, File file) throws IOException {
try (FileOutputStream out = new FileOutputStream(file)) {
writeTo(fmt, out);
}
} | java | public final void writeTo(String fmt, File file) throws IOException {
try (FileOutputStream out = new FileOutputStream(file)) {
writeTo(fmt, out);
}
} | [
"public",
"final",
"void",
"writeTo",
"(",
"String",
"fmt",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"try",
"(",
"FileOutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
"{",
"writeTo",
"(",
"fmt",
",",
"out",
")",... | Write the depiction to the provided output stream.
@param fmt format
@param file output destination
@throws IOException depiction could not be written, low level IO problem
@see #listFormats() | [
"Write",
"the",
"depiction",
"to",
"the",
"provided",
"output",
"stream",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/app/depict/src/main/java/org/openscience/cdk/depict/Depiction.java#L266-L270 |
liferay/com-liferay-commerce | commerce-product-type-grouped-service/src/main/java/com/liferay/commerce/product/type/grouped/service/persistence/impl/CPDefinitionGroupedEntryPersistenceImpl.java | CPDefinitionGroupedEntryPersistenceImpl.findAll | @Override
public List<CPDefinitionGroupedEntry> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CPDefinitionGroupedEntry> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionGroupedEntry",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the cp definition grouped entries.
@return the cp definition grouped entries | [
"Returns",
"all",
"the",
"cp",
"definition",
"grouped",
"entries",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-type-grouped-service/src/main/java/com/liferay/commerce/product/type/grouped/service/persistence/impl/CPDefinitionGroupedEntryPersistenceImpl.java#L2928-L2931 |
BBN-E/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/files/FileUtils.java | FileUtils.loadStringMap | public static ImmutableMap<String, String> loadStringMap(CharSource source) throws IOException {
return loadStringMap(source, false);
} | java | public static ImmutableMap<String, String> loadStringMap(CharSource source) throws IOException {
return loadStringMap(source, false);
} | [
"public",
"static",
"ImmutableMap",
"<",
"String",
",",
"String",
">",
"loadStringMap",
"(",
"CharSource",
"source",
")",
"throws",
"IOException",
"{",
"return",
"loadStringMap",
"(",
"source",
",",
"false",
")",
";",
"}"
] | Loads a file in the format {@code key value1} (tab-separated) into a {@link
com.google.common.collect.ImmutableMap} of {@link String}s. Each key should only appear on one
line, and there should be no duplicate values. Each key and value has whitespace trimmed off.
Skips empty lines and allows comment-lines with {@code #} in the first position. | [
"Loads",
"a",
"file",
"in",
"the",
"format",
"{"
] | train | https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/files/FileUtils.java#L676-L678 |
upwork/java-upwork | src/com/Upwork/api/Routers/Reports/Finance/Billings.java | Billings.getByFreelancersTeam | public JSONObject getByFreelancersTeam(String freelancerTeamReference, HashMap<String, String> params) throws JSONException {
return oClient.get("/finreports/v2/provider_teams/" + freelancerTeamReference + "/billings", params);
} | java | public JSONObject getByFreelancersTeam(String freelancerTeamReference, HashMap<String, String> params) throws JSONException {
return oClient.get("/finreports/v2/provider_teams/" + freelancerTeamReference + "/billings", params);
} | [
"public",
"JSONObject",
"getByFreelancersTeam",
"(",
"String",
"freelancerTeamReference",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"JSONException",
"{",
"return",
"oClient",
".",
"get",
"(",
"\"/finreports/v2/provider_teams/\"",
"+",... | Generate Billing Reports for a Specific Freelancer's Team
@param freelancerTeamReference Freelancer's team reference
@param params Parameters
@throws JSONException If error occurred
@return {@link JSONObject} | [
"Generate",
"Billing",
"Reports",
"for",
"a",
"Specific",
"Freelancer",
"s",
"Team"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/Routers/Reports/Finance/Billings.java#L66-L68 |
upwork/java-upwork | src/com/Upwork/api/Routers/Snapshot.java | Snapshot.deleteByContract | public JSONObject deleteByContract(String contractId, String ts) throws JSONException {
return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts);
} | java | public JSONObject deleteByContract(String contractId, String ts) throws JSONException {
return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts);
} | [
"public",
"JSONObject",
"deleteByContract",
"(",
"String",
"contractId",
",",
"String",
"ts",
")",
"throws",
"JSONException",
"{",
"return",
"oClient",
".",
"delete",
"(",
"\"/team/v3/snapshots/contracts/\"",
"+",
"contractId",
"+",
"\"/\"",
"+",
"ts",
")",
";",
... | Delete snapshot by specific contract
@param contractId Contract ID
@param ts Timestamp
@throws JSONException If error occurred
@return {@link JSONObject} | [
"Delete",
"snapshot",
"by",
"specific",
"contract"
] | train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/Routers/Snapshot.java#L79-L81 |
UrielCh/ovh-java-sdk | ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java | ApiOvhSms.serviceName_task_taskId_GET | public net.minidev.ovh.api.sms.OvhTask serviceName_task_taskId_GET(String serviceName, Long taskId) throws IOException {
String qPath = "/sms/{serviceName}/task/{taskId}";
StringBuilder sb = path(qPath, serviceName, taskId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, net.minidev.ovh.api.sms.OvhTask.class);
} | java | public net.minidev.ovh.api.sms.OvhTask serviceName_task_taskId_GET(String serviceName, Long taskId) throws IOException {
String qPath = "/sms/{serviceName}/task/{taskId}";
StringBuilder sb = path(qPath, serviceName, taskId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, net.minidev.ovh.api.sms.OvhTask.class);
} | [
"public",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"sms",
".",
"OvhTask",
"serviceName_task_taskId_GET",
"(",
"String",
"serviceName",
",",
"Long",
"taskId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/sms/{serviceName}/task/{taskId}\... | Get this object properties
REST: GET /sms/{serviceName}/task/{taskId}
@param serviceName [required] The internal name of your SMS offer
@param taskId [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L1566-L1571 |
gnagy/webhejj-commons | src/main/java/hu/webhejj/commons/collections/ArrayUtils.java | ArrayUtils.addToSortedIntArray | public static int[] addToSortedIntArray(int[] a, int value) {
if(a == null || a.length == 0) {
return new int[] {value};
}
int insertionPoint = -java.util.Arrays.binarySearch(a, value) - 1;
if(insertionPoint < 0) {
throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
}
int[] array = new int[a.length + 1];
if(insertionPoint > 0) {
System.arraycopy(a, 0, array, 0, insertionPoint);
}
array[insertionPoint] = value;
if(insertionPoint < a.length) {
System.arraycopy(a, insertionPoint, array, insertionPoint + 1, array.length - insertionPoint - 1);
}
return array;
} | java | public static int[] addToSortedIntArray(int[] a, int value) {
if(a == null || a.length == 0) {
return new int[] {value};
}
int insertionPoint = -java.util.Arrays.binarySearch(a, value) - 1;
if(insertionPoint < 0) {
throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
}
int[] array = new int[a.length + 1];
if(insertionPoint > 0) {
System.arraycopy(a, 0, array, 0, insertionPoint);
}
array[insertionPoint] = value;
if(insertionPoint < a.length) {
System.arraycopy(a, insertionPoint, array, insertionPoint + 1, array.length - insertionPoint - 1);
}
return array;
} | [
"public",
"static",
"int",
"[",
"]",
"addToSortedIntArray",
"(",
"int",
"[",
"]",
"a",
",",
"int",
"value",
")",
"{",
"if",
"(",
"a",
"==",
"null",
"||",
"a",
".",
"length",
"==",
"0",
")",
"{",
"return",
"new",
"int",
"[",
"]",
"{",
"value",
"... | insert value into the sorted array a, at the index returned by java.util.Arrays.binarySearch()
@param a array to add to, may be null
@param value value to add to a
@return new sorted array with value added | [
"insert",
"value",
"into",
"the",
"sorted",
"array",
"a",
"at",
"the",
"index",
"returned",
"by",
"java",
".",
"util",
".",
"Arrays",
".",
"binarySearch",
"()"
] | train | https://github.com/gnagy/webhejj-commons/blob/270bc6f111ec5761af31d39bd38c40fd914d2eba/src/main/java/hu/webhejj/commons/collections/ArrayUtils.java#L51-L72 |
samskivert/samskivert | src/main/java/com/samskivert/util/HashIntMap.java | HashIntMap.removeImpl | protected Record<V> removeImpl (int key, boolean checkShrink)
{
int index = keyToIndex(key);
// go through the chain looking for a match
for (Record<V> prev = null, rec = _buckets[index]; rec != null; rec = rec.next) {
if (rec.key == key) {
if (prev == null) {
_buckets[index] = rec.next;
} else {
prev.next = rec.next;
}
_size--;
if (checkShrink) {
checkShrink();
}
return rec;
}
prev = rec;
}
return null;
} | java | protected Record<V> removeImpl (int key, boolean checkShrink)
{
int index = keyToIndex(key);
// go through the chain looking for a match
for (Record<V> prev = null, rec = _buckets[index]; rec != null; rec = rec.next) {
if (rec.key == key) {
if (prev == null) {
_buckets[index] = rec.next;
} else {
prev.next = rec.next;
}
_size--;
if (checkShrink) {
checkShrink();
}
return rec;
}
prev = rec;
}
return null;
} | [
"protected",
"Record",
"<",
"V",
">",
"removeImpl",
"(",
"int",
"key",
",",
"boolean",
"checkShrink",
")",
"{",
"int",
"index",
"=",
"keyToIndex",
"(",
"key",
")",
";",
"// go through the chain looking for a match",
"for",
"(",
"Record",
"<",
"V",
">",
"prev... | Remove an element with optional checking to see if we should shrink.
When this is called from our iterator, checkShrink==false to avoid booching the buckets. | [
"Remove",
"an",
"element",
"with",
"optional",
"checking",
"to",
"see",
"if",
"we",
"should",
"shrink",
".",
"When",
"this",
"is",
"called",
"from",
"our",
"iterator",
"checkShrink",
"==",
"false",
"to",
"avoid",
"booching",
"the",
"buckets",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/HashIntMap.java#L182-L204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.