repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
Trilarion/java-vorbis-support | src/main/java/com/github/trilarion/sound/vorbis/sampled/spi/VorbisAudioFileReader.java | VorbisAudioFileReader.getAudioFileFormat | @Override
public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException {
LOG.log(Level.FINE, "getAudioFileFormat(File file)");
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
inputStream.mark(MARK_LIMIT);
getAudioFileFormat(inputStream);
inputStream.reset();
// Get Vorbis file info such as length in seconds.
VorbisFile vf = new VorbisFile(file.getAbsolutePath());
return getAudioFileFormat(inputStream, (int) file.length(), (int) Math.round(vf.time_total(-1) * 1000));
} catch (SoundException e) {
throw new IOException(e.getMessage());
}
} | java | @Override
public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException {
LOG.log(Level.FINE, "getAudioFileFormat(File file)");
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
inputStream.mark(MARK_LIMIT);
getAudioFileFormat(inputStream);
inputStream.reset();
// Get Vorbis file info such as length in seconds.
VorbisFile vf = new VorbisFile(file.getAbsolutePath());
return getAudioFileFormat(inputStream, (int) file.length(), (int) Math.round(vf.time_total(-1) * 1000));
} catch (SoundException e) {
throw new IOException(e.getMessage());
}
} | [
"@",
"Override",
"public",
"AudioFileFormat",
"getAudioFileFormat",
"(",
"File",
"file",
")",
"throws",
"UnsupportedAudioFileException",
",",
"IOException",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"getAudioFileFormat(File file)\"",
")",
";",
"try",... | Return the AudioFileFormat from the given file.
@return
@throws javax.sound.sampled.UnsupportedAudioFileException
@throws java.io.IOException | [
"Return",
"the",
"AudioFileFormat",
"from",
"the",
"given",
"file",
"."
] | train | https://github.com/Trilarion/java-vorbis-support/blob/f72aba7d97167fe0ff20b1b719fdb5bb662ff736/src/main/java/com/github/trilarion/sound/vorbis/sampled/spi/VorbisAudioFileReader.java#L96-L109 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/DatabaseSpec.java | DatabaseSpec.createCustomMapping | @When("^I create a Cassandra index named '(.+?)' with schema '(.+?)' of type '(json|string)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)' with:$")
public void createCustomMapping(String index_name, String schema, String type, String table, String magic_column, String keyspace, DataTable modifications) throws Exception {
String retrievedData = commonspec.retrieveData(schema, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString();
String query = "CREATE CUSTOM INDEX " + index_name + " ON " + keyspace + "." + table + "(" + magic_column + ") "
+ "USING 'com.stratio.cassandra.lucene.Index' WITH OPTIONS = " + modifiedData;
commonspec.getLogger().debug("Will execute a cassandra query: {}", query);
commonspec.getCassandraClient().executeQuery(query);
} | java | @When("^I create a Cassandra index named '(.+?)' with schema '(.+?)' of type '(json|string)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)' with:$")
public void createCustomMapping(String index_name, String schema, String type, String table, String magic_column, String keyspace, DataTable modifications) throws Exception {
String retrievedData = commonspec.retrieveData(schema, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString();
String query = "CREATE CUSTOM INDEX " + index_name + " ON " + keyspace + "." + table + "(" + magic_column + ") "
+ "USING 'com.stratio.cassandra.lucene.Index' WITH OPTIONS = " + modifiedData;
commonspec.getLogger().debug("Will execute a cassandra query: {}", query);
commonspec.getCassandraClient().executeQuery(query);
} | [
"@",
"When",
"(",
"\"^I create a Cassandra index named '(.+?)' with schema '(.+?)' of type '(json|string)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)' with:$\"",
")",
"public",
"void",
"createCustomMapping",
"(",
"String",
"index_name",
",",
"String",
"schema",
","... | Create a Cassandra index.
@param index_name index name
@param schema the file of configuration (.conf) with the options of mappin
@param type type of the changes in schema (string or json)
@param table table for create the index
@param magic_column magic column where index will be saved
@param keyspace keyspace used
@param modifications data introduced for query fields defined on schema | [
"Create",
"a",
"Cassandra",
"index",
"."
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L488-L496 |
vakinge/jeesuite-libs | jeesuite-spring/src/main/java/com/jeesuite/spring/InstanceFactory.java | InstanceFactory.getInstance | public static <T> T getInstance(Class<T> beanClass, String beanName) {
return (T) getInstanceProvider().getInstance(beanClass, beanName);
} | java | public static <T> T getInstance(Class<T> beanClass, String beanName) {
return (T) getInstanceProvider().getInstance(beanClass, beanName);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getInstance",
"(",
"Class",
"<",
"T",
">",
"beanClass",
",",
"String",
"beanName",
")",
"{",
"return",
"(",
"T",
")",
"getInstanceProvider",
"(",
")",
".",
"getInstance",
"(",
"beanClass",
",",
"beanName",
")",
... | 获取指定类型的对象实例。如果IoC容器没配置好或者IoC容器中找不到该实例则抛出异常。
@param <T> 对象的类型
@param beanName 实现类在容器中配置的名字
@param beanClass 对象的类
@return 类型为T的对象实例 | [
"获取指定类型的对象实例。如果IoC容器没配置好或者IoC容器中找不到该实例则抛出异常。"
] | train | https://github.com/vakinge/jeesuite-libs/blob/c48fe2c7fbd294892cf4030dbec96e744dd3e386/jeesuite-spring/src/main/java/com/jeesuite/spring/InstanceFactory.java#L61-L63 |
podio/podio-java | src/main/java/com/podio/app/AppAPI.java | AppAPI.getField | public ApplicationField getField(int appId, int fieldId) {
return getResourceFactory().getApiResource(
"/app/" + appId + "/field/" + fieldId).get(
ApplicationField.class);
} | java | public ApplicationField getField(int appId, int fieldId) {
return getResourceFactory().getApiResource(
"/app/" + appId + "/field/" + fieldId).get(
ApplicationField.class);
} | [
"public",
"ApplicationField",
"getField",
"(",
"int",
"appId",
",",
"int",
"fieldId",
")",
"{",
"return",
"getResourceFactory",
"(",
")",
".",
"getApiResource",
"(",
"\"/app/\"",
"+",
"appId",
"+",
"\"/field/\"",
"+",
"fieldId",
")",
".",
"get",
"(",
"Applic... | Returns a single field from an app.
@param appId
The id of the app the field is on
@param fieldId
The id of the field to be returned
@return The definition and current configuration of the requested field | [
"Returns",
"a",
"single",
"field",
"from",
"an",
"app",
"."
] | train | https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/app/AppAPI.java#L144-L148 |
algolia/instantsearch-android | core/src/main/java/com/algolia/instantsearch/core/utils/JSONUtils.java | JSONUtils.getStringFromJSONPath | public static String getStringFromJSONPath(JSONObject record, String path) {
final Object object = getObjectFromJSONPath(record, path);
return object == null ? null : object.toString();
} | java | public static String getStringFromJSONPath(JSONObject record, String path) {
final Object object = getObjectFromJSONPath(record, path);
return object == null ? null : object.toString();
} | [
"public",
"static",
"String",
"getStringFromJSONPath",
"(",
"JSONObject",
"record",
",",
"String",
"path",
")",
"{",
"final",
"Object",
"object",
"=",
"getObjectFromJSONPath",
"(",
"record",
",",
"path",
")",
";",
"return",
"object",
"==",
"null",
"?",
"null",... | Gets a string attribute from a json object given a path to traverse.
@param record a JSONObject to traverse.
@param path the json path to follow.
@return the attribute as a {@link String}, or null if it was not found. | [
"Gets",
"a",
"string",
"attribute",
"from",
"a",
"json",
"object",
"given",
"a",
"path",
"to",
"traverse",
"."
] | train | https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/utils/JSONUtils.java#L21-L24 |
PawelAdamski/HttpClientMock | src/main/java/com/github/paweladamski/httpclientmock/HttpClientVerifyBuilder.java | HttpClientVerifyBuilder.withParameter | public HttpClientVerifyBuilder withParameter(String name, Matcher<String> matcher) {
ruleBuilder.addParameterCondition(name, matcher);
return this;
} | java | public HttpClientVerifyBuilder withParameter(String name, Matcher<String> matcher) {
ruleBuilder.addParameterCondition(name, matcher);
return this;
} | [
"public",
"HttpClientVerifyBuilder",
"withParameter",
"(",
"String",
"name",
",",
"Matcher",
"<",
"String",
">",
"matcher",
")",
"{",
"ruleBuilder",
".",
"addParameterCondition",
"(",
"name",
",",
"matcher",
")",
";",
"return",
"this",
";",
"}"
] | Adds parameter condition. Parameter value must match.
@param name parameter name
@param matcher parameter value matcher
@return verification builder | [
"Adds",
"parameter",
"condition",
".",
"Parameter",
"value",
"must",
"match",
"."
] | train | https://github.com/PawelAdamski/HttpClientMock/blob/0205498434bbc0c78c187a51181cac9b266a28fb/src/main/java/com/github/paweladamski/httpclientmock/HttpClientVerifyBuilder.java#L84-L87 |
fcrepo4/fcrepo4 | fcrepo-http-api/src/main/java/org/fcrepo/http/api/ContentExposingResource.java | ContentExposingResource.buildLink | protected static String buildLink(final String linkUri, final String relation) {
return buildLink(URI.create(linkUri), relation);
} | java | protected static String buildLink(final String linkUri, final String relation) {
return buildLink(URI.create(linkUri), relation);
} | [
"protected",
"static",
"String",
"buildLink",
"(",
"final",
"String",
"linkUri",
",",
"final",
"String",
"relation",
")",
"{",
"return",
"buildLink",
"(",
"URI",
".",
"create",
"(",
"linkUri",
")",
",",
"relation",
")",
";",
"}"
] | Utility function for building a Link.
@param linkUri String of URI for the link.
@param relation the relation string.
@return the string version of the link. | [
"Utility",
"function",
"for",
"building",
"a",
"Link",
"."
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-api/src/main/java/org/fcrepo/http/api/ContentExposingResource.java#L625-L627 |
aws/aws-sdk-java | jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java | JmesPathEvaluationVisitor.visit | @Override
public JsonNode visit(Comparator op, JsonNode input) {
JsonNode lhsNode = op.getLhsExpr().accept(this, input);
JsonNode rhsNode = op.getRhsExpr().accept(this, input);
if (op.matches(lhsNode, rhsNode)) {
return BooleanNode.TRUE;
}
return BooleanNode.FALSE;
} | java | @Override
public JsonNode visit(Comparator op, JsonNode input) {
JsonNode lhsNode = op.getLhsExpr().accept(this, input);
JsonNode rhsNode = op.getRhsExpr().accept(this, input);
if (op.matches(lhsNode, rhsNode)) {
return BooleanNode.TRUE;
}
return BooleanNode.FALSE;
} | [
"@",
"Override",
"public",
"JsonNode",
"visit",
"(",
"Comparator",
"op",
",",
"JsonNode",
"input",
")",
"{",
"JsonNode",
"lhsNode",
"=",
"op",
".",
"getLhsExpr",
"(",
")",
".",
"accept",
"(",
"this",
",",
"input",
")",
";",
"JsonNode",
"rhsNode",
"=",
... | Evaluate the expressions as per the given comparison
operator.
@param op JmesPath comparison operator type
@param input Input json node against which evaluation is done
@return Result of the comparison | [
"Evaluate",
"the",
"expressions",
"as",
"per",
"the",
"given",
"comparison",
"operator",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java#L257-L266 |
netty/netty | codec/src/main/java/io/netty/handler/codec/protobuf/ProtobufVarint32LengthFieldPrepender.java | ProtobufVarint32LengthFieldPrepender.writeRawVarint32 | static void writeRawVarint32(ByteBuf out, int value) {
while (true) {
if ((value & ~0x7F) == 0) {
out.writeByte(value);
return;
} else {
out.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
}
} | java | static void writeRawVarint32(ByteBuf out, int value) {
while (true) {
if ((value & ~0x7F) == 0) {
out.writeByte(value);
return;
} else {
out.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
}
} | [
"static",
"void",
"writeRawVarint32",
"(",
"ByteBuf",
"out",
",",
"int",
"value",
")",
"{",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"(",
"value",
"&",
"~",
"0x7F",
")",
"==",
"0",
")",
"{",
"out",
".",
"writeByte",
"(",
"value",
")",
";",
"ret... | Writes protobuf varint32 to (@link ByteBuf).
@param out to be written to
@param value to be written | [
"Writes",
"protobuf",
"varint32",
"to",
"("
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/protobuf/ProtobufVarint32LengthFieldPrepender.java#L58-L68 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbKeywords.java | TmdbKeywords.getKeywordMovies | public ResultList<MovieBasic> getKeywordMovies(String keywordId, String language, Integer page) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, keywordId);
parameters.add(Param.LANGUAGE, language);
parameters.add(Param.PAGE, page);
URL url = new ApiUrl(apiKey, MethodBase.KEYWORD).subMethod(MethodSub.MOVIES).buildUrl(parameters);
WrapperGenericList<MovieBasic> wrapper = processWrapper(getTypeReference(MovieBasic.class), url, "keyword movies");
return wrapper.getResultsList();
} | java | public ResultList<MovieBasic> getKeywordMovies(String keywordId, String language, Integer page) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, keywordId);
parameters.add(Param.LANGUAGE, language);
parameters.add(Param.PAGE, page);
URL url = new ApiUrl(apiKey, MethodBase.KEYWORD).subMethod(MethodSub.MOVIES).buildUrl(parameters);
WrapperGenericList<MovieBasic> wrapper = processWrapper(getTypeReference(MovieBasic.class), url, "keyword movies");
return wrapper.getResultsList();
} | [
"public",
"ResultList",
"<",
"MovieBasic",
">",
"getKeywordMovies",
"(",
"String",
"keywordId",
",",
"String",
"language",
",",
"Integer",
"page",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",
")",
";",
... | Get the list of movies for a particular keyword by id.
@param keywordId
@param language
@param page
@return List of movies with the keyword
@throws MovieDbException | [
"Get",
"the",
"list",
"of",
"movies",
"for",
"a",
"particular",
"keyword",
"by",
"id",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbKeywords.java#L85-L94 |
logic-ng/LogicNG | src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java | Encoder.encodePB | public void encodePB(final MiniSatStyleSolver s, final LNGIntVector lits, final LNGIntVector coeffs, int rhs) {
switch (this.pbEncoding) {
case SWC:
this.swc.encode(s, lits, coeffs, rhs);
break;
default:
throw new IllegalStateException("Unknown pseudo-Boolean encoding: " + this.pbEncoding);
}
} | java | public void encodePB(final MiniSatStyleSolver s, final LNGIntVector lits, final LNGIntVector coeffs, int rhs) {
switch (this.pbEncoding) {
case SWC:
this.swc.encode(s, lits, coeffs, rhs);
break;
default:
throw new IllegalStateException("Unknown pseudo-Boolean encoding: " + this.pbEncoding);
}
} | [
"public",
"void",
"encodePB",
"(",
"final",
"MiniSatStyleSolver",
"s",
",",
"final",
"LNGIntVector",
"lits",
",",
"final",
"LNGIntVector",
"coeffs",
",",
"int",
"rhs",
")",
"{",
"switch",
"(",
"this",
".",
"pbEncoding",
")",
"{",
"case",
"SWC",
":",
"this"... | Encodes a pseudo-Boolean constraint.
@param s the solver
@param lits the literals of the constraint
@param coeffs the coefficients of the constraints
@param rhs the right hand side of the constraint
@throws IllegalStateException if the pseudo-Boolean encoding is unknown | [
"Encodes",
"a",
"pseudo",
"-",
"Boolean",
"constraint",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java#L252-L260 |
samskivert/samskivert | src/main/java/com/samskivert/swing/LabelSausage.java | LabelSausage.drawBase | protected void drawBase (Graphics2D gfx, int x, int y)
{
gfx.fillRoundRect(
x, y, _size.width - 1, _size.height - 1, _dia, _dia);
} | java | protected void drawBase (Graphics2D gfx, int x, int y)
{
gfx.fillRoundRect(
x, y, _size.width - 1, _size.height - 1, _dia, _dia);
} | [
"protected",
"void",
"drawBase",
"(",
"Graphics2D",
"gfx",
",",
"int",
"x",
",",
"int",
"y",
")",
"{",
"gfx",
".",
"fillRoundRect",
"(",
"x",
",",
"y",
",",
"_size",
".",
"width",
"-",
"1",
",",
"_size",
".",
"height",
"-",
"1",
",",
"_dia",
",",... | Draws the base sausage within which all the other decorations are added. | [
"Draws",
"the",
"base",
"sausage",
"within",
"which",
"all",
"the",
"other",
"decorations",
"are",
"added",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/LabelSausage.java#L127-L131 |
ops4j/org.ops4j.pax.exam2 | containers/pax-exam-container-eclipse/src/main/java/org/ops4j/pax/exam/container/eclipse/impl/parser/AbstractParser.java | AbstractParser.getAttribute | protected static String getAttribute(Node node, String name, boolean required) {
NamedNodeMap attributes = node.getAttributes();
Node idNode = attributes.getNamedItem(name);
if (idNode == null) {
if (required) {
throw new IllegalArgumentException(toPath(node) + " has no " + name + " attribute");
}
else {
return "";
}
}
else {
String value = idNode.getNodeValue();
if (value == null) {
return "";
}
return value;
}
} | java | protected static String getAttribute(Node node, String name, boolean required) {
NamedNodeMap attributes = node.getAttributes();
Node idNode = attributes.getNamedItem(name);
if (idNode == null) {
if (required) {
throw new IllegalArgumentException(toPath(node) + " has no " + name + " attribute");
}
else {
return "";
}
}
else {
String value = idNode.getNodeValue();
if (value == null) {
return "";
}
return value;
}
} | [
"protected",
"static",
"String",
"getAttribute",
"(",
"Node",
"node",
",",
"String",
"name",
",",
"boolean",
"required",
")",
"{",
"NamedNodeMap",
"attributes",
"=",
"node",
".",
"getAttributes",
"(",
")",
";",
"Node",
"idNode",
"=",
"attributes",
".",
"getN... | Get an Attribute from the given node and throwing an exception in the case it is required but
not present
@param node
@param name
@param required
@return | [
"Get",
"an",
"Attribute",
"from",
"the",
"given",
"node",
"and",
"throwing",
"an",
"exception",
"in",
"the",
"case",
"it",
"is",
"required",
"but",
"not",
"present"
] | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-eclipse/src/main/java/org/ops4j/pax/exam/container/eclipse/impl/parser/AbstractParser.java#L109-L127 |
pressgang-ccms/PressGangCCMSQuery | src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilder.java | BaseFilterQueryBuilder.addNotEqualsCondition | protected void addNotEqualsCondition(final String propertyName, final String value) {
fieldConditions.add(getCriteriaBuilder().notEqual(getRootPath().get(propertyName).as(String.class), value));
} | java | protected void addNotEqualsCondition(final String propertyName, final String value) {
fieldConditions.add(getCriteriaBuilder().notEqual(getRootPath().get(propertyName).as(String.class), value));
} | [
"protected",
"void",
"addNotEqualsCondition",
"(",
"final",
"String",
"propertyName",
",",
"final",
"String",
"value",
")",
"{",
"fieldConditions",
".",
"add",
"(",
"getCriteriaBuilder",
"(",
")",
".",
"notEqual",
"(",
"getRootPath",
"(",
")",
".",
"get",
"(",... | Add a Field Search Condition that will search a field for a specified value using the following SQL logic:
{@code field != 'value'}
@param propertyName The name of the field as defined in the Entity mapping class.
@param value The value to search against. | [
"Add",
"a",
"Field",
"Search",
"Condition",
"that",
"will",
"search",
"a",
"field",
"for",
"a",
"specified",
"value",
"using",
"the",
"following",
"SQL",
"logic",
":",
"{",
"@code",
"field",
"!",
"=",
"value",
"}"
] | train | https://github.com/pressgang-ccms/PressGangCCMSQuery/blob/2bb23430adab956737d0301cd2ea933f986dd85b/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilder.java#L463-L465 |
elki-project/elki | elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/invertedlist/InMemoryInvertedIndex.java | InMemoryInvertedIndex.naiveQueryDense | private double naiveQueryDense(NumberVector obj, WritableDoubleDataStore scores, HashSetModifiableDBIDs cands) {
double len = 0.; // Length of query object, for final normalization
for(int dim = 0, max = obj.getDimensionality(); dim < max; dim++) {
final double val = obj.doubleValue(dim);
if(val == 0. || val != val) {
continue;
}
len += val * val;
// No matching documents in index:
if(dim >= index.size()) {
continue;
}
ModifiableDoubleDBIDList column = index.get(dim);
for(DoubleDBIDListIter n = column.iter(); n.valid(); n.advance()) {
scores.increment(n, n.doubleValue() * val);
cands.add(n);
}
}
return FastMath.sqrt(len);
} | java | private double naiveQueryDense(NumberVector obj, WritableDoubleDataStore scores, HashSetModifiableDBIDs cands) {
double len = 0.; // Length of query object, for final normalization
for(int dim = 0, max = obj.getDimensionality(); dim < max; dim++) {
final double val = obj.doubleValue(dim);
if(val == 0. || val != val) {
continue;
}
len += val * val;
// No matching documents in index:
if(dim >= index.size()) {
continue;
}
ModifiableDoubleDBIDList column = index.get(dim);
for(DoubleDBIDListIter n = column.iter(); n.valid(); n.advance()) {
scores.increment(n, n.doubleValue() * val);
cands.add(n);
}
}
return FastMath.sqrt(len);
} | [
"private",
"double",
"naiveQueryDense",
"(",
"NumberVector",
"obj",
",",
"WritableDoubleDataStore",
"scores",
",",
"HashSetModifiableDBIDs",
"cands",
")",
"{",
"double",
"len",
"=",
"0.",
";",
"// Length of query object, for final normalization",
"for",
"(",
"int",
"dim... | Query the most similar objects, dense version.
@param obj Query object
@param scores Score storage
@param cands Non-zero objects set
@return Result | [
"Query",
"the",
"most",
"similar",
"objects",
"dense",
"version",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/invertedlist/InMemoryInvertedIndex.java#L210-L229 |
zerodhatech/javakiteconnect | kiteconnect/src/com/zerodhatech/kiteconnect/KiteConnect.java | KiteConnect.placeMFSIP | public MFSIP placeMFSIP(String tradingsymbol, String frequency, int installmentDay, int instalments, int initialAmount, double amount) throws KiteException, IOException, JSONException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("tradingsymbol", tradingsymbol);
params.put("frequency", frequency);
params.put("instalment_day", installmentDay);
params.put("instalments", instalments);
params.put("initial_amount", initialAmount);
params.put("amount", amount);
MFSIP MFSIP = new MFSIP();
JSONObject response = new KiteRequestHandler(proxy).postRequest(routes.get("mutualfunds.sips.place"),params, apiKey, accessToken);
MFSIP.orderId = response.getJSONObject("data").getString("order_id");
MFSIP.sipId = response.getJSONObject("data").getString("sip_id");
return MFSIP;
} | java | public MFSIP placeMFSIP(String tradingsymbol, String frequency, int installmentDay, int instalments, int initialAmount, double amount) throws KiteException, IOException, JSONException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("tradingsymbol", tradingsymbol);
params.put("frequency", frequency);
params.put("instalment_day", installmentDay);
params.put("instalments", instalments);
params.put("initial_amount", initialAmount);
params.put("amount", amount);
MFSIP MFSIP = new MFSIP();
JSONObject response = new KiteRequestHandler(proxy).postRequest(routes.get("mutualfunds.sips.place"),params, apiKey, accessToken);
MFSIP.orderId = response.getJSONObject("data").getString("order_id");
MFSIP.sipId = response.getJSONObject("data").getString("sip_id");
return MFSIP;
} | [
"public",
"MFSIP",
"placeMFSIP",
"(",
"String",
"tradingsymbol",
",",
"String",
"frequency",
",",
"int",
"installmentDay",
",",
"int",
"instalments",
",",
"int",
"initialAmount",
",",
"double",
"amount",
")",
"throws",
"KiteException",
",",
"IOException",
",",
"... | Place a mutualfunds sip.
@param tradingsymbol Tradingsymbol (ISIN) of the fund.
@param frequency weekly, monthly, or quarterly.
@param amount Amount worth of units to purchase. It should be equal to or greated than minimum_additional_purchase_amount and in multiple of purchase_amount_multiplier in the instrument master.
@param installmentDay If Frequency is monthly, the day of the month (1, 5, 10, 15, 20, 25) to trigger the order on.
@param instalments Number of instalments to trigger. If set to -1, instalments are triggered at fixed intervals until the SIP is cancelled.
@param initialAmount Amount worth of units to purchase before the SIP starts. Should be equal to or greater than minimum_purchase_amount and in multiple of purchase_amount_multiplier. This is only considered if there have been no prior investments in the target fund.
@return MFSIP object which contains sip id and order id.
@throws KiteException is thrown for all Kite trade related errors.
@throws IOException is thrown when there is connection related error. | [
"Place",
"a",
"mutualfunds",
"sip",
"."
] | train | https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/kiteconnect/KiteConnect.java#L686-L700 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java | IOGroovyMethods.withReader | public static <T> T withReader(InputStream in, @ClosureParams(value=SimpleType.class, options="java.io.Reader") Closure<T> closure) throws IOException {
return withReader(new InputStreamReader(in), closure);
} | java | public static <T> T withReader(InputStream in, @ClosureParams(value=SimpleType.class, options="java.io.Reader") Closure<T> closure) throws IOException {
return withReader(new InputStreamReader(in), closure);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"withReader",
"(",
"InputStream",
"in",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"SimpleType",
".",
"class",
",",
"options",
"=",
"\"java.io.Reader\"",
")",
"Closure",
"<",
"T",
">",
"closure",
")",
"throws",
... | Helper method to create a new Reader for a stream and then
passes it into the closure. The reader (and this stream) is closed after
the closure returns.
@param in a stream
@param closure the closure to invoke with the InputStream
@return the value returned by the closure
@throws IOException if an IOException occurs.
@see java.io.InputStreamReader
@since 1.5.2 | [
"Helper",
"method",
"to",
"create",
"a",
"new",
"Reader",
"for",
"a",
"stream",
"and",
"then",
"passes",
"it",
"into",
"the",
"closure",
".",
"The",
"reader",
"(",
"and",
"this",
"stream",
")",
"is",
"closed",
"after",
"the",
"closure",
"returns",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1209-L1211 |
cogroo/cogroo4 | lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/WizardDialog.java | WizardDialog.insertRoadmapItem | public void insertRoadmapItem(int Index, boolean _bEnabled, String _sLabel, int _ID) {
try {
// a roadmap is a SingleServiceFactory that can only create roadmapitems that are the only possible
// element types of the container
Object oRoadmapItem = m_xSSFRoadmap.createInstance();
XPropertySet xRMItemPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem);
xRMItemPSet.setPropertyValue("Label", _sLabel);
// sometimes steps are supposed to be set disabled depending on the program logic...
xRMItemPSet.setPropertyValue("Enabled", new Boolean(_bEnabled));
// in this context the "ID" is meant to refer to a step of the dialog
xRMItemPSet.setPropertyValue("ID", new Integer(_ID));
m_xRMIndexCont.insertByIndex(Index, oRoadmapItem);
} catch (com.sun.star.uno.Exception exception) {
exception.printStackTrace(System.out);
}
} | java | public void insertRoadmapItem(int Index, boolean _bEnabled, String _sLabel, int _ID) {
try {
// a roadmap is a SingleServiceFactory that can only create roadmapitems that are the only possible
// element types of the container
Object oRoadmapItem = m_xSSFRoadmap.createInstance();
XPropertySet xRMItemPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem);
xRMItemPSet.setPropertyValue("Label", _sLabel);
// sometimes steps are supposed to be set disabled depending on the program logic...
xRMItemPSet.setPropertyValue("Enabled", new Boolean(_bEnabled));
// in this context the "ID" is meant to refer to a step of the dialog
xRMItemPSet.setPropertyValue("ID", new Integer(_ID));
m_xRMIndexCont.insertByIndex(Index, oRoadmapItem);
} catch (com.sun.star.uno.Exception exception) {
exception.printStackTrace(System.out);
}
} | [
"public",
"void",
"insertRoadmapItem",
"(",
"int",
"Index",
",",
"boolean",
"_bEnabled",
",",
"String",
"_sLabel",
",",
"int",
"_ID",
")",
"{",
"try",
"{",
"// a roadmap is a SingleServiceFactory that can only create roadmapitems that are the only possible",
"// element types... | To fully understand the example one has to be aware that the passed ???Index??? parameter
refers to the position of the roadmap item in the roadmapmodel container
whereas the variable ???_ID??? directyl references to a certain step of dialog. | [
"To",
"fully",
"understand",
"the",
"example",
"one",
"has",
"to",
"be",
"aware",
"that",
"the",
"passed",
"???Index???",
"parameter",
"refers",
"to",
"the",
"position",
"of",
"the",
"roadmap",
"item",
"in",
"the",
"roadmapmodel",
"container",
"whereas",
"the"... | train | https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/WizardDialog.java#L1489-L1504 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/IssuesApi.java | IssuesApi.closeIssue | public Issue closeIssue(Object projectIdOrPath, Integer issueIid) throws GitLabApiException {
if (issueIid == null) {
throw new RuntimeException("issue IID cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("state_event", StateEvent.CLOSE);
Response response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid);
return (response.readEntity(Issue.class));
} | java | public Issue closeIssue(Object projectIdOrPath, Integer issueIid) throws GitLabApiException {
if (issueIid == null) {
throw new RuntimeException("issue IID cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("state_event", StateEvent.CLOSE);
Response response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "issues", issueIid);
return (response.readEntity(Issue.class));
} | [
"public",
"Issue",
"closeIssue",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"issueIid",
")",
"throws",
"GitLabApiException",
"{",
"if",
"(",
"issueIid",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"issue IID cannot be null\"",
")",
";... | Closes an existing project issue.
<pre><code>GitLab Endpoint: PUT /projects/:id/issues/:issue_iid</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required
@param issueIid the issue IID to update, required
@return an instance of the updated Issue
@throws GitLabApiException if any exception occurs | [
"Closes",
"an",
"existing",
"project",
"issue",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/IssuesApi.java#L380-L389 |
moparisthebest/beehive | beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlImpl.java | JdbcControlImpl.onRelease | @EventHandler(field = "_resourceContext", eventSet = ResourceContext.ResourceEvents.class, eventName = "onRelease")
public void onRelease() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Enter: onRelease()");
}
for (PreparedStatement ps : getResources()) {
try {
ps.close();
} catch (SQLException sqe) {
}
}
getResources().clear();
if (_connection != null) {
try {
_connection.close();
} catch (SQLException e) {
throw new ControlException("SQL Exception while attempting to close database connection.", e);
}
}
_connection = null;
_connectionDataSource = null;
_connectionDriver = null;
} | java | @EventHandler(field = "_resourceContext", eventSet = ResourceContext.ResourceEvents.class, eventName = "onRelease")
public void onRelease() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Enter: onRelease()");
}
for (PreparedStatement ps : getResources()) {
try {
ps.close();
} catch (SQLException sqe) {
}
}
getResources().clear();
if (_connection != null) {
try {
_connection.close();
} catch (SQLException e) {
throw new ControlException("SQL Exception while attempting to close database connection.", e);
}
}
_connection = null;
_connectionDataSource = null;
_connectionDriver = null;
} | [
"@",
"EventHandler",
"(",
"field",
"=",
"\"_resourceContext\"",
",",
"eventSet",
"=",
"ResourceContext",
".",
"ResourceEvents",
".",
"class",
",",
"eventName",
"=",
"\"onRelease\"",
")",
"public",
"void",
"onRelease",
"(",
")",
"{",
"if",
"(",
"LOGGER",
".",
... | Invoked by the controls runtime when an instance of this class is released by the runtime | [
"Invoked",
"by",
"the",
"controls",
"runtime",
"when",
"an",
"instance",
"of",
"this",
"class",
"is",
"released",
"by",
"the",
"runtime"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/JdbcControlImpl.java#L120-L146 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java | SameDiff.setGradientForVariableName | public void setGradientForVariableName(String variableName, SDVariable variable) {
Preconditions.checkState(variables.containsKey(variableName), "No variable exists with name \"%s\"", variableName);
if (variable == null) {
throw new ND4JIllegalStateException("Unable to set null gradient for variable name " + variableName);
}
variables.get(variableName).setGradient(variable);
} | java | public void setGradientForVariableName(String variableName, SDVariable variable) {
Preconditions.checkState(variables.containsKey(variableName), "No variable exists with name \"%s\"", variableName);
if (variable == null) {
throw new ND4JIllegalStateException("Unable to set null gradient for variable name " + variableName);
}
variables.get(variableName).setGradient(variable);
} | [
"public",
"void",
"setGradientForVariableName",
"(",
"String",
"variableName",
",",
"SDVariable",
"variable",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"variables",
".",
"containsKey",
"(",
"variableName",
")",
",",
"\"No variable exists with name \\\"%s\\\"\"",
... | Assign a SDVariable to represent the gradient of the SDVariable with the specified name
@param variableName the variable name to assign the gradient variable for
@param variable the gradient variable | [
"Assign",
"a",
"SDVariable",
"to",
"represent",
"the",
"gradient",
"of",
"the",
"SDVariable",
"with",
"the",
"specified",
"name"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L2640-L2646 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/core/Parser.java | Parser.parseWithKeyword | public static boolean parseWithKeyword(final char[] query, int offset) {
if (query.length < (offset + 4)) {
return false;
}
return (query[offset] | 32) == 'w'
&& (query[offset + 1] | 32) == 'i'
&& (query[offset + 2] | 32) == 't'
&& (query[offset + 3] | 32) == 'h';
} | java | public static boolean parseWithKeyword(final char[] query, int offset) {
if (query.length < (offset + 4)) {
return false;
}
return (query[offset] | 32) == 'w'
&& (query[offset + 1] | 32) == 'i'
&& (query[offset + 2] | 32) == 't'
&& (query[offset + 3] | 32) == 'h';
} | [
"public",
"static",
"boolean",
"parseWithKeyword",
"(",
"final",
"char",
"[",
"]",
"query",
",",
"int",
"offset",
")",
"{",
"if",
"(",
"query",
".",
"length",
"<",
"(",
"offset",
"+",
"4",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
... | Parse string to check presence of WITH keyword regardless of case.
@param query char[] of the query statement
@param offset position of query to start checking
@return boolean indicates presence of word | [
"Parse",
"string",
"to",
"check",
"presence",
"of",
"WITH",
"keyword",
"regardless",
"of",
"case",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L723-L732 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/Compiler.java | Compiler.locationPathPattern | public Expression locationPathPattern(int opPos)
throws TransformerException
{
opPos = getFirstChildPos(opPos);
return stepPattern(opPos, 0, null);
} | java | public Expression locationPathPattern(int opPos)
throws TransformerException
{
opPos = getFirstChildPos(opPos);
return stepPattern(opPos, 0, null);
} | [
"public",
"Expression",
"locationPathPattern",
"(",
"int",
"opPos",
")",
"throws",
"TransformerException",
"{",
"opPos",
"=",
"getFirstChildPos",
"(",
"opPos",
")",
";",
"return",
"stepPattern",
"(",
"opPos",
",",
"0",
",",
"null",
")",
";",
"}"
] | Compile a location match pattern unit expression.
@param opPos The current position in the m_opMap array.
@return reference to {@link org.apache.xpath.patterns.StepPattern} instance.
@throws TransformerException if a error occurs creating the Expression. | [
"Compile",
"a",
"location",
"match",
"pattern",
"unit",
"expression",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/Compiler.java#L724-L731 |
lightblueseas/swing-components | src/main/java/de/alpharogroup/swing/renderer/TableCellButtonRendererFactory.java | TableCellButtonRendererFactory.newTableCellButtonRenderer | public static TableCellButtonRenderer newTableCellButtonRenderer(String text)
{
return new TableCellButtonRenderer(null, null)
{
private static final long serialVersionUID = 1L;
@Override
protected String onSetText(final Object value)
{
String currentText = text;
return currentText;
}
};
} | java | public static TableCellButtonRenderer newTableCellButtonRenderer(String text)
{
return new TableCellButtonRenderer(null, null)
{
private static final long serialVersionUID = 1L;
@Override
protected String onSetText(final Object value)
{
String currentText = text;
return currentText;
}
};
} | [
"public",
"static",
"TableCellButtonRenderer",
"newTableCellButtonRenderer",
"(",
"String",
"text",
")",
"{",
"return",
"new",
"TableCellButtonRenderer",
"(",
"null",
",",
"null",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
... | Factory method for creating the new {@link TableCellButtonRenderer} with the given string
@param text
the text
@return the new {@link TableCellButtonRenderer} | [
"Factory",
"method",
"for",
"creating",
"the",
"new",
"{",
"@link",
"TableCellButtonRenderer",
"}",
"with",
"the",
"given",
"string"
] | train | https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/renderer/TableCellButtonRendererFactory.java#L40-L53 |
lionsoul2014/jcseg | jcseg-core/src/main/java/org/lionsoul/jcseg/tokenizer/NLPSeg.java | NLPSeg.getNumericUnitComposedWord | private IWord getNumericUnitComposedWord(String numeric, IWord unitWord)
{
IStringBuffer sb = new IStringBuffer();
sb.clear().append(numeric).append(unitWord.getValue());
IWord wd = new Word(sb.toString(), IWord.T_CJK_WORD);
String[] entity = unitWord.getEntity();
int eIdx = ArrayUtil.startsWith(Entity.E_TIME_P, entity);
if ( eIdx > -1 ) {
sb.clear().append(entity[eIdx].replace("time.", "datetime."));
} else {
sb.clear().append(Entity.E_NUC_PREFIX ).append(unitWord.getEntity(0));
}
wd.setEntity(new String[] {sb.toString()});
wd.setPartSpeech(IWord.QUANTIFIER);
sb.clear();sb = null;
return wd;
} | java | private IWord getNumericUnitComposedWord(String numeric, IWord unitWord)
{
IStringBuffer sb = new IStringBuffer();
sb.clear().append(numeric).append(unitWord.getValue());
IWord wd = new Word(sb.toString(), IWord.T_CJK_WORD);
String[] entity = unitWord.getEntity();
int eIdx = ArrayUtil.startsWith(Entity.E_TIME_P, entity);
if ( eIdx > -1 ) {
sb.clear().append(entity[eIdx].replace("time.", "datetime."));
} else {
sb.clear().append(Entity.E_NUC_PREFIX ).append(unitWord.getEntity(0));
}
wd.setEntity(new String[] {sb.toString()});
wd.setPartSpeech(IWord.QUANTIFIER);
sb.clear();sb = null;
return wd;
} | [
"private",
"IWord",
"getNumericUnitComposedWord",
"(",
"String",
"numeric",
",",
"IWord",
"unitWord",
")",
"{",
"IStringBuffer",
"sb",
"=",
"new",
"IStringBuffer",
"(",
")",
";",
"sb",
".",
"clear",
"(",
")",
".",
"append",
"(",
"numeric",
")",
".",
"appen... | internal method to define the composed entity
for numeric and unit word composed word
@param numeric
@param unitWord
@return IWord | [
"internal",
"method",
"to",
"define",
"the",
"composed",
"entity",
"for",
"numeric",
"and",
"unit",
"word",
"composed",
"word"
] | train | https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/tokenizer/NLPSeg.java#L398-L417 |
Wolfgang-Schuetzelhofer/jcypher | src/main/java/iot/jcypher/database/DBAccessFactory.java | DBAccessFactory.createDBAccess | public static IDBAccess createDBAccess(DBType dbType, Properties properties,
String userId, String password) {
return createDBAccess(dbType, properties, userId, password, null);
} | java | public static IDBAccess createDBAccess(DBType dbType, Properties properties,
String userId, String password) {
return createDBAccess(dbType, properties, userId, password, null);
} | [
"public",
"static",
"IDBAccess",
"createDBAccess",
"(",
"DBType",
"dbType",
",",
"Properties",
"properties",
",",
"String",
"userId",
",",
"String",
"password",
")",
"{",
"return",
"createDBAccess",
"(",
"dbType",
",",
"properties",
",",
"userId",
",",
"password... | create an IDBAccess (an accessor) for a specific database,
supports authentication.
@param dbType the type of database to access. Can be
<br/>DBType.REMOTE or DBType.EMBEDDED or DBType.IN_MEMORY
@param properties to configure the database connection.
<br/>The appropriate database access class will pick the properties it needs.
<br/>See also: DBProperties interface for required and optional properties.
@param userId
@param password
@return an instance of IDBAccess | [
"create",
"an",
"IDBAccess",
"(",
"an",
"accessor",
")",
"for",
"a",
"specific",
"database",
"supports",
"authentication",
"."
] | train | https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/database/DBAccessFactory.java#L77-L80 |
census-instrumentation/opencensus-java | contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java | DropWizardMetrics.collectCounter | private Metric collectCounter(MetricName dropwizardMetric, Counter counter) {
String metricName =
DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "counter");
String metricDescription =
DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), counter);
AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
DropWizardUtils.generateLabels(dropwizardMetric);
MetricDescriptor metricDescriptor =
MetricDescriptor.create(
metricName, metricDescription, DEFAULT_UNIT, Type.GAUGE_INT64, labels.getKey());
TimeSeries timeSeries =
TimeSeries.createWithOnePoint(
labels.getValue(),
Point.create(Value.longValue(counter.getCount()), clock.now()),
null);
return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
} | java | private Metric collectCounter(MetricName dropwizardMetric, Counter counter) {
String metricName =
DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "counter");
String metricDescription =
DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), counter);
AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
DropWizardUtils.generateLabels(dropwizardMetric);
MetricDescriptor metricDescriptor =
MetricDescriptor.create(
metricName, metricDescription, DEFAULT_UNIT, Type.GAUGE_INT64, labels.getKey());
TimeSeries timeSeries =
TimeSeries.createWithOnePoint(
labels.getValue(),
Point.create(Value.longValue(counter.getCount()), clock.now()),
null);
return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
} | [
"private",
"Metric",
"collectCounter",
"(",
"MetricName",
"dropwizardMetric",
",",
"Counter",
"counter",
")",
"{",
"String",
"metricName",
"=",
"DropWizardUtils",
".",
"generateFullMetricName",
"(",
"dropwizardMetric",
".",
"getKey",
"(",
")",
",",
"\"counter\"",
")... | Returns a {@code Metric} collected from {@link Counter}.
@param dropwizardMetric the metric name.
@param counter the counter object to collect.
@return a {@code Metric}. | [
"Returns",
"a",
"{",
"@code",
"Metric",
"}",
"collected",
"from",
"{",
"@link",
"Counter",
"}",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java#L143-L162 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java | ContinuousDistributions.dirichletPdf | public static double dirichletPdf(double[] pi, double[] ai) {
double probability=1.0;
double sumAi=0.0;
double productGammaAi=1.0;
double tmp;
int piLength=pi.length;
for(int i=0;i<piLength;++i) {
tmp=ai[i];
sumAi+= tmp;
productGammaAi*=gamma(tmp);
probability*=Math.pow(pi[i], tmp-1);
}
probability*=gamma(sumAi)/productGammaAi;
return probability;
} | java | public static double dirichletPdf(double[] pi, double[] ai) {
double probability=1.0;
double sumAi=0.0;
double productGammaAi=1.0;
double tmp;
int piLength=pi.length;
for(int i=0;i<piLength;++i) {
tmp=ai[i];
sumAi+= tmp;
productGammaAi*=gamma(tmp);
probability*=Math.pow(pi[i], tmp-1);
}
probability*=gamma(sumAi)/productGammaAi;
return probability;
} | [
"public",
"static",
"double",
"dirichletPdf",
"(",
"double",
"[",
"]",
"pi",
",",
"double",
"[",
"]",
"ai",
")",
"{",
"double",
"probability",
"=",
"1.0",
";",
"double",
"sumAi",
"=",
"0.0",
";",
"double",
"productGammaAi",
"=",
"1.0",
";",
"double",
"... | Calculates probability pi, ai under dirichlet distribution
@param pi The vector with probabilities.
@param ai The vector with pseudocounts.
@return The probability | [
"Calculates",
"probability",
"pi",
"ai",
"under",
"dirichlet",
"distribution"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java#L593-L610 |
Cornutum/tcases | tcases-openapi/src/main/java/org/cornutum/tcases/openapi/reader/OpenApiReaderException.java | OpenApiReaderException.errorReasonFor | private static String errorReasonFor( URL location, List<String> errors)
{
return
Stream.concat(
Stream.of( String.format( "%s conformance problem(s) found in Open API document%s", errors.size(), locationId( location))),
IntStream.range( 0, errors.size()).mapToObj( i -> String.format( "[%s] %s", i, errors.get(i))))
.collect( joining( "\n"));
} | java | private static String errorReasonFor( URL location, List<String> errors)
{
return
Stream.concat(
Stream.of( String.format( "%s conformance problem(s) found in Open API document%s", errors.size(), locationId( location))),
IntStream.range( 0, errors.size()).mapToObj( i -> String.format( "[%s] %s", i, errors.get(i))))
.collect( joining( "\n"));
} | [
"private",
"static",
"String",
"errorReasonFor",
"(",
"URL",
"location",
",",
"List",
"<",
"String",
">",
"errors",
")",
"{",
"return",
"Stream",
".",
"concat",
"(",
"Stream",
".",
"of",
"(",
"String",
".",
"format",
"(",
"\"%s conformance problem(s) found in ... | Returns a reason for the errors in the document at the given location. | [
"Returns",
"a",
"reason",
"for",
"the",
"errors",
"in",
"the",
"document",
"at",
"the",
"given",
"location",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-openapi/src/main/java/org/cornutum/tcases/openapi/reader/OpenApiReaderException.java#L62-L69 |
ops4j/org.ops4j.base | ops4j-base-lang/src/main/java/org/ops4j/lang/NullArgumentException.java | NullArgumentException.validateNotEmpty | public static void validateNotEmpty( String stringToCheck, String argumentName )
throws NullArgumentException
{
validateNotEmpty( stringToCheck, false, argumentName );
} | java | public static void validateNotEmpty( String stringToCheck, String argumentName )
throws NullArgumentException
{
validateNotEmpty( stringToCheck, false, argumentName );
} | [
"public",
"static",
"void",
"validateNotEmpty",
"(",
"String",
"stringToCheck",
",",
"String",
"argumentName",
")",
"throws",
"NullArgumentException",
"{",
"validateNotEmpty",
"(",
"stringToCheck",
",",
"false",
",",
"argumentName",
")",
";",
"}"
] | Validates that the string is not null and not an empty string without trimming the string.
@param stringToCheck The object to be tested.
@param argumentName The name of the object, which is used to construct the exception message.
@throws NullArgumentException if the stringToCheck is either null or zero characters long. | [
"Validates",
"that",
"the",
"string",
"is",
"not",
"null",
"and",
"not",
"an",
"empty",
"string",
"without",
"trimming",
"the",
"string",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-lang/src/main/java/org/ops4j/lang/NullArgumentException.java#L87-L91 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/FlowLayoutExample.java | FlowLayoutExample.addBoxesWithDiffContent | private static void addBoxesWithDiffContent(final WPanel panel, final int amount) {
for (int i = 1; i <= amount; i++) {
WPanel content = new WPanel(WPanel.Type.BOX);
content.setLayout(new FlowLayout(FlowLayout.VERTICAL, 3));
for (int j = 1; j <= i; j++) {
content.add(new WText(Integer.toString(i)));
}
panel.add(content);
}
} | java | private static void addBoxesWithDiffContent(final WPanel panel, final int amount) {
for (int i = 1; i <= amount; i++) {
WPanel content = new WPanel(WPanel.Type.BOX);
content.setLayout(new FlowLayout(FlowLayout.VERTICAL, 3));
for (int j = 1; j <= i; j++) {
content.add(new WText(Integer.toString(i)));
}
panel.add(content);
}
} | [
"private",
"static",
"void",
"addBoxesWithDiffContent",
"(",
"final",
"WPanel",
"panel",
",",
"final",
"int",
"amount",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<=",
"amount",
";",
"i",
"++",
")",
"{",
"WPanel",
"content",
"=",
"new",
"... | Adds a set of boxes to the given panel.
@param panel the panel to add the boxes to.
@param amount the number of boxes to add. | [
"Adds",
"a",
"set",
"of",
"boxes",
"to",
"the",
"given",
"panel",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/FlowLayoutExample.java#L191-L200 |
skyscreamer/JSONassert | src/main/java/org/skyscreamer/jsonassert/JSONAssert.java | JSONAssert.assertEquals | public static void assertEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
if (expectedStr==actualStr) return;
if (expectedStr==null){
throw new AssertionError("Expected string is null.");
}else if (actualStr==null){
throw new AssertionError("Actual string is null.");
}
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.failed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
} | java | public static void assertEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
if (expectedStr==actualStr) return;
if (expectedStr==null){
throw new AssertionError("Expected string is null.");
}else if (actualStr==null){
throw new AssertionError("Actual string is null.");
}
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.failed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
} | [
"public",
"static",
"void",
"assertEquals",
"(",
"String",
"message",
",",
"String",
"expectedStr",
",",
"String",
"actualStr",
",",
"JSONCompareMode",
"compareMode",
")",
"throws",
"JSONException",
"{",
"if",
"(",
"expectedStr",
"==",
"actualStr",
")",
"return",
... | Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
{@link AssertionError}.
@param message Error message to be displayed in case of assertion failure
@param expectedStr Expected JSON string
@param actualStr String to compare
@param compareMode Specifies which comparison mode to use
@throws JSONException JSON parsing error | [
"Asserts",
"that",
"the",
"JSONArray",
"provided",
"matches",
"the",
"expected",
"string",
".",
"If",
"it",
"isn",
"t",
"it",
"throws",
"an",
"{",
"@link",
"AssertionError",
"}",
"."
] | train | https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L407-L419 |
tempodb/tempodb-java | src/main/java/com/tempodb/Client.java | Client.readDataPoints | public Cursor<DataPoint> readDataPoints(Filter filter, Interval interval, DateTimeZone timezone, Aggregation aggregation, Rollup rollup, Interpolation interpolation) {
checkNotNull(filter);
checkNotNull(interval);
checkNotNull(aggregation);
checkNotNull(timezone);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/segment/", API_VERSION));
addFilterToURI(builder, filter);
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addAggregationToURI(builder, aggregation);
addRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: filter: %s, interval: %s, aggregation: %s, rollup: %s, timezone: %s", filter, interval, aggregation, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<DataPoint> cursor = new DataPointCursor(uri, this);
return cursor;
} | java | public Cursor<DataPoint> readDataPoints(Filter filter, Interval interval, DateTimeZone timezone, Aggregation aggregation, Rollup rollup, Interpolation interpolation) {
checkNotNull(filter);
checkNotNull(interval);
checkNotNull(aggregation);
checkNotNull(timezone);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/segment/", API_VERSION));
addFilterToURI(builder, filter);
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addAggregationToURI(builder, aggregation);
addRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: filter: %s, interval: %s, aggregation: %s, rollup: %s, timezone: %s", filter, interval, aggregation, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<DataPoint> cursor = new DataPointCursor(uri, this);
return cursor;
} | [
"public",
"Cursor",
"<",
"DataPoint",
">",
"readDataPoints",
"(",
"Filter",
"filter",
",",
"Interval",
"interval",
",",
"DateTimeZone",
"timezone",
",",
"Aggregation",
"aggregation",
",",
"Rollup",
"rollup",
",",
"Interpolation",
"interpolation",
")",
"{",
"checkN... | Returns a cursor of datapoints specified by a series filter.
This endpoint allows one to request multiple series and apply an aggregation function.
@param filter The series filter
@param interval An interval of time for the query (start/end datetimes)
@param timezone The time zone for the returned datapoints.
@param aggregation The aggregation for the read query. This is required.
@param rollup The rollup for the read query. This can be null.
@param interpolation The interpolation for the read query. This can be null.
@return A Cursor of DataPoints. The cursor.iterator().next() may throw a {@link TempoDBException} if an error occurs while making a request.
@see Aggregation
@see Cursor
@see Filter
@see Interpolation
@see Rollup
@since 1.0.0 | [
"Returns",
"a",
"cursor",
"of",
"datapoints",
"specified",
"by",
"a",
"series",
"filter",
"."
] | train | https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L830-L853 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java | TreeScanner.visitCase | @Override
public R visitCase(CaseTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getStatements(), p, r);
return r;
} | java | @Override
public R visitCase(CaseTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getStatements(), p, r);
return r;
} | [
"@",
"Override",
"public",
"R",
"visitCase",
"(",
"CaseTree",
"node",
",",
"P",
"p",
")",
"{",
"R",
"r",
"=",
"scan",
"(",
"node",
".",
"getExpression",
"(",
")",
",",
"p",
")",
";",
"r",
"=",
"scanAndReduce",
"(",
"node",
".",
"getStatements",
"("... | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L343-L348 |
Azure/azure-sdk-for-java | resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/TagsInner.java | TagsInner.deleteValue | public void deleteValue(String tagName, String tagValue) {
deleteValueWithServiceResponseAsync(tagName, tagValue).toBlocking().single().body();
} | java | public void deleteValue(String tagName, String tagValue) {
deleteValueWithServiceResponseAsync(tagName, tagValue).toBlocking().single().body();
} | [
"public",
"void",
"deleteValue",
"(",
"String",
"tagName",
",",
"String",
"tagValue",
")",
"{",
"deleteValueWithServiceResponseAsync",
"(",
"tagName",
",",
"tagValue",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"... | Deletes a tag value.
@param tagName The name of the tag.
@param tagValue The value of the tag to delete.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Deletes",
"a",
"tag",
"value",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/TagsInner.java#L97-L99 |
LearnLib/automatalib | incremental/src/main/java/net/automatalib/incremental/mealy/dag/IncrementalMealyDAGBuilder.java | IncrementalMealyDAGBuilder.updateInitSignature | private void updateInitSignature(int idx, State<O> succ) {
StateSignature<O> sig = init.getSignature();
State<O> oldSucc = sig.successors.array[idx];
if (oldSucc == succ) {
return;
}
if (oldSucc != null) {
oldSucc.decreaseIncoming();
}
sig.successors.array[idx] = succ;
succ.increaseIncoming();
} | java | private void updateInitSignature(int idx, State<O> succ) {
StateSignature<O> sig = init.getSignature();
State<O> oldSucc = sig.successors.array[idx];
if (oldSucc == succ) {
return;
}
if (oldSucc != null) {
oldSucc.decreaseIncoming();
}
sig.successors.array[idx] = succ;
succ.increaseIncoming();
} | [
"private",
"void",
"updateInitSignature",
"(",
"int",
"idx",
",",
"State",
"<",
"O",
">",
"succ",
")",
"{",
"StateSignature",
"<",
"O",
">",
"sig",
"=",
"init",
".",
"getSignature",
"(",
")",
";",
"State",
"<",
"O",
">",
"oldSucc",
"=",
"sig",
".",
... | Update the signature of the initial state. This requires special handling, as the initial state is not stored in
the register (since it can never legally act as a predecessor).
@param idx
the transition index being changed
@param succ
the new successor state | [
"Update",
"the",
"signature",
"of",
"the",
"initial",
"state",
".",
"This",
"requires",
"special",
"handling",
"as",
"the",
"initial",
"state",
"is",
"not",
"stored",
"in",
"the",
"register",
"(",
"since",
"it",
"can",
"never",
"legally",
"act",
"as",
"a",... | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/incremental/src/main/java/net/automatalib/incremental/mealy/dag/IncrementalMealyDAGBuilder.java#L329-L340 |
couchbase/couchbase-lite-java | src/main/java/okhttp3/internal/tls/CustomHostnameVerifier.java | CustomHostnameVerifier.verifyHostname | private boolean verifyHostname(String hostname, X509Certificate certificate) {
hostname = hostname.toLowerCase(Locale.US);
boolean hasDns = false;
List<String> altNames = getSubjectAltNames(certificate, ALT_DNS_NAME);
for (int i = 0, size = altNames.size(); i < size; i++) {
hasDns = true;
if (verifyHostname(hostname, altNames.get(i))) {
return true;
}
}
if (!hasDns) {
X500Principal principal = certificate.getSubjectX500Principal();
// RFC 2818 advises using the most specific name for matching.
String cn = new DistinguishedNameParser(principal).findMostSpecific("cn");
if (cn != null) {
return verifyHostname(hostname, cn);
}
else {
// NOTE: In case of empty Common Name (CN), not checking
return true;
}
}
return false;
} | java | private boolean verifyHostname(String hostname, X509Certificate certificate) {
hostname = hostname.toLowerCase(Locale.US);
boolean hasDns = false;
List<String> altNames = getSubjectAltNames(certificate, ALT_DNS_NAME);
for (int i = 0, size = altNames.size(); i < size; i++) {
hasDns = true;
if (verifyHostname(hostname, altNames.get(i))) {
return true;
}
}
if (!hasDns) {
X500Principal principal = certificate.getSubjectX500Principal();
// RFC 2818 advises using the most specific name for matching.
String cn = new DistinguishedNameParser(principal).findMostSpecific("cn");
if (cn != null) {
return verifyHostname(hostname, cn);
}
else {
// NOTE: In case of empty Common Name (CN), not checking
return true;
}
}
return false;
} | [
"private",
"boolean",
"verifyHostname",
"(",
"String",
"hostname",
",",
"X509Certificate",
"certificate",
")",
"{",
"hostname",
"=",
"hostname",
".",
"toLowerCase",
"(",
"Locale",
".",
"US",
")",
";",
"boolean",
"hasDns",
"=",
"false",
";",
"List",
"<",
"Str... | Returns true if {@code certificate} matches {@code hostname}. | [
"Returns",
"true",
"if",
"{"
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/okhttp3/internal/tls/CustomHostnameVerifier.java#L95-L120 |
google/error-prone-javac | src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java | JavadocFormatter.formatJavadoc | public String formatJavadoc(String header, String javadoc) {
try {
StringBuilder result = new StringBuilder();
result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n");
if (javadoc == null) {
return result.toString();
}
JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null);
DocTrees trees = DocTrees.instance(task);
DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) {
@Override @DefinedBy(Api.COMPILER)
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return "<body>" + javadoc + "</body>";
}
});
new FormatJavadocScanner(result, task).scan(docComment, null);
addNewLineIfNeeded(result);
return result.toString();
} catch (URISyntaxException ex) {
throw new InternalError("Unexpected exception", ex);
}
} | java | public String formatJavadoc(String header, String javadoc) {
try {
StringBuilder result = new StringBuilder();
result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n");
if (javadoc == null) {
return result.toString();
}
JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null);
DocTrees trees = DocTrees.instance(task);
DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) {
@Override @DefinedBy(Api.COMPILER)
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return "<body>" + javadoc + "</body>";
}
});
new FormatJavadocScanner(result, task).scan(docComment, null);
addNewLineIfNeeded(result);
return result.toString();
} catch (URISyntaxException ex) {
throw new InternalError("Unexpected exception", ex);
}
} | [
"public",
"String",
"formatJavadoc",
"(",
"String",
"header",
",",
"String",
"javadoc",
")",
"{",
"try",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"result",
".",
"append",
"(",
"escape",
"(",
"CODE_HIGHLIGHT",
")",
")",
".... | Format javadoc to plain text.
@param header element caption that should be used
@param javadoc to format
@return javadoc formatted to plain text | [
"Format",
"javadoc",
"to",
"plain",
"text",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java#L99-L126 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFolder.java | BoxApiFolder.getCreateRequest | public BoxRequestsFolder.CreateFolder getCreateRequest(String parentId, String name) {
BoxRequestsFolder.CreateFolder request = new BoxRequestsFolder.CreateFolder(parentId, name, getFoldersUrl(), mSession);
return request;
} | java | public BoxRequestsFolder.CreateFolder getCreateRequest(String parentId, String name) {
BoxRequestsFolder.CreateFolder request = new BoxRequestsFolder.CreateFolder(parentId, name, getFoldersUrl(), mSession);
return request;
} | [
"public",
"BoxRequestsFolder",
".",
"CreateFolder",
"getCreateRequest",
"(",
"String",
"parentId",
",",
"String",
"name",
")",
"{",
"BoxRequestsFolder",
".",
"CreateFolder",
"request",
"=",
"new",
"BoxRequestsFolder",
".",
"CreateFolder",
"(",
"parentId",
",",
"name... | Gets a request that creates a folder in a parent folder
@param parentId id of the parent folder to create the folder in
@param name name of the new folder
@return request to create a folder | [
"Gets",
"a",
"request",
"that",
"creates",
"a",
"folder",
"in",
"a",
"parent",
"folder"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFolder.java#L120-L123 |
ineunetOS/knife-commons | knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java | StringUtils.indexOfAnyBut | public static int indexOfAnyBut(String str, String searchChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
boolean chFound = searchChars.indexOf(ch) >= 0;
if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {
char ch2 = str.charAt(i + 1);
if (chFound && searchChars.indexOf(ch2) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
} | java | public static int indexOfAnyBut(String str, String searchChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
char ch = str.charAt(i);
boolean chFound = searchChars.indexOf(ch) >= 0;
if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {
char ch2 = str.charAt(i + 1);
if (chFound && searchChars.indexOf(ch2) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
} | [
"public",
"static",
"int",
"indexOfAnyBut",
"(",
"String",
"str",
",",
"String",
"searchChars",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"str",
")",
"||",
"isEmpty",
"(",
"searchChars",
")",
")",
"{",
"return",
"INDEX_NOT_FOUND",
";",
"}",
"int",
"strLen",
"... | <p>Search a String to find the first index of any
character not in the given set of characters.</p>
<p>A <code>null</code> String will return <code>-1</code>.
A <code>null</code> or empty search string will return <code>-1</code>.</p>
<pre>
StringUtils.indexOfAnyBut(null, *) = -1
StringUtils.indexOfAnyBut("", *) = -1
StringUtils.indexOfAnyBut(*, null) = -1
StringUtils.indexOfAnyBut(*, "") = -1
StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
StringUtils.indexOfAnyBut("zzabyycdxx", "") = -1
StringUtils.indexOfAnyBut("aba","ab") = -1
</pre>
@param str the String to check, may be null
@param searchChars the chars to search for, may be null
@return the index of any of the chars, -1 if no match or null input
@since 2.0 | [
"<p",
">",
"Search",
"a",
"String",
"to",
"find",
"the",
"first",
"index",
"of",
"any",
"character",
"not",
"in",
"the",
"given",
"set",
"of",
"characters",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java#L1520-L1540 |
skuzzle/semantic-version | src/it/java/de/skuzzle/semantic/VersionRegEx.java | VersionRegEx.min | public static VersionRegEx min(VersionRegEx v1, VersionRegEx v2) {
require(v1 != null, "v1 is null");
require(v2 != null, "v2 is null");
return compare(v1, v2, false) <= 0
? v1
: v2;
} | java | public static VersionRegEx min(VersionRegEx v1, VersionRegEx v2) {
require(v1 != null, "v1 is null");
require(v2 != null, "v2 is null");
return compare(v1, v2, false) <= 0
? v1
: v2;
} | [
"public",
"static",
"VersionRegEx",
"min",
"(",
"VersionRegEx",
"v1",
",",
"VersionRegEx",
"v2",
")",
"{",
"require",
"(",
"v1",
"!=",
"null",
",",
"\"v1 is null\"",
")",
";",
"require",
"(",
"v2",
"!=",
"null",
",",
"\"v2 is null\"",
")",
";",
"return",
... | Returns the lower of the two given versions by comparing them using their natural
ordering. If both versions are equal, then the first argument is returned.
@param v1 The first version.
@param v2 The second version.
@return The lower version.
@throws IllegalArgumentException If either argument is <code>null</code>.
@since 0.4.0 | [
"Returns",
"the",
"lower",
"of",
"the",
"two",
"given",
"versions",
"by",
"comparing",
"them",
"using",
"their",
"natural",
"ordering",
".",
"If",
"both",
"versions",
"are",
"equal",
"then",
"the",
"first",
"argument",
"is",
"returned",
"."
] | train | https://github.com/skuzzle/semantic-version/blob/2ddb66fb80244cd7f67c77ed5f8072d1132ad933/src/it/java/de/skuzzle/semantic/VersionRegEx.java#L246-L252 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/tiles/ImageUtils.java | ImageUtils.compressAndWriteImageToBytes | public static byte[] compressAndWriteImageToBytes(BufferedImage image,
String formatName, float quality) {
byte[] bytes = null;
Iterator<ImageWriter> writers = ImageIO
.getImageWritersByFormatName(formatName);
if (writers == null || !writers.hasNext()) {
throw new GeoPackageException(
"No Image Writer to compress format: " + formatName);
}
ImageWriter writer = writers.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(quality);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = null;
try {
ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), writeParam);
writer.dispose();
bytes = baos.toByteArray();
} catch (IOException e) {
throw new GeoPackageException(
"Failed to compress image to format: " + formatName
+ ", with quality: " + quality, e);
} finally {
closeQuietly(ios);
closeQuietly(baos);
}
return bytes;
} | java | public static byte[] compressAndWriteImageToBytes(BufferedImage image,
String formatName, float quality) {
byte[] bytes = null;
Iterator<ImageWriter> writers = ImageIO
.getImageWritersByFormatName(formatName);
if (writers == null || !writers.hasNext()) {
throw new GeoPackageException(
"No Image Writer to compress format: " + formatName);
}
ImageWriter writer = writers.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(quality);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = null;
try {
ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), writeParam);
writer.dispose();
bytes = baos.toByteArray();
} catch (IOException e) {
throw new GeoPackageException(
"Failed to compress image to format: " + formatName
+ ", with quality: " + quality, e);
} finally {
closeQuietly(ios);
closeQuietly(baos);
}
return bytes;
} | [
"public",
"static",
"byte",
"[",
"]",
"compressAndWriteImageToBytes",
"(",
"BufferedImage",
"image",
",",
"String",
"formatName",
",",
"float",
"quality",
")",
"{",
"byte",
"[",
"]",
"bytes",
"=",
"null",
";",
"Iterator",
"<",
"ImageWriter",
">",
"writers",
... | Compress and write the image to bytes in the provided format and quality
@param image
buffered image
@param formatName
image format name
@param quality
quality between 0.0 and 1.0
@return compressed image bytes
@since 1.1.2 | [
"Compress",
"and",
"write",
"the",
"image",
"to",
"bytes",
"in",
"the",
"provided",
"format",
"and",
"quality"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/tiles/ImageUtils.java#L200-L236 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/Util.java | Util.createHTTPCarbonMessage | public static HttpCarbonMessage createHTTPCarbonMessage(HttpMessage httpMessage, ChannelHandlerContext ctx) {
Listener contentListener = new DefaultListener(ctx);
return new HttpCarbonMessage(httpMessage, contentListener);
} | java | public static HttpCarbonMessage createHTTPCarbonMessage(HttpMessage httpMessage, ChannelHandlerContext ctx) {
Listener contentListener = new DefaultListener(ctx);
return new HttpCarbonMessage(httpMessage, contentListener);
} | [
"public",
"static",
"HttpCarbonMessage",
"createHTTPCarbonMessage",
"(",
"HttpMessage",
"httpMessage",
",",
"ChannelHandlerContext",
"ctx",
")",
"{",
"Listener",
"contentListener",
"=",
"new",
"DefaultListener",
"(",
"ctx",
")",
";",
"return",
"new",
"HttpCarbonMessage"... | Creates HTTP carbon message.
@param httpMessage HTTP message
@param ctx Channel handler context
@return HttpCarbonMessage | [
"Creates",
"HTTP",
"carbon",
"message",
"."
] | train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/common/Util.java#L672-L675 |
PistoiaHELM/HELM2NotationToolkit | src/main/java/org/helm/notation2/tools/BuilderMolecule.java | BuilderMolecule.buildMoleculefromCHEM | private static RgroupStructure buildMoleculefromCHEM(final String id, final List<Monomer> validMonomers) throws BuilderMoleculeException, ChemistryException {
LOG.info("Build molecule for chemical component");
/* a chemical molecule should only contain one monomer */
if (validMonomers.size() == 1) {
try {
Monomer monomer = validMonomers.get(0);
String input = getInput(monomer);
if (input != null) {
/* Build monomer + Rgroup information! */
List<Attachment> listAttachments = monomer.getAttachmentList();
AttachmentList list = new AttachmentList();
for (Attachment attachment : listAttachments) {
list.add(new org.helm.chemtoolkit.Attachment(attachment.getAlternateId(), attachment.getLabel(), attachment.getCapGroupName(), attachment.getCapGroupSMILES()));
}
AbstractMolecule molecule = Chemistry.getInstance().getManipulator().getMolecule(input, list);
RgroupStructure result = new RgroupStructure();
result.setMolecule(molecule);
result.setRgroupMap(generateRgroupMap(id + ":" + "1", molecule));
return result;
} else {
LOG.error("Chemical molecule should have canonical smiles");
throw new BuilderMoleculeException("Chemical molecule should have canoncial smiles");
}
} catch (NullPointerException ex) {
throw new BuilderMoleculeException("Monomer is not stored in the monomer database");
} catch (IOException | CTKException e) {
LOG.error("Molecule can't be built " + e.getMessage());
throw new BuilderMoleculeException("Molecule can't be built " + e.getMessage());
}
} else {
LOG.error("Chemical molecule should contain exactly one monomer");
throw new BuilderMoleculeException("Chemical molecule should contain exactly one monomer");
}
} | java | private static RgroupStructure buildMoleculefromCHEM(final String id, final List<Monomer> validMonomers) throws BuilderMoleculeException, ChemistryException {
LOG.info("Build molecule for chemical component");
/* a chemical molecule should only contain one monomer */
if (validMonomers.size() == 1) {
try {
Monomer monomer = validMonomers.get(0);
String input = getInput(monomer);
if (input != null) {
/* Build monomer + Rgroup information! */
List<Attachment> listAttachments = monomer.getAttachmentList();
AttachmentList list = new AttachmentList();
for (Attachment attachment : listAttachments) {
list.add(new org.helm.chemtoolkit.Attachment(attachment.getAlternateId(), attachment.getLabel(), attachment.getCapGroupName(), attachment.getCapGroupSMILES()));
}
AbstractMolecule molecule = Chemistry.getInstance().getManipulator().getMolecule(input, list);
RgroupStructure result = new RgroupStructure();
result.setMolecule(molecule);
result.setRgroupMap(generateRgroupMap(id + ":" + "1", molecule));
return result;
} else {
LOG.error("Chemical molecule should have canonical smiles");
throw new BuilderMoleculeException("Chemical molecule should have canoncial smiles");
}
} catch (NullPointerException ex) {
throw new BuilderMoleculeException("Monomer is not stored in the monomer database");
} catch (IOException | CTKException e) {
LOG.error("Molecule can't be built " + e.getMessage());
throw new BuilderMoleculeException("Molecule can't be built " + e.getMessage());
}
} else {
LOG.error("Chemical molecule should contain exactly one monomer");
throw new BuilderMoleculeException("Chemical molecule should contain exactly one monomer");
}
} | [
"private",
"static",
"RgroupStructure",
"buildMoleculefromCHEM",
"(",
"final",
"String",
"id",
",",
"final",
"List",
"<",
"Monomer",
">",
"validMonomers",
")",
"throws",
"BuilderMoleculeException",
",",
"ChemistryException",
"{",
"LOG",
".",
"info",
"(",
"\"Build mo... | method to build a molecule from a chemical component
@param validMonomers all valid monomers of the chemical component
@return Built Molecule
@throws BuilderMoleculeException if the polymer contains more than one
monomer or if the molecule can't be built
@throws ChemistryException if the Chemistry Engine can not be initialized | [
"method",
"to",
"build",
"a",
"molecule",
"from",
"a",
"chemical",
"component"
] | train | https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/BuilderMolecule.java#L261-L297 |
apache/fluo | modules/core/src/main/java/org/apache/fluo/core/util/CuratorUtil.java | CuratorUtil.startAppIdWatcher | public static NodeCache startAppIdWatcher(Environment env) {
try {
CuratorFramework curator = env.getSharedResources().getCurator();
byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);
if (uuidBytes == null) {
Halt.halt("Fluo Application UUID not found");
throw new RuntimeException(); // make findbugs happy
}
final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);
final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);
nodeCache.getListenable().addListener(() -> {
ChildData node = nodeCache.getCurrentData();
if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {
Halt.halt("Fluo Application UUID has changed or disappeared");
}
});
nodeCache.start();
return nodeCache;
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | public static NodeCache startAppIdWatcher(Environment env) {
try {
CuratorFramework curator = env.getSharedResources().getCurator();
byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);
if (uuidBytes == null) {
Halt.halt("Fluo Application UUID not found");
throw new RuntimeException(); // make findbugs happy
}
final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);
final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);
nodeCache.getListenable().addListener(() -> {
ChildData node = nodeCache.getCurrentData();
if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {
Halt.halt("Fluo Application UUID has changed or disappeared");
}
});
nodeCache.start();
return nodeCache;
} catch (Exception e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"NodeCache",
"startAppIdWatcher",
"(",
"Environment",
"env",
")",
"{",
"try",
"{",
"CuratorFramework",
"curator",
"=",
"env",
".",
"getSharedResources",
"(",
")",
".",
"getCurator",
"(",
")",
";",
"byte",
"[",
"]",
"uuidBytes",
"=",
"cura... | Start watching the fluo app uuid. If it changes or goes away then halt the process. | [
"Start",
"watching",
"the",
"fluo",
"app",
"uuid",
".",
"If",
"it",
"changes",
"or",
"goes",
"away",
"then",
"halt",
"the",
"process",
"."
] | train | https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/core/src/main/java/org/apache/fluo/core/util/CuratorUtil.java#L182-L206 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201902/reportservice/RunReachReport.java | RunReachReport.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws IOException, InterruptedException {
// Get the ReportService.
ReportServiceInterface reportService =
adManagerServices.get(session, ReportServiceInterface.class);
// Create report query.
ReportQuery reportQuery = new ReportQuery();
reportQuery.setDimensions(new Dimension[] {Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME});
reportQuery.setColumns(
new Column[] {Column.REACH_FREQUENCY, Column.REACH_AVERAGE_REVENUE, Column.REACH});
// Set the dynamic date range type or a custom start and end date that is
// the beginning of the week (Sunday) to the end of the week (Saturday), or
// the first of the month to the end of the month.
reportQuery.setDateRangeType(DateRangeType.REACH_LIFETIME);
// Create report job.
ReportJob reportJob = new ReportJob();
reportJob.setReportQuery(reportQuery);
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Create report downloader.
ReportDownloader reportDownloader = new ReportDownloader(reportService, reportJob.getId());
// Wait for the report to be ready.
reportDownloader.waitForReportReady();
// Change to your file location.
File file = File.createTempFile("reach-report-", ".csv.gz");
System.out.printf("Downloading report to %s ...", file.toString());
// Download the report.
ReportDownloadOptions options = new ReportDownloadOptions();
options.setExportFormat(ExportFormat.CSV_DUMP);
options.setUseGzipCompression(true);
URL url = reportDownloader.getDownloadUrl(options);
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
System.out.println("done.");
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws IOException, InterruptedException {
// Get the ReportService.
ReportServiceInterface reportService =
adManagerServices.get(session, ReportServiceInterface.class);
// Create report query.
ReportQuery reportQuery = new ReportQuery();
reportQuery.setDimensions(new Dimension[] {Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME});
reportQuery.setColumns(
new Column[] {Column.REACH_FREQUENCY, Column.REACH_AVERAGE_REVENUE, Column.REACH});
// Set the dynamic date range type or a custom start and end date that is
// the beginning of the week (Sunday) to the end of the week (Saturday), or
// the first of the month to the end of the month.
reportQuery.setDateRangeType(DateRangeType.REACH_LIFETIME);
// Create report job.
ReportJob reportJob = new ReportJob();
reportJob.setReportQuery(reportQuery);
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Create report downloader.
ReportDownloader reportDownloader = new ReportDownloader(reportService, reportJob.getId());
// Wait for the report to be ready.
reportDownloader.waitForReportReady();
// Change to your file location.
File file = File.createTempFile("reach-report-", ".csv.gz");
System.out.printf("Downloading report to %s ...", file.toString());
// Download the report.
ReportDownloadOptions options = new ReportDownloadOptions();
options.setExportFormat(ExportFormat.CSV_DUMP);
options.setUseGzipCompression(true);
URL url = reportDownloader.getDownloadUrl(options);
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
System.out.println("done.");
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"// Get the ReportService.",
"ReportServiceInterface",
"reportService",
"=",
"adManager... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
@throws IOException if unable to write the response to a file.
@throws InterruptedException if the thread is interrupted while waiting for the report to
complete. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201902/reportservice/RunReachReport.java#L64-L107 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.getAt | public static <T> List<T> getAt(T[] array, Range range) {
List<T> list = Arrays.asList(array);
return getAt(list, range);
} | java | public static <T> List<T> getAt(T[] array, Range range) {
List<T> list = Arrays.asList(array);
return getAt(list, range);
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"getAt",
"(",
"T",
"[",
"]",
"array",
",",
"Range",
"range",
")",
"{",
"List",
"<",
"T",
">",
"list",
"=",
"Arrays",
".",
"asList",
"(",
"array",
")",
";",
"return",
"getAt",
"(",
"list"... | Support the range subscript operator for an Array
@param array an Array of Objects
@param range a Range
@return a range of a list from the range's from index up to but not
including the range's to value
@since 1.0 | [
"Support",
"the",
"range",
"subscript",
"operator",
"for",
"an",
"Array"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L7784-L7787 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/script/ProgressScripService.java | ProgressScripService.startStep | public void startStep(String translationKey, String message, Object... arguments)
{
this.progress.startStep(this, new Message(translationKey, message, arguments));
} | java | public void startStep(String translationKey, String message, Object... arguments)
{
this.progress.startStep(this, new Message(translationKey, message, arguments));
} | [
"public",
"void",
"startStep",
"(",
"String",
"translationKey",
",",
"String",
"message",
",",
"Object",
"...",
"arguments",
")",
"{",
"this",
".",
"progress",
".",
"startStep",
"(",
"this",
",",
"new",
"Message",
"(",
"translationKey",
",",
"message",
",",
... | Close current step if any and move to next one.
@param translationKey the key used to find the translation of the step message
@param message the default message associated to the step
@param arguments the arguments to insert in the step message | [
"Close",
"current",
"step",
"if",
"any",
"and",
"move",
"to",
"next",
"one",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/script/ProgressScripService.java#L96-L99 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataCore.java | CoverageDataCore.getFloatPixelValue | public float getFloatPixelValue(GriddedTile griddedTile, Double value) {
double pixel = 0;
if (value == null) {
if (griddedCoverage != null) {
pixel = griddedCoverage.getDataNull();
}
} else {
pixel = valueToPixelValue(griddedTile, value);
}
float pixelValue = (float) pixel;
return pixelValue;
} | java | public float getFloatPixelValue(GriddedTile griddedTile, Double value) {
double pixel = 0;
if (value == null) {
if (griddedCoverage != null) {
pixel = griddedCoverage.getDataNull();
}
} else {
pixel = valueToPixelValue(griddedTile, value);
}
float pixelValue = (float) pixel;
return pixelValue;
} | [
"public",
"float",
"getFloatPixelValue",
"(",
"GriddedTile",
"griddedTile",
",",
"Double",
"value",
")",
"{",
"double",
"pixel",
"=",
"0",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"if",
"(",
"griddedCoverage",
"!=",
"null",
")",
"{",
"pixel",
"="... | Get the pixel value of the coverage data value
@param griddedTile
gridded tile
@param value
coverage data value
@return pixel value | [
"Get",
"the",
"pixel",
"value",
"of",
"the",
"coverage",
"data",
"value"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataCore.java#L1666-L1680 |
protobufel/protobuf-el | protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java | RepeatedFieldBuilder.getMessage | private MType getMessage(final int index, final boolean forBuild) {
if (this.builders == null) {
// We don't have any builders -- return the current Message.
// This is the case where no builder was created, so we MUST have a
// Message.
return messages.get(index);
}
final SingleFieldBuilder<MType, BType, IType> builder = builders.get(index);
if (builder == null) {
// We don't have a builder -- return the current message.
// This is the case where no builder was created for the entry at index,
// so we MUST have a message.
return messages.get(index);
} else {
return forBuild ? builder.build() : builder.getMessage();
}
} | java | private MType getMessage(final int index, final boolean forBuild) {
if (this.builders == null) {
// We don't have any builders -- return the current Message.
// This is the case where no builder was created, so we MUST have a
// Message.
return messages.get(index);
}
final SingleFieldBuilder<MType, BType, IType> builder = builders.get(index);
if (builder == null) {
// We don't have a builder -- return the current message.
// This is the case where no builder was created for the entry at index,
// so we MUST have a message.
return messages.get(index);
} else {
return forBuild ? builder.build() : builder.getMessage();
}
} | [
"private",
"MType",
"getMessage",
"(",
"final",
"int",
"index",
",",
"final",
"boolean",
"forBuild",
")",
"{",
"if",
"(",
"this",
".",
"builders",
"==",
"null",
")",
"{",
"// We don't have any builders -- return the current Message.\r",
"// This is the case where no bui... | Get the message at the specified index. If the message is currently stored as a {@code Builder}
, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial} on it.
@param index the index of the message to get
@param forBuild this is being called for build so we want to make sure we
SingleFieldBuilder.build to send dirty invalidations
@return the message for the specified index | [
"Get",
"the",
"message",
"at",
"the",
"specified",
"index",
".",
"If",
"the",
"message",
"is",
"currently",
"stored",
"as",
"a",
"{",
"@code",
"Builder",
"}",
"it",
"is",
"converted",
"to",
"a",
"{",
"@code",
"Message",
"}",
"by",
"calling",
"{",
"@lin... | train | https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L215-L233 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java | Transforms.timesOneMinus | public static INDArray timesOneMinus(INDArray in, boolean copy){
return Nd4j.getExecutioner().exec(new TimesOneMinus(in, (copy ? in.ulike() : in)));
} | java | public static INDArray timesOneMinus(INDArray in, boolean copy){
return Nd4j.getExecutioner().exec(new TimesOneMinus(in, (copy ? in.ulike() : in)));
} | [
"public",
"static",
"INDArray",
"timesOneMinus",
"(",
"INDArray",
"in",
",",
"boolean",
"copy",
")",
"{",
"return",
"Nd4j",
".",
"getExecutioner",
"(",
")",
".",
"exec",
"(",
"new",
"TimesOneMinus",
"(",
"in",
",",
"(",
"copy",
"?",
"in",
".",
"ulike",
... | out = in * (1-in)
@param in Input array
@param copy If true: copy. False: apply in-place
@return | [
"out",
"=",
"in",
"*",
"(",
"1",
"-",
"in",
")"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/ops/transforms/Transforms.java#L520-L522 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/searchindex/CmsEditSearchIndexDialog.java | CmsEditSearchIndexDialog.getRebuildModeWidgetConfiguration | private List<CmsSelectWidgetOption> getRebuildModeWidgetConfiguration() {
List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>();
String rebuildMode = getSearchIndexIndex().getRebuildMode();
result.add(new CmsSelectWidgetOption("auto", "auto".equals(rebuildMode)));
result.add(new CmsSelectWidgetOption("manual", "manual".equals(rebuildMode)));
result.add(new CmsSelectWidgetOption("offline", "offline".equals(rebuildMode)));
return result;
} | java | private List<CmsSelectWidgetOption> getRebuildModeWidgetConfiguration() {
List<CmsSelectWidgetOption> result = new ArrayList<CmsSelectWidgetOption>();
String rebuildMode = getSearchIndexIndex().getRebuildMode();
result.add(new CmsSelectWidgetOption("auto", "auto".equals(rebuildMode)));
result.add(new CmsSelectWidgetOption("manual", "manual".equals(rebuildMode)));
result.add(new CmsSelectWidgetOption("offline", "offline".equals(rebuildMode)));
return result;
} | [
"private",
"List",
"<",
"CmsSelectWidgetOption",
">",
"getRebuildModeWidgetConfiguration",
"(",
")",
"{",
"List",
"<",
"CmsSelectWidgetOption",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"CmsSelectWidgetOption",
">",
"(",
")",
";",
"String",
"rebuildMode",
"=",
... | Returns the rebuild mode widget configuration.<p>
@return the rebuild mode widget configuration | [
"Returns",
"the",
"rebuild",
"mode",
"widget",
"configuration",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/searchindex/CmsEditSearchIndexDialog.java#L233-L241 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/repository/internal/AbstractCachedExtensionRepository.java | AbstractCachedExtensionRepository.removeCachedExtensionVersion | protected void removeCachedExtensionVersion(String feature, E extension)
{
// versions
List<E> extensionVersions = this.extensionsVersions.get(feature);
extensionVersions.remove(extension);
if (extensionVersions.isEmpty()) {
this.extensionsVersions.remove(feature);
}
} | java | protected void removeCachedExtensionVersion(String feature, E extension)
{
// versions
List<E> extensionVersions = this.extensionsVersions.get(feature);
extensionVersions.remove(extension);
if (extensionVersions.isEmpty()) {
this.extensionsVersions.remove(feature);
}
} | [
"protected",
"void",
"removeCachedExtensionVersion",
"(",
"String",
"feature",
",",
"E",
"extension",
")",
"{",
"// versions",
"List",
"<",
"E",
">",
"extensionVersions",
"=",
"this",
".",
"extensionsVersions",
".",
"get",
"(",
"feature",
")",
";",
"extensionVer... | Remove passed extension associated to passed feature from the cache.
@param feature the feature associated to the extension
@param extension the extension | [
"Remove",
"passed",
"extension",
"associated",
"to",
"passed",
"feature",
"from",
"the",
"cache",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/repository/internal/AbstractCachedExtensionRepository.java#L167-L175 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleAssetCategoryRelPersistenceImpl.java | CPRuleAssetCategoryRelPersistenceImpl.findByCPRuleId | @Override
public List<CPRuleAssetCategoryRel> findByCPRuleId(long CPRuleId,
int start, int end) {
return findByCPRuleId(CPRuleId, start, end, null);
} | java | @Override
public List<CPRuleAssetCategoryRel> findByCPRuleId(long CPRuleId,
int start, int end) {
return findByCPRuleId(CPRuleId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPRuleAssetCategoryRel",
">",
"findByCPRuleId",
"(",
"long",
"CPRuleId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCPRuleId",
"(",
"CPRuleId",
",",
"start",
",",
"end",
",",
"null",
")",
";"... | Returns a range of all the cp rule asset category rels where CPRuleId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPRuleAssetCategoryRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CPRuleId the cp rule ID
@param start the lower bound of the range of cp rule asset category rels
@param end the upper bound of the range of cp rule asset category rels (not inclusive)
@return the range of matching cp rule asset category rels | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"rule",
"asset",
"category",
"rels",
"where",
"CPRuleId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleAssetCategoryRelPersistenceImpl.java#L140-L144 |
moparisthebest/beehive | beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java | ControlBean.lookupControlBeanContextFactory | private ControlBeanContextFactory lookupControlBeanContextFactory
(org.apache.beehive.controls.api.context.ControlBeanContext context) {
// first, try to find the CBCFactory from the container
if(context != null) {
ControlBeanContextFactory cbcFactory = context.getService(ControlBeanContextFactory.class, null);
if(cbcFactory != null) {
return cbcFactory;
}
}
// Create the context that acts as the BeanContextProxy for this bean (the context that this bean _defines_).
try
{
DiscoverClass discoverer = new DiscoverClass();
Class factoryClass =
discoverer.find(ControlBeanContextFactory.class, DefaultControlBeanContextFactory.class.getName());
return (ControlBeanContextFactory)factoryClass.newInstance();
}
catch (Exception e) {
throw new ControlException("Exception creating ControlBeanContext", e);
}
} | java | private ControlBeanContextFactory lookupControlBeanContextFactory
(org.apache.beehive.controls.api.context.ControlBeanContext context) {
// first, try to find the CBCFactory from the container
if(context != null) {
ControlBeanContextFactory cbcFactory = context.getService(ControlBeanContextFactory.class, null);
if(cbcFactory != null) {
return cbcFactory;
}
}
// Create the context that acts as the BeanContextProxy for this bean (the context that this bean _defines_).
try
{
DiscoverClass discoverer = new DiscoverClass();
Class factoryClass =
discoverer.find(ControlBeanContextFactory.class, DefaultControlBeanContextFactory.class.getName());
return (ControlBeanContextFactory)factoryClass.newInstance();
}
catch (Exception e) {
throw new ControlException("Exception creating ControlBeanContext", e);
}
} | [
"private",
"ControlBeanContextFactory",
"lookupControlBeanContextFactory",
"(",
"org",
".",
"apache",
".",
"beehive",
".",
"controls",
".",
"api",
".",
"context",
".",
"ControlBeanContext",
"context",
")",
"{",
"// first, try to find the CBCFactory from the container",
"if"... | Internal method used to lookup a ControlBeanContextFactory. This factory is used to create the
ControlBeanContext object for this ControlBean. The factory is discoverable from either the containing
ControlBeanContext object or from the environment. If the containing CBC object exposes a
contextual service of type {@link ControlBeanContextFactory}, the factory returned from this will
be used to create a ControlBeanContext object.
@param context
@return the ControlBeanContextFactory discovered in the environment or a default one if no factory is configured | [
"Internal",
"method",
"used",
"to",
"lookup",
"a",
"ControlBeanContextFactory",
".",
"This",
"factory",
"is",
"used",
"to",
"create",
"the",
"ControlBeanContext",
"object",
"for",
"this",
"ControlBean",
".",
"The",
"factory",
"is",
"discoverable",
"from",
"either"... | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBean.java#L934-L958 |
nguillaumin/slick2d-maven | slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/DataSet.java | DataSet.toAngelCodeText | public void toAngelCodeText(PrintStream out, String imageName) {
out.println("info face=\""+fontName+"\" size="+size+" bold=0 italic=0 charset=\""+setName+"\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1");
out.println("common lineHeight="+lineHeight+" base=26 scaleW="+width+" scaleH="+height+" pages=1 packed=0");
out.println("page id=0 file=\""+imageName+"\"");
out.println("chars count="+chars.size());
for (int i=0;i<chars.size();i++) {
CharData c = (CharData) chars.get(i);
out.println("char id="+c.getID()+" x="+c.getX()+" y="+c.getY()+" width="+c.getWidth()+" height="+c.getHeight()+" xoffset=0 yoffset="+c.getYOffset()+" xadvance="+c.getXAdvance()+" page=0 chnl=0 ");
}
out.println("kernings count="+kerning.size());
for (int i=0;i<kerning.size();i++) {
KerningData k = (KerningData) kerning.get(i);
out.println("kerning first="+k.first+" second="+k.second+" amount="+k.offset);
}
} | java | public void toAngelCodeText(PrintStream out, String imageName) {
out.println("info face=\""+fontName+"\" size="+size+" bold=0 italic=0 charset=\""+setName+"\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1");
out.println("common lineHeight="+lineHeight+" base=26 scaleW="+width+" scaleH="+height+" pages=1 packed=0");
out.println("page id=0 file=\""+imageName+"\"");
out.println("chars count="+chars.size());
for (int i=0;i<chars.size();i++) {
CharData c = (CharData) chars.get(i);
out.println("char id="+c.getID()+" x="+c.getX()+" y="+c.getY()+" width="+c.getWidth()+" height="+c.getHeight()+" xoffset=0 yoffset="+c.getYOffset()+" xadvance="+c.getXAdvance()+" page=0 chnl=0 ");
}
out.println("kernings count="+kerning.size());
for (int i=0;i<kerning.size();i++) {
KerningData k = (KerningData) kerning.get(i);
out.println("kerning first="+k.first+" second="+k.second+" amount="+k.offset);
}
} | [
"public",
"void",
"toAngelCodeText",
"(",
"PrintStream",
"out",
",",
"String",
"imageName",
")",
"{",
"out",
".",
"println",
"(",
"\"info face=\\\"\"",
"+",
"fontName",
"+",
"\"\\\" size=\"",
"+",
"size",
"+",
"\" bold=0 italic=0 charset=\\\"\"",
"+",
"setName",
"... | Output this data set as an angel code data file
@param imageName The name of the image to reference
@param out The output stream to write to | [
"Output",
"this",
"data",
"set",
"as",
"an",
"angel",
"code",
"data",
"file"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/DataSet.java#L93-L108 |
elki-project/elki | elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java | DBIDUtil.randomShuffle | public static void randomShuffle(ArrayModifiableDBIDs ids, Random random) {
randomShuffle(ids, random, ids.size());
} | java | public static void randomShuffle(ArrayModifiableDBIDs ids, Random random) {
randomShuffle(ids, random, ids.size());
} | [
"public",
"static",
"void",
"randomShuffle",
"(",
"ArrayModifiableDBIDs",
"ids",
",",
"Random",
"random",
")",
"{",
"randomShuffle",
"(",
"ids",
",",
"random",
",",
"ids",
".",
"size",
"(",
")",
")",
";",
"}"
] | Produce a random shuffling of the given DBID array.
@param ids Original DBIDs, no duplicates allowed
@param random Random generator | [
"Produce",
"a",
"random",
"shuffling",
"of",
"the",
"given",
"DBID",
"array",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L520-L522 |
dwdyer/reportng | reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java | JUnitXMLReporter.generateReport | public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectoryName)
{
removeEmptyDirectories(new File(outputDirectoryName));
File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);
outputDirectory.mkdirs();
Collection<TestClassResults> flattenedResults = flattenResults(suites);
for (TestClassResults results : flattenedResults)
{
VelocityContext context = createContext();
context.put(RESULTS_KEY, results);
try
{
generateFile(new File(outputDirectory, results.getTestClass().getName() + '_' + RESULTS_FILE),
RESULTS_FILE + TEMPLATE_EXTENSION,
context);
}
catch (Exception ex)
{
throw new ReportNGException("Failed generating JUnit XML report.", ex);
}
}
} | java | public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectoryName)
{
removeEmptyDirectories(new File(outputDirectoryName));
File outputDirectory = new File(outputDirectoryName, REPORT_DIRECTORY);
outputDirectory.mkdirs();
Collection<TestClassResults> flattenedResults = flattenResults(suites);
for (TestClassResults results : flattenedResults)
{
VelocityContext context = createContext();
context.put(RESULTS_KEY, results);
try
{
generateFile(new File(outputDirectory, results.getTestClass().getName() + '_' + RESULTS_FILE),
RESULTS_FILE + TEMPLATE_EXTENSION,
context);
}
catch (Exception ex)
{
throw new ReportNGException("Failed generating JUnit XML report.", ex);
}
}
} | [
"public",
"void",
"generateReport",
"(",
"List",
"<",
"XmlSuite",
">",
"xmlSuites",
",",
"List",
"<",
"ISuite",
">",
"suites",
",",
"String",
"outputDirectoryName",
")",
"{",
"removeEmptyDirectories",
"(",
"new",
"File",
"(",
"outputDirectoryName",
")",
")",
"... | Generates a set of XML files (JUnit format) that contain data about the
outcome of the specified test suites.
@param suites Data about the test runs.
@param outputDirectoryName The directory in which to create the report. | [
"Generates",
"a",
"set",
"of",
"XML",
"files",
"(",
"JUnit",
"format",
")",
"that",
"contain",
"data",
"about",
"the",
"outcome",
"of",
"the",
"specified",
"test",
"suites",
"."
] | train | https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/JUnitXMLReporter.java#L59-L86 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/classfile/ConstantNameAndTypeInfo.java | ConstantNameAndTypeInfo.make | static ConstantNameAndTypeInfo make(ConstantPool cp,
String name,
Descriptor type) {
ConstantInfo ci = new ConstantNameAndTypeInfo(cp, name, type);
return (ConstantNameAndTypeInfo)cp.addConstant(ci);
} | java | static ConstantNameAndTypeInfo make(ConstantPool cp,
String name,
Descriptor type) {
ConstantInfo ci = new ConstantNameAndTypeInfo(cp, name, type);
return (ConstantNameAndTypeInfo)cp.addConstant(ci);
} | [
"static",
"ConstantNameAndTypeInfo",
"make",
"(",
"ConstantPool",
"cp",
",",
"String",
"name",
",",
"Descriptor",
"type",
")",
"{",
"ConstantInfo",
"ci",
"=",
"new",
"ConstantNameAndTypeInfo",
"(",
"cp",
",",
"name",
",",
"type",
")",
";",
"return",
"(",
"Co... | Will return either a new ConstantNameAndTypeInfo object or one
already in the constant pool.
If it is a new ConstantNameAndTypeInfo, it will be inserted
into the pool. | [
"Will",
"return",
"either",
"a",
"new",
"ConstantNameAndTypeInfo",
"object",
"or",
"one",
"already",
"in",
"the",
"constant",
"pool",
".",
"If",
"it",
"is",
"a",
"new",
"ConstantNameAndTypeInfo",
"it",
"will",
"be",
"inserted",
"into",
"the",
"pool",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantNameAndTypeInfo.java#L40-L45 |
OpenTSDB/opentsdb | src/tsd/RpcHandler.java | RpcHandler.createQueryInstance | private AbstractHttpQuery createQueryInstance(final TSDB tsdb,
final HttpRequest request,
final Channel chan)
throws BadRequestException {
final String uri = request.getUri();
if (Strings.isNullOrEmpty(uri)) {
throw new BadRequestException("Request URI is empty");
} else if (uri.charAt(0) != '/') {
throw new BadRequestException("Request URI doesn't start with a slash");
} else if (rpc_manager.isHttpRpcPluginPath(uri)) {
http_plugin_rpcs_received.incrementAndGet();
return new HttpRpcPluginQuery(tsdb, request, chan);
} else {
http_rpcs_received.incrementAndGet();
HttpQuery builtinQuery = new HttpQuery(tsdb, request, chan);
return builtinQuery;
}
} | java | private AbstractHttpQuery createQueryInstance(final TSDB tsdb,
final HttpRequest request,
final Channel chan)
throws BadRequestException {
final String uri = request.getUri();
if (Strings.isNullOrEmpty(uri)) {
throw new BadRequestException("Request URI is empty");
} else if (uri.charAt(0) != '/') {
throw new BadRequestException("Request URI doesn't start with a slash");
} else if (rpc_manager.isHttpRpcPluginPath(uri)) {
http_plugin_rpcs_received.incrementAndGet();
return new HttpRpcPluginQuery(tsdb, request, chan);
} else {
http_rpcs_received.incrementAndGet();
HttpQuery builtinQuery = new HttpQuery(tsdb, request, chan);
return builtinQuery;
}
} | [
"private",
"AbstractHttpQuery",
"createQueryInstance",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"HttpRequest",
"request",
",",
"final",
"Channel",
"chan",
")",
"throws",
"BadRequestException",
"{",
"final",
"String",
"uri",
"=",
"request",
".",
"getUri",
"(",
... | Using the request URI, creates a query instance capable of handling
the given request.
@param tsdb the TSDB instance we are running within
@param request the incoming HTTP request
@param chan the {@link Channel} the request came in on.
@return a subclass of {@link AbstractHttpQuery}
@throws BadRequestException if the request is invalid in a way that
can be detected early, here. | [
"Using",
"the",
"request",
"URI",
"creates",
"a",
"query",
"instance",
"capable",
"of",
"handling",
"the",
"given",
"request",
"."
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/RpcHandler.java#L174-L191 |
windup/windup | utils/src/main/java/org/jboss/windup/util/furnace/FurnaceClasspathScanner.java | FurnaceClasspathScanner.handleDirectory | private void handleDirectory(final Predicate<String> filter, final File rootDir, final List<String> discoveredFiles)
{
try
{
new DirectoryWalker<String>()
{
private Path startDir;
public void walk() throws IOException
{
this.startDir = rootDir.toPath();
this.walk(rootDir, discoveredFiles);
}
@Override
protected void handleFile(File file, int depth, Collection<String> discoveredFiles) throws IOException
{
String newPath = startDir.relativize(file.toPath()).toString();
if (filter.accept(newPath))
discoveredFiles.add(newPath);
}
}.walk();
}
catch (IOException ex)
{
LOG.log(Level.SEVERE, "Error reading Furnace addon directory", ex);
}
} | java | private void handleDirectory(final Predicate<String> filter, final File rootDir, final List<String> discoveredFiles)
{
try
{
new DirectoryWalker<String>()
{
private Path startDir;
public void walk() throws IOException
{
this.startDir = rootDir.toPath();
this.walk(rootDir, discoveredFiles);
}
@Override
protected void handleFile(File file, int depth, Collection<String> discoveredFiles) throws IOException
{
String newPath = startDir.relativize(file.toPath()).toString();
if (filter.accept(newPath))
discoveredFiles.add(newPath);
}
}.walk();
}
catch (IOException ex)
{
LOG.log(Level.SEVERE, "Error reading Furnace addon directory", ex);
}
} | [
"private",
"void",
"handleDirectory",
"(",
"final",
"Predicate",
"<",
"String",
">",
"filter",
",",
"final",
"File",
"rootDir",
",",
"final",
"List",
"<",
"String",
">",
"discoveredFiles",
")",
"{",
"try",
"{",
"new",
"DirectoryWalker",
"<",
"String",
">",
... | Scans given directory for files passing given filter, adds the results into given list. | [
"Scans",
"given",
"directory",
"for",
"files",
"passing",
"given",
"filter",
"adds",
"the",
"results",
"into",
"given",
"list",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/furnace/FurnaceClasspathScanner.java#L172-L200 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java | PomUtils.analyzePOM | public static void analyzePOM(Dependency dependency, File pomFile) throws AnalysisException {
final Model pom = PomUtils.readPom(pomFile);
JarAnalyzer.setPomEvidence(dependency, pom, null, true);
} | java | public static void analyzePOM(Dependency dependency, File pomFile) throws AnalysisException {
final Model pom = PomUtils.readPom(pomFile);
JarAnalyzer.setPomEvidence(dependency, pom, null, true);
} | [
"public",
"static",
"void",
"analyzePOM",
"(",
"Dependency",
"dependency",
",",
"File",
"pomFile",
")",
"throws",
"AnalysisException",
"{",
"final",
"Model",
"pom",
"=",
"PomUtils",
".",
"readPom",
"(",
"pomFile",
")",
";",
"JarAnalyzer",
".",
"setPomEvidence",
... | Reads in the pom file and adds elements as evidence to the given
dependency.
@param dependency the dependency being analyzed
@param pomFile the pom file to read
@throws AnalysisException is thrown if there is an exception parsing the
pom | [
"Reads",
"in",
"the",
"pom",
"file",
"and",
"adds",
"elements",
"as",
"evidence",
"to",
"the",
"given",
"dependency",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java#L139-L142 |
icode/ameba | src/main/java/ameba/db/ebean/support/ModelResourceStructure.java | ModelResourceStructure.findByIds | public Response findByIds(@NotNull @PathParam("ids") URI_ID id,
@NotNull @PathParam("ids") final PathSegment ids,
@QueryParam("include_deleted") final boolean includeDeleted) throws Exception {
final Query<MODEL> query = server.find(modelType);
final MODEL_ID firstId = tryConvertId(ids.getPath());
Set<String> idSet = ids.getMatrixParameters().keySet();
final Set<MODEL_ID> idCollection = Sets.newLinkedHashSet();
idCollection.add(firstId);
if (!idSet.isEmpty()) {
idCollection.addAll(Collections2.transform(idSet, this::tryConvertId));
}
matchedFindByIds(firstId, idCollection, includeDeleted);
Object model;
if (includeDeleted) {
query.setIncludeSoftDeletes();
}
final TxRunnable configureQuery = t -> {
configDefaultQuery(query);
configFindByIdsQuery(query, includeDeleted);
applyUriQuery(query, false);
};
if (!idSet.isEmpty()) {
model = executeTx(t -> {
configureQuery.run(t);
List<MODEL> m = query.where().idIn(idCollection.toArray()).findList();
return processFoundByIdsModelList(m, includeDeleted);
});
} else {
model = executeTx(t -> {
configureQuery.run(t);
MODEL m = query.setId(firstId).findOne();
return processFoundByIdModel(m, includeDeleted);
});
}
if (isEmptyEntity(model)) {
throw new NotFoundException();
}
return Response.ok(model).build();
} | java | public Response findByIds(@NotNull @PathParam("ids") URI_ID id,
@NotNull @PathParam("ids") final PathSegment ids,
@QueryParam("include_deleted") final boolean includeDeleted) throws Exception {
final Query<MODEL> query = server.find(modelType);
final MODEL_ID firstId = tryConvertId(ids.getPath());
Set<String> idSet = ids.getMatrixParameters().keySet();
final Set<MODEL_ID> idCollection = Sets.newLinkedHashSet();
idCollection.add(firstId);
if (!idSet.isEmpty()) {
idCollection.addAll(Collections2.transform(idSet, this::tryConvertId));
}
matchedFindByIds(firstId, idCollection, includeDeleted);
Object model;
if (includeDeleted) {
query.setIncludeSoftDeletes();
}
final TxRunnable configureQuery = t -> {
configDefaultQuery(query);
configFindByIdsQuery(query, includeDeleted);
applyUriQuery(query, false);
};
if (!idSet.isEmpty()) {
model = executeTx(t -> {
configureQuery.run(t);
List<MODEL> m = query.where().idIn(idCollection.toArray()).findList();
return processFoundByIdsModelList(m, includeDeleted);
});
} else {
model = executeTx(t -> {
configureQuery.run(t);
MODEL m = query.setId(firstId).findOne();
return processFoundByIdModel(m, includeDeleted);
});
}
if (isEmptyEntity(model)) {
throw new NotFoundException();
}
return Response.ok(model).build();
} | [
"public",
"Response",
"findByIds",
"(",
"@",
"NotNull",
"@",
"PathParam",
"(",
"\"ids\"",
")",
"URI_ID",
"id",
",",
"@",
"NotNull",
"@",
"PathParam",
"(",
"\"ids\"",
")",
"final",
"PathSegment",
"ids",
",",
"@",
"QueryParam",
"(",
"\"include_deleted\"",
")",... | Find a model or model list given its Ids.
@param id The id use for path matching type
@param ids the id of the model.
@param includeDeleted a boolean.
@return a {@link javax.ws.rs.core.Response} object.
@throws java.lang.Exception if any.
@see javax.ws.rs.GET
@see AbstractModelResource#findByIds | [
"Find",
"a",
"model",
"or",
"model",
"list",
"given",
"its",
"Ids",
"."
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/support/ModelResourceStructure.java#L552-L591 |
opentelecoms-org/jsmpp | jsmpp/src/main/java/org/jsmpp/session/AbstractSession.java | AbstractSession.executeSendCommand | protected Command executeSendCommand(SendCommandTask task, long timeout)
throws PDUException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<Command> pendingResp = new PendingResponse<Command>(timeout);
pendingResponse.put(seqNum, pendingResp);
try {
task.executeTask(connection().getOutputStream(), seqNum);
} catch (IOException e) {
logger.error("Failed sending " + task.getCommandName() + " command", e);
if("enquire_link".equals(task.getCommandName())) {
logger.info("Tomas: Ignore failure of sending enquire_link, wait to see if connection is restored");
} else {
pendingResponse.remove(seqNum);
close();
throw e;
}
}
try {
pendingResp.waitDone();
logger.debug("{} response with sequence {} received for session {}", task.getCommandName(), seqNum, sessionId);
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw new ResponseTimeoutException("No response after waiting for "
+ timeout + " millis when executing "
+ task.getCommandName() + " with sessionId " + sessionId
+ " and sequenceNumber " + seqNum, e);
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
Command resp = pendingResp.getResponse();
validateResponse(resp);
return resp;
} | java | protected Command executeSendCommand(SendCommandTask task, long timeout)
throws PDUException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<Command> pendingResp = new PendingResponse<Command>(timeout);
pendingResponse.put(seqNum, pendingResp);
try {
task.executeTask(connection().getOutputStream(), seqNum);
} catch (IOException e) {
logger.error("Failed sending " + task.getCommandName() + " command", e);
if("enquire_link".equals(task.getCommandName())) {
logger.info("Tomas: Ignore failure of sending enquire_link, wait to see if connection is restored");
} else {
pendingResponse.remove(seqNum);
close();
throw e;
}
}
try {
pendingResp.waitDone();
logger.debug("{} response with sequence {} received for session {}", task.getCommandName(), seqNum, sessionId);
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw new ResponseTimeoutException("No response after waiting for "
+ timeout + " millis when executing "
+ task.getCommandName() + " with sessionId " + sessionId
+ " and sequenceNumber " + seqNum, e);
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
Command resp = pendingResp.getResponse();
validateResponse(resp);
return resp;
} | [
"protected",
"Command",
"executeSendCommand",
"(",
"SendCommandTask",
"task",
",",
"long",
"timeout",
")",
"throws",
"PDUException",
",",
"ResponseTimeoutException",
",",
"InvalidResponseException",
",",
"NegativeResponseException",
",",
"IOException",
"{",
"int",
"seqNum... | Execute send command command task.
@param task is the task.
@param timeout is the timeout in millisecond.
@return the command response.
@throws PDUException if there is invalid PDU parameter found.
@throws ResponseTimeoutException if the response has reach it timeout.
@throws InvalidResponseException if invalid response found.
@throws NegativeResponseException if the negative response found.
@throws IOException if there is an IO error found. | [
"Execute",
"send",
"command",
"command",
"task",
"."
] | train | https://github.com/opentelecoms-org/jsmpp/blob/acc15e73e7431deabc803731971b15323315baaf/jsmpp/src/main/java/org/jsmpp/session/AbstractSession.java#L269-L307 |
jenkinsci/jenkins | core/src/main/java/jenkins/util/JSONSignatureValidator.java | JSONSignatureValidator.digestMatches | private boolean digestMatches(byte[] digest, String providedDigest) {
return providedDigest.equalsIgnoreCase(Hex.encodeHexString(digest)) || providedDigest.equalsIgnoreCase(new String(Base64.getEncoder().encode(digest)));
} | java | private boolean digestMatches(byte[] digest, String providedDigest) {
return providedDigest.equalsIgnoreCase(Hex.encodeHexString(digest)) || providedDigest.equalsIgnoreCase(new String(Base64.getEncoder().encode(digest)));
} | [
"private",
"boolean",
"digestMatches",
"(",
"byte",
"[",
"]",
"digest",
",",
"String",
"providedDigest",
")",
"{",
"return",
"providedDigest",
".",
"equalsIgnoreCase",
"(",
"Hex",
".",
"encodeHexString",
"(",
"digest",
")",
")",
"||",
"providedDigest",
".",
"e... | Utility method supporting both possible digest formats: Base64 and Hex | [
"Utility",
"method",
"supporting",
"both",
"possible",
"digest",
"formats",
":",
"Base64",
"and",
"Hex"
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/JSONSignatureValidator.java#L238-L240 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationRuleParser.java | CollationRuleParser.parseSpecialPosition | private int parseSpecialPosition(int i, StringBuilder str) throws ParseException {
int j = readWords(i + 1, rawBuilder);
if(j > i && rules.charAt(j) == 0x5d && rawBuilder.length() != 0) { // words end with ]
++j;
String raw = rawBuilder.toString();
str.setLength(0);
for(int pos = 0; pos < positions.length; ++pos) {
if(raw.equals(positions[pos])) {
str.append(POS_LEAD).append((char)(POS_BASE + pos));
return j;
}
}
if(raw.equals("top")) {
str.append(POS_LEAD).append((char)(POS_BASE + Position.LAST_REGULAR.ordinal()));
return j;
}
if(raw.equals("variable top")) {
str.append(POS_LEAD).append((char)(POS_BASE + Position.LAST_VARIABLE.ordinal()));
return j;
}
}
setParseError("not a valid special reset position");
return i;
} | java | private int parseSpecialPosition(int i, StringBuilder str) throws ParseException {
int j = readWords(i + 1, rawBuilder);
if(j > i && rules.charAt(j) == 0x5d && rawBuilder.length() != 0) { // words end with ]
++j;
String raw = rawBuilder.toString();
str.setLength(0);
for(int pos = 0; pos < positions.length; ++pos) {
if(raw.equals(positions[pos])) {
str.append(POS_LEAD).append((char)(POS_BASE + pos));
return j;
}
}
if(raw.equals("top")) {
str.append(POS_LEAD).append((char)(POS_BASE + Position.LAST_REGULAR.ordinal()));
return j;
}
if(raw.equals("variable top")) {
str.append(POS_LEAD).append((char)(POS_BASE + Position.LAST_VARIABLE.ordinal()));
return j;
}
}
setParseError("not a valid special reset position");
return i;
} | [
"private",
"int",
"parseSpecialPosition",
"(",
"int",
"i",
",",
"StringBuilder",
"str",
")",
"throws",
"ParseException",
"{",
"int",
"j",
"=",
"readWords",
"(",
"i",
"+",
"1",
",",
"rawBuilder",
")",
";",
"if",
"(",
"j",
">",
"i",
"&&",
"rules",
".",
... | Sets str to a contraction of U+FFFE and (U+2800 + Position).
@return rule index after the special reset position
@throws ParseException | [
"Sets",
"str",
"to",
"a",
"contraction",
"of",
"U",
"+",
"FFFE",
"and",
"(",
"U",
"+",
"2800",
"+",
"Position",
")",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationRuleParser.java#L501-L524 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShippingMethodPersistenceImpl.java | CommerceShippingMethodPersistenceImpl.findByG_E | @Override
public CommerceShippingMethod findByG_E(long groupId, String engineKey)
throws NoSuchShippingMethodException {
CommerceShippingMethod commerceShippingMethod = fetchByG_E(groupId,
engineKey);
if (commerceShippingMethod == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("groupId=");
msg.append(groupId);
msg.append(", engineKey=");
msg.append(engineKey);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchShippingMethodException(msg.toString());
}
return commerceShippingMethod;
} | java | @Override
public CommerceShippingMethod findByG_E(long groupId, String engineKey)
throws NoSuchShippingMethodException {
CommerceShippingMethod commerceShippingMethod = fetchByG_E(groupId,
engineKey);
if (commerceShippingMethod == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("groupId=");
msg.append(groupId);
msg.append(", engineKey=");
msg.append(engineKey);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchShippingMethodException(msg.toString());
}
return commerceShippingMethod;
} | [
"@",
"Override",
"public",
"CommerceShippingMethod",
"findByG_E",
"(",
"long",
"groupId",
",",
"String",
"engineKey",
")",
"throws",
"NoSuchShippingMethodException",
"{",
"CommerceShippingMethod",
"commerceShippingMethod",
"=",
"fetchByG_E",
"(",
"groupId",
",",
"engineKe... | Returns the commerce shipping method where groupId = ? and engineKey = ? or throws a {@link NoSuchShippingMethodException} if it could not be found.
@param groupId the group ID
@param engineKey the engine key
@return the matching commerce shipping method
@throws NoSuchShippingMethodException if a matching commerce shipping method could not be found | [
"Returns",
"the",
"commerce",
"shipping",
"method",
"where",
"groupId",
"=",
"?",
";",
"and",
"engineKey",
"=",
"?",
";",
"or",
"throws",
"a",
"{",
"@link",
"NoSuchShippingMethodException",
"}",
"if",
"it",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShippingMethodPersistenceImpl.java#L625-L652 |
carewebframework/carewebframework-core | org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/query/QueryUtil.java | QueryUtil.packageResult | public static <T> IQueryResult<T> packageResult(List<T> results) {
return packageResult(results, null);
} | java | public static <T> IQueryResult<T> packageResult(List<T> results) {
return packageResult(results, null);
} | [
"public",
"static",
"<",
"T",
">",
"IQueryResult",
"<",
"T",
">",
"packageResult",
"(",
"List",
"<",
"T",
">",
"results",
")",
"{",
"return",
"packageResult",
"(",
"results",
",",
"null",
")",
";",
"}"
] | Convenience method for packaging query results.
@param <T> Class of query result.
@param results Results to package.
@return Packaged results. | [
"Convenience",
"method",
"for",
"packaging",
"query",
"results",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/query/QueryUtil.java#L103-L105 |
aws/aws-sdk-java | aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/AssessmentRun.java | AssessmentRun.withFindingCounts | public AssessmentRun withFindingCounts(java.util.Map<String, Integer> findingCounts) {
setFindingCounts(findingCounts);
return this;
} | java | public AssessmentRun withFindingCounts(java.util.Map<String, Integer> findingCounts) {
setFindingCounts(findingCounts);
return this;
} | [
"public",
"AssessmentRun",
"withFindingCounts",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"Integer",
">",
"findingCounts",
")",
"{",
"setFindingCounts",
"(",
"findingCounts",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Provides a total count of generated findings per severity.
</p>
@param findingCounts
Provides a total count of generated findings per severity.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Provides",
"a",
"total",
"count",
"of",
"generated",
"findings",
"per",
"severity",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/AssessmentRun.java#L906-L909 |
basho/riak-java-client | src/main/java/com/basho/riak/client/core/query/UserMetadata/RiakUserMetadata.java | RiakUserMetadata.put | public void put(String key, String value)
{
put(key, value, DefaultCharset.get());
} | java | public void put(String key, String value)
{
put(key, value, DefaultCharset.get());
} | [
"public",
"void",
"put",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"put",
"(",
"key",
",",
"value",
",",
"DefaultCharset",
".",
"get",
"(",
")",
")",
";",
"}"
] | Set a user metadata entry.
<p>
This method and its {@link RiakUserMetadata#get(java.lang.String) }
counterpart use the default {@code Charset} to convert the {@code String}s.
</p>
@param key the key for the user metadata entry as a {@code String} encoded using the default {@code Charset}
@param value the value for the entry as a {@code String} encoded using the default {@code Charset} | [
"Set",
"a",
"user",
"metadata",
"entry",
".",
"<p",
">",
"This",
"method",
"and",
"its",
"{",
"@link",
"RiakUserMetadata#get",
"(",
"java",
".",
"lang",
".",
"String",
")",
"}",
"counterpart",
"use",
"the",
"default",
"{",
"@code",
"Charset",
"}",
"to",
... | train | https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/core/query/UserMetadata/RiakUserMetadata.java#L165-L168 |
twitter/cloudhopper-commons | ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java | ByteBuffer.toArray | public void toArray(int offset, int length, byte[] targetBuffer, int targetOffset) {
// validate the offset, length are ok
ByteBuffer.checkOffsetLength(size(), offset, length);
// validate the offset, length are ok
ByteBuffer.checkOffsetLength(targetBuffer.length, targetOffset, length);
// will we have a large enough byte[] allocated?
if (targetBuffer.length < length) {
throw new IllegalArgumentException("TargetBuffer size must be large enough to hold a byte[] of at least a size=" + length);
}
// are we actually copying any data?
if (length > 0) {
// create adjusted versions of read and write positions based
// on the offset and length passed into this method
int offsetReadPosition = (this.currentReadPosition + offset) % this.buffer.length;
int offsetWritePosition = (this.currentReadPosition + offset + length) % this.buffer.length;
if (offsetReadPosition >= offsetWritePosition) {
System.arraycopy(
this.buffer,
offsetReadPosition,
targetBuffer,
targetOffset,
this.buffer.length - offsetReadPosition);
System.arraycopy(
this.buffer,
0,
targetBuffer,
targetOffset + this.buffer.length - offsetReadPosition,
offsetWritePosition);
} else {
System.arraycopy(
this.buffer,
offsetReadPosition,
targetBuffer,
targetOffset,
offsetWritePosition - offsetReadPosition);
}
}
} | java | public void toArray(int offset, int length, byte[] targetBuffer, int targetOffset) {
// validate the offset, length are ok
ByteBuffer.checkOffsetLength(size(), offset, length);
// validate the offset, length are ok
ByteBuffer.checkOffsetLength(targetBuffer.length, targetOffset, length);
// will we have a large enough byte[] allocated?
if (targetBuffer.length < length) {
throw new IllegalArgumentException("TargetBuffer size must be large enough to hold a byte[] of at least a size=" + length);
}
// are we actually copying any data?
if (length > 0) {
// create adjusted versions of read and write positions based
// on the offset and length passed into this method
int offsetReadPosition = (this.currentReadPosition + offset) % this.buffer.length;
int offsetWritePosition = (this.currentReadPosition + offset + length) % this.buffer.length;
if (offsetReadPosition >= offsetWritePosition) {
System.arraycopy(
this.buffer,
offsetReadPosition,
targetBuffer,
targetOffset,
this.buffer.length - offsetReadPosition);
System.arraycopy(
this.buffer,
0,
targetBuffer,
targetOffset + this.buffer.length - offsetReadPosition,
offsetWritePosition);
} else {
System.arraycopy(
this.buffer,
offsetReadPosition,
targetBuffer,
targetOffset,
offsetWritePosition - offsetReadPosition);
}
}
} | [
"public",
"void",
"toArray",
"(",
"int",
"offset",
",",
"int",
"length",
",",
"byte",
"[",
"]",
"targetBuffer",
",",
"int",
"targetOffset",
")",
"{",
"// validate the offset, length are ok",
"ByteBuffer",
".",
"checkOffsetLength",
"(",
"size",
"(",
")",
",",
"... | Will copy data from this ByteBuffer's buffer into the targetBuffer. This
method requires the targetBuffer to already be allocated with enough capacity
to hold this ByteBuffer's data.
@param offset The offset within the ByteBuffer to start copy from
@param length The length from the offset to copy
@param targetBuffer The target byte array we'll copy data into. Must already
be allocated with enough capacity.
@param targetOffset The offset within the target byte array to start from
@throws IllegalArgumentException If the offset and length are invalid
for this ByteBuffer, if the targetOffset and targetLength are invalid
for the targetBuffer, or if if the targetBuffer's capacity is not
large enough to hold the copied data. | [
"Will",
"copy",
"data",
"from",
"this",
"ByteBuffer",
"s",
"buffer",
"into",
"the",
"targetBuffer",
".",
"This",
"method",
"requires",
"the",
"targetBuffer",
"to",
"already",
"be",
"allocated",
"with",
"enough",
"capacity",
"to",
"hold",
"this",
"ByteBuffer",
... | train | https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java#L804-L847 |
UrielCh/ovh-java-sdk | ovh-java-sdk-caasregistry/src/main/java/net/minidev/ovh/api/ApiOvhCaasregistry.java | ApiOvhCaasregistry.serviceName_serviceInfos_PUT | public void serviceName_serviceInfos_PUT(String serviceName, net.minidev.ovh.api.services.OvhService body) throws IOException {
String qPath = "/caas/registry/{serviceName}/serviceInfos";
StringBuilder sb = path(qPath, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void serviceName_serviceInfos_PUT(String serviceName, net.minidev.ovh.api.services.OvhService body) throws IOException {
String qPath = "/caas/registry/{serviceName}/serviceInfos";
StringBuilder sb = path(qPath, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"serviceName_serviceInfos_PUT",
"(",
"String",
"serviceName",
",",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"services",
".",
"OvhService",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/caas/registry/{serviceNam... | Alter this object properties
REST: PUT /caas/registry/{serviceName}/serviceInfos
@param body [required] New object properties
@param serviceName [required] The internal ID of your project
API beta | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-caasregistry/src/main/java/net/minidev/ovh/api/ApiOvhCaasregistry.java#L185-L189 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/AbstractValidate.java | AbstractValidate.exclusiveBetween | public <T, V extends Comparable<T>> V exclusiveBetween(final T start, final T end, final V value) {
if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
fail(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
return value;
} | java | public <T, V extends Comparable<T>> V exclusiveBetween(final T start, final T end, final V value) {
if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
fail(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
return value;
} | [
"public",
"<",
"T",
",",
"V",
"extends",
"Comparable",
"<",
"T",
">",
">",
"V",
"exclusiveBetween",
"(",
"final",
"T",
"start",
",",
"final",
"T",
"end",
",",
"final",
"V",
"value",
")",
"{",
"if",
"(",
"value",
".",
"compareTo",
"(",
"start",
")",... | <p>Validate that the specified argument object fall between the two exclusive values specified; otherwise, throws an exception.</p>
<pre>Validate.exclusiveBetween(0, 2, 1);</pre>
@param <T>
the type of the argument start and end values
@param <V>
the type of the value
@param start
the exclusive start value, not null
@param end
the exclusive end value, not null
@param value
the object to validate, not null
@return the value
@throws IllegalArgumentValidationException
if the value falls outside the boundaries
@see #exclusiveBetween(Object, Object, Comparable, String, Object...) | [
"<p",
">",
"Validate",
"that",
"the",
"specified",
"argument",
"object",
"fall",
"between",
"the",
"two",
"exclusive",
"values",
"specified",
";",
"otherwise",
"throws",
"an",
"exception",
".",
"<",
"/",
"p",
">",
"<pre",
">",
"Validate",
".",
"exclusiveBetw... | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/AbstractValidate.java#L1387-L1392 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/TitlePaneMaximizeButtonPainter.java | TitlePaneMaximizeButtonPainter.paintMaximizeHover | private void paintMaximizeHover(Graphics2D g, JComponent c, int width, int height) {
maximizePainter.paintHover(g, c, width, height);
} | java | private void paintMaximizeHover(Graphics2D g, JComponent c, int width, int height) {
maximizePainter.paintHover(g, c, width, height);
} | [
"private",
"void",
"paintMaximizeHover",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"maximizePainter",
".",
"paintHover",
"(",
"g",
",",
"c",
",",
"width",
",",
"height",
")",
";",
"}"
] | Paint the foreground maximized button mouse-over state.
@param g the Graphics2D context to paint with.
@param c the component.
@param width the width of the component.
@param height the height of the component. | [
"Paint",
"the",
"foreground",
"maximized",
"button",
"mouse",
"-",
"over",
"state",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneMaximizeButtonPainter.java#L185-L187 |
google/error-prone-javac | src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ArgTokenizer.java | ArgTokenizer.whitespaceChars | private void whitespaceChars(int low, int hi) {
if (low < 0)
low = 0;
if (hi >= ctype.length)
hi = ctype.length - 1;
while (low <= hi)
ctype[low++] = CT_WHITESPACE;
} | java | private void whitespaceChars(int low, int hi) {
if (low < 0)
low = 0;
if (hi >= ctype.length)
hi = ctype.length - 1;
while (low <= hi)
ctype[low++] = CT_WHITESPACE;
} | [
"private",
"void",
"whitespaceChars",
"(",
"int",
"low",
",",
"int",
"hi",
")",
"{",
"if",
"(",
"low",
"<",
"0",
")",
"low",
"=",
"0",
";",
"if",
"(",
"hi",
">=",
"ctype",
".",
"length",
")",
"hi",
"=",
"ctype",
".",
"length",
"-",
"1",
";",
... | Specifies that all characters <i>c</i> in the range
<code>low <= <i>c</i> <= high</code>
are white space characters. White space characters serve only to
separate tokens in the input stream.
<p>Any other attribute settings for the characters in the specified
range are cleared.
@param low the low end of the range.
@param hi the high end of the range. | [
"Specifies",
"that",
"all",
"characters",
"<i",
">",
"c<",
"/",
"i",
">",
"in",
"the",
"range",
"<code",
">",
"low ",
";",
"<",
";",
"=",
" ",
";",
"<i",
">",
"c<",
"/",
"i",
">",
" ",
";",
"<",
";",
"=",
" ",
";",
"high<",
... | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ArgTokenizer.java#L220-L227 |
pravega/pravega | segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/BookKeeperServiceRunner.java | BookKeeperServiceRunner.resumeZooKeeper | public void resumeZooKeeper() throws Exception {
val zk = new ZooKeeperServiceRunner(this.zkPort, this.secureZK, this.tLSKeyStore, this.tLSKeyStorePasswordPath, this.tlsTrustStore);
if (this.zkServer.compareAndSet(null, zk)) {
// Initialize ZK runner (since nobody else did it for us).
zk.initialize();
log.info("ZooKeeper initialized.");
} else {
zk.close();
}
// Start or resume ZK.
this.zkServer.get().start();
log.info("ZooKeeper resumed.");
} | java | public void resumeZooKeeper() throws Exception {
val zk = new ZooKeeperServiceRunner(this.zkPort, this.secureZK, this.tLSKeyStore, this.tLSKeyStorePasswordPath, this.tlsTrustStore);
if (this.zkServer.compareAndSet(null, zk)) {
// Initialize ZK runner (since nobody else did it for us).
zk.initialize();
log.info("ZooKeeper initialized.");
} else {
zk.close();
}
// Start or resume ZK.
this.zkServer.get().start();
log.info("ZooKeeper resumed.");
} | [
"public",
"void",
"resumeZooKeeper",
"(",
")",
"throws",
"Exception",
"{",
"val",
"zk",
"=",
"new",
"ZooKeeperServiceRunner",
"(",
"this",
".",
"zkPort",
",",
"this",
".",
"secureZK",
",",
"this",
".",
"tLSKeyStore",
",",
"this",
".",
"tLSKeyStorePasswordPath"... | Resumes ZooKeeper (if it had previously been suspended).
@throws Exception If an exception got thrown. | [
"Resumes",
"ZooKeeper",
"(",
"if",
"it",
"had",
"previously",
"been",
"suspended",
")",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/BookKeeperServiceRunner.java#L143-L156 |
notnoop/java-apns | src/main/java/com/notnoop/apns/internal/SSLContextBuilder.java | SSLContextBuilder.getKeyStoreWithSingleKey | private KeyStore getKeyStoreWithSingleKey(KeyStore keyStore, String keyStorePassword, String keyAlias)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
KeyStore singleKeyKeyStore = KeyStore.getInstance(keyStore.getType(), keyStore.getProvider());
final char[] password = keyStorePassword.toCharArray();
singleKeyKeyStore.load(null, password);
Key key = keyStore.getKey(keyAlias, password);
Certificate[] chain = keyStore.getCertificateChain(keyAlias);
singleKeyKeyStore.setKeyEntry(keyAlias, key, password, chain);
return singleKeyKeyStore;
} | java | private KeyStore getKeyStoreWithSingleKey(KeyStore keyStore, String keyStorePassword, String keyAlias)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
KeyStore singleKeyKeyStore = KeyStore.getInstance(keyStore.getType(), keyStore.getProvider());
final char[] password = keyStorePassword.toCharArray();
singleKeyKeyStore.load(null, password);
Key key = keyStore.getKey(keyAlias, password);
Certificate[] chain = keyStore.getCertificateChain(keyAlias);
singleKeyKeyStore.setKeyEntry(keyAlias, key, password, chain);
return singleKeyKeyStore;
} | [
"private",
"KeyStore",
"getKeyStoreWithSingleKey",
"(",
"KeyStore",
"keyStore",
",",
"String",
"keyStorePassword",
",",
"String",
"keyAlias",
")",
"throws",
"KeyStoreException",
",",
"IOException",
",",
"NoSuchAlgorithmException",
",",
"CertificateException",
",",
"Unreco... | /*
Workaround for keystores containing multiple keys. Java will take the first key that matches
and this way we can still offer configuration for a keystore with multiple keys and a selection
based on alias. Also much easier than making a subclass of a KeyManagerFactory | [
"/",
"*",
"Workaround",
"for",
"keystores",
"containing",
"multiple",
"keys",
".",
"Java",
"will",
"take",
"the",
"first",
"key",
"that",
"matches",
"and",
"this",
"way",
"we",
"can",
"still",
"offer",
"configuration",
"for",
"a",
"keystore",
"with",
"multip... | train | https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/internal/SSLContextBuilder.java#L151-L160 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/jvm/ClassReader.java | ClassReader.complete | private void complete(Symbol sym) throws CompletionFailure {
if (sym.kind == TYP) {
ClassSymbol c = (ClassSymbol)sym;
c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
annotate.enterStart();
try {
completeOwners(c.owner);
completeEnclosing(c);
} finally {
// The flush needs to happen only after annotations
// are filled in.
annotate.enterDoneWithoutFlush();
}
fillIn(c);
} else if (sym.kind == PCK) {
PackageSymbol p = (PackageSymbol)sym;
try {
fillIn(p);
} catch (IOException ex) {
throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
}
}
if (!filling)
annotate.flush(); // finish attaching annotations
} | java | private void complete(Symbol sym) throws CompletionFailure {
if (sym.kind == TYP) {
ClassSymbol c = (ClassSymbol)sym;
c.members_field = new Scope.ErrorScope(c); // make sure it's always defined
annotate.enterStart();
try {
completeOwners(c.owner);
completeEnclosing(c);
} finally {
// The flush needs to happen only after annotations
// are filled in.
annotate.enterDoneWithoutFlush();
}
fillIn(c);
} else if (sym.kind == PCK) {
PackageSymbol p = (PackageSymbol)sym;
try {
fillIn(p);
} catch (IOException ex) {
throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex);
}
}
if (!filling)
annotate.flush(); // finish attaching annotations
} | [
"private",
"void",
"complete",
"(",
"Symbol",
"sym",
")",
"throws",
"CompletionFailure",
"{",
"if",
"(",
"sym",
".",
"kind",
"==",
"TYP",
")",
"{",
"ClassSymbol",
"c",
"=",
"(",
"ClassSymbol",
")",
"sym",
";",
"c",
".",
"members_field",
"=",
"new",
"Sc... | Completion for classes to be loaded. Before a class is loaded
we make sure its enclosing class (if any) is loaded. | [
"Completion",
"for",
"classes",
"to",
"be",
"loaded",
".",
"Before",
"a",
"class",
"is",
"loaded",
"we",
"make",
"sure",
"its",
"enclosing",
"class",
"(",
"if",
"any",
")",
"is",
"loaded",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java#L2442-L2466 |
classgraph/classgraph | src/main/java/nonapi/io/github/classgraph/json/JSONSerializer.java | JSONSerializer.jsonValToJSONString | static void jsonValToJSONString(final Object jsonVal,
final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
final boolean includeNullValuedFields, final int depth, final int indentWidth,
final StringBuilder buf) {
if (jsonVal == null) {
buf.append("null");
} else if (jsonVal instanceof JSONObject) {
// Serialize JSONObject to string
((JSONObject) jsonVal).toJSONString(jsonReferenceToId, includeNullValuedFields, depth, indentWidth,
buf);
} else if (jsonVal instanceof JSONArray) {
// Serialize JSONArray to string
((JSONArray) jsonVal).toJSONString(jsonReferenceToId, includeNullValuedFields, depth, indentWidth, buf);
} else if (jsonVal instanceof JSONReference) {
// Serialize JSONReference to string
final Object referencedObjectId = jsonReferenceToId
.get(new ReferenceEqualityKey<>((JSONReference) jsonVal));
jsonValToJSONString(referencedObjectId, jsonReferenceToId, includeNullValuedFields, depth, indentWidth,
buf);
} else if (jsonVal instanceof CharSequence || jsonVal instanceof Character || jsonVal.getClass().isEnum()) {
// Serialize String, Character or enum val to quoted/escaped string
buf.append('"');
JSONUtils.escapeJSONString(jsonVal.toString(), buf);
buf.append('"');
} else {
// Serialize a numeric or Boolean type (Integer, Long, Short, Float, Double, Boolean, Byte) to string
// (doesn't need quoting or escaping)
buf.append(jsonVal.toString());
}
} | java | static void jsonValToJSONString(final Object jsonVal,
final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
final boolean includeNullValuedFields, final int depth, final int indentWidth,
final StringBuilder buf) {
if (jsonVal == null) {
buf.append("null");
} else if (jsonVal instanceof JSONObject) {
// Serialize JSONObject to string
((JSONObject) jsonVal).toJSONString(jsonReferenceToId, includeNullValuedFields, depth, indentWidth,
buf);
} else if (jsonVal instanceof JSONArray) {
// Serialize JSONArray to string
((JSONArray) jsonVal).toJSONString(jsonReferenceToId, includeNullValuedFields, depth, indentWidth, buf);
} else if (jsonVal instanceof JSONReference) {
// Serialize JSONReference to string
final Object referencedObjectId = jsonReferenceToId
.get(new ReferenceEqualityKey<>((JSONReference) jsonVal));
jsonValToJSONString(referencedObjectId, jsonReferenceToId, includeNullValuedFields, depth, indentWidth,
buf);
} else if (jsonVal instanceof CharSequence || jsonVal instanceof Character || jsonVal.getClass().isEnum()) {
// Serialize String, Character or enum val to quoted/escaped string
buf.append('"');
JSONUtils.escapeJSONString(jsonVal.toString(), buf);
buf.append('"');
} else {
// Serialize a numeric or Boolean type (Integer, Long, Short, Float, Double, Boolean, Byte) to string
// (doesn't need quoting or escaping)
buf.append(jsonVal.toString());
}
} | [
"static",
"void",
"jsonValToJSONString",
"(",
"final",
"Object",
"jsonVal",
",",
"final",
"Map",
"<",
"ReferenceEqualityKey",
"<",
"JSONReference",
">",
",",
"CharSequence",
">",
"jsonReferenceToId",
",",
"final",
"boolean",
"includeNullValuedFields",
",",
"final",
... | Serialize a JSON object, array, or value.
@param jsonVal
the json val
@param jsonReferenceToId
a map from json reference to id
@param includeNullValuedFields
the include null valued fields
@param depth
the depth
@param indentWidth
the indent width
@param buf
the buf | [
"Serialize",
"a",
"JSON",
"object",
"array",
"or",
"value",
"."
] | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/json/JSONSerializer.java#L417-L452 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/convert/MergeConverter.java | MergeConverter.setupDefaultView | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert convert, int iDisplayFieldDesc, Map<String, Object> properties)
{
ScreenComponent sField = null;
Converter converter = this.getNextConverter();
if (converter != null)
sField = converter.setupDefaultView(itsLocation, targetScreen, convert, iDisplayFieldDesc, properties);
else
sField = super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties);
if (sField != null)
{ // Get rid of any and all links to/from field/converter
converter.removeComponent(sField); // Have the field add me to its list for display
sField.setConverter(this);
}
return sField;
} | java | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert convert, int iDisplayFieldDesc, Map<String, Object> properties)
{
ScreenComponent sField = null;
Converter converter = this.getNextConverter();
if (converter != null)
sField = converter.setupDefaultView(itsLocation, targetScreen, convert, iDisplayFieldDesc, properties);
else
sField = super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties);
if (sField != null)
{ // Get rid of any and all links to/from field/converter
converter.removeComponent(sField); // Have the field add me to its list for display
sField.setConverter(this);
}
return sField;
} | [
"public",
"ScreenComponent",
"setupDefaultView",
"(",
"ScreenLoc",
"itsLocation",
",",
"ComponentParent",
"targetScreen",
",",
"Convert",
"convert",
",",
"int",
"iDisplayFieldDesc",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"ScreenCompon... | Set up the default control for this field.
Adds the default screen control for the current converter, and makes me it's converter.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param iDisplayFieldDesc Display the label? (optional).
@return Return the component or ScreenField that is created for this field. | [
"Set",
"up",
"the",
"default",
"control",
"for",
"this",
"field",
".",
"Adds",
"the",
"default",
"screen",
"control",
"for",
"the",
"current",
"converter",
"and",
"makes",
"me",
"it",
"s",
"converter",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/convert/MergeConverter.java#L179-L193 |
WASdev/ci.gradle | src/main/groovy/net/wasdev/wlp/gradle/plugins/utils/ServerConfigDocument.java | ServerConfigDocument.getFileFromConfigDirectory | private File getFileFromConfigDirectory(String file, File def) {
File f = new File(configDirectory, file);
if (configDirectory != null && f.exists()) {
return f;
}
if (def != null && def.exists()) {
return def;
}
return null;
} | java | private File getFileFromConfigDirectory(String file, File def) {
File f = new File(configDirectory, file);
if (configDirectory != null && f.exists()) {
return f;
}
if (def != null && def.exists()) {
return def;
}
return null;
} | [
"private",
"File",
"getFileFromConfigDirectory",
"(",
"String",
"file",
",",
"File",
"def",
")",
"{",
"File",
"f",
"=",
"new",
"File",
"(",
"configDirectory",
",",
"file",
")",
";",
"if",
"(",
"configDirectory",
"!=",
"null",
"&&",
"f",
".",
"exists",
"(... | /*
Get the file from configDrectory if it exists;
otherwise return def only if it exists, or null if not | [
"/",
"*",
"Get",
"the",
"file",
"from",
"configDrectory",
"if",
"it",
"exists",
";",
"otherwise",
"return",
"def",
"only",
"if",
"it",
"exists",
"or",
"null",
"if",
"not"
] | train | https://github.com/WASdev/ci.gradle/blob/523a35e5146c1c5ab8f3aa00d353bbe91eecc180/src/main/groovy/net/wasdev/wlp/gradle/plugins/utils/ServerConfigDocument.java#L493-L502 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseBool | public static boolean parseBool (@Nullable final Object aObject, final boolean bDefault)
{
if (aObject instanceof Boolean)
return ((Boolean) aObject).booleanValue ();
if (aObject instanceof String)
return parseBool ((String) aObject);
return bDefault;
} | java | public static boolean parseBool (@Nullable final Object aObject, final boolean bDefault)
{
if (aObject instanceof Boolean)
return ((Boolean) aObject).booleanValue ();
if (aObject instanceof String)
return parseBool ((String) aObject);
return bDefault;
} | [
"public",
"static",
"boolean",
"parseBool",
"(",
"@",
"Nullable",
"final",
"Object",
"aObject",
",",
"final",
"boolean",
"bDefault",
")",
"{",
"if",
"(",
"aObject",
"instanceof",
"Boolean",
")",
"return",
"(",
"(",
"Boolean",
")",
"aObject",
")",
".",
"boo... | Try to interpret the passed object as boolean. This works only if the
passed object is either a {@link String} or a {@link Boolean}.
@param aObject
The object to be interpreted. May be <code>null</code>.
@param bDefault
The default value to be returned, if the object cannot be
interpreted.
@return The boolean representation or the default value if the passed
object cannot be interpreted as a boolean. | [
"Try",
"to",
"interpret",
"the",
"passed",
"object",
"as",
"boolean",
".",
"This",
"works",
"only",
"if",
"the",
"passed",
"object",
"is",
"either",
"a",
"{",
"@link",
"String",
"}",
"or",
"a",
"{",
"@link",
"Boolean",
"}",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L93-L100 |
apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/avro/AvroSchemaManager.java | AvroSchemaManager.getOrGenerateSchemaFile | private Path getOrGenerateSchemaFile(Schema schema) throws IOException {
Preconditions.checkNotNull(schema, "Avro Schema should not be null");
String hashedSchema = Hashing.sha256().hashString(schema.toString(), StandardCharsets.UTF_8).toString();
if (!this.schemaPaths.containsKey(hashedSchema)) {
Path schemaFilePath = new Path(this.schemaDir, String.valueOf(System.currentTimeMillis() + ".avsc"));
AvroUtils.writeSchemaToFile(schema, schemaFilePath, fs, true);
this.schemaPaths.put(hashedSchema, schemaFilePath);
}
return this.schemaPaths.get(hashedSchema);
} | java | private Path getOrGenerateSchemaFile(Schema schema) throws IOException {
Preconditions.checkNotNull(schema, "Avro Schema should not be null");
String hashedSchema = Hashing.sha256().hashString(schema.toString(), StandardCharsets.UTF_8).toString();
if (!this.schemaPaths.containsKey(hashedSchema)) {
Path schemaFilePath = new Path(this.schemaDir, String.valueOf(System.currentTimeMillis() + ".avsc"));
AvroUtils.writeSchemaToFile(schema, schemaFilePath, fs, true);
this.schemaPaths.put(hashedSchema, schemaFilePath);
}
return this.schemaPaths.get(hashedSchema);
} | [
"private",
"Path",
"getOrGenerateSchemaFile",
"(",
"Schema",
"schema",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"schema",
",",
"\"Avro Schema should not be null\"",
")",
";",
"String",
"hashedSchema",
"=",
"Hashing",
".",
"sha256",... | If url for schema already exists, return the url. If not create a new temporary schema file and return a the url. | [
"If",
"url",
"for",
"schema",
"already",
"exists",
"return",
"the",
"url",
".",
"If",
"not",
"create",
"a",
"new",
"temporary",
"schema",
"file",
"and",
"return",
"a",
"the",
"url",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/avro/AvroSchemaManager.java#L185-L200 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/CustomMatchingStrategy.java | CustomMatchingStrategy.getCollectionMatchForWebResourceCollection | @Override
protected CollectionMatch getCollectionMatchForWebResourceCollection(WebResourceCollection webResourceCollection, String resourceName, String method) {
CollectionMatch match = null;
CollectionMatch collectionMatchFound = webResourceCollection.performUrlMatch(resourceName);
if (collectionMatchFound != null) {
if (webResourceCollection.isMethodMatched(method)) {
match = collectionMatchFound;
} else if (webResourceCollection.isMethodListed(method)) {
match = CollectionMatch.RESPONSE_NO_MATCH;
}
} else {
match = CollectionMatch.RESPONSE_NO_MATCH;
}
return match;
} | java | @Override
protected CollectionMatch getCollectionMatchForWebResourceCollection(WebResourceCollection webResourceCollection, String resourceName, String method) {
CollectionMatch match = null;
CollectionMatch collectionMatchFound = webResourceCollection.performUrlMatch(resourceName);
if (collectionMatchFound != null) {
if (webResourceCollection.isMethodMatched(method)) {
match = collectionMatchFound;
} else if (webResourceCollection.isMethodListed(method)) {
match = CollectionMatch.RESPONSE_NO_MATCH;
}
} else {
match = CollectionMatch.RESPONSE_NO_MATCH;
}
return match;
} | [
"@",
"Override",
"protected",
"CollectionMatch",
"getCollectionMatchForWebResourceCollection",
"(",
"WebResourceCollection",
"webResourceCollection",
",",
"String",
"resourceName",
",",
"String",
"method",
")",
"{",
"CollectionMatch",
"match",
"=",
"null",
";",
"CollectionM... | Gets the collection match for the web resource collection based on the following custom method algorithm.
<pre>
Custom method matching use case.
Happy path:
1. Validate the resource name matches one of the URL patterns
2. Validate the method matches
3. Return the collection match found
Exceptional path:
1.a If resource name does not match, return RESPONSE_NO_MATCH.
2.a If method does not match, determine that it is listed and return RESPONSE_NO_MATCH.
2.b When method is not listed, the match is null and it is processed by method getMatchResponse turning it into a CUSTOM_NO_MATCH_RESPONSE.
</pre> | [
"Gets",
"the",
"collection",
"match",
"for",
"the",
"web",
"resource",
"collection",
"based",
"on",
"the",
"following",
"custom",
"method",
"algorithm",
".",
"<pre",
">",
"Custom",
"method",
"matching",
"use",
"case",
".",
"Happy",
"path",
":",
"1",
".",
"... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/CustomMatchingStrategy.java#L83-L97 |
dottydingo/hyperion | jpa/src/main/java/com/dottydingo/hyperion/jpa/persistence/query/AbstractEntityJpaQueryBuilder.java | AbstractEntityJpaQueryBuilder.createPredicate | protected Predicate createPredicate(Path root, CriteriaQuery<?> query, CriteriaBuilder cb, String propertyName,
ComparisonOperator operator, Object argument, PersistenceContext context)
{
logger.debug("Creating criterion: {} {} {}", propertyName, operator, argument);
switch (operator)
{
case EQUAL:
{
if (containWildcard(argument))
{
return createLike(root, query, cb, propertyName, argument, context);
}
else
{
return createEqual(root, query, cb, propertyName, argument, context);
}
}
case NOT_EQUAL:
{
if (containWildcard(argument))
{
return createNotLike(root, query, cb, propertyName, argument, context);
}
else
{
return createNotEqual(root, query, cb, propertyName, argument, context);
}
}
case GREATER_THAN:
return createGreaterThan(root, query, cb, propertyName, argument, context);
case GREATER_EQUAL:
return createGreaterEqual(root, query, cb, propertyName, argument, context);
case LESS_THAN:
return createLessThan(root, query, cb, propertyName, argument, context);
case LESS_EQUAL:
return createLessEqual(root, query, cb, propertyName, argument, context);
case IN:
return createIn(root, query, cb, propertyName, argument, context);
case NOT_IN:
return createNotIn(root, query, cb, propertyName, argument, context);
}
throw new IllegalArgumentException("Unknown operator: " + operator);
} | java | protected Predicate createPredicate(Path root, CriteriaQuery<?> query, CriteriaBuilder cb, String propertyName,
ComparisonOperator operator, Object argument, PersistenceContext context)
{
logger.debug("Creating criterion: {} {} {}", propertyName, operator, argument);
switch (operator)
{
case EQUAL:
{
if (containWildcard(argument))
{
return createLike(root, query, cb, propertyName, argument, context);
}
else
{
return createEqual(root, query, cb, propertyName, argument, context);
}
}
case NOT_EQUAL:
{
if (containWildcard(argument))
{
return createNotLike(root, query, cb, propertyName, argument, context);
}
else
{
return createNotEqual(root, query, cb, propertyName, argument, context);
}
}
case GREATER_THAN:
return createGreaterThan(root, query, cb, propertyName, argument, context);
case GREATER_EQUAL:
return createGreaterEqual(root, query, cb, propertyName, argument, context);
case LESS_THAN:
return createLessThan(root, query, cb, propertyName, argument, context);
case LESS_EQUAL:
return createLessEqual(root, query, cb, propertyName, argument, context);
case IN:
return createIn(root, query, cb, propertyName, argument, context);
case NOT_IN:
return createNotIn(root, query, cb, propertyName, argument, context);
}
throw new IllegalArgumentException("Unknown operator: " + operator);
} | [
"protected",
"Predicate",
"createPredicate",
"(",
"Path",
"root",
",",
"CriteriaQuery",
"<",
"?",
">",
"query",
",",
"CriteriaBuilder",
"cb",
",",
"String",
"propertyName",
",",
"ComparisonOperator",
"operator",
",",
"Object",
"argument",
",",
"PersistenceContext",
... | Delegate creating of a Predicate to an appropriate method according to
operator.
@param root root
@param query query
@param propertyName property name
@param operator comparison operator
@param argument argument
@param context context
@return Predicate | [
"Delegate",
"creating",
"of",
"a",
"Predicate",
"to",
"an",
"appropriate",
"method",
"according",
"to",
"operator",
"."
] | train | https://github.com/dottydingo/hyperion/blob/c4d119c90024a88c0335d7d318e9ccdb70149764/jpa/src/main/java/com/dottydingo/hyperion/jpa/persistence/query/AbstractEntityJpaQueryBuilder.java#L43-L86 |
Impetus/Kundera | src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java | ESFilterBuilder.populateBetweenFilter | private QueryBuilder populateBetweenFilter(BetweenExpression betweenExpression, EntityMetadata m)
{
String lowerBoundExpression = getBetweenBoundaryValues(betweenExpression.getLowerBoundExpression());
String upperBoundExpression = getBetweenBoundaryValues(betweenExpression.getUpperBoundExpression());
String field = getField(betweenExpression.getExpression().toParsedText());
log.debug("Between clause for field " + field + "with lower bound " + lowerBoundExpression + "and upper bound "
+ upperBoundExpression);
return new AndQueryBuilder(getFilter(kunderaQuery.new FilterClause(field, Expression.GREATER_THAN_OR_EQUAL,
lowerBoundExpression, field), m), getFilter(kunderaQuery.new FilterClause(field,
Expression.LOWER_THAN_OR_EQUAL, upperBoundExpression,field), m));
} | java | private QueryBuilder populateBetweenFilter(BetweenExpression betweenExpression, EntityMetadata m)
{
String lowerBoundExpression = getBetweenBoundaryValues(betweenExpression.getLowerBoundExpression());
String upperBoundExpression = getBetweenBoundaryValues(betweenExpression.getUpperBoundExpression());
String field = getField(betweenExpression.getExpression().toParsedText());
log.debug("Between clause for field " + field + "with lower bound " + lowerBoundExpression + "and upper bound "
+ upperBoundExpression);
return new AndQueryBuilder(getFilter(kunderaQuery.new FilterClause(field, Expression.GREATER_THAN_OR_EQUAL,
lowerBoundExpression, field), m), getFilter(kunderaQuery.new FilterClause(field,
Expression.LOWER_THAN_OR_EQUAL, upperBoundExpression,field), m));
} | [
"private",
"QueryBuilder",
"populateBetweenFilter",
"(",
"BetweenExpression",
"betweenExpression",
",",
"EntityMetadata",
"m",
")",
"{",
"String",
"lowerBoundExpression",
"=",
"getBetweenBoundaryValues",
"(",
"betweenExpression",
".",
"getLowerBoundExpression",
"(",
")",
")... | Populate between filter.
@param betweenExpression
the between expression
@param m
the m
@param entity
the entity
@return the filter builder | [
"Populate",
"between",
"filter",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java#L253-L265 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/FieldAccessor.java | FieldAccessor.setMapPosition | public void setMapPosition(final Object targetObj, final CellPosition position, final String key) {
ArgUtils.notNull(targetObj, "targetObj");
ArgUtils.notNull(position, "position");
ArgUtils.notEmpty(key, "key");
mapPositionSetter.ifPresent(setter -> setter.set(targetObj, position, key));
} | java | public void setMapPosition(final Object targetObj, final CellPosition position, final String key) {
ArgUtils.notNull(targetObj, "targetObj");
ArgUtils.notNull(position, "position");
ArgUtils.notEmpty(key, "key");
mapPositionSetter.ifPresent(setter -> setter.set(targetObj, position, key));
} | [
"public",
"void",
"setMapPosition",
"(",
"final",
"Object",
"targetObj",
",",
"final",
"CellPosition",
"position",
",",
"final",
"String",
"key",
")",
"{",
"ArgUtils",
".",
"notNull",
"(",
"targetObj",
",",
"\"targetObj\"",
")",
";",
"ArgUtils",
".",
"notNull"... | {@link XlsMapColumns}フィールド用の位置情報を設定します。
<p>位置情報を保持するフィールドがない場合は、処理はスキップされます。</p>
@param targetObj フィールドが定義されているクラスのインスタンス
@param position 位置情報
@param key マップのキー
@throws IllegalArgumentException {@literal targetObj == null or position == null or key == null}
@throws IllegalArgumentException {@literal key is empty.} | [
"{",
"@link",
"XlsMapColumns",
"}",
"フィールド用の位置情報を設定します。",
"<p",
">",
"位置情報を保持するフィールドがない場合は、処理はスキップされます。<",
"/",
"p",
">"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/FieldAccessor.java#L385-L393 |
SimiaCryptus/utilities | java-util/src/main/java/com/simiacryptus/text/CompressionUtil.java | CompressionUtil.decodeLZToString | public static String decodeLZToString(byte[] data, String dictionary) {
try {
return new String(decodeLZ(data), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | java | public static String decodeLZToString(byte[] data, String dictionary) {
try {
return new String(decodeLZ(data), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"String",
"decodeLZToString",
"(",
"byte",
"[",
"]",
"data",
",",
"String",
"dictionary",
")",
"{",
"try",
"{",
"return",
"new",
"String",
"(",
"decodeLZ",
"(",
"data",
")",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedE... | Decode lz to string string.
@param data the data
@param dictionary the dictionary
@return the string | [
"Decode",
"lz",
"to",
"string",
"string",
"."
] | train | https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/text/CompressionUtil.java#L143-L149 |
eclipse/hawkbit | hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/RolloutHelper.java | RolloutHelper.verifyRolloutGroupParameter | public static void verifyRolloutGroupParameter(final int amountGroup, final QuotaManagement quotaManagement) {
if (amountGroup <= 0) {
throw new ValidationException("The amount of groups cannot be lower than zero");
} else if (amountGroup > quotaManagement.getMaxRolloutGroupsPerRollout()) {
throw new QuotaExceededException(
"The amount of groups cannot be greater than " + quotaManagement.getMaxRolloutGroupsPerRollout());
}
} | java | public static void verifyRolloutGroupParameter(final int amountGroup, final QuotaManagement quotaManagement) {
if (amountGroup <= 0) {
throw new ValidationException("The amount of groups cannot be lower than zero");
} else if (amountGroup > quotaManagement.getMaxRolloutGroupsPerRollout()) {
throw new QuotaExceededException(
"The amount of groups cannot be greater than " + quotaManagement.getMaxRolloutGroupsPerRollout());
}
} | [
"public",
"static",
"void",
"verifyRolloutGroupParameter",
"(",
"final",
"int",
"amountGroup",
",",
"final",
"QuotaManagement",
"quotaManagement",
")",
"{",
"if",
"(",
"amountGroup",
"<=",
"0",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"\"The amount of g... | Verify if the supplied amount of groups is in range
@param amountGroup
amount of groups
@param quotaManagement
to retrieve maximum number of groups allowed | [
"Verify",
"if",
"the",
"supplied",
"amount",
"of",
"groups",
"is",
"in",
"range"
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/RolloutHelper.java#L77-L85 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/dnd/CmsDNDHandler.java | CmsDNDHandler.showEndAnimation | private void showEndAnimation(Command callback, int top, int left, boolean isDrop) {
if (!isAnimationEnabled() || (m_dragHelper == null)) {
callback.execute();
return;
}
switch (m_animationType) {
case SPECIAL:
List<Element> overlays = CmsDomUtil.getElementsByClass(
I_CmsLayoutBundle.INSTANCE.generalCss().disablingOverlay(),
m_draggable.getElement());
Element overlay = overlays.size() > 0 ? overlays.get(0) : null;
m_currentAnimation = new SpecialAnimation(
m_dragHelper,
m_draggable.getElement(),
overlay,
callback,
isDrop);
break;
case MOVE:
Element parentElement = m_dragHelper.getParentElement();
int endTop = top - parentElement.getAbsoluteTop();
int endLeft = left - parentElement.getAbsoluteLeft();
int startTop = CmsDomUtil.getCurrentStyleInt(m_dragHelper, Style.top);
int startLeft = CmsDomUtil.getCurrentStyleInt(m_dragHelper, Style.left);
m_currentAnimation = new CmsMoveAnimation(m_dragHelper, startTop, startLeft, endTop, endLeft, callback);
break;
default:
// nothing to do
}
m_currentAnimation.run(400);
} | java | private void showEndAnimation(Command callback, int top, int left, boolean isDrop) {
if (!isAnimationEnabled() || (m_dragHelper == null)) {
callback.execute();
return;
}
switch (m_animationType) {
case SPECIAL:
List<Element> overlays = CmsDomUtil.getElementsByClass(
I_CmsLayoutBundle.INSTANCE.generalCss().disablingOverlay(),
m_draggable.getElement());
Element overlay = overlays.size() > 0 ? overlays.get(0) : null;
m_currentAnimation = new SpecialAnimation(
m_dragHelper,
m_draggable.getElement(),
overlay,
callback,
isDrop);
break;
case MOVE:
Element parentElement = m_dragHelper.getParentElement();
int endTop = top - parentElement.getAbsoluteTop();
int endLeft = left - parentElement.getAbsoluteLeft();
int startTop = CmsDomUtil.getCurrentStyleInt(m_dragHelper, Style.top);
int startLeft = CmsDomUtil.getCurrentStyleInt(m_dragHelper, Style.left);
m_currentAnimation = new CmsMoveAnimation(m_dragHelper, startTop, startLeft, endTop, endLeft, callback);
break;
default:
// nothing to do
}
m_currentAnimation.run(400);
} | [
"private",
"void",
"showEndAnimation",
"(",
"Command",
"callback",
",",
"int",
"top",
",",
"int",
"left",
",",
"boolean",
"isDrop",
")",
"{",
"if",
"(",
"!",
"isAnimationEnabled",
"(",
")",
"||",
"(",
"m_dragHelper",
"==",
"null",
")",
")",
"{",
"callbac... | Shows the end animation on drop or cancel. Executes the given callback afterwards.<p>
@param callback the callback to execute
@param top absolute top of the animation end position
@param left absolute left of the animation end position
@param isDrop if the animation is done on drop | [
"Shows",
"the",
"end",
"animation",
"on",
"drop",
"or",
"cancel",
".",
"Executes",
"the",
"given",
"callback",
"afterwards",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/dnd/CmsDNDHandler.java#L1097-L1131 |
xvik/dropwizard-guicey | src/main/java/ru/vyarus/dropwizard/guice/injector/lookup/InjectorLookup.java | InjectorLookup.registerInjector | public static Managed registerInjector(final Application application, final Injector injector) {
Preconditions.checkNotNull(application, "Application instance required");
Preconditions.checkArgument(!INJECTORS.containsKey(application),
"Injector already registered for application %s", application.getClass().getName());
INJECTORS.put(application, injector);
return new Managed() {
@Override
public void start() throws Exception {
// not used
}
@Override
public void stop() throws Exception {
INJECTORS.remove(application);
}
};
} | java | public static Managed registerInjector(final Application application, final Injector injector) {
Preconditions.checkNotNull(application, "Application instance required");
Preconditions.checkArgument(!INJECTORS.containsKey(application),
"Injector already registered for application %s", application.getClass().getName());
INJECTORS.put(application, injector);
return new Managed() {
@Override
public void start() throws Exception {
// not used
}
@Override
public void stop() throws Exception {
INJECTORS.remove(application);
}
};
} | [
"public",
"static",
"Managed",
"registerInjector",
"(",
"final",
"Application",
"application",
",",
"final",
"Injector",
"injector",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"application",
",",
"\"Application instance required\"",
")",
";",
"Preconditions",
... | Used internally to register application specific injector.
@param application application instance
@param injector injector instance
@return managed object, which must be registered to remove injector on application stop | [
"Used",
"internally",
"to",
"register",
"application",
"specific",
"injector",
"."
] | train | https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/injector/lookup/InjectorLookup.java#L32-L48 |
primefaces-extensions/core | src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java | SheetRenderer.encodeInvalidData | protected void encodeInvalidData(final FacesContext context, final Sheet sheet, final WidgetBuilder wb)
throws IOException {
wb.attr("errors", sheet.getInvalidDataValue());
} | java | protected void encodeInvalidData(final FacesContext context, final Sheet sheet, final WidgetBuilder wb)
throws IOException {
wb.attr("errors", sheet.getInvalidDataValue());
} | [
"protected",
"void",
"encodeInvalidData",
"(",
"final",
"FacesContext",
"context",
",",
"final",
"Sheet",
"sheet",
",",
"final",
"WidgetBuilder",
"wb",
")",
"throws",
"IOException",
"{",
"wb",
".",
"attr",
"(",
"\"errors\"",
",",
"sheet",
".",
"getInvalidDataVal... | Encodes the necessary JS to render invalid data.
@throws IOException | [
"Encodes",
"the",
"necessary",
"JS",
"to",
"render",
"invalid",
"data",
"."
] | train | https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java#L248-L251 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/model/ProcessedInput.java | ProcessedInput.addParameter | public void addParameter(String parameterName, int parameterStart, int parameterEnd) {
addParameter(parameterName, parameterStart, parameterEnd, null, null);
} | java | public void addParameter(String parameterName, int parameterStart, int parameterEnd) {
addParameter(parameterName, parameterStart, parameterEnd, null, null);
} | [
"public",
"void",
"addParameter",
"(",
"String",
"parameterName",
",",
"int",
"parameterStart",
",",
"int",
"parameterEnd",
")",
"{",
"addParameter",
"(",
"parameterName",
",",
"parameterStart",
",",
"parameterEnd",
",",
"null",
",",
"null",
")",
";",
"}"
] | Adds parameter into list of input SQL parameters
@param parameterName Parameter name
@param parameterStart Character position at which parameter starts
@param parameterEnd Character position at which parameter ends | [
"Adds",
"parameter",
"into",
"list",
"of",
"input",
"SQL",
"parameters"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/model/ProcessedInput.java#L163-L165 |
jMetal/jMetal | jmetal-core/src/main/java/org/uma/jmetal/util/measure/impl/SimpleMeasureManager.java | SimpleMeasureManager.setMeasure | public void setMeasure(Object key, Measure<?> measure) {
if (measure instanceof PullMeasure) {
setPullMeasure(key, (PullMeasure<?>) measure);
}
if (measure instanceof PushMeasure) {
setPushMeasure(key, (PushMeasure<?>) measure);
}
} | java | public void setMeasure(Object key, Measure<?> measure) {
if (measure instanceof PullMeasure) {
setPullMeasure(key, (PullMeasure<?>) measure);
}
if (measure instanceof PushMeasure) {
setPushMeasure(key, (PushMeasure<?>) measure);
}
} | [
"public",
"void",
"setMeasure",
"(",
"Object",
"key",
",",
"Measure",
"<",
"?",
">",
"measure",
")",
"{",
"if",
"(",
"measure",
"instanceof",
"PullMeasure",
")",
"{",
"setPullMeasure",
"(",
"key",
",",
"(",
"PullMeasure",
"<",
"?",
">",
")",
"measure",
... | This method call {@link #setPullMeasure(Object, PullMeasure)} or
{@link #setPushMeasure(Object, PushMeasure)} depending on the interfaces
implemented by the {@link Measure} given in argument. If both interfaces
are implemented, both methods are called, allowing to register all the
aspects of the {@link Measure} in one call.
@param key
the key of the {@link Measure}
@param measure
the {@link Measure} to register | [
"This",
"method",
"call",
"{",
"@link",
"#setPullMeasure",
"(",
"Object",
"PullMeasure",
")",
"}",
"or",
"{",
"@link",
"#setPushMeasure",
"(",
"Object",
"PushMeasure",
")",
"}",
"depending",
"on",
"the",
"interfaces",
"implemented",
"by",
"the",
"{",
"@link",
... | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/util/measure/impl/SimpleMeasureManager.java#L126-L133 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/Signature.java | Signature.initSign | public final void initSign(PrivateKey privateKey, SecureRandom random)
throws InvalidKeyException {
engineInitSign(privateKey, random);
state = SIGN;
// BEGIN Android-removed: this debugging mechanism is not supported in Android.
/*
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" signing algorithm from: " + this.provider.getName());
}
*/
// END Android-removed: this debugging mechanism is not supported in Android.
} | java | public final void initSign(PrivateKey privateKey, SecureRandom random)
throws InvalidKeyException {
engineInitSign(privateKey, random);
state = SIGN;
// BEGIN Android-removed: this debugging mechanism is not supported in Android.
/*
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" signing algorithm from: " + this.provider.getName());
}
*/
// END Android-removed: this debugging mechanism is not supported in Android.
} | [
"public",
"final",
"void",
"initSign",
"(",
"PrivateKey",
"privateKey",
",",
"SecureRandom",
"random",
")",
"throws",
"InvalidKeyException",
"{",
"engineInitSign",
"(",
"privateKey",
",",
"random",
")",
";",
"state",
"=",
"SIGN",
";",
"// BEGIN Android-removed: this... | Initialize this object for signing. If this method is called
again with a different argument, it negates the effect
of this call.
@param privateKey the private key of the identity whose signature
is going to be generated.
@param random the source of randomness for this signature.
@exception InvalidKeyException if the key is invalid. | [
"Initialize",
"this",
"object",
"for",
"signing",
".",
"If",
"this",
"method",
"is",
"called",
"again",
"with",
"a",
"different",
"argument",
"it",
"negates",
"the",
"effect",
"of",
"this",
"call",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/Signature.java#L699-L712 |
thinkaurelius/titan | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/database/management/RelationIndexStatusWatcher.java | RelationIndexStatusWatcher.call | @Override
public RelationIndexStatusReport call() throws InterruptedException {
Preconditions.checkNotNull(g, "Graph instance must not be null");
Preconditions.checkNotNull(relationIndexName, "Index name must not be null");
Preconditions.checkNotNull(status, "Target status must not be null");
RelationTypeIndex idx;
Timer t = new Timer(TimestampProviders.MILLI).start();
boolean timedOut;
while (true) {
SchemaStatus actualStatus = null;
TitanManagement mgmt = null;
try {
mgmt = g.openManagement();
idx = mgmt.getRelationIndex(mgmt.getRelationType(relationTypeName), relationIndexName);
actualStatus = idx.getIndexStatus();
LOGGER.info("Index {} (relation type {}) has status {}", relationIndexName, relationTypeName, actualStatus);
if (status.equals(actualStatus)) {
return new RelationIndexStatusReport(true, relationIndexName, relationTypeName, actualStatus, status, t.elapsed());
}
} finally {
if (null != mgmt)
mgmt.rollback(); // Let an exception here propagate up the stack
}
timedOut = null != timeout && 0 < t.elapsed().compareTo(timeout);
if (timedOut) {
LOGGER.info("Timed out ({}) while waiting for index {} (relation type {}) to reach status {}",
timeout, relationIndexName, relationTypeName, status);
return new RelationIndexStatusReport(false, relationIndexName, relationTypeName, actualStatus, status, t.elapsed());
}
Thread.sleep(poll.toMillis());
}
} | java | @Override
public RelationIndexStatusReport call() throws InterruptedException {
Preconditions.checkNotNull(g, "Graph instance must not be null");
Preconditions.checkNotNull(relationIndexName, "Index name must not be null");
Preconditions.checkNotNull(status, "Target status must not be null");
RelationTypeIndex idx;
Timer t = new Timer(TimestampProviders.MILLI).start();
boolean timedOut;
while (true) {
SchemaStatus actualStatus = null;
TitanManagement mgmt = null;
try {
mgmt = g.openManagement();
idx = mgmt.getRelationIndex(mgmt.getRelationType(relationTypeName), relationIndexName);
actualStatus = idx.getIndexStatus();
LOGGER.info("Index {} (relation type {}) has status {}", relationIndexName, relationTypeName, actualStatus);
if (status.equals(actualStatus)) {
return new RelationIndexStatusReport(true, relationIndexName, relationTypeName, actualStatus, status, t.elapsed());
}
} finally {
if (null != mgmt)
mgmt.rollback(); // Let an exception here propagate up the stack
}
timedOut = null != timeout && 0 < t.elapsed().compareTo(timeout);
if (timedOut) {
LOGGER.info("Timed out ({}) while waiting for index {} (relation type {}) to reach status {}",
timeout, relationIndexName, relationTypeName, status);
return new RelationIndexStatusReport(false, relationIndexName, relationTypeName, actualStatus, status, t.elapsed());
}
Thread.sleep(poll.toMillis());
}
} | [
"@",
"Override",
"public",
"RelationIndexStatusReport",
"call",
"(",
")",
"throws",
"InterruptedException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"g",
",",
"\"Graph instance must not be null\"",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"relationInd... | Poll a relation index until it has a certain {@link SchemaStatus},
or until a configurable timeout is exceeded.
@return a report with information about schema state, execution duration, and the index | [
"Poll",
"a",
"relation",
"index",
"until",
"it",
"has",
"a",
"certain",
"{",
"@link",
"SchemaStatus",
"}",
"or",
"until",
"a",
"configurable",
"timeout",
"is",
"exceeded",
"."
] | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/database/management/RelationIndexStatusWatcher.java#L38-L74 |
likethecolor/Alchemy-API | src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java | AbstractParser.getLong | protected Long getLong(final String key, final JSONObject jsonObject) {
Long value = null;
if(hasKey(key, jsonObject)) {
try {
value = jsonObject.getLong(key);
}
catch(JSONException e) {
LOGGER.error("Could not get Long from JSONObject for key: " + key, e);
}
}
return value;
} | java | protected Long getLong(final String key, final JSONObject jsonObject) {
Long value = null;
if(hasKey(key, jsonObject)) {
try {
value = jsonObject.getLong(key);
}
catch(JSONException e) {
LOGGER.error("Could not get Long from JSONObject for key: " + key, e);
}
}
return value;
} | [
"protected",
"Long",
"getLong",
"(",
"final",
"String",
"key",
",",
"final",
"JSONObject",
"jsonObject",
")",
"{",
"Long",
"value",
"=",
"null",
";",
"if",
"(",
"hasKey",
"(",
"key",
",",
"jsonObject",
")",
")",
"{",
"try",
"{",
"value",
"=",
"jsonObje... | Check to make sure the JSONObject has the specified key and if so return
the value as a long. If no key is found null is returned.
@param key name of the field to fetch from the json object
@param jsonObject object from which to fetch the value
@return long value corresponding to the key or null if key not found | [
"Check",
"to",
"make",
"sure",
"the",
"JSONObject",
"has",
"the",
"specified",
"key",
"and",
"if",
"so",
"return",
"the",
"value",
"as",
"a",
"long",
".",
"If",
"no",
"key",
"is",
"found",
"null",
"is",
"returned",
"."
] | train | https://github.com/likethecolor/Alchemy-API/blob/5208cfc92a878ceeaff052787af29da92d98db7e/src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java#L186-L197 |
fommil/matrix-toolkits-java | src/main/java/no/uib/cipr/matrix/LowerTriangPackMatrix.java | LowerTriangPackMatrix.getIndex | int getIndex(int row, int column) {
check(row, column);
return row + (2 * n - (column + 1)) * column / 2;
} | java | int getIndex(int row, int column) {
check(row, column);
return row + (2 * n - (column + 1)) * column / 2;
} | [
"int",
"getIndex",
"(",
"int",
"row",
",",
"int",
"column",
")",
"{",
"check",
"(",
"row",
",",
"column",
")",
";",
"return",
"row",
"+",
"(",
"2",
"*",
"n",
"-",
"(",
"column",
"+",
"1",
")",
")",
"*",
"column",
"/",
"2",
";",
"}"
] | Checks the row and column indices, and returns the linear data index | [
"Checks",
"the",
"row",
"and",
"column",
"indices",
"and",
"returns",
"the",
"linear",
"data",
"index"
] | train | https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/LowerTriangPackMatrix.java#L163-L166 |
Stratio/deep-spark | deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java | Cells.getValue | public <T> T getValue(String nameSpace, String cellName, Class<T> cellClass) {
Cell cell = getCellByName(nameSpace, cellName);
return cell == null ? null : cell.getValue(cellClass);
} | java | public <T> T getValue(String nameSpace, String cellName, Class<T> cellClass) {
Cell cell = getCellByName(nameSpace, cellName);
return cell == null ? null : cell.getValue(cellClass);
} | [
"public",
"<",
"T",
">",
"T",
"getValue",
"(",
"String",
"nameSpace",
",",
"String",
"cellName",
",",
"Class",
"<",
"T",
">",
"cellClass",
")",
"{",
"Cell",
"cell",
"=",
"getCellByName",
"(",
"nameSpace",
",",
"cellName",
")",
";",
"return",
"cell",
"=... | Returns the casted value of the {@link Cell} (associated to {@code table}) whose name is cellName, or null if
this Cells object contains no cell whose name is cellName.
@param nameSpace the name of the owning table
@param cellName the name of the Cell we want to retrieve from this Cells object.
@param cellClass the class of the cell's value
@param <T> the type of the cell's value
@return the casted value of the {@link Cell} (associated to {@code table}) whose name is cellName, or null if
this Cells object contains no cell whose name is cellName | [
"Returns",
"the",
"casted",
"value",
"of",
"the",
"{",
"@link",
"Cell",
"}",
"(",
"associated",
"to",
"{",
"@code",
"table",
"}",
")",
"whose",
"name",
"is",
"cellName",
"or",
"null",
"if",
"this",
"Cells",
"object",
"contains",
"no",
"cell",
"whose",
... | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java#L621-L624 |
graknlabs/grakn | server/src/server/session/TransactionOLTP.java | TransactionOLTP.addTypeVertex | protected VertexElement addTypeVertex(LabelId id, Label label, Schema.BaseType baseType) {
VertexElement vertexElement = addVertexElement(baseType);
vertexElement.property(Schema.VertexProperty.SCHEMA_LABEL, label.getValue());
vertexElement.property(Schema.VertexProperty.LABEL_ID, id.getValue());
return vertexElement;
} | java | protected VertexElement addTypeVertex(LabelId id, Label label, Schema.BaseType baseType) {
VertexElement vertexElement = addVertexElement(baseType);
vertexElement.property(Schema.VertexProperty.SCHEMA_LABEL, label.getValue());
vertexElement.property(Schema.VertexProperty.LABEL_ID, id.getValue());
return vertexElement;
} | [
"protected",
"VertexElement",
"addTypeVertex",
"(",
"LabelId",
"id",
",",
"Label",
"label",
",",
"Schema",
".",
"BaseType",
"baseType",
")",
"{",
"VertexElement",
"vertexElement",
"=",
"addVertexElement",
"(",
"baseType",
")",
";",
"vertexElement",
".",
"property"... | Adds a new type vertex which occupies a grakn id. This result in the grakn id count on the meta concept to be
incremented.
@param label The label of the new type vertex
@param baseType The base type of the new type
@return The new type vertex | [
"Adds",
"a",
"new",
"type",
"vertex",
"which",
"occupies",
"a",
"grakn",
"id",
".",
"This",
"result",
"in",
"the",
"grakn",
"id",
"count",
"on",
"the",
"meta",
"concept",
"to",
"be",
"incremented",
"."
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/TransactionOLTP.java#L463-L468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.