repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/convert/TimeConverter.java | TimeConverter.toObject | public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (StringUtil.isEmpty(pString))
return null;
TimeFormat format;
try {
if (pFormat == null) {
// Use system default format
format = TimeFormat.getInstance();
}
else {
// Get format from cache
format = getTimeFormat(pFormat);
}
return format.parse(pString);
}
catch (RuntimeException rte) {
throw new ConversionException(rte);
}
} | java | public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (StringUtil.isEmpty(pString))
return null;
TimeFormat format;
try {
if (pFormat == null) {
// Use system default format
format = TimeFormat.getInstance();
}
else {
// Get format from cache
format = getTimeFormat(pFormat);
}
return format.parse(pString);
}
catch (RuntimeException rte) {
throw new ConversionException(rte);
}
} | [
"public",
"Object",
"toObject",
"(",
"String",
"pString",
",",
"Class",
"pType",
",",
"String",
"pFormat",
")",
"throws",
"ConversionException",
"{",
"if",
"(",
"StringUtil",
".",
"isEmpty",
"(",
"pString",
")",
")",
"return",
"null",
";",
"TimeFormat",
"for... | Converts the string to a time, using the given format for parsing.
@param pString the string to convert.
@param pType the type to convert to. PropertyConverter
implementations may choose to ignore this parameter.
@param pFormat the format used for parsing. PropertyConverter
implementations may choose to ignore this parameter. Also,
implementations that require a parser format, should provide a default
format, and allow {@code null} as the format argument.
@return the object created from the given string. May safely be typecast
to {@code com.twelvemonkeys.util.Time}
@see com.twelvemonkeys.util.Time
@see com.twelvemonkeys.util.TimeFormat
@throws ConversionException | [
"Converts",
"the",
"string",
"to",
"a",
"time",
"using",
"the",
"given",
"format",
"for",
"parsing",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/convert/TimeConverter.java#L71-L94 |
jenkinsci/jenkins | core/src/main/java/hudson/Launcher.java | Launcher.decorateByPrefix | @Nonnull
public final Launcher decorateByPrefix(final String... prefix) {
final Launcher outer = this;
return new Launcher(outer) {
@Override
public boolean isUnix() {
return outer.isUnix();
}
@Override
public Proc launch(ProcStarter starter) throws IOException {
starter.commands.addAll(0,Arrays.asList(prefix));
boolean[] masks = starter.masks;
if (masks != null) {
starter.masks = prefix(masks);
}
return outer.launch(starter);
}
@Override
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String, String> envVars) throws IOException, InterruptedException {
return outer.launchChannel(prefix(cmd),out,workDir,envVars);
}
@Override
public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
outer.kill(modelEnvVars);
}
private String[] prefix(@Nonnull String[] args) {
String[] newArgs = new String[args.length+prefix.length];
System.arraycopy(prefix,0,newArgs,0,prefix.length);
System.arraycopy(args,0,newArgs,prefix.length,args.length);
return newArgs;
}
private boolean[] prefix(@Nonnull boolean[] args) {
boolean[] newArgs = new boolean[args.length+prefix.length];
System.arraycopy(args,0,newArgs,prefix.length,args.length);
return newArgs;
}
};
} | java | @Nonnull
public final Launcher decorateByPrefix(final String... prefix) {
final Launcher outer = this;
return new Launcher(outer) {
@Override
public boolean isUnix() {
return outer.isUnix();
}
@Override
public Proc launch(ProcStarter starter) throws IOException {
starter.commands.addAll(0,Arrays.asList(prefix));
boolean[] masks = starter.masks;
if (masks != null) {
starter.masks = prefix(masks);
}
return outer.launch(starter);
}
@Override
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String, String> envVars) throws IOException, InterruptedException {
return outer.launchChannel(prefix(cmd),out,workDir,envVars);
}
@Override
public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
outer.kill(modelEnvVars);
}
private String[] prefix(@Nonnull String[] args) {
String[] newArgs = new String[args.length+prefix.length];
System.arraycopy(prefix,0,newArgs,0,prefix.length);
System.arraycopy(args,0,newArgs,prefix.length,args.length);
return newArgs;
}
private boolean[] prefix(@Nonnull boolean[] args) {
boolean[] newArgs = new boolean[args.length+prefix.length];
System.arraycopy(args,0,newArgs,prefix.length,args.length);
return newArgs;
}
};
} | [
"@",
"Nonnull",
"public",
"final",
"Launcher",
"decorateByPrefix",
"(",
"final",
"String",
"...",
"prefix",
")",
"{",
"final",
"Launcher",
"outer",
"=",
"this",
";",
"return",
"new",
"Launcher",
"(",
"outer",
")",
"{",
"@",
"Override",
"public",
"boolean",
... | Returns a decorated {@link Launcher} that puts the given set of arguments as a prefix to any commands
that it invokes.
@param prefix Prefixes to be appended
@since 1.299 | [
"Returns",
"a",
"decorated",
"{",
"@link",
"Launcher",
"}",
"that",
"puts",
"the",
"given",
"set",
"of",
"arguments",
"as",
"a",
"prefix",
"to",
"any",
"commands",
"that",
"it",
"invokes",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Launcher.java#L819-L861 |
js-lib-com/commons | src/main/java/js/util/Strings.java | Strings.removeTrailing | public static String removeTrailing(String string, char c)
{
if(string == null) {
return null;
}
final int lastCharIndex = string.length() - 1;
return string.charAt(lastCharIndex) == c ? string.substring(0, lastCharIndex) : string;
} | java | public static String removeTrailing(String string, char c)
{
if(string == null) {
return null;
}
final int lastCharIndex = string.length() - 1;
return string.charAt(lastCharIndex) == c ? string.substring(0, lastCharIndex) : string;
} | [
"public",
"static",
"String",
"removeTrailing",
"(",
"String",
"string",
",",
"char",
"c",
")",
"{",
"if",
"(",
"string",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"int",
"lastCharIndex",
"=",
"string",
".",
"length",
"(",
")",
"-",
... | Remove trailing character, if exists.
@param string source string,
@param c trailing character to eliminate.
@return source string guaranteed to not end in requested character. | [
"Remove",
"trailing",
"character",
"if",
"exists",
"."
] | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Strings.java#L1328-L1335 |
naver/android-utilset | UtilSet/src/com/navercorp/utilset/ui/ScreenUtils.java | ScreenUtils.setScreenOffTimeout | public static void setScreenOffTimeout(Context context, int millis) {
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, millis);
} | java | public static void setScreenOffTimeout(Context context, int millis) {
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, millis);
} | [
"public",
"static",
"void",
"setScreenOffTimeout",
"(",
"Context",
"context",
",",
"int",
"millis",
")",
"{",
"Settings",
".",
"System",
".",
"putInt",
"(",
"context",
".",
"getContentResolver",
"(",
")",
",",
"Settings",
".",
"System",
".",
"SCREEN_OFF_TIMEOU... | @param context
@param millis Time for screen to turn off. Setting this value to -1 will prohibit screen from turning off | [
"@param",
"context",
"@param",
"millis",
"Time",
"for",
"screen",
"to",
"turn",
"off",
".",
"Setting",
"this",
"value",
"to",
"-",
"1",
"will",
"prohibit",
"screen",
"from",
"turning",
"off"
] | train | https://github.com/naver/android-utilset/blob/4af5f821466bc5bec4ea221ca6d87e0ac9b87e0b/UtilSet/src/com/navercorp/utilset/ui/ScreenUtils.java#L30-L32 |
intellimate/Izou | src/main/java/org/intellimate/izou/security/FilePermissionModule.java | FilePermissionModule.checkPermission | @Override
public void checkPermission(Permission permission, AddOnModel addon) throws IzouPermissionException {
String canonicalName = permission.getName().intern().toLowerCase();
String canonicalAction = permission.getActions().intern().toLowerCase();
if (canonicalName.contains("all files") || canonicalAction.equals("execute")) {
throw getException(permission.getName());
}
if (canonicalAction.equals("read")) {
fileReadCheck(canonicalName);
}
fileWriteCheck(canonicalName, addon);
} | java | @Override
public void checkPermission(Permission permission, AddOnModel addon) throws IzouPermissionException {
String canonicalName = permission.getName().intern().toLowerCase();
String canonicalAction = permission.getActions().intern().toLowerCase();
if (canonicalName.contains("all files") || canonicalAction.equals("execute")) {
throw getException(permission.getName());
}
if (canonicalAction.equals("read")) {
fileReadCheck(canonicalName);
}
fileWriteCheck(canonicalName, addon);
} | [
"@",
"Override",
"public",
"void",
"checkPermission",
"(",
"Permission",
"permission",
",",
"AddOnModel",
"addon",
")",
"throws",
"IzouPermissionException",
"{",
"String",
"canonicalName",
"=",
"permission",
".",
"getName",
"(",
")",
".",
"intern",
"(",
")",
"."... | Checks if the given addOn is allowed to access the requested service and registers them if not yet registered.
@param permission the Permission to check
@param addon the identifiable to check
@throws IzouPermissionException thrown if the addOn is not allowed to access its requested service | [
"Checks",
"if",
"the",
"given",
"addOn",
"is",
"allowed",
"to",
"access",
"the",
"requested",
"service",
"and",
"registers",
"them",
"if",
"not",
"yet",
"registered",
"."
] | train | https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/security/FilePermissionModule.java#L76-L88 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/websphere/servlet/filter/ChainedResponse.java | ChainedResponse.setAutoTransferringHeader | @SuppressWarnings("unchecked")
public void setAutoTransferringHeader(String name, String value)
{
Hashtable headers = getAutoTransferringHeaders();
headers.put(name, value);
// setHeader(name, value);
} | java | @SuppressWarnings("unchecked")
public void setAutoTransferringHeader(String name, String value)
{
Hashtable headers = getAutoTransferringHeaders();
headers.put(name, value);
// setHeader(name, value);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"setAutoTransferringHeader",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"Hashtable",
"headers",
"=",
"getAutoTransferringHeaders",
"(",
")",
";",
"headers",
".",
"put",
"(",
"nam... | Set a header that should be automatically transferred to all requests
in a chain. These headers will be backed up in a request attribute that
will automatically read and transferred by all ChainedResponses. This method
is useful for transparently transferring the original headers sent by the client
without forcing servlets to be specially written to transfer these headers. | [
"Set",
"a",
"header",
"that",
"should",
"be",
"automatically",
"transferred",
"to",
"all",
"requests",
"in",
"a",
"chain",
".",
"These",
"headers",
"will",
"be",
"backed",
"up",
"in",
"a",
"request",
"attribute",
"that",
"will",
"automatically",
"read",
"and... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/websphere/servlet/filter/ChainedResponse.java#L123-L129 |
raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java | ElementMatchers.takesGenericArgument | public static <T extends MethodDescription> ElementMatcher.Junction<T> takesGenericArgument(int index, Type type) {
return takesGenericArgument(index, TypeDefinition.Sort.describe(type));
} | java | public static <T extends MethodDescription> ElementMatcher.Junction<T> takesGenericArgument(int index, Type type) {
return takesGenericArgument(index, TypeDefinition.Sort.describe(type));
} | [
"public",
"static",
"<",
"T",
"extends",
"MethodDescription",
">",
"ElementMatcher",
".",
"Junction",
"<",
"T",
">",
"takesGenericArgument",
"(",
"int",
"index",
",",
"Type",
"type",
")",
"{",
"return",
"takesGenericArgument",
"(",
"index",
",",
"TypeDefinition"... | Matches {@link MethodDescription}s that define a given generic type as a parameter at the given index.
@param index The index of the parameter.
@param type The generic type the matched method is expected to define as a parameter type.
@param <T> The type of the matched object.
@return An element matcher that matches a given generic return type for a method description. | [
"Matches",
"{",
"@link",
"MethodDescription",
"}",
"s",
"that",
"define",
"a",
"given",
"generic",
"type",
"as",
"a",
"parameter",
"at",
"the",
"given",
"index",
"."
] | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java#L1158-L1160 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ProactiveDetectionConfigurationsInner.java | ProactiveDetectionConfigurationsInner.updateAsync | public Observable<ApplicationInsightsComponentProactiveDetectionConfigurationInner> updateAsync(String resourceGroupName, String resourceName, String configurationId, ApplicationInsightsComponentProactiveDetectionConfigurationInner proactiveDetectionProperties) {
return updateWithServiceResponseAsync(resourceGroupName, resourceName, configurationId, proactiveDetectionProperties).map(new Func1<ServiceResponse<ApplicationInsightsComponentProactiveDetectionConfigurationInner>, ApplicationInsightsComponentProactiveDetectionConfigurationInner>() {
@Override
public ApplicationInsightsComponentProactiveDetectionConfigurationInner call(ServiceResponse<ApplicationInsightsComponentProactiveDetectionConfigurationInner> response) {
return response.body();
}
});
} | java | public Observable<ApplicationInsightsComponentProactiveDetectionConfigurationInner> updateAsync(String resourceGroupName, String resourceName, String configurationId, ApplicationInsightsComponentProactiveDetectionConfigurationInner proactiveDetectionProperties) {
return updateWithServiceResponseAsync(resourceGroupName, resourceName, configurationId, proactiveDetectionProperties).map(new Func1<ServiceResponse<ApplicationInsightsComponentProactiveDetectionConfigurationInner>, ApplicationInsightsComponentProactiveDetectionConfigurationInner>() {
@Override
public ApplicationInsightsComponentProactiveDetectionConfigurationInner call(ServiceResponse<ApplicationInsightsComponentProactiveDetectionConfigurationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ApplicationInsightsComponentProactiveDetectionConfigurationInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
",",
"String",
"configurationId",
",",
"ApplicationInsightsComponentProactiveDetectionConfigurationI... | Update the ProactiveDetection configuration for this configuration id.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@param configurationId The ProactiveDetection configuration ID. This is unique within a Application Insights component.
@param proactiveDetectionProperties Properties that need to be specified to update the ProactiveDetection configuration.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ApplicationInsightsComponentProactiveDetectionConfigurationInner object | [
"Update",
"the",
"ProactiveDetection",
"configuration",
"for",
"this",
"configuration",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ProactiveDetectionConfigurationsInner.java#L292-L299 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrBinaryResourceRequestHandler.java | JawrBinaryResourceRequestHandler.getRealFilePath | private String getRealFilePath(String fileName, BundleHashcodeType bundleHashcodeType) {
String realFilePath = fileName;
if (bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) {
int idx = realFilePath.indexOf(JawrConstant.URL_SEPARATOR, 1);
if (idx != -1) {
realFilePath = realFilePath.substring(idx);
}
} else {
String[] resourceInfo = PathNormalizer.extractBinaryResourceInfo(realFilePath);
realFilePath = resourceInfo[0];
}
return realFilePath;
} | java | private String getRealFilePath(String fileName, BundleHashcodeType bundleHashcodeType) {
String realFilePath = fileName;
if (bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) {
int idx = realFilePath.indexOf(JawrConstant.URL_SEPARATOR, 1);
if (idx != -1) {
realFilePath = realFilePath.substring(idx);
}
} else {
String[] resourceInfo = PathNormalizer.extractBinaryResourceInfo(realFilePath);
realFilePath = resourceInfo[0];
}
return realFilePath;
} | [
"private",
"String",
"getRealFilePath",
"(",
"String",
"fileName",
",",
"BundleHashcodeType",
"bundleHashcodeType",
")",
"{",
"String",
"realFilePath",
"=",
"fileName",
";",
"if",
"(",
"bundleHashcodeType",
".",
"equals",
"(",
"BundleHashcodeType",
".",
"INVALID_HASHC... | Removes the cache buster
@param fileName
the file name
@return the file name without the cache buster. | [
"Removes",
"the",
"cache",
"buster"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrBinaryResourceRequestHandler.java#L612-L626 |
Alluxio/alluxio | core/base/src/main/java/alluxio/AlluxioURI.java | AlluxioURI.hasWindowsDrive | public static boolean hasWindowsDrive(String path, boolean slashed) {
int start = slashed ? 1 : 0;
return path.length() >= start + 2
&& (!slashed || path.charAt(0) == '/')
&& path.charAt(start + 1) == ':'
&& ((path.charAt(start) >= 'A' && path.charAt(start) <= 'Z') || (path.charAt(start) >= 'a'
&& path.charAt(start) <= 'z'));
} | java | public static boolean hasWindowsDrive(String path, boolean slashed) {
int start = slashed ? 1 : 0;
return path.length() >= start + 2
&& (!slashed || path.charAt(0) == '/')
&& path.charAt(start + 1) == ':'
&& ((path.charAt(start) >= 'A' && path.charAt(start) <= 'Z') || (path.charAt(start) >= 'a'
&& path.charAt(start) <= 'z'));
} | [
"public",
"static",
"boolean",
"hasWindowsDrive",
"(",
"String",
"path",
",",
"boolean",
"slashed",
")",
"{",
"int",
"start",
"=",
"slashed",
"?",
"1",
":",
"0",
";",
"return",
"path",
".",
"length",
"(",
")",
">=",
"start",
"+",
"2",
"&&",
"(",
"!",... | Checks if the path is a windows path. This should be platform independent.
@param path the path to check
@param slashed if the path starts with a slash
@return true if it is a windows path, false otherwise | [
"Checks",
"if",
"the",
"path",
"is",
"a",
"windows",
"path",
".",
"This",
"should",
"be",
"platform",
"independent",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/base/src/main/java/alluxio/AlluxioURI.java#L335-L342 |
google/closure-compiler | src/com/google/javascript/jscomp/CheckJSDoc.java | CheckJSDoc.validateClassLevelJsDoc | private void validateClassLevelJsDoc(Node n, JSDocInfo info) {
if (info != null && n.isMemberFunctionDef()
&& hasClassLevelJsDoc(info)) {
report(n, DISALLOWED_MEMBER_JSDOC);
}
} | java | private void validateClassLevelJsDoc(Node n, JSDocInfo info) {
if (info != null && n.isMemberFunctionDef()
&& hasClassLevelJsDoc(info)) {
report(n, DISALLOWED_MEMBER_JSDOC);
}
} | [
"private",
"void",
"validateClassLevelJsDoc",
"(",
"Node",
"n",
",",
"JSDocInfo",
"info",
")",
"{",
"if",
"(",
"info",
"!=",
"null",
"&&",
"n",
".",
"isMemberFunctionDef",
"(",
")",
"&&",
"hasClassLevelJsDoc",
"(",
"info",
")",
")",
"{",
"report",
"(",
"... | Checks that class-level annotations like @interface/@extends are not used on member functions. | [
"Checks",
"that",
"class",
"-",
"level",
"annotations",
"like"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckJSDoc.java#L310-L315 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/LicenseClient.java | LicenseClient.insertLicense | @BetaApi
public final Operation insertLicense(ProjectName project, License licenseResource) {
InsertLicenseHttpRequest request =
InsertLicenseHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setLicenseResource(licenseResource)
.build();
return insertLicense(request);
} | java | @BetaApi
public final Operation insertLicense(ProjectName project, License licenseResource) {
InsertLicenseHttpRequest request =
InsertLicenseHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setLicenseResource(licenseResource)
.build();
return insertLicense(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertLicense",
"(",
"ProjectName",
"project",
",",
"License",
"licenseResource",
")",
"{",
"InsertLicenseHttpRequest",
"request",
"=",
"InsertLicenseHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"setProject",
"(",
... | Create a License resource in the specified project.
<p>Sample code:
<pre><code>
try (LicenseClient licenseClient = LicenseClient.create()) {
ProjectName project = ProjectName.of("[PROJECT]");
License licenseResource = License.newBuilder().build();
Operation response = licenseClient.insertLicense(project, licenseResource);
}
</code></pre>
@param project Project ID for this request.
@param licenseResource A license resource.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Create",
"a",
"License",
"resource",
"in",
"the",
"specified",
"project",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/LicenseClient.java#L466-L475 |
mgormley/prim | src/main/java_generated/edu/jhu/prim/vector/IntLongDenseVector.java | IntLongDenseVector.add | public void add(IntLongVector other) {
if (other instanceof IntLongUnsortedVector) {
IntLongUnsortedVector vec = (IntLongUnsortedVector) other;
for (int i=0; i<vec.top; i++) {
this.add(vec.idx[i], vec.vals[i]);
}
} else {
// TODO: Add special case for IntLongDenseVector.
other.iterate(new SparseBinaryOpApplier(this, new Lambda.LongAdd()));
}
} | java | public void add(IntLongVector other) {
if (other instanceof IntLongUnsortedVector) {
IntLongUnsortedVector vec = (IntLongUnsortedVector) other;
for (int i=0; i<vec.top; i++) {
this.add(vec.idx[i], vec.vals[i]);
}
} else {
// TODO: Add special case for IntLongDenseVector.
other.iterate(new SparseBinaryOpApplier(this, new Lambda.LongAdd()));
}
} | [
"public",
"void",
"add",
"(",
"IntLongVector",
"other",
")",
"{",
"if",
"(",
"other",
"instanceof",
"IntLongUnsortedVector",
")",
"{",
"IntLongUnsortedVector",
"vec",
"=",
"(",
"IntLongUnsortedVector",
")",
"other",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";"... | Updates this vector to be the entrywise sum of this vector with the other. | [
"Updates",
"this",
"vector",
"to",
"be",
"the",
"entrywise",
"sum",
"of",
"this",
"vector",
"with",
"the",
"other",
"."
] | train | https://github.com/mgormley/prim/blob/5dce5e1ae94a9ae558a6262fc246e1a24f56686c/src/main/java_generated/edu/jhu/prim/vector/IntLongDenseVector.java#L143-L153 |
realexpayments/rxp-hpp-java | src/main/java/com/realexpayments/hpp/sdk/utils/JsonUtils.java | JsonUtils.toJson | public static String toJson(HppResponse hppResponse) {
try {
return hppResponseWriter.writeValueAsString(hppResponse);
} catch (JsonProcessingException ex) {
LOGGER.error("Error writing HppResponse to JSON.", ex);
throw new RealexException("Error writing HppResponse to JSON.", ex);
}
} | java | public static String toJson(HppResponse hppResponse) {
try {
return hppResponseWriter.writeValueAsString(hppResponse);
} catch (JsonProcessingException ex) {
LOGGER.error("Error writing HppResponse to JSON.", ex);
throw new RealexException("Error writing HppResponse to JSON.", ex);
}
} | [
"public",
"static",
"String",
"toJson",
"(",
"HppResponse",
"hppResponse",
")",
"{",
"try",
"{",
"return",
"hppResponseWriter",
".",
"writeValueAsString",
"(",
"hppResponse",
")",
";",
"}",
"catch",
"(",
"JsonProcessingException",
"ex",
")",
"{",
"LOGGER",
".",
... | Method serialises <code>HppResponse</code> to JSON.
@param hppResponse
@return String | [
"Method",
"serialises",
"<code",
">",
"HppResponse<",
"/",
"code",
">",
"to",
"JSON",
"."
] | train | https://github.com/realexpayments/rxp-hpp-java/blob/29cc5df036af09a6d8ea16ccd7e02e856f72620f/src/main/java/com/realexpayments/hpp/sdk/utils/JsonUtils.java#L78-L85 |
banq/jdonframework | src/main/java/com/jdon/util/jdom/XMLFilterBase.java | XMLFilterBase.setProperty | public void setProperty (String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException
{
for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
setLexicalHandler((LexicalHandler) value);
return;
}
}
super.setProperty(name, value);
} | java | public void setProperty (String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException
{
for (int i = 0; i < LEXICAL_HANDLER_NAMES.length; i++) {
if (LEXICAL_HANDLER_NAMES[i].equals(name)) {
setLexicalHandler((LexicalHandler) value);
return;
}
}
super.setProperty(name, value);
} | [
"public",
"void",
"setProperty",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"throws",
"SAXNotRecognizedException",
",",
"SAXNotSupportedException",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"LEXICAL_HANDLER_NAMES",
".",
"length",
";",
"i",... | Set the value of a property.
<p>This will always fail if the parent is null.</p>
@param name The property name.
@param state The requested property value.
@exception org.xml.sax.SAXNotRecognizedException When the
XMLReader does not recognize the property name.
@exception org.xml.sax.SAXNotSupportedException When the
XMLReader recognizes the property name but
cannot set the requested value.
@see org.xml.sax.XMLReader#setProperty | [
"Set",
"the",
"value",
"of",
"a",
"property",
"."
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/jdom/XMLFilterBase.java#L507-L517 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NodeTemplateClient.java | NodeTemplateClient.insertNodeTemplate | @BetaApi
public final Operation insertNodeTemplate(String region, NodeTemplate nodeTemplateResource) {
InsertNodeTemplateHttpRequest request =
InsertNodeTemplateHttpRequest.newBuilder()
.setRegion(region)
.setNodeTemplateResource(nodeTemplateResource)
.build();
return insertNodeTemplate(request);
} | java | @BetaApi
public final Operation insertNodeTemplate(String region, NodeTemplate nodeTemplateResource) {
InsertNodeTemplateHttpRequest request =
InsertNodeTemplateHttpRequest.newBuilder()
.setRegion(region)
.setNodeTemplateResource(nodeTemplateResource)
.build();
return insertNodeTemplate(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertNodeTemplate",
"(",
"String",
"region",
",",
"NodeTemplate",
"nodeTemplateResource",
")",
"{",
"InsertNodeTemplateHttpRequest",
"request",
"=",
"InsertNodeTemplateHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"set... | Creates a NodeTemplate resource in the specified project using the data included in the
request.
<p>Sample code:
<pre><code>
try (NodeTemplateClient nodeTemplateClient = NodeTemplateClient.create()) {
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
NodeTemplate nodeTemplateResource = NodeTemplate.newBuilder().build();
Operation response = nodeTemplateClient.insertNodeTemplate(region.toString(), nodeTemplateResource);
}
</code></pre>
@param region The name of the region for this request.
@param nodeTemplateResource A Node Template resource. To learn more about node templates and
sole-tenant nodes, read the Sole-tenant nodes documentation. (== resource_for
beta.nodeTemplates ==) (== resource_for v1.nodeTemplates ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"NodeTemplate",
"resource",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NodeTemplateClient.java#L651-L660 |
relayrides/pushy | pushy/src/main/java/com/turo/pushy/apns/ApnsClientBuilder.java | ApnsClientBuilder.setClientCredentials | public ApnsClientBuilder setClientCredentials(final X509Certificate clientCertificate, final PrivateKey privateKey, final String privateKeyPassword) {
this.clientCertificate = clientCertificate;
this.privateKey = privateKey;
this.privateKeyPassword = privateKeyPassword;
return this;
} | java | public ApnsClientBuilder setClientCredentials(final X509Certificate clientCertificate, final PrivateKey privateKey, final String privateKeyPassword) {
this.clientCertificate = clientCertificate;
this.privateKey = privateKey;
this.privateKeyPassword = privateKeyPassword;
return this;
} | [
"public",
"ApnsClientBuilder",
"setClientCredentials",
"(",
"final",
"X509Certificate",
"clientCertificate",
",",
"final",
"PrivateKey",
"privateKey",
",",
"final",
"String",
"privateKeyPassword",
")",
"{",
"this",
".",
"clientCertificate",
"=",
"clientCertificate",
";",
... | <p>Sets the TLS credentials for the client under construction. Clients constructed with TLS credentials will use
TLS-based authentication when sending push notifications.</p>
<p>Clients may not have both TLS credentials and a signing key.</p>
@param clientCertificate the certificate to be used to identify the client to the APNs server
@param privateKey the private key for the client certificate
@param privateKeyPassword the password to be used to decrypt the private key; may be {@code null} if the private
key does not require a password
@return a reference to this builder
@since 0.8 | [
"<p",
">",
"Sets",
"the",
"TLS",
"credentials",
"for",
"the",
"client",
"under",
"construction",
".",
"Clients",
"constructed",
"with",
"TLS",
"credentials",
"will",
"use",
"TLS",
"-",
"based",
"authentication",
"when",
"sending",
"push",
"notifications",
".",
... | train | https://github.com/relayrides/pushy/blob/1f6f9a0e07d785c815d74c2320a8d87c80231d36/pushy/src/main/java/com/turo/pushy/apns/ApnsClientBuilder.java#L253-L259 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/MutableDictionary.java | MutableDictionary.setDouble | @NonNull
@Override
public MutableDictionary setDouble(@NonNull String key, double value) {
return setValue(key, value);
} | java | @NonNull
@Override
public MutableDictionary setDouble(@NonNull String key, double value) {
return setValue(key, value);
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"MutableDictionary",
"setDouble",
"(",
"@",
"NonNull",
"String",
"key",
",",
"double",
"value",
")",
"{",
"return",
"setValue",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Set a double value for the given key.
@param key The key
@param value The double value.
@return The self object. | [
"Set",
"a",
"double",
"value",
"for",
"the",
"given",
"key",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableDictionary.java#L182-L186 |
netty/netty | common/src/main/java/io/netty/util/NetUtil.java | NetUtil.createByteArrayFromIpAddressString | public static byte[] createByteArrayFromIpAddressString(String ipAddressString) {
if (isValidIpV4Address(ipAddressString)) {
return validIpV4ToBytes(ipAddressString);
}
if (isValidIpV6Address(ipAddressString)) {
if (ipAddressString.charAt(0) == '[') {
ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1);
}
int percentPos = ipAddressString.indexOf('%');
if (percentPos >= 0) {
ipAddressString = ipAddressString.substring(0, percentPos);
}
return getIPv6ByName(ipAddressString, true);
}
return null;
} | java | public static byte[] createByteArrayFromIpAddressString(String ipAddressString) {
if (isValidIpV4Address(ipAddressString)) {
return validIpV4ToBytes(ipAddressString);
}
if (isValidIpV6Address(ipAddressString)) {
if (ipAddressString.charAt(0) == '[') {
ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1);
}
int percentPos = ipAddressString.indexOf('%');
if (percentPos >= 0) {
ipAddressString = ipAddressString.substring(0, percentPos);
}
return getIPv6ByName(ipAddressString, true);
}
return null;
} | [
"public",
"static",
"byte",
"[",
"]",
"createByteArrayFromIpAddressString",
"(",
"String",
"ipAddressString",
")",
"{",
"if",
"(",
"isValidIpV4Address",
"(",
"ipAddressString",
")",
")",
"{",
"return",
"validIpV4ToBytes",
"(",
"ipAddressString",
")",
";",
"}",
"if... | Creates an byte[] based on an ipAddressString. No error handling is performed here. | [
"Creates",
"an",
"byte",
"[]",
"based",
"on",
"an",
"ipAddressString",
".",
"No",
"error",
"handling",
"is",
"performed",
"here",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/NetUtil.java#L366-L385 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java | DebuggableThreadPoolExecutor.createWithFixedPoolSize | public static DebuggableThreadPoolExecutor createWithFixedPoolSize(String threadPoolName, int size)
{
return createWithMaximumPoolSize(threadPoolName, size, Integer.MAX_VALUE, TimeUnit.SECONDS);
} | java | public static DebuggableThreadPoolExecutor createWithFixedPoolSize(String threadPoolName, int size)
{
return createWithMaximumPoolSize(threadPoolName, size, Integer.MAX_VALUE, TimeUnit.SECONDS);
} | [
"public",
"static",
"DebuggableThreadPoolExecutor",
"createWithFixedPoolSize",
"(",
"String",
"threadPoolName",
",",
"int",
"size",
")",
"{",
"return",
"createWithMaximumPoolSize",
"(",
"threadPoolName",
",",
"size",
",",
"Integer",
".",
"MAX_VALUE",
",",
"TimeUnit",
... | Returns a ThreadPoolExecutor with a fixed number of threads.
When all threads are actively executing tasks, new tasks are queued.
If (most) threads are expected to be idle most of the time, prefer createWithMaxSize() instead.
@param threadPoolName the name of the threads created by this executor
@param size the fixed number of threads for this executor
@return the new DebuggableThreadPoolExecutor | [
"Returns",
"a",
"ThreadPoolExecutor",
"with",
"a",
"fixed",
"number",
"of",
"threads",
".",
"When",
"all",
"threads",
"are",
"actively",
"executing",
"tasks",
"new",
"tasks",
"are",
"queued",
".",
"If",
"(",
"most",
")",
"threads",
"are",
"expected",
"to",
... | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java#L110-L113 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/util/StringUtils.java | StringUtils.printToFile | public static void printToFile(File file, String message, boolean append,
boolean printLn, String encoding) {
PrintWriter pw = null;
try {
Writer fw;
if (encoding != null) {
fw = new OutputStreamWriter(new FileOutputStream(file, append),
encoding);
} else {
fw = new FileWriter(file, append);
}
pw = new PrintWriter(fw);
if (printLn) {
pw.println(message);
} else {
pw.print(message);
}
} catch (Exception e) {
System.err.println("Exception: in printToFile " + file.getAbsolutePath());
e.printStackTrace();
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
} | java | public static void printToFile(File file, String message, boolean append,
boolean printLn, String encoding) {
PrintWriter pw = null;
try {
Writer fw;
if (encoding != null) {
fw = new OutputStreamWriter(new FileOutputStream(file, append),
encoding);
} else {
fw = new FileWriter(file, append);
}
pw = new PrintWriter(fw);
if (printLn) {
pw.println(message);
} else {
pw.print(message);
}
} catch (Exception e) {
System.err.println("Exception: in printToFile " + file.getAbsolutePath());
e.printStackTrace();
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
} | [
"public",
"static",
"void",
"printToFile",
"(",
"File",
"file",
",",
"String",
"message",
",",
"boolean",
"append",
",",
"boolean",
"printLn",
",",
"String",
"encoding",
")",
"{",
"PrintWriter",
"pw",
"=",
"null",
";",
"try",
"{",
"Writer",
"fw",
";",
"i... | Prints to a file. If the file already exists, appends if
<code>append=true</code>, and overwrites if <code>append=false</code>. | [
"Prints",
"to",
"a",
"file",
".",
"If",
"the",
"file",
"already",
"exists",
"appends",
"if",
"<code",
">",
"append",
"=",
"true<",
"/",
"code",
">",
"and",
"overwrites",
"if",
"<code",
">",
"append",
"=",
"false<",
"/",
"code",
">",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/StringUtils.java#L876-L902 |
nostra13/Android-Universal-Image-Loader | library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java | ImageLoader.displayImage | public void displayImage(String uri, ImageAware imageAware, ImageLoadingListener listener) {
displayImage(uri, imageAware, null, listener, null);
} | java | public void displayImage(String uri, ImageAware imageAware, ImageLoadingListener listener) {
displayImage(uri, imageAware, null, listener, null);
} | [
"public",
"void",
"displayImage",
"(",
"String",
"uri",
",",
"ImageAware",
"imageAware",
",",
"ImageLoadingListener",
"listener",
")",
"{",
"displayImage",
"(",
"uri",
",",
"imageAware",
",",
"null",
",",
"listener",
",",
"null",
")",
";",
"}"
] | Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />
Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration
configuration} will be used.<br />
<b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call
@param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
@param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}
which should display image
@param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on
UI thread if this method is called on UI thread.
@throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before
@throws IllegalArgumentException if passed <b>imageAware</b> is null | [
"Adds",
"display",
"image",
"task",
"to",
"execution",
"pool",
".",
"Image",
"will",
"be",
"set",
"to",
"ImageAware",
"when",
"it",
"s",
"turn",
".",
"<br",
"/",
">",
"Default",
"{",
"@linkplain",
"DisplayImageOptions",
"display",
"image",
"options",
"}",
... | train | https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java#L143-L145 |
Azure/azure-sdk-for-java | iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java | IotHubResourcesInner.getValidSkusWithServiceResponseAsync | public Observable<ServiceResponse<Page<IotHubSkuDescriptionInner>>> getValidSkusWithServiceResponseAsync(final String resourceGroupName, final String resourceName) {
return getValidSkusSinglePageAsync(resourceGroupName, resourceName)
.concatMap(new Func1<ServiceResponse<Page<IotHubSkuDescriptionInner>>, Observable<ServiceResponse<Page<IotHubSkuDescriptionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<IotHubSkuDescriptionInner>>> call(ServiceResponse<Page<IotHubSkuDescriptionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getValidSkusNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<IotHubSkuDescriptionInner>>> getValidSkusWithServiceResponseAsync(final String resourceGroupName, final String resourceName) {
return getValidSkusSinglePageAsync(resourceGroupName, resourceName)
.concatMap(new Func1<ServiceResponse<Page<IotHubSkuDescriptionInner>>, Observable<ServiceResponse<Page<IotHubSkuDescriptionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<IotHubSkuDescriptionInner>>> call(ServiceResponse<Page<IotHubSkuDescriptionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getValidSkusNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"IotHubSkuDescriptionInner",
">",
">",
">",
"getValidSkusWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"resourceName",
")",
"{",
"return",
"getValidSkusSi... | Get the list of valid SKUs for an IoT hub.
Get the list of valid SKUs for an IoT hub.
@param resourceGroupName The name of the resource group that contains the IoT hub.
@param resourceName The name of the IoT hub.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<IotHubSkuDescriptionInner> object | [
"Get",
"the",
"list",
"of",
"valid",
"SKUs",
"for",
"an",
"IoT",
"hub",
".",
"Get",
"the",
"list",
"of",
"valid",
"SKUs",
"for",
"an",
"IoT",
"hub",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L1564-L1576 |
dkmfbk/knowledgestore | ks-core/src/main/java/eu/fbk/knowledgestore/data/XPath.java | XPath.asFunctionUnique | public final <T> Function<Object, T> asFunctionUnique(final Class<T> resultClass) {
Preconditions.checkNotNull(resultClass);
return new Function<Object, T>() {
@Override
public T apply(@Nullable final Object object) {
Preconditions.checkNotNull(object);
return evalUnique(object, resultClass);
}
};
} | java | public final <T> Function<Object, T> asFunctionUnique(final Class<T> resultClass) {
Preconditions.checkNotNull(resultClass);
return new Function<Object, T>() {
@Override
public T apply(@Nullable final Object object) {
Preconditions.checkNotNull(object);
return evalUnique(object, resultClass);
}
};
} | [
"public",
"final",
"<",
"T",
">",
"Function",
"<",
"Object",
",",
"T",
">",
"asFunctionUnique",
"(",
"final",
"Class",
"<",
"T",
">",
"resultClass",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"resultClass",
")",
";",
"return",
"new",
"Function",
... | Returns a function view of this {@code XPath} expression that produces a unique {@code T}
result given an input object. If this {@code XPath} is lenient, evaluation of the function
will return null on failure, rather than throwing an {@link IllegalArgumentException}.
@param resultClass
the {@code Class} object for the expected function result
@param <T>
the type of result
@return the requested function view | [
"Returns",
"a",
"function",
"view",
"of",
"this",
"{",
"@code",
"XPath",
"}",
"expression",
"that",
"produces",
"a",
"unique",
"{",
"@code",
"T",
"}",
"result",
"given",
"an",
"input",
"object",
".",
"If",
"this",
"{",
"@code",
"XPath",
"}",
"is",
"len... | train | https://github.com/dkmfbk/knowledgestore/blob/a548101b1dd67fcf72a1ec6f838ea7539bdbbe7a/ks-core/src/main/java/eu/fbk/knowledgestore/data/XPath.java#L852-L865 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java | JdbcAccessImpl.setLockingValues | private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)
{
FieldDescriptor fields[] = cld.getLockingFields();
for (int i=0; i<fields.length; i++)
{
PersistentField field = fields[i].getPersistentField();
Object lockVal = oldLockingValues[i].getValue();
field.set(obj, lockVal);
}
} | java | private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)
{
FieldDescriptor fields[] = cld.getLockingFields();
for (int i=0; i<fields.length; i++)
{
PersistentField field = fields[i].getPersistentField();
Object lockVal = oldLockingValues[i].getValue();
field.set(obj, lockVal);
}
} | [
"private",
"void",
"setLockingValues",
"(",
"ClassDescriptor",
"cld",
",",
"Object",
"obj",
",",
"ValueContainer",
"[",
"]",
"oldLockingValues",
")",
"{",
"FieldDescriptor",
"fields",
"[",
"]",
"=",
"cld",
".",
"getLockingFields",
"(",
")",
";",
"for",
"(",
... | Set the locking values
@param cld
@param obj
@param oldLockingValues | [
"Set",
"the",
"locking",
"values"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java#L625-L636 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagImage.java | CmsJspTagImage.imageTagAction | public static String imageTagAction(
String src,
CmsImageScaler scaler,
Map<String, String> attributes,
boolean partialTag,
ServletRequest req)
throws CmsException {
return imageTagAction(src, scaler, attributes, partialTag, false, req);
} | java | public static String imageTagAction(
String src,
CmsImageScaler scaler,
Map<String, String> attributes,
boolean partialTag,
ServletRequest req)
throws CmsException {
return imageTagAction(src, scaler, attributes, partialTag, false, req);
} | [
"public",
"static",
"String",
"imageTagAction",
"(",
"String",
"src",
",",
"CmsImageScaler",
"scaler",
",",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
",",
"boolean",
"partialTag",
",",
"ServletRequest",
"req",
")",
"throws",
"CmsException",
"{",
... | Internal action method to create the tag content.<p>
@param src the image source
@param scaler the image scaleing parameters
@param attributes the additional image HTML attributes
@param partialTag if <code>true</code>, the opening <code><img</code> and closing <code> /></code> is omitted
@param req the current request
@return the created <img src> tag content
@throws CmsException in case something goes wrong | [
"Internal",
"action",
"method",
"to",
"create",
"the",
"tag",
"content",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagImage.java#L288-L297 |
tommyettinger/RegExodus | src/main/java/regexodus/CharacterClass.java | CharacterClass.makeDigit | static void makeDigit(Term term, boolean inverse, boolean unicode) {
BlockSet digit = unicode ? inverse ? UNONDIGIT : UDIGIT :
inverse ? NONDIGIT : DIGIT;
BlockSet.unify(digit, term);
} | java | static void makeDigit(Term term, boolean inverse, boolean unicode) {
BlockSet digit = unicode ? inverse ? UNONDIGIT : UDIGIT :
inverse ? NONDIGIT : DIGIT;
BlockSet.unify(digit, term);
} | [
"static",
"void",
"makeDigit",
"(",
"Term",
"term",
",",
"boolean",
"inverse",
",",
"boolean",
"unicode",
")",
"{",
"BlockSet",
"digit",
"=",
"unicode",
"?",
"inverse",
"?",
"UNONDIGIT",
":",
"UDIGIT",
":",
"inverse",
"?",
"NONDIGIT",
":",
"DIGIT",
";",
... | /*
static void makeICase(Term term, char c) {
BlockSet bs = new BlockSet();
bs.setChar(Character.toLowerCase(c));
bs.setChar(Character.toUpperCase(c));
bs.setChar(Character.toTitleCase(c));
bs.setChar(Category.caseFold(c));
BlockSet.unify(bs, term);
} | [
"/",
"*",
"static",
"void",
"makeICase",
"(",
"Term",
"term",
"char",
"c",
")",
"{",
"BlockSet",
"bs",
"=",
"new",
"BlockSet",
"()",
";"
] | train | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/CharacterClass.java#L281-L285 |
killbill/killbill | util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java | InternalCallContextFactory.createInternalCallContext | public InternalCallContext createInternalCallContext(final UUID accountId, final CallContext context) {
return createInternalCallContext(accountId, ObjectType.ACCOUNT, context);
} | java | public InternalCallContext createInternalCallContext(final UUID accountId, final CallContext context) {
return createInternalCallContext(accountId, ObjectType.ACCOUNT, context);
} | [
"public",
"InternalCallContext",
"createInternalCallContext",
"(",
"final",
"UUID",
"accountId",
",",
"final",
"CallContext",
"context",
")",
"{",
"return",
"createInternalCallContext",
"(",
"accountId",
",",
"ObjectType",
".",
"ACCOUNT",
",",
"context",
")",
";",
"... | Create an internal call callcontext using an existing account to retrieve tenant and account record ids
<p/>
This is used for r/w operations - we need the account id to populate the account_record_id field
@param accountId account id
@param context original call callcontext
@return internal call callcontext | [
"Create",
"an",
"internal",
"call",
"callcontext",
"using",
"an",
"existing",
"account",
"to",
"retrieve",
"tenant",
"and",
"account",
"record",
"ids",
"<p",
"/",
">",
"This",
"is",
"used",
"for",
"r",
"/",
"w",
"operations",
"-",
"we",
"need",
"the",
"a... | train | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L182-L184 |
jenetics/jpx | jpx/src/main/java/io/jenetics/jpx/Speed.java | Speed.of | public static Speed of(final double speed, final Unit unit) {
requireNonNull(unit);
return new Speed(Unit.METERS_PER_SECOND.convert(speed, unit));
} | java | public static Speed of(final double speed, final Unit unit) {
requireNonNull(unit);
return new Speed(Unit.METERS_PER_SECOND.convert(speed, unit));
} | [
"public",
"static",
"Speed",
"of",
"(",
"final",
"double",
"speed",
",",
"final",
"Unit",
"unit",
")",
"{",
"requireNonNull",
"(",
"unit",
")",
";",
"return",
"new",
"Speed",
"(",
"Unit",
".",
"METERS_PER_SECOND",
".",
"convert",
"(",
"speed",
",",
"unit... | Create a new GPS {@code Speed} object.
@param speed the GPS speed value
@param unit the speed unit
@return a new GPS {@code Speed} object
@throws NullPointerException if the given speed {@code unit} is
{@code null} | [
"Create",
"a",
"new",
"GPS",
"{",
"@code",
"Speed",
"}",
"object",
"."
] | train | https://github.com/jenetics/jpx/blob/58fefc10580602d07f1480d6a5886d13a553ff8f/jpx/src/main/java/io/jenetics/jpx/Speed.java#L192-L195 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions.java | EscapedFunctions.sqlsubstring | public static String sqlsubstring(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() == 2) {
return "substr(" + parsedArgs.get(0) + "," + parsedArgs.get(1) + ")";
} else if (parsedArgs.size() == 3) {
return "substr(" + parsedArgs.get(0) + "," + parsedArgs.get(1) + "," + parsedArgs.get(2)
+ ")";
} else {
throw new PSQLException(GT.tr("{0} function takes two or three arguments.", "substring"),
PSQLState.SYNTAX_ERROR);
}
} | java | public static String sqlsubstring(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() == 2) {
return "substr(" + parsedArgs.get(0) + "," + parsedArgs.get(1) + ")";
} else if (parsedArgs.size() == 3) {
return "substr(" + parsedArgs.get(0) + "," + parsedArgs.get(1) + "," + parsedArgs.get(2)
+ ")";
} else {
throw new PSQLException(GT.tr("{0} function takes two or three arguments.", "substring"),
PSQLState.SYNTAX_ERROR);
}
} | [
"public",
"static",
"String",
"sqlsubstring",
"(",
"List",
"<",
"?",
">",
"parsedArgs",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"parsedArgs",
".",
"size",
"(",
")",
"==",
"2",
")",
"{",
"return",
"\"substr(\"",
"+",
"parsedArgs",
".",
"get",
"(",
... | substring to substr translation.
@param parsedArgs arguments
@return sql call
@throws SQLException if something wrong happens | [
"substring",
"to",
"substr",
"translation",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions.java#L377-L387 |
jankotek/mapdb | src/main/java/org/mapdb/io/DataIO.java | DataIO.packLong | static public void packLong(DataOutput out, long value) throws IOException {
//$DELAY$
int shift = 63-Long.numberOfLeadingZeros(value);
shift -= shift%7; // round down to nearest multiple of 7
while(shift!=0){
out.writeByte((byte) ((value>>>shift) & 0x7F) );
//$DELAY$
shift-=7;
}
out.writeByte((byte) ((value & 0x7F)|0x80));
} | java | static public void packLong(DataOutput out, long value) throws IOException {
//$DELAY$
int shift = 63-Long.numberOfLeadingZeros(value);
shift -= shift%7; // round down to nearest multiple of 7
while(shift!=0){
out.writeByte((byte) ((value>>>shift) & 0x7F) );
//$DELAY$
shift-=7;
}
out.writeByte((byte) ((value & 0x7F)|0x80));
} | [
"static",
"public",
"void",
"packLong",
"(",
"DataOutput",
"out",
",",
"long",
"value",
")",
"throws",
"IOException",
"{",
"//$DELAY$",
"int",
"shift",
"=",
"63",
"-",
"Long",
".",
"numberOfLeadingZeros",
"(",
"value",
")",
";",
"shift",
"-=",
"shift",
"%"... | Pack long into output.
It will occupy 1-10 bytes depending on value (lower values occupy smaller space)
@param out DataOutput to put value into
@param value to be serialized, must be non-negative
@throws java.io.IOException in case of IO error | [
"Pack",
"long",
"into",
"output",
".",
"It",
"will",
"occupy",
"1",
"-",
"10",
"bytes",
"depending",
"on",
"value",
"(",
"lower",
"values",
"occupy",
"smaller",
"space",
")"
] | train | https://github.com/jankotek/mapdb/blob/dfd873b2b9cc4e299228839c100adf93a98f1903/src/main/java/org/mapdb/io/DataIO.java#L111-L121 |
sagiegurari/fax4j | src/main/java/org/fax4j/spi/process/ProcessFaxClientSpi.java | ProcessFaxClientSpi.executeProcess | protected ProcessOutput executeProcess(FaxJob faxJob,String command,FaxActionType faxActionType)
{
if(command==null)
{
this.throwUnsupportedException();
}
//update command
String updatedCommand=command;
if(this.useWindowsCommandPrefix)
{
//init buffer
StringBuilder buffer=new StringBuilder(updatedCommand.length()+this.windowsCommandPrefix.length()+1);
//update command
buffer.append(this.windowsCommandPrefix);
buffer.append(" ");
buffer.append(updatedCommand);
updatedCommand=buffer.toString();
}
//execute process
ProcessOutput processOutput=ProcessExecutorHelper.executeProcess(this,updatedCommand);
//validate output (if not valid, an exception should be thrown)
this.validateProcessOutput(processOutput,faxActionType);
//update fax job
this.updateFaxJob(faxJob,processOutput,faxActionType);
return processOutput;
} | java | protected ProcessOutput executeProcess(FaxJob faxJob,String command,FaxActionType faxActionType)
{
if(command==null)
{
this.throwUnsupportedException();
}
//update command
String updatedCommand=command;
if(this.useWindowsCommandPrefix)
{
//init buffer
StringBuilder buffer=new StringBuilder(updatedCommand.length()+this.windowsCommandPrefix.length()+1);
//update command
buffer.append(this.windowsCommandPrefix);
buffer.append(" ");
buffer.append(updatedCommand);
updatedCommand=buffer.toString();
}
//execute process
ProcessOutput processOutput=ProcessExecutorHelper.executeProcess(this,updatedCommand);
//validate output (if not valid, an exception should be thrown)
this.validateProcessOutput(processOutput,faxActionType);
//update fax job
this.updateFaxJob(faxJob,processOutput,faxActionType);
return processOutput;
} | [
"protected",
"ProcessOutput",
"executeProcess",
"(",
"FaxJob",
"faxJob",
",",
"String",
"command",
",",
"FaxActionType",
"faxActionType",
")",
"{",
"if",
"(",
"command",
"==",
"null",
")",
"{",
"this",
".",
"throwUnsupportedException",
"(",
")",
";",
"}",
"//u... | Executes the process and returns the output.
@param faxJob
The fax job object
@param command
The command to execute
@param faxActionType
The fax action type
@return The process output | [
"Executes",
"the",
"process",
"and",
"returns",
"the",
"output",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/process/ProcessFaxClientSpi.java#L467-L498 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository/src/com/ibm/ws/repository/connections/RestRepositoryConnectionProxy.java | RestRepositoryConnectionProxy.setURL | private URL setURL(URL url) throws RepositoryIllegalArgumentException {
int port = url.getPort();
if (port == -1) {
throw new RepositoryIllegalArgumentException("Bad proxy URL", new IllegalArgumentException("Proxy URL does not contain a port"));
}
String host = url.getHost();
if (host.equals("")) {
throw new RepositoryIllegalArgumentException("Bad proxy URL", new IllegalArgumentException("Proxy URL does not contain a host"));
}
return url;
} | java | private URL setURL(URL url) throws RepositoryIllegalArgumentException {
int port = url.getPort();
if (port == -1) {
throw new RepositoryIllegalArgumentException("Bad proxy URL", new IllegalArgumentException("Proxy URL does not contain a port"));
}
String host = url.getHost();
if (host.equals("")) {
throw new RepositoryIllegalArgumentException("Bad proxy URL", new IllegalArgumentException("Proxy URL does not contain a host"));
}
return url;
} | [
"private",
"URL",
"setURL",
"(",
"URL",
"url",
")",
"throws",
"RepositoryIllegalArgumentException",
"{",
"int",
"port",
"=",
"url",
".",
"getPort",
"(",
")",
";",
"if",
"(",
"port",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"RepositoryIllegalArgumentExceptio... | Rather than setting the port directly, verify that the proxy URL did contain a port
and throw an exception if it did not. This avoids problems later.
@param url
@return | [
"Rather",
"than",
"setting",
"the",
"port",
"directly",
"verify",
"that",
"the",
"proxy",
"URL",
"did",
"contain",
"a",
"port",
"and",
"throw",
"an",
"exception",
"if",
"it",
"did",
"not",
".",
"This",
"avoids",
"problems",
"later",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/connections/RestRepositoryConnectionProxy.java#L60-L70 |
centic9/commons-dost | src/main/java/org/dstadler/commons/svn/SVNCommands.java | SVNCommands.copyBranch | public static void copyBranch(String base, String branch, long revision, String baseUrl) throws IOException {
log.info("Copying branch " + base + AT_REVISION + revision + " to branch " + branch);
CommandLine cmdLine = new CommandLine(SVN_CMD);
cmdLine.addArgument("cp");
addDefaultArguments(cmdLine, null, null);
if (revision > 0) {
cmdLine.addArgument("-r" + revision);
}
cmdLine.addArgument("-m");
cmdLine.addArgument("Branch automatically created from " + base + (revision > 0 ? AT_REVISION + revision : ""));
cmdLine.addArgument(baseUrl + base);
cmdLine.addArgument(baseUrl + branch);
/*
svn copy -r123 http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
*/
try (InputStream result = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) {
log.info("Svn-Copy reported:\n" + extractResult(result));
}
} | java | public static void copyBranch(String base, String branch, long revision, String baseUrl) throws IOException {
log.info("Copying branch " + base + AT_REVISION + revision + " to branch " + branch);
CommandLine cmdLine = new CommandLine(SVN_CMD);
cmdLine.addArgument("cp");
addDefaultArguments(cmdLine, null, null);
if (revision > 0) {
cmdLine.addArgument("-r" + revision);
}
cmdLine.addArgument("-m");
cmdLine.addArgument("Branch automatically created from " + base + (revision > 0 ? AT_REVISION + revision : ""));
cmdLine.addArgument(baseUrl + base);
cmdLine.addArgument(baseUrl + branch);
/*
svn copy -r123 http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
*/
try (InputStream result = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) {
log.info("Svn-Copy reported:\n" + extractResult(result));
}
} | [
"public",
"static",
"void",
"copyBranch",
"(",
"String",
"base",
",",
"String",
"branch",
",",
"long",
"revision",
",",
"String",
"baseUrl",
")",
"throws",
"IOException",
"{",
"log",
".",
"info",
"(",
"\"Copying branch \"",
"+",
"base",
"+",
"AT_REVISION",
"... | Make a branch by calling the "svn cp" operation.
@param base The source of the SVN copy operation
@param branch The name and location of the new branch
@param revision The revision to base the branch off
@param baseUrl The SVN url to connect to
@throws IOException Execution of the SVN sub-process failed or the
sub-process returned a exit value indicating a failure | [
"Make",
"a",
"branch",
"by",
"calling",
"the",
"svn",
"cp",
"operation",
"."
] | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L756-L778 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/util/ProcfsBasedProcessTree.java | ProcfsBasedProcessTree.constructProcessInfo | private static ProcessInfo constructProcessInfo(ProcessInfo pinfo,
String procfsDir) {
ProcessInfo ret = null;
// Read "procfsDir/<pid>/stat" file - typically /proc/<pid>/stat
BufferedReader in = null;
FileReader fReader = null;
try {
File pidDir = new File(procfsDir, String.valueOf(pinfo.getPid()));
fReader = new FileReader(new File(pidDir, PROCFS_STAT_FILE));
in = new BufferedReader(fReader);
} catch (FileNotFoundException f) {
// The process vanished in the interim!
LOG.debug("The process " + pinfo.getPid()
+ " may have finished in the interim.");
return ret;
}
ret = pinfo;
try {
String str = in.readLine(); // only one line
Matcher m = PROCFS_STAT_FILE_FORMAT.matcher(str);
boolean mat = m.find();
if (mat) {
// Set (name) (ppid) (pgrpId) (session) (utime) (stime) (vsize) (rss)
pinfo.updateProcessInfo(m.group(2), Integer.parseInt(m.group(3)),
Integer.parseInt(m.group(4)), Integer.parseInt(m.group(5)),
Long.parseLong(m.group(7)), Long.parseLong(m.group(8)),
Long.parseLong(m.group(10)), Long.parseLong(m.group(11)));
} else {
LOG.warn("Unexpected: procfs stat file is not in the expected format"
+ " for process with pid " + pinfo.getPid());
ret = null;
}
} catch (IOException io) {
LOG.warn("Error reading the stream " + io);
ret = null;
} finally {
// Close the streams
try {
fReader.close();
try {
in.close();
} catch (IOException i) {
LOG.warn("Error closing the stream " + in);
}
} catch (IOException i) {
LOG.warn("Error closing the stream " + fReader);
}
}
return ret;
} | java | private static ProcessInfo constructProcessInfo(ProcessInfo pinfo,
String procfsDir) {
ProcessInfo ret = null;
// Read "procfsDir/<pid>/stat" file - typically /proc/<pid>/stat
BufferedReader in = null;
FileReader fReader = null;
try {
File pidDir = new File(procfsDir, String.valueOf(pinfo.getPid()));
fReader = new FileReader(new File(pidDir, PROCFS_STAT_FILE));
in = new BufferedReader(fReader);
} catch (FileNotFoundException f) {
// The process vanished in the interim!
LOG.debug("The process " + pinfo.getPid()
+ " may have finished in the interim.");
return ret;
}
ret = pinfo;
try {
String str = in.readLine(); // only one line
Matcher m = PROCFS_STAT_FILE_FORMAT.matcher(str);
boolean mat = m.find();
if (mat) {
// Set (name) (ppid) (pgrpId) (session) (utime) (stime) (vsize) (rss)
pinfo.updateProcessInfo(m.group(2), Integer.parseInt(m.group(3)),
Integer.parseInt(m.group(4)), Integer.parseInt(m.group(5)),
Long.parseLong(m.group(7)), Long.parseLong(m.group(8)),
Long.parseLong(m.group(10)), Long.parseLong(m.group(11)));
} else {
LOG.warn("Unexpected: procfs stat file is not in the expected format"
+ " for process with pid " + pinfo.getPid());
ret = null;
}
} catch (IOException io) {
LOG.warn("Error reading the stream " + io);
ret = null;
} finally {
// Close the streams
try {
fReader.close();
try {
in.close();
} catch (IOException i) {
LOG.warn("Error closing the stream " + in);
}
} catch (IOException i) {
LOG.warn("Error closing the stream " + fReader);
}
}
return ret;
} | [
"private",
"static",
"ProcessInfo",
"constructProcessInfo",
"(",
"ProcessInfo",
"pinfo",
",",
"String",
"procfsDir",
")",
"{",
"ProcessInfo",
"ret",
"=",
"null",
";",
"// Read \"procfsDir/<pid>/stat\" file - typically /proc/<pid>/stat",
"BufferedReader",
"in",
"=",
"null",
... | Construct the ProcessInfo using the process' PID and procfs rooted at the
specified directory and return the same. It is provided mainly to assist
testing purposes.
Returns null on failing to read from procfs,
@param pinfo ProcessInfo that needs to be updated
@param procfsDir root of the proc file system
@return updated ProcessInfo, null on errors. | [
"Construct",
"the",
"ProcessInfo",
"using",
"the",
"process",
"PID",
"and",
"procfs",
"rooted",
"at",
"the",
"specified",
"directory",
"and",
"return",
"the",
"same",
".",
"It",
"is",
"provided",
"mainly",
"to",
"assist",
"testing",
"purposes",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/ProcfsBasedProcessTree.java#L540-L591 |
Impetus/Kundera | src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java | ESQuery.buildAggregation | public AggregationBuilder buildAggregation(KunderaQuery query, EntityMetadata entityMetadata, QueryBuilder filter)
{
SelectStatement selectStatement = query.getSelectStatement();
// To apply filter for where clause
AggregationBuilder aggregationBuilder = buildWhereAggregations(entityMetadata, filter);
if (KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
{
TermsBuilder termsBuilder = processGroupByClause(selectStatement.getGroupByClause(), entityMetadata, query);
aggregationBuilder.subAggregation(termsBuilder);
}
else
{
if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
{
logger.error("Identified having clause without group by, Throwing not supported operation Exception");
throw new UnsupportedOperationException(
"Currently, Having clause without group by caluse is not supported.");
}
else
{
aggregationBuilder = (selectStatement != null) ? query.isAggregated() ? buildSelectAggregations(
aggregationBuilder, selectStatement, entityMetadata) : null : null;
}
}
return aggregationBuilder;
} | java | public AggregationBuilder buildAggregation(KunderaQuery query, EntityMetadata entityMetadata, QueryBuilder filter)
{
SelectStatement selectStatement = query.getSelectStatement();
// To apply filter for where clause
AggregationBuilder aggregationBuilder = buildWhereAggregations(entityMetadata, filter);
if (KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
{
TermsBuilder termsBuilder = processGroupByClause(selectStatement.getGroupByClause(), entityMetadata, query);
aggregationBuilder.subAggregation(termsBuilder);
}
else
{
if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
{
logger.error("Identified having clause without group by, Throwing not supported operation Exception");
throw new UnsupportedOperationException(
"Currently, Having clause without group by caluse is not supported.");
}
else
{
aggregationBuilder = (selectStatement != null) ? query.isAggregated() ? buildSelectAggregations(
aggregationBuilder, selectStatement, entityMetadata) : null : null;
}
}
return aggregationBuilder;
} | [
"public",
"AggregationBuilder",
"buildAggregation",
"(",
"KunderaQuery",
"query",
",",
"EntityMetadata",
"entityMetadata",
",",
"QueryBuilder",
"filter",
")",
"{",
"SelectStatement",
"selectStatement",
"=",
"query",
".",
"getSelectStatement",
"(",
")",
";",
"// To apply... | Use aggregation.
@param query
the query
@param entityMetadata
the entity metadata
@param filter
the filter
@return the filter aggregation builder | [
"Use",
"aggregation",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java#L218-L245 |
openbase/jul | processing/xml/src/main/java/org/openbase/jul/processing/xml/processing/XMLProcessor.java | XMLProcessor.extractAttributeValue | public static String extractAttributeValue(final String attrName, final Node doc, final boolean throwException) throws XMLParsingException {
String xpath = "descendant-or-self::*/@" + attrName;
Nodes nodes = doc.query(xpath);
for (int i = 0; i < nodes.size(); i++) {
if (nodes.get(i) instanceof Attribute) {
return nodes.get(i).getValue();
}
}
if (throwException) {
throw new XMLParsingException("No Attribute " + attrName + " in document:\n" + doc.toXML());
} else {
return null;
}
} | java | public static String extractAttributeValue(final String attrName, final Node doc, final boolean throwException) throws XMLParsingException {
String xpath = "descendant-or-self::*/@" + attrName;
Nodes nodes = doc.query(xpath);
for (int i = 0; i < nodes.size(); i++) {
if (nodes.get(i) instanceof Attribute) {
return nodes.get(i).getValue();
}
}
if (throwException) {
throw new XMLParsingException("No Attribute " + attrName + " in document:\n" + doc.toXML());
} else {
return null;
}
} | [
"public",
"static",
"String",
"extractAttributeValue",
"(",
"final",
"String",
"attrName",
",",
"final",
"Node",
"doc",
",",
"final",
"boolean",
"throwException",
")",
"throws",
"XMLParsingException",
"{",
"String",
"xpath",
"=",
"\"descendant-or-self::*/@\"",
"+",
... | <p>
Returns the first Attribute with name attrName from Document doc. Uses xPath "//
@throws XMLParsingException
@param throwException flag set throw exception if no such Attribute can be found. <br>
@param attrName
@param doc
@return | [
"<p",
">",
"Returns",
"the",
"first",
"Attribute",
"with",
"name",
"attrName",
"from",
"Document",
"doc",
".",
"Uses",
"xPath",
"//"
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/processing/xml/src/main/java/org/openbase/jul/processing/xml/processing/XMLProcessor.java#L269-L282 |
awslabs/amazon-sqs-java-extended-client-lib | src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClient.java | AmazonSQSExtendedClient.changeMessageVisibilityBatch | public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(
String queueUrl,
java.util.List<ChangeMessageVisibilityBatchRequestEntry> entries) {
ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest =
new ChangeMessageVisibilityBatchRequest(queueUrl, entries);
return changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest);
} | java | public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(
String queueUrl,
java.util.List<ChangeMessageVisibilityBatchRequestEntry> entries) {
ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest =
new ChangeMessageVisibilityBatchRequest(queueUrl, entries);
return changeMessageVisibilityBatch(changeMessageVisibilityBatchRequest);
} | [
"public",
"ChangeMessageVisibilityBatchResult",
"changeMessageVisibilityBatch",
"(",
"String",
"queueUrl",
",",
"java",
".",
"util",
".",
"List",
"<",
"ChangeMessageVisibilityBatchRequestEntry",
">",
"entries",
")",
"{",
"ChangeMessageVisibilityBatchRequest",
"changeMessageVisi... | Simplified method form for invoking the ChangeMessageVisibilityBatch
operation.
@see #changeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest) | [
"Simplified",
"method",
"form",
"for",
"invoking",
"the",
"ChangeMessageVisibilityBatch",
"operation",
"."
] | train | https://github.com/awslabs/amazon-sqs-java-extended-client-lib/blob/df0c6251b99e682d6179938fe784590e662b84ea/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClient.java#L983-L989 |
ZieIony/Carbon | carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java | ShapeAppearanceModel.setTopLeftCorner | public void setTopLeftCorner(@CornerFamily int cornerFamily, @Dimension int cornerSize) {
setTopLeftCorner(MaterialShapeUtils.createCornerTreatment(cornerFamily, cornerSize));
} | java | public void setTopLeftCorner(@CornerFamily int cornerFamily, @Dimension int cornerSize) {
setTopLeftCorner(MaterialShapeUtils.createCornerTreatment(cornerFamily, cornerSize));
} | [
"public",
"void",
"setTopLeftCorner",
"(",
"@",
"CornerFamily",
"int",
"cornerFamily",
",",
"@",
"Dimension",
"int",
"cornerSize",
")",
"{",
"setTopLeftCorner",
"(",
"MaterialShapeUtils",
".",
"createCornerTreatment",
"(",
"cornerFamily",
",",
"cornerSize",
")",
")"... | Sets the corner treatment for the top-left corner.
@param cornerFamily the family to use to create the corner treatment
@param cornerSize the size to use to create the corner treatment | [
"Sets",
"the",
"corner",
"treatment",
"for",
"the",
"top",
"-",
"left",
"corner",
"."
] | train | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShapeAppearanceModel.java#L232-L234 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/IndexReader.java | IndexReader.getBucketOffsets | @VisibleForTesting
CompletableFuture<List<Long>> getBucketOffsets(DirectSegmentAccess segment, TableBucket bucket, TimeoutTimer timer) {
val result = new ArrayList<Long>();
AtomicLong offset = new AtomicLong(bucket.getSegmentOffset());
return Futures.loop(
() -> offset.get() >= 0,
() -> {
result.add(offset.get());
return getBackpointerOffset(segment, offset.get(), timer.getRemaining());
},
offset::set,
this.executor)
.thenApply(v -> result);
} | java | @VisibleForTesting
CompletableFuture<List<Long>> getBucketOffsets(DirectSegmentAccess segment, TableBucket bucket, TimeoutTimer timer) {
val result = new ArrayList<Long>();
AtomicLong offset = new AtomicLong(bucket.getSegmentOffset());
return Futures.loop(
() -> offset.get() >= 0,
() -> {
result.add(offset.get());
return getBackpointerOffset(segment, offset.get(), timer.getRemaining());
},
offset::set,
this.executor)
.thenApply(v -> result);
} | [
"@",
"VisibleForTesting",
"CompletableFuture",
"<",
"List",
"<",
"Long",
">",
">",
"getBucketOffsets",
"(",
"DirectSegmentAccess",
"segment",
",",
"TableBucket",
"bucket",
",",
"TimeoutTimer",
"timer",
")",
"{",
"val",
"result",
"=",
"new",
"ArrayList",
"<",
"Lo... | Gets the offsets for all the Table Entries in the given {@link TableBucket}.
@param segment A {@link DirectSegmentAccess}
@param bucket The {@link TableBucket} to get offsets for.
@param timer Timer for the operation.
@return A CompletableFuture that, when completed, will contain a List of offsets, with the first offset being the
{@link TableBucket}'s offset itself, then descending down in the order of backpointers. If the {@link TableBucket}
is partial, then the list will be empty. | [
"Gets",
"the",
"offsets",
"for",
"all",
"the",
"Table",
"Entries",
"in",
"the",
"given",
"{",
"@link",
"TableBucket",
"}",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/IndexReader.java#L169-L182 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java | ClassFinder.newCompletionFailure | private CompletionFailure newCompletionFailure(TypeSymbol c,
JCDiagnostic diag) {
if (!cacheCompletionFailure) {
// log.warning("proc.messager",
// Log.getLocalizedString("class.file.not.found", c.flatname));
// c.debug.printStackTrace();
return new CompletionFailure(c, diag);
} else {
CompletionFailure result = cachedCompletionFailure;
result.sym = c;
result.diag = diag;
return result;
}
} | java | private CompletionFailure newCompletionFailure(TypeSymbol c,
JCDiagnostic diag) {
if (!cacheCompletionFailure) {
// log.warning("proc.messager",
// Log.getLocalizedString("class.file.not.found", c.flatname));
// c.debug.printStackTrace();
return new CompletionFailure(c, diag);
} else {
CompletionFailure result = cachedCompletionFailure;
result.sym = c;
result.diag = diag;
return result;
}
} | [
"private",
"CompletionFailure",
"newCompletionFailure",
"(",
"TypeSymbol",
"c",
",",
"JCDiagnostic",
"diag",
")",
"{",
"if",
"(",
"!",
"cacheCompletionFailure",
")",
"{",
"// log.warning(\"proc.messager\",",
"// Log.getLocalizedString(\"class.file.not.found\", c.flatn... | Static factory for CompletionFailure objects.
In practice, only one can be used at a time, so we share one
to reduce the expense of allocating new exception objects. | [
"Static",
"factory",
"for",
"CompletionFailure",
"objects",
".",
"In",
"practice",
"only",
"one",
"can",
"be",
"used",
"at",
"a",
"time",
"so",
"we",
"share",
"one",
"to",
"reduce",
"the",
"expense",
"of",
"allocating",
"new",
"exception",
"objects",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java#L375-L388 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataCore.java | CoverageDataCore.getValue | public Double getValue(GriddedTile griddedTile, int unsignedPixelValue) {
Double value = null;
if (!isDataNull(unsignedPixelValue)) {
value = pixelValueToValue(griddedTile, new Double(
unsignedPixelValue));
}
return value;
} | java | public Double getValue(GriddedTile griddedTile, int unsignedPixelValue) {
Double value = null;
if (!isDataNull(unsignedPixelValue)) {
value = pixelValueToValue(griddedTile, new Double(
unsignedPixelValue));
}
return value;
} | [
"public",
"Double",
"getValue",
"(",
"GriddedTile",
"griddedTile",
",",
"int",
"unsignedPixelValue",
")",
"{",
"Double",
"value",
"=",
"null",
";",
"if",
"(",
"!",
"isDataNull",
"(",
"unsignedPixelValue",
")",
")",
"{",
"value",
"=",
"pixelValueToValue",
"(",
... | Get the coverage data value for the unsigned short pixel value
@param griddedTile
gridded tile
@param unsignedPixelValue
pixel value as an unsigned 16 bit integer
@return coverage data value | [
"Get",
"the",
"coverage",
"data",
"value",
"for",
"the",
"unsigned",
"short",
"pixel",
"value"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataCore.java#L1432-L1441 |
btc-ag/redg | redg-generator/src/main/java/com/btc/redg/generator/extractor/DatabaseManager.java | DatabaseManager.crawlDatabase | public static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule) throws SchemaCrawlerException {
final SchemaCrawlerOptions options = SchemaCrawlerOptionsBuilder.builder()
.withSchemaInfoLevel(SchemaInfoLevelBuilder.standard().setRetrieveIndexes(false))
.routineTypes(Arrays.asList(RoutineType.procedure, RoutineType.unknown))
.includeSchemas(schemaRule == null ? new IncludeAll() : schemaRule)
.includeTables(tableRule == null ? new IncludeAll() : tableRule)
.toOptions();
try {
return SchemaCrawlerUtility.getCatalog(connection, options);
} catch (SchemaCrawlerException e) {
LOG.error("Schema crawling failed with exception", e);
throw e;
}
} | java | public static Catalog crawlDatabase(final Connection connection, final InclusionRule schemaRule, final InclusionRule tableRule) throws SchemaCrawlerException {
final SchemaCrawlerOptions options = SchemaCrawlerOptionsBuilder.builder()
.withSchemaInfoLevel(SchemaInfoLevelBuilder.standard().setRetrieveIndexes(false))
.routineTypes(Arrays.asList(RoutineType.procedure, RoutineType.unknown))
.includeSchemas(schemaRule == null ? new IncludeAll() : schemaRule)
.includeTables(tableRule == null ? new IncludeAll() : tableRule)
.toOptions();
try {
return SchemaCrawlerUtility.getCatalog(connection, options);
} catch (SchemaCrawlerException e) {
LOG.error("Schema crawling failed with exception", e);
throw e;
}
} | [
"public",
"static",
"Catalog",
"crawlDatabase",
"(",
"final",
"Connection",
"connection",
",",
"final",
"InclusionRule",
"schemaRule",
",",
"final",
"InclusionRule",
"tableRule",
")",
"throws",
"SchemaCrawlerException",
"{",
"final",
"SchemaCrawlerOptions",
"options",
"... | Starts the schema crawler and lets it crawl the given JDBC connection.
@param connection The JDBC connection
@param schemaRule The {@link InclusionRule} to be passed to SchemaCrawler that specifies which schemas should be analyzed
@param tableRule The {@link InclusionRule} to be passed to SchemaCrawler that specifies which tables should be analyzed. If a table is included by the
{@code tableRule} but excluded by the {@code schemaRule} it will not be analyzed.
@return The populated {@link Catalog} object containing the metadata for the extractor
@throws SchemaCrawlerException Gets thrown when the database could not be crawled successfully | [
"Starts",
"the",
"schema",
"crawler",
"and",
"lets",
"it",
"crawl",
"the",
"given",
"JDBC",
"connection",
"."
] | train | https://github.com/btc-ag/redg/blob/416a68639d002512cabfebff09afd2e1909e27df/redg-generator/src/main/java/com/btc/redg/generator/extractor/DatabaseManager.java#L146-L160 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/host_device.java | host_device.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
host_device_responses result = (host_device_responses) service.get_payload_formatter().string_to_resource(host_device_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.host_device_response_array);
}
host_device[] result_host_device = new host_device[result.host_device_response_array.length];
for(int i = 0; i < result.host_device_response_array.length; i++)
{
result_host_device[i] = result.host_device_response_array[i].host_device[0];
}
return result_host_device;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
host_device_responses result = (host_device_responses) service.get_payload_formatter().string_to_resource(host_device_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.host_device_response_array);
}
host_device[] result_host_device = new host_device[result.host_device_response_array.length];
for(int i = 0; i < result.host_device_response_array.length; i++)
{
result_host_device[i] = result.host_device_response_array[i].host_device[0];
}
return result_host_device;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"host_device_responses",
"result",
"=",
"(",
"host_device_responses",
")",
"service",
".",
"get_payload_format... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/host_device.java#L333-L350 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/Expression.java | Expression.checkTypes | static void checkTypes(ImmutableList<Type> types, Iterable<? extends Expression> exprs) {
int size = Iterables.size(exprs);
checkArgument(
size == types.size(),
"Supplied the wrong number of parameters. Expected %s, got %s",
types.size(),
size);
// checkIsAssignableTo is an no-op if DEBUG is false
if (Flags.DEBUG) {
int i = 0;
for (Expression expr : exprs) {
expr.checkAssignableTo(types.get(i), "Parameter %s", i);
i++;
}
}
} | java | static void checkTypes(ImmutableList<Type> types, Iterable<? extends Expression> exprs) {
int size = Iterables.size(exprs);
checkArgument(
size == types.size(),
"Supplied the wrong number of parameters. Expected %s, got %s",
types.size(),
size);
// checkIsAssignableTo is an no-op if DEBUG is false
if (Flags.DEBUG) {
int i = 0;
for (Expression expr : exprs) {
expr.checkAssignableTo(types.get(i), "Parameter %s", i);
i++;
}
}
} | [
"static",
"void",
"checkTypes",
"(",
"ImmutableList",
"<",
"Type",
">",
"types",
",",
"Iterable",
"<",
"?",
"extends",
"Expression",
">",
"exprs",
")",
"{",
"int",
"size",
"=",
"Iterables",
".",
"size",
"(",
"exprs",
")",
";",
"checkArgument",
"(",
"size... | Checks that the given expressions are compatible with the given types. | [
"Checks",
"that",
"the",
"given",
"expressions",
"are",
"compatible",
"with",
"the",
"given",
"types",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Expression.java#L167-L182 |
LearnLib/learnlib | algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/adt/ADT.java | ADT.replaceNode | public void replaceNode(final ADTNode<S, I, O> oldNode, final ADTNode<S, I, O> newNode) {
if (this.root.equals(oldNode)) {
this.root = newNode;
} else if (ADTUtil.isResetNode(oldNode)) {
final ADTNode<S, I, O> endOfPreviousADS = oldNode.getParent();
final O outputToReset = ADTUtil.getOutputForSuccessor(endOfPreviousADS, oldNode);
newNode.setParent(endOfPreviousADS);
endOfPreviousADS.getChildren().put(outputToReset, newNode);
} else {
final ADTNode<S, I, O> oldNodeParent = oldNode.getParent(); //reset node
assert ADTUtil.isResetNode(oldNodeParent);
final ADTNode<S, I, O> endOfPreviousADS = oldNodeParent.getParent();
final O outputToReset = ADTUtil.getOutputForSuccessor(endOfPreviousADS, oldNodeParent);
final ADTNode<S, I, O> newResetNode = new ADTResetNode<>(newNode);
newResetNode.setParent(endOfPreviousADS);
newNode.setParent(newResetNode);
endOfPreviousADS.getChildren().put(outputToReset, newResetNode);
}
} | java | public void replaceNode(final ADTNode<S, I, O> oldNode, final ADTNode<S, I, O> newNode) {
if (this.root.equals(oldNode)) {
this.root = newNode;
} else if (ADTUtil.isResetNode(oldNode)) {
final ADTNode<S, I, O> endOfPreviousADS = oldNode.getParent();
final O outputToReset = ADTUtil.getOutputForSuccessor(endOfPreviousADS, oldNode);
newNode.setParent(endOfPreviousADS);
endOfPreviousADS.getChildren().put(outputToReset, newNode);
} else {
final ADTNode<S, I, O> oldNodeParent = oldNode.getParent(); //reset node
assert ADTUtil.isResetNode(oldNodeParent);
final ADTNode<S, I, O> endOfPreviousADS = oldNodeParent.getParent();
final O outputToReset = ADTUtil.getOutputForSuccessor(endOfPreviousADS, oldNodeParent);
final ADTNode<S, I, O> newResetNode = new ADTResetNode<>(newNode);
newResetNode.setParent(endOfPreviousADS);
newNode.setParent(newResetNode);
endOfPreviousADS.getChildren().put(outputToReset, newResetNode);
}
} | [
"public",
"void",
"replaceNode",
"(",
"final",
"ADTNode",
"<",
"S",
",",
"I",
",",
"O",
">",
"oldNode",
",",
"final",
"ADTNode",
"<",
"S",
",",
"I",
",",
"O",
">",
"newNode",
")",
"{",
"if",
"(",
"this",
".",
"root",
".",
"equals",
"(",
"oldNode"... | Replaces an existing node in the tree with a new one and updates the references of parent/child nodes
accordingly.
@param oldNode
the node to replace
@param newNode
the replacement | [
"Replaces",
"an",
"existing",
"node",
"in",
"the",
"tree",
"with",
"a",
"new",
"one",
"and",
"updates",
"the",
"references",
"of",
"parent",
"/",
"child",
"nodes",
"accordingly",
"."
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/adt/ADT.java#L83-L106 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/WsLocationAdminImpl.java | WsLocationAdminImpl.createLocations | public static WsLocationAdminImpl createLocations(final Map<String, Object> initProps) {
if (instance.get() == null) {
SymbolRegistry.getRegistry().clear();
Callable<WsLocationAdminImpl> initializer = new Callable<WsLocationAdminImpl>() {
@Override
public WsLocationAdminImpl call() throws Exception {
return new WsLocationAdminImpl(initProps);
}
};
instance = StaticValue.mutateStaticValue(instance, initializer);
}
return instance.get();
} | java | public static WsLocationAdminImpl createLocations(final Map<String, Object> initProps) {
if (instance.get() == null) {
SymbolRegistry.getRegistry().clear();
Callable<WsLocationAdminImpl> initializer = new Callable<WsLocationAdminImpl>() {
@Override
public WsLocationAdminImpl call() throws Exception {
return new WsLocationAdminImpl(initProps);
}
};
instance = StaticValue.mutateStaticValue(instance, initializer);
}
return instance.get();
} | [
"public",
"static",
"WsLocationAdminImpl",
"createLocations",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"initProps",
")",
"{",
"if",
"(",
"instance",
".",
"get",
"(",
")",
"==",
"null",
")",
"{",
"SymbolRegistry",
".",
"getRegistry",
"(",
")"... | Construct the WsLocationAdminService singleton based on a set of initial
properties provided by bootstrap or other initialization code (e.g. an
initializer in a test environment).
@param initProps
@return WsLocationAdmin | [
"Construct",
"the",
"WsLocationAdminService",
"singleton",
"based",
"on",
"a",
"set",
"of",
"initial",
"properties",
"provided",
"by",
"bootstrap",
"or",
"other",
"initialization",
"code",
"(",
"e",
".",
"g",
".",
"an",
"initializer",
"in",
"a",
"test",
"envir... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/WsLocationAdminImpl.java#L81-L94 |
apache/incubator-zipkin | zipkin-storage/elasticsearch/src/main/java/zipkin2/elasticsearch/internal/JsonReaders.java | JsonReaders.enterPath | @Nullable
public static JsonReader enterPath(JsonReader reader, String path1, String path2)
throws IOException {
return enterPath(reader, path1) != null ? enterPath(reader, path2) : null;
} | java | @Nullable
public static JsonReader enterPath(JsonReader reader, String path1, String path2)
throws IOException {
return enterPath(reader, path1) != null ? enterPath(reader, path2) : null;
} | [
"@",
"Nullable",
"public",
"static",
"JsonReader",
"enterPath",
"(",
"JsonReader",
"reader",
",",
"String",
"path1",
",",
"String",
"path2",
")",
"throws",
"IOException",
"{",
"return",
"enterPath",
"(",
"reader",
",",
"path1",
")",
"!=",
"null",
"?",
"enter... | This saves you from having to define nested types to read a single value
<p>Instead of defining two types like this, and double-checking null..
<pre>{@code
class Response {
Message message;
}
class Message {
String status;
}
JsonAdapter<Response> adapter = moshi.adapter(Response.class);
Message message = adapter.fromJson(body.source());
if (message != null && message.status != null) throw new IllegalStateException(message.status);
}</pre>
<p>You can advance to the field directly.
<pre>{@code
JsonReader status = enterPath(JsonReader.of(body.source()), "message", "status");
if (status != null) throw new IllegalStateException(status.nextString());
}</pre> | [
"This",
"saves",
"you",
"from",
"having",
"to",
"define",
"nested",
"types",
"to",
"read",
"a",
"single",
"value"
] | train | https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin-storage/elasticsearch/src/main/java/zipkin2/elasticsearch/internal/JsonReaders.java#L54-L58 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/distance/Distance.java | Distance.Canberra | public static double Canberra(IntPoint p, IntPoint q) {
return Canberra(p.x, p.y, q.x, q.y);
} | java | public static double Canberra(IntPoint p, IntPoint q) {
return Canberra(p.x, p.y, q.x, q.y);
} | [
"public",
"static",
"double",
"Canberra",
"(",
"IntPoint",
"p",
",",
"IntPoint",
"q",
")",
"{",
"return",
"Canberra",
"(",
"p",
".",
"x",
",",
"p",
".",
"y",
",",
"q",
".",
"x",
",",
"q",
".",
"y",
")",
";",
"}"
] | Gets the Canberra distance between two points.
@param p IntPoint with X and Y axis coordinates.
@param q IntPoint with X and Y axis coordinates.
@return The Canberra distance between x and y. | [
"Gets",
"the",
"Canberra",
"distance",
"between",
"two",
"points",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L167-L169 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java | DateUtil.getEndValue | public static int getEndValue(Calendar calendar, int dateField) {
if(Calendar.DAY_OF_WEEK == dateField) {
return (calendar.getFirstDayOfWeek() + 6) % 7;
}
return calendar.getActualMaximum(dateField);
} | java | public static int getEndValue(Calendar calendar, int dateField) {
if(Calendar.DAY_OF_WEEK == dateField) {
return (calendar.getFirstDayOfWeek() + 6) % 7;
}
return calendar.getActualMaximum(dateField);
} | [
"public",
"static",
"int",
"getEndValue",
"(",
"Calendar",
"calendar",
",",
"int",
"dateField",
")",
"{",
"if",
"(",
"Calendar",
".",
"DAY_OF_WEEK",
"==",
"dateField",
")",
"{",
"return",
"(",
"calendar",
".",
"getFirstDayOfWeek",
"(",
")",
"+",
"6",
")",
... | 获取指定日期字段的最大值,例如分钟的最小值是59
@param calendar {@link Calendar}
@param dateField {@link DateField}
@return 字段最大值
@since 4.5.7
@see Calendar#getActualMaximum(int) | [
"获取指定日期字段的最大值,例如分钟的最小值是59"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L1696-L1701 |
lets-blade/blade | src/main/java/com/blade/kit/ReflectKit.java | ReflectKit.getMethod | public static Method getMethod(Class<?> cls, String methodName, Class<?>... types) {
try {
return cls.getMethod(methodName, types);
} catch (Exception e) {
return null;
}
} | java | public static Method getMethod(Class<?> cls, String methodName, Class<?>... types) {
try {
return cls.getMethod(methodName, types);
} catch (Exception e) {
return null;
}
} | [
"public",
"static",
"Method",
"getMethod",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"types",
")",
"{",
"try",
"{",
"return",
"cls",
".",
"getMethod",
"(",
"methodName",
",",
"types",
")",
";... | Get cls method name by name and parameter types
@param cls
@param methodName
@param types
@return | [
"Get",
"cls",
"method",
"name",
"by",
"name",
"and",
"parameter",
"types"
] | train | https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/kit/ReflectKit.java#L252-L258 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.audit.file/src/com/ibm/ws/security/audit/logutils/FileLogSet.java | FileLogSet.createNewUniqueFile | private File createNewUniqueFile(File srcFile) throws IOException {
String dateString = getDateString();
int index = findFileIndexAndUpdateCounter(dateString);
String destFileName;
File destFile;
do {
int counter = lastCounter++;
destFileName = fileName + dateString + '.' + counter + fileExtension;
destFile = new File(directory, destFileName);
boolean success;
if (srcFile == null) {
success = destFile.createNewFile();
} else {
// We don't want to rename over an existing file, so try to
// avoid doing so with a racy exists() check.
if (!destFile.exists()) {
success = srcFile.renameTo(destFile);
} else {
success = false;
}
}
if (success) {
// Add the file to our list, which will cause old files to be
// deleted if we've reached the max.
addFile(index, destFileName);
return destFile;
}
} while (destFile.isFile());
if (srcFile != null && copyFileTo(srcFile, destFile)) {
addFile(index, destFileName);
return FileLogUtils.deleteFile(srcFile) ? destFile : null;
}
Tr.error(tc, "UNABLE_TO_DELETE_RESOURCE_NOEX", new Object[] { destFile });
return null;
} | java | private File createNewUniqueFile(File srcFile) throws IOException {
String dateString = getDateString();
int index = findFileIndexAndUpdateCounter(dateString);
String destFileName;
File destFile;
do {
int counter = lastCounter++;
destFileName = fileName + dateString + '.' + counter + fileExtension;
destFile = new File(directory, destFileName);
boolean success;
if (srcFile == null) {
success = destFile.createNewFile();
} else {
// We don't want to rename over an existing file, so try to
// avoid doing so with a racy exists() check.
if (!destFile.exists()) {
success = srcFile.renameTo(destFile);
} else {
success = false;
}
}
if (success) {
// Add the file to our list, which will cause old files to be
// deleted if we've reached the max.
addFile(index, destFileName);
return destFile;
}
} while (destFile.isFile());
if (srcFile != null && copyFileTo(srcFile, destFile)) {
addFile(index, destFileName);
return FileLogUtils.deleteFile(srcFile) ? destFile : null;
}
Tr.error(tc, "UNABLE_TO_DELETE_RESOURCE_NOEX", new Object[] { destFile });
return null;
} | [
"private",
"File",
"createNewUniqueFile",
"(",
"File",
"srcFile",
")",
"throws",
"IOException",
"{",
"String",
"dateString",
"=",
"getDateString",
"(",
")",
";",
"int",
"index",
"=",
"findFileIndexAndUpdateCounter",
"(",
"dateString",
")",
";",
"String",
"destFile... | Create a new unique file name. If the source file is specified, the new
file should be created by renaming the source file as the unique file.
@param srcFile the file to rename, or null to create a new file
@return the newly created file, or null if the could not be created
@throws IOException if an unexpected I/O error occurs | [
"Create",
"a",
"new",
"unique",
"file",
"name",
".",
"If",
"the",
"source",
"file",
"is",
"specified",
"the",
"new",
"file",
"should",
"be",
"created",
"by",
"renaming",
"the",
"source",
"file",
"as",
"the",
"unique",
"file",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.audit.file/src/com/ibm/ws/security/audit/logutils/FileLogSet.java#L240-L279 |
OpenLiberty/open-liberty | dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java | RepositoryResolver.createInstallList | List<RepositoryResource> createInstallList(String featureName) {
ProvisioningFeatureDefinition feature = resolverRepository.getFeature(featureName);
if (feature == null) {
// Feature missing
missingTopLevelRequirements.add(featureName);
// If we didn't find this feature in another product, we need to record it as missing
if (!requirementsFoundForOtherProducts.contains(featureName)) {
missingRequirements.add(new MissingRequirement(featureName, null));
}
return Collections.emptyList();
}
if (!(feature instanceof KernelResolverEsa)) {
// Feature already installed
return Collections.emptyList();
}
EsaResource esa = ((KernelResolverEsa) feature).getResource();
Map<String, Integer> maxDistanceMap = new HashMap<>();
List<MissingRequirement> missingRequirements = new ArrayList<>();
boolean foundAllDependencies = populateMaxDistanceMap(maxDistanceMap, esa.getProvideFeature(), 0, new HashSet<ProvisioningFeatureDefinition>(), missingRequirements);
if (!foundAllDependencies) {
missingTopLevelRequirements.add(featureName);
this.missingRequirements.addAll(missingRequirements);
}
ArrayList<RepositoryResource> installList = new ArrayList<>();
installList.addAll(convertFeatureNamesToResources(maxDistanceMap.keySet()));
Collections.sort(installList, byMaxDistance(maxDistanceMap));
return installList;
} | java | List<RepositoryResource> createInstallList(String featureName) {
ProvisioningFeatureDefinition feature = resolverRepository.getFeature(featureName);
if (feature == null) {
// Feature missing
missingTopLevelRequirements.add(featureName);
// If we didn't find this feature in another product, we need to record it as missing
if (!requirementsFoundForOtherProducts.contains(featureName)) {
missingRequirements.add(new MissingRequirement(featureName, null));
}
return Collections.emptyList();
}
if (!(feature instanceof KernelResolverEsa)) {
// Feature already installed
return Collections.emptyList();
}
EsaResource esa = ((KernelResolverEsa) feature).getResource();
Map<String, Integer> maxDistanceMap = new HashMap<>();
List<MissingRequirement> missingRequirements = new ArrayList<>();
boolean foundAllDependencies = populateMaxDistanceMap(maxDistanceMap, esa.getProvideFeature(), 0, new HashSet<ProvisioningFeatureDefinition>(), missingRequirements);
if (!foundAllDependencies) {
missingTopLevelRequirements.add(featureName);
this.missingRequirements.addAll(missingRequirements);
}
ArrayList<RepositoryResource> installList = new ArrayList<>();
installList.addAll(convertFeatureNamesToResources(maxDistanceMap.keySet()));
Collections.sort(installList, byMaxDistance(maxDistanceMap));
return installList;
} | [
"List",
"<",
"RepositoryResource",
">",
"createInstallList",
"(",
"String",
"featureName",
")",
"{",
"ProvisioningFeatureDefinition",
"feature",
"=",
"resolverRepository",
".",
"getFeature",
"(",
"featureName",
")",
";",
"if",
"(",
"feature",
"==",
"null",
")",
"{... | Create a list of resources which should be installed in order to install the given featutre.
<p>
The install list consists of all the dependencies which are needed by {@code esa}, ordered so that each resource in the list comes after its dependencies.
@param featureName the feature name (as provided to {@link #resolve(Collection)}) for which to create an install list
@return the ordered list of resources to install, will be empty if the feature cannot be found or is already installed | [
"Create",
"a",
"list",
"of",
"resources",
"which",
"should",
"be",
"installed",
"in",
"order",
"to",
"install",
"the",
"given",
"featutre",
".",
"<p",
">",
"The",
"install",
"list",
"consists",
"of",
"all",
"the",
"dependencies",
"which",
"are",
"needed",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java#L545-L579 |
broadinstitute/barclay | src/main/java/org/broadinstitute/barclay/help/HelpDoclet.java | HelpDoclet.processIndexTemplate | protected void processIndexTemplate(
final Configuration cfg,
final List<DocWorkUnit> workUnitList,
final List<Map<String, String>> groupMaps
) throws IOException {
// Get or create a template and merge in the data
final Template template = cfg.getTemplate(getIndexTemplateName());
final File indexFile = new File(getDestinationDir(),
getIndexBaseFileName() + '.' + getIndexFileExtension()
);
try (final FileOutputStream fileOutStream = new FileOutputStream(indexFile);
final OutputStreamWriter outWriter = new OutputStreamWriter(fileOutStream)) {
template.process(groupIndexMap(workUnitList, groupMaps), outWriter);
} catch (TemplateException e) {
throw new DocException("Freemarker Template Exception during documentation index creation", e);
}
} | java | protected void processIndexTemplate(
final Configuration cfg,
final List<DocWorkUnit> workUnitList,
final List<Map<String, String>> groupMaps
) throws IOException {
// Get or create a template and merge in the data
final Template template = cfg.getTemplate(getIndexTemplateName());
final File indexFile = new File(getDestinationDir(),
getIndexBaseFileName() + '.' + getIndexFileExtension()
);
try (final FileOutputStream fileOutStream = new FileOutputStream(indexFile);
final OutputStreamWriter outWriter = new OutputStreamWriter(fileOutStream)) {
template.process(groupIndexMap(workUnitList, groupMaps), outWriter);
} catch (TemplateException e) {
throw new DocException("Freemarker Template Exception during documentation index creation", e);
}
} | [
"protected",
"void",
"processIndexTemplate",
"(",
"final",
"Configuration",
"cfg",
",",
"final",
"List",
"<",
"DocWorkUnit",
">",
"workUnitList",
",",
"final",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"groupMaps",
")",
"throws",
"IOException... | Create the php index listing all of the Docs features
@param cfg
@param workUnitList
@param groupMaps
@throws IOException | [
"Create",
"the",
"php",
"index",
"listing",
"all",
"of",
"the",
"Docs",
"features"
] | train | https://github.com/broadinstitute/barclay/blob/7e56d725766b0da3baff23e79a31c3d01c3589c2/src/main/java/org/broadinstitute/barclay/help/HelpDoclet.java#L464-L482 |
Azure/azure-sdk-for-java | mediaservices/data-plane/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java | QueueService.create | public static QueueContract create(String profile, Configuration config) {
return config.create(profile, QueueContract.class);
} | java | public static QueueContract create(String profile, Configuration config) {
return config.create(profile, QueueContract.class);
} | [
"public",
"static",
"QueueContract",
"create",
"(",
"String",
"profile",
",",
"Configuration",
"config",
")",
"{",
"return",
"config",
".",
"create",
"(",
"profile",
",",
"QueueContract",
".",
"class",
")",
";",
"}"
] | A static factory method that returns an instance implementing
{@link com.microsoft.windowsazure.services.queue.QueueContract} using the specified {@link Configuration} instance
and profile prefix for service settings. The {@link Configuration}
instance must have storage account information and credentials set with
the specified profile prefix before this method is called for the
returned interface to work.
@param profile
A string prefix for the account name and credentials settings
in the {@link Configuration} instance.
@param config
A {@link Configuration} instance configured with storage
account information and credentials.
@return An instance implementing {@link com.microsoft.windowsazure.services.queue.QueueContract} for interacting
with the queue service. | [
"A",
"static",
"factory",
"method",
"that",
"returns",
"an",
"instance",
"implementing",
"{",
"@link",
"com",
".",
"microsoft",
".",
"windowsazure",
".",
"services",
".",
"queue",
".",
"QueueContract",
"}",
"using",
"the",
"specified",
"{",
"@link",
"Configura... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/data-plane/src/main/java/com/microsoft/windowsazure/services/queue/QueueService.java#L99-L101 |
alibaba/otter | shared/common/src/main/java/com/alibaba/otter/shared/common/utils/zookeeper/ZkClientx.java | ZkClientx.watchForChilds | public List<String> watchForChilds(final String path) {
if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
}
return retryUntilConnected(new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
exists(path, true);
try {
return getChildren(path, true);
} catch (ZkNoNodeException e) {
// ignore, the "exists" watch will listen for the parent node to appear
}
return null;
}
});
} | java | public List<String> watchForChilds(final String path) {
if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
}
return retryUntilConnected(new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
exists(path, true);
try {
return getChildren(path, true);
} catch (ZkNoNodeException e) {
// ignore, the "exists" watch will listen for the parent node to appear
}
return null;
}
});
} | [
"public",
"List",
"<",
"String",
">",
"watchForChilds",
"(",
"final",
"String",
"path",
")",
"{",
"if",
"(",
"_zookeeperEventThread",
"!=",
"null",
"&&",
"Thread",
".",
"currentThread",
"(",
")",
"==",
"_zookeeperEventThread",
")",
"{",
"throw",
"new",
"Ille... | Installs a child watch for the given path.
@param path
@return the current children of the path or null if the zk node with the given path doesn't exist. | [
"Installs",
"a",
"child",
"watch",
"for",
"the",
"given",
"path",
"."
] | train | https://github.com/alibaba/otter/blob/c7b5f94a0dd162e01ddffaf3a63cade7d23fca55/shared/common/src/main/java/com/alibaba/otter/shared/common/utils/zookeeper/ZkClientx.java#L934-L951 |
VoltDB/voltdb | src/frontend/org/voltdb/utils/CatalogUtil.java | CatalogUtil.getBuildInfoFromJar | public static String[] getBuildInfoFromJar(InMemoryJarfile jarfile)
throws IOException
{
// Read the raw build info bytes.
byte[] buildInfoBytes = jarfile.get(CATALOG_BUILDINFO_FILENAME);
if (buildInfoBytes == null) {
throw new IOException("Catalog build information not found - please build your application using the current version of VoltDB.");
}
// Convert the bytes to a string and split by lines.
String buildInfo;
buildInfo = new String(buildInfoBytes, Constants.UTF8ENCODING);
String[] buildInfoLines = buildInfo.split("\n");
// Sanity check the number of lines and the version string.
if (buildInfoLines.length < 1) {
throw new IOException("Catalog build info has no version string.");
}
String versionFromCatalog = buildInfoLines[0].trim();
if (!CatalogUtil.isCatalogVersionValid(versionFromCatalog)) {
throw new IOException(String.format(
"Catalog build info version (%s) is bad.", versionFromCatalog));
}
// Trim leading/trailing whitespace.
for (int i = 0; i < buildInfoLines.length; ++i) {
buildInfoLines[i] = buildInfoLines[i].trim();
}
return buildInfoLines;
} | java | public static String[] getBuildInfoFromJar(InMemoryJarfile jarfile)
throws IOException
{
// Read the raw build info bytes.
byte[] buildInfoBytes = jarfile.get(CATALOG_BUILDINFO_FILENAME);
if (buildInfoBytes == null) {
throw new IOException("Catalog build information not found - please build your application using the current version of VoltDB.");
}
// Convert the bytes to a string and split by lines.
String buildInfo;
buildInfo = new String(buildInfoBytes, Constants.UTF8ENCODING);
String[] buildInfoLines = buildInfo.split("\n");
// Sanity check the number of lines and the version string.
if (buildInfoLines.length < 1) {
throw new IOException("Catalog build info has no version string.");
}
String versionFromCatalog = buildInfoLines[0].trim();
if (!CatalogUtil.isCatalogVersionValid(versionFromCatalog)) {
throw new IOException(String.format(
"Catalog build info version (%s) is bad.", versionFromCatalog));
}
// Trim leading/trailing whitespace.
for (int i = 0; i < buildInfoLines.length; ++i) {
buildInfoLines[i] = buildInfoLines[i].trim();
}
return buildInfoLines;
} | [
"public",
"static",
"String",
"[",
"]",
"getBuildInfoFromJar",
"(",
"InMemoryJarfile",
"jarfile",
")",
"throws",
"IOException",
"{",
"// Read the raw build info bytes.",
"byte",
"[",
"]",
"buildInfoBytes",
"=",
"jarfile",
".",
"get",
"(",
"CATALOG_BUILDINFO_FILENAME",
... | Get the catalog build info from the jar bytes.
Performs sanity checks on the build info and version strings.
@param jarfile in-memory catalog jar file
@return build info lines
@throws IOException If the catalog or the version string cannot be loaded. | [
"Get",
"the",
"catalog",
"build",
"info",
"from",
"the",
"jar",
"bytes",
".",
"Performs",
"sanity",
"checks",
"on",
"the",
"build",
"info",
"and",
"version",
"strings",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/CatalogUtil.java#L298-L328 |
git-commit-id/maven-git-commit-id-plugin | src/main/java/pl/project13/maven/git/GitDirLocator.java | GitDirLocator.findProjectGitDirectory | @Nullable
private File findProjectGitDirectory() {
if (this.mavenProject == null) {
return null;
}
File basedir = mavenProject.getBasedir();
while (basedir != null) {
File gitdir = new File(basedir, Constants.DOT_GIT);
if (gitdir.exists()) {
if (gitdir.isDirectory()) {
return gitdir;
} else if (gitdir.isFile()) {
return processGitDirFile(gitdir);
} else {
return null;
}
}
basedir = basedir.getParentFile();
}
return null;
} | java | @Nullable
private File findProjectGitDirectory() {
if (this.mavenProject == null) {
return null;
}
File basedir = mavenProject.getBasedir();
while (basedir != null) {
File gitdir = new File(basedir, Constants.DOT_GIT);
if (gitdir.exists()) {
if (gitdir.isDirectory()) {
return gitdir;
} else if (gitdir.isFile()) {
return processGitDirFile(gitdir);
} else {
return null;
}
}
basedir = basedir.getParentFile();
}
return null;
} | [
"@",
"Nullable",
"private",
"File",
"findProjectGitDirectory",
"(",
")",
"{",
"if",
"(",
"this",
".",
"mavenProject",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"File",
"basedir",
"=",
"mavenProject",
".",
"getBasedir",
"(",
")",
";",
"while",
"... | Search up all the maven parent project hierarchy until a .git directory is found.
@return File which represents the location of the .git directory or NULL if none found. | [
"Search",
"up",
"all",
"the",
"maven",
"parent",
"project",
"hierarchy",
"until",
"a",
".",
"git",
"directory",
"is",
"found",
"."
] | train | https://github.com/git-commit-id/maven-git-commit-id-plugin/blob/a276551fb043d1b7fc4c890603f6ea0c79dc729a/src/main/java/pl/project13/maven/git/GitDirLocator.java#L73-L94 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java | BeanUtil.toBean | public static <T> T toBean(Object source, Class<T> clazz) {
final T target = ReflectUtil.newInstance(clazz);
copyProperties(source, target);
return target;
} | java | public static <T> T toBean(Object source, Class<T> clazz) {
final T target = ReflectUtil.newInstance(clazz);
copyProperties(source, target);
return target;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"toBean",
"(",
"Object",
"source",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"final",
"T",
"target",
"=",
"ReflectUtil",
".",
"newInstance",
"(",
"clazz",
")",
";",
"copyProperties",
"(",
"source",
",",
"... | 对象或Map转Bean
@param source Bean对象或Map
@param clazz 目标的Bean类型
@return Bean对象
@since 4.1.20 | [
"对象或Map转Bean"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java#L442-L446 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/KetamaNodeKeyFormatter.java | KetamaNodeKeyFormatter.getKeyForNode | public String getKeyForNode(MemcachedNode node, int repetition) {
// Carrried over from the DefaultKetamaNodeLocatorConfiguration:
// Internal Using the internal map retrieve the socket addresses
// for given nodes.
// I'm aware that this code is inherently thread-unsafe as
// I'm using a HashMap implementation of the map, but the worst
// case ( I believe) is we're slightly in-efficient when
// a node has never been seen before concurrently on two different
// threads, so it the socketaddress will be requested multiple times!
// all other cases should be as fast as possible.
String nodeKey = nodeKeys.get(node);
if (nodeKey == null) {
switch(this.format) {
case LIBMEMCACHED:
InetSocketAddress address = (InetSocketAddress)node.getSocketAddress();
nodeKey = address.getHostName();
if (address.getPort() != 11211) {
nodeKey += ":" + address.getPort();
}
break;
case SPYMEMCACHED:
nodeKey = String.valueOf(node.getSocketAddress());
if (nodeKey.startsWith("/")) {
nodeKey = nodeKey.substring(1);
}
break;
default:
assert false;
}
nodeKeys.put(node, nodeKey);
}
return nodeKey + "-" + repetition;
} | java | public String getKeyForNode(MemcachedNode node, int repetition) {
// Carrried over from the DefaultKetamaNodeLocatorConfiguration:
// Internal Using the internal map retrieve the socket addresses
// for given nodes.
// I'm aware that this code is inherently thread-unsafe as
// I'm using a HashMap implementation of the map, but the worst
// case ( I believe) is we're slightly in-efficient when
// a node has never been seen before concurrently on two different
// threads, so it the socketaddress will be requested multiple times!
// all other cases should be as fast as possible.
String nodeKey = nodeKeys.get(node);
if (nodeKey == null) {
switch(this.format) {
case LIBMEMCACHED:
InetSocketAddress address = (InetSocketAddress)node.getSocketAddress();
nodeKey = address.getHostName();
if (address.getPort() != 11211) {
nodeKey += ":" + address.getPort();
}
break;
case SPYMEMCACHED:
nodeKey = String.valueOf(node.getSocketAddress());
if (nodeKey.startsWith("/")) {
nodeKey = nodeKey.substring(1);
}
break;
default:
assert false;
}
nodeKeys.put(node, nodeKey);
}
return nodeKey + "-" + repetition;
} | [
"public",
"String",
"getKeyForNode",
"(",
"MemcachedNode",
"node",
",",
"int",
"repetition",
")",
"{",
"// Carrried over from the DefaultKetamaNodeLocatorConfiguration:",
"// Internal Using the internal map retrieve the socket addresses",
"// for given nodes.",
"// I'm aware that this co... | Returns a uniquely identifying key, suitable for hashing by the
KetamaNodeLocator algorithm.
@param node The MemcachedNode to use to form the unique identifier
@param repetition The repetition number for the particular node in question
(0 is the first repetition)
@return The key that represents the specific repetition of the node | [
"Returns",
"a",
"uniquely",
"identifying",
"key",
"suitable",
"for",
"hashing",
"by",
"the",
"KetamaNodeLocator",
"algorithm",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/KetamaNodeKeyFormatter.java#L105-L137 |
albfernandez/itext2 | src/main/java/com/lowagie/text/rtf/parser/RtfImportMgr.java | RtfImportMgr.importFont | public boolean importFont(String fontNr, String fontName, String fontFamily, int charset) {
RtfFont rtfFont = new RtfFont(fontName);
if(charset>= 0)
rtfFont.setCharset(charset);
if(fontFamily != null && fontFamily.length() > 0)
rtfFont.setFamily(fontFamily);
rtfFont.setRtfDocument(this.rtfDoc);
this.importFontMapping.put(fontNr, Integer.toString(this.rtfDoc.getDocumentHeader().getFontNumber(rtfFont)));
return true;
} | java | public boolean importFont(String fontNr, String fontName, String fontFamily, int charset) {
RtfFont rtfFont = new RtfFont(fontName);
if(charset>= 0)
rtfFont.setCharset(charset);
if(fontFamily != null && fontFamily.length() > 0)
rtfFont.setFamily(fontFamily);
rtfFont.setRtfDocument(this.rtfDoc);
this.importFontMapping.put(fontNr, Integer.toString(this.rtfDoc.getDocumentHeader().getFontNumber(rtfFont)));
return true;
} | [
"public",
"boolean",
"importFont",
"(",
"String",
"fontNr",
",",
"String",
"fontName",
",",
"String",
"fontFamily",
",",
"int",
"charset",
")",
"{",
"RtfFont",
"rtfFont",
"=",
"new",
"RtfFont",
"(",
"fontName",
")",
";",
"if",
"(",
"charset",
">=",
"0",
... | Imports a font. The font name is looked up in the RtfDocumentHeader and
then the mapping from original font number to actual font number is added.
@param fontNr The original font number.
@param fontName The font name to look up.
@param charset The character set to use for the font. | [
"Imports",
"a",
"font",
".",
"The",
"font",
"name",
"is",
"looked",
"up",
"in",
"the",
"RtfDocumentHeader",
"and",
"then",
"the",
"mapping",
"from",
"original",
"font",
"number",
"to",
"actual",
"font",
"number",
"is",
"added",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/parser/RtfImportMgr.java#L157-L167 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/CheckerUtility.java | CheckerUtility.checkMethodSignature | public static boolean checkMethodSignature(final Method method, final List<WaveItem<?>> wParams) {
boolean isCompliant = false;
final Type[] mParams = method.getGenericParameterTypes();
if (wParams.isEmpty() && Wave.class.isAssignableFrom(ClassUtility.getClassFromType(mParams[0]))) {
isCompliant = true;
} else if (mParams.length - 1 == wParams.size()) {
// Flag used to skip a method not compliant
boolean skipMethod = false;
// Check each parameter
for (int i = 0; !skipMethod && i < mParams.length - 1 && !isCompliant; i++) {
if (!ClassUtility.getClassFromType(mParams[i]).isAssignableFrom(ClassUtility.getClassFromType(wParams.get(i).type()))) {
// This method has not the right parameters
skipMethod = true;
}
if (i == mParams.length - 2
&& Wave.class.isAssignableFrom(ClassUtility.getClassFromType(mParams[i + 1]))) {
// This method is compliant with wave type
isCompliant = true;
}
}
}
return isCompliant;
} | java | public static boolean checkMethodSignature(final Method method, final List<WaveItem<?>> wParams) {
boolean isCompliant = false;
final Type[] mParams = method.getGenericParameterTypes();
if (wParams.isEmpty() && Wave.class.isAssignableFrom(ClassUtility.getClassFromType(mParams[0]))) {
isCompliant = true;
} else if (mParams.length - 1 == wParams.size()) {
// Flag used to skip a method not compliant
boolean skipMethod = false;
// Check each parameter
for (int i = 0; !skipMethod && i < mParams.length - 1 && !isCompliant; i++) {
if (!ClassUtility.getClassFromType(mParams[i]).isAssignableFrom(ClassUtility.getClassFromType(wParams.get(i).type()))) {
// This method has not the right parameters
skipMethod = true;
}
if (i == mParams.length - 2
&& Wave.class.isAssignableFrom(ClassUtility.getClassFromType(mParams[i + 1]))) {
// This method is compliant with wave type
isCompliant = true;
}
}
}
return isCompliant;
} | [
"public",
"static",
"boolean",
"checkMethodSignature",
"(",
"final",
"Method",
"method",
",",
"final",
"List",
"<",
"WaveItem",
"<",
"?",
">",
">",
"wParams",
")",
"{",
"boolean",
"isCompliant",
"=",
"false",
";",
"final",
"Type",
"[",
"]",
"mParams",
"=",... | Compare method parameters with wave parameters.
@param method the method to check
@param wParams the wave parameters taht define the contract
@return true if the method has the right signature | [
"Compare",
"method",
"parameters",
"with",
"wave",
"parameters",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/CheckerUtility.java#L110-L135 |
katharsis-project/katharsis-framework | katharsis-core/src/main/java/io/katharsis/core/internal/registry/ResourceRegistryImpl.java | ResourceRegistryImpl.findEntry | public RegistryEntry findEntry(String searchType, Class<?> clazz) {
RegistryEntry entry = getEntry(searchType);
if (entry == null) {
return getEntry(clazz, false);
}
return entry;
} | java | public RegistryEntry findEntry(String searchType, Class<?> clazz) {
RegistryEntry entry = getEntry(searchType);
if (entry == null) {
return getEntry(clazz, false);
}
return entry;
} | [
"public",
"RegistryEntry",
"findEntry",
"(",
"String",
"searchType",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"RegistryEntry",
"entry",
"=",
"getEntry",
"(",
"searchType",
")",
";",
"if",
"(",
"entry",
"==",
"null",
")",
"{",
"return",
"getEntry",
... | Searches the registry for a resource identified by, 1) JSON API resource
type. 2) JSON API resource class.
<p>
If a resource cannot be found,
{@link ResourceNotFoundInitializationException} is thrown.
@param searchType
resource type
@param clazz
resource type
@return registry entry
@throws ResourceNotFoundInitializationException
if resource is not found | [
"Searches",
"the",
"registry",
"for",
"a",
"resource",
"identified",
"by",
"1",
")",
"JSON",
"API",
"resource",
"type",
".",
"2",
")",
"JSON",
"API",
"resource",
"class",
".",
"<p",
">",
"If",
"a",
"resource",
"cannot",
"be",
"found",
"{",
"@link",
"Re... | train | https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-core/src/main/java/io/katharsis/core/internal/registry/ResourceRegistryImpl.java#L88-L94 |
apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/HivePurgerSource.java | HivePurgerSource.setJobWatermark | protected void setJobWatermark(SourceState state, String watermark) {
state.setProp(ComplianceConfigurationKeys.HIVE_PURGER_WATERMARK, watermark);
log.info("Setting job watermark for the job: " + watermark);
} | java | protected void setJobWatermark(SourceState state, String watermark) {
state.setProp(ComplianceConfigurationKeys.HIVE_PURGER_WATERMARK, watermark);
log.info("Setting job watermark for the job: " + watermark);
} | [
"protected",
"void",
"setJobWatermark",
"(",
"SourceState",
"state",
",",
"String",
"watermark",
")",
"{",
"state",
".",
"setProp",
"(",
"ComplianceConfigurationKeys",
".",
"HIVE_PURGER_WATERMARK",
",",
"watermark",
")",
";",
"log",
".",
"info",
"(",
"\"Setting jo... | Sets Job Watermark in the SourceState which will be copied to all WorkUnitStates. Job Watermark is a complete partition name.
During next run of this job, fresh work units will be created starting from this partition. | [
"Sets",
"Job",
"Watermark",
"in",
"the",
"SourceState",
"which",
"will",
"be",
"copied",
"to",
"all",
"WorkUnitStates",
".",
"Job",
"Watermark",
"is",
"a",
"complete",
"partition",
"name",
".",
"During",
"next",
"run",
"of",
"this",
"job",
"fresh",
"work",
... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/HivePurgerSource.java#L327-L330 |
jMotif/SAX | src/main/java/net/seninp/util/HeatChart.java | HeatChart.getCellColour | private Color getCellColour(double data, double min, double max) {
double range = max - min;
double position = data - min;
// What proportion of the way through the possible values is that.
double percentPosition = position / range;
// Which colour group does that put us in.
// int colourPosition = getColourPosition(percentPosition);
int r = (int) (255 * red(percentPosition * 2 - 1));
int g = (int) (255 * green(percentPosition * 2 - 1));
int b = (int) (255 * blue(percentPosition * 2 - 1));
// int r = lowValueColour.getRed();
// int g = lowValueColour.getGreen();
// int b = lowValueColour.getBlue();
//
// // Make n shifts of the colour, where n is the colourPosition.
// for (int i = 0; i < colourPosition; i++) {
// int rDistance = r - highValueColour.getRed();
// int gDistance = g - highValueColour.getGreen();
// int bDistance = b - highValueColour.getBlue();
//
// if ((Math.abs(rDistance) >= Math.abs(gDistance))
// && (Math.abs(rDistance) >= Math.abs(bDistance))) {
// // Red must be the largest.
// r = changeColourValue(r, rDistance);
// }
// else if (Math.abs(gDistance) >= Math.abs(bDistance)) {
// // Green must be the largest.
// g = changeColourValue(g, gDistance);
// }
// else {
// // Blue must be the largest.
// b = changeColourValue(b, bDistance);
// }
// }
return new Color(r, g, b);
} | java | private Color getCellColour(double data, double min, double max) {
double range = max - min;
double position = data - min;
// What proportion of the way through the possible values is that.
double percentPosition = position / range;
// Which colour group does that put us in.
// int colourPosition = getColourPosition(percentPosition);
int r = (int) (255 * red(percentPosition * 2 - 1));
int g = (int) (255 * green(percentPosition * 2 - 1));
int b = (int) (255 * blue(percentPosition * 2 - 1));
// int r = lowValueColour.getRed();
// int g = lowValueColour.getGreen();
// int b = lowValueColour.getBlue();
//
// // Make n shifts of the colour, where n is the colourPosition.
// for (int i = 0; i < colourPosition; i++) {
// int rDistance = r - highValueColour.getRed();
// int gDistance = g - highValueColour.getGreen();
// int bDistance = b - highValueColour.getBlue();
//
// if ((Math.abs(rDistance) >= Math.abs(gDistance))
// && (Math.abs(rDistance) >= Math.abs(bDistance))) {
// // Red must be the largest.
// r = changeColourValue(r, rDistance);
// }
// else if (Math.abs(gDistance) >= Math.abs(bDistance)) {
// // Green must be the largest.
// g = changeColourValue(g, gDistance);
// }
// else {
// // Blue must be the largest.
// b = changeColourValue(b, bDistance);
// }
// }
return new Color(r, g, b);
} | [
"private",
"Color",
"getCellColour",
"(",
"double",
"data",
",",
"double",
"min",
",",
"double",
"max",
")",
"{",
"double",
"range",
"=",
"max",
"-",
"min",
";",
"double",
"position",
"=",
"data",
"-",
"min",
";",
"// What proportion of the way through the pos... | /*
Determines what colour a heat map cell should be based upon the cell values. | [
"/",
"*",
"Determines",
"what",
"colour",
"a",
"heat",
"map",
"cell",
"should",
"be",
"based",
"upon",
"the",
"cell",
"values",
"."
] | train | https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/util/HeatChart.java#L1626-L1666 |
knowm/XChange | xchange-lakebtc/src/main/java/org/knowm/xchange/lakebtc/LakeBTCAdapters.java | LakeBTCAdapters.adaptTrade | public static Trade adaptTrade(
LakeBTCTradeResponse tx, CurrencyPair currencyPair, int timeScale) {
final String tradeId = String.valueOf(tx.getId());
Date date = DateUtils.fromMillisUtc(tx.getAt() * timeScale); // polled order
// books provide
// a timestamp
// in seconds,
// stream in ms
return new Trade(null, tx.getAmount(), currencyPair, tx.getTotal(), date, tradeId);
} | java | public static Trade adaptTrade(
LakeBTCTradeResponse tx, CurrencyPair currencyPair, int timeScale) {
final String tradeId = String.valueOf(tx.getId());
Date date = DateUtils.fromMillisUtc(tx.getAt() * timeScale); // polled order
// books provide
// a timestamp
// in seconds,
// stream in ms
return new Trade(null, tx.getAmount(), currencyPair, tx.getTotal(), date, tradeId);
} | [
"public",
"static",
"Trade",
"adaptTrade",
"(",
"LakeBTCTradeResponse",
"tx",
",",
"CurrencyPair",
"currencyPair",
",",
"int",
"timeScale",
")",
"{",
"final",
"String",
"tradeId",
"=",
"String",
".",
"valueOf",
"(",
"tx",
".",
"getId",
"(",
")",
")",
";",
... | Adapts a Transaction to a Trade Object
@param tx The LakeBtc transaction
@param currencyPair (e.g. BTC/USD)
@param timeScale polled order books provide a timestamp in seconds, stream in ms
@return The XChange Trade | [
"Adapts",
"a",
"Transaction",
"to",
"a",
"Trade",
"Object"
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-lakebtc/src/main/java/org/knowm/xchange/lakebtc/LakeBTCAdapters.java#L106-L116 |
derari/cthul | xml/src/main/java/org/cthul/resolve/UriMappingResolver.java | UriMappingResolver.addDomain | public UriMappingResolver addDomain(String domain, String replacement) {
addDomainPattern(quote(domain) + "[/]*(.*)", replacement);
return this;
} | java | public UriMappingResolver addDomain(String domain, String replacement) {
addDomainPattern(quote(domain) + "[/]*(.*)", replacement);
return this;
} | [
"public",
"UriMappingResolver",
"addDomain",
"(",
"String",
"domain",
",",
"String",
"replacement",
")",
"{",
"addDomainPattern",
"(",
"quote",
"(",
"domain",
")",
"+",
"\"[/]*(.*)\"",
",",
"replacement",
")",
";",
"return",
"this",
";",
"}"
] | Adds a domain for relative lookup.
All uris starting with {@code domain} will be replaced with
{@code replacement}. In the replacement string {@code "$1"}, will
be replaced with path of the request uri.
Path separators ({@code '/'}) between the domain and the path will be removed.
@param domain
@param replacement
@return this | [
"Adds",
"a",
"domain",
"for",
"relative",
"lookup",
".",
"All",
"uris",
"starting",
"with",
"{"
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/xml/src/main/java/org/cthul/resolve/UriMappingResolver.java#L129-L132 |
pili-engineering/pili-sdk-java | src/main/java/com/qiniu/pili/Client.java | Client.RTMPPublishURL | public String RTMPPublishURL(String domain, String hub, String streamKey, int expireAfterSeconds) {
long expire = System.currentTimeMillis() / 1000 + expireAfterSeconds;
String path = String.format("/%s/%s?e=%d", hub, streamKey, expire);
String token;
try {
token = this.cli.getMac().sign(path);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return String.format("rtmp://%s%s&token=%s", domain, path, token);
} | java | public String RTMPPublishURL(String domain, String hub, String streamKey, int expireAfterSeconds) {
long expire = System.currentTimeMillis() / 1000 + expireAfterSeconds;
String path = String.format("/%s/%s?e=%d", hub, streamKey, expire);
String token;
try {
token = this.cli.getMac().sign(path);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return String.format("rtmp://%s%s&token=%s", domain, path, token);
} | [
"public",
"String",
"RTMPPublishURL",
"(",
"String",
"domain",
",",
"String",
"hub",
",",
"String",
"streamKey",
",",
"int",
"expireAfterSeconds",
")",
"{",
"long",
"expire",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"/",
"1000",
"+",
"expireAfterSeco... | /*
RTMPPublishURL generates RTMP publish URL
expireAfterSeconds means URL will be invalid after expireAfterSeconds. | [
"/",
"*",
"RTMPPublishURL",
"generates",
"RTMP",
"publish",
"URL",
"expireAfterSeconds",
"means",
"URL",
"will",
"be",
"invalid",
"after",
"expireAfterSeconds",
"."
] | train | https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Client.java#L14-L25 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineExtensionsInner.java | VirtualMachineExtensionsInner.beginUpdateAsync | public Observable<VirtualMachineExtensionInner> beginUpdateAsync(String resourceGroupName, String vmName, String vmExtensionName, VirtualMachineExtensionUpdate extensionParameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters).map(new Func1<ServiceResponse<VirtualMachineExtensionInner>, VirtualMachineExtensionInner>() {
@Override
public VirtualMachineExtensionInner call(ServiceResponse<VirtualMachineExtensionInner> response) {
return response.body();
}
});
} | java | public Observable<VirtualMachineExtensionInner> beginUpdateAsync(String resourceGroupName, String vmName, String vmExtensionName, VirtualMachineExtensionUpdate extensionParameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters).map(new Func1<ServiceResponse<VirtualMachineExtensionInner>, VirtualMachineExtensionInner>() {
@Override
public VirtualMachineExtensionInner call(ServiceResponse<VirtualMachineExtensionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VirtualMachineExtensionInner",
">",
"beginUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmName",
",",
"String",
"vmExtensionName",
",",
"VirtualMachineExtensionUpdate",
"extensionParameters",
")",
"{",
"return",
"beginUpdate... | The operation to update the extension.
@param resourceGroupName The name of the resource group.
@param vmName The name of the virtual machine where the extension should be updated.
@param vmExtensionName The name of the virtual machine extension.
@param extensionParameters Parameters supplied to the Update Virtual Machine Extension operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VirtualMachineExtensionInner object | [
"The",
"operation",
"to",
"update",
"the",
"extension",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineExtensionsInner.java#L401-L408 |
ecclesia/kipeto | kipeto-core/src/main/java/de/ecclesia/kipeto/blueprint/FileItem.java | FileItem.fromStream | public static FileItem fromStream(DataInputStream dataInputStream) throws IOException {
// Über die Version kann gesteuert werden, wieviele Felder gelesen
// werden. Das ist aus Gründen der Abwärtskompatibilität notwendig.
// Neue Felder dürfen nur am Ende hinzugefügt werden. Die Version
// muss dann heraufgesetzt werden.
byte binaryVersion = dataInputStream.readByte();
if (binaryVersion >= 1) {
String name = dataInputStream.readUTF();
long length = dataInputStream.readLong();
long lastModified = dataInputStream.readLong();
String blobId = dataInputStream.readUTF();
return new FileItem(name, blobId, length, lastModified);
} else {
throw new IllegalStateException("Unsupported binary version <" + binaryVersion + ">");
}
} | java | public static FileItem fromStream(DataInputStream dataInputStream) throws IOException {
// Über die Version kann gesteuert werden, wieviele Felder gelesen
// werden. Das ist aus Gründen der Abwärtskompatibilität notwendig.
// Neue Felder dürfen nur am Ende hinzugefügt werden. Die Version
// muss dann heraufgesetzt werden.
byte binaryVersion = dataInputStream.readByte();
if (binaryVersion >= 1) {
String name = dataInputStream.readUTF();
long length = dataInputStream.readLong();
long lastModified = dataInputStream.readLong();
String blobId = dataInputStream.readUTF();
return new FileItem(name, blobId, length, lastModified);
} else {
throw new IllegalStateException("Unsupported binary version <" + binaryVersion + ">");
}
} | [
"public",
"static",
"FileItem",
"fromStream",
"(",
"DataInputStream",
"dataInputStream",
")",
"throws",
"IOException",
"{",
"// Über die Version kann gesteuert werden, wieviele Felder gelesen",
"// werden. Das ist aus Gründen der Abwärtskompatibilität notwendig.",
"// Neue Felder dürfen nu... | Deserialisiert ein FileItem aus einem übergebenen InputStream.
@param dataInputStream
Quelle der Deserialisierung
@return FileItem
@throws IOException | [
"Deserialisiert",
"ein",
"FileItem",
"aus",
"einem",
"übergebenen",
"InputStream",
"."
] | train | https://github.com/ecclesia/kipeto/blob/ea39a10ae4eaa550f71a856ab2f2845270a64913/kipeto-core/src/main/java/de/ecclesia/kipeto/blueprint/FileItem.java#L128-L146 |
DataArt/CalculationEngine | calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataSetConverters.java | DataSetConverters.toWorkbook | static Workbook toWorkbook(final IDataSet dataSet, final Workbook formatting) {
Workbook result = formatting == null ? ConverterUtils.newWorkbook() : ConverterUtils.clearContent(formatting);
Sheet sheet = result.createSheet(dataSet.getName());
for (IDsRow row : dataSet) {
Row wbRow = sheet.createRow(row.index() - 1);
for (IDsCell cell : row) {
Cell wbCell = wbRow.createCell(cell.index() - 1);
ConverterUtils.populateCellValue(wbCell, cell.getValue());
}
}
return result;
} | java | static Workbook toWorkbook(final IDataSet dataSet, final Workbook formatting) {
Workbook result = formatting == null ? ConverterUtils.newWorkbook() : ConverterUtils.clearContent(formatting);
Sheet sheet = result.createSheet(dataSet.getName());
for (IDsRow row : dataSet) {
Row wbRow = sheet.createRow(row.index() - 1);
for (IDsCell cell : row) {
Cell wbCell = wbRow.createCell(cell.index() - 1);
ConverterUtils.populateCellValue(wbCell, cell.getValue());
}
}
return result;
} | [
"static",
"Workbook",
"toWorkbook",
"(",
"final",
"IDataSet",
"dataSet",
",",
"final",
"Workbook",
"formatting",
")",
"{",
"Workbook",
"result",
"=",
"formatting",
"==",
"null",
"?",
"ConverterUtils",
".",
"newWorkbook",
"(",
")",
":",
"ConverterUtils",
".",
"... | Converts {@link IDataSet} to {@link Workbook}.
The result {@link Workbook} is created from @param formatting. | [
"Converts",
"{"
] | train | https://github.com/DataArt/CalculationEngine/blob/34ce1d9c1f9b57a502906b274311d28580b134e5/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataSetConverters.java#L133-L146 |
JOML-CI/JOML | src/org/joml/Quaternionf.java | Quaternionf.rotateAxis | public Quaternionf rotateAxis(float angle, float axisX, float axisY, float axisZ) {
return rotateAxis(angle, axisX, axisY, axisZ, this);
} | java | public Quaternionf rotateAxis(float angle, float axisX, float axisY, float axisZ) {
return rotateAxis(angle, axisX, axisY, axisZ, this);
} | [
"public",
"Quaternionf",
"rotateAxis",
"(",
"float",
"angle",
",",
"float",
"axisX",
",",
"float",
"axisY",
",",
"float",
"axisZ",
")",
"{",
"return",
"rotateAxis",
"(",
"angle",
",",
"axisX",
",",
"axisY",
",",
"axisZ",
",",
"this",
")",
";",
"}"
] | Apply a rotation to <code>this</code> quaternion rotating the given radians about the specified axis.
<p>
If <code>Q</code> is <code>this</code> quaternion and <code>R</code> the quaternion representing the
specified rotation, then the new quaternion will be <code>Q * R</code>. So when transforming a
vector <code>v</code> with the new quaternion by using <code>Q * R * v</code>, the
rotation added by this method will be applied first!
@see #rotateAxis(float, float, float, float, Quaternionf)
@param angle
the angle in radians to rotate about the specified axis
@param axisX
the x coordinate of the rotation axis
@param axisY
the y coordinate of the rotation axis
@param axisZ
the z coordinate of the rotation axis
@return this | [
"Apply",
"a",
"rotation",
"to",
"<code",
">",
"this<",
"/",
"code",
">",
"quaternion",
"rotating",
"the",
"given",
"radians",
"about",
"the",
"specified",
"axis",
".",
"<p",
">",
"If",
"<code",
">",
"Q<",
"/",
"code",
">",
"is",
"<code",
">",
"this<",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L2601-L2603 |
ironjacamar/ironjacamar | common/src/main/java/org/ironjacamar/common/metadata/MetadataFactory.java | MetadataFactory.getStandardMetaData | public Connector getStandardMetaData(File root) throws Exception
{
Connector result = null;
File metadataFile = new File(root, "/META-INF/ra.xml");
if (metadataFile.exists())
{
InputStream input = null;
String url = metadataFile.getAbsolutePath();
try
{
long start = System.currentTimeMillis();
input = new FileInputStream(metadataFile);
XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(input);
result = (new RaParser()).parse(xsr);
log.debugf("Total parse for %s took %d ms", url, (System.currentTimeMillis() - start));
}
catch (Exception e)
{
log.parsingErrorRaXml(url, e);
throw e;
}
finally
{
if (input != null)
input.close();
}
}
else
{
log.tracef("metadata file %s does not exist", metadataFile.toString());
}
return result;
} | java | public Connector getStandardMetaData(File root) throws Exception
{
Connector result = null;
File metadataFile = new File(root, "/META-INF/ra.xml");
if (metadataFile.exists())
{
InputStream input = null;
String url = metadataFile.getAbsolutePath();
try
{
long start = System.currentTimeMillis();
input = new FileInputStream(metadataFile);
XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(input);
result = (new RaParser()).parse(xsr);
log.debugf("Total parse for %s took %d ms", url, (System.currentTimeMillis() - start));
}
catch (Exception e)
{
log.parsingErrorRaXml(url, e);
throw e;
}
finally
{
if (input != null)
input.close();
}
}
else
{
log.tracef("metadata file %s does not exist", metadataFile.toString());
}
return result;
} | [
"public",
"Connector",
"getStandardMetaData",
"(",
"File",
"root",
")",
"throws",
"Exception",
"{",
"Connector",
"result",
"=",
"null",
";",
"File",
"metadataFile",
"=",
"new",
"File",
"(",
"root",
",",
"\"/META-INF/ra.xml\"",
")",
";",
"if",
"(",
"metadataFil... | Get the JCA standard metadata
@param root The root of the deployment
@return The metadata
@exception Exception Thrown if an error occurs | [
"Get",
"the",
"JCA",
"standard",
"metadata"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/MetadataFactory.java#L62-L100 |
boncey/Flickr4Java | src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java | PhotosInterface.setDates | public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_SET_DATES);
parameters.put("photo_id", photoId);
if (datePosted != null) {
parameters.put("date_posted", Long.toString(datePosted.getTime() / 1000));
}
if (dateTaken != null) {
parameters.put("date_taken", ((DateFormat) DATE_FORMATS.get()).format(dateTaken));
}
if (dateTakenGranularity != null) {
parameters.put("date_taken_granularity", dateTakenGranularity);
}
Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
} | java | public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_SET_DATES);
parameters.put("photo_id", photoId);
if (datePosted != null) {
parameters.put("date_posted", Long.toString(datePosted.getTime() / 1000));
}
if (dateTaken != null) {
parameters.put("date_taken", ((DateFormat) DATE_FORMATS.get()).format(dateTaken));
}
if (dateTakenGranularity != null) {
parameters.put("date_taken_granularity", dateTakenGranularity);
}
Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
} | [
"public",
"void",
"setDates",
"(",
"String",
"photoId",
",",
"Date",
"datePosted",
",",
"Date",
"dateTaken",
",",
"String",
"dateTakenGranularity",
")",
"throws",
"FlickrException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
"=",
"new",
"Hash... | Set the dates for the specified photo.
This method requires authentication with 'write' permission.
@param photoId
The photo ID
@param datePosted
The date the photo was posted or null
@param dateTaken
The date the photo was taken or null
@param dateTakenGranularity
The granularity of the taken date or null
@throws FlickrException | [
"Set",
"the",
"dates",
"for",
"the",
"specified",
"photo",
"."
] | train | https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java#L1164-L1186 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/util/TaskQueueThread.java | TaskQueueThread.execute | public void execute(Runnable task, long timeoutMillis) throws RejectedExecutionException {
if (task == null) {
throw new NullPointerException("Cannot accept null task");
}
synchronized (this) {
if (mState != STATE_RUNNING && mState != STATE_NOT_STARTED) {
throw new RejectedExecutionException("Task queue is shutdown");
}
}
try {
if (!mQueue.offer(task, timeoutMillis, TimeUnit.MILLISECONDS)) {
throw new RejectedExecutionException("Unable to enqueue task after waiting " +
timeoutMillis + " milliseconds");
}
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
} | java | public void execute(Runnable task, long timeoutMillis) throws RejectedExecutionException {
if (task == null) {
throw new NullPointerException("Cannot accept null task");
}
synchronized (this) {
if (mState != STATE_RUNNING && mState != STATE_NOT_STARTED) {
throw new RejectedExecutionException("Task queue is shutdown");
}
}
try {
if (!mQueue.offer(task, timeoutMillis, TimeUnit.MILLISECONDS)) {
throw new RejectedExecutionException("Unable to enqueue task after waiting " +
timeoutMillis + " milliseconds");
}
} catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
} | [
"public",
"void",
"execute",
"(",
"Runnable",
"task",
",",
"long",
"timeoutMillis",
")",
"throws",
"RejectedExecutionException",
"{",
"if",
"(",
"task",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Cannot accept null task\"",
")",
";",
... | Enqueue a task to run.
@param task task to enqueue
@param timeoutMillis maximum time to wait for queue to have an available slot
@throws RejectedExecutionException if wait interrupted, timeout expires,
or shutdown has been called | [
"Enqueue",
"a",
"task",
"to",
"run",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/util/TaskQueueThread.java#L85-L102 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java | TypeUtility.typeName | public static TypeName typeName(TypeElement element, String suffix) {
String fullName = element.getQualifiedName().toString() + suffix;
int lastIndex = fullName.lastIndexOf(".");
String packageName = fullName.substring(0, lastIndex);
String className = fullName.substring(lastIndex + 1);
return typeName(packageName, className);
} | java | public static TypeName typeName(TypeElement element, String suffix) {
String fullName = element.getQualifiedName().toString() + suffix;
int lastIndex = fullName.lastIndexOf(".");
String packageName = fullName.substring(0, lastIndex);
String className = fullName.substring(lastIndex + 1);
return typeName(packageName, className);
} | [
"public",
"static",
"TypeName",
"typeName",
"(",
"TypeElement",
"element",
",",
"String",
"suffix",
")",
"{",
"String",
"fullName",
"=",
"element",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
"+",
"suffix",
";",
"int",
"lastIndex",
"=",
"... | Type name.
@param element
the element
@param suffix
the suffix
@return the type name | [
"Type",
"name",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java#L488-L497 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/TransformXMLInterceptor.java | TransformXMLInterceptor.newTransformer | private static Transformer newTransformer() {
if (TEMPLATES == null) {
throw new IllegalStateException("TransformXMLInterceptor not initialized.");
}
try {
return TEMPLATES.newTransformer();
} catch (TransformerConfigurationException ex) {
throw new SystemException("Could not create transformer for " + RESOURCE_NAME, ex);
}
} | java | private static Transformer newTransformer() {
if (TEMPLATES == null) {
throw new IllegalStateException("TransformXMLInterceptor not initialized.");
}
try {
return TEMPLATES.newTransformer();
} catch (TransformerConfigurationException ex) {
throw new SystemException("Could not create transformer for " + RESOURCE_NAME, ex);
}
} | [
"private",
"static",
"Transformer",
"newTransformer",
"(",
")",
"{",
"if",
"(",
"TEMPLATES",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"TransformXMLInterceptor not initialized.\"",
")",
";",
"}",
"try",
"{",
"return",
"TEMPLATES",
"."... | Creates a new Transformer instance using cached XSLT Templates. There will be one cached template. Transformer
instances are not thread-safe and cannot be reused (they can after the transformation is complete).
@return A new Transformer instance. | [
"Creates",
"a",
"new",
"Transformer",
"instance",
"using",
"cached",
"XSLT",
"Templates",
".",
"There",
"will",
"be",
"one",
"cached",
"template",
".",
"Transformer",
"instances",
"are",
"not",
"thread",
"-",
"safe",
"and",
"cannot",
"be",
"reused",
"(",
"th... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/TransformXMLInterceptor.java#L203-L214 |
jasminb/jsonapi-converter | src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java | ResourceConverter.readObject | @Deprecated
public <T> T readObject(byte [] data, Class<T> clazz) {
return readDocument(data, clazz).get();
} | java | @Deprecated
public <T> T readObject(byte [] data, Class<T> clazz) {
return readDocument(data, clazz).get();
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"T",
"readObject",
"(",
"byte",
"[",
"]",
"data",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"return",
"readDocument",
"(",
"data",
",",
"clazz",
")",
".",
"get",
"(",
")",
";",
"}"
] | Converts raw data input into requested target type.
@param data raw data
@param clazz target object
@param <T> type
@return converted object
@throws RuntimeException in case conversion fails | [
"Converts",
"raw",
"data",
"input",
"into",
"requested",
"target",
"type",
"."
] | train | https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java#L148-L151 |
code4everything/util | src/main/java/com/zhazhapan/util/Checker.java | Checker.isIn | public static <T> boolean isIn(T t, List<T> ts) {
return isIn(t, ts.toArray());
} | java | public static <T> boolean isIn(T t, List<T> ts) {
return isIn(t, ts.toArray());
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"isIn",
"(",
"T",
"t",
",",
"List",
"<",
"T",
">",
"ts",
")",
"{",
"return",
"isIn",
"(",
"t",
",",
"ts",
".",
"toArray",
"(",
")",
")",
";",
"}"
] | 检查对象是否在集合中
@param <T> 类型
@param t 对象
@param ts 集合
@return 是否存在
@since 1.0.8 | [
"检查对象是否在集合中"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L641-L643 |
alkacon/opencms-core | src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java | CmsSitemapView.initiateTreeItems | void initiateTreeItems(FlowPanel page, Label loadingLabel) {
CmsSitemapTreeItem rootItem = getRootItem();
m_controller.addPropertyUpdateHandler(new CmsStatusIconUpdateHandler());
m_controller.recomputeProperties();
rootItem.updateSitePath();
// check if editable
if (!m_controller.isEditable()) {
// notify user
CmsNotification.get().sendSticky(
CmsNotification.Type.WARNING,
Messages.get().key(Messages.GUI_NO_EDIT_NOTIFICATION_1, m_controller.getData().getNoEditReason()));
}
String openPath = m_controller.getData().getOpenPath();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(openPath)) {
m_openHandler.setInitializing(true);
openItemsOnPath(openPath);
m_openHandler.setInitializing(false);
}
page.remove(loadingLabel);
} | java | void initiateTreeItems(FlowPanel page, Label loadingLabel) {
CmsSitemapTreeItem rootItem = getRootItem();
m_controller.addPropertyUpdateHandler(new CmsStatusIconUpdateHandler());
m_controller.recomputeProperties();
rootItem.updateSitePath();
// check if editable
if (!m_controller.isEditable()) {
// notify user
CmsNotification.get().sendSticky(
CmsNotification.Type.WARNING,
Messages.get().key(Messages.GUI_NO_EDIT_NOTIFICATION_1, m_controller.getData().getNoEditReason()));
}
String openPath = m_controller.getData().getOpenPath();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(openPath)) {
m_openHandler.setInitializing(true);
openItemsOnPath(openPath);
m_openHandler.setInitializing(false);
}
page.remove(loadingLabel);
} | [
"void",
"initiateTreeItems",
"(",
"FlowPanel",
"page",
",",
"Label",
"loadingLabel",
")",
"{",
"CmsSitemapTreeItem",
"rootItem",
"=",
"getRootItem",
"(",
")",
";",
"m_controller",
".",
"addPropertyUpdateHandler",
"(",
"new",
"CmsStatusIconUpdateHandler",
"(",
")",
"... | Builds the tree items initially.<p>
@param page the page
@param loadingLabel the loading label, will be removed when finished | [
"Builds",
"the",
"tree",
"items",
"initially",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java#L1490-L1510 |
logic-ng/LogicNG | src/main/java/org/logicng/collections/LNGVector.java | LNGVector.selectionSort | private void selectionSort(final T[] array, int start, int end, Comparator<T> lt) {
int i;
int j;
int bestI;
T tmp;
for (i = start; i < end; i++) {
bestI = i;
for (j = i + 1; j < end; j++) {
if (lt.compare(array[j], array[bestI]) < 0)
bestI = j;
}
tmp = array[i];
array[i] = array[bestI];
array[bestI] = tmp;
}
} | java | private void selectionSort(final T[] array, int start, int end, Comparator<T> lt) {
int i;
int j;
int bestI;
T tmp;
for (i = start; i < end; i++) {
bestI = i;
for (j = i + 1; j < end; j++) {
if (lt.compare(array[j], array[bestI]) < 0)
bestI = j;
}
tmp = array[i];
array[i] = array[bestI];
array[bestI] = tmp;
}
} | [
"private",
"void",
"selectionSort",
"(",
"final",
"T",
"[",
"]",
"array",
",",
"int",
"start",
",",
"int",
"end",
",",
"Comparator",
"<",
"T",
">",
"lt",
")",
"{",
"int",
"i",
";",
"int",
"j",
";",
"int",
"bestI",
";",
"T",
"tmp",
";",
"for",
"... | Selection sort implementation for a given array.
@param array the array
@param start the start index for sorting
@param end the end index for sorting
@param lt the comparator for elements of the array | [
"Selection",
"sort",
"implementation",
"for",
"a",
"given",
"array",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/collections/LNGVector.java#L288-L303 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/users/ExtensionUserManagement.java | ExtensionUserManagement.addSharedContextUser | public void addSharedContextUser(Context sharedContext, User user) {
this.getContextPanel(sharedContext.getIndex()).getUsersTableModel().addUser(user);
} | java | public void addSharedContextUser(Context sharedContext, User user) {
this.getContextPanel(sharedContext.getIndex()).getUsersTableModel().addUser(user);
} | [
"public",
"void",
"addSharedContextUser",
"(",
"Context",
"sharedContext",
",",
"User",
"user",
")",
"{",
"this",
".",
"getContextPanel",
"(",
"sharedContext",
".",
"getIndex",
"(",
")",
")",
".",
"getUsersTableModel",
"(",
")",
".",
"addUser",
"(",
"user",
... | Add a new user shown in the UI (for the Users context panel) that corresponds
to a particular shared Context.
@param sharedContext the shared context
@param user the user | [
"Add",
"a",
"new",
"user",
"shown",
"in",
"the",
"UI",
"(",
"for",
"the",
"Users",
"context",
"panel",
")",
"that",
"corresponds",
"to",
"a",
"particular",
"shared",
"Context",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/users/ExtensionUserManagement.java#L296-L298 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/quotes/OrderItemUrl.java | OrderItemUrl.updateQuoteItemUrl | public static MozuUrl updateQuoteItemUrl(String quoteId, String quoteItemId, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/{quoteId}/items/{quoteItemId}?responseFields={responseFields}");
formatter.formatUrl("quoteId", quoteId);
formatter.formatUrl("quoteItemId", quoteItemId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl updateQuoteItemUrl(String quoteId, String quoteItemId, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/{quoteId}/items/{quoteItemId}?responseFields={responseFields}");
formatter.formatUrl("quoteId", quoteId);
formatter.formatUrl("quoteItemId", quoteItemId);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"updateQuoteItemUrl",
"(",
"String",
"quoteId",
",",
"String",
"quoteItemId",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/quotes/{quoteId}/items/{quoteItemId}?respon... | Get Resource Url for UpdateQuoteItem
@param quoteId
@param quoteItemId
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"UpdateQuoteItem"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/quotes/OrderItemUrl.java#L99-L106 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java | Validator.validateNull | public void validateNull(Object object, String name) {
validateNull(object, name, messages.get(Validation.NULL_KEY.name(), name));
} | java | public void validateNull(Object object, String name) {
validateNull(object, name, messages.get(Validation.NULL_KEY.name(), name));
} | [
"public",
"void",
"validateNull",
"(",
"Object",
"object",
",",
"String",
"name",
")",
"{",
"validateNull",
"(",
"object",
",",
"name",
",",
"messages",
".",
"get",
"(",
"Validation",
".",
"NULL_KEY",
".",
"name",
"(",
")",
",",
"name",
")",
")",
";",
... | Validates a given object to be null
@param object The object to check
@param name The name of the field to display the error message | [
"Validates",
"a",
"given",
"object",
"to",
"be",
"null"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L511-L513 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X500Name.java | X500Name.getRFC2253Name | public String getRFC2253Name(Map<String, String> oidMap) {
/* check for and return cached name */
if (oidMap.isEmpty()) {
if (rfc2253Dn != null) {
return rfc2253Dn;
} else {
rfc2253Dn = generateRFC2253DN(oidMap);
return rfc2253Dn;
}
}
return generateRFC2253DN(oidMap);
} | java | public String getRFC2253Name(Map<String, String> oidMap) {
/* check for and return cached name */
if (oidMap.isEmpty()) {
if (rfc2253Dn != null) {
return rfc2253Dn;
} else {
rfc2253Dn = generateRFC2253DN(oidMap);
return rfc2253Dn;
}
}
return generateRFC2253DN(oidMap);
} | [
"public",
"String",
"getRFC2253Name",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"oidMap",
")",
"{",
"/* check for and return cached name */",
"if",
"(",
"oidMap",
".",
"isEmpty",
"(",
")",
")",
"{",
"if",
"(",
"rfc2253Dn",
"!=",
"null",
")",
"{",
"ret... | Returns a string form of the X.500 distinguished name
using the algorithm defined in RFC 2253. Attribute type
keywords defined in RFC 2253 are emitted, as well as additional
keywords contained in the OID/keyword map. | [
"Returns",
"a",
"string",
"form",
"of",
"the",
"X",
".",
"500",
"distinguished",
"name",
"using",
"the",
"algorithm",
"defined",
"in",
"RFC",
"2253",
".",
"Attribute",
"type",
"keywords",
"defined",
"in",
"RFC",
"2253",
"are",
"emitted",
"as",
"well",
"as"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X500Name.java#L665-L676 |
lessthanoptimal/ejml | main/ejml-simple/src/org/ejml/simple/SimpleMatrix.java | SimpleMatrix.randomNormal | public static SimpleMatrix randomNormal( SimpleMatrix covariance , Random random ) {
SimpleMatrix found = new SimpleMatrix(covariance.numRows(), 1,covariance.getType());
switch( found.getType() ) {
case DDRM:{
CovarianceRandomDraw_DDRM draw = new CovarianceRandomDraw_DDRM(random, (DMatrixRMaj)covariance.getMatrix());
draw.next((DMatrixRMaj)found.getMatrix());
}break;
case FDRM:{
CovarianceRandomDraw_FDRM draw = new CovarianceRandomDraw_FDRM(random, (FMatrixRMaj)covariance.getMatrix());
draw.next((FMatrixRMaj)found.getMatrix());
}break;
default:
throw new IllegalArgumentException("Matrix type is currently not supported");
}
return found;
} | java | public static SimpleMatrix randomNormal( SimpleMatrix covariance , Random random ) {
SimpleMatrix found = new SimpleMatrix(covariance.numRows(), 1,covariance.getType());
switch( found.getType() ) {
case DDRM:{
CovarianceRandomDraw_DDRM draw = new CovarianceRandomDraw_DDRM(random, (DMatrixRMaj)covariance.getMatrix());
draw.next((DMatrixRMaj)found.getMatrix());
}break;
case FDRM:{
CovarianceRandomDraw_FDRM draw = new CovarianceRandomDraw_FDRM(random, (FMatrixRMaj)covariance.getMatrix());
draw.next((FMatrixRMaj)found.getMatrix());
}break;
default:
throw new IllegalArgumentException("Matrix type is currently not supported");
}
return found;
} | [
"public",
"static",
"SimpleMatrix",
"randomNormal",
"(",
"SimpleMatrix",
"covariance",
",",
"Random",
"random",
")",
"{",
"SimpleMatrix",
"found",
"=",
"new",
"SimpleMatrix",
"(",
"covariance",
".",
"numRows",
"(",
")",
",",
"1",
",",
"covariance",
".",
"getTy... | <p>
Creates a new vector which is drawn from a multivariate normal distribution with zero mean
and the provided covariance.
</p>
@see CovarianceRandomDraw_DDRM
@param covariance Covariance of the multivariate normal distribution
@return Vector randomly drawn from the distribution | [
"<p",
">",
"Creates",
"a",
"new",
"vector",
"which",
"is",
"drawn",
"from",
"a",
"multivariate",
"normal",
"distribution",
"with",
"zero",
"mean",
"and",
"the",
"provided",
"covariance",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/simple/SimpleMatrix.java#L313-L335 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/SimulatedTaskRunner.java | SimulatedTaskRunner.addTipToFinish | protected void addTipToFinish(TaskInProgress tip,
TaskUmbilicalProtocol umbilicalProtocol) {
long currentTime = System.currentTimeMillis();
long finishTime = currentTime + Math.abs(rand.nextLong()) %
timeToFinishTask;
LOG.info("Adding TIP " + tip.getTask().getTaskID() +
" to finishing queue with start time " +
currentTime + " and finish time " + finishTime +
" (" + ((finishTime - currentTime) / 1000.0) + " sec) to thread " +
getName());
TipToFinish ttf = new TipToFinish(tip, finishTime, umbilicalProtocol);
tipQueue.put(ttf);
// Interrupt the waiting thread. We could put in additional logic to only
// interrupt when necessary, but probably not worth the complexity.
this.interrupt();
} | java | protected void addTipToFinish(TaskInProgress tip,
TaskUmbilicalProtocol umbilicalProtocol) {
long currentTime = System.currentTimeMillis();
long finishTime = currentTime + Math.abs(rand.nextLong()) %
timeToFinishTask;
LOG.info("Adding TIP " + tip.getTask().getTaskID() +
" to finishing queue with start time " +
currentTime + " and finish time " + finishTime +
" (" + ((finishTime - currentTime) / 1000.0) + " sec) to thread " +
getName());
TipToFinish ttf = new TipToFinish(tip, finishTime, umbilicalProtocol);
tipQueue.put(ttf);
// Interrupt the waiting thread. We could put in additional logic to only
// interrupt when necessary, but probably not worth the complexity.
this.interrupt();
} | [
"protected",
"void",
"addTipToFinish",
"(",
"TaskInProgress",
"tip",
",",
"TaskUmbilicalProtocol",
"umbilicalProtocol",
")",
"{",
"long",
"currentTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"finishTime",
"=",
"currentTime",
"+",
"Math",
... | Add the specified TaskInProgress to the priority queue of tasks to finish.
@param tip
@param umbilicalProtocol | [
"Add",
"the",
"specified",
"TaskInProgress",
"to",
"the",
"priority",
"queue",
"of",
"tasks",
"to",
"finish",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/SimulatedTaskRunner.java#L169-L184 |
geomajas/geomajas-project-client-gwt2 | impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java | JsonService.getChildArray | public static JSONArray getChildArray(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null) {
if (value.isArray() != null) {
return value.isArray();
} else if (value.isNull() != null) {
return null;
}
throw new JSONException("Child is not a JSONArray, but a: " + value.getClass());
}
return null;
} | java | public static JSONArray getChildArray(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null) {
if (value.isArray() != null) {
return value.isArray();
} else if (value.isNull() != null) {
return null;
}
throw new JSONException("Child is not a JSONArray, but a: " + value.getClass());
}
return null;
} | [
"public",
"static",
"JSONArray",
"getChildArray",
"(",
"JSONObject",
"jsonObject",
",",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"checkArguments",
"(",
"jsonObject",
",",
"key",
")",
";",
"JSONValue",
"value",
"=",
"jsonObject",
".",
"get",
"(",
"... | Get a child JSON array from a parent JSON object.
@param jsonObject The parent JSON object.
@param key The name of the child object.
@return Returns the child JSON array if it could be found, or null if the value was null.
@throws JSONException In case something went wrong while searching for the child. | [
"Get",
"a",
"child",
"JSON",
"array",
"from",
"a",
"parent",
"JSON",
"object",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L116-L128 |
Erudika/para | para-client/src/main/java/com/erudika/para/client/ParaClient.java | ParaClient.findSimilar | public <P extends ParaObject> List<P> findSimilar(String type, String filterKey, String[] fields, String liketext,
Pager... pager) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.put("fields", fields == null ? null : Arrays.asList(fields));
params.putSingle("filterid", filterKey);
params.putSingle("like", liketext);
params.putSingle(Config._TYPE, type);
params.putAll(pagerToParams(pager));
return getItems(find("similar", params), pager);
} | java | public <P extends ParaObject> List<P> findSimilar(String type, String filterKey, String[] fields, String liketext,
Pager... pager) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.put("fields", fields == null ? null : Arrays.asList(fields));
params.putSingle("filterid", filterKey);
params.putSingle("like", liketext);
params.putSingle(Config._TYPE, type);
params.putAll(pagerToParams(pager));
return getItems(find("similar", params), pager);
} | [
"public",
"<",
"P",
"extends",
"ParaObject",
">",
"List",
"<",
"P",
">",
"findSimilar",
"(",
"String",
"type",
",",
"String",
"filterKey",
",",
"String",
"[",
"]",
"fields",
",",
"String",
"liketext",
",",
"Pager",
"...",
"pager",
")",
"{",
"MultivaluedM... | Searches for objects that have similar property values to a given text. A "find like this" query.
@param <P> type of the object
@param type the type of object to search for. See {@link com.erudika.para.core.ParaObject#getType()}
@param filterKey exclude an object with this key from the results (optional)
@param fields a list of property names
@param liketext text to compare to
@param pager a {@link com.erudika.para.utils.Pager}
@return a list of objects found | [
"Searches",
"for",
"objects",
"that",
"have",
"similar",
"property",
"values",
"to",
"a",
"given",
"text",
".",
"A",
"find",
"like",
"this",
"query",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L761-L770 |
greenmail-mail-test/greenmail | greenmail-spring/src/main/java/com/icegreen/greenmail/spring/GreenMailBean.java | GreenMailBean.sendEmail | public void sendEmail(final String theTo, final String theFrom, final String theSubject,
final String theContent) {
if (null == smtpServerSetup) {
throw new IllegalStateException("Can not send mail, no SMTP or SMTPS setup found");
}
GreenMailUtil.sendTextEmail(theTo, theFrom, theSubject, theContent, smtpServerSetup);
} | java | public void sendEmail(final String theTo, final String theFrom, final String theSubject,
final String theContent) {
if (null == smtpServerSetup) {
throw new IllegalStateException("Can not send mail, no SMTP or SMTPS setup found");
}
GreenMailUtil.sendTextEmail(theTo, theFrom, theSubject, theContent, smtpServerSetup);
} | [
"public",
"void",
"sendEmail",
"(",
"final",
"String",
"theTo",
",",
"final",
"String",
"theFrom",
",",
"final",
"String",
"theSubject",
",",
"final",
"String",
"theContent",
")",
"{",
"if",
"(",
"null",
"==",
"smtpServerSetup",
")",
"{",
"throw",
"new",
"... | Sends a mail message to the GreenMail server.
<p/>
Note: SMTP or SMTPS must be configured.
@param theTo the <em>TO</em> field.
@param theFrom the <em>FROM</em>field.
@param theSubject the subject.
@param theContent the message content. | [
"Sends",
"a",
"mail",
"message",
"to",
"the",
"GreenMail",
"server",
".",
"<p",
"/",
">",
"Note",
":",
"SMTP",
"or",
"SMTPS",
"must",
"be",
"configured",
"."
] | train | https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-spring/src/main/java/com/icegreen/greenmail/spring/GreenMailBean.java#L395-L401 |
messagebird/java-rest-api | api/src/main/java/com/messagebird/MessageBirdClient.java | MessageBirdClient.deleteGroupContact | public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException {
if (groupId == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
if (contactId == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId);
messageBirdService.deleteByID(GROUPPATH, id);
} | java | public void deleteGroupContact(final String groupId, final String contactId) throws NotFoundException, GeneralException, UnauthorizedException {
if (groupId == null) {
throw new IllegalArgumentException("Group ID must be specified.");
}
if (contactId == null) {
throw new IllegalArgumentException("Contact ID must be specified.");
}
String id = String.format("%s%s/%s", groupId, CONTACTPATH, contactId);
messageBirdService.deleteByID(GROUPPATH, id);
} | [
"public",
"void",
"deleteGroupContact",
"(",
"final",
"String",
"groupId",
",",
"final",
"String",
"contactId",
")",
"throws",
"NotFoundException",
",",
"GeneralException",
",",
"UnauthorizedException",
"{",
"if",
"(",
"groupId",
"==",
"null",
")",
"{",
"throw",
... | Removes a contact from group. You need to supply the IDs of the group
and contact. Does not delete the contact. | [
"Removes",
"a",
"contact",
"from",
"group",
".",
"You",
"need",
"to",
"supply",
"the",
"IDs",
"of",
"the",
"group",
"and",
"contact",
".",
"Does",
"not",
"delete",
"the",
"contact",
"."
] | train | https://github.com/messagebird/java-rest-api/blob/f92cd93afff413e6dc12aa6e41e69f26cbae8941/api/src/main/java/com/messagebird/MessageBirdClient.java#L613-L623 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/Utils4J.java | Utils4J.getRelativePath | public static String getRelativePath(final File baseDir, final File dir) {
checkNotNull("baseDir", baseDir);
checkNotNull("dir", dir);
final String base = getCanonicalPath(baseDir);
final String path = getCanonicalPath(dir);
if (!path.startsWith(base)) {
throw new IllegalArgumentException("The path '" + path + "' is not inside the base directory '" + base + "'!");
}
if (base.equals(path)) {
return "";
}
return path.substring(base.length() + 1);
} | java | public static String getRelativePath(final File baseDir, final File dir) {
checkNotNull("baseDir", baseDir);
checkNotNull("dir", dir);
final String base = getCanonicalPath(baseDir);
final String path = getCanonicalPath(dir);
if (!path.startsWith(base)) {
throw new IllegalArgumentException("The path '" + path + "' is not inside the base directory '" + base + "'!");
}
if (base.equals(path)) {
return "";
}
return path.substring(base.length() + 1);
} | [
"public",
"static",
"String",
"getRelativePath",
"(",
"final",
"File",
"baseDir",
",",
"final",
"File",
"dir",
")",
"{",
"checkNotNull",
"(",
"\"baseDir\"",
",",
"baseDir",
")",
";",
"checkNotNull",
"(",
"\"dir\"",
",",
"dir",
")",
";",
"final",
"String",
... | Returns a relative path based on a base directory. If the <code>dir</code> is not inside <code>baseDir</code> an
<code>IllegalArgumentException</code> is thrown.
@param baseDir
Base directory the path is relative to - Cannot be <code>null</code>.
@param dir
Directory inside the base directory - Cannot be <code>null</code>.
@return Path of <code>dir</code> relative to <code>baseDir</code>. If both are equal an empty string is returned. | [
"Returns",
"a",
"relative",
"path",
"based",
"on",
"a",
"base",
"directory",
".",
"If",
"the",
"<code",
">",
"dir<",
"/",
"code",
">",
"is",
"not",
"inside",
"<code",
">",
"baseDir<",
"/",
"code",
">",
"an",
"<code",
">",
"IllegalArgumentException<",
"/"... | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L508-L521 |
sarl/sarl | main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/dialog/SARLAgentMainLaunchConfigurationTab.java | SARLAgentMainLaunchConfigurationTab.initializeAgentName | protected void initializeAgentName(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
String name = extractNameFromJavaElement(javaElement);
// Set the attribute
this.configurator.setAgent(config, name);
// Rename the launch configuration
if (name.length() > 0) {
final int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(index + 1);
}
name = getLaunchConfigurationDialog().generateName(name);
config.rename(name);
}
} | java | protected void initializeAgentName(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
String name = extractNameFromJavaElement(javaElement);
// Set the attribute
this.configurator.setAgent(config, name);
// Rename the launch configuration
if (name.length() > 0) {
final int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(index + 1);
}
name = getLaunchConfigurationDialog().generateName(name);
config.rename(name);
}
} | [
"protected",
"void",
"initializeAgentName",
"(",
"IJavaElement",
"javaElement",
",",
"ILaunchConfigurationWorkingCopy",
"config",
")",
"{",
"String",
"name",
"=",
"extractNameFromJavaElement",
"(",
"javaElement",
")",
";",
"// Set the attribute",
"this",
".",
"configurato... | Reset the given configuration with the agent name attributes associated
to the given element.
@param javaElement the element from which information may be retrieved.
@param config the config to set with the agent name. | [
"Reset",
"the",
"given",
"configuration",
"with",
"the",
"agent",
"name",
"attributes",
"associated",
"to",
"the",
"given",
"element",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/dialog/SARLAgentMainLaunchConfigurationTab.java#L473-L488 |
JodaOrg/joda-time | src/main/java/org/joda/time/Period.java | Period.plusYears | public Period plusYears(int years) {
if (years == 0) {
return this;
}
int[] values = getValues(); // cloned
getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, years);
return new Period(values, getPeriodType());
} | java | public Period plusYears(int years) {
if (years == 0) {
return this;
}
int[] values = getValues(); // cloned
getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, years);
return new Period(values, getPeriodType());
} | [
"public",
"Period",
"plusYears",
"(",
"int",
"years",
")",
"{",
"if",
"(",
"years",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"int",
"[",
"]",
"values",
"=",
"getValues",
"(",
")",
";",
"// cloned",
"getPeriodType",
"(",
")",
".",
"addIndexedF... | Returns a new period with the specified number of years added.
<p>
This period instance is immutable and unaffected by this method call.
@param years the amount of years to add, may be negative
@return the new period with the increased years
@throws UnsupportedOperationException if the field is not supported | [
"Returns",
"a",
"new",
"period",
"with",
"the",
"specified",
"number",
"of",
"years",
"added",
".",
"<p",
">",
"This",
"period",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Period.java#L1069-L1076 |
redisson/redisson | redisson/src/main/java/org/redisson/misc/HighwayHash.java | HighwayHash.updatePacket | public void updatePacket(byte[] packet, int pos) {
if (pos < 0) {
throw new IllegalArgumentException(String.format("Pos (%s) must be positive", pos));
}
if (pos + 32 > packet.length) {
throw new IllegalArgumentException("packet must have at least 32 bytes after pos");
}
long a0 = read64(packet, pos + 0);
long a1 = read64(packet, pos + 8);
long a2 = read64(packet, pos + 16);
long a3 = read64(packet, pos + 24);
update(a0, a1, a2, a3);
} | java | public void updatePacket(byte[] packet, int pos) {
if (pos < 0) {
throw new IllegalArgumentException(String.format("Pos (%s) must be positive", pos));
}
if (pos + 32 > packet.length) {
throw new IllegalArgumentException("packet must have at least 32 bytes after pos");
}
long a0 = read64(packet, pos + 0);
long a1 = read64(packet, pos + 8);
long a2 = read64(packet, pos + 16);
long a3 = read64(packet, pos + 24);
update(a0, a1, a2, a3);
} | [
"public",
"void",
"updatePacket",
"(",
"byte",
"[",
"]",
"packet",
",",
"int",
"pos",
")",
"{",
"if",
"(",
"pos",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"Pos (%s) must be positive\"",
",",
"pos"... | Updates the hash with 32 bytes of data. If you can read 4 long values
from your data efficiently, prefer using update() instead for more speed.
@param packet data array which has a length of at least pos + 32
@param pos position in the array to read the first of 32 bytes from | [
"Updates",
"the",
"hash",
"with",
"32",
"bytes",
"of",
"data",
".",
"If",
"you",
"can",
"read",
"4",
"long",
"values",
"from",
"your",
"data",
"efficiently",
"prefer",
"using",
"update",
"()",
"instead",
"for",
"more",
"speed",
"."
] | train | https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/misc/HighwayHash.java#L56-L68 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/RouteFiltersInner.java | RouteFiltersInner.beginCreateOrUpdateAsync | public Observable<RouteFilterInner> beginCreateOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
} | java | public Observable<RouteFilterInner> beginCreateOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RouteFilterInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"routeFilterName",
",",
"RouteFilterInner",
"routeFilterParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"r... | Creates or updates a route filter in a specified resource group.
@param resourceGroupName The name of the resource group.
@param routeFilterName The name of the route filter.
@param routeFilterParameters Parameters supplied to the create or update route filter operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RouteFilterInner object | [
"Creates",
"or",
"updates",
"a",
"route",
"filter",
"in",
"a",
"specified",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/RouteFiltersInner.java#L545-L552 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/h/HomographyInducedStereoLinePt.java | HomographyInducedStereoLinePt.setFundamental | public void setFundamental( DMatrixRMaj F , Point3D_F64 e2 ) {
this.F = F;
if( e2 != null )
this.e2.set(e2);
else {
MultiViewOps.extractEpipoles(F,new Point3D_F64(),this.e2);
}
} | java | public void setFundamental( DMatrixRMaj F , Point3D_F64 e2 ) {
this.F = F;
if( e2 != null )
this.e2.set(e2);
else {
MultiViewOps.extractEpipoles(F,new Point3D_F64(),this.e2);
}
} | [
"public",
"void",
"setFundamental",
"(",
"DMatrixRMaj",
"F",
",",
"Point3D_F64",
"e2",
")",
"{",
"this",
".",
"F",
"=",
"F",
";",
"if",
"(",
"e2",
"!=",
"null",
")",
"this",
".",
"e2",
".",
"set",
"(",
"e2",
")",
";",
"else",
"{",
"MultiViewOps",
... | Specify the fundamental matrix and the camera 2 epipole.
@param F Fundamental matrix.
@param e2 Epipole for camera 2. If null it will be computed internally. | [
"Specify",
"the",
"fundamental",
"matrix",
"and",
"the",
"camera",
"2",
"epipole",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/h/HomographyInducedStereoLinePt.java#L79-L86 |
whizzosoftware/WZWave | src/main/java/com/whizzosoftware/wzwave/channel/TransactionInboundHandler.java | TransactionInboundHandler.channelRead | @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof Frame) {
Frame frame = (Frame) msg;
if (hasCurrentTransaction()) {
String tid = currentDataFrameTransaction.getId();
logger.trace("Received frame within transaction ({}) context: {}", tid, frame);
// give new frame to current transaction
NettyZWaveChannelContext zctx = new NettyZWaveChannelContext();
if (currentDataFrameTransaction.addFrame(zctx, frame)) {
if (currentDataFrameTransaction.isComplete()) {
logger.trace("*** Data frame transaction ({}) completed", tid);
logger.trace("");
cancelTimeoutCallback();
}
zctx.process(ctx);
// if transaction didn't consume frame, then pass it down the pipeline
} else {
logger.trace("Transaction ignored frame so passing it along");
ctx.fireChannelRead(msg);
}
} else if (msg instanceof AddNodeToNetwork) {
logger.trace("Received ADD_NODE_STATUS_NODE_FOUND; starting transaction");
NettyZWaveChannelContext zctx = new NettyZWaveChannelContext();
currentDataFrameTransaction = new NodeInclusionTransaction(zctx, (DataFrame)msg);
zctx.process(ctx);
} else {
logger.trace("Received frame outside of transaction context so passing it along: {}", frame);
ctx.fireChannelRead(msg);
}
}
} | java | @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof Frame) {
Frame frame = (Frame) msg;
if (hasCurrentTransaction()) {
String tid = currentDataFrameTransaction.getId();
logger.trace("Received frame within transaction ({}) context: {}", tid, frame);
// give new frame to current transaction
NettyZWaveChannelContext zctx = new NettyZWaveChannelContext();
if (currentDataFrameTransaction.addFrame(zctx, frame)) {
if (currentDataFrameTransaction.isComplete()) {
logger.trace("*** Data frame transaction ({}) completed", tid);
logger.trace("");
cancelTimeoutCallback();
}
zctx.process(ctx);
// if transaction didn't consume frame, then pass it down the pipeline
} else {
logger.trace("Transaction ignored frame so passing it along");
ctx.fireChannelRead(msg);
}
} else if (msg instanceof AddNodeToNetwork) {
logger.trace("Received ADD_NODE_STATUS_NODE_FOUND; starting transaction");
NettyZWaveChannelContext zctx = new NettyZWaveChannelContext();
currentDataFrameTransaction = new NodeInclusionTransaction(zctx, (DataFrame)msg);
zctx.process(ctx);
} else {
logger.trace("Received frame outside of transaction context so passing it along: {}", frame);
ctx.fireChannelRead(msg);
}
}
} | [
"@",
"Override",
"public",
"void",
"channelRead",
"(",
"ChannelHandlerContext",
"ctx",
",",
"Object",
"msg",
")",
"{",
"if",
"(",
"msg",
"instanceof",
"Frame",
")",
"{",
"Frame",
"frame",
"=",
"(",
"Frame",
")",
"msg",
";",
"if",
"(",
"hasCurrentTransactio... | Called when data is read from the Z-Wave network.
@param ctx the handler context
@param msg the message that was read | [
"Called",
"when",
"data",
"is",
"read",
"from",
"the",
"Z",
"-",
"Wave",
"network",
"."
] | train | https://github.com/whizzosoftware/WZWave/blob/b9dfec6b55515226edf9d772a89933b336397501/src/main/java/com/whizzosoftware/wzwave/channel/TransactionInboundHandler.java#L50-L82 |
menacher/java-game-server | jetserver/src/main/java/org/menacheri/jetserver/concurrent/Fibers.java | Fibers.pooledFiber | public static Fiber pooledFiber(Lane<String,ExecutorService> lane)
{
if(null == lanePoolFactoryMap.get(lane))
{
lanePoolFactoryMap.putIfAbsent(lane, new PoolFiberFactory(lane.getUnderlyingLane()));
}
Fiber fiber = lanePoolFactoryMap.get(lane).create();
fiber.start();
return fiber;
} | java | public static Fiber pooledFiber(Lane<String,ExecutorService> lane)
{
if(null == lanePoolFactoryMap.get(lane))
{
lanePoolFactoryMap.putIfAbsent(lane, new PoolFiberFactory(lane.getUnderlyingLane()));
}
Fiber fiber = lanePoolFactoryMap.get(lane).create();
fiber.start();
return fiber;
} | [
"public",
"static",
"Fiber",
"pooledFiber",
"(",
"Lane",
"<",
"String",
",",
"ExecutorService",
">",
"lane",
")",
"{",
"if",
"(",
"null",
"==",
"lanePoolFactoryMap",
".",
"get",
"(",
"lane",
")",
")",
"{",
"lanePoolFactoryMap",
".",
"putIfAbsent",
"(",
"la... | Creates and starts a fiber and returns the created instance.
@return The created fiber. | [
"Creates",
"and",
"starts",
"a",
"fiber",
"and",
"returns",
"the",
"created",
"instance",
"."
] | train | https://github.com/menacher/java-game-server/blob/668ca49e8bd1dac43add62378cf6c22a93125d48/jetserver/src/main/java/org/menacheri/jetserver/concurrent/Fibers.java#L52-L62 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/string/Levenshtein.java | Levenshtein.weightedLevenshtein | public static <T extends Levenshtein> T weightedLevenshtein(String baseTarget, CharacterSubstitution characterSubstitution) {
return weightedLevenshtein(baseTarget, null, characterSubstitution);
} | java | public static <T extends Levenshtein> T weightedLevenshtein(String baseTarget, CharacterSubstitution characterSubstitution) {
return weightedLevenshtein(baseTarget, null, characterSubstitution);
} | [
"public",
"static",
"<",
"T",
"extends",
"Levenshtein",
">",
"T",
"weightedLevenshtein",
"(",
"String",
"baseTarget",
",",
"CharacterSubstitution",
"characterSubstitution",
")",
"{",
"return",
"weightedLevenshtein",
"(",
"baseTarget",
",",
"null",
",",
"characterSubst... | Returns a new Weighted Levenshtein edit distance instance
@see WeightedLevenshtein
@param baseTarget
@param characterSubstitution
@return | [
"Returns",
"a",
"new",
"Weighted",
"Levenshtein",
"edit",
"distance",
"instance"
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Levenshtein.java#L74-L76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.