repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
stripe/stripe-android | stripe/src/main/java/com/stripe/android/Stripe.java | Stripe.createPiiTokenSynchronous | public Token createPiiTokenSynchronous(@NonNull String personalId, String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(
publishableKey,
mStripeAccount,
RequestOptions.TYPE_QUERY).build();
return mApiHandler.createToken(
hashMapFromPersonalId(personalId),
requestOptions,
Token.TYPE_PII
);
} | java | public Token createPiiTokenSynchronous(@NonNull String personalId, String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(
publishableKey,
mStripeAccount,
RequestOptions.TYPE_QUERY).build();
return mApiHandler.createToken(
hashMapFromPersonalId(personalId),
requestOptions,
Token.TYPE_PII
);
} | [
"public",
"Token",
"createPiiTokenSynchronous",
"(",
"@",
"NonNull",
"String",
"personalId",
",",
"String",
"publishableKey",
")",
"throws",
"AuthenticationException",
",",
"InvalidRequestException",
",",
"APIConnectionException",
",",
"CardException",
",",
"APIException",
... | Blocking method to create a {@link Token} for PII. Do not call this on the UI thread
or your app will crash.
@param personalId the personal ID to use for this token
@param publishableKey the publishable key to use with this request
@return a {@link Token} that can be used for this card
@throws AuthenticationException failure to properly authenticate yourself (check your key)
@throws InvalidRequestException your request has invalid parameters
@throws APIConnectionException failure to connect to Stripe's API
@throws APIException any other type of problem (for instance, a temporary issue with
Stripe's servers) | [
"Blocking",
"method",
"to",
"create",
"a",
"{",
"@link",
"Token",
"}",
"for",
"PII",
".",
"Do",
"not",
"call",
"this",
"on",
"the",
"UI",
"thread",
"or",
"your",
"app",
"will",
"crash",
"."
] | train | https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/Stripe.java#L600-L616 |
zhangyingwei/cockroach | cockroach-core/src/main/java/com/zhangyingwei/cockroach/common/utils/FileUtils.java | FileUtils.write | public static void write(byte[] bytes,File file) throws IOException {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
outputStream.write(bytes);
outputStream.close();
} | java | public static void write(byte[] bytes,File file) throws IOException {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
outputStream.write(bytes);
outputStream.close();
} | [
"public",
"static",
"void",
"write",
"(",
"byte",
"[",
"]",
"bytes",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"BufferedOutputStream",
"outputStream",
"=",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
";",... | wtire bytes into file
@param bytes
@param file
@throws IOException | [
"wtire",
"bytes",
"into",
"file"
] | train | https://github.com/zhangyingwei/cockroach/blob/a8139dea1b4e3e6ec2451520cb9f7700ff0f704e/cockroach-core/src/main/java/com/zhangyingwei/cockroach/common/utils/FileUtils.java#L52-L56 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/FileSpec.java | FileSpec.readFileToVariableNoDataTable | @When("^I read file '(.+?)' as '(.+?)' and save it in environment variable '(.+?)'$")
public void readFileToVariableNoDataTable(String baseData, String type, String envVar) throws Exception {
// Retrieve data
String retrievedData = commonspec.retrieveData(baseData, type);
// Save in environment variable
ThreadProperty.set(envVar, retrievedData);
} | java | @When("^I read file '(.+?)' as '(.+?)' and save it in environment variable '(.+?)'$")
public void readFileToVariableNoDataTable(String baseData, String type, String envVar) throws Exception {
// Retrieve data
String retrievedData = commonspec.retrieveData(baseData, type);
// Save in environment variable
ThreadProperty.set(envVar, retrievedData);
} | [
"@",
"When",
"(",
"\"^I read file '(.+?)' as '(.+?)' and save it in environment variable '(.+?)'$\"",
")",
"public",
"void",
"readFileToVariableNoDataTable",
"(",
"String",
"baseData",
",",
"String",
"type",
",",
"String",
"envVar",
")",
"throws",
"Exception",
"{",
"// Retr... | Read the file passed as parameter and save the result in the environment
variable passed as parameter.
@param baseData file to read
@param type whether the info in the file is a 'json' or a simple 'string'
@param envVar name of the variable where to store the result | [
"Read",
"the",
"file",
"passed",
"as",
"parameter",
"and",
"save",
"the",
"result",
"in",
"the",
"environment",
"variable",
"passed",
"as",
"parameter",
"."
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/FileSpec.java#L192-L199 |
m-m-m/util | text/src/main/java/net/sf/mmm/util/text/base/DefaultLineWrapper.java | DefaultLineWrapper.verifyWithOfColumns | private boolean verifyWithOfColumns(ColumnState[] columnStates, TextTableInfo tableInfo) {
int tableWidth = tableInfo.getWidth();
if (tableWidth != TextColumnInfo.WIDTH_AUTO_ADJUST) {
int calculatedWidth = 0;
for (ColumnState columnState : columnStates) {
if (columnState.width < 0) {
throw new AssertionError("columnWidth=" + columnState.width);
// return false;
}
calculatedWidth = calculatedWidth + columnState.width + columnState.getColumnInfo().getBorderWidth();
}
if (calculatedWidth != tableWidth) {
throw new AssertionError("with=" + tableWidth + ", sum-of-columns=" + calculatedWidth);
// return false;
}
}
return true;
} | java | private boolean verifyWithOfColumns(ColumnState[] columnStates, TextTableInfo tableInfo) {
int tableWidth = tableInfo.getWidth();
if (tableWidth != TextColumnInfo.WIDTH_AUTO_ADJUST) {
int calculatedWidth = 0;
for (ColumnState columnState : columnStates) {
if (columnState.width < 0) {
throw new AssertionError("columnWidth=" + columnState.width);
// return false;
}
calculatedWidth = calculatedWidth + columnState.width + columnState.getColumnInfo().getBorderWidth();
}
if (calculatedWidth != tableWidth) {
throw new AssertionError("with=" + tableWidth + ", sum-of-columns=" + calculatedWidth);
// return false;
}
}
return true;
} | [
"private",
"boolean",
"verifyWithOfColumns",
"(",
"ColumnState",
"[",
"]",
"columnStates",
",",
"TextTableInfo",
"tableInfo",
")",
"{",
"int",
"tableWidth",
"=",
"tableInfo",
".",
"getWidth",
"(",
")",
";",
"if",
"(",
"tableWidth",
"!=",
"TextColumnInfo",
".",
... | This method verifies that the width of the columns are sane.
@param columnStates are the {@link ColumnState}s.
@param tableInfo is the {@link TextTableInfo}.
@return {@code true} if the width is sane, {@code false} otherwise. | [
"This",
"method",
"verifies",
"that",
"the",
"width",
"of",
"the",
"columns",
"are",
"sane",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/text/src/main/java/net/sf/mmm/util/text/base/DefaultLineWrapper.java#L258-L276 |
sarl/sarl | contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java | PyExpressionGenerator.generateAnonymousClassDefinition | protected void generateAnonymousClassDefinition(AnonymousClass anonClass, IAppendable it, IExtraLanguageGeneratorContext context) {
if (!it.hasName(anonClass) && it instanceof PyAppendable) {
final LightweightTypeReference jvmAnonType = getExpectedType(anonClass);
final String anonName = it.declareSyntheticVariable(anonClass, jvmAnonType.getSimpleName());
QualifiedName anonQualifiedName = QualifiedName.create(
jvmAnonType.getType().getQualifiedName().split(Pattern.quote("."))); //$NON-NLS-1$
anonQualifiedName = anonQualifiedName.skipLast(1);
if (anonQualifiedName.isEmpty()) {
// The type resolver does not include the enclosing class.
assert anonClass.getDeclaringType() == null : "The Xtend API has changed the AnonymousClass definition!"; //$NON-NLS-1$
final XtendTypeDeclaration container = EcoreUtil2.getContainerOfType(anonClass.eContainer(), XtendTypeDeclaration.class);
anonQualifiedName = anonQualifiedName.append(this.qualifiedNameProvider.getFullyQualifiedName(container));
}
anonQualifiedName = anonQualifiedName.append(anonName);
it.openPseudoScope();
final IRootGenerator rootGenerator = context.getRootGenerator();
assert rootGenerator instanceof PyGenerator;
final List<JvmTypeReference> types = new ArrayList<>();
for (final JvmTypeReference superType : anonClass.getConstructorCall().getConstructor().getDeclaringType().getSuperTypes()) {
if (!Object.class.getCanonicalName().equals(superType.getIdentifier())) {
types.add(superType);
}
}
((PyGenerator) rootGenerator).generateTypeDeclaration(
anonQualifiedName.toString(),
anonName,
false,
types,
getTypeBuilder().getDocumentation(anonClass),
false,
anonClass.getMembers(),
(PyAppendable) it,
context,
null);
it.closeScope();
}
} | java | protected void generateAnonymousClassDefinition(AnonymousClass anonClass, IAppendable it, IExtraLanguageGeneratorContext context) {
if (!it.hasName(anonClass) && it instanceof PyAppendable) {
final LightweightTypeReference jvmAnonType = getExpectedType(anonClass);
final String anonName = it.declareSyntheticVariable(anonClass, jvmAnonType.getSimpleName());
QualifiedName anonQualifiedName = QualifiedName.create(
jvmAnonType.getType().getQualifiedName().split(Pattern.quote("."))); //$NON-NLS-1$
anonQualifiedName = anonQualifiedName.skipLast(1);
if (anonQualifiedName.isEmpty()) {
// The type resolver does not include the enclosing class.
assert anonClass.getDeclaringType() == null : "The Xtend API has changed the AnonymousClass definition!"; //$NON-NLS-1$
final XtendTypeDeclaration container = EcoreUtil2.getContainerOfType(anonClass.eContainer(), XtendTypeDeclaration.class);
anonQualifiedName = anonQualifiedName.append(this.qualifiedNameProvider.getFullyQualifiedName(container));
}
anonQualifiedName = anonQualifiedName.append(anonName);
it.openPseudoScope();
final IRootGenerator rootGenerator = context.getRootGenerator();
assert rootGenerator instanceof PyGenerator;
final List<JvmTypeReference> types = new ArrayList<>();
for (final JvmTypeReference superType : anonClass.getConstructorCall().getConstructor().getDeclaringType().getSuperTypes()) {
if (!Object.class.getCanonicalName().equals(superType.getIdentifier())) {
types.add(superType);
}
}
((PyGenerator) rootGenerator).generateTypeDeclaration(
anonQualifiedName.toString(),
anonName,
false,
types,
getTypeBuilder().getDocumentation(anonClass),
false,
anonClass.getMembers(),
(PyAppendable) it,
context,
null);
it.closeScope();
}
} | [
"protected",
"void",
"generateAnonymousClassDefinition",
"(",
"AnonymousClass",
"anonClass",
",",
"IAppendable",
"it",
",",
"IExtraLanguageGeneratorContext",
"context",
")",
"{",
"if",
"(",
"!",
"it",
".",
"hasName",
"(",
"anonClass",
")",
"&&",
"it",
"instanceof",
... | Generate the anonymous class definition.
@param anonClass the anonymous class.
@param it the target for the generated content.
@param context the context. | [
"Generate",
"the",
"anonymous",
"class",
"definition",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java#L211-L247 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/ThresholdNick.java | ThresholdNick.process | @Override
public void process(GrayF32 input , GrayU8 output ) {
imageI2.reshape(input.width,input.height);
meanImage.reshape(input.width,input.height);
meanI2.reshape(input.width,input.height);
tmp.reshape(input.width,input.height);
imageI2.reshape(input.width,input.height);
int radius = width.computeI(Math.min(input.width,input.height))/2;
float NP = (radius*2+1)*(radius*2+1);
// mean of input image = E[X]
BlurImageOps.mean(input, meanImage, radius, tmp, work);
// Compute I^2
PixelMath.pow2(input, imageI2);
// Compute local mean of I^2
BlurImageOps.mean(imageI2, meanI2, radius, tmp, work);
if( down ) {
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {
for (int y = 0; y < input.height; y++) {
int i = y * meanI2.width;
int indexIn = input.startIndex + y * input.stride;
int indexOut = output.startIndex + y * output.stride;
for (int x = 0; x < input.width; x++, i++) {
float mean = meanImage.data[i];
float A = meanI2.data[i] - (mean*mean/NP);
// threshold = mean + k*sqrt( A )
float threshold = mean + k*(float)Math.sqrt(A);
output.data[indexOut++] = (byte) (input.data[indexIn++] <= threshold ? 1 : 0);
}
}
//CONCURRENT_ABOVE });
} else {
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {
for (int y = 0; y < input.height; y++) {
int i = y * meanI2.width;
int indexIn = input.startIndex + y * input.stride;
int indexOut = output.startIndex + y * output.stride;
for (int x = 0; x < input.width; x++, i++) {
float mean = meanImage.data[i];
float A = meanI2.data[i] - (mean*mean/NP);
// threshold = mean + k*sqrt( A )
float threshold = mean + k*(float)Math.sqrt(A);
output.data[indexOut++] = (byte) (input.data[indexIn++] >= threshold ? 1 : 0);
}
}
//CONCURRENT_ABOVE });
}
} | java | @Override
public void process(GrayF32 input , GrayU8 output ) {
imageI2.reshape(input.width,input.height);
meanImage.reshape(input.width,input.height);
meanI2.reshape(input.width,input.height);
tmp.reshape(input.width,input.height);
imageI2.reshape(input.width,input.height);
int radius = width.computeI(Math.min(input.width,input.height))/2;
float NP = (radius*2+1)*(radius*2+1);
// mean of input image = E[X]
BlurImageOps.mean(input, meanImage, radius, tmp, work);
// Compute I^2
PixelMath.pow2(input, imageI2);
// Compute local mean of I^2
BlurImageOps.mean(imageI2, meanI2, radius, tmp, work);
if( down ) {
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {
for (int y = 0; y < input.height; y++) {
int i = y * meanI2.width;
int indexIn = input.startIndex + y * input.stride;
int indexOut = output.startIndex + y * output.stride;
for (int x = 0; x < input.width; x++, i++) {
float mean = meanImage.data[i];
float A = meanI2.data[i] - (mean*mean/NP);
// threshold = mean + k*sqrt( A )
float threshold = mean + k*(float)Math.sqrt(A);
output.data[indexOut++] = (byte) (input.data[indexIn++] <= threshold ? 1 : 0);
}
}
//CONCURRENT_ABOVE });
} else {
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {
for (int y = 0; y < input.height; y++) {
int i = y * meanI2.width;
int indexIn = input.startIndex + y * input.stride;
int indexOut = output.startIndex + y * output.stride;
for (int x = 0; x < input.width; x++, i++) {
float mean = meanImage.data[i];
float A = meanI2.data[i] - (mean*mean/NP);
// threshold = mean + k*sqrt( A )
float threshold = mean + k*(float)Math.sqrt(A);
output.data[indexOut++] = (byte) (input.data[indexIn++] >= threshold ? 1 : 0);
}
}
//CONCURRENT_ABOVE });
}
} | [
"@",
"Override",
"public",
"void",
"process",
"(",
"GrayF32",
"input",
",",
"GrayU8",
"output",
")",
"{",
"imageI2",
".",
"reshape",
"(",
"input",
".",
"width",
",",
"input",
".",
"height",
")",
";",
"meanImage",
".",
"reshape",
"(",
"input",
".",
"wid... | Converts the input image into a binary image.
@param input Input image. Not modified.
@param output Output binary image. Modified. | [
"Converts",
"the",
"input",
"image",
"into",
"a",
"binary",
"image",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/ThresholdNick.java#L82-L138 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java | Calc.isConnected | public static final boolean isConnected(AminoAcid a, AminoAcid b) {
Atom C = null ;
Atom N = null;
C = a.getC();
N = b.getN();
if ( C == null || N == null)
return false;
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C,N);
return distance < 2.5;
} | java | public static final boolean isConnected(AminoAcid a, AminoAcid b) {
Atom C = null ;
Atom N = null;
C = a.getC();
N = b.getN();
if ( C == null || N == null)
return false;
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C,N);
return distance < 2.5;
} | [
"public",
"static",
"final",
"boolean",
"isConnected",
"(",
"AminoAcid",
"a",
",",
"AminoAcid",
"b",
")",
"{",
"Atom",
"C",
"=",
"null",
";",
"Atom",
"N",
"=",
"null",
";",
"C",
"=",
"a",
".",
"getC",
"(",
")",
";",
"N",
"=",
"b",
".",
"getN",
... | Test if two amino acids are connected, i.e. if the distance from C to N <
2.5 Angstrom.
If one of the AminoAcids has an atom missing, returns false.
@param a
an AminoAcid object
@param b
an AminoAcid object
@return true if ... | [
"Test",
"if",
"two",
"amino",
"acids",
"are",
"connected",
"i",
".",
"e",
".",
"if",
"the",
"distance",
"from",
"C",
"to",
"N",
"<",
"2",
".",
"5",
"Angstrom",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java#L341-L354 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/config/CommandLine.java | CommandLine.addOption | public void addOption(String option, String argumentDesc, String description) {
optionList.add(option);
optionDescriptionMap.put(option, description);
requiresArgumentSet.add(option);
argumentDescriptionMap.put(option, argumentDesc);
int width = option.length() + 3 + argumentDesc.length();
if (width > maxWidth) {
maxWidth = width;
}
} | java | public void addOption(String option, String argumentDesc, String description) {
optionList.add(option);
optionDescriptionMap.put(option, description);
requiresArgumentSet.add(option);
argumentDescriptionMap.put(option, argumentDesc);
int width = option.length() + 3 + argumentDesc.length();
if (width > maxWidth) {
maxWidth = width;
}
} | [
"public",
"void",
"addOption",
"(",
"String",
"option",
",",
"String",
"argumentDesc",
",",
"String",
"description",
")",
"{",
"optionList",
".",
"add",
"(",
"option",
")",
";",
"optionDescriptionMap",
".",
"put",
"(",
"option",
",",
"description",
")",
";",... | Add an option requiring an argument.
@param option
the option, must start with "-"
@param argumentDesc
brief (one or two word) description of the argument
@param description
single line description of the option | [
"Add",
"an",
"option",
"requiring",
"an",
"argument",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/config/CommandLine.java#L136-L146 |
pwheel/spring-security-oauth2-client | src/main/java/com/racquettrack/security/oauth/OAuth2UserDetailsService.java | OAuth2UserDetailsService.postCreatedOrEnabledUser | private void postCreatedOrEnabledUser(UserDetails userDetails, Map<String, Object> userInfo) {
if (oAuth2PostCreatedOrEnabledUserService != null) {
oAuth2PostCreatedOrEnabledUserService.postCreatedOrEnabledUser(userDetails, userInfo);
}
} | java | private void postCreatedOrEnabledUser(UserDetails userDetails, Map<String, Object> userInfo) {
if (oAuth2PostCreatedOrEnabledUserService != null) {
oAuth2PostCreatedOrEnabledUserService.postCreatedOrEnabledUser(userDetails, userInfo);
}
} | [
"private",
"void",
"postCreatedOrEnabledUser",
"(",
"UserDetails",
"userDetails",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"userInfo",
")",
"{",
"if",
"(",
"oAuth2PostCreatedOrEnabledUserService",
"!=",
"null",
")",
"{",
"oAuth2PostCreatedOrEnabledUserService",
... | Extension point to allow sub classes to optionally do some processing after a user has been created or enabled.
For example they could set something in the session so that the authentication success handler can treat
the first log in differently.
@param userDetails The {@link UserDetails} object created by
{@link OAuth2UserDetailsLoader#createUser(Object, Map)}
@param userInfo A map representing the user information returned from the OAuth Provider. | [
"Extension",
"point",
"to",
"allow",
"sub",
"classes",
"to",
"optionally",
"do",
"some",
"processing",
"after",
"a",
"user",
"has",
"been",
"created",
"or",
"enabled",
".",
"For",
"example",
"they",
"could",
"set",
"something",
"in",
"the",
"session",
"so",
... | train | https://github.com/pwheel/spring-security-oauth2-client/blob/c0258823493e268495c9752c5d752f74c6809c6b/src/main/java/com/racquettrack/security/oauth/OAuth2UserDetailsService.java#L99-L103 |
facebookarchive/hive-dwrf | hive-dwrf/src/main/java/com/facebook/hive/orc/ReaderImpl.java | ReaderImpl.checkIfORC | public static void checkIfORC(FileSystem fs, Path path) throws IOException {
// hardcoded to 40 because "SEQ-org.apache.hadoop.hive.ql.io.RCFile", the header, is of 40 chars
final int buffLen = 40;
final byte header[] = new byte[buffLen];
final FSDataInputStream file = fs.open(path);
final long fileLength = fs.getFileStatus(path).getLen();
int sizeToBeRead = buffLen;
if (buffLen > fileLength) {
sizeToBeRead = (int)fileLength;
}
IOUtils.readFully(file, header, 0, sizeToBeRead);
file.close();
final String headerString = new String(header);
if (headerString.startsWith("ORC")) {
LOG.error("Error while parsing the footer of the file : " + path);
} else {
throw new NotAnORCFileException("Input file = " + path + " , header = " + headerString);
}
} | java | public static void checkIfORC(FileSystem fs, Path path) throws IOException {
// hardcoded to 40 because "SEQ-org.apache.hadoop.hive.ql.io.RCFile", the header, is of 40 chars
final int buffLen = 40;
final byte header[] = new byte[buffLen];
final FSDataInputStream file = fs.open(path);
final long fileLength = fs.getFileStatus(path).getLen();
int sizeToBeRead = buffLen;
if (buffLen > fileLength) {
sizeToBeRead = (int)fileLength;
}
IOUtils.readFully(file, header, 0, sizeToBeRead);
file.close();
final String headerString = new String(header);
if (headerString.startsWith("ORC")) {
LOG.error("Error while parsing the footer of the file : " + path);
} else {
throw new NotAnORCFileException("Input file = " + path + " , header = " + headerString);
}
} | [
"public",
"static",
"void",
"checkIfORC",
"(",
"FileSystem",
"fs",
",",
"Path",
"path",
")",
"throws",
"IOException",
"{",
"// hardcoded to 40 because \"SEQ-org.apache.hadoop.hive.ql.io.RCFile\", the header, is of 40 chars",
"final",
"int",
"buffLen",
"=",
"40",
";",
"final... | Reads the file header (first 40 bytes) and checks if the first three characters are 'ORC'. | [
"Reads",
"the",
"file",
"header",
"(",
"first",
"40",
"bytes",
")",
"and",
"checks",
"if",
"the",
"first",
"three",
"characters",
"are",
"ORC",
"."
] | train | https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/ReaderImpl.java#L265-L285 |
Steveice10/OpenNBT | src/main/java/com/github/steveice10/opennbt/NBTIO.java | NBTIO.writeFile | public static void writeFile(CompoundTag tag, File file, boolean compressed, boolean littleEndian) throws IOException {
if(!file.exists()) {
if(file.getParentFile() != null && !file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
if(compressed) {
out = new GZIPOutputStream(out);
}
writeTag(out, tag, littleEndian);
out.close();
} | java | public static void writeFile(CompoundTag tag, File file, boolean compressed, boolean littleEndian) throws IOException {
if(!file.exists()) {
if(file.getParentFile() != null && !file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
if(compressed) {
out = new GZIPOutputStream(out);
}
writeTag(out, tag, littleEndian);
out.close();
} | [
"public",
"static",
"void",
"writeFile",
"(",
"CompoundTag",
"tag",
",",
"File",
"file",
",",
"boolean",
"compressed",
",",
"boolean",
"littleEndian",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"if",
"("... | Writes the given root CompoundTag to the given file.
@param tag Tag to write.
@param file File to write to.
@param compressed Whether the NBT file should be compressed.
@param littleEndian Whether to write little endian NBT.
@throws java.io.IOException If an I/O error occurs. | [
"Writes",
"the",
"given",
"root",
"CompoundTag",
"to",
"the",
"given",
"file",
"."
] | train | https://github.com/Steveice10/OpenNBT/blob/9bf4adb2afd206a21bc4309c85d642494d1fb536/src/main/java/com/github/steveice10/opennbt/NBTIO.java#L130-L146 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/component/bean/proxy/JavassistDynamicBeanProxy.java | JavassistDynamicBeanProxy.newInstance | public static Object newInstance(ActivityContext context, BeanRule beanRule, Object[] args, Class<?>[] argTypes) {
try {
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setSuperclass(beanRule.getBeanClass());
MethodHandler methodHandler = new JavassistDynamicBeanProxy(context, beanRule);
return proxyFactory.create(argTypes, args, methodHandler);
} catch (Exception e) {
throw new ProxyBeanInstantiationException(beanRule, e);
}
} | java | public static Object newInstance(ActivityContext context, BeanRule beanRule, Object[] args, Class<?>[] argTypes) {
try {
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setSuperclass(beanRule.getBeanClass());
MethodHandler methodHandler = new JavassistDynamicBeanProxy(context, beanRule);
return proxyFactory.create(argTypes, args, methodHandler);
} catch (Exception e) {
throw new ProxyBeanInstantiationException(beanRule, e);
}
} | [
"public",
"static",
"Object",
"newInstance",
"(",
"ActivityContext",
"context",
",",
"BeanRule",
"beanRule",
",",
"Object",
"[",
"]",
"args",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"argTypes",
")",
"{",
"try",
"{",
"ProxyFactory",
"proxyFactory",
"=",
"new... | Creates a proxy class of bean and returns an instance of that class.
@param context the activity context
@param beanRule the bean rule
@param args the arguments passed to a constructor
@param argTypes the parameter types for a constructor
@return a new proxy bean object | [
"Creates",
"a",
"proxy",
"class",
"of",
"bean",
"and",
"returns",
"an",
"instance",
"of",
"that",
"class",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/component/bean/proxy/JavassistDynamicBeanProxy.java#L126-L135 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/model/JavacElements.java | JavacElements.nameToSymbol | private <S extends Symbol> S nameToSymbol(ModuleSymbol module, String nameStr, Class<S> clazz) {
Name name = names.fromString(nameStr);
// First check cache.
Symbol sym = (clazz == ClassSymbol.class)
? syms.getClass(module, name)
: syms.lookupPackage(module, name);
try {
if (sym == null)
sym = javaCompiler.resolveIdent(module, nameStr);
sym.complete();
return (sym.kind != ERR &&
sym.exists() &&
clazz.isInstance(sym) &&
name.equals(sym.getQualifiedName()))
? clazz.cast(sym)
: null;
} catch (CompletionFailure e) {
return null;
}
} | java | private <S extends Symbol> S nameToSymbol(ModuleSymbol module, String nameStr, Class<S> clazz) {
Name name = names.fromString(nameStr);
// First check cache.
Symbol sym = (clazz == ClassSymbol.class)
? syms.getClass(module, name)
: syms.lookupPackage(module, name);
try {
if (sym == null)
sym = javaCompiler.resolveIdent(module, nameStr);
sym.complete();
return (sym.kind != ERR &&
sym.exists() &&
clazz.isInstance(sym) &&
name.equals(sym.getQualifiedName()))
? clazz.cast(sym)
: null;
} catch (CompletionFailure e) {
return null;
}
} | [
"private",
"<",
"S",
"extends",
"Symbol",
">",
"S",
"nameToSymbol",
"(",
"ModuleSymbol",
"module",
",",
"String",
"nameStr",
",",
"Class",
"<",
"S",
">",
"clazz",
")",
"{",
"Name",
"name",
"=",
"names",
".",
"fromString",
"(",
"nameStr",
")",
";",
"// ... | Returns a symbol given the type's or package's canonical name,
or null if the name isn't found. | [
"Returns",
"a",
"symbol",
"given",
"the",
"type",
"s",
"or",
"package",
"s",
"canonical",
"name",
"or",
"null",
"if",
"the",
"name",
"isn",
"t",
"found",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/model/JavacElements.java#L229-L251 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/core/encoding/ConvertYuv420_888.java | ConvertYuv420_888.yuvToGray | public static <T extends ImageGray<T>>
T yuvToGray(ByteBuffer bufferY , int width , int height, int strideRow , T output , BWorkArrays workArrays, Class<T> outputType )
{
if( outputType == GrayU8.class ) {
return (T) yuvToGray(bufferY,width,height,strideRow,(GrayU8)output);
} else if( outputType == GrayF32.class ) {
return (T) yuvToGray(bufferY,width,height,strideRow,(GrayF32)output,workArrays);
} else {
throw new IllegalArgumentException("Unsupported BoofCV Image Type "+outputType.getSimpleName());
}
} | java | public static <T extends ImageGray<T>>
T yuvToGray(ByteBuffer bufferY , int width , int height, int strideRow , T output , BWorkArrays workArrays, Class<T> outputType )
{
if( outputType == GrayU8.class ) {
return (T) yuvToGray(bufferY,width,height,strideRow,(GrayU8)output);
} else if( outputType == GrayF32.class ) {
return (T) yuvToGray(bufferY,width,height,strideRow,(GrayF32)output,workArrays);
} else {
throw new IllegalArgumentException("Unsupported BoofCV Image Type "+outputType.getSimpleName());
}
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
">",
"T",
"yuvToGray",
"(",
"ByteBuffer",
"bufferY",
",",
"int",
"width",
",",
"int",
"height",
",",
"int",
"strideRow",
",",
"T",
"output",
",",
"BWorkArrays",
"workArrays",
",",
"Clas... | Converts an YUV 420 888 into gray
@param output Output: Optional storage for output image. Can be null.
@param outputType Output: Type of output image
@param <T> Output image type
@return Gray scale image | [
"Converts",
"an",
"YUV",
"420",
"888",
"into",
"gray"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/core/encoding/ConvertYuv420_888.java#L111-L121 |
javers/javers | javers-core/src/main/java/org/javers/repository/jql/QueryBuilder.java | QueryBuilder.byInstanceId | public static QueryBuilder byInstanceId(Object localId, String typeName){
Validate.argumentsAreNotNull(localId, typeName);
return new QueryBuilder(new IdAndTypeNameFilterDefinition(localId, typeName));
} | java | public static QueryBuilder byInstanceId(Object localId, String typeName){
Validate.argumentsAreNotNull(localId, typeName);
return new QueryBuilder(new IdAndTypeNameFilterDefinition(localId, typeName));
} | [
"public",
"static",
"QueryBuilder",
"byInstanceId",
"(",
"Object",
"localId",
",",
"String",
"typeName",
")",
"{",
"Validate",
".",
"argumentsAreNotNull",
"(",
"localId",
",",
"typeName",
")",
";",
"return",
"new",
"QueryBuilder",
"(",
"new",
"IdAndTypeNameFilterD... | Query for selecting changes (or snapshots) made on a concrete type identified by name.
<br/><br/>
For example, last changes on "bob" Person:
<pre>
javers.findChanges( QueryBuilder.byInstanceId("bob", "Person").build() );
</pre> | [
"Query",
"for",
"selecting",
"changes",
"(",
"or",
"snapshots",
")",
"made",
"on",
"a",
"concrete",
"type",
"identified",
"by",
"name",
".",
"<br",
"/",
">",
"<br",
"/",
">"
] | train | https://github.com/javers/javers/blob/a51511be7d8bcee3e1812db8b7e69a45330b4e14/javers-core/src/main/java/org/javers/repository/jql/QueryBuilder.java#L104-L107 |
citrusframework/citrus | modules/citrus-zookeeper/src/main/java/com/consol/citrus/zookeeper/command/AbstractZooCommand.java | AbstractZooCommand.withParam | public AbstractZooCommand withParam(String name, String value) {
parameters.put(name, value);
return this;
} | java | public AbstractZooCommand withParam(String name, String value) {
parameters.put(name, value);
return this;
} | [
"public",
"AbstractZooCommand",
"withParam",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"parameters",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds command parameter to current command.
@param name
@param value
@return | [
"Adds",
"command",
"parameter",
"to",
"current",
"command",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-zookeeper/src/main/java/com/consol/citrus/zookeeper/command/AbstractZooCommand.java#L131-L134 |
alkacon/opencms-core | src/org/opencms/widgets/CmsLocalizationWidget.java | CmsLocalizationWidget.initConfiguration | protected void initConfiguration(CmsObject cms, I_CmsWidgetParameter param) {
// set the default bundle key
m_bundleKey = param.getName();
// set the default locale for XML contents
m_locale = cms.getRequestContext().getLocale();
try {
I_CmsXmlContentValue value = (I_CmsXmlContentValue)param;
m_locale = value.getLocale();
} catch (Exception e) {
// ignore, this is no XML content
}
// check the message bundle
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getConfiguration())) {
//initialize messages, the optional bundle key name and the optional locale from configuration String
String bundleName = "";
List<String> configs = CmsStringUtil.splitAsList(getConfiguration(), '|');
Iterator<String> i = configs.iterator();
while (i.hasNext()) {
String config = i.next();
if (config.startsWith(OPTION_KEY)) {
m_bundleKey = config.substring(OPTION_KEY.length());
} else if (config.startsWith(OPTION_LOCALE)) {
m_locale = CmsLocaleManager.getLocale(config.substring(OPTION_LOCALE.length()));
} else {
bundleName = config;
}
}
// create messages object
m_messages = new CmsMessages(bundleName, m_locale);
} else {
// initialize empty messages object to avoid NPE
m_messages = new CmsMessages("", m_locale);
}
} | java | protected void initConfiguration(CmsObject cms, I_CmsWidgetParameter param) {
// set the default bundle key
m_bundleKey = param.getName();
// set the default locale for XML contents
m_locale = cms.getRequestContext().getLocale();
try {
I_CmsXmlContentValue value = (I_CmsXmlContentValue)param;
m_locale = value.getLocale();
} catch (Exception e) {
// ignore, this is no XML content
}
// check the message bundle
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getConfiguration())) {
//initialize messages, the optional bundle key name and the optional locale from configuration String
String bundleName = "";
List<String> configs = CmsStringUtil.splitAsList(getConfiguration(), '|');
Iterator<String> i = configs.iterator();
while (i.hasNext()) {
String config = i.next();
if (config.startsWith(OPTION_KEY)) {
m_bundleKey = config.substring(OPTION_KEY.length());
} else if (config.startsWith(OPTION_LOCALE)) {
m_locale = CmsLocaleManager.getLocale(config.substring(OPTION_LOCALE.length()));
} else {
bundleName = config;
}
}
// create messages object
m_messages = new CmsMessages(bundleName, m_locale);
} else {
// initialize empty messages object to avoid NPE
m_messages = new CmsMessages("", m_locale);
}
} | [
"protected",
"void",
"initConfiguration",
"(",
"CmsObject",
"cms",
",",
"I_CmsWidgetParameter",
"param",
")",
"{",
"// set the default bundle key",
"m_bundleKey",
"=",
"param",
".",
"getName",
"(",
")",
";",
"// set the default locale for XML contents",
"m_locale",
"=",
... | Initializes the localized bundle to get the value from, the optional key name and the optional locale.<p>
@param cms an initialized instance of a CmsObject
@param param the widget parameter to generate the widget for | [
"Initializes",
"the",
"localized",
"bundle",
"to",
"get",
"the",
"value",
"from",
"the",
"optional",
"key",
"name",
"and",
"the",
"optional",
"locale",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/CmsLocalizationWidget.java#L300-L335 |
jklingsporn/vertx-jooq | vertx-jooq-generate/src/main/java/io/github/jklingsporn/vertx/jooq/generate/VertxGenerator.java | VertxGenerator.handleCustomTypeFromJson | protected boolean handleCustomTypeFromJson(TypedElementDefinition<?> column, String setter, String columnType, String javaMemberName, JavaWriter out){
return false;
} | java | protected boolean handleCustomTypeFromJson(TypedElementDefinition<?> column, String setter, String columnType, String javaMemberName, JavaWriter out){
return false;
} | [
"protected",
"boolean",
"handleCustomTypeFromJson",
"(",
"TypedElementDefinition",
"<",
"?",
">",
"column",
",",
"String",
"setter",
",",
"String",
"columnType",
",",
"String",
"javaMemberName",
",",
"JavaWriter",
"out",
")",
"{",
"return",
"false",
";",
"}"
] | Overwrite this method to handle your custom type. This is needed especially when you have custom converters.
@param column the column definition
@param setter the setter name
@param columnType the type of the column
@param javaMemberName the java member name
@param out the JavaWriter
@return <code>true</code> if the column was handled.
@see #generateFromJson(TableDefinition, JavaWriter, org.jooq.codegen.GeneratorStrategy.Mode) | [
"Overwrite",
"this",
"method",
"to",
"handle",
"your",
"custom",
"type",
".",
"This",
"is",
"needed",
"especially",
"when",
"you",
"have",
"custom",
"converters",
"."
] | train | https://github.com/jklingsporn/vertx-jooq/blob/0db00b5e040639c309691dfbc125034fa3346d88/vertx-jooq-generate/src/main/java/io/github/jklingsporn/vertx/jooq/generate/VertxGenerator.java#L58-L60 |
konvergeio/cofoja | src/main/java/com/google/java/contract/core/agent/ContractClassFileTransformer.java | ContractClassFileTransformer.instrumentWithContracts | @Requires({
"bytecode != null",
"contracts != null"
})
@Ensures("result != null")
protected byte[] instrumentWithContracts(byte[] bytecode,
ContractAnalyzer contracts) {
ClassReader reader = new ClassReader(bytecode);
ClassWriter writer =
new NonLoadingClassWriter(reader,
ClassWriter.COMPUTE_FRAMES |
ClassWriter.COMPUTE_MAXS);
SpecificationClassAdapter adapter =
new SpecificationClassAdapter(writer, contracts);
reader.accept(adapter, ClassReader.EXPAND_FRAMES);
return writer.toByteArray();
} | java | @Requires({
"bytecode != null",
"contracts != null"
})
@Ensures("result != null")
protected byte[] instrumentWithContracts(byte[] bytecode,
ContractAnalyzer contracts) {
ClassReader reader = new ClassReader(bytecode);
ClassWriter writer =
new NonLoadingClassWriter(reader,
ClassWriter.COMPUTE_FRAMES |
ClassWriter.COMPUTE_MAXS);
SpecificationClassAdapter adapter =
new SpecificationClassAdapter(writer, contracts);
reader.accept(adapter, ClassReader.EXPAND_FRAMES);
return writer.toByteArray();
} | [
"@",
"Requires",
"(",
"{",
"\"bytecode != null\"",
",",
"\"contracts != null\"",
"}",
")",
"@",
"Ensures",
"(",
"\"result != null\"",
")",
"protected",
"byte",
"[",
"]",
"instrumentWithContracts",
"(",
"byte",
"[",
"]",
"bytecode",
",",
"ContractAnalyzer",
"contra... | Instruments the passed class file so that it contains contract
methods and calls to these methods. The contract information is
retrieved from the {@link ContractCodePool}.
@param bytecode the bytecode of the class
@param contracts the extracted contracts for the class
@return the instrumented bytecode of the class | [
"Instruments",
"the",
"passed",
"class",
"file",
"so",
"that",
"it",
"contains",
"contract",
"methods",
"and",
"calls",
"to",
"these",
"methods",
".",
"The",
"contract",
"information",
"is",
"retrieved",
"from",
"the",
"{",
"@link",
"ContractCodePool",
"}",
".... | train | https://github.com/konvergeio/cofoja/blob/6ded58fa05eb5bf85f16353c8dd4c70bee59121a/src/main/java/com/google/java/contract/core/agent/ContractClassFileTransformer.java#L375-L393 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java | PoolOperations.existsPool | public boolean existsPool(String poolId, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
PoolExistsOptions options = new PoolExistsOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
return this.parentBatchClient.protocolLayer().pools().exists(poolId, options);
} | java | public boolean existsPool(String poolId, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
PoolExistsOptions options = new PoolExistsOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
return this.parentBatchClient.protocolLayer().pools().exists(poolId, options);
} | [
"public",
"boolean",
"existsPool",
"(",
"String",
"poolId",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"PoolExistsOptions",
"options",
"=",
"new",
"PoolExistsOptions",
"(",
")... | Checks whether the specified pool exists.
@param poolId
The ID of the pool.
@param additionalBehaviors
A collection of {@link BatchClientBehavior} instances that are
applied to the Batch service request.
@return True if the pool exists; otherwise, false.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service. | [
"Checks",
"whether",
"the",
"specified",
"pool",
"exists",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L1060-L1068 |
BotMill/fb-botmill | src/main/java/co/aurasphere/botmill/fb/internal/util/network/FbBotMillNetworkController.java | FbBotMillNetworkController.postFormDataMessage | public static void postFormDataMessage(String recipient,
AttachmentType type, File file) {
String pageToken = FbBotMillContext.getInstance().getPageToken();
// If the page token is invalid, returns.
if (!validatePageToken(pageToken)) {
return;
}
// TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
HttpPost post = new HttpPost(
FbBotMillNetworkConstants.FACEBOOK_BASE_URL
+ FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL
+ pageToken);
FileBody filedata = new FileBody(file);
StringBody recipientPart = new StringBody("{\"id\":\"" + recipient
+ "\"}", ContentType.MULTIPART_FORM_DATA);
StringBody messagePart = new StringBody("{\"attachment\":{\"type\":\""
+ type.name().toLowerCase() + "\", \"payload\":{}}}",
ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.STRICT);
builder.addPart("recipient", recipientPart);
builder.addPart("message", messagePart);
// builder.addPart("filedata", filedata);
builder.addBinaryBody("filedata", file);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
// builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
HttpEntity entity = builder.build();
post.setEntity(entity);
// Logs the raw JSON for debug purposes.
BufferedReader br;
// post.addHeader("Content-Type", "multipart/form-data");
try {
// br = new BufferedReader(new InputStreamReader(
// ())));
Header[] allHeaders = post.getAllHeaders();
for (Header h : allHeaders) {
logger.debug("Header {} -> {}", h.getName(), h.getValue());
}
// String output = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
// postInternal(post);
} | java | public static void postFormDataMessage(String recipient,
AttachmentType type, File file) {
String pageToken = FbBotMillContext.getInstance().getPageToken();
// If the page token is invalid, returns.
if (!validatePageToken(pageToken)) {
return;
}
// TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
HttpPost post = new HttpPost(
FbBotMillNetworkConstants.FACEBOOK_BASE_URL
+ FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL
+ pageToken);
FileBody filedata = new FileBody(file);
StringBody recipientPart = new StringBody("{\"id\":\"" + recipient
+ "\"}", ContentType.MULTIPART_FORM_DATA);
StringBody messagePart = new StringBody("{\"attachment\":{\"type\":\""
+ type.name().toLowerCase() + "\", \"payload\":{}}}",
ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.STRICT);
builder.addPart("recipient", recipientPart);
builder.addPart("message", messagePart);
// builder.addPart("filedata", filedata);
builder.addBinaryBody("filedata", file);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
// builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
HttpEntity entity = builder.build();
post.setEntity(entity);
// Logs the raw JSON for debug purposes.
BufferedReader br;
// post.addHeader("Content-Type", "multipart/form-data");
try {
// br = new BufferedReader(new InputStreamReader(
// ())));
Header[] allHeaders = post.getAllHeaders();
for (Header h : allHeaders) {
logger.debug("Header {} -> {}", h.getName(), h.getValue());
}
// String output = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
// postInternal(post);
} | [
"public",
"static",
"void",
"postFormDataMessage",
"(",
"String",
"recipient",
",",
"AttachmentType",
"type",
",",
"File",
"file",
")",
"{",
"String",
"pageToken",
"=",
"FbBotMillContext",
".",
"getInstance",
"(",
")",
".",
"getPageToken",
"(",
")",
";",
"// I... | POSTs a message as a JSON string to Facebook.
@param recipient
the recipient
@param type
the type
@param file
the file | [
"POSTs",
"a",
"message",
"as",
"a",
"JSON",
"string",
"to",
"Facebook",
"."
] | train | https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/internal/util/network/FbBotMillNetworkController.java#L478-L529 |
FXMisc/WellBehavedFX | src/main/java/org/fxmisc/wellbehaved/event/template/InputMapTemplate.java | InputMapTemplate.installFallback | public static <S extends Node, E extends Event> void installFallback(InputMapTemplate<S, E> imt, S node) {
Nodes.addFallbackInputMap(node, imt.instantiate(node));
} | java | public static <S extends Node, E extends Event> void installFallback(InputMapTemplate<S, E> imt, S node) {
Nodes.addFallbackInputMap(node, imt.instantiate(node));
} | [
"public",
"static",
"<",
"S",
"extends",
"Node",
",",
"E",
"extends",
"Event",
">",
"void",
"installFallback",
"(",
"InputMapTemplate",
"<",
"S",
",",
"E",
">",
"imt",
",",
"S",
"node",
")",
"{",
"Nodes",
".",
"addFallbackInputMap",
"(",
"node",
",",
"... | Instantiates the input map and installs it into the node via {@link Nodes#addFallbackInputMap(Node, InputMap)} | [
"Instantiates",
"the",
"input",
"map",
"and",
"installs",
"it",
"into",
"the",
"node",
"via",
"{"
] | train | https://github.com/FXMisc/WellBehavedFX/blob/ca889734481f5439655ca8deb6f742964b5654b0/src/main/java/org/fxmisc/wellbehaved/event/template/InputMapTemplate.java#L385-L387 |
infinispan/infinispan | persistence/remote/src/main/java/org/infinispan/persistence/remote/configuration/ExecutorFactoryConfigurationBuilder.java | ExecutorFactoryConfigurationBuilder.addExecutorProperty | public ExecutorFactoryConfigurationBuilder addExecutorProperty(String key, String value) {
TypedProperties properties = attributes.attribute(PROPERTIES).get();
properties.put(key, value);
attributes.attribute(PROPERTIES).set(properties);
return this;
} | java | public ExecutorFactoryConfigurationBuilder addExecutorProperty(String key, String value) {
TypedProperties properties = attributes.attribute(PROPERTIES).get();
properties.put(key, value);
attributes.attribute(PROPERTIES).set(properties);
return this;
} | [
"public",
"ExecutorFactoryConfigurationBuilder",
"addExecutorProperty",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"TypedProperties",
"properties",
"=",
"attributes",
".",
"attribute",
"(",
"PROPERTIES",
")",
".",
"get",
"(",
")",
";",
"properties",
"... | Add key/value property pair to this executor factory configuration
@param key
property key
@param value
property value
@return previous value if exists, null otherwise | [
"Add",
"key",
"/",
"value",
"property",
"pair",
"to",
"this",
"executor",
"factory",
"configuration"
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/persistence/remote/src/main/java/org/infinispan/persistence/remote/configuration/ExecutorFactoryConfigurationBuilder.java#L59-L64 |
aws/aws-sdk-java | aws-java-sdk-pi/src/main/java/com/amazonaws/services/pi/model/ResponseResourceMetricKey.java | ResponseResourceMetricKey.withDimensions | public ResponseResourceMetricKey withDimensions(java.util.Map<String, String> dimensions) {
setDimensions(dimensions);
return this;
} | java | public ResponseResourceMetricKey withDimensions(java.util.Map<String, String> dimensions) {
setDimensions(dimensions);
return this;
} | [
"public",
"ResponseResourceMetricKey",
"withDimensions",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"dimensions",
")",
"{",
"setDimensions",
"(",
"dimensions",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The valid dimensions for the metric.
</p>
@param dimensions
The valid dimensions for the metric.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"valid",
"dimensions",
"for",
"the",
"metric",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pi/src/main/java/com/amazonaws/services/pi/model/ResponseResourceMetricKey.java#L224-L227 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.deleteCertificateOperation | public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) {
return deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body();
} | java | public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) {
return deleteCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName).toBlocking().single().body();
} | [
"public",
"CertificateOperation",
"deleteCertificateOperation",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
")",
"{",
"return",
"deleteCertificateOperationWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"certificateName",
")",
".",
"toBlocking",
"(",... | Deletes the creation operation for a specific certificate.
Deletes the creation operation for a specified certificate that is in the process of being created. The certificate is no longer created. This operation requires the certificates/update permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws KeyVaultErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the CertificateOperation object if successful. | [
"Deletes",
"the",
"creation",
"operation",
"for",
"a",
"specific",
"certificate",
".",
"Deletes",
"the",
"creation",
"operation",
"for",
"a",
"specified",
"certificate",
"that",
"is",
"in",
"the",
"process",
"of",
"being",
"created",
".",
"The",
"certificate",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L7822-L7824 |
jbundle/jbundle | app/program/manual/util/src/main/java/org/jbundle/app/program/manual/util/WriteResourceClass.java | WriteResourceClass.writeResources | public void writeResources(String strClassName)
{
boolean bResourceListBundle = ResourceTypeField.LIST_RESOURCE_BUNDLE.equals(this.getRecord(ProgramControl.PROGRAM_CONTROL_FILE).getField(ProgramControl.CLASS_RESOURCE_TYPE).toString());
if (bResourceListBundle)
{
m_StreamOut.writeit("protected Object[][] contents = {\n");
m_StreamOut.setTabs(+1);
}
ClassResource recClassResource = new ClassResource(this);
recClassResource.setKeyArea(ClassResource.CLASS_NAME_KEY);
recClassResource.addListener(new StringSubFileFilter(strClassName, ClassResource.CLASS_NAME, null, null, null, null));
try {
recClassResource.close();
while (recClassResource.hasNext())
{
recClassResource.next();
if (bResourceListBundle)
m_StreamOut.writeit("{\"" + recClassResource.getField(ClassResource.KEY_NAME).toString()
+ "\"," + ResourcesUtilities.fixPropertyValue(recClassResource.getField(ClassResource.VALUE_NAME).toString(), bResourceListBundle) + "},\n");
else
m_StreamOut.writeit(recClassResource.getField(ClassResource.KEY_NAME).toString()
+ "=" + ResourcesUtilities.fixPropertyValue(recClassResource.getField(ClassResource.VALUE_NAME).toString(), bResourceListBundle) + "\n");
}
} catch (DBException ex) {
ex.printStackTrace();
}
recClassResource.free();
if (bResourceListBundle)
{
m_StreamOut.setTabs(-1);
m_StreamOut.writeit("};\n");
}
} | java | public void writeResources(String strClassName)
{
boolean bResourceListBundle = ResourceTypeField.LIST_RESOURCE_BUNDLE.equals(this.getRecord(ProgramControl.PROGRAM_CONTROL_FILE).getField(ProgramControl.CLASS_RESOURCE_TYPE).toString());
if (bResourceListBundle)
{
m_StreamOut.writeit("protected Object[][] contents = {\n");
m_StreamOut.setTabs(+1);
}
ClassResource recClassResource = new ClassResource(this);
recClassResource.setKeyArea(ClassResource.CLASS_NAME_KEY);
recClassResource.addListener(new StringSubFileFilter(strClassName, ClassResource.CLASS_NAME, null, null, null, null));
try {
recClassResource.close();
while (recClassResource.hasNext())
{
recClassResource.next();
if (bResourceListBundle)
m_StreamOut.writeit("{\"" + recClassResource.getField(ClassResource.KEY_NAME).toString()
+ "\"," + ResourcesUtilities.fixPropertyValue(recClassResource.getField(ClassResource.VALUE_NAME).toString(), bResourceListBundle) + "},\n");
else
m_StreamOut.writeit(recClassResource.getField(ClassResource.KEY_NAME).toString()
+ "=" + ResourcesUtilities.fixPropertyValue(recClassResource.getField(ClassResource.VALUE_NAME).toString(), bResourceListBundle) + "\n");
}
} catch (DBException ex) {
ex.printStackTrace();
}
recClassResource.free();
if (bResourceListBundle)
{
m_StreamOut.setTabs(-1);
m_StreamOut.writeit("};\n");
}
} | [
"public",
"void",
"writeResources",
"(",
"String",
"strClassName",
")",
"{",
"boolean",
"bResourceListBundle",
"=",
"ResourceTypeField",
".",
"LIST_RESOURCE_BUNDLE",
".",
"equals",
"(",
"this",
".",
"getRecord",
"(",
"ProgramControl",
".",
"PROGRAM_CONTROL_FILE",
")",... | Write out all the data fields for this class (not file fields!)
Required: strClassName - Current Class | [
"Write",
"out",
"all",
"the",
"data",
"fields",
"for",
"this",
"class",
"(",
"not",
"file",
"fields!",
")",
"Required",
":",
"strClassName",
"-",
"Current",
"Class"
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/manual/util/src/main/java/org/jbundle/app/program/manual/util/WriteResourceClass.java#L124-L156 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.order_orderId_payment_GET | public OvhPayment order_orderId_payment_GET(Long orderId) throws IOException {
String qPath = "/me/order/{orderId}/payment";
StringBuilder sb = path(qPath, orderId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPayment.class);
} | java | public OvhPayment order_orderId_payment_GET(Long orderId) throws IOException {
String qPath = "/me/order/{orderId}/payment";
StringBuilder sb = path(qPath, orderId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPayment.class);
} | [
"public",
"OvhPayment",
"order_orderId_payment_GET",
"(",
"Long",
"orderId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/order/{orderId}/payment\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"orderId",
")",
";",
"String",
"r... | Get this object properties
REST: GET /me/order/{orderId}/payment
@param orderId [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L1858-L1863 |
legsem/legstar-core2 | legstar-jaxb-generator/src/main/java/com/legstar/jaxb/generator/EachHelper.java | EachHelper.hashContext | private CharSequence hashContext(final Object context, final Options options)
throws IOException {
Set < Entry < String, Object >> propertySet = options
.propertySet(context);
StringBuilder buffer = new StringBuilder();
Context parent = options.context;
boolean first = true;
for (Entry < String, Object > entry : propertySet) {
Context current = Context.newBuilder(parent, entry.getValue())
.combine("@key", entry.getKey())
.combine("@first", first ? "first" : "").build();
buffer.append(options.fn(current));
current.destroy();
first = false;
}
return buffer.toString();
} | java | private CharSequence hashContext(final Object context, final Options options)
throws IOException {
Set < Entry < String, Object >> propertySet = options
.propertySet(context);
StringBuilder buffer = new StringBuilder();
Context parent = options.context;
boolean first = true;
for (Entry < String, Object > entry : propertySet) {
Context current = Context.newBuilder(parent, entry.getValue())
.combine("@key", entry.getKey())
.combine("@first", first ? "first" : "").build();
buffer.append(options.fn(current));
current.destroy();
first = false;
}
return buffer.toString();
} | [
"private",
"CharSequence",
"hashContext",
"(",
"final",
"Object",
"context",
",",
"final",
"Options",
"options",
")",
"throws",
"IOException",
"{",
"Set",
"<",
"Entry",
"<",
"String",
",",
"Object",
">",
">",
"propertySet",
"=",
"options",
".",
"propertySet",
... | Iterate over a hash like object.
@param context The context object.
@param options The helper options.
@return The string output.
@throws IOException If something goes wrong. | [
"Iterate",
"over",
"a",
"hash",
"like",
"object",
"."
] | train | https://github.com/legsem/legstar-core2/blob/f74d25d5b2b21a2ebaaaf2162b3fb7138dca40c6/legstar-jaxb-generator/src/main/java/com/legstar/jaxb/generator/EachHelper.java#L54-L70 |
hawkular/hawkular-agent | hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java | SocketBindingJBossASClient.setSocketBindingPort | public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, String interfaceName)
throws Exception {
setSocketBindingInterfaceExpression(socketBindingGroupName, socketBindingName, null, interfaceName);
} | java | public void setSocketBindingPort(String socketBindingGroupName, String socketBindingName, String interfaceName)
throws Exception {
setSocketBindingInterfaceExpression(socketBindingGroupName, socketBindingName, null, interfaceName);
} | [
"public",
"void",
"setSocketBindingPort",
"(",
"String",
"socketBindingGroupName",
",",
"String",
"socketBindingName",
",",
"String",
"interfaceName",
")",
"throws",
"Exception",
"{",
"setSocketBindingInterfaceExpression",
"(",
"socketBindingGroupName",
",",
"socketBindingNam... | Sets the interface name for the named socket binding found in the named socket binding group.
@param socketBindingGroupName the name of the socket binding group that has the named socket binding
@param socketBindingName the name of the socket binding whose interface is to be set
@param interfaceName the new interface name
@throws Exception any error | [
"Sets",
"the",
"interface",
"name",
"for",
"the",
"named",
"socket",
"binding",
"found",
"in",
"the",
"named",
"socket",
"binding",
"group",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SocketBindingJBossASClient.java#L306-L309 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rpc/akka/AkkaRpcServiceUtils.java | AkkaRpcServiceUtils.createRpcService | public static RpcService createRpcService(
String hostname,
String portRangeDefinition,
Configuration configuration,
String actorSystemName,
@Nonnull BootstrapTools.ActorSystemExecutorConfiguration actorSystemExecutorConfiguration) throws Exception {
final ActorSystem actorSystem = BootstrapTools.startActorSystem(
configuration,
actorSystemName,
hostname,
portRangeDefinition,
LOG,
actorSystemExecutorConfiguration);
return instantiateAkkaRpcService(configuration, actorSystem);
} | java | public static RpcService createRpcService(
String hostname,
String portRangeDefinition,
Configuration configuration,
String actorSystemName,
@Nonnull BootstrapTools.ActorSystemExecutorConfiguration actorSystemExecutorConfiguration) throws Exception {
final ActorSystem actorSystem = BootstrapTools.startActorSystem(
configuration,
actorSystemName,
hostname,
portRangeDefinition,
LOG,
actorSystemExecutorConfiguration);
return instantiateAkkaRpcService(configuration, actorSystem);
} | [
"public",
"static",
"RpcService",
"createRpcService",
"(",
"String",
"hostname",
",",
"String",
"portRangeDefinition",
",",
"Configuration",
"configuration",
",",
"String",
"actorSystemName",
",",
"@",
"Nonnull",
"BootstrapTools",
".",
"ActorSystemExecutorConfiguration",
... | Utility method to create RPC service from configuration and hostname, port.
@param hostname The hostname/address that describes the TaskManager's data location.
@param portRangeDefinition The port range to start TaskManager on.
@param configuration The configuration for the TaskManager.
@param actorSystemName The actor system name of the RpcService.
@param actorSystemExecutorConfiguration The configuration of the executor of the actor system.
@return The rpc service which is used to start and connect to the TaskManager RpcEndpoint .
@throws IOException Thrown, if the actor system can not bind to the address
@throws Exception Thrown is some other error occurs while creating akka actor system | [
"Utility",
"method",
"to",
"create",
"RPC",
"service",
"from",
"configuration",
"and",
"hostname",
"port",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/rpc/akka/AkkaRpcServiceUtils.java#L118-L134 |
threerings/narya | core/src/main/java/com/threerings/presents/dobj/DObject.java | DObject.addToSet | public <T extends DSet.Entry> void addToSet (String setName, T entry)
{
requestEntryAdd(setName, getSet(setName), entry);
} | java | public <T extends DSet.Entry> void addToSet (String setName, T entry)
{
requestEntryAdd(setName, getSet(setName), entry);
} | [
"public",
"<",
"T",
"extends",
"DSet",
".",
"Entry",
">",
"void",
"addToSet",
"(",
"String",
"setName",
",",
"T",
"entry",
")",
"{",
"requestEntryAdd",
"(",
"setName",
",",
"getSet",
"(",
"setName",
")",
",",
"entry",
")",
";",
"}"
] | Request to have the specified item added to the specified DSet. | [
"Request",
"to",
"have",
"the",
"specified",
"item",
"added",
"to",
"the",
"specified",
"DSet",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/dobj/DObject.java#L267-L270 |
overturetool/overture | core/codegen/vdm2jml/src/main/java/org/overture/codegen/vdm2jml/JmlGenerator.java | JmlGenerator.changeRecInvMethod | private void changeRecInvMethod(ARecordDeclIR rec)
{
try
{
rec.getInvariant().apply(new RecInvTransformation(javaGen, rec));
} catch (org.overture.codegen.ir.analysis.AnalysisException e)
{
log.error("Could not transform the invariant method of a record");
e.printStackTrace();
}
} | java | private void changeRecInvMethod(ARecordDeclIR rec)
{
try
{
rec.getInvariant().apply(new RecInvTransformation(javaGen, rec));
} catch (org.overture.codegen.ir.analysis.AnalysisException e)
{
log.error("Could not transform the invariant method of a record");
e.printStackTrace();
}
} | [
"private",
"void",
"changeRecInvMethod",
"(",
"ARecordDeclIR",
"rec",
")",
"{",
"try",
"{",
"rec",
".",
"getInvariant",
"(",
")",
".",
"apply",
"(",
"new",
"RecInvTransformation",
"(",
"javaGen",
",",
"rec",
")",
")",
";",
"}",
"catch",
"(",
"org",
".",
... | The record invariant method is generated such that it takes the record instance as an argument, e.g.
inv_Rec(recToCheck). When I try to invoke it from the instance invariant clause as //@ invariant inv_Rec(this);
it crashes on a stackoverflow where it keeps calling the invariant check. Adjusting the invariant method such
that it instead takes the fields as arguments does, however, work. This is exactly what this method does. After
calling this method a call to the invariant method from the invariant will take the following form: //@ public
instance invariant inv_Rec(field1,field2);
@param rec
The record for which we will change the invariant method | [
"The",
"record",
"invariant",
"method",
"is",
"generated",
"such",
"that",
"it",
"takes",
"the",
"record",
"instance",
"as",
"an",
"argument",
"e",
".",
"g",
".",
"inv_Rec",
"(",
"recToCheck",
")",
".",
"When",
"I",
"try",
"to",
"invoke",
"it",
"from",
... | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/codegen/vdm2jml/src/main/java/org/overture/codegen/vdm2jml/JmlGenerator.java#L543-L553 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java | Aggregations.comparableMin | public static <Key, Value> Aggregation<Key, Comparable, Comparable> comparableMin() {
return new AggregationAdapter(new ComparableMinAggregation<Key, Value>());
} | java | public static <Key, Value> Aggregation<Key, Comparable, Comparable> comparableMin() {
return new AggregationAdapter(new ComparableMinAggregation<Key, Value>());
} | [
"public",
"static",
"<",
"Key",
",",
"Value",
">",
"Aggregation",
"<",
"Key",
",",
"Comparable",
",",
"Comparable",
">",
"comparableMin",
"(",
")",
"{",
"return",
"new",
"AggregationAdapter",
"(",
"new",
"ComparableMinAggregation",
"<",
"Key",
",",
"Value",
... | Returns an aggregation to find the minimum value of all supplied
{@link java.lang.Comparable} implementing values.<br/>
This aggregation is similar to: <pre>SELECT MIN(value) FROM x</pre>
@param <Key> the input key type
@param <Value> the supplied value type
@return the minimum value over all supplied values | [
"Returns",
"an",
"aggregation",
"to",
"find",
"the",
"minimum",
"value",
"of",
"all",
"supplied",
"{",
"@link",
"java",
".",
"lang",
".",
"Comparable",
"}",
"implementing",
"values",
".",
"<br",
"/",
">",
"This",
"aggregation",
"is",
"similar",
"to",
":",
... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java#L351-L353 |
riversun/string-grabber | src/main/java/org/riversun/string_grabber/StringCropper.java | StringCropper.getAfterOfWithDetails | public StrPosition getAfterOfWithDetails(String srcStr, String token) {
return getAfterOfWithDetails(srcStr, token, true);
} | java | public StrPosition getAfterOfWithDetails(String srcStr, String token) {
return getAfterOfWithDetails(srcStr, token, true);
} | [
"public",
"StrPosition",
"getAfterOfWithDetails",
"(",
"String",
"srcStr",
",",
"String",
"token",
")",
"{",
"return",
"getAfterOfWithDetails",
"(",
"srcStr",
",",
"token",
",",
"true",
")",
";",
"}"
] | returns the string that is cropped after token with position-detail-info<br>
<br>
Method Example,<br>
<br>
getAfterOfWithDetails("AAABCDBCDEEE","BCD") returns str=EEE,
startIndex=9, endIndex=11<br>
@param srcStr
@param token
@return | [
"returns",
"the",
"string",
"that",
"is",
"cropped",
"after",
"token",
"with",
"position",
"-",
"detail",
"-",
"info<br",
">",
"<br",
">",
"Method",
"Example",
"<br",
">",
"<br",
">",
"getAfterOfWithDetails",
"(",
"AAABCDBCDEEE",
"BCD",
")",
"returns",
"str"... | train | https://github.com/riversun/string-grabber/blob/b5aadc21fe15f50d35392188dec6ab81dcf8d464/src/main/java/org/riversun/string_grabber/StringCropper.java#L300-L302 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java | ReUtil.replaceAll | public static String replaceAll(CharSequence content, Pattern pattern, String replacementTemplate) {
if (StrUtil.isEmpty(content)) {
return StrUtil.str(content);
}
final Matcher matcher = pattern.matcher(content);
boolean result = matcher.find();
if (result) {
final Set<String> varNums = findAll(PatternPool.GROUP_VAR, replacementTemplate, 1, new HashSet<String>());
final StringBuffer sb = new StringBuffer();
do {
String replacement = replacementTemplate;
for (String var : varNums) {
int group = Integer.parseInt(var);
replacement = replacement.replace("$" + var, matcher.group(group));
}
matcher.appendReplacement(sb, escape(replacement));
result = matcher.find();
} while (result);
matcher.appendTail(sb);
return sb.toString();
}
return StrUtil.str(content);
} | java | public static String replaceAll(CharSequence content, Pattern pattern, String replacementTemplate) {
if (StrUtil.isEmpty(content)) {
return StrUtil.str(content);
}
final Matcher matcher = pattern.matcher(content);
boolean result = matcher.find();
if (result) {
final Set<String> varNums = findAll(PatternPool.GROUP_VAR, replacementTemplate, 1, new HashSet<String>());
final StringBuffer sb = new StringBuffer();
do {
String replacement = replacementTemplate;
for (String var : varNums) {
int group = Integer.parseInt(var);
replacement = replacement.replace("$" + var, matcher.group(group));
}
matcher.appendReplacement(sb, escape(replacement));
result = matcher.find();
} while (result);
matcher.appendTail(sb);
return sb.toString();
}
return StrUtil.str(content);
} | [
"public",
"static",
"String",
"replaceAll",
"(",
"CharSequence",
"content",
",",
"Pattern",
"pattern",
",",
"String",
"replacementTemplate",
")",
"{",
"if",
"(",
"StrUtil",
".",
"isEmpty",
"(",
"content",
")",
")",
"{",
"return",
"StrUtil",
".",
"str",
"(",
... | 正则替换指定值<br>
通过正则查找到字符串,然后把匹配到的字符串加入到replacementTemplate中,$1表示分组1的字符串
@param content 文本
@param pattern {@link Pattern}
@param replacementTemplate 替换的文本模板,可以使用$1类似的变量提取正则匹配出的内容
@return 处理后的文本
@since 3.0.4 | [
"正则替换指定值<br",
">",
"通过正则查找到字符串,然后把匹配到的字符串加入到replacementTemplate中,$1表示分组1的字符串"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L615-L638 |
jbundle/jbundle | base/message/service/src/main/java/org/jbundle/base/message/service/ServiceTrxMessageIn.java | ServiceTrxMessageIn.getMessageBody | public org.w3c.dom.Node getMessageBody(Object rawData, boolean bReturnCopy)
{
return super.getMessageBody(rawData, bReturnCopy);
} | java | public org.w3c.dom.Node getMessageBody(Object rawData, boolean bReturnCopy)
{
return super.getMessageBody(rawData, bReturnCopy);
} | [
"public",
"org",
".",
"w3c",
".",
"dom",
".",
"Node",
"getMessageBody",
"(",
"Object",
"rawData",
",",
"boolean",
"bReturnCopy",
")",
"{",
"return",
"super",
".",
"getMessageBody",
"(",
"rawData",
",",
"bReturnCopy",
")",
";",
"}"
] | Get the SOAP message body as a DOM node.
@param message the SOAP message.
@param bReturnCopy Return a copy of the message node, instead of the actual node.
@return The DOM node containing the message body. | [
"Get",
"the",
"SOAP",
"message",
"body",
"as",
"a",
"DOM",
"node",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/service/src/main/java/org/jbundle/base/message/service/ServiceTrxMessageIn.java#L81-L84 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/HFSUtils.java | HFSUtils.getNumSector | public static long getNumSector(String requestSize, String sectorSize) {
Double memSize = Double.parseDouble(requestSize);
Double sectorBytes = Double.parseDouble(sectorSize);
Double nSectors = memSize / sectorBytes;
Double memSizeKB = memSize / 1024;
Double memSizeGB = memSize / (1024 * 1024 * 1024);
Double memSize100GB = memSizeGB / 100;
// allocation bitmap file: one bit per sector
Double allocBitmapSize = nSectors / 8;
// extend overflow file: 4MB, plus 4MB per 100GB
Double extOverflowFileSize = memSize100GB * 1024 * 1024 * 4;
// journal file: 8MB, plus 8MB per 100GB
Double journalFileSize = memSize100GB * 1024 * 1024 * 8;
// catalog file: 10bytes per KB
Double catalogFileSize = memSizeKB * 10;
// hot files: 5bytes per KB
Double hotFileSize = memSizeKB * 5;
// quota users file and quota groups file
Double quotaUsersFileSize = (memSizeGB * 256 + 1) * 64;
Double quotaGroupsFileSize = (memSizeGB * 32 + 1) * 64;
Double metadataSize = allocBitmapSize + extOverflowFileSize + journalFileSize
+ catalogFileSize + hotFileSize + quotaUsersFileSize + quotaGroupsFileSize;
Double allocSize = memSize + metadataSize;
Double numSectors = allocSize / sectorBytes;
System.out.println(numSectors.longValue() + 1); // round up
return numSectors.longValue() + 1;
} | java | public static long getNumSector(String requestSize, String sectorSize) {
Double memSize = Double.parseDouble(requestSize);
Double sectorBytes = Double.parseDouble(sectorSize);
Double nSectors = memSize / sectorBytes;
Double memSizeKB = memSize / 1024;
Double memSizeGB = memSize / (1024 * 1024 * 1024);
Double memSize100GB = memSizeGB / 100;
// allocation bitmap file: one bit per sector
Double allocBitmapSize = nSectors / 8;
// extend overflow file: 4MB, plus 4MB per 100GB
Double extOverflowFileSize = memSize100GB * 1024 * 1024 * 4;
// journal file: 8MB, plus 8MB per 100GB
Double journalFileSize = memSize100GB * 1024 * 1024 * 8;
// catalog file: 10bytes per KB
Double catalogFileSize = memSizeKB * 10;
// hot files: 5bytes per KB
Double hotFileSize = memSizeKB * 5;
// quota users file and quota groups file
Double quotaUsersFileSize = (memSizeGB * 256 + 1) * 64;
Double quotaGroupsFileSize = (memSizeGB * 32 + 1) * 64;
Double metadataSize = allocBitmapSize + extOverflowFileSize + journalFileSize
+ catalogFileSize + hotFileSize + quotaUsersFileSize + quotaGroupsFileSize;
Double allocSize = memSize + metadataSize;
Double numSectors = allocSize / sectorBytes;
System.out.println(numSectors.longValue() + 1); // round up
return numSectors.longValue() + 1;
} | [
"public",
"static",
"long",
"getNumSector",
"(",
"String",
"requestSize",
",",
"String",
"sectorSize",
")",
"{",
"Double",
"memSize",
"=",
"Double",
".",
"parseDouble",
"(",
"requestSize",
")",
";",
"Double",
"sectorBytes",
"=",
"Double",
".",
"parseDouble",
"... | Converts the memory size to number of sectors.
@param requestSize requested filesystem size in bytes
@param sectorSize the size of each sector in bytes
@return total sectors of HFS+ including estimated metadata zone size | [
"Converts",
"the",
"memory",
"size",
"to",
"number",
"of",
"sectors",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/HFSUtils.java#L29-L63 |
Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/matcher/Optimizer.java | Optimizer.inlineMatchAnyPrecedingOr | static Matcher inlineMatchAnyPrecedingOr(Matcher matcher) {
if (matcher instanceof ZeroOrMoreMatcher) {
ZeroOrMoreMatcher zm = matcher.as();
if (zm.repeated() instanceof AnyMatcher && zm.next() instanceof OrMatcher) {
List<Matcher> matchers = zm.next().<OrMatcher>as().matchers();
List<Matcher> ms = new ArrayList<>();
for (Matcher m : matchers) {
ms.add(new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, m));
}
return OrMatcher.create(ms);
}
}
return matcher;
} | java | static Matcher inlineMatchAnyPrecedingOr(Matcher matcher) {
if (matcher instanceof ZeroOrMoreMatcher) {
ZeroOrMoreMatcher zm = matcher.as();
if (zm.repeated() instanceof AnyMatcher && zm.next() instanceof OrMatcher) {
List<Matcher> matchers = zm.next().<OrMatcher>as().matchers();
List<Matcher> ms = new ArrayList<>();
for (Matcher m : matchers) {
ms.add(new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, m));
}
return OrMatcher.create(ms);
}
}
return matcher;
} | [
"static",
"Matcher",
"inlineMatchAnyPrecedingOr",
"(",
"Matcher",
"matcher",
")",
"{",
"if",
"(",
"matcher",
"instanceof",
"ZeroOrMoreMatcher",
")",
"{",
"ZeroOrMoreMatcher",
"zm",
"=",
"matcher",
".",
"as",
"(",
")",
";",
"if",
"(",
"zm",
".",
"repeated",
"... | If the matcher preceding an OR clause is a repeated any match, move into each branch
of the OR clause. This allows for other optimizations such as conversion to an indexOf
to take effect for each branch. | [
"If",
"the",
"matcher",
"preceding",
"an",
"OR",
"clause",
"is",
"a",
"repeated",
"any",
"match",
"move",
"into",
"each",
"branch",
"of",
"the",
"OR",
"clause",
".",
"This",
"allows",
"for",
"other",
"optimizations",
"such",
"as",
"conversion",
"to",
"an",... | train | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/Optimizer.java#L378-L391 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/MediaUtils.java | MediaUtils.revokePermissions | private static void revokePermissions(Context ctx, Uri uri){
ctx.revokeUriPermission(uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
} | java | private static void revokePermissions(Context ctx, Uri uri){
ctx.revokeUriPermission(uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
} | [
"private",
"static",
"void",
"revokePermissions",
"(",
"Context",
"ctx",
",",
"Uri",
"uri",
")",
"{",
"ctx",
".",
"revokeUriPermission",
"(",
"uri",
",",
"Intent",
".",
"FLAG_GRANT_WRITE_URI_PERMISSION",
"|",
"Intent",
".",
"FLAG_GRANT_READ_URI_PERMISSION",
")",
"... | Revoke URI permissions to a specific URI that had been previously granted | [
"Revoke",
"URI",
"permissions",
"to",
"a",
"specific",
"URI",
"that",
"had",
"been",
"previously",
"granted"
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/MediaUtils.java#L271-L275 |
awltech/org.parallelj | parallelj-core-parent/parallelj-core-api/src/main/java/org/parallelj/internal/kernel/KProgram.java | KProgram.newProcess | public KProcess newProcess(Object context) {
KProcess process = new KProcess(this, context);
this.init(process);
return process;
} | java | public KProcess newProcess(Object context) {
KProcess process = new KProcess(this, context);
this.init(process);
return process;
} | [
"public",
"KProcess",
"newProcess",
"(",
"Object",
"context",
")",
"{",
"KProcess",
"process",
"=",
"new",
"KProcess",
"(",
"this",
",",
"context",
")",
";",
"this",
".",
"init",
"(",
"process",
")",
";",
"return",
"process",
";",
"}"
] | Create a new {@link KProcess}
@param context
context linked to the program
@return a new program. | [
"Create",
"a",
"new",
"{",
"@link",
"KProcess",
"}"
] | train | https://github.com/awltech/org.parallelj/blob/2a2498cc4ac6227df6f45d295ec568cad3cffbc4/parallelj-core-parent/parallelj-core-api/src/main/java/org/parallelj/internal/kernel/KProgram.java#L104-L108 |
Syncleus/aparapi | src/main/java/com/aparapi/Range.java | Range.create2D | public static Range create2D(Device _device, int _globalWidth, int _globalHeight, int _localWidth, int _localHeight) {
final Range range = new Range(_device, 2);
range.setGlobalSize_0(_globalWidth);
range.setLocalSize_0(_localWidth);
range.setGlobalSize_1(_globalHeight);
range.setLocalSize_1(_localHeight);
range.setValid((range.getLocalSize_0() > 0) && (range.getLocalSize_1() > 0)
&& (range.getLocalSize_0() <= range.getMaxWorkItemSize()[0])
&& (range.getLocalSize_1() <= range.getMaxWorkItemSize()[1])
&& ((range.getLocalSize_0() * range.getLocalSize_1()) <= range.getMaxWorkGroupSize())
&& ((range.getGlobalSize_0() % range.getLocalSize_0()) == 0)
&& ((range.getGlobalSize_1() % range.getLocalSize_1()) == 0));
return (range);
} | java | public static Range create2D(Device _device, int _globalWidth, int _globalHeight, int _localWidth, int _localHeight) {
final Range range = new Range(_device, 2);
range.setGlobalSize_0(_globalWidth);
range.setLocalSize_0(_localWidth);
range.setGlobalSize_1(_globalHeight);
range.setLocalSize_1(_localHeight);
range.setValid((range.getLocalSize_0() > 0) && (range.getLocalSize_1() > 0)
&& (range.getLocalSize_0() <= range.getMaxWorkItemSize()[0])
&& (range.getLocalSize_1() <= range.getMaxWorkItemSize()[1])
&& ((range.getLocalSize_0() * range.getLocalSize_1()) <= range.getMaxWorkGroupSize())
&& ((range.getGlobalSize_0() % range.getLocalSize_0()) == 0)
&& ((range.getGlobalSize_1() % range.getLocalSize_1()) == 0));
return (range);
} | [
"public",
"static",
"Range",
"create2D",
"(",
"Device",
"_device",
",",
"int",
"_globalWidth",
",",
"int",
"_globalHeight",
",",
"int",
"_localWidth",
",",
"int",
"_localHeight",
")",
"{",
"final",
"Range",
"range",
"=",
"new",
"Range",
"(",
"_device",
",",
... | Create a two dimensional range 0.._globalWidth x 0.._globalHeight using a group which is _localWidth x _localHeight in size.
<br/>
Note that for this range to be valid _globalWidth > 0 && _globalHeight >0 && _localWidth>0 && _localHeight>0 && _localWidth*_localHeight < MAX_GROUP_SIZE && _globalWidth%_localWidth==0 && _globalHeight%_localHeight==0.
@param _globalWidth the overall range we wish to process
@return | [
"Create",
"a",
"two",
"dimensional",
"range",
"0",
"..",
"_globalWidth",
"x",
"0",
"..",
"_globalHeight",
"using",
"a",
"group",
"which",
"is",
"_localWidth",
"x",
"_localHeight",
"in",
"size",
".",
"<br",
"/",
">",
"Note",
"that",
"for",
"this",
"range",
... | train | https://github.com/Syncleus/aparapi/blob/6d5892c8e69854b3968c541023de37cf4762bd24/src/main/java/com/aparapi/Range.java#L207-L223 |
fcrepo4/fcrepo4 | fcrepo-http-commons/src/main/java/org/fcrepo/http/commons/session/SessionFactory.java | SessionFactory.getSessionFromTransaction | protected HttpSession getSessionFromTransaction(final HttpServletRequest servletRequest, final String txId) {
final Principal userPrincipal = servletRequest.getUserPrincipal();
final String userName = userPrincipal == null ? null : userPrincipal.getName();
final FedoraSession session = batchService.getSession(txId, userName);
final HttpSession batchSession = new HttpSession(session);
batchSession.makeBatchSession();
LOGGER.debug("Returning a session in the batch {} for user {}", batchSession, userName);
return batchSession;
} | java | protected HttpSession getSessionFromTransaction(final HttpServletRequest servletRequest, final String txId) {
final Principal userPrincipal = servletRequest.getUserPrincipal();
final String userName = userPrincipal == null ? null : userPrincipal.getName();
final FedoraSession session = batchService.getSession(txId, userName);
final HttpSession batchSession = new HttpSession(session);
batchSession.makeBatchSession();
LOGGER.debug("Returning a session in the batch {} for user {}", batchSession, userName);
return batchSession;
} | [
"protected",
"HttpSession",
"getSessionFromTransaction",
"(",
"final",
"HttpServletRequest",
"servletRequest",
",",
"final",
"String",
"txId",
")",
"{",
"final",
"Principal",
"userPrincipal",
"=",
"servletRequest",
".",
"getUserPrincipal",
"(",
")",
";",
"final",
"Str... | Retrieve a JCR session from an active transaction
@param servletRequest the servlet request
@param txId the transaction id
@return a JCR session that is associated with the transaction | [
"Retrieve",
"a",
"JCR",
"session",
"from",
"an",
"active",
"transaction"
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-commons/src/main/java/org/fcrepo/http/commons/session/SessionFactory.java#L146-L156 |
Red5/red5-server-common | src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java | RTMPHandshake.verifyDigest | public boolean verifyDigest(int digestPos, byte[] handshakeMessage, byte[] key, int keyLen) {
if (log.isTraceEnabled()) {
log.trace("verifyDigest - digestPos: {} keyLen: {} handshake size: {} ", digestPos, keyLen, handshakeMessage.length);
}
byte[] calcDigest = new byte[DIGEST_LENGTH];
calculateDigest(digestPos, handshakeMessage, 0, key, keyLen, calcDigest, 0);
if (!Arrays.equals(Arrays.copyOfRange(handshakeMessage, digestPos, (digestPos + DIGEST_LENGTH)), calcDigest)) {
return false;
}
return true;
} | java | public boolean verifyDigest(int digestPos, byte[] handshakeMessage, byte[] key, int keyLen) {
if (log.isTraceEnabled()) {
log.trace("verifyDigest - digestPos: {} keyLen: {} handshake size: {} ", digestPos, keyLen, handshakeMessage.length);
}
byte[] calcDigest = new byte[DIGEST_LENGTH];
calculateDigest(digestPos, handshakeMessage, 0, key, keyLen, calcDigest, 0);
if (!Arrays.equals(Arrays.copyOfRange(handshakeMessage, digestPos, (digestPos + DIGEST_LENGTH)), calcDigest)) {
return false;
}
return true;
} | [
"public",
"boolean",
"verifyDigest",
"(",
"int",
"digestPos",
",",
"byte",
"[",
"]",
"handshakeMessage",
",",
"byte",
"[",
"]",
"key",
",",
"int",
"keyLen",
")",
"{",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"trace",
"... | Verifies the digest.
@param digestPos digest position
@param handshakeMessage handshake message
@param key contains the key
@param keyLen the length of the key
@return true if valid and false otherwise | [
"Verifies",
"the",
"digest",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandshake.java#L346-L356 |
dima767/inspektr | inspektr-support-spring/src/main/java/com/github/inspektr/audit/support/AbstractWhereClauseMatchCriteria.java | AbstractWhereClauseMatchCriteria.addCriteria | protected void addCriteria(String column, String operator) {
if (this.sbClause.length() == 0) {
this.sbClause.append("WHERE");
} else {
this.sbClause.append(" AND");
}
this.sbClause.append(' ');
this.sbClause.append(column);
this.sbClause.append(' ');
this.sbClause.append(operator);
this.sbClause.append(" ?");
} | java | protected void addCriteria(String column, String operator) {
if (this.sbClause.length() == 0) {
this.sbClause.append("WHERE");
} else {
this.sbClause.append(" AND");
}
this.sbClause.append(' ');
this.sbClause.append(column);
this.sbClause.append(' ');
this.sbClause.append(operator);
this.sbClause.append(" ?");
} | [
"protected",
"void",
"addCriteria",
"(",
"String",
"column",
",",
"String",
"operator",
")",
"{",
"if",
"(",
"this",
".",
"sbClause",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"this",
".",
"sbClause",
".",
"append",
"(",
"\"WHERE\"",
")",
";",
"}... | Adds a parameterized selection criterion of the form "column [operator] ?"
to the where clause.
@param column Database column name.
@param operator the operator to use to separate. | [
"Adds",
"a",
"parameterized",
"selection",
"criterion",
"of",
"the",
"form",
"column",
"[",
"operator",
"]",
"?",
"to",
"the",
"where",
"clause",
"."
] | train | https://github.com/dima767/inspektr/blob/ec5128712a28f9371f1041a4f2063fc7eec04228/inspektr-support-spring/src/main/java/com/github/inspektr/audit/support/AbstractWhereClauseMatchCriteria.java#L68-L79 |
alkacon/opencms-core | src/org/opencms/ade/contenteditor/CmsContentService.java | CmsContentService.checkAutoCorrection | private boolean checkAutoCorrection(CmsObject cms, CmsXmlContent content) throws CmsXmlException {
boolean performedAutoCorrection = false;
try {
content.validateXmlStructure(new CmsXmlEntityResolver(cms));
} catch (CmsXmlException eXml) {
// validation failed
content.setAutoCorrectionEnabled(true);
content.correctXmlStructure(cms);
performedAutoCorrection = true;
}
return performedAutoCorrection;
} | java | private boolean checkAutoCorrection(CmsObject cms, CmsXmlContent content) throws CmsXmlException {
boolean performedAutoCorrection = false;
try {
content.validateXmlStructure(new CmsXmlEntityResolver(cms));
} catch (CmsXmlException eXml) {
// validation failed
content.setAutoCorrectionEnabled(true);
content.correctXmlStructure(cms);
performedAutoCorrection = true;
}
return performedAutoCorrection;
} | [
"private",
"boolean",
"checkAutoCorrection",
"(",
"CmsObject",
"cms",
",",
"CmsXmlContent",
"content",
")",
"throws",
"CmsXmlException",
"{",
"boolean",
"performedAutoCorrection",
"=",
"false",
";",
"try",
"{",
"content",
".",
"validateXmlStructure",
"(",
"new",
"Cm... | Check if automatic content correction is required. Returns <code>true</code> if the content was changed.<p>
@param cms the cms context
@param content the content to check
@return <code>true</code> if the content was changed
@throws CmsXmlException if the automatic content correction failed | [
"Check",
"if",
"automatic",
"content",
"correction",
"is",
"required",
".",
"Returns",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"the",
"content",
"was",
"changed",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/contenteditor/CmsContentService.java#L1532-L1544 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java | Arc42DocumentationTemplate.addIntroductionAndGoalsSection | public Section addIntroductionAndGoalsSection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Introduction and Goals", files);
} | java | public Section addIntroductionAndGoalsSection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Introduction and Goals", files);
} | [
"public",
"Section",
"addIntroductionAndGoalsSection",
"(",
"SoftwareSystem",
"softwareSystem",
",",
"File",
"...",
"files",
")",
"throws",
"IOException",
"{",
"return",
"addSection",
"(",
"softwareSystem",
",",
"\"Introduction and Goals\"",
",",
"files",
")",
";",
"}... | Adds a "Introduction and Goals" section relating to a {@link SoftwareSystem} from one or more files.
@param softwareSystem the {@link SoftwareSystem} the documentation content relates to
@param files one or more File objects that point to the documentation content
@return a documentation {@link Section}
@throws IOException if there is an error reading the files | [
"Adds",
"a",
"Introduction",
"and",
"Goals",
"section",
"relating",
"to",
"a",
"{",
"@link",
"SoftwareSystem",
"}",
"from",
"one",
"or",
"more",
"files",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java#L49-L51 |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDFactoryDaoImpl.java | GeneratedDFactoryDaoImpl.queryByClientId | public Iterable<DFactory> queryByClientId(java.lang.String clientId) {
return queryByField(null, DFactoryMapper.Field.CLIENTID.getFieldName(), clientId);
} | java | public Iterable<DFactory> queryByClientId(java.lang.String clientId) {
return queryByField(null, DFactoryMapper.Field.CLIENTID.getFieldName(), clientId);
} | [
"public",
"Iterable",
"<",
"DFactory",
">",
"queryByClientId",
"(",
"java",
".",
"lang",
".",
"String",
"clientId",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"DFactoryMapper",
".",
"Field",
".",
"CLIENTID",
".",
"getFieldName",
"(",
")",
",",
"... | query-by method for field clientId
@param clientId the specified attribute
@return an Iterable of DFactorys for the specified clientId | [
"query",
"-",
"by",
"method",
"for",
"field",
"clientId"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDFactoryDaoImpl.java#L79-L81 |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java | MagickUtil.paletteToBuffered | private static BufferedImage paletteToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
// Create indexcolormodel for the image
IndexColorModel cm;
try {
cm = createIndexColorModel(pImage.getColormap(), pAlpha);
}
catch (MagickException e) {
// NOTE: Some MagickImages incorrecly (?) reports to be paletteType,
// but does not have a colormap, this is a workaround.
return rgbToBuffered(pImage, pAlpha);
}
// As there is no way to get the indexes of an indexed image, convert to
// RGB, and the create an indexed image from it
BufferedImage temp = rgbToBuffered(pImage, pAlpha);
BufferedImage image;
if (cm.getMapSize() <= 16) {
image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_BINARY, cm);
}
else {
image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_INDEXED, cm);
}
// Create transparent background for images containing alpha
if (pAlpha) {
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, temp.getWidth(), temp.getHeight());
}
finally {
g.dispose();
}
}
// NOTE: This is (surprisingly) much faster than using g2d.drawImage()..
// (Tests shows 20-30ms, vs. 600-700ms on the same image)
BufferedImageOp op = new CopyDither(cm);
op.filter(temp, image);
return image;
} | java | private static BufferedImage paletteToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException {
// Create indexcolormodel for the image
IndexColorModel cm;
try {
cm = createIndexColorModel(pImage.getColormap(), pAlpha);
}
catch (MagickException e) {
// NOTE: Some MagickImages incorrecly (?) reports to be paletteType,
// but does not have a colormap, this is a workaround.
return rgbToBuffered(pImage, pAlpha);
}
// As there is no way to get the indexes of an indexed image, convert to
// RGB, and the create an indexed image from it
BufferedImage temp = rgbToBuffered(pImage, pAlpha);
BufferedImage image;
if (cm.getMapSize() <= 16) {
image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_BINARY, cm);
}
else {
image = new BufferedImage(temp.getWidth(), temp.getHeight(), BufferedImage.TYPE_BYTE_INDEXED, cm);
}
// Create transparent background for images containing alpha
if (pAlpha) {
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, temp.getWidth(), temp.getHeight());
}
finally {
g.dispose();
}
}
// NOTE: This is (surprisingly) much faster than using g2d.drawImage()..
// (Tests shows 20-30ms, vs. 600-700ms on the same image)
BufferedImageOp op = new CopyDither(cm);
op.filter(temp, image);
return image;
} | [
"private",
"static",
"BufferedImage",
"paletteToBuffered",
"(",
"MagickImage",
"pImage",
",",
"boolean",
"pAlpha",
")",
"throws",
"MagickException",
"{",
"// Create indexcolormodel for the image\r",
"IndexColorModel",
"cm",
";",
"try",
"{",
"cm",
"=",
"createIndexColorMod... | Converts a palette-based {@code MagickImage} to a
{@code BufferedImage}, of type {@code TYPE_BYTE_BINARY} (for images
with a palette of <= 16 colors) or {@code TYPE_BYTE_INDEXED}.
@param pImage the original {@code MagickImage}
@param pAlpha keep alpha channel
@return a new {@code BufferedImage}
@throws MagickException if an exception occurs during conversion
@see BufferedImage | [
"Converts",
"a",
"palette",
"-",
"based",
"{",
"@code",
"MagickImage",
"}",
"to",
"a",
"{",
"@code",
"BufferedImage",
"}",
"of",
"type",
"{",
"@code",
"TYPE_BYTE_BINARY",
"}",
"(",
"for",
"images",
"with",
"a",
"palette",
"of",
"<",
"=",
"16",
"colors",
... | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java#L445-L488 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/classify/LinearClassifier.java | LinearClassifier.scoreOf | private double scoreOf(int[] feats, L label) {
int iLabel = labelIndex.indexOf(label);
double score = 0.0;
for (int feat : feats) {
score += weight(feat, iLabel);
}
return score + thresholds[iLabel];
} | java | private double scoreOf(int[] feats, L label) {
int iLabel = labelIndex.indexOf(label);
double score = 0.0;
for (int feat : feats) {
score += weight(feat, iLabel);
}
return score + thresholds[iLabel];
} | [
"private",
"double",
"scoreOf",
"(",
"int",
"[",
"]",
"feats",
",",
"L",
"label",
")",
"{",
"int",
"iLabel",
"=",
"labelIndex",
".",
"indexOf",
"(",
"label",
")",
";",
"double",
"score",
"=",
"0.0",
";",
"for",
"(",
"int",
"feat",
":",
"feats",
")"... | Returns of the score of the Datum as internalized features for the
specified label. Ignores the true label of the Datum.
Doesn't consider a value for each feature. | [
"Returns",
"of",
"the",
"score",
"of",
"the",
"Datum",
"as",
"internalized",
"features",
"for",
"the",
"specified",
"label",
".",
"Ignores",
"the",
"true",
"label",
"of",
"the",
"Datum",
".",
"Doesn",
"t",
"consider",
"a",
"value",
"for",
"each",
"feature"... | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LinearClassifier.java#L234-L241 |
diegossilveira/jcors | src/main/java/org/jcors/util/Constraint.java | Constraint.ensureNotEmpty | public static void ensureNotEmpty(String string, String errorMessage) {
ensureNotNull(string, errorMessage);
ensure(string.trim().length() > 0, errorMessage);
} | java | public static void ensureNotEmpty(String string, String errorMessage) {
ensureNotNull(string, errorMessage);
ensure(string.trim().length() > 0, errorMessage);
} | [
"public",
"static",
"void",
"ensureNotEmpty",
"(",
"String",
"string",
",",
"String",
"errorMessage",
")",
"{",
"ensureNotNull",
"(",
"string",
",",
"errorMessage",
")",
";",
"ensure",
"(",
"string",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
">",
"... | Ensures that a String is not empty
@param string
@param errorMessage | [
"Ensures",
"that",
"a",
"String",
"is",
"not",
"empty"
] | train | https://github.com/diegossilveira/jcors/blob/cd56a9e2055d629baa42f93b27dd5615ced9632f/src/main/java/org/jcors/util/Constraint.java#L30-L34 |
threerings/nenya | core/src/main/java/com/threerings/miso/client/MisoScenePanel.java | MisoScenePanel.getTipText | protected String getTipText (SceneObject scobj, String action)
{
ObjectActionHandler oah = ObjectActionHandler.lookup(action);
return (oah == null) ? action : oah.getTipText(action);
} | java | protected String getTipText (SceneObject scobj, String action)
{
ObjectActionHandler oah = ObjectActionHandler.lookup(action);
return (oah == null) ? action : oah.getTipText(action);
} | [
"protected",
"String",
"getTipText",
"(",
"SceneObject",
"scobj",
",",
"String",
"action",
")",
"{",
"ObjectActionHandler",
"oah",
"=",
"ObjectActionHandler",
".",
"lookup",
"(",
"action",
")",
";",
"return",
"(",
"oah",
"==",
"null",
")",
"?",
"action",
":"... | Derived classes can provide human readable object tips via this method. | [
"Derived",
"classes",
"can",
"provide",
"human",
"readable",
"object",
"tips",
"via",
"this",
"method",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L1083-L1087 |
BellaDati/belladati-sdk-java | src/main/java/com/belladati/sdk/impl/BellaDatiServiceImpl.java | BellaDatiServiceImpl.appendLocale | public URIBuilder appendLocale(URIBuilder builder, Locale locale) {
if (locale != null) {
builder.addParameter("lang", locale.getLanguage());
}
return builder;
} | java | public URIBuilder appendLocale(URIBuilder builder, Locale locale) {
if (locale != null) {
builder.addParameter("lang", locale.getLanguage());
}
return builder;
} | [
"public",
"URIBuilder",
"appendLocale",
"(",
"URIBuilder",
"builder",
",",
"Locale",
"locale",
")",
"{",
"if",
"(",
"locale",
"!=",
"null",
")",
"{",
"builder",
".",
"addParameter",
"(",
"\"lang\"",
",",
"locale",
".",
"getLanguage",
"(",
")",
")",
";",
... | Appends a locale language parameter to the URI builder. Won't do anything
if the locale is <tt>null</tt>.
@param builder the builder to append to
@param locale the locale to append
@return the same builder, for chaining | [
"Appends",
"a",
"locale",
"language",
"parameter",
"to",
"the",
"URI",
"builder",
".",
"Won",
"t",
"do",
"anything",
"if",
"the",
"locale",
"is",
"<tt",
">",
"null<",
"/",
"tt",
">",
"."
] | train | https://github.com/BellaDati/belladati-sdk-java/blob/1a732a57ebc825ddf47ce405723cc958adb1a43f/src/main/java/com/belladati/sdk/impl/BellaDatiServiceImpl.java#L428-L433 |
mgledi/DRUMS | src/main/java/com/unister/semweb/drums/api/DRUMS.java | DRUMS.findElementInReadBuffer | public int findElementInReadBuffer(ByteBuffer workingBuffer, byte[] key, int indexInChunk) {
workingBuffer.position(indexInChunk);
int minElement = indexInChunk / gp.getElementSize();
int numberOfEntries = workingBuffer.limit() / gp.getElementSize();
// binary search
int maxElement = numberOfEntries - 1;
int midElement;
int comp;
byte[] tempKey = new byte[gp.getKeySize()];
while (minElement <= maxElement) {
midElement = minElement + (maxElement - minElement) / 2;
indexInChunk = midElement * gp.getElementSize();
workingBuffer.position(indexInChunk);
workingBuffer.get(tempKey);
comp = KeyUtils.compareKey(key, tempKey, gp.getKeySize());
if (comp == 0) {
return indexInChunk;
} else if (comp < 0) {
maxElement = midElement - 1;
} else {
minElement = midElement + 1;
}
}
return -1;
} | java | public int findElementInReadBuffer(ByteBuffer workingBuffer, byte[] key, int indexInChunk) {
workingBuffer.position(indexInChunk);
int minElement = indexInChunk / gp.getElementSize();
int numberOfEntries = workingBuffer.limit() / gp.getElementSize();
// binary search
int maxElement = numberOfEntries - 1;
int midElement;
int comp;
byte[] tempKey = new byte[gp.getKeySize()];
while (minElement <= maxElement) {
midElement = minElement + (maxElement - minElement) / 2;
indexInChunk = midElement * gp.getElementSize();
workingBuffer.position(indexInChunk);
workingBuffer.get(tempKey);
comp = KeyUtils.compareKey(key, tempKey, gp.getKeySize());
if (comp == 0) {
return indexInChunk;
} else if (comp < 0) {
maxElement = midElement - 1;
} else {
minElement = midElement + 1;
}
}
return -1;
} | [
"public",
"int",
"findElementInReadBuffer",
"(",
"ByteBuffer",
"workingBuffer",
",",
"byte",
"[",
"]",
"key",
",",
"int",
"indexInChunk",
")",
"{",
"workingBuffer",
".",
"position",
"(",
"indexInChunk",
")",
";",
"int",
"minElement",
"=",
"indexInChunk",
"/",
... | Searches for the given key in workingBuffer, beginning at the given index. Remember: The records in the
given workingBuffer have to be ordered ascending.
@param workingBuffer
the ByteBuffer to work on
@param key
the key to find
@param indexInChunk
the start position of reading the <code>workingBuffer</code>
@return the byteOffset where the key was found.<br>
-1 if the key wasn't found | [
"Searches",
"for",
"the",
"given",
"key",
"in",
"workingBuffer",
"beginning",
"at",
"the",
"given",
"index",
".",
"Remember",
":",
"The",
"records",
"in",
"the",
"given",
"workingBuffer",
"have",
"to",
"be",
"ordered",
"ascending",
"."
] | train | https://github.com/mgledi/DRUMS/blob/a670f17a2186c9a15725f26617d77ce8e444e072/src/main/java/com/unister/semweb/drums/api/DRUMS.java#L407-L435 |
opsmatters/newrelic-api | src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java | HttpContext.PATCH | public <T> Optional<T> PATCH(String partialUrl, Object payload,
Map<String, Object> headers, List<String> queryParams, GenericType<T> returnType)
{
URI uri = buildUri(partialUrl);
return executePatchRequest(uri, payload, headers, queryParams, returnType);
} | java | public <T> Optional<T> PATCH(String partialUrl, Object payload,
Map<String, Object> headers, List<String> queryParams, GenericType<T> returnType)
{
URI uri = buildUri(partialUrl);
return executePatchRequest(uri, payload, headers, queryParams, returnType);
} | [
"public",
"<",
"T",
">",
"Optional",
"<",
"T",
">",
"PATCH",
"(",
"String",
"partialUrl",
",",
"Object",
"payload",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"headers",
",",
"List",
"<",
"String",
">",
"queryParams",
",",
"GenericType",
"<",
"T",
... | Execute a PATCH call against the partial URL.
@param <T> The type parameter used for the return object
@param partialUrl The partial URL to build
@param payload The object to use for the PATCH
@param headers A set of headers to add to the request
@param queryParams A set of query parameters to add to the request
@param returnType The expected return type
@return The return type | [
"Execute",
"a",
"PATCH",
"call",
"against",
"the",
"partial",
"URL",
"."
] | train | https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L291-L296 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/TimestampUtils.java | TimestampUtils.toTimestamp | public synchronized Timestamp toTimestamp(Calendar cal, String s) throws SQLException {
if (s == null) {
return null;
}
int slen = s.length();
// convert postgres's infinity values to internal infinity magic value
if (slen == 8 && s.equals("infinity")) {
return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY);
}
if (slen == 9 && s.equals("-infinity")) {
return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY);
}
ParsedTimestamp ts = parseBackendTimestamp(s);
Calendar useCal = ts.tz != null ? ts.tz : setupCalendar(cal);
useCal.set(Calendar.ERA, ts.era);
useCal.set(Calendar.YEAR, ts.year);
useCal.set(Calendar.MONTH, ts.month - 1);
useCal.set(Calendar.DAY_OF_MONTH, ts.day);
useCal.set(Calendar.HOUR_OF_DAY, ts.hour);
useCal.set(Calendar.MINUTE, ts.minute);
useCal.set(Calendar.SECOND, ts.second);
useCal.set(Calendar.MILLISECOND, 0);
Timestamp result = new Timestamp(useCal.getTimeInMillis());
result.setNanos(ts.nanos);
return result;
} | java | public synchronized Timestamp toTimestamp(Calendar cal, String s) throws SQLException {
if (s == null) {
return null;
}
int slen = s.length();
// convert postgres's infinity values to internal infinity magic value
if (slen == 8 && s.equals("infinity")) {
return new Timestamp(PGStatement.DATE_POSITIVE_INFINITY);
}
if (slen == 9 && s.equals("-infinity")) {
return new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY);
}
ParsedTimestamp ts = parseBackendTimestamp(s);
Calendar useCal = ts.tz != null ? ts.tz : setupCalendar(cal);
useCal.set(Calendar.ERA, ts.era);
useCal.set(Calendar.YEAR, ts.year);
useCal.set(Calendar.MONTH, ts.month - 1);
useCal.set(Calendar.DAY_OF_MONTH, ts.day);
useCal.set(Calendar.HOUR_OF_DAY, ts.hour);
useCal.set(Calendar.MINUTE, ts.minute);
useCal.set(Calendar.SECOND, ts.second);
useCal.set(Calendar.MILLISECOND, 0);
Timestamp result = new Timestamp(useCal.getTimeInMillis());
result.setNanos(ts.nanos);
return result;
} | [
"public",
"synchronized",
"Timestamp",
"toTimestamp",
"(",
"Calendar",
"cal",
",",
"String",
"s",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"int",
"slen",
"=",
"s",
".",
"length",
"(",
")",
... | Parse a string and return a timestamp representing its value.
@param cal calendar to be used to parse the input string
@param s The ISO formated date string to parse.
@return null if s is null or a timestamp of the parsed string s.
@throws SQLException if there is a problem parsing s. | [
"Parse",
"a",
"string",
"and",
"return",
"a",
"timestamp",
"representing",
"its",
"value",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/TimestampUtils.java#L379-L409 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.hosting_web_serviceName_upgrade_GET | public ArrayList<String> hosting_web_serviceName_upgrade_GET(String serviceName, net.minidev.ovh.api.hosting.web.OvhOfferEnum offer, Boolean waiveRetractationPeriod) throws IOException {
String qPath = "/order/hosting/web/{serviceName}/upgrade";
StringBuilder sb = path(qPath, serviceName);
query(sb, "offer", offer);
query(sb, "waiveRetractationPeriod", waiveRetractationPeriod);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> hosting_web_serviceName_upgrade_GET(String serviceName, net.minidev.ovh.api.hosting.web.OvhOfferEnum offer, Boolean waiveRetractationPeriod) throws IOException {
String qPath = "/order/hosting/web/{serviceName}/upgrade";
StringBuilder sb = path(qPath, serviceName);
query(sb, "offer", offer);
query(sb, "waiveRetractationPeriod", waiveRetractationPeriod);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"hosting_web_serviceName_upgrade_GET",
"(",
"String",
"serviceName",
",",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"hosting",
".",
"web",
".",
"OvhOfferEnum",
"offer",
",",
"Boolean",
"waiveRetractationPeriod",... | Get allowed durations for 'upgrade' option
REST: GET /order/hosting/web/{serviceName}/upgrade
@param offer [required] New offers for your hosting account
@param waiveRetractationPeriod [required] Indicates that order will be processed with waiving retractation period
@param serviceName [required] The internal name of your hosting | [
"Get",
"allowed",
"durations",
"for",
"upgrade",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L4980-L4987 |
alkacon/opencms-core | src/org/opencms/xml/containerpage/CmsContainerElementBean.java | CmsContainerElementBean.updateIndividualSettings | public void updateIndividualSettings(Map<String, String> newSettings) {
m_individualSettings = Collections.unmodifiableMap(newSettings);
setSettings(getIndividualSettings());
} | java | public void updateIndividualSettings(Map<String, String> newSettings) {
m_individualSettings = Collections.unmodifiableMap(newSettings);
setSettings(getIndividualSettings());
} | [
"public",
"void",
"updateIndividualSettings",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"newSettings",
")",
"{",
"m_individualSettings",
"=",
"Collections",
".",
"unmodifiableMap",
"(",
"newSettings",
")",
";",
"setSettings",
"(",
"getIndividualSettings",
"(",
... | Updates the individual settings.<p>
This causes all merged settings (from defaults etc.) to be lost.
@param newSettings the new settings | [
"Updates",
"the",
"individual",
"settings",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsContainerElementBean.java#L786-L790 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/WebContainer.java | WebContainer.removeExtraPathInfo | private PathInfoHelper removeExtraPathInfo(String pathInfo) {
if (pathInfo == null)
return null;
int semicolon = pathInfo.indexOf(';');
if (semicolon != -1) {
String tmpPathInfo = pathInfo.substring(0, semicolon);
String extraPathInfo = pathInfo.substring(semicolon);
return new PathInfoHelper(tmpPathInfo, extraPathInfo);
}
return new PathInfoHelper(pathInfo, null);
} | java | private PathInfoHelper removeExtraPathInfo(String pathInfo) {
if (pathInfo == null)
return null;
int semicolon = pathInfo.indexOf(';');
if (semicolon != -1) {
String tmpPathInfo = pathInfo.substring(0, semicolon);
String extraPathInfo = pathInfo.substring(semicolon);
return new PathInfoHelper(tmpPathInfo, extraPathInfo);
}
return new PathInfoHelper(pathInfo, null);
} | [
"private",
"PathInfoHelper",
"removeExtraPathInfo",
"(",
"String",
"pathInfo",
")",
"{",
"if",
"(",
"pathInfo",
"==",
"null",
")",
"return",
"null",
";",
"int",
"semicolon",
"=",
"pathInfo",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"semicolon",
... | begin 272738 Duplicate CacheServletWrappers when url-rewriting is enabled WAS.webcontainer | [
"begin",
"272738",
"Duplicate",
"CacheServletWrappers",
"when",
"url",
"-",
"rewriting",
"is",
"enabled",
"WAS",
".",
"webcontainer"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/WebContainer.java#L1512-L1524 |
JM-Lab/utils-elasticsearch | src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchSearchAndCount.java | JMElasticsearchSearchAndCount.searchAll | public SearchResponse searchAll(String[] indices, String type) {
return searchAll(indices, JMArrays.buildArray(type));
} | java | public SearchResponse searchAll(String[] indices, String type) {
return searchAll(indices, JMArrays.buildArray(type));
} | [
"public",
"SearchResponse",
"searchAll",
"(",
"String",
"[",
"]",
"indices",
",",
"String",
"type",
")",
"{",
"return",
"searchAll",
"(",
"indices",
",",
"JMArrays",
".",
"buildArray",
"(",
"type",
")",
")",
";",
"}"
] | Search all search response.
@param indices the indices
@param type the type
@return the search response | [
"Search",
"all",
"search",
"response",
"."
] | train | https://github.com/JM-Lab/utils-elasticsearch/blob/6ccec90e1e51d65d2af5efbb6d7b9f9bad90e638/src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchSearchAndCount.java#L432-L434 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/refer/References.java | References.getOneOptional | public <T> T getOneOptional(Class<T> type, Object locator) {
try {
List<T> components = find(type, locator, false);
return components.size() > 0 ? components.get(0) : null;
} catch (Exception ex) {
return null;
}
} | java | public <T> T getOneOptional(Class<T> type, Object locator) {
try {
List<T> components = find(type, locator, false);
return components.size() > 0 ? components.get(0) : null;
} catch (Exception ex) {
return null;
}
} | [
"public",
"<",
"T",
">",
"T",
"getOneOptional",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"Object",
"locator",
")",
"{",
"try",
"{",
"List",
"<",
"T",
">",
"components",
"=",
"find",
"(",
"type",
",",
"locator",
",",
"false",
")",
";",
"return",
... | Gets an optional component reference that matches specified locator and
matching to the specified type.
@param type the Class type that defined the type of the result.
@param locator the locator to find references by.
@return a matching component reference or null if nothing was found. | [
"Gets",
"an",
"optional",
"component",
"reference",
"that",
"matches",
"specified",
"locator",
"and",
"matching",
"to",
"the",
"specified",
"type",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/References.java#L184-L191 |
apache/incubator-gobblin | gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/fork/InstrumentedForkOperatorBase.java | InstrumentedForkOperatorBase.afterFork | protected void afterFork(List<Boolean> forks, long startTimeNanos) {
int forksGenerated = 0;
for (Boolean fork : forks) {
forksGenerated += fork ? 1 : 0;
}
Instrumented.markMeter(this.outputForks, forksGenerated);
Instrumented.updateTimer(this.forkOperatorTimer, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS);
} | java | protected void afterFork(List<Boolean> forks, long startTimeNanos) {
int forksGenerated = 0;
for (Boolean fork : forks) {
forksGenerated += fork ? 1 : 0;
}
Instrumented.markMeter(this.outputForks, forksGenerated);
Instrumented.updateTimer(this.forkOperatorTimer, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS);
} | [
"protected",
"void",
"afterFork",
"(",
"List",
"<",
"Boolean",
">",
"forks",
",",
"long",
"startTimeNanos",
")",
"{",
"int",
"forksGenerated",
"=",
"0",
";",
"for",
"(",
"Boolean",
"fork",
":",
"forks",
")",
"{",
"forksGenerated",
"+=",
"fork",
"?",
"1",... | Called after forkDataRecord.
@param forks result from forkDataRecord.
@param startTimeNanos start time of forkDataRecord. | [
"Called",
"after",
"forkDataRecord",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/fork/InstrumentedForkOperatorBase.java#L152-L159 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/chrono/Chronology.java | Chronology.ensureChronoLocalDate | <D extends ChronoLocalDate> D ensureChronoLocalDate(Temporal temporal) {
@SuppressWarnings("unchecked")
D other = (D) temporal;
if (this.equals(other.getChronology()) == false) {
throw new ClassCastException("Chrono mismatch, expected: " + getId() + ", actual: " + other.getChronology().getId());
}
return other;
} | java | <D extends ChronoLocalDate> D ensureChronoLocalDate(Temporal temporal) {
@SuppressWarnings("unchecked")
D other = (D) temporal;
if (this.equals(other.getChronology()) == false) {
throw new ClassCastException("Chrono mismatch, expected: " + getId() + ", actual: " + other.getChronology().getId());
}
return other;
} | [
"<",
"D",
"extends",
"ChronoLocalDate",
">",
"D",
"ensureChronoLocalDate",
"(",
"Temporal",
"temporal",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"D",
"other",
"=",
"(",
"D",
")",
"temporal",
";",
"if",
"(",
"this",
".",
"equals",
"(",
... | Casts the {@code Temporal} to {@code ChronoLocalDate} with the same chronology.
@param temporal a date-time to cast, not null
@return the date-time checked and cast to {@code ChronoLocalDate}, not null
@throws ClassCastException if the date-time cannot be cast to ChronoLocalDate
or the chronology is not equal this Chrono | [
"Casts",
"the",
"{",
"@code",
"Temporal",
"}",
"to",
"{",
"@code",
"ChronoLocalDate",
"}",
"with",
"the",
"same",
"chronology",
"."
] | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/chrono/Chronology.java#L357-L364 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | StrBuilder.validateRange | protected int validateRange(final int startIndex, int endIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex > size) {
endIndex = size;
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException("end < start");
}
return endIndex;
} | java | protected int validateRange(final int startIndex, int endIndex) {
if (startIndex < 0) {
throw new StringIndexOutOfBoundsException(startIndex);
}
if (endIndex > size) {
endIndex = size;
}
if (startIndex > endIndex) {
throw new StringIndexOutOfBoundsException("end < start");
}
return endIndex;
} | [
"protected",
"int",
"validateRange",
"(",
"final",
"int",
"startIndex",
",",
"int",
"endIndex",
")",
"{",
"if",
"(",
"startIndex",
"<",
"0",
")",
"{",
"throw",
"new",
"StringIndexOutOfBoundsException",
"(",
"startIndex",
")",
";",
"}",
"if",
"(",
"endIndex",... | Validates parameters defining a range of the builder.
@param startIndex the start index, inclusive, must be valid
@param endIndex the end index, exclusive, must be valid except
that if too large it is treated as end of string
@return the new string
@throws IndexOutOfBoundsException if the index is invalid | [
"Validates",
"parameters",
"defining",
"a",
"range",
"of",
"the",
"builder",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L2897-L2908 |
dbracewell/hermes | hermes-core/src/main/java/com/davidbracewell/hermes/HString.java | HString.findAll | public Stream<HString> findAll(@NonNull String text) {
return Streams.asStream(new Iterator<HString>() {
Integer pos = null;
int start = 0;
private boolean advance() {
if (pos == null) {
pos = indexOf(text, start);
}
return pos != -1;
}
@Override
public boolean hasNext() {
return advance();
}
@Override
public HString next() {
if (!advance()) {
throw new NoSuchElementException();
}
int n = pos;
pos = null;
start = n + 1;
//If we have tokens expand the match to the overlaping tokens.
if (document() != null && document().isCompleted(Types.TOKEN)) {
return union(substring(n, n + text.length()).tokens());
}
return substring(n, n + text.length());
}
});
} | java | public Stream<HString> findAll(@NonNull String text) {
return Streams.asStream(new Iterator<HString>() {
Integer pos = null;
int start = 0;
private boolean advance() {
if (pos == null) {
pos = indexOf(text, start);
}
return pos != -1;
}
@Override
public boolean hasNext() {
return advance();
}
@Override
public HString next() {
if (!advance()) {
throw new NoSuchElementException();
}
int n = pos;
pos = null;
start = n + 1;
//If we have tokens expand the match to the overlaping tokens.
if (document() != null && document().isCompleted(Types.TOKEN)) {
return union(substring(n, n + text.length()).tokens());
}
return substring(n, n + text.length());
}
});
} | [
"public",
"Stream",
"<",
"HString",
">",
"findAll",
"(",
"@",
"NonNull",
"String",
"text",
")",
"{",
"return",
"Streams",
".",
"asStream",
"(",
"new",
"Iterator",
"<",
"HString",
">",
"(",
")",
"{",
"Integer",
"pos",
"=",
"null",
";",
"int",
"start",
... | Finds all occurrences of the given text in this HString starting
@param text the text to search for
@return A list of HString that are matches to the given string | [
"Finds",
"all",
"occurrences",
"of",
"the",
"given",
"text",
"in",
"this",
"HString",
"starting"
] | train | https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/HString.java#L422-L454 |
tvesalainen/util | rpm/src/main/java/org/vesalainen/pm/rpm/RPMBuilder.java | RPMBuilder.addRequire | @Override
public RPMBuilder addRequire(String name, String version, Condition... dependency)
{
addString(RPMTAG_REQUIRENAME, name);
addString(RPMTAG_REQUIREVERSION, version);
addInt32(RPMTAG_REQUIREFLAGS, Dependency.or(dependency));
ensureVersionReq(version);
return this;
} | java | @Override
public RPMBuilder addRequire(String name, String version, Condition... dependency)
{
addString(RPMTAG_REQUIRENAME, name);
addString(RPMTAG_REQUIREVERSION, version);
addInt32(RPMTAG_REQUIREFLAGS, Dependency.or(dependency));
ensureVersionReq(version);
return this;
} | [
"@",
"Override",
"public",
"RPMBuilder",
"addRequire",
"(",
"String",
"name",
",",
"String",
"version",
",",
"Condition",
"...",
"dependency",
")",
"{",
"addString",
"(",
"RPMTAG_REQUIRENAME",
",",
"name",
")",
";",
"addString",
"(",
"RPMTAG_REQUIREVERSION",
","... | Add RPMTAG_REQUIRENAME, RPMTAG_REQUIREVERSION and RPMTAG_REQUIREFLAGS
@param name
@param version
@param dependency
@return | [
"Add",
"RPMTAG_REQUIRENAME",
"RPMTAG_REQUIREVERSION",
"and",
"RPMTAG_REQUIREFLAGS"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/rpm/src/main/java/org/vesalainen/pm/rpm/RPMBuilder.java#L270-L278 |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/container/services/PortletCookieServiceImpl.java | PortletCookieServiceImpl.getCookieFromRequest | protected Cookie getCookieFromRequest(String name, HttpServletRequest request) {
final Cookie[] cookies = request.getCookies();
if (cookies == null) { // getCookies() returns null if there aren't any
return null;
}
for (final Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
} | java | protected Cookie getCookieFromRequest(String name, HttpServletRequest request) {
final Cookie[] cookies = request.getCookies();
if (cookies == null) { // getCookies() returns null if there aren't any
return null;
}
for (final Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
} | [
"protected",
"Cookie",
"getCookieFromRequest",
"(",
"String",
"name",
",",
"HttpServletRequest",
"request",
")",
"{",
"final",
"Cookie",
"[",
"]",
"cookies",
"=",
"request",
".",
"getCookies",
"(",
")",
";",
"if",
"(",
"cookies",
"==",
"null",
")",
"{",
"/... | Attempts to retrieve the {@link Cookie} with the specified name from the {@link
HttpServletRequest}.
<p>Returns the {@link Cookie} if a match is found in the request, otherwise gracefully
returns null.
@param name
@param request
@return | [
"Attempts",
"to",
"retrieve",
"the",
"{",
"@link",
"Cookie",
"}",
"with",
"the",
"specified",
"name",
"from",
"the",
"{",
"@link",
"HttpServletRequest",
"}",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/container/services/PortletCookieServiceImpl.java#L463-L476 |
jasminb/jsonapi-converter | src/main/java/com/github/jasminb/jsonapi/ErrorUtils.java | ErrorUtils.parseError | public static <T extends Errors> T parseError(ObjectMapper mapper, JsonNode errorResponse, Class<T> cls) throws JsonProcessingException {
return mapper.treeToValue(errorResponse, cls);
} | java | public static <T extends Errors> T parseError(ObjectMapper mapper, JsonNode errorResponse, Class<T> cls) throws JsonProcessingException {
return mapper.treeToValue(errorResponse, cls);
} | [
"public",
"static",
"<",
"T",
"extends",
"Errors",
">",
"T",
"parseError",
"(",
"ObjectMapper",
"mapper",
",",
"JsonNode",
"errorResponse",
",",
"Class",
"<",
"T",
">",
"cls",
")",
"throws",
"JsonProcessingException",
"{",
"return",
"mapper",
".",
"treeToValue... | Parses provided JsonNode and returns it as T.
@param mapper Jackson Object mapper instance
@param errorResponse error response body
@return T collection
@throws JsonProcessingException thrown in case JsonNode cannot be parsed | [
"Parses",
"provided",
"JsonNode",
"and",
"returns",
"it",
"as",
"T",
"."
] | train | https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ErrorUtils.java#L44-L46 |
milaboratory/milib | src/main/java/com/milaboratory/core/Range.java | Range.getAbsoluteRangeFor | public Range getAbsoluteRangeFor(Range relativeRange) {
int from = convertBoundaryToAbsolutePosition(relativeRange.getFrom()),
to = convertBoundaryToAbsolutePosition(relativeRange.getTo());
return new Range(from, to);
} | java | public Range getAbsoluteRangeFor(Range relativeRange) {
int from = convertBoundaryToAbsolutePosition(relativeRange.getFrom()),
to = convertBoundaryToAbsolutePosition(relativeRange.getTo());
return new Range(from, to);
} | [
"public",
"Range",
"getAbsoluteRangeFor",
"(",
"Range",
"relativeRange",
")",
"{",
"int",
"from",
"=",
"convertBoundaryToAbsolutePosition",
"(",
"relativeRange",
".",
"getFrom",
"(",
")",
")",
",",
"to",
"=",
"convertBoundaryToAbsolutePosition",
"(",
"relativeRange",
... | Reverse operation for {@link #getRelativeRangeOf(Range)}.
A.getAbsoluteRangeFor(A.getRelativeRangeOf(B)) == B
@param relativeRange range defined relative to this range
@return absolute range | [
"Reverse",
"operation",
"for",
"{",
"@link",
"#getRelativeRangeOf",
"(",
"Range",
")",
"}",
"."
] | train | https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L397-L401 |
zaproxy/zaproxy | src/org/parosproxy/paros/view/AbstractParamDialog.java | AbstractParamDialog.addParamPanel | public void addParamPanel(String[] parentParams, String name, AbstractParamPanel panel, boolean sort) {
this.getJSplitPane().addParamPanel(parentParams, name, panel, sort);
} | java | public void addParamPanel(String[] parentParams, String name, AbstractParamPanel panel, boolean sort) {
this.getJSplitPane().addParamPanel(parentParams, name, panel, sort);
} | [
"public",
"void",
"addParamPanel",
"(",
"String",
"[",
"]",
"parentParams",
",",
"String",
"name",
",",
"AbstractParamPanel",
"panel",
",",
"boolean",
"sort",
")",
"{",
"this",
".",
"getJSplitPane",
"(",
")",
".",
"addParamPanel",
"(",
"parentParams",
",",
"... | Adds the given panel with the given name positioned under the given parents (or root node if none given).
<p>
If not sorted the panel is appended to existing panels.
@param parentParams the name of the parent nodes of the panel, might be {@code null}.
@param name the name of the panel, must not be {@code null}.
@param panel the panel, must not be {@code null}.
@param sort {@code true} if the panel should be added in alphabetic order, {@code false} otherwise | [
"Adds",
"the",
"given",
"panel",
"with",
"the",
"given",
"name",
"positioned",
"under",
"the",
"given",
"parents",
"(",
"or",
"root",
"node",
"if",
"none",
"given",
")",
".",
"<p",
">",
"If",
"not",
"sorted",
"the",
"panel",
"is",
"appended",
"to",
"ex... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/AbstractParamDialog.java#L268-L270 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java | HttpChannelConfig.parseStrictURLFormat | private void parseStrictURLFormat(Map<Object, Object> props) {
Object value = props.get(HttpConfigConstants.PROPNAME_STRICT_URL_FORMAT);
if (null != value) {
this.bStrictURLFormat = convertBoolean(value);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Strict URL formatting is " + isStrictURLFormat());
}
}
} | java | private void parseStrictURLFormat(Map<Object, Object> props) {
Object value = props.get(HttpConfigConstants.PROPNAME_STRICT_URL_FORMAT);
if (null != value) {
this.bStrictURLFormat = convertBoolean(value);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Strict URL formatting is " + isStrictURLFormat());
}
}
} | [
"private",
"void",
"parseStrictURLFormat",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"props",
")",
"{",
"Object",
"value",
"=",
"props",
".",
"get",
"(",
"HttpConfigConstants",
".",
"PROPNAME_STRICT_URL_FORMAT",
")",
";",
"if",
"(",
"null",
"!=",
"value... | Check the input configuration to decide whether to enforce a strict RFC
compliance while parsing URLs.
@param props | [
"Check",
"the",
"input",
"configuration",
"to",
"decide",
"whether",
"to",
"enforce",
"a",
"strict",
"RFC",
"compliance",
"while",
"parsing",
"URLs",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L1045-L1053 |
datacleaner/AnalyzerBeans | components/html-rendering/src/main/java/org/eobjects/analyzer/result/renderer/TableBodyElement.java | TableBodyElement.getHeaderValue | protected String getHeaderValue(HtmlRenderingContext context, int col, String columnName) {
return context.escapeHtml(columnName);
} | java | protected String getHeaderValue(HtmlRenderingContext context, int col, String columnName) {
return context.escapeHtml(columnName);
} | [
"protected",
"String",
"getHeaderValue",
"(",
"HtmlRenderingContext",
"context",
",",
"int",
"col",
",",
"String",
"columnName",
")",
"{",
"return",
"context",
".",
"escapeHtml",
"(",
"columnName",
")",
";",
"}"
] | Overrideable method for defining the literal HTML table header of a
particular column.
@param context
@param col
@param columnName
@return | [
"Overrideable",
"method",
"for",
"defining",
"the",
"literal",
"HTML",
"table",
"header",
"of",
"a",
"particular",
"column",
"."
] | train | https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/components/html-rendering/src/main/java/org/eobjects/analyzer/result/renderer/TableBodyElement.java#L122-L124 |
jenetics/jenetics | jenetics.ext/src/main/java/io/jenetics/ext/util/TreeNode.java | TreeNode.replaceAtPath | public boolean replaceAtPath(final Path path, final TreeNode<T> child) {
requireNonNull(path);
requireNonNull(child);
final Optional<TreeNode<T>> old = childAtPath(path);
final Optional<TreeNode<T>> parent = old.flatMap(TreeNode::getParent);
if (parent.isPresent()) {
parent.orElseThrow(AssertionError::new)
.replace(path.get(path.length() - 1), child);
} else {
removeAllChildren();
setValue(child.getValue());
final ISeq<TreeNode<T>> nodes = child.childStream()
.collect(ISeq.toISeq());
for (TreeNode<T> node : nodes) {
attach(node);
}
}
return old.isPresent();
} | java | public boolean replaceAtPath(final Path path, final TreeNode<T> child) {
requireNonNull(path);
requireNonNull(child);
final Optional<TreeNode<T>> old = childAtPath(path);
final Optional<TreeNode<T>> parent = old.flatMap(TreeNode::getParent);
if (parent.isPresent()) {
parent.orElseThrow(AssertionError::new)
.replace(path.get(path.length() - 1), child);
} else {
removeAllChildren();
setValue(child.getValue());
final ISeq<TreeNode<T>> nodes = child.childStream()
.collect(ISeq.toISeq());
for (TreeNode<T> node : nodes) {
attach(node);
}
}
return old.isPresent();
} | [
"public",
"boolean",
"replaceAtPath",
"(",
"final",
"Path",
"path",
",",
"final",
"TreeNode",
"<",
"T",
">",
"child",
")",
"{",
"requireNonNull",
"(",
"path",
")",
";",
"requireNonNull",
"(",
"child",
")",
";",
"final",
"Optional",
"<",
"TreeNode",
"<",
... | Replaces the child at the given {@code path} with the given new
{@code child}. If no child exists at the given path, nothing is replaced.
@since 4.4
@param path the path of the child to replace
@param child the new child
@return {@code true} if a child at the given {@code path} existed and
has been replaced
@throws NullPointerException if one of the given argument is {@code null} | [
"Replaces",
"the",
"child",
"at",
"the",
"given",
"{",
"@code",
"path",
"}",
"with",
"the",
"given",
"new",
"{",
"@code",
"child",
"}",
".",
"If",
"no",
"child",
"exists",
"at",
"the",
"given",
"path",
"nothing",
"is",
"replaced",
"."
] | train | https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics.ext/src/main/java/io/jenetics/ext/util/TreeNode.java#L284-L307 |
mmazi/rescu | src/main/java/si/mazi/rescu/HttpTemplate.java | HttpTemplate.configureURLConnection | private HttpURLConnection configureURLConnection(HttpMethod method, String urlString, Map<String, String> httpHeaders, int contentLength) throws IOException {
preconditionNotNull(method, "method cannot be null");
preconditionNotNull(urlString, "urlString cannot be null");
preconditionNotNull(httpHeaders, "httpHeaders cannot be null");
HttpURLConnection connection = getHttpURLConnection(urlString);
connection.setRequestMethod(method.name());
Map<String, String> headerKeyValues = new HashMap<>(defaultHttpHeaders);
headerKeyValues.putAll(httpHeaders);
for (Map.Entry<String, String> entry : headerKeyValues.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
log.trace("Header request property: key='{}', value='{}'", entry.getKey(), entry.getValue());
}
// Perform additional configuration for POST
if (contentLength > 0) {
connection.setDoOutput(true);
connection.setDoInput(true);
}
connection.setRequestProperty("Content-Length", Integer.toString(contentLength));
return connection;
} | java | private HttpURLConnection configureURLConnection(HttpMethod method, String urlString, Map<String, String> httpHeaders, int contentLength) throws IOException {
preconditionNotNull(method, "method cannot be null");
preconditionNotNull(urlString, "urlString cannot be null");
preconditionNotNull(httpHeaders, "httpHeaders cannot be null");
HttpURLConnection connection = getHttpURLConnection(urlString);
connection.setRequestMethod(method.name());
Map<String, String> headerKeyValues = new HashMap<>(defaultHttpHeaders);
headerKeyValues.putAll(httpHeaders);
for (Map.Entry<String, String> entry : headerKeyValues.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
log.trace("Header request property: key='{}', value='{}'", entry.getKey(), entry.getValue());
}
// Perform additional configuration for POST
if (contentLength > 0) {
connection.setDoOutput(true);
connection.setDoInput(true);
}
connection.setRequestProperty("Content-Length", Integer.toString(contentLength));
return connection;
} | [
"private",
"HttpURLConnection",
"configureURLConnection",
"(",
"HttpMethod",
"method",
",",
"String",
"urlString",
",",
"Map",
"<",
"String",
",",
"String",
">",
"httpHeaders",
",",
"int",
"contentLength",
")",
"throws",
"IOException",
"{",
"preconditionNotNull",
"(... | Provides an internal convenience method to allow easy overriding by test classes
@param method The HTTP method (e.g. GET, POST etc)
@param urlString A string representation of a URL
@param httpHeaders The HTTP headers (will override the defaults)
@param contentLength The Content-Length request property
@return An HttpURLConnection based on the given parameters
@throws IOException If something goes wrong | [
"Provides",
"an",
"internal",
"convenience",
"method",
"to",
"allow",
"easy",
"overriding",
"by",
"test",
"classes"
] | train | https://github.com/mmazi/rescu/blob/8a4f9367994da0a2617bd37acf0320c942e62de3/src/main/java/si/mazi/rescu/HttpTemplate.java#L153-L179 |
apache/incubator-atlas | client/src/main/java/org/apache/atlas/AtlasClient.java | AtlasClient.listTraits | public List<String> listTraits(final String guid) throws AtlasServiceException {
JSONObject jsonResponse = callAPIWithBodyAndParams(API.LIST_TRAITS, null, guid, URI_TRAITS);
return extractResults(jsonResponse, AtlasClient.RESULTS, new ExtractOperation<String, String>());
} | java | public List<String> listTraits(final String guid) throws AtlasServiceException {
JSONObject jsonResponse = callAPIWithBodyAndParams(API.LIST_TRAITS, null, guid, URI_TRAITS);
return extractResults(jsonResponse, AtlasClient.RESULTS, new ExtractOperation<String, String>());
} | [
"public",
"List",
"<",
"String",
">",
"listTraits",
"(",
"final",
"String",
"guid",
")",
"throws",
"AtlasServiceException",
"{",
"JSONObject",
"jsonResponse",
"=",
"callAPIWithBodyAndParams",
"(",
"API",
".",
"LIST_TRAITS",
",",
"null",
",",
"guid",
",",
"URI_TR... | List traits for a given entity identified by its GUID
@param guid GUID of the entity
@return List<String> - traitnames associated with entity
@throws AtlasServiceException | [
"List",
"traits",
"for",
"a",
"given",
"entity",
"identified",
"by",
"its",
"GUID"
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/client/src/main/java/org/apache/atlas/AtlasClient.java#L707-L710 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.copy | public static long copy(FileInputStream in, FileOutputStream out) throws IORuntimeException {
Assert.notNull(in, "FileInputStream is null!");
Assert.notNull(out, "FileOutputStream is null!");
final FileChannel inChannel = in.getChannel();
final FileChannel outChannel = out.getChannel();
try {
return inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | java | public static long copy(FileInputStream in, FileOutputStream out) throws IORuntimeException {
Assert.notNull(in, "FileInputStream is null!");
Assert.notNull(out, "FileOutputStream is null!");
final FileChannel inChannel = in.getChannel();
final FileChannel outChannel = out.getChannel();
try {
return inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | [
"public",
"static",
"long",
"copy",
"(",
"FileInputStream",
"in",
",",
"FileOutputStream",
"out",
")",
"throws",
"IORuntimeException",
"{",
"Assert",
".",
"notNull",
"(",
"in",
",",
"\"FileInputStream is null!\"",
")",
";",
"Assert",
".",
"notNull",
"(",
"out",
... | 拷贝文件流,使用NIO
@param in 输入
@param out 输出
@return 拷贝的字节数
@throws IORuntimeException IO异常 | [
"拷贝文件流,使用NIO"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L213-L225 |
RestComm/sip-servlets | sip-servlets-examples/diameter-event-charging/src/main/java/org/mobicents/servlet/sip/example/DiameterEventChargingSipServlet.java | DiameterEventChargingSipServlet.doDiameterCharging | private long doDiameterCharging(String sessionId, String userId, Long cost, boolean refund)
{
try
{
logger.info( "Creating Diameter Charging " + (refund ? "Refund" : "Debit") + " Request UserId[" + userId + "], Cost[" + cost + "]..." );
Request req = (Request) diameterBaseClient.createAccountingRequest( sessionId, userId, cost, refund );
logger.info( "Sending Diameter Charging " + (refund ? "Refund" : "Debit") + " Request..." );
Message msg = diameterBaseClient.sendMessageSync( req );
long resultCode = -1;
if(msg instanceof Answer)
resultCode = ((Answer)msg).getResultCode().getUnsigned32();
return resultCode;
}
catch ( Exception e )
{
logger.error( "Failure communicating with Diameter Charging Server.", e );
return 5012;
}
} | java | private long doDiameterCharging(String sessionId, String userId, Long cost, boolean refund)
{
try
{
logger.info( "Creating Diameter Charging " + (refund ? "Refund" : "Debit") + " Request UserId[" + userId + "], Cost[" + cost + "]..." );
Request req = (Request) diameterBaseClient.createAccountingRequest( sessionId, userId, cost, refund );
logger.info( "Sending Diameter Charging " + (refund ? "Refund" : "Debit") + " Request..." );
Message msg = diameterBaseClient.sendMessageSync( req );
long resultCode = -1;
if(msg instanceof Answer)
resultCode = ((Answer)msg).getResultCode().getUnsigned32();
return resultCode;
}
catch ( Exception e )
{
logger.error( "Failure communicating with Diameter Charging Server.", e );
return 5012;
}
} | [
"private",
"long",
"doDiameterCharging",
"(",
"String",
"sessionId",
",",
"String",
"userId",
",",
"Long",
"cost",
",",
"boolean",
"refund",
")",
"{",
"try",
"{",
"logger",
".",
"info",
"(",
"\"Creating Diameter Charging \"",
"+",
"(",
"refund",
"?",
"\"Refund... | Method for doing the Charging, either it's a debit or a refund.
@param sessionId the Session-Id for the Diameter Message
@param userId the User-Id of the client in the Diameter Server
@param cost the Cost (or Refund value) of the service
@param refund boolean indicating if it's a refund or not
@return a long with the Result-Code AVP from the Answer | [
"Method",
"for",
"doing",
"the",
"Charging",
"either",
"it",
"s",
"a",
"debit",
"or",
"a",
"refund",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/diameter-event-charging/src/main/java/org/mobicents/servlet/sip/example/DiameterEventChargingSipServlet.java#L245-L267 |
datasift/datasift-java | src/main/java/com/datasift/client/accounts/DataSiftAccount.java | DataSiftAccount.deleteLimit | public FutureData<DataSiftResult> deleteLimit(String identity, String service) {
if (identity == null) {
throw new IllegalArgumentException("An identity is required");
}
if (service == null) {
throw new IllegalArgumentException("A service is required");
}
FutureData<DataSiftResult> future = new FutureData<>();
URI uri = newParams().forURL(config.newAPIEndpointURI(IDENTITY + "/" + identity + "/limit/" + service));
Request request = config.http()
.DELETE(uri, new PageReader(newRequestCallback(future, new BaseDataSiftResult(), config)));
performRequest(future, request);
return future;
} | java | public FutureData<DataSiftResult> deleteLimit(String identity, String service) {
if (identity == null) {
throw new IllegalArgumentException("An identity is required");
}
if (service == null) {
throw new IllegalArgumentException("A service is required");
}
FutureData<DataSiftResult> future = new FutureData<>();
URI uri = newParams().forURL(config.newAPIEndpointURI(IDENTITY + "/" + identity + "/limit/" + service));
Request request = config.http()
.DELETE(uri, new PageReader(newRequestCallback(future, new BaseDataSiftResult(), config)));
performRequest(future, request);
return future;
} | [
"public",
"FutureData",
"<",
"DataSiftResult",
">",
"deleteLimit",
"(",
"String",
"identity",
",",
"String",
"service",
")",
"{",
"if",
"(",
"identity",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"An identity is required\"",
")",
... | /*
Delete a limit
@param identity identity to delete the limit from
@param service service to delete the limit from
@return Success of deletion | [
"/",
"*",
"Delete",
"a",
"limit"
] | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/accounts/DataSiftAccount.java#L390-L403 |
lightblueseas/file-worker | src/main/java/de/alpharogroup/file/search/FileSearchExtensions.java | FileSearchExtensions.findFilesWithFilter | public static List<File> findFilesWithFilter(final File dir, final String... extension)
{
final List<File> foundedFileList = new ArrayList<>();
final File[] children = dir.listFiles(new MultiplyExtensionsFileFilter(true, extension));
for (final File element : children)
{
// if the entry is a directory
if (element.isDirectory())
{ // then
// find recursively in the directory and put it in a List.
// Put the founded files in the main List.
foundedFileList.addAll(findFilesWithFilter(element, extension));
}
else
{
foundedFileList.add(element.getAbsoluteFile());
}
}
return foundedFileList;
} | java | public static List<File> findFilesWithFilter(final File dir, final String... extension)
{
final List<File> foundedFileList = new ArrayList<>();
final File[] children = dir.listFiles(new MultiplyExtensionsFileFilter(true, extension));
for (final File element : children)
{
// if the entry is a directory
if (element.isDirectory())
{ // then
// find recursively in the directory and put it in a List.
// Put the founded files in the main List.
foundedFileList.addAll(findFilesWithFilter(element, extension));
}
else
{
foundedFileList.add(element.getAbsoluteFile());
}
}
return foundedFileList;
} | [
"public",
"static",
"List",
"<",
"File",
">",
"findFilesWithFilter",
"(",
"final",
"File",
"dir",
",",
"final",
"String",
"...",
"extension",
")",
"{",
"final",
"List",
"<",
"File",
">",
"foundedFileList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"f... | Finds all files that match the given extension. The search is recursively.
@param dir
The directory to search.
@param extension
The extensions to search.
@return A List with all files that matches the search pattern. | [
"Finds",
"all",
"files",
"that",
"match",
"the",
"given",
"extension",
".",
"The",
"search",
"is",
"recursively",
"."
] | train | https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/search/FileSearchExtensions.java#L330-L349 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/renderer/animation/transformation/ChainedTransformation.java | ChainedTransformation.addTransformations | public ChainedTransformation addTransformations(Transformation<?, ?>... transformations)
{
duration = 0;
for (Transformation<?, ?> transformation : transformations)
{
duration += transformation.totalDuration();
listTransformations.add(transformation);
}
return this;
} | java | public ChainedTransformation addTransformations(Transformation<?, ?>... transformations)
{
duration = 0;
for (Transformation<?, ?> transformation : transformations)
{
duration += transformation.totalDuration();
listTransformations.add(transformation);
}
return this;
} | [
"public",
"ChainedTransformation",
"addTransformations",
"(",
"Transformation",
"<",
"?",
",",
"?",
">",
"...",
"transformations",
")",
"{",
"duration",
"=",
"0",
";",
"for",
"(",
"Transformation",
"<",
"?",
",",
"?",
">",
"transformation",
":",
"transformatio... | Adds the {@link Transformation} this to {@link ParallelTransformation}
@param transformations the transformations
@return the chained transformation | [
"Adds",
"the",
"{",
"@link",
"Transformation",
"}",
"this",
"to",
"{",
"@link",
"ParallelTransformation",
"}"
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/animation/transformation/ChainedTransformation.java#L65-L75 |
probedock/probedock-java | src/main/java/io/probedock/client/utils/EnvironmentUtils.java | EnvironmentUtils.getEnvironmentString | public static String getEnvironmentString(String name, String defaultValue) {
if (envVars == null) {
throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentString.");
}
return envVars.get(ENV_PREFIX + name) != null ? envVars.get(ENV_PREFIX + name) : defaultValue;
} | java | public static String getEnvironmentString(String name, String defaultValue) {
if (envVars == null) {
throw new IllegalStateException("The environment vars must be provided before calling getEnvironmentString.");
}
return envVars.get(ENV_PREFIX + name) != null ? envVars.get(ENV_PREFIX + name) : defaultValue;
} | [
"public",
"static",
"String",
"getEnvironmentString",
"(",
"String",
"name",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"envVars",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"The environment vars must be provided before calling getE... | Retrieve string value for the environment variable name
@param name The name of the variable without prefix
@param defaultValue The default value if not found
@return The value found, or the default if not found | [
"Retrieve",
"string",
"value",
"for",
"the",
"environment",
"variable",
"name"
] | train | https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/utils/EnvironmentUtils.java#L76-L82 |
ironjacamar/ironjacamar | common/src/main/java/org/ironjacamar/common/metadata/ds/DsParser.java | DsParser.parseDataSources | protected DataSources parseDataSources(XMLStreamReader reader) throws XMLStreamException, ParserException,
ValidateException
{
List<DataSource> datasource = new ArrayList<DataSource>();
List<XaDataSource> xaDataSource = new ArrayList<XaDataSource>();
Map<String, Driver> drivers = new HashMap<String, Driver>();
boolean driversMatched = false;
while (reader.hasNext())
{
switch (reader.nextTag())
{
case END_ELEMENT : {
if (XML.ELEMENT_DATASOURCES.equals(reader.getLocalName()))
{
return new DatasourcesImpl(datasource, xaDataSource, drivers);
}
else
{
switch (reader.getLocalName())
{
case XML.ELEMENT_DATASOURCE :
case XML.ELEMENT_XA_DATASOURCE :
case XML.ELEMENT_DRIVERS :
case XML.ELEMENT_DRIVER :
break;
default :
throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
}
}
break;
}
case START_ELEMENT : {
switch (reader.getLocalName())
{
case XML.ELEMENT_DATASOURCE : {
datasource.add(parseDataSource(reader));
break;
}
case XML.ELEMENT_XA_DATASOURCE : {
xaDataSource.add(parseXADataSource(reader));
break;
}
case XML.ELEMENT_DRIVERS : {
driversMatched = true;
break;
}
case XML.ELEMENT_DRIVER : {
Driver driver = parseDriver(reader);
drivers.put(driver.getName(), driver);
break;
}
default :
throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
}
break;
}
}
}
throw new ParserException(bundle.unexpectedEndOfDocument());
} | java | protected DataSources parseDataSources(XMLStreamReader reader) throws XMLStreamException, ParserException,
ValidateException
{
List<DataSource> datasource = new ArrayList<DataSource>();
List<XaDataSource> xaDataSource = new ArrayList<XaDataSource>();
Map<String, Driver> drivers = new HashMap<String, Driver>();
boolean driversMatched = false;
while (reader.hasNext())
{
switch (reader.nextTag())
{
case END_ELEMENT : {
if (XML.ELEMENT_DATASOURCES.equals(reader.getLocalName()))
{
return new DatasourcesImpl(datasource, xaDataSource, drivers);
}
else
{
switch (reader.getLocalName())
{
case XML.ELEMENT_DATASOURCE :
case XML.ELEMENT_XA_DATASOURCE :
case XML.ELEMENT_DRIVERS :
case XML.ELEMENT_DRIVER :
break;
default :
throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
}
}
break;
}
case START_ELEMENT : {
switch (reader.getLocalName())
{
case XML.ELEMENT_DATASOURCE : {
datasource.add(parseDataSource(reader));
break;
}
case XML.ELEMENT_XA_DATASOURCE : {
xaDataSource.add(parseXADataSource(reader));
break;
}
case XML.ELEMENT_DRIVERS : {
driversMatched = true;
break;
}
case XML.ELEMENT_DRIVER : {
Driver driver = parseDriver(reader);
drivers.put(driver.getName(), driver);
break;
}
default :
throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
}
break;
}
}
}
throw new ParserException(bundle.unexpectedEndOfDocument());
} | [
"protected",
"DataSources",
"parseDataSources",
"(",
"XMLStreamReader",
"reader",
")",
"throws",
"XMLStreamException",
",",
"ParserException",
",",
"ValidateException",
"{",
"List",
"<",
"DataSource",
">",
"datasource",
"=",
"new",
"ArrayList",
"<",
"DataSource",
">",... | Parse datasource
@param reader The reader
@return The result
@exception XMLStreamException XMLStreamException
@exception ParserException ParserException
@exception ValidateException ValidateException | [
"Parse",
"datasource"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/ds/DsParser.java#L165-L225 |
quattor/pan | panc/src/main/java/org/quattor/pan/utils/Range.java | Range.checkRangeValues | private void checkRangeValues(long minimum, long maximum) {
if (minimum > maximum) {
throw EvaluationException.create(
MSG_MIN_MUST_BE_LESS_OR_EQUAL_TO_MAX, minimum, maximum);
}
} | java | private void checkRangeValues(long minimum, long maximum) {
if (minimum > maximum) {
throw EvaluationException.create(
MSG_MIN_MUST_BE_LESS_OR_EQUAL_TO_MAX, minimum, maximum);
}
} | [
"private",
"void",
"checkRangeValues",
"(",
"long",
"minimum",
",",
"long",
"maximum",
")",
"{",
"if",
"(",
"minimum",
">",
"maximum",
")",
"{",
"throw",
"EvaluationException",
".",
"create",
"(",
"MSG_MIN_MUST_BE_LESS_OR_EQUAL_TO_MAX",
",",
"minimum",
",",
"max... | Checks whether the range values are valid. Specifically whether the
minimum is less than or equal to the maximum. This will throw an
EvaluationException if any problems are found.
@param minimum
@param maximum | [
"Checks",
"whether",
"the",
"range",
"values",
"are",
"valid",
".",
"Specifically",
"whether",
"the",
"minimum",
"is",
"less",
"than",
"or",
"equal",
"to",
"the",
"maximum",
".",
"This",
"will",
"throw",
"an",
"EvaluationException",
"if",
"any",
"problems",
... | train | https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/utils/Range.java#L133-L138 |
google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java | Es6RewriteBlockScopedDeclaration.visitBlockScopedName | private void visitBlockScopedName(NodeTraversal t, Node decl, Node nameNode) {
Scope scope = t.getScope();
Node parent = decl.getParent();
// Normalize "let x;" to "let x = undefined;" if in a loop, since we later convert x
// to be $jscomp$loop$0.x and want to reset the property to undefined every loop iteration.
if ((decl.isLet() || decl.isConst())
&& !nameNode.hasChildren()
&& (parent == null || !parent.isForIn())
&& inLoop(decl)) {
Node undefined = createUndefinedNode().srcref(nameNode);
nameNode.addChildToFront(undefined);
compiler.reportChangeToEnclosingScope(undefined);
}
String oldName = nameNode.getString();
Scope hoistScope = scope.getClosestHoistScope();
if (scope != hoistScope) {
String newName = oldName;
if (hoistScope.hasSlot(oldName) || undeclaredNames.contains(oldName)) {
do {
newName = oldName + "$" + compiler.getUniqueNameIdSupplier().get();
} while (hoistScope.hasSlot(newName));
nameNode.setString(newName);
compiler.reportChangeToEnclosingScope(nameNode);
Node scopeRoot = scope.getRootNode();
renameTable.put(scopeRoot, oldName, newName);
}
Var oldVar = scope.getVar(oldName);
scope.undeclare(oldVar);
hoistScope.declare(newName, nameNode, oldVar.input);
}
} | java | private void visitBlockScopedName(NodeTraversal t, Node decl, Node nameNode) {
Scope scope = t.getScope();
Node parent = decl.getParent();
// Normalize "let x;" to "let x = undefined;" if in a loop, since we later convert x
// to be $jscomp$loop$0.x and want to reset the property to undefined every loop iteration.
if ((decl.isLet() || decl.isConst())
&& !nameNode.hasChildren()
&& (parent == null || !parent.isForIn())
&& inLoop(decl)) {
Node undefined = createUndefinedNode().srcref(nameNode);
nameNode.addChildToFront(undefined);
compiler.reportChangeToEnclosingScope(undefined);
}
String oldName = nameNode.getString();
Scope hoistScope = scope.getClosestHoistScope();
if (scope != hoistScope) {
String newName = oldName;
if (hoistScope.hasSlot(oldName) || undeclaredNames.contains(oldName)) {
do {
newName = oldName + "$" + compiler.getUniqueNameIdSupplier().get();
} while (hoistScope.hasSlot(newName));
nameNode.setString(newName);
compiler.reportChangeToEnclosingScope(nameNode);
Node scopeRoot = scope.getRootNode();
renameTable.put(scopeRoot, oldName, newName);
}
Var oldVar = scope.getVar(oldName);
scope.undeclare(oldVar);
hoistScope.declare(newName, nameNode, oldVar.input);
}
} | [
"private",
"void",
"visitBlockScopedName",
"(",
"NodeTraversal",
"t",
",",
"Node",
"decl",
",",
"Node",
"nameNode",
")",
"{",
"Scope",
"scope",
"=",
"t",
".",
"getScope",
"(",
")",
";",
"Node",
"parent",
"=",
"decl",
".",
"getParent",
"(",
")",
";",
"/... | Renames block-scoped declarations that shadow a variable in an outer scope
<p>Also normalizes declarations with no initializer in a loop to be initialized to undefined. | [
"Renames",
"block",
"-",
"scoped",
"declarations",
"that",
"shadow",
"a",
"variable",
"in",
"an",
"outer",
"scope"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteBlockScopedDeclaration.java#L141-L172 |
amzn/ion-java | src/com/amazon/ion/impl/bin/WriteBuffer.java | WriteBuffer.writeBytes | public void writeBytes(final byte[] bytes, final int off, final int len)
{
if (len > remaining())
{
writeBytesSlow(bytes, off, len);
return;
}
final Block block = current;
System.arraycopy(bytes, off, block.data, block.limit, len);
block.limit += len;
} | java | public void writeBytes(final byte[] bytes, final int off, final int len)
{
if (len > remaining())
{
writeBytesSlow(bytes, off, len);
return;
}
final Block block = current;
System.arraycopy(bytes, off, block.data, block.limit, len);
block.limit += len;
} | [
"public",
"void",
"writeBytes",
"(",
"final",
"byte",
"[",
"]",
"bytes",
",",
"final",
"int",
"off",
",",
"final",
"int",
"len",
")",
"{",
"if",
"(",
"len",
">",
"remaining",
"(",
")",
")",
"{",
"writeBytesSlow",
"(",
"bytes",
",",
"off",
",",
"len... | Writes an array of bytes to the buffer expanding if necessary. | [
"Writes",
"an",
"array",
"of",
"bytes",
"to",
"the",
"buffer",
"expanding",
"if",
"necessary",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/bin/WriteBuffer.java#L160-L171 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/Iterate.java | Iterate.detectIfNone | public static <T> T detectIfNone(Iterable<T> iterable, Predicate<? super T> predicate, T ifNone)
{
T result = Iterate.detect(iterable, predicate);
return result == null ? ifNone : result;
} | java | public static <T> T detectIfNone(Iterable<T> iterable, Predicate<? super T> predicate, T ifNone)
{
T result = Iterate.detect(iterable, predicate);
return result == null ? ifNone : result;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"detectIfNone",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
",",
"Predicate",
"<",
"?",
"super",
"T",
">",
"predicate",
",",
"T",
"ifNone",
")",
"{",
"T",
"result",
"=",
"Iterate",
".",
"detect",
"(",
"iterable... | Returns the first element of the iterable that evaluates to true for the specified predicate, or returns the
result ifNone if no element evaluates to true. | [
"Returns",
"the",
"first",
"element",
"of",
"the",
"iterable",
"that",
"evaluates",
"to",
"true",
"for",
"the",
"specified",
"predicate",
"or",
"returns",
"the",
"result",
"ifNone",
"if",
"no",
"element",
"evaluates",
"to",
"true",
"."
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/Iterate.java#L2334-L2338 |
UrielCh/ovh-java-sdk | ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java | ApiOvhClusterhadoop.serviceName_networkAcl_block_GET | public OvhNetworkAcl serviceName_networkAcl_block_GET(String serviceName, String block) throws IOException {
String qPath = "/cluster/hadoop/{serviceName}/networkAcl/{block}";
StringBuilder sb = path(qPath, serviceName, block);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhNetworkAcl.class);
} | java | public OvhNetworkAcl serviceName_networkAcl_block_GET(String serviceName, String block) throws IOException {
String qPath = "/cluster/hadoop/{serviceName}/networkAcl/{block}";
StringBuilder sb = path(qPath, serviceName, block);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhNetworkAcl.class);
} | [
"public",
"OvhNetworkAcl",
"serviceName_networkAcl_block_GET",
"(",
"String",
"serviceName",
",",
"String",
"block",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cluster/hadoop/{serviceName}/networkAcl/{block}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
... | Get this object properties
REST: GET /cluster/hadoop/{serviceName}/networkAcl/{block}
@param serviceName [required] The internal name of your cluster
@param block [required] IP Block to allow | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java#L42-L47 |
Netflix/Nicobar | nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleUtils.java | JBossModuleUtils.populateModuleSpecWithCoreDependencies | public static void populateModuleSpecWithCoreDependencies(ModuleSpec.Builder moduleSpecBuilder, ScriptArchive scriptArchive) throws ModuleLoadException {
Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder");
Objects.requireNonNull(scriptArchive, "scriptArchive");
Set<String> compilerPlugins = scriptArchive.getModuleSpec().getCompilerPluginIds();
for (String compilerPluginId : compilerPlugins) {
moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(getPluginModuleId(compilerPluginId), false));
}
moduleSpecBuilder.addDependency(JRE_DEPENDENCY_SPEC);
// TODO: Why does a module need a dependency on Nicobar itself?
moduleSpecBuilder.addDependency(NICOBAR_CORE_DEPENDENCY_SPEC);
moduleSpecBuilder.addDependency(DependencySpec.createLocalDependencySpec());
} | java | public static void populateModuleSpecWithCoreDependencies(ModuleSpec.Builder moduleSpecBuilder, ScriptArchive scriptArchive) throws ModuleLoadException {
Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder");
Objects.requireNonNull(scriptArchive, "scriptArchive");
Set<String> compilerPlugins = scriptArchive.getModuleSpec().getCompilerPluginIds();
for (String compilerPluginId : compilerPlugins) {
moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(getPluginModuleId(compilerPluginId), false));
}
moduleSpecBuilder.addDependency(JRE_DEPENDENCY_SPEC);
// TODO: Why does a module need a dependency on Nicobar itself?
moduleSpecBuilder.addDependency(NICOBAR_CORE_DEPENDENCY_SPEC);
moduleSpecBuilder.addDependency(DependencySpec.createLocalDependencySpec());
} | [
"public",
"static",
"void",
"populateModuleSpecWithCoreDependencies",
"(",
"ModuleSpec",
".",
"Builder",
"moduleSpecBuilder",
",",
"ScriptArchive",
"scriptArchive",
")",
"throws",
"ModuleLoadException",
"{",
"Objects",
".",
"requireNonNull",
"(",
"moduleSpecBuilder",
",",
... | Populates a module spec builder with core dependencies on JRE, Nicobar, itself, and compiler plugins.
@param moduleSpecBuilder builder to populate
@param scriptArchive {@link ScriptArchive} to copy from | [
"Populates",
"a",
"module",
"spec",
"builder",
"with",
"core",
"dependencies",
"on",
"JRE",
"Nicobar",
"itself",
"and",
"compiler",
"plugins",
"."
] | train | https://github.com/Netflix/Nicobar/blob/507173dcae4a86a955afc3df222a855862fab8d7/nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleUtils.java#L142-L154 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingPoliciesInner.java | StreamingPoliciesInner.createAsync | public Observable<StreamingPolicyInner> createAsync(String resourceGroupName, String accountName, String streamingPolicyName, StreamingPolicyInner parameters) {
return createWithServiceResponseAsync(resourceGroupName, accountName, streamingPolicyName, parameters).map(new Func1<ServiceResponse<StreamingPolicyInner>, StreamingPolicyInner>() {
@Override
public StreamingPolicyInner call(ServiceResponse<StreamingPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<StreamingPolicyInner> createAsync(String resourceGroupName, String accountName, String streamingPolicyName, StreamingPolicyInner parameters) {
return createWithServiceResponseAsync(resourceGroupName, accountName, streamingPolicyName, parameters).map(new Func1<ServiceResponse<StreamingPolicyInner>, StreamingPolicyInner>() {
@Override
public StreamingPolicyInner call(ServiceResponse<StreamingPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StreamingPolicyInner",
">",
"createAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"streamingPolicyName",
",",
"StreamingPolicyInner",
"parameters",
")",
"{",
"return",
"createWithServiceResponseAsync",
... | Create a Streaming Policy.
Create a Streaming Policy in the Media Services account.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param streamingPolicyName The Streaming Policy name.
@param parameters The request parameters
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StreamingPolicyInner object | [
"Create",
"a",
"Streaming",
"Policy",
".",
"Create",
"a",
"Streaming",
"Policy",
"in",
"the",
"Media",
"Services",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingPoliciesInner.java#L495-L502 |
hibernate/hibernate-ogm | core/src/main/java/org/hibernate/ogm/loader/entity/impl/BatchingEntityLoaderBuilder.java | BatchingEntityLoaderBuilder.buildLoader | public UniqueEntityLoader buildLoader(
OuterJoinLoadable persister,
int batchSize,
LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers influencers,
BatchableEntityLoaderBuilder innerEntityLoaderBuilder) {
if ( batchSize <= 1 ) {
// no batching
return buildNonBatchingLoader( persister, lockOptions, factory, influencers, innerEntityLoaderBuilder );
}
return buildBatchingLoader( persister, batchSize, lockOptions, factory, influencers, innerEntityLoaderBuilder );
} | java | public UniqueEntityLoader buildLoader(
OuterJoinLoadable persister,
int batchSize,
LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers influencers,
BatchableEntityLoaderBuilder innerEntityLoaderBuilder) {
if ( batchSize <= 1 ) {
// no batching
return buildNonBatchingLoader( persister, lockOptions, factory, influencers, innerEntityLoaderBuilder );
}
return buildBatchingLoader( persister, batchSize, lockOptions, factory, influencers, innerEntityLoaderBuilder );
} | [
"public",
"UniqueEntityLoader",
"buildLoader",
"(",
"OuterJoinLoadable",
"persister",
",",
"int",
"batchSize",
",",
"LockOptions",
"lockOptions",
",",
"SessionFactoryImplementor",
"factory",
",",
"LoadQueryInfluencers",
"influencers",
",",
"BatchableEntityLoaderBuilder",
"inn... | Builds a batch-fetch capable loader based on the given persister, lock-options, etc.
@param persister The entity persister
@param batchSize The maximum number of ids to batch-fetch at once
@param lockOptions The lock options
@param factory The SessionFactory
@param influencers Any influencers that should affect the built query
@param innerEntityLoaderBuilder Builder of the entity loader receiving the subset of batches
@return The loader. | [
"Builds",
"a",
"batch",
"-",
"fetch",
"capable",
"loader",
"based",
"on",
"the",
"given",
"persister",
"lock",
"-",
"options",
"etc",
"."
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/loader/entity/impl/BatchingEntityLoaderBuilder.java#L141-L153 |
actorapp/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/notifications/NotificationsActor.java | NotificationsActor.setLastReadDate | private void setLastReadDate(Peer peer, long date) {
storage.put(peer.getUnuqueId(), new ReadState(date).toByteArray());
readStates.put(peer, date);
} | java | private void setLastReadDate(Peer peer, long date) {
storage.put(peer.getUnuqueId(), new ReadState(date).toByteArray());
readStates.put(peer, date);
} | [
"private",
"void",
"setLastReadDate",
"(",
"Peer",
"peer",
",",
"long",
"date",
")",
"{",
"storage",
".",
"put",
"(",
"peer",
".",
"getUnuqueId",
"(",
")",
",",
"new",
"ReadState",
"(",
"date",
")",
".",
"toByteArray",
"(",
")",
")",
";",
"readStates",... | Setting last read date for peer
@param peer peer
@param date date | [
"Setting",
"last",
"read",
"date",
"for",
"peer"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/notifications/NotificationsActor.java#L543-L546 |
hellosign/hellosign-java-sdk | src/main/java/com/hellosign/sdk/http/HttpClient.java | HttpClient.validate | private void validate(JSONObject json) throws HelloSignException {
if (json.has("error")) {
try {
JSONObject error = json.getJSONObject("error");
String message = error.getString("error_msg");
String type = error.getString("error_name");
throw new HelloSignException(message, getLastResponseCode(), type);
} catch (JSONException ex) {
throw new HelloSignException(ex);
}
}
} | java | private void validate(JSONObject json) throws HelloSignException {
if (json.has("error")) {
try {
JSONObject error = json.getJSONObject("error");
String message = error.getString("error_msg");
String type = error.getString("error_name");
throw new HelloSignException(message, getLastResponseCode(), type);
} catch (JSONException ex) {
throw new HelloSignException(ex);
}
}
} | [
"private",
"void",
"validate",
"(",
"JSONObject",
"json",
")",
"throws",
"HelloSignException",
"{",
"if",
"(",
"json",
".",
"has",
"(",
"\"error\"",
")",
")",
"{",
"try",
"{",
"JSONObject",
"error",
"=",
"json",
".",
"getJSONObject",
"(",
"\"error\"",
")",... | Inspects the JSONObject response for errors and throws an exception if
found.
@param json JSONObject response
@param code HTTP response code
@throws HelloSignException thrown if an error is reported from the API
call | [
"Inspects",
"the",
"JSONObject",
"response",
"for",
"errors",
"and",
"throws",
"an",
"exception",
"if",
"found",
"."
] | train | https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/http/HttpClient.java#L171-L182 |
pedrovgs/DraggablePanel | sample/src/main/java/com/github/pedrovgs/sample/di/MainModule.java | MainModule.provideTvShowRendererAdapter | @Provides protected RendererAdapter<TvShowViewModel> provideTvShowRendererAdapter(
LayoutInflater layoutInflater,
TvShowCollectionRendererBuilder tvShowCollectionRendererBuilder,
TvShowCollectionViewModel tvShowCollectionViewModel) {
return new RendererAdapter<TvShowViewModel>(layoutInflater, tvShowCollectionRendererBuilder,
tvShowCollectionViewModel);
} | java | @Provides protected RendererAdapter<TvShowViewModel> provideTvShowRendererAdapter(
LayoutInflater layoutInflater,
TvShowCollectionRendererBuilder tvShowCollectionRendererBuilder,
TvShowCollectionViewModel tvShowCollectionViewModel) {
return new RendererAdapter<TvShowViewModel>(layoutInflater, tvShowCollectionRendererBuilder,
tvShowCollectionViewModel);
} | [
"@",
"Provides",
"protected",
"RendererAdapter",
"<",
"TvShowViewModel",
">",
"provideTvShowRendererAdapter",
"(",
"LayoutInflater",
"layoutInflater",
",",
"TvShowCollectionRendererBuilder",
"tvShowCollectionRendererBuilder",
",",
"TvShowCollectionViewModel",
"tvShowCollectionViewMod... | Provisioning of a RendererAdapter implementation to work with tv shows ListView. More
information in this library: {@link https://github.com/pedrovgs/Renderers} | [
"Provisioning",
"of",
"a",
"RendererAdapter",
"implementation",
"to",
"work",
"with",
"tv",
"shows",
"ListView",
".",
"More",
"information",
"in",
"this",
"library",
":",
"{"
] | train | https://github.com/pedrovgs/DraggablePanel/blob/6b6d1806fa4140113f31307a2571bf02435aa53a/sample/src/main/java/com/github/pedrovgs/sample/di/MainModule.java#L106-L112 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsp.2.3/src/org/apache/jasper/runtime/ProtectedFunctionMapper.java | ProtectedFunctionMapper.resolveFunction | @Override
public Method resolveFunction(String prefix, String localName) {
return (Method) this.fnmap.get(prefix + ":" + localName);
} | java | @Override
public Method resolveFunction(String prefix, String localName) {
return (Method) this.fnmap.get(prefix + ":" + localName);
} | [
"@",
"Override",
"public",
"Method",
"resolveFunction",
"(",
"String",
"prefix",
",",
"String",
"localName",
")",
"{",
"return",
"(",
"Method",
")",
"this",
".",
"fnmap",
".",
"get",
"(",
"prefix",
"+",
"\":\"",
"+",
"localName",
")",
";",
"}"
] | Resolves the specified local name and prefix into a Java.lang.Method.
Returns null if the prefix and local name are not found.
@param prefix the prefix of the function
@param localName the short name of the function
@return the result of the method mapping. Null means no entry found. | [
"Resolves",
"the",
"specified",
"local",
"name",
"and",
"prefix",
"into",
"a",
"Java",
".",
"lang",
".",
"Method",
".",
"Returns",
"null",
"if",
"the",
"prefix",
"and",
"local",
"name",
"are",
"not",
"found",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsp.2.3/src/org/apache/jasper/runtime/ProtectedFunctionMapper.java#L177-L180 |
lessthanoptimal/ejml | main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java | CommonOps_DSCC.multColumns | public static void multColumns(DMatrixSparseCSC A , double []values , int offset) {
if( values.length+offset < A.numCols )
throw new IllegalArgumentException("Array is too small. "+values.length+" < "+A.numCols);
for (int i = 0; i < A.numCols; i++) {
int idx0 = A.col_idx[i];
int idx1 = A.col_idx[i+1];
double v = values[offset+i];
for (int j = idx0; j < idx1; j++) {
A.nz_values[j] *= v;
}
}
} | java | public static void multColumns(DMatrixSparseCSC A , double []values , int offset) {
if( values.length+offset < A.numCols )
throw new IllegalArgumentException("Array is too small. "+values.length+" < "+A.numCols);
for (int i = 0; i < A.numCols; i++) {
int idx0 = A.col_idx[i];
int idx1 = A.col_idx[i+1];
double v = values[offset+i];
for (int j = idx0; j < idx1; j++) {
A.nz_values[j] *= v;
}
}
} | [
"public",
"static",
"void",
"multColumns",
"(",
"DMatrixSparseCSC",
"A",
",",
"double",
"[",
"]",
"values",
",",
"int",
"offset",
")",
"{",
"if",
"(",
"values",
".",
"length",
"+",
"offset",
"<",
"A",
".",
"numCols",
")",
"throw",
"new",
"IllegalArgument... | Multiply all elements of column 'i' by value[i]. A[:,i] *= values[i].<br>
Equivalent to A = A*diag(values)
@param A (Input/Output) Matrix. Modified.
@param values (Input) multiplication factor for each column
@param offset (Input) first index in values to start at | [
"Multiply",
"all",
"elements",
"of",
"column",
"i",
"by",
"value",
"[",
"i",
"]",
".",
"A",
"[",
":",
"i",
"]",
"*",
"=",
"values",
"[",
"i",
"]",
".",
"<br",
">",
"Equivalent",
"to",
"A",
"=",
"A",
"*",
"diag",
"(",
"values",
")"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L605-L618 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getFromLastIncl | @Nullable
public static String getFromLastIncl (@Nullable final String sStr, final char cSearch)
{
return _getFromLast (sStr, cSearch, true);
} | java | @Nullable
public static String getFromLastIncl (@Nullable final String sStr, final char cSearch)
{
return _getFromLast (sStr, cSearch, true);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getFromLastIncl",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"final",
"char",
"cSearch",
")",
"{",
"return",
"_getFromLast",
"(",
"sStr",
",",
"cSearch",
",",
"true",
")",
";",
"}"
] | Get everything from the string from and including the first passed char.
@param sStr
The source string. May be <code>null</code>.
@param cSearch
The character to search.
@return <code>null</code> if the passed string does not contain the search
character. | [
"Get",
"everything",
"from",
"the",
"string",
"from",
"and",
"including",
"the",
"first",
"passed",
"char",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L5025-L5029 |
brettonw/Bag | src/main/java/com/brettonw/bag/Bag.java | Bag.getBoolean | public Boolean getBoolean (String key, Supplier<Boolean> notFound) {
return getParsed (key, Boolean::new, notFound);
} | java | public Boolean getBoolean (String key, Supplier<Boolean> notFound) {
return getParsed (key, Boolean::new, notFound);
} | [
"public",
"Boolean",
"getBoolean",
"(",
"String",
"key",
",",
"Supplier",
"<",
"Boolean",
">",
"notFound",
")",
"{",
"return",
"getParsed",
"(",
"key",
",",
"Boolean",
"::",
"new",
",",
"notFound",
")",
";",
"}"
] | Retrieve a mapped element and return it as a Boolean.
@param key A string value used to index the element.
@param notFound A function to create a new Boolean if the requested key was not found
@return The element as a Boolean, or notFound if the element is not found. | [
"Retrieve",
"a",
"mapped",
"element",
"and",
"return",
"it",
"as",
"a",
"Boolean",
"."
] | train | https://github.com/brettonw/Bag/blob/25c0ff74893b6c9a2c61bf0f97189ab82e0b2f56/src/main/java/com/brettonw/bag/Bag.java#L166-L168 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java | MapIterate.occurrencesOf | public static <K, V> int occurrencesOf(Map<K, V> map, V object)
{
return Iterate.count(map.values(), Predicates.equal(object));
} | java | public static <K, V> int occurrencesOf(Map<K, V> map, V object)
{
return Iterate.count(map.values(), Predicates.equal(object));
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"int",
"occurrencesOf",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"V",
"object",
")",
"{",
"return",
"Iterate",
".",
"count",
"(",
"map",
".",
"values",
"(",
")",
",",
"Predicates",
".",
"equal"... | Return the number of occurrences of object in the specified map. | [
"Return",
"the",
"number",
"of",
"occurrences",
"of",
"object",
"in",
"the",
"specified",
"map",
"."
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L1022-L1025 |
jayantk/jklol | src/com/jayantkrish/jklol/cfg/CfgParseChart.java | CfgParseChart.getBestParseTreeWithSpan | public CfgParseTree getBestParseTreeWithSpan(Object root, int spanStart,
int spanEnd) {
Preconditions.checkState(!sumProduct);
Assignment rootAssignment = parentVar.outcomeArrayToAssignment(root);
int rootNonterminalNum = parentVar.assignmentToIntArray(rootAssignment)[0];
double prob = insideChart[spanStart][spanEnd][rootNonterminalNum]
* outsideChart[spanStart][spanEnd][rootNonterminalNum];
if (prob == 0.0) {
return null;
}
int splitInd = splitBackpointers[spanStart][spanEnd][rootNonterminalNum];
if (splitInd < 0) {
long terminalKey = backpointers[spanStart][spanEnd][rootNonterminalNum];
int positiveSplitInd = (-1 * splitInd) - 1;
int terminalSpanStart = positiveSplitInd / numTerminals;
int terminalSpanEnd = positiveSplitInd % numTerminals;
// This is a really sucky way to transform the keys back to objects.
VariableNumMap vars = parentVar.union(ruleTypeVar);
int[] dimKey = TableFactor.zero(vars).getWeights().keyNumToDimKey(terminalKey);
Assignment a = vars.intArrayToAssignment(dimKey);
Object ruleType = a.getValue(ruleTypeVar.getOnlyVariableNum());
List<Object> terminalList = Lists.newArrayList();
terminalList.addAll(terminals.subList(terminalSpanStart, terminalSpanEnd + 1));
return new CfgParseTree(root, ruleType, terminalList, prob, spanStart, spanEnd);
} else {
long binaryRuleKey = backpointers[spanStart][spanEnd][rootNonterminalNum];
int[] binaryRuleComponents = binaryRuleDistribution.coerceToDiscrete()
.getWeights().keyNumToDimKey(binaryRuleKey);
Assignment best = binaryRuleDistribution.getVars().intArrayToAssignment(binaryRuleComponents);
Object leftRoot = best.getValue(leftVar.getOnlyVariableNum());
Object rightRoot = best.getValue(rightVar.getOnlyVariableNum());
Object ruleType = best.getValue(ruleTypeVar.getOnlyVariableNum());
Preconditions.checkArgument(spanStart + splitInd != spanEnd,
"CFG parse decoding error: %s %s %s", spanStart, spanEnd, splitInd);
CfgParseTree leftTree = getBestParseTreeWithSpan(leftRoot, spanStart, spanStart + splitInd);
CfgParseTree rightTree = getBestParseTreeWithSpan(rightRoot, spanStart + splitInd + 1, spanEnd);
Preconditions.checkState(leftTree != null);
Preconditions.checkState(rightTree != null);
return new CfgParseTree(root, ruleType, leftTree, rightTree, prob);
}
} | java | public CfgParseTree getBestParseTreeWithSpan(Object root, int spanStart,
int spanEnd) {
Preconditions.checkState(!sumProduct);
Assignment rootAssignment = parentVar.outcomeArrayToAssignment(root);
int rootNonterminalNum = parentVar.assignmentToIntArray(rootAssignment)[0];
double prob = insideChart[spanStart][spanEnd][rootNonterminalNum]
* outsideChart[spanStart][spanEnd][rootNonterminalNum];
if (prob == 0.0) {
return null;
}
int splitInd = splitBackpointers[spanStart][spanEnd][rootNonterminalNum];
if (splitInd < 0) {
long terminalKey = backpointers[spanStart][spanEnd][rootNonterminalNum];
int positiveSplitInd = (-1 * splitInd) - 1;
int terminalSpanStart = positiveSplitInd / numTerminals;
int terminalSpanEnd = positiveSplitInd % numTerminals;
// This is a really sucky way to transform the keys back to objects.
VariableNumMap vars = parentVar.union(ruleTypeVar);
int[] dimKey = TableFactor.zero(vars).getWeights().keyNumToDimKey(terminalKey);
Assignment a = vars.intArrayToAssignment(dimKey);
Object ruleType = a.getValue(ruleTypeVar.getOnlyVariableNum());
List<Object> terminalList = Lists.newArrayList();
terminalList.addAll(terminals.subList(terminalSpanStart, terminalSpanEnd + 1));
return new CfgParseTree(root, ruleType, terminalList, prob, spanStart, spanEnd);
} else {
long binaryRuleKey = backpointers[spanStart][spanEnd][rootNonterminalNum];
int[] binaryRuleComponents = binaryRuleDistribution.coerceToDiscrete()
.getWeights().keyNumToDimKey(binaryRuleKey);
Assignment best = binaryRuleDistribution.getVars().intArrayToAssignment(binaryRuleComponents);
Object leftRoot = best.getValue(leftVar.getOnlyVariableNum());
Object rightRoot = best.getValue(rightVar.getOnlyVariableNum());
Object ruleType = best.getValue(ruleTypeVar.getOnlyVariableNum());
Preconditions.checkArgument(spanStart + splitInd != spanEnd,
"CFG parse decoding error: %s %s %s", spanStart, spanEnd, splitInd);
CfgParseTree leftTree = getBestParseTreeWithSpan(leftRoot, spanStart, spanStart + splitInd);
CfgParseTree rightTree = getBestParseTreeWithSpan(rightRoot, spanStart + splitInd + 1, spanEnd);
Preconditions.checkState(leftTree != null);
Preconditions.checkState(rightTree != null);
return new CfgParseTree(root, ruleType, leftTree, rightTree, prob);
}
} | [
"public",
"CfgParseTree",
"getBestParseTreeWithSpan",
"(",
"Object",
"root",
",",
"int",
"spanStart",
",",
"int",
"spanEnd",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"!",
"sumProduct",
")",
";",
"Assignment",
"rootAssignment",
"=",
"parentVar",
".",
"o... | If this tree contains max-marginals, recover the best parse subtree for a
given symbol with the specified span. | [
"If",
"this",
"tree",
"contains",
"max",
"-",
"marginals",
"recover",
"the",
"best",
"parse",
"subtree",
"for",
"a",
"given",
"symbol",
"with",
"the",
"specified",
"span",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/cfg/CfgParseChart.java#L308-L358 |
BellaDati/belladati-sdk-java | src/main/java/com/belladati/sdk/impl/BellaDatiClient.java | BellaDatiClient.buildClient | private CloseableHttpClient buildClient(boolean trustSelfSigned) {
try {
// if required, define custom SSL context allowing self-signed certs
SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault()
: SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
// set timeouts for the HTTP client
int globalTimeout = readFromProperty("bdTimeout", 100000);
int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout);
int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout);
int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout);
RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
// configure caching
CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000)
.setMaxObjectSize(2 * 1024 * 1024).build();
// configure connection pooling
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder
.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslContext)).build());
int connectionLimit = readFromProperty("bdMaxConnections", 40);
// there's only one server to connect to, so max per route matters
connManager.setMaxTotal(connectionLimit);
connManager.setDefaultMaxPerRoute(connectionLimit);
// create the HTTP client
return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig)
.setConnectionManager(connManager).build();
} catch (GeneralSecurityException e) {
throw new InternalConfigurationException("Failed to set up SSL context", e);
}
} | java | private CloseableHttpClient buildClient(boolean trustSelfSigned) {
try {
// if required, define custom SSL context allowing self-signed certs
SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault()
: SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
// set timeouts for the HTTP client
int globalTimeout = readFromProperty("bdTimeout", 100000);
int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout);
int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout);
int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout);
RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
// configure caching
CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000)
.setMaxObjectSize(2 * 1024 * 1024).build();
// configure connection pooling
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder
.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslContext)).build());
int connectionLimit = readFromProperty("bdMaxConnections", 40);
// there's only one server to connect to, so max per route matters
connManager.setMaxTotal(connectionLimit);
connManager.setDefaultMaxPerRoute(connectionLimit);
// create the HTTP client
return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig)
.setConnectionManager(connManager).build();
} catch (GeneralSecurityException e) {
throw new InternalConfigurationException("Failed to set up SSL context", e);
}
} | [
"private",
"CloseableHttpClient",
"buildClient",
"(",
"boolean",
"trustSelfSigned",
")",
"{",
"try",
"{",
"// if required, define custom SSL context allowing self-signed certs",
"SSLContext",
"sslContext",
"=",
"!",
"trustSelfSigned",
"?",
"SSLContexts",
".",
"createSystemDefau... | Builds the HTTP client to connect to the server.
@param trustSelfSigned <tt>true</tt> if the client should accept
self-signed certificates
@return a new client instance | [
"Builds",
"the",
"HTTP",
"client",
"to",
"connect",
"to",
"the",
"server",
"."
] | train | https://github.com/BellaDati/belladati-sdk-java/blob/1a732a57ebc825ddf47ce405723cc958adb1a43f/src/main/java/com/belladati/sdk/impl/BellaDatiClient.java#L94-L127 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java | TextAnalyticsManager.authenticate | public static TextAnalyticsAPI authenticate(AzureRegions region, String subscriptionKey) {
return authenticate("https://{AzureRegion}.api.cognitive.microsoft.com/text/analytics/", subscriptionKey)
.withAzureRegion(region);
} | java | public static TextAnalyticsAPI authenticate(AzureRegions region, String subscriptionKey) {
return authenticate("https://{AzureRegion}.api.cognitive.microsoft.com/text/analytics/", subscriptionKey)
.withAzureRegion(region);
} | [
"public",
"static",
"TextAnalyticsAPI",
"authenticate",
"(",
"AzureRegions",
"region",
",",
"String",
"subscriptionKey",
")",
"{",
"return",
"authenticate",
"(",
"\"https://{AzureRegion}.api.cognitive.microsoft.com/text/analytics/\"",
",",
"subscriptionKey",
")",
".",
"withAz... | Initializes an instance of Text Analytics API client.
@param region Supported Azure regions for Cognitive Services endpoints.
@param subscriptionKey the Text Analytics API key
@return the Text Analytics API client | [
"Initializes",
"an",
"instance",
"of",
"Text",
"Analytics",
"API",
"client",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java#L31-L34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.