repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
ops4j/org.ops4j.base | ops4j-base-lang/src/main/java/org/ops4j/lang/PreConditionException.java | PreConditionException.validateNotNull | public static void validateNotNull( Object object, String identifier )
throws PreConditionException
{
if( object == null )
{
throw new PreConditionException( identifier + " was NULL." );
}
} | java | public static void validateNotNull( Object object, String identifier )
throws PreConditionException
{
if( object == null )
{
throw new PreConditionException( identifier + " was NULL." );
}
} | [
"public",
"static",
"void",
"validateNotNull",
"(",
"Object",
"object",
",",
"String",
"identifier",
")",
"throws",
"PreConditionException",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"throw",
"new",
"PreConditionException",
"(",
"identifier",
"+",
"\" wa... | Validates that the object is not null.
@param object The object to be validated.
@param identifier The name of the object.
@throws PreConditionException if the object is null. | [
"Validates",
"that",
"the",
"object",
"is",
"not",
"null",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-lang/src/main/java/org/ops4j/lang/PreConditionException.java#L47-L54 |
OpenBEL/openbel-framework | org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/beldata/equivalence/EquivalenceHeaderParser.java | EquivalenceHeaderParser.parseEquivalence | public EquivalenceHeader parseEquivalence(String resourceLocation,
File equivalenceFile) throws IOException,
BELDataMissingPropertyException,
BELDataConversionException {
if (equivalenceFile == null) {
throw new InvalidArgument("namespaceFile", equivalenceFile);
}
if (!equivalenceFile.exists()) {
throw new InvalidArgument("namespaceFile does not exist");
}
if (!equivalenceFile.canRead()) {
throw new InvalidArgument("namespaceFile cannot be read");
}
Map<String, Properties> blockProperties = parse(equivalenceFile);
EquivalenceBlock equivalenceBlock =
EquivalenceBlock.create(resourceLocation,
blockProperties.get(EquivalenceBlock.BLOCK_NAME));
NamespaceReferenceBlock namespaceReferenceBlock =
NamespaceReferenceBlock
.create(resourceLocation,
blockProperties
.get(NamespaceReferenceBlock.BLOCK_NAME));
AuthorBlock authorblock = AuthorBlock.create(resourceLocation,
blockProperties.get(AuthorBlock.BLOCK_NAME));
CitationBlock citationBlock = CitationBlock.create(resourceLocation,
blockProperties.get(CitationBlock.BLOCK_NAME));
ProcessingBlock processingBlock = ProcessingBlock.create(
resourceLocation,
blockProperties.get(ProcessingBlock.BLOCK_NAME));
return new EquivalenceHeader(equivalenceBlock, namespaceReferenceBlock,
authorblock, citationBlock, processingBlock);
} | java | public EquivalenceHeader parseEquivalence(String resourceLocation,
File equivalenceFile) throws IOException,
BELDataMissingPropertyException,
BELDataConversionException {
if (equivalenceFile == null) {
throw new InvalidArgument("namespaceFile", equivalenceFile);
}
if (!equivalenceFile.exists()) {
throw new InvalidArgument("namespaceFile does not exist");
}
if (!equivalenceFile.canRead()) {
throw new InvalidArgument("namespaceFile cannot be read");
}
Map<String, Properties> blockProperties = parse(equivalenceFile);
EquivalenceBlock equivalenceBlock =
EquivalenceBlock.create(resourceLocation,
blockProperties.get(EquivalenceBlock.BLOCK_NAME));
NamespaceReferenceBlock namespaceReferenceBlock =
NamespaceReferenceBlock
.create(resourceLocation,
blockProperties
.get(NamespaceReferenceBlock.BLOCK_NAME));
AuthorBlock authorblock = AuthorBlock.create(resourceLocation,
blockProperties.get(AuthorBlock.BLOCK_NAME));
CitationBlock citationBlock = CitationBlock.create(resourceLocation,
blockProperties.get(CitationBlock.BLOCK_NAME));
ProcessingBlock processingBlock = ProcessingBlock.create(
resourceLocation,
blockProperties.get(ProcessingBlock.BLOCK_NAME));
return new EquivalenceHeader(equivalenceBlock, namespaceReferenceBlock,
authorblock, citationBlock, processingBlock);
} | [
"public",
"EquivalenceHeader",
"parseEquivalence",
"(",
"String",
"resourceLocation",
",",
"File",
"equivalenceFile",
")",
"throws",
"IOException",
",",
"BELDataMissingPropertyException",
",",
"BELDataConversionException",
"{",
"if",
"(",
"equivalenceFile",
"==",
"null",
... | Parses the equivalence {@link File} into a {@link EquivalenceHeader} object.
@param equivalenceFile {@link File}, the equivalence file, which cannot be
null, must exist, and must be readable
@return {@link NamespaceHeader}, the parsed equivalence header
@throws IOException Thrown if an IO error occurred reading the
<tt>equivalenceFile</tt>
@throws BELDataHeaderParseException Thrown if a parsing error occurred
when processing the <tt>equivalenceFile</tt>
@throws BELDataConversionException
@throws BELDataMissingPropertyException
@throws InvalidArgument Thrown if the <tt>equivalenceFile</tt> is null,
does not exist, or cannot be read | [
"Parses",
"the",
"equivalence",
"{",
"@link",
"File",
"}",
"into",
"a",
"{",
"@link",
"EquivalenceHeader",
"}",
"object",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/beldata/equivalence/EquivalenceHeaderParser.java#L75-L115 |
jenkinsci/jenkins | core/src/main/java/hudson/model/ViewDescriptor.java | ViewDescriptor.doAutoCompleteCopyNewItemFrom | @Restricted(DoNotUse.class)
public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value, @AncestorInPath ItemGroup<?> container) {
AutoCompletionCandidates candidates = AutoCompletionCandidates.ofJobNames(TopLevelItem.class, value, container);
if (container instanceof DirectlyModifiableTopLevelItemGroup) {
DirectlyModifiableTopLevelItemGroup modifiableContainer = (DirectlyModifiableTopLevelItemGroup) container;
Iterator<String> it = candidates.getValues().iterator();
while (it.hasNext()) {
TopLevelItem item = Jenkins.getInstance().getItem(it.next(), container, TopLevelItem.class);
if (item == null) {
continue; // ?
}
if (!modifiableContainer.canAdd(item)) {
it.remove();
}
}
}
return candidates;
} | java | @Restricted(DoNotUse.class)
public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value, @AncestorInPath ItemGroup<?> container) {
AutoCompletionCandidates candidates = AutoCompletionCandidates.ofJobNames(TopLevelItem.class, value, container);
if (container instanceof DirectlyModifiableTopLevelItemGroup) {
DirectlyModifiableTopLevelItemGroup modifiableContainer = (DirectlyModifiableTopLevelItemGroup) container;
Iterator<String> it = candidates.getValues().iterator();
while (it.hasNext()) {
TopLevelItem item = Jenkins.getInstance().getItem(it.next(), container, TopLevelItem.class);
if (item == null) {
continue; // ?
}
if (!modifiableContainer.canAdd(item)) {
it.remove();
}
}
}
return candidates;
} | [
"@",
"Restricted",
"(",
"DoNotUse",
".",
"class",
")",
"public",
"AutoCompletionCandidates",
"doAutoCompleteCopyNewItemFrom",
"(",
"@",
"QueryParameter",
"final",
"String",
"value",
",",
"@",
"AncestorInPath",
"ItemGroup",
"<",
"?",
">",
"container",
")",
"{",
"Au... | Auto-completion for the "copy from" field in the new job page. | [
"Auto",
"-",
"completion",
"for",
"the",
"copy",
"from",
"field",
"in",
"the",
"new",
"job",
"page",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/ViewDescriptor.java#L87-L104 |
OpenLiberty/open-liberty | dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java | AuditEvent.setObserver | public void setObserver(Map<String, Object> observer) {
removeEntriesStartingWith(OBSERVER);
eventMap.putAll(observer);
} | java | public void setObserver(Map<String, Object> observer) {
removeEntriesStartingWith(OBSERVER);
eventMap.putAll(observer);
} | [
"public",
"void",
"setObserver",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"observer",
")",
"{",
"removeEntriesStartingWith",
"(",
"OBSERVER",
")",
";",
"eventMap",
".",
"putAll",
"(",
"observer",
")",
";",
"}"
] | Set the observer keys/values. The provided Map will completely replace
the existing observer, i.e. all current observer keys/values will be removed
and the new observer keys/values will be added.
@param observer - Map of all the observer keys/values | [
"Set",
"the",
"observer",
"keys",
"/",
"values",
".",
"The",
"provided",
"Map",
"will",
"completely",
"replace",
"the",
"existing",
"observer",
"i",
".",
"e",
".",
"all",
"current",
"observer",
"keys",
"/",
"values",
"will",
"be",
"removed",
"and",
"the",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java#L315-L318 |
biojava/biojava | biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java | TranscriptSequence.addCDS | public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) throws Exception {
if (cdsSequenceHashMap.containsKey(accession.getID())) {
throw new Exception("Duplicate accesion id " + accession.getID());
}
CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase); //sense should be the same as parent
cdsSequence.setAccession(accession);
cdsSequenceList.add(cdsSequence);
Collections.sort(cdsSequenceList, new CDSComparator());
cdsSequenceHashMap.put(accession.getID(), cdsSequence);
return cdsSequence;
} | java | public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) throws Exception {
if (cdsSequenceHashMap.containsKey(accession.getID())) {
throw new Exception("Duplicate accesion id " + accession.getID());
}
CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase); //sense should be the same as parent
cdsSequence.setAccession(accession);
cdsSequenceList.add(cdsSequence);
Collections.sort(cdsSequenceList, new CDSComparator());
cdsSequenceHashMap.put(accession.getID(), cdsSequence);
return cdsSequence;
} | [
"public",
"CDSSequence",
"addCDS",
"(",
"AccessionID",
"accession",
",",
"int",
"begin",
",",
"int",
"end",
",",
"int",
"phase",
")",
"throws",
"Exception",
"{",
"if",
"(",
"cdsSequenceHashMap",
".",
"containsKey",
"(",
"accession",
".",
"getID",
"(",
")",
... | Add a Coding Sequence region with phase to the transcript sequence
@param accession
@param begin
@param end
@param phase 0,1,2
@return | [
"Add",
"a",
"Coding",
"Sequence",
"region",
"with",
"phase",
"to",
"the",
"transcript",
"sequence"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java#L109-L119 |
phax/ph-schedule | ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java | DateBuilder.translateTime | public static Date translateTime (final Date date, final TimeZone aSrcTZ, final TimeZone aDestTZ)
{
final Date newDate = new Date ();
final int offset = aDestTZ.getOffset (date.getTime ()) - aSrcTZ.getOffset (date.getTime ());
newDate.setTime (date.getTime () - offset);
return newDate;
} | java | public static Date translateTime (final Date date, final TimeZone aSrcTZ, final TimeZone aDestTZ)
{
final Date newDate = new Date ();
final int offset = aDestTZ.getOffset (date.getTime ()) - aSrcTZ.getOffset (date.getTime ());
newDate.setTime (date.getTime () - offset);
return newDate;
} | [
"public",
"static",
"Date",
"translateTime",
"(",
"final",
"Date",
"date",
",",
"final",
"TimeZone",
"aSrcTZ",
",",
"final",
"TimeZone",
"aDestTZ",
")",
"{",
"final",
"Date",
"newDate",
"=",
"new",
"Date",
"(",
")",
";",
"final",
"int",
"offset",
"=",
"a... | Translate a date & time from a users time zone to the another (probably
server) time zone to assist in creating a simple trigger with the right
date & time.
@param date
the date to translate
@param aSrcTZ
the original time-zone
@param aDestTZ
the destination time-zone
@return the translated date | [
"Translate",
"a",
"date",
"&",
";",
"time",
"from",
"a",
"users",
"time",
"zone",
"to",
"the",
"another",
"(",
"probably",
"server",
")",
"time",
"zone",
"to",
"assist",
"in",
"creating",
"a",
"simple",
"trigger",
"with",
"the",
"right",
"date",
"&... | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java#L916-L922 |
jbundle/jbundle | thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageFilter.java | BaseMessageFilter.updateFilterTree | public final void updateFilterTree(Map<String, Object> propTree)
{
Object[][] mxProperties = this.cloneMatrix(this.getNameValueTree());
mxProperties = this.createNameValueTree(mxProperties, propTree); // Update these properties
this.setFilterTree(mxProperties); // Update any remote copy of this.
} | java | public final void updateFilterTree(Map<String, Object> propTree)
{
Object[][] mxProperties = this.cloneMatrix(this.getNameValueTree());
mxProperties = this.createNameValueTree(mxProperties, propTree); // Update these properties
this.setFilterTree(mxProperties); // Update any remote copy of this.
} | [
"public",
"final",
"void",
"updateFilterTree",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"propTree",
")",
"{",
"Object",
"[",
"]",
"[",
"]",
"mxProperties",
"=",
"this",
".",
"cloneMatrix",
"(",
"this",
".",
"getNameValueTree",
"(",
")",
")",
";",
... | Update this object's filter with this new tree information.
@param propTree Changes to the current property tree. | [
"Update",
"this",
"object",
"s",
"filter",
"with",
"this",
"new",
"tree",
"information",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageFilter.java#L446-L451 |
hedyn/wsonrpc | wsonrpc-core/src/main/java/net/apexes/wsonrpc/core/JsonRpcControl.java | JsonRpcControl.receiveRequest | public void receiveRequest(byte[] bytes, Transport transport) throws IOException, WsonrpcException {
JsonRpcResponse resp;
try {
JsonRpcMessage msg = receive(bytes);
if (msg instanceof JsonRpcRequest) {
JsonRpcRequest req = (JsonRpcRequest) msg;
resp = execute(req);
} else {
resp = new JsonRpcResponse(null, JsonRpcError.invalidRequestError(null));
}
} catch (JsonException e) {
resp = new JsonRpcResponse(null, JsonRpcError.parseError(e));
} catch (IOException e) {
resp = new JsonRpcResponse(null, JsonRpcError.internalError(e));
}
transmit(transport, resp);
} | java | public void receiveRequest(byte[] bytes, Transport transport) throws IOException, WsonrpcException {
JsonRpcResponse resp;
try {
JsonRpcMessage msg = receive(bytes);
if (msg instanceof JsonRpcRequest) {
JsonRpcRequest req = (JsonRpcRequest) msg;
resp = execute(req);
} else {
resp = new JsonRpcResponse(null, JsonRpcError.invalidRequestError(null));
}
} catch (JsonException e) {
resp = new JsonRpcResponse(null, JsonRpcError.parseError(e));
} catch (IOException e) {
resp = new JsonRpcResponse(null, JsonRpcError.internalError(e));
}
transmit(transport, resp);
} | [
"public",
"void",
"receiveRequest",
"(",
"byte",
"[",
"]",
"bytes",
",",
"Transport",
"transport",
")",
"throws",
"IOException",
",",
"WsonrpcException",
"{",
"JsonRpcResponse",
"resp",
";",
"try",
"{",
"JsonRpcMessage",
"msg",
"=",
"receive",
"(",
"bytes",
")... | 接收远端的调用请求,并将回复执行结果。
@param bytes 接收到的数据
@param transport {@link Transport} 实例
@throws IOException
@throws WsonrpcException | [
"接收远端的调用请求,并将回复执行结果。"
] | train | https://github.com/hedyn/wsonrpc/blob/decbaad4cb8145590bab039d5cfe12437ada0d0a/wsonrpc-core/src/main/java/net/apexes/wsonrpc/core/JsonRpcControl.java#L65-L81 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/reader/ReaderElement.java | ReaderElement.hasTag | public boolean hasTag(List<String> keyList, Set<String> values) {
for (String key : keyList) {
if (values.contains(getTag(key, "")))
return true;
}
return false;
} | java | public boolean hasTag(List<String> keyList, Set<String> values) {
for (String key : keyList) {
if (values.contains(getTag(key, "")))
return true;
}
return false;
} | [
"public",
"boolean",
"hasTag",
"(",
"List",
"<",
"String",
">",
"keyList",
",",
"Set",
"<",
"String",
">",
"values",
")",
"{",
"for",
"(",
"String",
"key",
":",
"keyList",
")",
"{",
"if",
"(",
"values",
".",
"contains",
"(",
"getTag",
"(",
"key",
"... | Check a number of tags in the given order for the any of the given values. Used to parse
hierarchical access restrictions | [
"Check",
"a",
"number",
"of",
"tags",
"in",
"the",
"given",
"order",
"for",
"the",
"any",
"of",
"the",
"given",
"values",
".",
"Used",
"to",
"parse",
"hierarchical",
"access",
"restrictions"
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/ReaderElement.java#L140-L146 |
m-m-m/util | pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java | PojoDescriptorBuilderImpl.mergePropertyDescriptorWithSuperClass | private void mergePropertyDescriptorWithSuperClass(PojoPropertyDescriptorImpl propertyDescriptor, PojoPropertyDescriptorImpl superPropertyDescriptor) {
for (PojoPropertyAccessor superPropertyAccessor : superPropertyDescriptor.getAccessors()) {
PojoPropertyAccessor propertyAccessor = propertyDescriptor.getAccessor(superPropertyAccessor.getMode());
if (propertyAccessor == null) {
propertyDescriptor.putAccessor(superPropertyAccessor);
}
}
Field field = superPropertyDescriptor.getField();
if ((field != null) && (propertyDescriptor.getField() == null)) {
propertyDescriptor.setField(field);
}
} | java | private void mergePropertyDescriptorWithSuperClass(PojoPropertyDescriptorImpl propertyDescriptor, PojoPropertyDescriptorImpl superPropertyDescriptor) {
for (PojoPropertyAccessor superPropertyAccessor : superPropertyDescriptor.getAccessors()) {
PojoPropertyAccessor propertyAccessor = propertyDescriptor.getAccessor(superPropertyAccessor.getMode());
if (propertyAccessor == null) {
propertyDescriptor.putAccessor(superPropertyAccessor);
}
}
Field field = superPropertyDescriptor.getField();
if ((field != null) && (propertyDescriptor.getField() == null)) {
propertyDescriptor.setField(field);
}
} | [
"private",
"void",
"mergePropertyDescriptorWithSuperClass",
"(",
"PojoPropertyDescriptorImpl",
"propertyDescriptor",
",",
"PojoPropertyDescriptorImpl",
"superPropertyDescriptor",
")",
"{",
"for",
"(",
"PojoPropertyAccessor",
"superPropertyAccessor",
":",
"superPropertyDescriptor",
... | This method merges the {@code superPropertyDescriptor} into the {@code propertyDescriptor}.
@param propertyDescriptor is the {@link PojoPropertyDescriptorImpl} to build for the
{@link net.sf.mmm.util.pojo.api.Pojo}.
@param superPropertyDescriptor is the super {@link PojoPropertyDescriptorImpl} to "inherit" from. | [
"This",
"method",
"merges",
"the",
"{",
"@code",
"superPropertyDescriptor",
"}",
"into",
"the",
"{",
"@code",
"propertyDescriptor",
"}",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java#L370-L383 |
kaazing/java.client | amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/AmqpClient.java | AmqpClient.tuneOkConnection | AmqpClient tuneOkConnection(int channelMax, int frameMax, int heartbeat) {
this.tuneOkConnection(channelMax, frameMax, heartbeat, null, null);
return this;
} | java | AmqpClient tuneOkConnection(int channelMax, int frameMax, int heartbeat) {
this.tuneOkConnection(channelMax, frameMax, heartbeat, null, null);
return this;
} | [
"AmqpClient",
"tuneOkConnection",
"(",
"int",
"channelMax",
",",
"int",
"frameMax",
",",
"int",
"heartbeat",
")",
"{",
"this",
".",
"tuneOkConnection",
"(",
"channelMax",
",",
"frameMax",
",",
"heartbeat",
",",
"null",
",",
"null",
")",
";",
"return",
"this"... | Sends a TuneOkConnection to server.
@param channelMax
@param frameMax
@param heartbeat
@return AmqpClient | [
"Sends",
"a",
"TuneOkConnection",
"to",
"server",
"."
] | train | https://github.com/kaazing/java.client/blob/25ad2ae5bb24aa9d6b79400fce649b518dcfbe26/amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/AmqpClient.java#L814-L817 |
denisneuling/apitrary.jar | apitrary-orm/apitrary-orm-core/src/main/java/com/apitrary/orm/core/unmarshalling/JsonResponseConsumer.java | JsonResponseConsumer.onDouble | protected void onDouble(Double floating, String fieldName, JsonParser jp) {
log.trace(fieldName + " " + floating);
} | java | protected void onDouble(Double floating, String fieldName, JsonParser jp) {
log.trace(fieldName + " " + floating);
} | [
"protected",
"void",
"onDouble",
"(",
"Double",
"floating",
",",
"String",
"fieldName",
",",
"JsonParser",
"jp",
")",
"{",
"log",
".",
"trace",
"(",
"fieldName",
"+",
"\" \"",
"+",
"floating",
")",
";",
"}"
] | <p>
onDouble.
</p>
@param floating
a {@link java.lang.Double} object.
@param fieldName
a {@link java.lang.String} object.
@param jp
a {@link org.codehaus.jackson.JsonParser} object. | [
"<p",
">",
"onDouble",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/denisneuling/apitrary.jar/blob/b7f639a1e735c60ba2b1b62851926757f5de8628/apitrary-orm/apitrary-orm-core/src/main/java/com/apitrary/orm/core/unmarshalling/JsonResponseConsumer.java#L250-L252 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java | SparkUtils.balancedRandomSplit | public static <T> JavaRDD<T>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit, JavaRDD<T> data) {
return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong());
} | java | public static <T> JavaRDD<T>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit, JavaRDD<T> data) {
return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong());
} | [
"public",
"static",
"<",
"T",
">",
"JavaRDD",
"<",
"T",
">",
"[",
"]",
"balancedRandomSplit",
"(",
"int",
"totalObjectCount",
",",
"int",
"numObjectsPerSplit",
",",
"JavaRDD",
"<",
"T",
">",
"data",
")",
"{",
"return",
"balancedRandomSplit",
"(",
"totalObjec... | Random split the specified RDD into a number of RDDs, where each has {@code numObjectsPerSplit} in them.
<p>
This similar to how RDD.randomSplit works (i.e., split via filtering), but this should result in more
equal splits (instead of independent binomial sampling that is used there, based on weighting)
This balanced splitting approach is important when the number of DataSet objects we want in each split is small,
as random sampling variance of {@link JavaRDD#randomSplit(double[])} is quite large relative to the number of examples
in each split. Note however that this method doesn't <i>guarantee</i> that partitions will be balanced
<p>
Downside is we need total object count (whereas {@link JavaRDD#randomSplit(double[])} does not). However, randomSplit
requires a full pass of the data anyway (in order to do filtering upon it) so this should not add much overhead in practice
@param totalObjectCount Total number of objects in the RDD to split
@param numObjectsPerSplit Number of objects in each split
@param data Data to split
@param <T> Generic type for the RDD
@return The RDD split up (without replacement) into a number of smaller RDDs | [
"Random",
"split",
"the",
"specified",
"RDD",
"into",
"a",
"number",
"of",
"RDDs",
"where",
"each",
"has",
"{",
"@code",
"numObjectsPerSplit",
"}",
"in",
"them",
".",
"<p",
">",
"This",
"similar",
"to",
"how",
"RDD",
".",
"randomSplit",
"works",
"(",
"i"... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L460-L462 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/SchemaSet.java | SchemaSet.hashToTable | private int hashToTable(Long id, Entry[] table) {
int posVal = id.intValue() & Integer.MAX_VALUE;
return (posVal % table.length);
} | java | private int hashToTable(Long id, Entry[] table) {
int posVal = id.intValue() & Integer.MAX_VALUE;
return (posVal % table.length);
} | [
"private",
"int",
"hashToTable",
"(",
"Long",
"id",
",",
"Entry",
"[",
"]",
"table",
")",
"{",
"int",
"posVal",
"=",
"id",
".",
"intValue",
"(",
")",
"&",
"Integer",
".",
"MAX_VALUE",
";",
"return",
"(",
"posVal",
"%",
"table",
".",
"length",
")",
... | The Long Id is already effectively a hashcode for the Schema and should
be unique. All we should need to do is get a positive integer version of it
& divide by the table size. | [
"The",
"Long",
"Id",
"is",
"already",
"effectively",
"a",
"hashcode",
"for",
"the",
"Schema",
"and",
"should",
"be",
"unique",
".",
"All",
"we",
"should",
"need",
"to",
"do",
"is",
"get",
"a",
"positive",
"integer",
"version",
"of",
"it",
"&",
"divide",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/impl/SchemaSet.java#L289-L292 |
alkacon/opencms-core | src/org/opencms/jlan/CmsJlanDiskInterface.java | CmsJlanDiskInterface.getFileForPath | protected CmsJlanNetworkFile getFileForPath(
CmsObjectWrapper cms,
SrvSession session,
TreeConnection connection,
String path) throws CmsException {
try {
String cmsPath = getCmsPath(path);
CmsResource resource = cms.readResource(cmsPath, STANDARD_FILTER);
CmsJlanNetworkFile result = new CmsJlanNetworkFile(cms, resource, path);
return result;
} catch (CmsVfsResourceNotFoundException e) {
return null;
}
} | java | protected CmsJlanNetworkFile getFileForPath(
CmsObjectWrapper cms,
SrvSession session,
TreeConnection connection,
String path) throws CmsException {
try {
String cmsPath = getCmsPath(path);
CmsResource resource = cms.readResource(cmsPath, STANDARD_FILTER);
CmsJlanNetworkFile result = new CmsJlanNetworkFile(cms, resource, path);
return result;
} catch (CmsVfsResourceNotFoundException e) {
return null;
}
} | [
"protected",
"CmsJlanNetworkFile",
"getFileForPath",
"(",
"CmsObjectWrapper",
"cms",
",",
"SrvSession",
"session",
",",
"TreeConnection",
"connection",
",",
"String",
"path",
")",
"throws",
"CmsException",
"{",
"try",
"{",
"String",
"cmsPath",
"=",
"getCmsPath",
"("... | Helper method to get a network file object given a path.<p>
@param cms the CMS context wrapper
@param session the current session
@param connection the current connection
@param path the file path
@return the network file object for the given path
@throws CmsException if something goes wrong | [
"Helper",
"method",
"to",
"get",
"a",
"network",
"file",
"object",
"given",
"a",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jlan/CmsJlanDiskInterface.java#L448-L462 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletResponse.java | SRTServletResponse.getOutputStream | public ServletOutputStream getOutputStream() {
final boolean isTraceOn = com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled();
if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15
logger.entering(CLASS_NAME,"getOutputStream","gotWriter="+String.valueOf(_gotWriter)+" ["+this+"]");
if (!_ignoreStateErrors && _gotWriter) {
if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15
logger.exiting(CLASS_NAME,"getOutputStream","throw IllegalStateException");
throw new IllegalStateException(nls.getString("Writer.already.obtained", "Writer already obtained"));
}
//PK89810 Start
if(!(WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) || ! _gotOutputStream)
{
_gotOutputStream = true;
// LIBERTY _bufferedOut.init(_rawOut, getBufferSize());
// LIBERTY _bufferedOut.setLimit(_contentLength);
// LIBERTY _bufferedOut.setResponse(_response);
// LIBERTY _responseBuffer = _bufferedOut;
} //PK89810 End
this.fireOutputStreamRetrievedEvent(_bufferedOut);
if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15
logger.exiting(CLASS_NAME,"getOutputStream");
return _bufferedOut;
} | java | public ServletOutputStream getOutputStream() {
final boolean isTraceOn = com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled();
if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15
logger.entering(CLASS_NAME,"getOutputStream","gotWriter="+String.valueOf(_gotWriter)+" ["+this+"]");
if (!_ignoreStateErrors && _gotWriter) {
if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15
logger.exiting(CLASS_NAME,"getOutputStream","throw IllegalStateException");
throw new IllegalStateException(nls.getString("Writer.already.obtained", "Writer already obtained"));
}
//PK89810 Start
if(!(WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) || ! _gotOutputStream)
{
_gotOutputStream = true;
// LIBERTY _bufferedOut.init(_rawOut, getBufferSize());
// LIBERTY _bufferedOut.setLimit(_contentLength);
// LIBERTY _bufferedOut.setResponse(_response);
// LIBERTY _responseBuffer = _bufferedOut;
} //PK89810 End
this.fireOutputStreamRetrievedEvent(_bufferedOut);
if (isTraceOn&&logger.isLoggable (Level.FINE)) //306998.15
logger.exiting(CLASS_NAME,"getOutputStream");
return _bufferedOut;
} | [
"public",
"ServletOutputStream",
"getOutputStream",
"(",
")",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"com",
".",
"ibm",
".",
"ejs",
".",
"ras",
".",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
";",
"if",
"(",
"isTraceOn",
"&&",
"logger",
".",... | Returns an output stream for writing binary response data.
@see reinitStreamState | [
"Returns",
"an",
"output",
"stream",
"for",
"writing",
"binary",
"response",
"data",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTServletResponse.java#L761-L790 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-kms/src/main/java/com/google/cloud/kms/v1/KeyManagementServiceClient.java | KeyManagementServiceClient.asymmetricDecrypt | public final AsymmetricDecryptResponse asymmetricDecrypt(String name, ByteString ciphertext) {
AsymmetricDecryptRequest request =
AsymmetricDecryptRequest.newBuilder().setName(name).setCiphertext(ciphertext).build();
return asymmetricDecrypt(request);
} | java | public final AsymmetricDecryptResponse asymmetricDecrypt(String name, ByteString ciphertext) {
AsymmetricDecryptRequest request =
AsymmetricDecryptRequest.newBuilder().setName(name).setCiphertext(ciphertext).build();
return asymmetricDecrypt(request);
} | [
"public",
"final",
"AsymmetricDecryptResponse",
"asymmetricDecrypt",
"(",
"String",
"name",
",",
"ByteString",
"ciphertext",
")",
"{",
"AsymmetricDecryptRequest",
"request",
"=",
"AsymmetricDecryptRequest",
".",
"newBuilder",
"(",
")",
".",
"setName",
"(",
"name",
")"... | Decrypts data that was encrypted with a public key retrieved from
[GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] corresponding to a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] ASYMMETRIC_DECRYPT.
<p>Sample code:
<pre><code>
try (KeyManagementServiceClient keyManagementServiceClient = KeyManagementServiceClient.create()) {
CryptoKeyVersionName name = CryptoKeyVersionName.of("[PROJECT]", "[LOCATION]", "[KEY_RING]", "[CRYPTO_KEY]", "[CRYPTO_KEY_VERSION]");
ByteString ciphertext = ByteString.copyFromUtf8("");
AsymmetricDecryptResponse response = keyManagementServiceClient.asymmetricDecrypt(name.toString(), ciphertext);
}
</code></pre>
@param name Required. The resource name of the
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for decryption.
@param ciphertext Required. The data encrypted with the named
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s public key using OAEP.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Decrypts",
"data",
"that",
"was",
"encrypted",
"with",
"a",
"public",
"key",
"retrieved",
"from",
"[",
"GetPublicKey",
"]",
"[",
"google",
".",
"cloud",
".",
"kms",
".",
"v1",
".",
"KeyManagementService",
".",
"GetPublicKey",
"]",
"corresponding",
"to",
"a"... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-kms/src/main/java/com/google/cloud/kms/v1/KeyManagementServiceClient.java#L2292-L2297 |
javamelody/javamelody | javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackendFactory.java | RrdNioBackendFactory.open | @Override
protected RrdBackend open(String path, boolean readOnly) throws IOException {
return new RrdNioBackend(path, readOnly, syncPeriod);
} | java | @Override
protected RrdBackend open(String path, boolean readOnly) throws IOException {
return new RrdNioBackend(path, readOnly, syncPeriod);
} | [
"@",
"Override",
"protected",
"RrdBackend",
"open",
"(",
"String",
"path",
",",
"boolean",
"readOnly",
")",
"throws",
"IOException",
"{",
"return",
"new",
"RrdNioBackend",
"(",
"path",
",",
"readOnly",
",",
"syncPeriod",
")",
";",
"}"
] | Creates RrdNioBackend object for the given file path.
@param path File path
@param readOnly True, if the file should be accessed in read/only mode.
False otherwise.
@return RrdNioBackend object which handles all I/O operations for the given file path
@throws IOException Thrown in case of I/O error. | [
"Creates",
"RrdNioBackend",
"object",
"for",
"the",
"given",
"file",
"path",
"."
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackendFactory.java#L82-L85 |
jmeetsma/Iglu-Common | src/main/java/org/ijsberg/iglu/configuration/classloading/ExtendedClassPathClassLoader.java | ExtendedClassPathClassLoader.findClass | public Class<?> findClass(String className) throws ClassNotFoundException {
Object location = classResourceLocations.get(className);
if (location == null && this.propertiesResourceLocations.containsKey(className)) {
String fileName = (String) propertiesResourceLocations.get(className);
if (fileName.endsWith(".properties")) {
//notify invoker that file is present as properties file
return ResourceBundle.class;
} else {
throw new ClassNotFoundException("resource '" + fileName + "' for class '" + className + "' has incompatible format");
}
}
if (className.startsWith("java.")) {
return super.findClass(className);
}
if (location == null) {
throw new ClassNotFoundException("class '" + className + "' not found in " + classpath);
}
String fileName = className.replace('.', '/') + ".class";
byte[] data;
try {
data = getData(fileName, location);
} catch (IOException ioe) {
throw new NoClassDefFoundError("class '" + className + "' could not be loaded from '" + location + "' with message: " + ioe);
}
return defineClass(className, data, 0, data.length);
} | java | public Class<?> findClass(String className) throws ClassNotFoundException {
Object location = classResourceLocations.get(className);
if (location == null && this.propertiesResourceLocations.containsKey(className)) {
String fileName = (String) propertiesResourceLocations.get(className);
if (fileName.endsWith(".properties")) {
//notify invoker that file is present as properties file
return ResourceBundle.class;
} else {
throw new ClassNotFoundException("resource '" + fileName + "' for class '" + className + "' has incompatible format");
}
}
if (className.startsWith("java.")) {
return super.findClass(className);
}
if (location == null) {
throw new ClassNotFoundException("class '" + className + "' not found in " + classpath);
}
String fileName = className.replace('.', '/') + ".class";
byte[] data;
try {
data = getData(fileName, location);
} catch (IOException ioe) {
throw new NoClassDefFoundError("class '" + className + "' could not be loaded from '" + location + "' with message: " + ioe);
}
return defineClass(className, data, 0, data.length);
} | [
"public",
"Class",
"<",
"?",
">",
"findClass",
"(",
"String",
"className",
")",
"throws",
"ClassNotFoundException",
"{",
"Object",
"location",
"=",
"classResourceLocations",
".",
"get",
"(",
"className",
")",
";",
"if",
"(",
"location",
"==",
"null",
"&&",
"... | Tries to locate a class in the specific class path.
@param className
@return
@throws ClassNotFoundException | [
"Tries",
"to",
"locate",
"a",
"class",
"in",
"the",
"specific",
"class",
"path",
"."
] | train | https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/configuration/classloading/ExtendedClassPathClassLoader.java#L317-L343 |
hypercube1024/firefly | firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java | AtomicBiInteger.encodeLo | public static long encodeLo(long encoded, int lo) {
long h = (encoded >> 32) & 0xFFFF_FFFFL;
long l = ((long) lo) & 0xFFFF_FFFFL;
return (h << 32) + l;
} | java | public static long encodeLo(long encoded, int lo) {
long h = (encoded >> 32) & 0xFFFF_FFFFL;
long l = ((long) lo) & 0xFFFF_FFFFL;
return (h << 32) + l;
} | [
"public",
"static",
"long",
"encodeLo",
"(",
"long",
"encoded",
",",
"int",
"lo",
")",
"{",
"long",
"h",
"=",
"(",
"encoded",
">>",
"32",
")",
"&",
"0xFFFF_FFFF",
"",
"L",
";",
"long",
"l",
"=",
"(",
"(",
"long",
")",
"lo",
")",
"&",
"0xFFFF_FFFF... | Sets the lo value into the given encoded value.
@param encoded the encoded value
@param lo the lo value
@return the new encoded value | [
"Sets",
"the",
"lo",
"value",
"into",
"the",
"given",
"encoded",
"value",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/lang/AtomicBiInteger.java#L237-L241 |
netheosgithub/pcs_api | java/src/main/java/net/netheos/pcsapi/providers/cloudme/CMBlob.java | CMBlob.buildCMFile | public static CMBlob buildCMFile( CMFolder folder, Element xmlEntry )
throws ParseException
{
final String name = xmlEntry.getElementsByTagNameNS( "*", "title" ).item( 0 ).getTextContent();
final String id = xmlEntry.getElementsByTagNameNS( "*", "document" ).item( 0 ).getTextContent();
final String updateDate = xmlEntry.getElementsByTagNameNS( "*", "updated" ).item( 0 ).getTextContent();
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" );
sdf.setLenient( false );
sdf.setTimeZone( TimeZone.getTimeZone( "GMT" ) );
final Date updated = sdf.parse( updateDate );
final Element elementLink = ( Element ) xmlEntry.getElementsByTagNameNS( "*",
"link" ).item( 0 );
final long length = Long.parseLong( elementLink.getAttribute( "length" ) );
final String contentType = elementLink.getAttribute( "type" );
return new CMBlob( folder, id, name, length, updated, contentType );
} | java | public static CMBlob buildCMFile( CMFolder folder, Element xmlEntry )
throws ParseException
{
final String name = xmlEntry.getElementsByTagNameNS( "*", "title" ).item( 0 ).getTextContent();
final String id = xmlEntry.getElementsByTagNameNS( "*", "document" ).item( 0 ).getTextContent();
final String updateDate = xmlEntry.getElementsByTagNameNS( "*", "updated" ).item( 0 ).getTextContent();
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" );
sdf.setLenient( false );
sdf.setTimeZone( TimeZone.getTimeZone( "GMT" ) );
final Date updated = sdf.parse( updateDate );
final Element elementLink = ( Element ) xmlEntry.getElementsByTagNameNS( "*",
"link" ).item( 0 );
final long length = Long.parseLong( elementLink.getAttribute( "length" ) );
final String contentType = elementLink.getAttribute( "type" );
return new CMBlob( folder, id, name, length, updated, contentType );
} | [
"public",
"static",
"CMBlob",
"buildCMFile",
"(",
"CMFolder",
"folder",
",",
"Element",
"xmlEntry",
")",
"throws",
"ParseException",
"{",
"final",
"String",
"name",
"=",
"xmlEntry",
".",
"getElementsByTagNameNS",
"(",
"\"*\"",
",",
"\"title\"",
")",
".",
"item",... | Factory method that builds a CMBlob based on a XML "atom:entry" element
@param xmlEntry | [
"Factory",
"method",
"that",
"builds",
"a",
"CMBlob",
"based",
"on",
"a",
"XML",
"atom",
":",
"entry",
"element"
] | train | https://github.com/netheosgithub/pcs_api/blob/20691e52e144014f99ca75cb7dedc7ba0c18586c/java/src/main/java/net/netheos/pcsapi/providers/cloudme/CMBlob.java#L80-L99 |
jenkinsci/jenkins | core/src/main/java/hudson/console/ConsoleLogFilter.java | ConsoleLogFilter.decorateLogger | public OutputStream decorateLogger(Run build, OutputStream logger) throws IOException, InterruptedException {
// this implementation is backward compatibility thunk in case subtypes only override the
// old signature (AbstractBuild,OutputStream)
if (build instanceof AbstractBuild) {
// maybe the plugin implements the old signature.
return decorateLogger((AbstractBuild) build, logger);
} else {
// this ConsoleLogFilter can only decorate AbstractBuild, so just pass through
return logger;
}
} | java | public OutputStream decorateLogger(Run build, OutputStream logger) throws IOException, InterruptedException {
// this implementation is backward compatibility thunk in case subtypes only override the
// old signature (AbstractBuild,OutputStream)
if (build instanceof AbstractBuild) {
// maybe the plugin implements the old signature.
return decorateLogger((AbstractBuild) build, logger);
} else {
// this ConsoleLogFilter can only decorate AbstractBuild, so just pass through
return logger;
}
} | [
"public",
"OutputStream",
"decorateLogger",
"(",
"Run",
"build",
",",
"OutputStream",
"logger",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"// this implementation is backward compatibility thunk in case subtypes only override the",
"// old signature (AbstractBuil... | Called on the start of each build, giving extensions a chance to intercept
the data that is written to the log.
<p>
Even though this method is not marked 'abstract', this is the method that must be overridden
by extensions. | [
"Called",
"on",
"the",
"start",
"of",
"each",
"build",
"giving",
"extensions",
"a",
"chance",
"to",
"intercept",
"the",
"data",
"that",
"is",
"written",
"to",
"the",
"log",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/console/ConsoleLogFilter.java#L83-L94 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/restricted/ConstructorRef.java | ConstructorRef.create | public static ConstructorRef create(TypeInfo type, Method init) {
checkArgument(
init.getName().equals("<init>") && init.getReturnType().equals(Type.VOID_TYPE),
"'%s' is not a valid constructor",
init);
return new AutoValue_ConstructorRef(type, init, ImmutableList.copyOf(init.getArgumentTypes()));
} | java | public static ConstructorRef create(TypeInfo type, Method init) {
checkArgument(
init.getName().equals("<init>") && init.getReturnType().equals(Type.VOID_TYPE),
"'%s' is not a valid constructor",
init);
return new AutoValue_ConstructorRef(type, init, ImmutableList.copyOf(init.getArgumentTypes()));
} | [
"public",
"static",
"ConstructorRef",
"create",
"(",
"TypeInfo",
"type",
",",
"Method",
"init",
")",
"{",
"checkArgument",
"(",
"init",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"\"<init>\"",
")",
"&&",
"init",
".",
"getReturnType",
"(",
")",
".",
"e... | Returns a new {@link ConstructorRef} that refers to a constructor on the given type with the
given parameter types. | [
"Returns",
"a",
"new",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/ConstructorRef.java#L45-L51 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WValidationErrorsRenderer.java | WValidationErrorsRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WValidationErrors errors = (WValidationErrors) component;
XmlStringBuilder xml = renderContext.getWriter();
if (errors.hasErrors()) {
xml.appendTagOpen("ui:validationerrors");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("title", errors.getTitleText());
xml.appendClose();
for (GroupedDiagnositcs nextGroup : errors.getGroupedErrors()) {
// Render each diagnostic message in this group.
for (Diagnostic nextMessage : nextGroup.getDiagnostics()) {
xml.appendTagOpen("ui:error");
WComponent forComponent = nextMessage.getComponent();
if (forComponent != null) {
UIContextHolder.pushContext(nextMessage.getContext());
try {
xml.appendAttribute("for", forComponent.getId());
} finally {
UIContextHolder.popContext();
}
}
xml.appendClose();
// DiagnosticImpl has been extended to support rendering
// of a WComponent as the message.
if (nextMessage instanceof DiagnosticImpl) {
WComponent messageComponent = ((DiagnosticImpl) nextMessage)
.createDiagnosticErrorComponent();
// We add the component to a throw-away container so that it renders with the correct ID.
WContainer container = new WContainer() {
@Override
public String getId() {
return component.getId();
}
};
container.add(messageComponent);
messageComponent.paint(renderContext);
container.remove(messageComponent);
container.reset();
} else {
xml.append(nextMessage.getDescription());
}
xml.appendEndTag("ui:error");
}
}
xml.appendEndTag("ui:validationerrors");
}
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WValidationErrors errors = (WValidationErrors) component;
XmlStringBuilder xml = renderContext.getWriter();
if (errors.hasErrors()) {
xml.appendTagOpen("ui:validationerrors");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("title", errors.getTitleText());
xml.appendClose();
for (GroupedDiagnositcs nextGroup : errors.getGroupedErrors()) {
// Render each diagnostic message in this group.
for (Diagnostic nextMessage : nextGroup.getDiagnostics()) {
xml.appendTagOpen("ui:error");
WComponent forComponent = nextMessage.getComponent();
if (forComponent != null) {
UIContextHolder.pushContext(nextMessage.getContext());
try {
xml.appendAttribute("for", forComponent.getId());
} finally {
UIContextHolder.popContext();
}
}
xml.appendClose();
// DiagnosticImpl has been extended to support rendering
// of a WComponent as the message.
if (nextMessage instanceof DiagnosticImpl) {
WComponent messageComponent = ((DiagnosticImpl) nextMessage)
.createDiagnosticErrorComponent();
// We add the component to a throw-away container so that it renders with the correct ID.
WContainer container = new WContainer() {
@Override
public String getId() {
return component.getId();
}
};
container.add(messageComponent);
messageComponent.paint(renderContext);
container.remove(messageComponent);
container.reset();
} else {
xml.append(nextMessage.getDescription());
}
xml.appendEndTag("ui:error");
}
}
xml.appendEndTag("ui:validationerrors");
}
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WValidationErrors",
"errors",
"=",
"(",
"WValidationErrors",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=... | Paints the given {@link WValidationErrors} component.
@param component The {@link WValidationErrors} component to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"{",
"@link",
"WValidationErrors",
"}",
"component",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WValidationErrorsRenderer.java#L28-L87 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorIDParser.java | TransliteratorIDParser.parseFilterID | public static SingleID parseFilterID(String id, int[] pos) {
int start = pos[0];
Specs specs = parseFilterID(id, pos, true);
if (specs == null) {
pos[0] = start;
return null;
}
// Assemble return results
SingleID single = specsToID(specs, FORWARD);
single.filter = specs.filter;
return single;
} | java | public static SingleID parseFilterID(String id, int[] pos) {
int start = pos[0];
Specs specs = parseFilterID(id, pos, true);
if (specs == null) {
pos[0] = start;
return null;
}
// Assemble return results
SingleID single = specsToID(specs, FORWARD);
single.filter = specs.filter;
return single;
} | [
"public",
"static",
"SingleID",
"parseFilterID",
"(",
"String",
"id",
",",
"int",
"[",
"]",
"pos",
")",
"{",
"int",
"start",
"=",
"pos",
"[",
"0",
"]",
";",
"Specs",
"specs",
"=",
"parseFilterID",
"(",
"id",
",",
"pos",
",",
"true",
")",
";",
"if",... | Parse a filter ID, that is, an ID of the general form
"[f1] s1-t1/v1", with the filters optional, and the variants optional.
@param id the id to be parsed
@param pos INPUT-OUTPUT parameter. On input, the position of
the first character to parse. On output, the position after
the last character parsed.
@return a SingleID object or null if the parse fails | [
"Parse",
"a",
"filter",
"ID",
"that",
"is",
"an",
"ID",
"of",
"the",
"general",
"form",
"[",
"f1",
"]",
"s1",
"-",
"t1",
"/",
"v1",
"with",
"the",
"filters",
"optional",
"and",
"the",
"variants",
"optional",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorIDParser.java#L151-L164 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/SearchFilter.java | SearchFilter.matchList | public void matchList(String ElementName, String[] values, int oper)
{
// Delete the old search filter
m_filter = null;
// If not NOT_IN, assume IN
// (Since ints are passed by value, it is OK to change it)
if (oper != NOT_IN)
{
oper = IN;
// Create a leaf node for this list and store it as the filter
}
m_filter = new SearchBaseLeaf(ElementName, oper, values);
} | java | public void matchList(String ElementName, String[] values, int oper)
{
// Delete the old search filter
m_filter = null;
// If not NOT_IN, assume IN
// (Since ints are passed by value, it is OK to change it)
if (oper != NOT_IN)
{
oper = IN;
// Create a leaf node for this list and store it as the filter
}
m_filter = new SearchBaseLeaf(ElementName, oper, values);
} | [
"public",
"void",
"matchList",
"(",
"String",
"ElementName",
",",
"String",
"[",
"]",
"values",
",",
"int",
"oper",
")",
"{",
"// Delete the old search filter\r",
"m_filter",
"=",
"null",
";",
"// If not NOT_IN, assume IN\r",
"// (Since ints are passed by value, it is OK ... | Change the search filter to one that specifies an element to not
match one of a list of values.
The old search filter is deleted.
@param ElementName is the name of the element to be matched
@param values is an array of possible matches
@param oper is the IN or NOT_IN operator to indicate how to matche | [
"Change",
"the",
"search",
"filter",
"to",
"one",
"that",
"specifies",
"an",
"element",
"to",
"not",
"match",
"one",
"of",
"a",
"list",
"of",
"values",
".",
"The",
"old",
"search",
"filter",
"is",
"deleted",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/SearchFilter.java#L100-L112 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/wrapper/json/PJsonArray.java | PJsonArray.getJSONArray | public final PJsonArray getJSONArray(final int i) {
JSONArray val = this.array.optJSONArray(i);
final String context = "[" + i + "]";
if (val == null) {
throw new ObjectMissingException(this, context);
}
return new PJsonArray(this, val, context);
} | java | public final PJsonArray getJSONArray(final int i) {
JSONArray val = this.array.optJSONArray(i);
final String context = "[" + i + "]";
if (val == null) {
throw new ObjectMissingException(this, context);
}
return new PJsonArray(this, val, context);
} | [
"public",
"final",
"PJsonArray",
"getJSONArray",
"(",
"final",
"int",
"i",
")",
"{",
"JSONArray",
"val",
"=",
"this",
".",
"array",
".",
"optJSONArray",
"(",
"i",
")",
";",
"final",
"String",
"context",
"=",
"\"[\"",
"+",
"i",
"+",
"\"]\"",
";",
"if",
... | Get the element at the index as a json array.
@param i the index of the element to access | [
"Get",
"the",
"element",
"at",
"the",
"index",
"as",
"a",
"json",
"array",
"."
] | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/wrapper/json/PJsonArray.java#L76-L83 |
rythmengine/rythmengine | src/main/java/org/rythmengine/utils/S.java | S.isEqual | public static boolean isEqual(Object o1, Object o2) {
return isEqual(str(o1), str(o2));
} | java | public static boolean isEqual(Object o1, Object o2) {
return isEqual(str(o1), str(o2));
} | [
"public",
"static",
"boolean",
"isEqual",
"(",
"Object",
"o1",
",",
"Object",
"o2",
")",
"{",
"return",
"isEqual",
"(",
"str",
"(",
"o1",
")",
",",
"str",
"(",
"o2",
")",
")",
";",
"}"
] | Check if two Object is equal after converted into String
@param o1
@param o2
@return true if the specified two object instance are equal after converting to String | [
"Check",
"if",
"two",
"Object",
"is",
"equal",
"after",
"converted",
"into",
"String"
] | train | https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/utils/S.java#L206-L208 |
GoSimpleLLC/nbvcxz | src/main/java/me/gosimple/nbvcxz/resources/CharacterCaseUtil.java | CharacterCaseUtil.fractionOfStringUppercase | public static double fractionOfStringUppercase(String input)
{
if (input == null)
{
return 0;
}
double upperCasableCharacters = 0;
double upperCount = 0;
for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
char uc = Character.toUpperCase(c);
char lc = Character.toLowerCase(c);
// If both the upper and lowercase version of a character are the same, then the character has
// no distinct uppercase form (e.g., a digit or punctuation). Ignore these.
if (c == uc && c == lc)
{
continue;
}
upperCasableCharacters++;
if (c == uc)
{
upperCount++;
}
}
return upperCasableCharacters == 0 ? 0 : upperCount / upperCasableCharacters;
} | java | public static double fractionOfStringUppercase(String input)
{
if (input == null)
{
return 0;
}
double upperCasableCharacters = 0;
double upperCount = 0;
for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
char uc = Character.toUpperCase(c);
char lc = Character.toLowerCase(c);
// If both the upper and lowercase version of a character are the same, then the character has
// no distinct uppercase form (e.g., a digit or punctuation). Ignore these.
if (c == uc && c == lc)
{
continue;
}
upperCasableCharacters++;
if (c == uc)
{
upperCount++;
}
}
return upperCasableCharacters == 0 ? 0 : upperCount / upperCasableCharacters;
} | [
"public",
"static",
"double",
"fractionOfStringUppercase",
"(",
"String",
"input",
")",
"{",
"if",
"(",
"input",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"double",
"upperCasableCharacters",
"=",
"0",
";",
"double",
"upperCount",
"=",
"0",
";",
"for... | Of the characters in the string that have an uppercase form, how many are uppercased?
@param input Input string.
@return The fraction of uppercased characters, with {@code 0.0d} meaning that all uppercasable characters are in
lowercase and {@code 1.0d} that all of them are in uppercase. | [
"Of",
"the",
"characters",
"in",
"the",
"string",
"that",
"have",
"an",
"uppercase",
"form",
"how",
"many",
"are",
"uppercased?"
] | train | https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/resources/CharacterCaseUtil.java#L12-L41 |
apache/incubator-shardingsphere | sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/PostgreSQLCommandPacketFactory.java | PostgreSQLCommandPacketFactory.newInstance | public static PostgreSQLCommandPacket newInstance(
final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLPacketPayload payload, final int connectionId) throws SQLException {
switch (commandPacketType) {
case QUERY:
return new PostgreSQLComQueryPacket(payload);
case PARSE:
return new PostgreSQLComParsePacket(payload);
case BIND:
return new PostgreSQLComBindPacket(payload, connectionId);
case DESCRIBE:
return new PostgreSQLComDescribePacket(payload);
case EXECUTE:
return new PostgreSQLComExecutePacket(payload);
case SYNC:
return new PostgreSQLComSyncPacket(payload);
case TERMINATE:
return new PostgreSQLComTerminationPacket(payload);
default:
return new PostgreSQLUnsupportedCommandPacket(commandPacketType.getValue());
}
} | java | public static PostgreSQLCommandPacket newInstance(
final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLPacketPayload payload, final int connectionId) throws SQLException {
switch (commandPacketType) {
case QUERY:
return new PostgreSQLComQueryPacket(payload);
case PARSE:
return new PostgreSQLComParsePacket(payload);
case BIND:
return new PostgreSQLComBindPacket(payload, connectionId);
case DESCRIBE:
return new PostgreSQLComDescribePacket(payload);
case EXECUTE:
return new PostgreSQLComExecutePacket(payload);
case SYNC:
return new PostgreSQLComSyncPacket(payload);
case TERMINATE:
return new PostgreSQLComTerminationPacket(payload);
default:
return new PostgreSQLUnsupportedCommandPacket(commandPacketType.getValue());
}
} | [
"public",
"static",
"PostgreSQLCommandPacket",
"newInstance",
"(",
"final",
"PostgreSQLCommandPacketType",
"commandPacketType",
",",
"final",
"PostgreSQLPacketPayload",
"payload",
",",
"final",
"int",
"connectionId",
")",
"throws",
"SQLException",
"{",
"switch",
"(",
"com... | Create new instance of command packet.
@param commandPacketType command packet type for PostgreSQL
@param payload packet payload for PostgreSQL
@param connectionId connection id
@return command packet for PostgreSQL
@throws SQLException SQL exception | [
"Create",
"new",
"instance",
"of",
"command",
"packet",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/PostgreSQLCommandPacketFactory.java#L51-L71 |
OpenNTF/JavascriptAggregator | jaggr-core/src/main/java/com/ibm/jaggr/core/impl/resource/FileResource.java | FileResource.recurse | private void recurse(File file, IResourceVisitor visitor, String path)
throws IOException {
File[] files = file.listFiles();
if (files == null) {
return;
}
for (File child : files) {
String childName = path + (path.length() == 0 ? "" : "/") //$NON-NLS-1$ //$NON-NLS-2$
+ child.getName();
boolean result = visitor.visitResource(new VisitorResource(child,
child.lastModified(), childName), childName);
if (child.isDirectory() && result) {
recurse(child, visitor, childName);
}
}
} | java | private void recurse(File file, IResourceVisitor visitor, String path)
throws IOException {
File[] files = file.listFiles();
if (files == null) {
return;
}
for (File child : files) {
String childName = path + (path.length() == 0 ? "" : "/") //$NON-NLS-1$ //$NON-NLS-2$
+ child.getName();
boolean result = visitor.visitResource(new VisitorResource(child,
child.lastModified(), childName), childName);
if (child.isDirectory() && result) {
recurse(child, visitor, childName);
}
}
} | [
"private",
"void",
"recurse",
"(",
"File",
"file",
",",
"IResourceVisitor",
"visitor",
",",
"String",
"path",
")",
"throws",
"IOException",
"{",
"File",
"[",
"]",
"files",
"=",
"file",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"files",
"==",
"null",
... | Internal method for recursing sub directories.
@param file
The file object
@param visitor
The {@link IResourceVisitor} to call for non-folder resources
@throws IOException | [
"Internal",
"method",
"for",
"recursing",
"sub",
"directories",
"."
] | train | https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/resource/FileResource.java#L162-L177 |
alkacon/opencms-core | src/org/opencms/staticexport/CmsLinkManager.java | CmsLinkManager.getPermalink | public String getPermalink(CmsObject cms, String resourceName) {
return getPermalink(cms, resourceName, null);
} | java | public String getPermalink(CmsObject cms, String resourceName) {
return getPermalink(cms, resourceName, null);
} | [
"public",
"String",
"getPermalink",
"(",
"CmsObject",
"cms",
",",
"String",
"resourceName",
")",
"{",
"return",
"getPermalink",
"(",
"cms",
",",
"resourceName",
",",
"null",
")",
";",
"}"
] | Returns the perma link for the given resource.<p>
Like
<code>http://site.enterprise.com:8080/permalink/4b65369f-1266-11db-8360-bf0f6fbae1f8.html</code>.<p>
@param cms the cms context
@param resourceName the resource to generate the perma link for
@return the perma link | [
"Returns",
"the",
"perma",
"link",
"for",
"the",
"given",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L409-L412 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfStamper.java | PdfStamper.addSignature | public PdfFormField addSignature(String name, int page, float llx, float lly, float urx, float ury) {
PdfAcroForm acroForm = stamper.getAcroForm();
PdfFormField signature = PdfFormField.createSignature(stamper);
acroForm.setSignatureParams(signature, name, llx, lly, urx, ury);
acroForm.drawSignatureAppearences(signature, llx, lly, urx, ury);
addAnnotation(signature, page);
return signature;
} | java | public PdfFormField addSignature(String name, int page, float llx, float lly, float urx, float ury) {
PdfAcroForm acroForm = stamper.getAcroForm();
PdfFormField signature = PdfFormField.createSignature(stamper);
acroForm.setSignatureParams(signature, name, llx, lly, urx, ury);
acroForm.drawSignatureAppearences(signature, llx, lly, urx, ury);
addAnnotation(signature, page);
return signature;
} | [
"public",
"PdfFormField",
"addSignature",
"(",
"String",
"name",
",",
"int",
"page",
",",
"float",
"llx",
",",
"float",
"lly",
",",
"float",
"urx",
",",
"float",
"ury",
")",
"{",
"PdfAcroForm",
"acroForm",
"=",
"stamper",
".",
"getAcroForm",
"(",
")",
";... | Adds an empty signature.
@param name the name of the signature
@param page the page number
@param llx lower left x coordinate of the signature's position
@param lly lower left y coordinate of the signature's position
@param urx upper right x coordinate of the signature's position
@param ury upper right y coordinate of the signature's position
@return a signature form field
@since 2.1.4 | [
"Adds",
"an",
"empty",
"signature",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfStamper.java#L434-L441 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java | SVGUtil.elementCoordinatesFromEvent | public static SVGPoint elementCoordinatesFromEvent(Document doc, Element tag, Event evt) {
try {
DOMMouseEvent gnme = (DOMMouseEvent) evt;
SVGMatrix mat = ((SVGLocatable) tag).getScreenCTM();
SVGMatrix imat = mat.inverse();
SVGPoint cPt = ((SVGDocument) doc).getRootElement().createSVGPoint();
cPt.setX(gnme.getClientX());
cPt.setY(gnme.getClientY());
return cPt.matrixTransform(imat);
}
catch(Exception e) {
LoggingUtil.warning("Error getting coordinates from SVG event.", e);
return null;
}
} | java | public static SVGPoint elementCoordinatesFromEvent(Document doc, Element tag, Event evt) {
try {
DOMMouseEvent gnme = (DOMMouseEvent) evt;
SVGMatrix mat = ((SVGLocatable) tag).getScreenCTM();
SVGMatrix imat = mat.inverse();
SVGPoint cPt = ((SVGDocument) doc).getRootElement().createSVGPoint();
cPt.setX(gnme.getClientX());
cPt.setY(gnme.getClientY());
return cPt.matrixTransform(imat);
}
catch(Exception e) {
LoggingUtil.warning("Error getting coordinates from SVG event.", e);
return null;
}
} | [
"public",
"static",
"SVGPoint",
"elementCoordinatesFromEvent",
"(",
"Document",
"doc",
",",
"Element",
"tag",
",",
"Event",
"evt",
")",
"{",
"try",
"{",
"DOMMouseEvent",
"gnme",
"=",
"(",
"DOMMouseEvent",
")",
"evt",
";",
"SVGMatrix",
"mat",
"=",
"(",
"(",
... | Convert the coordinates of an DOM Event from screen into element
coordinates.
@param doc Document context
@param tag Element containing the coordinate system
@param evt Event to interpret
@return coordinates | [
"Convert",
"the",
"coordinates",
"of",
"an",
"DOM",
"Event",
"from",
"screen",
"into",
"element",
"coordinates",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java#L627-L641 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/TaskInProgress.java | TaskInProgress.hasRunOnMachine | public boolean hasRunOnMachine(String trackerHost, String trackerName) {
return this.activeTasks.values().contains(trackerName) ||
hasFailedOnMachine(trackerHost);
} | java | public boolean hasRunOnMachine(String trackerHost, String trackerName) {
return this.activeTasks.values().contains(trackerName) ||
hasFailedOnMachine(trackerHost);
} | [
"public",
"boolean",
"hasRunOnMachine",
"(",
"String",
"trackerHost",
",",
"String",
"trackerName",
")",
"{",
"return",
"this",
".",
"activeTasks",
".",
"values",
"(",
")",
".",
"contains",
"(",
"trackerName",
")",
"||",
"hasFailedOnMachine",
"(",
"trackerHost",... | Was this task ever scheduled to run on this machine?
@param trackerHost The task tracker hostname
@param trackerName The tracker name
@return Was task scheduled on the tracker? | [
"Was",
"this",
"task",
"ever",
"scheduled",
"to",
"run",
"on",
"this",
"machine?"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskInProgress.java#L1374-L1377 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/EigenOps_DDRM.java | EigenOps_DDRM.computeEigenValue | public static double computeEigenValue(DMatrixRMaj A , DMatrixRMaj eigenVector )
{
double bottom = VectorVectorMult_DDRM.innerProd(eigenVector,eigenVector);
double top = VectorVectorMult_DDRM.innerProdA(eigenVector,A,eigenVector);
return top/bottom;
} | java | public static double computeEigenValue(DMatrixRMaj A , DMatrixRMaj eigenVector )
{
double bottom = VectorVectorMult_DDRM.innerProd(eigenVector,eigenVector);
double top = VectorVectorMult_DDRM.innerProdA(eigenVector,A,eigenVector);
return top/bottom;
} | [
"public",
"static",
"double",
"computeEigenValue",
"(",
"DMatrixRMaj",
"A",
",",
"DMatrixRMaj",
"eigenVector",
")",
"{",
"double",
"bottom",
"=",
"VectorVectorMult_DDRM",
".",
"innerProd",
"(",
"eigenVector",
",",
"eigenVector",
")",
";",
"double",
"top",
"=",
"... | <p>
Given matrix A and an eigen vector of A, compute the corresponding eigen value. This is
the Rayleigh quotient.<br>
<br>
x<sup>T</sup>Ax / x<sup>T</sup>x
</p>
@param A Matrix. Not modified.
@param eigenVector An eigen vector of A. Not modified.
@return The corresponding eigen value. | [
"<p",
">",
"Given",
"matrix",
"A",
"and",
"an",
"eigen",
"vector",
"of",
"A",
"compute",
"the",
"corresponding",
"eigen",
"value",
".",
"This",
"is",
"the",
"Rayleigh",
"quotient",
".",
"<br",
">",
"<br",
">",
"x<sup",
">",
"T<",
"/",
"sup",
">",
"Ax... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/EigenOps_DDRM.java#L51-L57 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/AsyncLookupInBuilder.java | AsyncLookupInBuilder.getCount | public AsyncLookupInBuilder getCount(String path, SubdocOptionsBuilder optionsBuilder) {
if (path == null) {
throw new IllegalArgumentException("Path is mandatory for subdoc get count");
}
if (optionsBuilder.createPath()) {
throw new IllegalArgumentException("Options createPath are not supported for lookup");
}
this.specs.add(new LookupSpec(Lookup.GET_COUNT, path, optionsBuilder));
return this;
} | java | public AsyncLookupInBuilder getCount(String path, SubdocOptionsBuilder optionsBuilder) {
if (path == null) {
throw new IllegalArgumentException("Path is mandatory for subdoc get count");
}
if (optionsBuilder.createPath()) {
throw new IllegalArgumentException("Options createPath are not supported for lookup");
}
this.specs.add(new LookupSpec(Lookup.GET_COUNT, path, optionsBuilder));
return this;
} | [
"public",
"AsyncLookupInBuilder",
"getCount",
"(",
"String",
"path",
",",
"SubdocOptionsBuilder",
"optionsBuilder",
")",
"{",
"if",
"(",
"path",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Path is mandatory for subdoc get count\"",
")",
... | Get the count of values inside the JSON document.
This method is only available with Couchbase Server 5.0 and later.
@param path the path inside the document where to get the count from.
@param optionsBuilder {@link SubdocOptionsBuilder}
@return this builder for chaining. | [
"Get",
"the",
"count",
"of",
"values",
"inside",
"the",
"JSON",
"document",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/AsyncLookupInBuilder.java#L406-L415 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java | CommonMpJwtFat.addApiOutputExpectation | public ResponseFullExpectation addApiOutputExpectation(String api, String claimIdentifier, String key, String value) throws Exception {
return new ResponseFullExpectation(MpJwtFatConstants.STRING_MATCHES, buildStringToCheck(claimIdentifier, key, value), "API " + api + " did NOT return the correct value ("
+ value + ").");
} | java | public ResponseFullExpectation addApiOutputExpectation(String api, String claimIdentifier, String key, String value) throws Exception {
return new ResponseFullExpectation(MpJwtFatConstants.STRING_MATCHES, buildStringToCheck(claimIdentifier, key, value), "API " + api + " did NOT return the correct value ("
+ value + ").");
} | [
"public",
"ResponseFullExpectation",
"addApiOutputExpectation",
"(",
"String",
"api",
",",
"String",
"claimIdentifier",
",",
"String",
"key",
",",
"String",
"value",
")",
"throws",
"Exception",
"{",
"return",
"new",
"ResponseFullExpectation",
"(",
"MpJwtFatConstants",
... | Create a response expectation for the key/value being checked
@param api - The api that was used to retrieve the claim
@param claimIdentifier - A more descriptive identifier for the claim
@param key - the claim's key
@param value - the claims value
@return - returns a new Full Response expectation with a properly formatted string to look for the specified claim
@throws Exception | [
"Create",
"a",
"response",
"expectation",
"for",
"the",
"key",
"/",
"value",
"being",
"checked"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java#L264-L268 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowRunActionScopedRepetitionsInner.java | WorkflowRunActionScopedRepetitionsInner.getAsync | public Observable<WorkflowRunActionRepetitionDefinitionInner> getAsync(String resourceGroupName, String workflowName, String runName, String actionName, String repetitionName) {
return getWithServiceResponseAsync(resourceGroupName, workflowName, runName, actionName, repetitionName).map(new Func1<ServiceResponse<WorkflowRunActionRepetitionDefinitionInner>, WorkflowRunActionRepetitionDefinitionInner>() {
@Override
public WorkflowRunActionRepetitionDefinitionInner call(ServiceResponse<WorkflowRunActionRepetitionDefinitionInner> response) {
return response.body();
}
});
} | java | public Observable<WorkflowRunActionRepetitionDefinitionInner> getAsync(String resourceGroupName, String workflowName, String runName, String actionName, String repetitionName) {
return getWithServiceResponseAsync(resourceGroupName, workflowName, runName, actionName, repetitionName).map(new Func1<ServiceResponse<WorkflowRunActionRepetitionDefinitionInner>, WorkflowRunActionRepetitionDefinitionInner>() {
@Override
public WorkflowRunActionRepetitionDefinitionInner call(ServiceResponse<WorkflowRunActionRepetitionDefinitionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"WorkflowRunActionRepetitionDefinitionInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"workflowName",
",",
"String",
"runName",
",",
"String",
"actionName",
",",
"String",
"repetitionName",
")",
"{",
"return",
"... | Get a workflow run action scoped repetition.
@param resourceGroupName The resource group name.
@param workflowName The workflow name.
@param runName The workflow run name.
@param actionName The workflow action name.
@param repetitionName The workflow repetition.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the WorkflowRunActionRepetitionDefinitionInner object | [
"Get",
"a",
"workflow",
"run",
"action",
"scoped",
"repetition",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowRunActionScopedRepetitionsInner.java#L208-L215 |
prestodb/presto | presto-main/src/main/java/com/facebook/presto/execution/ClusterSizeMonitor.java | ClusterSizeMonitor.waitForMinimumWorkers | public synchronized ListenableFuture<?> waitForMinimumWorkers()
{
if (currentCount >= executionMinCount) {
return immediateFuture(null);
}
SettableFuture<?> future = SettableFuture.create();
futures.add(future);
// if future does not finish in wait period, complete with an exception
ScheduledFuture<?> timeoutTask = executor.schedule(
() -> {
synchronized (this) {
future.setException(new PrestoException(
GENERIC_INSUFFICIENT_RESOURCES,
format("Insufficient active worker nodes. Waited %s for at least %s workers, but only %s workers are active", executionMaxWait, executionMinCount, currentCount)));
}
},
executionMaxWait.toMillis(),
MILLISECONDS);
// remove future if finished (e.g., canceled, timed out)
future.addListener(() -> {
timeoutTask.cancel(true);
removeFuture(future);
}, executor);
return future;
} | java | public synchronized ListenableFuture<?> waitForMinimumWorkers()
{
if (currentCount >= executionMinCount) {
return immediateFuture(null);
}
SettableFuture<?> future = SettableFuture.create();
futures.add(future);
// if future does not finish in wait period, complete with an exception
ScheduledFuture<?> timeoutTask = executor.schedule(
() -> {
synchronized (this) {
future.setException(new PrestoException(
GENERIC_INSUFFICIENT_RESOURCES,
format("Insufficient active worker nodes. Waited %s for at least %s workers, but only %s workers are active", executionMaxWait, executionMinCount, currentCount)));
}
},
executionMaxWait.toMillis(),
MILLISECONDS);
// remove future if finished (e.g., canceled, timed out)
future.addListener(() -> {
timeoutTask.cancel(true);
removeFuture(future);
}, executor);
return future;
} | [
"public",
"synchronized",
"ListenableFuture",
"<",
"?",
">",
"waitForMinimumWorkers",
"(",
")",
"{",
"if",
"(",
"currentCount",
">=",
"executionMinCount",
")",
"{",
"return",
"immediateFuture",
"(",
"null",
")",
";",
"}",
"SettableFuture",
"<",
"?",
">",
"futu... | Returns a listener that completes when the minimum number of workers for the cluster has been met.
Note: caller should not add a listener using the direct executor, as this can delay the
notifications for other listeners. | [
"Returns",
"a",
"listener",
"that",
"completes",
"when",
"the",
"minimum",
"number",
"of",
"workers",
"for",
"the",
"cluster",
"has",
"been",
"met",
".",
"Note",
":",
"caller",
"should",
"not",
"add",
"a",
"listener",
"using",
"the",
"direct",
"executor",
... | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/execution/ClusterSizeMonitor.java#L132-L160 |
gallandarakhneorg/afc | advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java | BusItinerary.putHaltOnRoad | @SuppressWarnings("checkstyle:nestedifdepth")
public boolean putHaltOnRoad(BusItineraryHalt halt, RoadSegment road) {
if (contains(halt)) {
final BusStop stop = halt.getBusStop();
if (stop != null) {
final Point2d stopPosition = stop.getPosition2D();
if (stopPosition != null) {
final int idx = indexOf(road);
if (idx >= 0) {
final Point1d pos = road.getNearestPosition(stopPosition);
if (pos != null) {
halt.setRoadSegmentIndex(idx);
halt.setPositionOnSegment(pos.getCurvilineCoordinate());
halt.checkPrimitiveValidity();
fireShapeChanged(new BusChangeEvent(this,
BusChangeEventType.ITINERARY_CHANGED,
null,
-1,
"shape", //$NON-NLS-1$
null,
null));
checkPrimitiveValidity();
return true;
}
}
return false;
}
}
}
return true;
} | java | @SuppressWarnings("checkstyle:nestedifdepth")
public boolean putHaltOnRoad(BusItineraryHalt halt, RoadSegment road) {
if (contains(halt)) {
final BusStop stop = halt.getBusStop();
if (stop != null) {
final Point2d stopPosition = stop.getPosition2D();
if (stopPosition != null) {
final int idx = indexOf(road);
if (idx >= 0) {
final Point1d pos = road.getNearestPosition(stopPosition);
if (pos != null) {
halt.setRoadSegmentIndex(idx);
halt.setPositionOnSegment(pos.getCurvilineCoordinate());
halt.checkPrimitiveValidity();
fireShapeChanged(new BusChangeEvent(this,
BusChangeEventType.ITINERARY_CHANGED,
null,
-1,
"shape", //$NON-NLS-1$
null,
null));
checkPrimitiveValidity();
return true;
}
}
return false;
}
}
}
return true;
} | [
"@",
"SuppressWarnings",
"(",
"\"checkstyle:nestedifdepth\"",
")",
"public",
"boolean",
"putHaltOnRoad",
"(",
"BusItineraryHalt",
"halt",
",",
"RoadSegment",
"road",
")",
"{",
"if",
"(",
"contains",
"(",
"halt",
")",
")",
"{",
"final",
"BusStop",
"stop",
"=",
... | Put the given bus itinerary halt on the nearest
point on road.
@param halt is the halt to put on the road.
@param road is the road.
@return <code>false</code> if the road was not found;
otherwise <code>true</code>. If the bus halt is not binded
to a valid bus stop, replies <code>true</code> also. | [
"Put",
"the",
"given",
"bus",
"itinerary",
"halt",
"on",
"the",
"nearest",
"point",
"on",
"road",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java#L2068-L2098 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/io/InputSourceFactory.java | InputSourceFactory.constructCharArraySource | public static WstxInputSource constructCharArraySource
(WstxInputSource parent, String fromEntity,
char[] text, int offset, int len, Location loc, URL src)
{
SystemId sysId = SystemId.construct(loc.getSystemId(), src);
return new CharArraySource(parent, fromEntity, text, offset, len, loc, sysId);
} | java | public static WstxInputSource constructCharArraySource
(WstxInputSource parent, String fromEntity,
char[] text, int offset, int len, Location loc, URL src)
{
SystemId sysId = SystemId.construct(loc.getSystemId(), src);
return new CharArraySource(parent, fromEntity, text, offset, len, loc, sysId);
} | [
"public",
"static",
"WstxInputSource",
"constructCharArraySource",
"(",
"WstxInputSource",
"parent",
",",
"String",
"fromEntity",
",",
"char",
"[",
"]",
"text",
",",
"int",
"offset",
",",
"int",
"len",
",",
"Location",
"loc",
",",
"URL",
"src",
")",
"{",
"Sy... | Factory method usually used to expand internal parsed entities; in
which case context remains mostly the same. | [
"Factory",
"method",
"usually",
"used",
"to",
"expand",
"internal",
"parsed",
"entities",
";",
"in",
"which",
"case",
"context",
"remains",
"mostly",
"the",
"same",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/io/InputSourceFactory.java#L69-L75 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/StringUtils.java | StringUtils.indexOf | public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0);
} | java | public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0);
} | [
"public",
"static",
"int",
"indexOf",
"(",
"final",
"CharSequence",
"seq",
",",
"final",
"CharSequence",
"searchSeq",
")",
"{",
"if",
"(",
"seq",
"==",
"null",
"||",
"searchSeq",
"==",
"null",
")",
"{",
"return",
"INDEX_NOT_FOUND",
";",
"}",
"return",
"Cha... | <p>Finds the first index within a CharSequence, handling {@code null}.
This method uses {@link String#indexOf(String, int)} if possible.</p>
<p>A {@code null} CharSequence will return {@code -1}.</p>
<pre>
StringUtils.indexOf(null, *) = -1
StringUtils.indexOf(*, null) = -1
StringUtils.indexOf("", "") = 0
StringUtils.indexOf("", *) = -1 (except when * = "")
StringUtils.indexOf("aabaabaa", "a") = 0
StringUtils.indexOf("aabaabaa", "b") = 2
StringUtils.indexOf("aabaabaa", "ab") = 1
StringUtils.indexOf("aabaabaa", "") = 0
</pre>
@param seq the CharSequence to check, may be null
@param searchSeq the CharSequence to find, may be null
@return the first index of the search CharSequence,
-1 if no match or {@code null} string input
@since 2.0
@since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence) | [
"<p",
">",
"Finds",
"the",
"first",
"index",
"within",
"a",
"CharSequence",
"handling",
"{",
"@code",
"null",
"}",
".",
"This",
"method",
"uses",
"{",
"@link",
"String#indexOf",
"(",
"String",
"int",
")",
"}",
"if",
"possible",
".",
"<",
"/",
"p",
">"
... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L1415-L1420 |
joniles/mpxj | src/main/java/net/sf/mpxj/mspdi/MSPDIWriter.java | MSPDIWriter.writeExceptions12 | private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)
{
Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();
calendar.setExceptions(ce);
List<Exceptions.Exception> el = ce.getException();
for (ProjectCalendarException exception : exceptions)
{
Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();
el.add(ex);
ex.setName(exception.getName());
boolean working = exception.getWorking();
ex.setDayWorking(Boolean.valueOf(working));
if (exception.getRecurring() == null)
{
ex.setEnteredByOccurrences(Boolean.FALSE);
ex.setOccurrences(BigInteger.ONE);
ex.setType(BigInteger.ONE);
}
else
{
populateRecurringException(exception, ex);
}
Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();
ex.setTimePeriod(period);
period.setFromDate(exception.getFromDate());
period.setToDate(exception.getToDate());
if (working)
{
Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();
ex.setWorkingTimes(times);
List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();
for (DateRange range : exception)
{
Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();
timesList.add(time);
time.setFromTime(range.getStart());
time.setToTime(range.getEnd());
}
}
}
} | java | private void writeExceptions12(Project.Calendars.Calendar calendar, List<ProjectCalendarException> exceptions)
{
Exceptions ce = m_factory.createProjectCalendarsCalendarExceptions();
calendar.setExceptions(ce);
List<Exceptions.Exception> el = ce.getException();
for (ProjectCalendarException exception : exceptions)
{
Exceptions.Exception ex = m_factory.createProjectCalendarsCalendarExceptionsException();
el.add(ex);
ex.setName(exception.getName());
boolean working = exception.getWorking();
ex.setDayWorking(Boolean.valueOf(working));
if (exception.getRecurring() == null)
{
ex.setEnteredByOccurrences(Boolean.FALSE);
ex.setOccurrences(BigInteger.ONE);
ex.setType(BigInteger.ONE);
}
else
{
populateRecurringException(exception, ex);
}
Project.Calendars.Calendar.Exceptions.Exception.TimePeriod period = m_factory.createProjectCalendarsCalendarExceptionsExceptionTimePeriod();
ex.setTimePeriod(period);
period.setFromDate(exception.getFromDate());
period.setToDate(exception.getToDate());
if (working)
{
Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimes();
ex.setWorkingTimes(times);
List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> timesList = times.getWorkingTime();
for (DateRange range : exception)
{
Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime time = m_factory.createProjectCalendarsCalendarExceptionsExceptionWorkingTimesWorkingTime();
timesList.add(time);
time.setFromTime(range.getStart());
time.setToTime(range.getEnd());
}
}
}
} | [
"private",
"void",
"writeExceptions12",
"(",
"Project",
".",
"Calendars",
".",
"Calendar",
"calendar",
",",
"List",
"<",
"ProjectCalendarException",
">",
"exceptions",
")",
"{",
"Exceptions",
"ce",
"=",
"m_factory",
".",
"createProjectCalendarsCalendarExceptions",
"("... | Write exceptions into the format used by MSPDI files from
Project 2007 onwards.
@param calendar parent calendar
@param exceptions list of exceptions | [
"Write",
"exceptions",
"into",
"the",
"format",
"used",
"by",
"MSPDI",
"files",
"from",
"Project",
"2007",
"onwards",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIWriter.java#L529-L576 |
tempodb/tempodb-java | src/main/java/com/tempodb/Client.java | Client.readDataPoints | public Cursor<DataPoint> readDataPoints(Series series, Interval interval, DateTimeZone timezone, Rollup rollup, Interpolation interpolation) {
checkNotNull(series);
checkNotNull(interval);
checkNotNull(timezone);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/series/key/%s/segment/", API_VERSION, urlencode(series.getKey())));
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: key: %s, interval: %s, rollup: %s, timezone: %s", series.getKey(), interval, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<DataPoint> cursor = new DataPointCursor(uri, this);
return cursor;
} | java | public Cursor<DataPoint> readDataPoints(Series series, Interval interval, DateTimeZone timezone, Rollup rollup, Interpolation interpolation) {
checkNotNull(series);
checkNotNull(interval);
checkNotNull(timezone);
URI uri = null;
try {
URIBuilder builder = new URIBuilder(String.format("/%s/series/key/%s/segment/", API_VERSION, urlencode(series.getKey())));
addInterpolationToURI(builder, interpolation);
addIntervalToURI(builder, interval);
addRollupToURI(builder, rollup);
addTimeZoneToURI(builder, timezone);
uri = builder.build();
} catch (URISyntaxException e) {
String message = String.format("Could not build URI with inputs: key: %s, interval: %s, rollup: %s, timezone: %s", series.getKey(), interval, rollup, timezone);
throw new IllegalArgumentException(message, e);
}
Cursor<DataPoint> cursor = new DataPointCursor(uri, this);
return cursor;
} | [
"public",
"Cursor",
"<",
"DataPoint",
">",
"readDataPoints",
"(",
"Series",
"series",
",",
"Interval",
"interval",
",",
"DateTimeZone",
"timezone",
",",
"Rollup",
"rollup",
",",
"Interpolation",
"interpolation",
")",
"{",
"checkNotNull",
"(",
"series",
")",
";",... | Returns a cursor of datapoints specified by series.
@param series The series
@param interval An interval of time for the query (start/end datetimes)
@param timezone The time zone for the returned datapoints.
@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 Cursor
@since 1.0.0 | [
"Returns",
"a",
"cursor",
"of",
"datapoints",
"specified",
"by",
"series",
"."
] | train | https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L655-L675 |
opencypher/openCypher | tools/grammar/src/main/java/org/opencypher/grammar/Description.java | Description.emitLine | private static int emitLine( StringBuilder target, char[] buffer, int start, int end, int indentation )
{
int last = start;
for ( int pos = start, cp; pos < end; pos += charCount( cp ) )
{
cp = codePointAt( buffer, pos );
if ( cp == '\n' )
{
end = pos + 1;
}
if ( indentation > 0 )
{
if ( --indentation == 0 )
{
start = pos + 1;
}
last = pos;
}
else if ( !isWhitespace( cp ) )
{
last = pos + 1;
}
}
target.append( buffer, start, last - start );
return end;
} | java | private static int emitLine( StringBuilder target, char[] buffer, int start, int end, int indentation )
{
int last = start;
for ( int pos = start, cp; pos < end; pos += charCount( cp ) )
{
cp = codePointAt( buffer, pos );
if ( cp == '\n' )
{
end = pos + 1;
}
if ( indentation > 0 )
{
if ( --indentation == 0 )
{
start = pos + 1;
}
last = pos;
}
else if ( !isWhitespace( cp ) )
{
last = pos + 1;
}
}
target.append( buffer, start, last - start );
return end;
} | [
"private",
"static",
"int",
"emitLine",
"(",
"StringBuilder",
"target",
",",
"char",
"[",
"]",
"buffer",
",",
"int",
"start",
",",
"int",
"end",
",",
"int",
"indentation",
")",
"{",
"int",
"last",
"=",
"start",
";",
"for",
"(",
"int",
"pos",
"=",
"st... | Emits the line that starts at {@code start} position, and ends at a newline or the {@code end} position.
@return the start position of the next line (the {@code end} position | [
"Emits",
"the",
"line",
"that",
"starts",
"at",
"{",
"@code",
"start",
"}",
"position",
"and",
"ends",
"at",
"a",
"newline",
"or",
"the",
"{",
"@code",
"end",
"}",
"position",
"."
] | train | https://github.com/opencypher/openCypher/blob/eb780caea625900ddbedd28a1eac9a5dbe09c5f0/tools/grammar/src/main/java/org/opencypher/grammar/Description.java#L140-L165 |
rapidoid/rapidoid | rapidoid-rest/src/main/java/org/rapidoid/setup/App.java | App.bootstrap | public static synchronized void bootstrap(String[] args, String... extraArgs) {
AppStarter.startUp(args, extraArgs);
boot();
App.scan(); // scan classpath for beans
// finish initialization and start the application
onAppReady();
boot();
} | java | public static synchronized void bootstrap(String[] args, String... extraArgs) {
AppStarter.startUp(args, extraArgs);
boot();
App.scan(); // scan classpath for beans
// finish initialization and start the application
onAppReady();
boot();
} | [
"public",
"static",
"synchronized",
"void",
"bootstrap",
"(",
"String",
"[",
"]",
"args",
",",
"String",
"...",
"extraArgs",
")",
"{",
"AppStarter",
".",
"startUp",
"(",
"args",
",",
"extraArgs",
")",
";",
"boot",
"(",
")",
";",
"App",
".",
"scan",
"("... | Initializes the app in non-atomic way.
Then scans the classpath for beans.
Then starts serving requests immediately when routes are configured. | [
"Initializes",
"the",
"app",
"in",
"non",
"-",
"atomic",
"way",
".",
"Then",
"scans",
"the",
"classpath",
"for",
"beans",
".",
"Then",
"starts",
"serving",
"requests",
"immediately",
"when",
"routes",
"are",
"configured",
"."
] | train | https://github.com/rapidoid/rapidoid/blob/1775344bcf4abbee289d474b34d553ff6bc821b0/rapidoid-rest/src/main/java/org/rapidoid/setup/App.java#L107-L118 |
strator-dev/greenpepper | greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Repository.java | Repository.removeSpecification | public void removeSpecification(Specification specification) throws GreenPepperServerException
{
if(!specifications.contains(specification))
throw new GreenPepperServerException( GreenPepperServerErrorKey.SPECIFICATION_NOT_FOUND, "Specification not found");
specifications.remove(specification);
specification.setRepository(null);
} | java | public void removeSpecification(Specification specification) throws GreenPepperServerException
{
if(!specifications.contains(specification))
throw new GreenPepperServerException( GreenPepperServerErrorKey.SPECIFICATION_NOT_FOUND, "Specification not found");
specifications.remove(specification);
specification.setRepository(null);
} | [
"public",
"void",
"removeSpecification",
"(",
"Specification",
"specification",
")",
"throws",
"GreenPepperServerException",
"{",
"if",
"(",
"!",
"specifications",
".",
"contains",
"(",
"specification",
")",
")",
"throw",
"new",
"GreenPepperServerException",
"(",
"Gre... | <p>removeSpecification.</p>
@param specification a {@link com.greenpepper.server.domain.Specification} object.
@throws com.greenpepper.server.GreenPepperServerException if any. | [
"<p",
">",
"removeSpecification",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Repository.java#L393-L400 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.correctlySpends | public void correctlySpends(Transaction txContainingThis, int scriptSigIndex, @Nullable TransactionWitness witness, @Nullable Coin value,
Script scriptPubKey, Set<VerifyFlag> verifyFlags) throws ScriptException {
if (ScriptPattern.isP2WPKH(scriptPubKey)) {
// For SegWit, full validation isn't implemented. So we simply check the signature. P2SH_P2WPKH is handled
// by the P2SH code for now.
if (witness.getPushCount() < 2)
throw new ScriptException(ScriptError.SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, witness.toString());
TransactionSignature signature;
try {
signature = TransactionSignature.decodeFromBitcoin(witness.getPush(0), true, true);
} catch (SignatureDecodeException x) {
throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_DER, "Cannot decode", x);
}
ECKey pubkey = ECKey.fromPublicOnly(witness.getPush(1));
Script scriptCode = new ScriptBuilder().data(ScriptBuilder.createP2PKHOutputScript(pubkey).getProgram())
.build();
Sha256Hash sigHash = txContainingThis.hashForWitnessSignature(scriptSigIndex, scriptCode, value,
signature.sigHashMode(), false);
boolean validSig = pubkey.verify(sigHash, signature);
if (!validSig)
throw new ScriptException(ScriptError.SCRIPT_ERR_CHECKSIGVERIFY, "Invalid signature");
} else {
correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, verifyFlags);
}
} | java | public void correctlySpends(Transaction txContainingThis, int scriptSigIndex, @Nullable TransactionWitness witness, @Nullable Coin value,
Script scriptPubKey, Set<VerifyFlag> verifyFlags) throws ScriptException {
if (ScriptPattern.isP2WPKH(scriptPubKey)) {
// For SegWit, full validation isn't implemented. So we simply check the signature. P2SH_P2WPKH is handled
// by the P2SH code for now.
if (witness.getPushCount() < 2)
throw new ScriptException(ScriptError.SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, witness.toString());
TransactionSignature signature;
try {
signature = TransactionSignature.decodeFromBitcoin(witness.getPush(0), true, true);
} catch (SignatureDecodeException x) {
throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_DER, "Cannot decode", x);
}
ECKey pubkey = ECKey.fromPublicOnly(witness.getPush(1));
Script scriptCode = new ScriptBuilder().data(ScriptBuilder.createP2PKHOutputScript(pubkey).getProgram())
.build();
Sha256Hash sigHash = txContainingThis.hashForWitnessSignature(scriptSigIndex, scriptCode, value,
signature.sigHashMode(), false);
boolean validSig = pubkey.verify(sigHash, signature);
if (!validSig)
throw new ScriptException(ScriptError.SCRIPT_ERR_CHECKSIGVERIFY, "Invalid signature");
} else {
correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, verifyFlags);
}
} | [
"public",
"void",
"correctlySpends",
"(",
"Transaction",
"txContainingThis",
",",
"int",
"scriptSigIndex",
",",
"@",
"Nullable",
"TransactionWitness",
"witness",
",",
"@",
"Nullable",
"Coin",
"value",
",",
"Script",
"scriptPubKey",
",",
"Set",
"<",
"VerifyFlag",
"... | Verifies that this script (interpreted as a scriptSig) correctly spends the given scriptPubKey.
@param txContainingThis The transaction in which this input scriptSig resides.
Accessing txContainingThis from another thread while this method runs results in undefined behavior.
@param scriptSigIndex The index in txContainingThis of the scriptSig (note: NOT the index of the scriptPubKey).
@param scriptPubKey The connected scriptPubKey containing the conditions needed to claim the value.
@param witness Transaction witness belonging to the transaction input containing this script. Needed for SegWit.
@param value Value of the output. Needed for SegWit scripts.
@param verifyFlags Each flag enables one validation rule. | [
"Verifies",
"that",
"this",
"script",
"(",
"interpreted",
"as",
"a",
"scriptSig",
")",
"correctly",
"spends",
"the",
"given",
"scriptPubKey",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L1576-L1600 |
EdwardRaff/JSAT | JSAT/src/jsat/distributions/kernels/KernelPoints.java | KernelPoints.setMaxBudget | public void setMaxBudget(int maxBudget)
{
if(maxBudget < 1)
throw new IllegalArgumentException("Budget must be positive, not " + maxBudget);
this.maxBudget = maxBudget;
for(KernelPoint kp : points)
kp.setMaxBudget(maxBudget);
} | java | public void setMaxBudget(int maxBudget)
{
if(maxBudget < 1)
throw new IllegalArgumentException("Budget must be positive, not " + maxBudget);
this.maxBudget = maxBudget;
for(KernelPoint kp : points)
kp.setMaxBudget(maxBudget);
} | [
"public",
"void",
"setMaxBudget",
"(",
"int",
"maxBudget",
")",
"{",
"if",
"(",
"maxBudget",
"<",
"1",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Budget must be positive, not \"",
"+",
"maxBudget",
")",
";",
"this",
".",
"maxBudget",
"=",
"maxBudge... | Sets the maximum budget for support vectors to allow. Setting to
{@link Integer#MAX_VALUE} is essentially an unbounded number of support
vectors. Increasing the budget after adding the first vector is always
allowed, but it may not be possible to reduce the number of current
support vectors is above the desired budget.
@param maxBudget the maximum number of allowed support vectors | [
"Sets",
"the",
"maximum",
"budget",
"for",
"support",
"vectors",
"to",
"allow",
".",
"Setting",
"to",
"{",
"@link",
"Integer#MAX_VALUE",
"}",
"is",
"essentially",
"an",
"unbounded",
"number",
"of",
"support",
"vectors",
".",
"Increasing",
"the",
"budget",
"aft... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/KernelPoints.java#L156-L163 |
sporniket/core | sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/XmlStringTools.java | XmlStringTools.appendTextInsideTag | public static StringBuffer appendTextInsideTag(StringBuffer buffer, String text, String tag)
{
return appendTextInsideTag(buffer, text, tag, EMPTY_MAP);
} | java | public static StringBuffer appendTextInsideTag(StringBuffer buffer, String text, String tag)
{
return appendTextInsideTag(buffer, text, tag, EMPTY_MAP);
} | [
"public",
"static",
"StringBuffer",
"appendTextInsideTag",
"(",
"StringBuffer",
"buffer",
",",
"String",
"text",
",",
"String",
"tag",
")",
"{",
"return",
"appendTextInsideTag",
"(",
"buffer",
",",
"text",
",",
"tag",
",",
"EMPTY_MAP",
")",
";",
"}"
] | Wrap a text inside a tag.
@param buffer
StringBuffer to fill
@param text
the text to wrap
@param tag
the tag to use
@return the buffer | [
"Wrap",
"a",
"text",
"inside",
"a",
"tag",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/XmlStringTools.java#L386-L389 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java | KeyVaultClientImpl.deleteKeyAsync | public Observable<KeyBundle> deleteKeyAsync(String vaultBaseUrl, String keyName) {
return deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName).map(new Func1<ServiceResponse<KeyBundle>, KeyBundle>() {
@Override
public KeyBundle call(ServiceResponse<KeyBundle> response) {
return response.body();
}
});
} | java | public Observable<KeyBundle> deleteKeyAsync(String vaultBaseUrl, String keyName) {
return deleteKeyWithServiceResponseAsync(vaultBaseUrl, keyName).map(new Func1<ServiceResponse<KeyBundle>, KeyBundle>() {
@Override
public KeyBundle call(ServiceResponse<KeyBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"KeyBundle",
">",
"deleteKeyAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"keyName",
")",
"{",
"return",
"deleteKeyWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"keyName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"Se... | Deletes a key of any type from storage in Azure Key Vault. The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. Authorization: Requires the keys/delete permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key to delete.
@return the observable to the KeyBundle object | [
"Deletes",
"a",
"key",
"of",
"any",
"type",
"from",
"storage",
"in",
"Azure",
"Key",
"Vault",
".",
"The",
"delete",
"key",
"operation",
"cannot",
"be",
"used",
"to",
"remove",
"individual",
"versions",
"of",
"a",
"key",
".",
"This",
"operation",
"removes",... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java#L859-L866 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/BizwifiAPI.java | BizwifiAPI.finishpageSet | public static BaseResult finishpageSet(String accessToken, FinishPageSet finishPageSet) {
return finishpageSet(accessToken, JsonUtil.toJSONString(finishPageSet));
} | java | public static BaseResult finishpageSet(String accessToken, FinishPageSet finishPageSet) {
return finishpageSet(accessToken, JsonUtil.toJSONString(finishPageSet));
} | [
"public",
"static",
"BaseResult",
"finishpageSet",
"(",
"String",
"accessToken",
",",
"FinishPageSet",
"finishPageSet",
")",
"{",
"return",
"finishpageSet",
"(",
"accessToken",
",",
"JsonUtil",
".",
"toJSONString",
"(",
"finishPageSet",
")",
")",
";",
"}"
] | 连Wi-Fi小程序-连Wi-Fi完成页跳转小程序
场景介绍:
设置需要跳转的小程序,连网完成点击“完成”按钮,即可进入设置的小程序。
注:只能跳转与公众号关联的小程序。
@param accessToken accessToken
@param finishPageSet finishPageSet
@return BaseResult | [
"连Wi",
"-",
"Fi小程序",
"-",
"连Wi",
"-",
"Fi完成页跳转小程序",
"场景介绍:",
"设置需要跳转的小程序,连网完成点击“完成”按钮,即可进入设置的小程序。",
"注:只能跳转与公众号关联的小程序。"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/BizwifiAPI.java#L99-L101 |
casmi/casmi | src/main/java/casmi/graphics/color/CMYKColor.java | CMYKColor.getComplementaryColor | public CMYKColor getComplementaryColor() {
double[] rgb = CMYKColor.getRGB(cyan, magenta, yellow, black);
double[] cmyk = CMYKColor.getCMYK(1.0 - rgb[0], 1.0 - rgb[1], 1.0 - rgb[2]);
return new CMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]);
} | java | public CMYKColor getComplementaryColor() {
double[] rgb = CMYKColor.getRGB(cyan, magenta, yellow, black);
double[] cmyk = CMYKColor.getCMYK(1.0 - rgb[0], 1.0 - rgb[1], 1.0 - rgb[2]);
return new CMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]);
} | [
"public",
"CMYKColor",
"getComplementaryColor",
"(",
")",
"{",
"double",
"[",
"]",
"rgb",
"=",
"CMYKColor",
".",
"getRGB",
"(",
"cyan",
",",
"magenta",
",",
"yellow",
",",
"black",
")",
";",
"double",
"[",
"]",
"cmyk",
"=",
"CMYKColor",
".",
"getCMYK",
... | Returns a Color object that shows a complementary color.
@return a complementary Color object. | [
"Returns",
"a",
"Color",
"object",
"that",
"shows",
"a",
"complementary",
"color",
"."
] | train | https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/color/CMYKColor.java#L196-L200 |
xfcjscn/sudoor-server-lib | src/main/java/net/gplatform/sudoor/server/cors/StringManager.java | StringManager.getManager | public static final synchronized StringManager getManager(
String packageName, Locale locale) {
Map<Locale,StringManager> map = managers.get(packageName);
if (map == null) {
/*
* Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.
* Expansion occurs when size() exceeds capacity. Therefore keep
* size at or below capacity.
* removeEldestEntry() executes after insertion therefore the test
* for removal needs to use one less than the maximum desired size
*
*/
map = new LinkedHashMap<Locale,StringManager>(LOCALE_CACHE_SIZE, 1, true) {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(
Map.Entry<Locale,StringManager> eldest) {
if (size() > (LOCALE_CACHE_SIZE - 1)) {
return true;
}
return false;
}
};
managers.put(packageName, map);
}
StringManager mgr = map.get(locale);
if (mgr == null) {
mgr = new StringManager(packageName, locale);
map.put(locale, mgr);
}
return mgr;
} | java | public static final synchronized StringManager getManager(
String packageName, Locale locale) {
Map<Locale,StringManager> map = managers.get(packageName);
if (map == null) {
/*
* Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.
* Expansion occurs when size() exceeds capacity. Therefore keep
* size at or below capacity.
* removeEldestEntry() executes after insertion therefore the test
* for removal needs to use one less than the maximum desired size
*
*/
map = new LinkedHashMap<Locale,StringManager>(LOCALE_CACHE_SIZE, 1, true) {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(
Map.Entry<Locale,StringManager> eldest) {
if (size() > (LOCALE_CACHE_SIZE - 1)) {
return true;
}
return false;
}
};
managers.put(packageName, map);
}
StringManager mgr = map.get(locale);
if (mgr == null) {
mgr = new StringManager(packageName, locale);
map.put(locale, mgr);
}
return mgr;
} | [
"public",
"static",
"final",
"synchronized",
"StringManager",
"getManager",
"(",
"String",
"packageName",
",",
"Locale",
"locale",
")",
"{",
"Map",
"<",
"Locale",
",",
"StringManager",
">",
"map",
"=",
"managers",
".",
"get",
"(",
"packageName",
")",
";",
"i... | Get the StringManager for a particular package and Locale. If a manager
for a package/Locale combination already exists, it will be reused, else
a new StringManager will be created and returned.
@param packageName The package name
@param locale The Locale | [
"Get",
"the",
"StringManager",
"for",
"a",
"particular",
"package",
"and",
"Locale",
".",
"If",
"a",
"manager",
"for",
"a",
"package",
"/",
"Locale",
"combination",
"already",
"exists",
"it",
"will",
"be",
"reused",
"else",
"a",
"new",
"StringManager",
"will... | train | https://github.com/xfcjscn/sudoor-server-lib/blob/37dc1996eaa9cad25c82abd1de315ba565e32097/src/main/java/net/gplatform/sudoor/server/cors/StringManager.java#L222-L255 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/Channel.java | Channel.unregisterBlockListener | public boolean unregisterBlockListener(String handle) throws InvalidArgumentException {
if (shutdown) {
throw new InvalidArgumentException(format("Channel %s has been shutdown.", name));
}
checkHandle(BLOCK_LISTENER_TAG, handle);
logger.trace(format("Unregister BlockListener with handle %s.", handle));
LinkedHashMap<String, BL> lblockListeners = blockListeners;
if (lblockListeners == null) {
return false;
}
synchronized (lblockListeners) {
return null != lblockListeners.remove(handle);
}
} | java | public boolean unregisterBlockListener(String handle) throws InvalidArgumentException {
if (shutdown) {
throw new InvalidArgumentException(format("Channel %s has been shutdown.", name));
}
checkHandle(BLOCK_LISTENER_TAG, handle);
logger.trace(format("Unregister BlockListener with handle %s.", handle));
LinkedHashMap<String, BL> lblockListeners = blockListeners;
if (lblockListeners == null) {
return false;
}
synchronized (lblockListeners) {
return null != lblockListeners.remove(handle);
}
} | [
"public",
"boolean",
"unregisterBlockListener",
"(",
"String",
"handle",
")",
"throws",
"InvalidArgumentException",
"{",
"if",
"(",
"shutdown",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"format",
"(",
"\"Channel %s has been shutdown.\"",
",",
"name",
... | Unregister a block listener.
@param handle of Block listener to remove.
@return false if not found.
@throws InvalidArgumentException if the channel is shutdown or invalid arguments. | [
"Unregister",
"a",
"block",
"listener",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L5576-L5595 |
xmlet/HtmlFlow | src/main/java/htmlflow/HtmlView.java | HtmlView.addPartial | public final <U> void addPartial(HtmlView<U> partial, U model) {
getVisitor().closeBeginTag();
partial.getVisitor().depth = getVisitor().depth;
if (this.getVisitor().isWriting())
getVisitor().write(partial.render(model));
} | java | public final <U> void addPartial(HtmlView<U> partial, U model) {
getVisitor().closeBeginTag();
partial.getVisitor().depth = getVisitor().depth;
if (this.getVisitor().isWriting())
getVisitor().write(partial.render(model));
} | [
"public",
"final",
"<",
"U",
">",
"void",
"addPartial",
"(",
"HtmlView",
"<",
"U",
">",
"partial",
",",
"U",
"model",
")",
"{",
"getVisitor",
"(",
")",
".",
"closeBeginTag",
"(",
")",
";",
"partial",
".",
"getVisitor",
"(",
")",
".",
"depth",
"=",
... | Adds a partial view to this view.
@param partial inner view.
@param model the domain object bound to the partial view.
@param <U> the type of the domain model of the partial view. | [
"Adds",
"a",
"partial",
"view",
"to",
"this",
"view",
"."
] | train | https://github.com/xmlet/HtmlFlow/blob/5318be5765b0850496645d7c11bdf2848c094b17/src/main/java/htmlflow/HtmlView.java#L170-L175 |
alkacon/opencms-core | src/org/opencms/staticexport/A_CmsStaticExportHandler.java | A_CmsStaticExportHandler.purgeFiles | private void purgeFiles(List<File> files, String vfsName, Set<String> scrubbedFiles) {
for (File file : files) {
purgeFile(file.getAbsolutePath(), vfsName);
String rfsName = CmsFileUtil.normalizePath(
OpenCms.getStaticExportManager().getRfsPrefix(vfsName)
+ "/"
+ file.getAbsolutePath().substring(
OpenCms.getStaticExportManager().getExportPath(vfsName).length()));
rfsName = CmsStringUtil.substitute(rfsName, new String(new char[] {File.separatorChar}), "/");
scrubbedFiles.add(rfsName);
}
} | java | private void purgeFiles(List<File> files, String vfsName, Set<String> scrubbedFiles) {
for (File file : files) {
purgeFile(file.getAbsolutePath(), vfsName);
String rfsName = CmsFileUtil.normalizePath(
OpenCms.getStaticExportManager().getRfsPrefix(vfsName)
+ "/"
+ file.getAbsolutePath().substring(
OpenCms.getStaticExportManager().getExportPath(vfsName).length()));
rfsName = CmsStringUtil.substitute(rfsName, new String(new char[] {File.separatorChar}), "/");
scrubbedFiles.add(rfsName);
}
} | [
"private",
"void",
"purgeFiles",
"(",
"List",
"<",
"File",
">",
"files",
",",
"String",
"vfsName",
",",
"Set",
"<",
"String",
">",
"scrubbedFiles",
")",
"{",
"for",
"(",
"File",
"file",
":",
"files",
")",
"{",
"purgeFile",
"(",
"file",
".",
"getAbsolut... | Purges a list of files from the rfs.<p>
@param files the list of files to purge
@param vfsName the vfs name of the originally file to purge
@param scrubbedFiles the list which stores all the scrubbed files | [
"Purges",
"a",
"list",
"of",
"files",
"from",
"the",
"rfs",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/A_CmsStaticExportHandler.java#L680-L692 |
QSFT/Doradus | doradus-common/src/main/java/com/dell/doradus/common/TenantDefinition.java | TenantDefinition.optionValueToUNode | @SuppressWarnings("unchecked")
private UNode optionValueToUNode(String optName, Object optValue) {
if (!(optValue instanceof Map)) {
if (optValue == null) {
optValue = "";
}
return UNode.createValueNode(optName, optValue.toString(), "option");
}
UNode optNode = UNode.createMapNode(optName, "option");
Map<String, Object> suboptMap = (Map<String,Object>)optValue;
for (String suboptName : suboptMap.keySet()) {
optNode.addChildNode(optionValueToUNode(suboptName, suboptMap.get(suboptName)));
}
return optNode;
} | java | @SuppressWarnings("unchecked")
private UNode optionValueToUNode(String optName, Object optValue) {
if (!(optValue instanceof Map)) {
if (optValue == null) {
optValue = "";
}
return UNode.createValueNode(optName, optValue.toString(), "option");
}
UNode optNode = UNode.createMapNode(optName, "option");
Map<String, Object> suboptMap = (Map<String,Object>)optValue;
for (String suboptName : suboptMap.keySet()) {
optNode.addChildNode(optionValueToUNode(suboptName, suboptMap.get(suboptName)));
}
return optNode;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"UNode",
"optionValueToUNode",
"(",
"String",
"optName",
",",
"Object",
"optValue",
")",
"{",
"if",
"(",
"!",
"(",
"optValue",
"instanceof",
"Map",
")",
")",
"{",
"if",
"(",
"optValue",
"==",
"... | Return a UNode that represents the given option's serialized value. | [
"Return",
"a",
"UNode",
"that",
"represents",
"the",
"given",
"option",
"s",
"serialized",
"value",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TenantDefinition.java#L198-L212 |
czyzby/gdx-lml | kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/reflection/Reflection.java | Reflection.newInstance | public static <Type> Type newInstance(final Class<Type> ofClass) {
try {
return ClassReflection.newInstance(ofClass);
} catch (final Throwable exception) {
throw new GdxRuntimeException("Unable to create a new instance of class: " + ofClass, exception);
}
} | java | public static <Type> Type newInstance(final Class<Type> ofClass) {
try {
return ClassReflection.newInstance(ofClass);
} catch (final Throwable exception) {
throw new GdxRuntimeException("Unable to create a new instance of class: " + ofClass, exception);
}
} | [
"public",
"static",
"<",
"Type",
">",
"Type",
"newInstance",
"(",
"final",
"Class",
"<",
"Type",
">",
"ofClass",
")",
"{",
"try",
"{",
"return",
"ClassReflection",
".",
"newInstance",
"(",
"ofClass",
")",
";",
"}",
"catch",
"(",
"final",
"Throwable",
"ex... | Allows to gracefully create a new instance of class, without having to try-catch exceptions.
@param ofClass instance of this class will be constructed using reflection.
@return a new instance of passed class.
@throws GdxRuntimeException when unable to create a new instance.
@param <Type> type of constructed value. | [
"Allows",
"to",
"gracefully",
"create",
"a",
"new",
"instance",
"of",
"class",
"without",
"having",
"to",
"try",
"-",
"catch",
"exceptions",
"."
] | train | https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/reflection/Reflection.java#L29-L35 |
agapsys/embedded-servlet-container | src/main/java/com/agapsys/jee/ServletContainer.java | ServletContainer.registerServlet | public SC registerServlet(Class<? extends HttpServlet> servletClass, String urlPattern) {
__throwIfInitialized();
if (servletMap.containsKey(urlPattern) && servletMap.get(urlPattern) != servletClass)
throw new IllegalArgumentException(String.format("URL pattern is already associated with another servlet class: %s => %s", urlPattern, servletMap.get(urlPattern)));
servletMap.put(urlPattern, servletClass);
return (SC) this;
} | java | public SC registerServlet(Class<? extends HttpServlet> servletClass, String urlPattern) {
__throwIfInitialized();
if (servletMap.containsKey(urlPattern) && servletMap.get(urlPattern) != servletClass)
throw new IllegalArgumentException(String.format("URL pattern is already associated with another servlet class: %s => %s", urlPattern, servletMap.get(urlPattern)));
servletMap.put(urlPattern, servletClass);
return (SC) this;
} | [
"public",
"SC",
"registerServlet",
"(",
"Class",
"<",
"?",
"extends",
"HttpServlet",
">",
"servletClass",
",",
"String",
"urlPattern",
")",
"{",
"__throwIfInitialized",
"(",
")",
";",
"if",
"(",
"servletMap",
".",
"containsKey",
"(",
"urlPattern",
")",
"&&",
... | Registers a servlet.
@param servletClass class to be registered.
@param urlPattern url pattern to be associated with given class.
@return this | [
"Registers",
"a",
"servlet",
"."
] | train | https://github.com/agapsys/embedded-servlet-container/blob/28314a2600ad8550ed2c901d8e35d86583c26bb0/src/main/java/com/agapsys/jee/ServletContainer.java#L344-L352 |
trellis-ldp-archive/trellis-io-jena | src/main/java/org/trellisldp/io/impl/HtmlSerializer.java | HtmlSerializer.write | public void write(final OutputStream out, final Stream<? extends Triple> triples, final IRI subject) {
final Writer writer = new OutputStreamWriter(out, UTF_8);
try {
template
.execute(writer, new HtmlData(namespaceService, subject, triples.collect(toList()), properties))
.flush();
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
} | java | public void write(final OutputStream out, final Stream<? extends Triple> triples, final IRI subject) {
final Writer writer = new OutputStreamWriter(out, UTF_8);
try {
template
.execute(writer, new HtmlData(namespaceService, subject, triples.collect(toList()), properties))
.flush();
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
} | [
"public",
"void",
"write",
"(",
"final",
"OutputStream",
"out",
",",
"final",
"Stream",
"<",
"?",
"extends",
"Triple",
">",
"triples",
",",
"final",
"IRI",
"subject",
")",
"{",
"final",
"Writer",
"writer",
"=",
"new",
"OutputStreamWriter",
"(",
"out",
",",... | Send the content to an output stream
@param out the output stream
@param triples the triples
@param subject the subject | [
"Send",
"the",
"content",
"to",
"an",
"output",
"stream"
] | train | https://github.com/trellis-ldp-archive/trellis-io-jena/blob/3a06f8f8e7b6fc83fb659cb61217810f813967e8/src/main/java/org/trellisldp/io/impl/HtmlSerializer.java#L80-L89 |
atomix/atomix | cluster/src/main/java/io/atomix/cluster/AtomixClusterBuilder.java | AtomixClusterBuilder.withProperty | public AtomixClusterBuilder withProperty(String key, String value) {
config.getNodeConfig().setProperty(key, value);
return this;
} | java | public AtomixClusterBuilder withProperty(String key, String value) {
config.getNodeConfig().setProperty(key, value);
return this;
} | [
"public",
"AtomixClusterBuilder",
"withProperty",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"config",
".",
"getNodeConfig",
"(",
")",
".",
"setProperty",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Sets a property of the member.
<p>
The properties are arbitrary settings that will be replicated along with this node's member information. Properties
can be used to enable other nodes to determine metadata about this node.
@param key the property key to set
@param value the property value to set
@return the cluster builder
@throws NullPointerException if the property is null | [
"Sets",
"a",
"property",
"of",
"the",
"member",
".",
"<p",
">",
"The",
"properties",
"are",
"arbitrary",
"settings",
"that",
"will",
"be",
"replicated",
"along",
"with",
"this",
"node",
"s",
"member",
"information",
".",
"Properties",
"can",
"be",
"used",
... | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixClusterBuilder.java#L295-L298 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/visualizers/scatterplot/AbstractScatterplotVisualization.java | AbstractScatterplotVisualization.setupCanvas | public static Element setupCanvas(SVGPlot svgp, Projection2D proj, double margin, double width, double height) {
final CanvasSize canvas = proj.estimateViewport();
final double sizex = canvas.getDiffX();
final double sizey = canvas.getDiffY();
String transform = SVGUtil.makeMarginTransform(width, height, sizex, sizey, margin) + " translate(" + SVGUtil.fmt(sizex * .5) + " " + SVGUtil.fmt(sizey * .5) + ")";
final Element layer = SVGUtil.svgElement(svgp.getDocument(), SVGConstants.SVG_G_TAG);
SVGUtil.setAtt(layer, SVGConstants.SVG_TRANSFORM_ATTRIBUTE, transform);
return layer;
} | java | public static Element setupCanvas(SVGPlot svgp, Projection2D proj, double margin, double width, double height) {
final CanvasSize canvas = proj.estimateViewport();
final double sizex = canvas.getDiffX();
final double sizey = canvas.getDiffY();
String transform = SVGUtil.makeMarginTransform(width, height, sizex, sizey, margin) + " translate(" + SVGUtil.fmt(sizex * .5) + " " + SVGUtil.fmt(sizey * .5) + ")";
final Element layer = SVGUtil.svgElement(svgp.getDocument(), SVGConstants.SVG_G_TAG);
SVGUtil.setAtt(layer, SVGConstants.SVG_TRANSFORM_ATTRIBUTE, transform);
return layer;
} | [
"public",
"static",
"Element",
"setupCanvas",
"(",
"SVGPlot",
"svgp",
",",
"Projection2D",
"proj",
",",
"double",
"margin",
",",
"double",
"width",
",",
"double",
"height",
")",
"{",
"final",
"CanvasSize",
"canvas",
"=",
"proj",
".",
"estimateViewport",
"(",
... | Utility function to setup a canvas element for the visualization.
@param svgp Plot element
@param proj Projection to use
@param margin Margin to use
@param width Width
@param height Height
@return wrapper element with appropriate view box. | [
"Utility",
"function",
"to",
"setup",
"a",
"canvas",
"element",
"for",
"the",
"visualization",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/visualizers/scatterplot/AbstractScatterplotVisualization.java#L105-L114 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.getRunnersWithPagination | public List<GitlabRunner> getRunnersWithPagination(GitlabRunner.RunnerScope scope, int page, int perPage) throws IOException {
Pagination pagination = new Pagination()
.withPage(page)
.withPerPage(perPage);
return getRunnersWithPagination(scope, pagination);
} | java | public List<GitlabRunner> getRunnersWithPagination(GitlabRunner.RunnerScope scope, int page, int perPage) throws IOException {
Pagination pagination = new Pagination()
.withPage(page)
.withPerPage(perPage);
return getRunnersWithPagination(scope, pagination);
} | [
"public",
"List",
"<",
"GitlabRunner",
">",
"getRunnersWithPagination",
"(",
"GitlabRunner",
".",
"RunnerScope",
"scope",
",",
"int",
"page",
",",
"int",
"perPage",
")",
"throws",
"IOException",
"{",
"Pagination",
"pagination",
"=",
"new",
"Pagination",
"(",
")"... | Returns a list of runners with perPage elements on the page number specified.
@param scope Can be null. Defines type of Runner to retrieve.
@param page Page to get perPage number of Runners from.
@param perPage Number of elements to get per page.
@return List of GitlabRunners
@throws IOException on Gitlab API call error | [
"Returns",
"a",
"list",
"of",
"runners",
"with",
"perPage",
"elements",
"on",
"the",
"page",
"number",
"specified",
"."
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3967-L3972 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/spi/OverviewDocumentExtension.java | OverviewDocumentExtension.levelOffset | protected int levelOffset(Context context) {
//TODO: Unused method, make sure this is never used and then remove it.
int levelOffset;
switch (context.position) {
case DOCUMENT_BEFORE:
case DOCUMENT_AFTER:
levelOffset = 0;
break;
case DOCUMENT_BEGIN:
case DOCUMENT_END:
levelOffset = 1;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
return levelOffset;
} | java | protected int levelOffset(Context context) {
//TODO: Unused method, make sure this is never used and then remove it.
int levelOffset;
switch (context.position) {
case DOCUMENT_BEFORE:
case DOCUMENT_AFTER:
levelOffset = 0;
break;
case DOCUMENT_BEGIN:
case DOCUMENT_END:
levelOffset = 1;
break;
default:
throw new RuntimeException(String.format("Unknown position '%s'", context.position));
}
return levelOffset;
} | [
"protected",
"int",
"levelOffset",
"(",
"Context",
"context",
")",
"{",
"//TODO: Unused method, make sure this is never used and then remove it.",
"int",
"levelOffset",
";",
"switch",
"(",
"context",
".",
"position",
")",
"{",
"case",
"DOCUMENT_BEFORE",
":",
"case",
"DO... | Returns title level offset from 1 to apply to content
@param context context
@return title level offset | [
"Returns",
"title",
"level",
"offset",
"from",
"1",
"to",
"apply",
"to",
"content"
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/spi/OverviewDocumentExtension.java#L35-L52 |
alkacon/opencms-core | src/org/opencms/search/documents/A_CmsVfsDocument.java | A_CmsVfsDocument.readFile | protected CmsFile readFile(CmsObject cms, CmsResource resource) throws CmsException, CmsIndexNoContentException {
CmsFile file = cms.readFile(resource);
if (file.getLength() <= 0) {
throw new CmsIndexNoContentException(
Messages.get().container(Messages.ERR_NO_CONTENT_1, resource.getRootPath()));
}
return file;
} | java | protected CmsFile readFile(CmsObject cms, CmsResource resource) throws CmsException, CmsIndexNoContentException {
CmsFile file = cms.readFile(resource);
if (file.getLength() <= 0) {
throw new CmsIndexNoContentException(
Messages.get().container(Messages.ERR_NO_CONTENT_1, resource.getRootPath()));
}
return file;
} | [
"protected",
"CmsFile",
"readFile",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
",",
"CmsIndexNoContentException",
"{",
"CmsFile",
"file",
"=",
"cms",
".",
"readFile",
"(",
"resource",
")",
";",
"if",
"(",
"file",
".... | Upgrades the given resource to a {@link CmsFile} with content.<p>
@param cms the current users OpenCms context
@param resource the resource to upgrade
@return the given resource upgraded to a {@link CmsFile} with content
@throws CmsException if the resource could not be read
@throws CmsIndexNoContentException if the resource has no content | [
"Upgrades",
"the",
"given",
"resource",
"to",
"a",
"{",
"@link",
"CmsFile",
"}",
"with",
"content",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/documents/A_CmsVfsDocument.java#L250-L258 |
SimiaCryptus/utilities | java-util/src/main/java/com/simiacryptus/util/io/JsonUtil.java | JsonUtil.writeJson | public static void writeJson(@javax.annotation.Nonnull final OutputStream out, final Object obj) throws IOException {
final ObjectMapper mapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL)
.enable(SerializationFeature.INDENT_OUTPUT);
@javax.annotation.Nonnull final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
mapper.writeValue(buffer, obj);
out.write(buffer.toByteArray());
} | java | public static void writeJson(@javax.annotation.Nonnull final OutputStream out, final Object obj) throws IOException {
final ObjectMapper mapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL)
.enable(SerializationFeature.INDENT_OUTPUT);
@javax.annotation.Nonnull final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
mapper.writeValue(buffer, obj);
out.write(buffer.toByteArray());
} | [
"public",
"static",
"void",
"writeJson",
"(",
"@",
"javax",
".",
"annotation",
".",
"Nonnull",
"final",
"OutputStream",
"out",
",",
"final",
"Object",
"obj",
")",
"throws",
"IOException",
"{",
"final",
"ObjectMapper",
"mapper",
"=",
"new",
"ObjectMapper",
"(",... | Write json.
@param out the out
@param obj the obj
@throws IOException the io exception | [
"Write",
"json",
"."
] | train | https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/io/JsonUtil.java#L99-L105 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/time/JMTimeUtil.java | JMTimeUtil.changeIsoTimestampToLong | public static long changeIsoTimestampToLong(String isoTimestamp) {
try {
return ZonedDateTime.parse(isoTimestamp).toInstant().toEpochMilli();
} catch (Exception e) {
return changeIsoTimestampToLong(isoTimestamp, DEFAULT_ZONE_ID);
}
} | java | public static long changeIsoTimestampToLong(String isoTimestamp) {
try {
return ZonedDateTime.parse(isoTimestamp).toInstant().toEpochMilli();
} catch (Exception e) {
return changeIsoTimestampToLong(isoTimestamp, DEFAULT_ZONE_ID);
}
} | [
"public",
"static",
"long",
"changeIsoTimestampToLong",
"(",
"String",
"isoTimestamp",
")",
"{",
"try",
"{",
"return",
"ZonedDateTime",
".",
"parse",
"(",
"isoTimestamp",
")",
".",
"toInstant",
"(",
")",
".",
"toEpochMilli",
"(",
")",
";",
"}",
"catch",
"(",... | Change iso timestamp to long long.
@param isoTimestamp the iso timestamp
@return the long | [
"Change",
"iso",
"timestamp",
"to",
"long",
"long",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/time/JMTimeUtil.java#L459-L465 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/RunnersApi.java | RunnersApi.getRunners | public List<Runner> getRunners(int page, int perPage) throws GitLabApiException {
return getRunners(null, page, perPage);
} | java | public List<Runner> getRunners(int page, int perPage) throws GitLabApiException {
return getRunners(null, page, perPage);
} | [
"public",
"List",
"<",
"Runner",
">",
"getRunners",
"(",
"int",
"page",
",",
"int",
"perPage",
")",
"throws",
"GitLabApiException",
"{",
"return",
"getRunners",
"(",
"null",
",",
"page",
",",
"perPage",
")",
";",
"}"
] | Get a list of all available runners available to the user with pagination support.
<pre><code>GitLab Endpoint: GET /runners</code></pre>
@param page The page offset of runners
@param perPage The number of runners to get after the page offset
@return List of Runners
@throws GitLabApiException if any exception occurs | [
"Get",
"a",
"list",
"of",
"all",
"available",
"runners",
"available",
"to",
"the",
"user",
"with",
"pagination",
"support",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RunnersApi.java#L82-L84 |
OpenBEL/openbel-framework | org.openbel.framework.core/src/main/java/org/openbel/framework/core/SimpleApplication.java | SimpleApplication.printHelp | private void printHelp(Options o, boolean exit, OutputStream os) {
final PrintWriter pw = new PrintWriter(os);
final String syntax = getUsage();
String header = getApplicationName();
header = header.concat("\nOptions:");
HelpFormatter hf = new HelpFormatter();
hf.printHelp(pw, 80, syntax, header, o, 2, 2, null, false);
pw.flush();
if (exit) {
bail(SUCCESS);
}
} | java | private void printHelp(Options o, boolean exit, OutputStream os) {
final PrintWriter pw = new PrintWriter(os);
final String syntax = getUsage();
String header = getApplicationName();
header = header.concat("\nOptions:");
HelpFormatter hf = new HelpFormatter();
hf.printHelp(pw, 80, syntax, header, o, 2, 2, null, false);
pw.flush();
if (exit) {
bail(SUCCESS);
}
} | [
"private",
"void",
"printHelp",
"(",
"Options",
"o",
",",
"boolean",
"exit",
",",
"OutputStream",
"os",
")",
"{",
"final",
"PrintWriter",
"pw",
"=",
"new",
"PrintWriter",
"(",
"os",
")",
";",
"final",
"String",
"syntax",
"=",
"getUsage",
"(",
")",
";",
... | Write command-line help to the provided stream. If {@code exit} is
{@code true}, exit with status code {@link #EXIT_FAILURE}.
@param o Options
@param exit Exit flag | [
"Write",
"command",
"-",
"line",
"help",
"to",
"the",
"provided",
"stream",
".",
"If",
"{",
"@code",
"exit",
"}",
"is",
"{",
"@code",
"true",
"}",
"exit",
"with",
"status",
"code",
"{",
"@link",
"#EXIT_FAILURE",
"}",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/SimpleApplication.java#L381-L393 |
cesarferreira/AndroidQuickUtils | library/src/main/java/quickutils/core/categories/date.java | date.getDayAsString | public static String getDayAsString(int day, String format) {
SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
return simpleFormat.format(getDayAsDate(day));
} | java | public static String getDayAsString(int day, String format) {
SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
return simpleFormat.format(getDayAsDate(day));
} | [
"public",
"static",
"String",
"getDayAsString",
"(",
"int",
"day",
",",
"String",
"format",
")",
"{",
"SimpleDateFormat",
"simpleFormat",
"=",
"new",
"SimpleDateFormat",
"(",
"format",
")",
";",
"return",
"simpleFormat",
".",
"format",
"(",
"getDayAsDate",
"(",
... | Gets a date with a desired format as a String
@param day Can be: <li>QuickUtils.date.YESTERDAY</li><li>
QuickUtils.date.TODAY</li><li>QuickUtils.date.TOMORROW</li>
@param format desired format (e.g. "yyyy-MM-dd HH:mm:ss")
@return returns a day with the given format | [
"Gets",
"a",
"date",
"with",
"a",
"desired",
"format",
"as",
"a",
"String"
] | train | https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/date.java#L87-L90 |
jpelzer/pelzer-util | src/main/java/com/pelzer/util/PropertyManager.java | PropertyManager.getLocalizedProperty | public synchronized static String getLocalizedProperty(final String namespace, final String key, final String defaultValue) {
if (namespace == null || namespace.equals(""))
return getProperty("", hostname + "." + key, defaultValue);
return getProperty(hostname + "." + namespace, key, defaultValue);
} | java | public synchronized static String getLocalizedProperty(final String namespace, final String key, final String defaultValue) {
if (namespace == null || namespace.equals(""))
return getProperty("", hostname + "." + key, defaultValue);
return getProperty(hostname + "." + namespace, key, defaultValue);
} | [
"public",
"synchronized",
"static",
"String",
"getLocalizedProperty",
"(",
"final",
"String",
"namespace",
",",
"final",
"String",
"key",
",",
"final",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"namespace",
"==",
"null",
"||",
"namespace",
".",
"equals",
... | Allows retrieval of localized properties set up for SPECIFIC hosts. Calling
getLocalizedProperty("foo.bar.BLAH") on the machine 'wintermute' is
equivilant to doing getProperty("WINTERMUTE.foo.bar.BLAH"). Machine names
are always uppercase, and never have sub-domains (ie WINTERMUTE and not
WINTERMUTE.PELZER.COM) | [
"Allows",
"retrieval",
"of",
"localized",
"properties",
"set",
"up",
"for",
"SPECIFIC",
"hosts",
".",
"Calling",
"getLocalizedProperty",
"(",
"foo",
".",
"bar",
".",
"BLAH",
")",
"on",
"the",
"machine",
"wintermute",
"is",
"equivilant",
"to",
"doing",
"getProp... | train | https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/PropertyManager.java#L117-L121 |
tzaeschke/zoodb | src/org/zoodb/internal/util/ReflTools.java | ReflTools.getInt | public static int getInt(Object obj, String fieldName) {
try {
return getField(obj.getClass(), fieldName).getInt(obj);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | java | public static int getInt(Object obj, String fieldName) {
try {
return getField(obj.getClass(), fieldName).getInt(obj);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"int",
"getInt",
"(",
"Object",
"obj",
",",
"String",
"fieldName",
")",
"{",
"try",
"{",
"return",
"getField",
"(",
"obj",
".",
"getClass",
"(",
")",
",",
"fieldName",
")",
".",
"getInt",
"(",
"obj",
")",
";",
"}",
"catch",
"(",
... | Read the value of the field <tt>fieldName</tt> of object <tt>obj</tt>.
@param obj The object
@param fieldName The field name
@return the value of the field. | [
"Read",
"the",
"value",
"of",
"the",
"field",
"<tt",
">",
"fieldName<",
"/",
"tt",
">",
"of",
"object",
"<tt",
">",
"obj<",
"/",
"tt",
">",
"."
] | train | https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/util/ReflTools.java#L137-L145 |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.getRegisteredObject | static Object getRegisteredObject (Connection connection, int objectID) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an object with the objectID.
Object object = objectSpace.idToObject.get(objectID);
if (object != null) return object;
}
}
return null;
} | java | static Object getRegisteredObject (Connection connection, int objectID) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an object with the objectID.
Object object = objectSpace.idToObject.get(objectID);
if (object != null) return object;
}
}
return null;
} | [
"static",
"Object",
"getRegisteredObject",
"(",
"Connection",
"connection",
",",
"int",
"objectID",
")",
"{",
"ObjectSpace",
"[",
"]",
"instances",
"=",
"ObjectSpace",
".",
"instances",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"instances",
"."... | Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs
to. | [
"Returns",
"the",
"first",
"object",
"registered",
"with",
"the",
"specified",
"ID",
"in",
"any",
"of",
"the",
"ObjectSpaces",
"the",
"specified",
"connection",
"belongs",
"to",
"."
] | train | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L651-L665 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.withDataOutputStream | public static <T> T withDataOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataOutputStream") Closure<T> closure) throws IOException {
return IOGroovyMethods.withStream(newDataOutputStream(self), closure);
} | java | public static <T> T withDataOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataOutputStream") Closure<T> closure) throws IOException {
return IOGroovyMethods.withStream(newDataOutputStream(self), closure);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"withDataOutputStream",
"(",
"Path",
"self",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"SimpleType",
".",
"class",
",",
"options",
"=",
"\"java.io.DataOutputStream\"",
")",
"Closure",
"<",
"T",
">",
"closure",
")",... | Create a new DataOutputStream for this file and passes it into the closure.
This method ensures the stream is closed after the closure returns.
@param self a Path
@param closure a closure
@return the value returned by the closure
@throws java.io.IOException if an IOException occurs.
@see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure)
@since 2.3.0 | [
"Create",
"a",
"new",
"DataOutputStream",
"for",
"this",
"file",
"and",
"passes",
"it",
"into",
"the",
"closure",
".",
"This",
"method",
"ensures",
"the",
"stream",
"is",
"closed",
"after",
"the",
"closure",
"returns",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1515-L1517 |
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/PippoSettings.java | PippoSettings.getBoolean | public boolean getBoolean(String name, boolean defaultValue) {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return Boolean.parseBoolean(value.trim());
}
return defaultValue;
} | java | public boolean getBoolean(String name, boolean defaultValue) {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return Boolean.parseBoolean(value.trim());
}
return defaultValue;
} | [
"public",
"boolean",
"getBoolean",
"(",
"String",
"name",
",",
"boolean",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"getString",
"(",
"name",
",",
"null",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isNullOrEmpty",
"(",
"value",
")",
")",
"{",... | Returns the boolean value for the specified name. If the name does not
exist or the value for the name can not be interpreted as a boolean, the
defaultValue is returned.
@param name
@param defaultValue
@return name value or defaultValue | [
"Returns",
"the",
"boolean",
"value",
"for",
"the",
"specified",
"name",
".",
"If",
"the",
"name",
"does",
"not",
"exist",
"or",
"the",
"value",
"for",
"the",
"name",
"can",
"not",
"be",
"interpreted",
"as",
"a",
"boolean",
"the",
"defaultValue",
"is",
"... | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L477-L484 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_acl_POST | public OvhAcl project_serviceName_acl_POST(String serviceName, String accountId, OvhAclTypeEnum type) throws IOException {
String qPath = "/cloud/project/{serviceName}/acl";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "accountId", accountId);
addBody(o, "type", type);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhAcl.class);
} | java | public OvhAcl project_serviceName_acl_POST(String serviceName, String accountId, OvhAclTypeEnum type) throws IOException {
String qPath = "/cloud/project/{serviceName}/acl";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "accountId", accountId);
addBody(o, "type", type);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhAcl.class);
} | [
"public",
"OvhAcl",
"project_serviceName_acl_POST",
"(",
"String",
"serviceName",
",",
"String",
"accountId",
",",
"OvhAclTypeEnum",
"type",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/acl\"",
";",
"StringBuilder",
"sb",
"=... | Create new ACL
REST: POST /cloud/project/{serviceName}/acl
@param type [required] Acl type
@param accountId [required] Deleguates rights to
@param serviceName [required] The project id | [
"Create",
"new",
"ACL"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L363-L371 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/PgCallableStatement.java | PgCallableStatement.checkIndex | private void checkIndex(int parameterIndex, boolean fetchingData) throws SQLException {
if (!isFunction) {
throw new PSQLException(
GT.tr(
"A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."),
PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
}
if (fetchingData) {
if (!returnTypeSet) {
throw new PSQLException(GT.tr("No function outputs were registered."),
PSQLState.OBJECT_NOT_IN_STATE);
}
if (callResult == null) {
throw new PSQLException(
GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."),
PSQLState.NO_DATA);
}
lastIndex = parameterIndex;
}
} | java | private void checkIndex(int parameterIndex, boolean fetchingData) throws SQLException {
if (!isFunction) {
throw new PSQLException(
GT.tr(
"A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."),
PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
}
if (fetchingData) {
if (!returnTypeSet) {
throw new PSQLException(GT.tr("No function outputs were registered."),
PSQLState.OBJECT_NOT_IN_STATE);
}
if (callResult == null) {
throw new PSQLException(
GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."),
PSQLState.NO_DATA);
}
lastIndex = parameterIndex;
}
} | [
"private",
"void",
"checkIndex",
"(",
"int",
"parameterIndex",
",",
"boolean",
"fetchingData",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"!",
"isFunction",
")",
"{",
"throw",
"new",
"PSQLException",
"(",
"GT",
".",
"tr",
"(",
"\"A CallableStatement was decl... | Helper function for the getXXX calls to check isFunction and index == 1.
@param parameterIndex index of getXXX (index) check to make sure is a function and index == 1
@param fetchingData fetching data | [
"Helper",
"function",
"for",
"the",
"getXXX",
"calls",
"to",
"check",
"isFunction",
"and",
"index",
"==",
"1",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/PgCallableStatement.java#L403-L425 |
Impetus/Kundera | src/kundera-redis/src/main/java/com/impetus/client/redis/RedisClient.java | RedisClient.onDelete | private void onDelete(Object entity, Object pKey, Object connection)
{
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
AttributeWrapper wrapper = wrap(entityMetadata, entity);
Set<byte[]> columnNames = wrapper.columns.keySet();
String rowKey = null;
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
{
rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, pKey);
}
else
{
rowKey = PropertyAccessorHelper.getString(entity, (Field) entityMetadata.getIdAttribute().getJavaMember());
}
for (byte[] name : columnNames)
{
if (resource != null && resource.isActive())
{
((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),
PropertyAccessorFactory.STRING.fromBytes(String.class, name));
}
else
{
((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),
PropertyAccessorFactory.STRING.fromBytes(String.class, name));
}
}
// Delete relation values.
deleteRelation(connection, entityMetadata, rowKey);
// Delete inverted indexes.
unIndex(connection, wrapper, rowKey);
if (resource != null && resource.isActive())
{
((Transaction) connection).zrem(
getHashKey(entityMetadata.getTableName(),
((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey);
}
else
{
((Pipeline) connection).zrem(
getHashKey(entityMetadata.getTableName(),
((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey);
}
KunderaCoreUtils.printQuery("Delete data from:" + entityMetadata.getTableName() + "for primary key: " + rowKey,
showQuery);
} | java | private void onDelete(Object entity, Object pKey, Object connection)
{
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
AttributeWrapper wrapper = wrap(entityMetadata, entity);
Set<byte[]> columnNames = wrapper.columns.keySet();
String rowKey = null;
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
{
rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, pKey);
}
else
{
rowKey = PropertyAccessorHelper.getString(entity, (Field) entityMetadata.getIdAttribute().getJavaMember());
}
for (byte[] name : columnNames)
{
if (resource != null && resource.isActive())
{
((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),
PropertyAccessorFactory.STRING.fromBytes(String.class, name));
}
else
{
((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),
PropertyAccessorFactory.STRING.fromBytes(String.class, name));
}
}
// Delete relation values.
deleteRelation(connection, entityMetadata, rowKey);
// Delete inverted indexes.
unIndex(connection, wrapper, rowKey);
if (resource != null && resource.isActive())
{
((Transaction) connection).zrem(
getHashKey(entityMetadata.getTableName(),
((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey);
}
else
{
((Pipeline) connection).zrem(
getHashKey(entityMetadata.getTableName(),
((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey);
}
KunderaCoreUtils.printQuery("Delete data from:" + entityMetadata.getTableName() + "for primary key: " + rowKey,
showQuery);
} | [
"private",
"void",
"onDelete",
"(",
"Object",
"entity",
",",
"Object",
"pKey",
",",
"Object",
"connection",
")",
"{",
"EntityMetadata",
"entityMetadata",
"=",
"KunderaMetadataManager",
".",
"getEntityMetadata",
"(",
"kunderaMetadata",
",",
"entity",
".",
"getClass",... | On delete.
@param entity
the entity
@param pKey
the key
@param connection
the connection | [
"On",
"delete",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-redis/src/main/java/com/impetus/client/redis/RedisClient.java#L2162-L2222 |
Chorus-bdd/Chorus | interpreter/chorus-processes/src/main/java/org/chorusbdd/chorus/processes/manager/ProcessManagerProcess.java | ProcessManagerProcess.writeToStdIn | public void writeToStdIn(String text, boolean newLine) {
if ( outputStream == null) {
outputStream = new BufferedOutputStream(process.getOutputStream());
outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
}
try {
outputWriter.write(text);
if ( newLine ) {
outputWriter.newLine();
}
outputWriter.flush();
outputStream.flush();
} catch (IOException e) {
getLog().debug("Error when writing to process in for " + this, e);
ChorusAssert.fail("IOException when writing line to process");
}
} | java | public void writeToStdIn(String text, boolean newLine) {
if ( outputStream == null) {
outputStream = new BufferedOutputStream(process.getOutputStream());
outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
}
try {
outputWriter.write(text);
if ( newLine ) {
outputWriter.newLine();
}
outputWriter.flush();
outputStream.flush();
} catch (IOException e) {
getLog().debug("Error when writing to process in for " + this, e);
ChorusAssert.fail("IOException when writing line to process");
}
} | [
"public",
"void",
"writeToStdIn",
"(",
"String",
"text",
",",
"boolean",
"newLine",
")",
"{",
"if",
"(",
"outputStream",
"==",
"null",
")",
"{",
"outputStream",
"=",
"new",
"BufferedOutputStream",
"(",
"process",
".",
"getOutputStream",
"(",
")",
")",
";",
... | Write the text to the std in of the process
@param newLine append a new line | [
"Write",
"the",
"text",
"to",
"the",
"std",
"in",
"of",
"the",
"process"
] | train | https://github.com/Chorus-bdd/Chorus/blob/1eea7ca858876bce821bb49b43fd5b6ba1737997/interpreter/chorus-processes/src/main/java/org/chorusbdd/chorus/processes/manager/ProcessManagerProcess.java#L171-L188 |
jparsec/jparsec | jparsec/src/main/java/org/jparsec/internal/util/Checks.java | Checks.checkState | public static void checkState(boolean condition, String message, Object... args)
throws IllegalStateException {
if (!condition) {
throw new IllegalStateException(String.format(message, args));
}
} | java | public static void checkState(boolean condition, String message, Object... args)
throws IllegalStateException {
if (!condition) {
throw new IllegalStateException(String.format(message, args));
}
} | [
"public",
"static",
"void",
"checkState",
"(",
"boolean",
"condition",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"!",
"condition",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"St... | Checks a certain state.
@param condition the condition of the state that has to be true
@param message the error message if {@code condition} is false
@param args the arguments to the error message
@throws IllegalStateException if {@code condition} is false | [
"Checks",
"a",
"certain",
"state",
"."
] | train | https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/internal/util/Checks.java#L90-L95 |
SonarSource/sonarqube | sonar-duplications/src/main/java/org/sonar/duplications/detector/original/BlocksGroup.java | BlocksGroup.subsumedBy | private static boolean subsumedBy(BlocksGroup group1, BlocksGroup group2, int indexCorrection) {
List<Block> list1 = group1.blocks;
List<Block> list2 = group2.blocks;
int i = 0;
int j = 0;
while (i < list1.size() && j < list2.size()) {
Block block1 = list1.get(i);
Block block2 = list2.get(j);
int c = RESOURCE_ID_COMPARATOR.compare(block1.getResourceId(), block2.getResourceId());
if (c != 0) {
j++;
continue;
}
c = block1.getIndexInFile() - indexCorrection - block2.getIndexInFile();
if (c < 0) {
// list1[i] < list2[j]
break;
}
if (c != 0) {
// list1[i] != list2[j]
j++;
}
if (c == 0) {
// list1[i] == list2[j]
i++;
j++;
}
}
return i == list1.size();
} | java | private static boolean subsumedBy(BlocksGroup group1, BlocksGroup group2, int indexCorrection) {
List<Block> list1 = group1.blocks;
List<Block> list2 = group2.blocks;
int i = 0;
int j = 0;
while (i < list1.size() && j < list2.size()) {
Block block1 = list1.get(i);
Block block2 = list2.get(j);
int c = RESOURCE_ID_COMPARATOR.compare(block1.getResourceId(), block2.getResourceId());
if (c != 0) {
j++;
continue;
}
c = block1.getIndexInFile() - indexCorrection - block2.getIndexInFile();
if (c < 0) {
// list1[i] < list2[j]
break;
}
if (c != 0) {
// list1[i] != list2[j]
j++;
}
if (c == 0) {
// list1[i] == list2[j]
i++;
j++;
}
}
return i == list1.size();
} | [
"private",
"static",
"boolean",
"subsumedBy",
"(",
"BlocksGroup",
"group1",
",",
"BlocksGroup",
"group2",
",",
"int",
"indexCorrection",
")",
"{",
"List",
"<",
"Block",
">",
"list1",
"=",
"group1",
".",
"blocks",
";",
"List",
"<",
"Block",
">",
"list2",
"=... | One group is subsumed by another group, when each block from first group has corresponding block from second group
with same resource id and with corrected index. | [
"One",
"group",
"is",
"subsumed",
"by",
"another",
"group",
"when",
"each",
"block",
"from",
"first",
"group",
"has",
"corresponding",
"block",
"from",
"second",
"group",
"with",
"same",
"resource",
"id",
"and",
"with",
"corrected",
"index",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-duplications/src/main/java/org/sonar/duplications/detector/original/BlocksGroup.java#L138-L167 |
EMCECS/nfs-client-java | src/main/java/com/emc/ecs/nfsclient/network/Connection.java | Connection.bindToPrivilegedPort | private Channel bindToPrivilegedPort() throws RpcException {
System.out.println("Attempting to use privileged port.");
for (int port = 1023; port > 0; --port) {
try {
ChannelPipeline pipeline = _clientBootstrap.getPipelineFactory().getPipeline();
Channel channel = _clientBootstrap.getFactory().newChannel(pipeline);
channel.getConfig().setOptions(_clientBootstrap.getOptions());
ChannelFuture bindFuture = channel.bind(new InetSocketAddress(port)).awaitUninterruptibly();
if (bindFuture.isSuccess()) {
System.out.println("Success! Bound to port " + port);
return bindFuture.getChannel();
}
} catch (Exception e) {
String msg = String.format("rpc request bind error for address: %s",
getRemoteAddress());
throw new RpcException(RpcStatus.NETWORK_ERROR, msg, e);
}
}
throw new RpcException(RpcStatus.LOCAL_BINDING_ERROR, String.format("Cannot bind a port < 1024: %s", getRemoteAddress()));
} | java | private Channel bindToPrivilegedPort() throws RpcException {
System.out.println("Attempting to use privileged port.");
for (int port = 1023; port > 0; --port) {
try {
ChannelPipeline pipeline = _clientBootstrap.getPipelineFactory().getPipeline();
Channel channel = _clientBootstrap.getFactory().newChannel(pipeline);
channel.getConfig().setOptions(_clientBootstrap.getOptions());
ChannelFuture bindFuture = channel.bind(new InetSocketAddress(port)).awaitUninterruptibly();
if (bindFuture.isSuccess()) {
System.out.println("Success! Bound to port " + port);
return bindFuture.getChannel();
}
} catch (Exception e) {
String msg = String.format("rpc request bind error for address: %s",
getRemoteAddress());
throw new RpcException(RpcStatus.NETWORK_ERROR, msg, e);
}
}
throw new RpcException(RpcStatus.LOCAL_BINDING_ERROR, String.format("Cannot bind a port < 1024: %s", getRemoteAddress()));
} | [
"private",
"Channel",
"bindToPrivilegedPort",
"(",
")",
"throws",
"RpcException",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Attempting to use privileged port.\"",
")",
";",
"for",
"(",
"int",
"port",
"=",
"1023",
";",
"port",
">",
"0",
";",
"--",
"p... | This attempts to bind to privileged ports, starting with 1023 and working downwards, and returns when the first binding succeeds.
<p>
Some NFS servers apparently may require that some requests originate on
an Internet port below IPPORT_RESERVED (1024). This is generally not
used, though, as the client then has to run as a user authorized for
privileged, which is dangerous. It is also not generally needed.
</p>
@return
<ul>
<li><code>true</code> if the binding succeeds,</li>
<li><code>false</code> otherwise.</li>
</ul>
@throws RpcException If an exception occurs, or if no binding succeeds. | [
"This",
"attempts",
"to",
"bind",
"to",
"privileged",
"ports",
"starting",
"with",
"1023",
"and",
"working",
"downwards",
"and",
"returns",
"when",
"the",
"first",
"binding",
"succeeds",
"."
] | train | https://github.com/EMCECS/nfs-client-java/blob/7ba25bad5052b95cd286052745327729288b2843/src/main/java/com/emc/ecs/nfsclient/network/Connection.java#L399-L419 |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/AccountManager.java | AccountManager.decodeFavoritesUrls | public void decodeFavoritesUrls(String encodedUrlList, boolean clearFirst) {
int start = 0;
int end = encodedUrlList.length();
if ( encodedUrlList.startsWith("<") ) start++;
if ( encodedUrlList.endsWith(">") ) end--;
encodedUrlList = encodedUrlList.substring(start, end);
if ( clearFirst ) favoriteUrls.clear();
for (String url : Splitter.on(">,<").omitEmptyStrings().split(encodedUrlList) ) {
favoriteUrls.add(url);
}
} | java | public void decodeFavoritesUrls(String encodedUrlList, boolean clearFirst) {
int start = 0;
int end = encodedUrlList.length();
if ( encodedUrlList.startsWith("<") ) start++;
if ( encodedUrlList.endsWith(">") ) end--;
encodedUrlList = encodedUrlList.substring(start, end);
if ( clearFirst ) favoriteUrls.clear();
for (String url : Splitter.on(">,<").omitEmptyStrings().split(encodedUrlList) ) {
favoriteUrls.add(url);
}
} | [
"public",
"void",
"decodeFavoritesUrls",
"(",
"String",
"encodedUrlList",
",",
"boolean",
"clearFirst",
")",
"{",
"int",
"start",
"=",
"0",
";",
"int",
"end",
"=",
"encodedUrlList",
".",
"length",
"(",
")",
";",
"if",
"(",
"encodedUrlList",
".",
"startsWith"... | Decodes a list of favorites urls from a series of <url1>,<url2>...
Will then put them into the list of favorites, optionally clearing first
@param encodedUrlList - String encoded version of the list
@param clearFirst - clear the list of favorites first | [
"Decodes",
"a",
"list",
"of",
"favorites",
"urls",
"from",
"a",
"series",
"of",
"<",
";",
"url1>",
";",
"<",
";",
"url2>",
";",
"..."
] | train | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/AccountManager.java#L232-L242 |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java | ResourceUtils.getResourceAsReader | public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(loader, resource));
} | java | public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(loader, resource));
} | [
"public",
"static",
"Reader",
"getResourceAsReader",
"(",
"ClassLoader",
"loader",
",",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"return",
"new",
"InputStreamReader",
"(",
"getResourceAsStream",
"(",
"loader",
",",
"resource",
")",
")",
";",
"}"
] | Returns a resource on the classpath as a Reader object
@param loader
The classloader used to load the resource
@param resource
The resource to find
@throws IOException
If the resource cannot be found or read
@return The resource | [
"Returns",
"a",
"resource",
"on",
"the",
"classpath",
"as",
"a",
"Reader",
"object"
] | train | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java#L213-L215 |
google/error-prone | check_api/src/main/java/com/google/errorprone/matchers/Matchers.java | Matchers.assertionWithCondition | public static Matcher<AssertTree> assertionWithCondition(
final Matcher<ExpressionTree> conditionMatcher) {
return new Matcher<AssertTree>() {
@Override
public boolean matches(AssertTree tree, VisitorState state) {
return conditionMatcher.matches(tree.getCondition(), state);
}
};
} | java | public static Matcher<AssertTree> assertionWithCondition(
final Matcher<ExpressionTree> conditionMatcher) {
return new Matcher<AssertTree>() {
@Override
public boolean matches(AssertTree tree, VisitorState state) {
return conditionMatcher.matches(tree.getCondition(), state);
}
};
} | [
"public",
"static",
"Matcher",
"<",
"AssertTree",
">",
"assertionWithCondition",
"(",
"final",
"Matcher",
"<",
"ExpressionTree",
">",
"conditionMatcher",
")",
"{",
"return",
"new",
"Matcher",
"<",
"AssertTree",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"b... | Matches an assertion AST node if the given matcher matches its condition.
@param conditionMatcher The matcher to apply to the condition in the assertion, e.g. in "assert
false", the "false" part of the statement | [
"Matches",
"an",
"assertion",
"AST",
"node",
"if",
"the",
"given",
"matcher",
"matches",
"its",
"condition",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L1384-L1392 |
apache/incubator-gobblin | gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/ConfigStoreUtils.java | ConfigStoreUtils.getConfig | public static Config getConfig(ConfigClient client, URI u, Optional<Config> runtimeConfig) {
try {
return client.getConfig(u, runtimeConfig);
} catch (ConfigStoreFactoryDoesNotExistsException | ConfigStoreCreationException e) {
throw new Error(e);
}
} | java | public static Config getConfig(ConfigClient client, URI u, Optional<Config> runtimeConfig) {
try {
return client.getConfig(u, runtimeConfig);
} catch (ConfigStoreFactoryDoesNotExistsException | ConfigStoreCreationException e) {
throw new Error(e);
}
} | [
"public",
"static",
"Config",
"getConfig",
"(",
"ConfigClient",
"client",
",",
"URI",
"u",
",",
"Optional",
"<",
"Config",
">",
"runtimeConfig",
")",
"{",
"try",
"{",
"return",
"client",
".",
"getConfig",
"(",
"u",
",",
"runtimeConfig",
")",
";",
"}",
"c... | Wrapper to convert Checked Exception to Unchecked Exception
Easy to use in lambda expressions | [
"Wrapper",
"to",
"convert",
"Checked",
"Exception",
"to",
"Unchecked",
"Exception",
"Easy",
"to",
"use",
"in",
"lambda",
"expressions"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/ConfigStoreUtils.java#L116-L122 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata/model/curves/ForwardCurveInterpolation.java | ForwardCurveInterpolation.createForwardCurveFromForwards | public static ForwardCurveInterpolation createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, String interpolationEntityForward, String discountCurveName, AnalyticModel model, double[] times, double[] givenForwards) {
return createForwardCurveFromForwards(name, referenceDate, paymentOffsetCode, InterpolationEntityForward.valueOf(interpolationEntityForward), discountCurveName, model, times, givenForwards);
} | java | public static ForwardCurveInterpolation createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, String interpolationEntityForward, String discountCurveName, AnalyticModel model, double[] times, double[] givenForwards) {
return createForwardCurveFromForwards(name, referenceDate, paymentOffsetCode, InterpolationEntityForward.valueOf(interpolationEntityForward), discountCurveName, model, times, givenForwards);
} | [
"public",
"static",
"ForwardCurveInterpolation",
"createForwardCurveFromForwards",
"(",
"String",
"name",
",",
"LocalDate",
"referenceDate",
",",
"String",
"paymentOffsetCode",
",",
"String",
"interpolationEntityForward",
",",
"String",
"discountCurveName",
",",
"AnalyticMode... | Create a forward curve from given times and given forwards.
@param name The name of this curve.
@param referenceDate The reference date for this code, i.e., the date which defines t=0.
@param paymentOffsetCode The maturity of the index modeled by this curve.
@param interpolationEntityForward Interpolation entity used for forward rate interpolation.
@param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any.
@param model The model to be used to fetch the discount curve, if needed.
@param times A vector of given time points.
@param givenForwards A vector of given forwards (corresponding to the given time points).
@return A new ForwardCurve object. | [
"Create",
"a",
"forward",
"curve",
"from",
"given",
"times",
"and",
"given",
"forwards",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/curves/ForwardCurveInterpolation.java#L188-L190 |
pf4j/pf4j-update | src/main/java/org/pf4j/update/UpdateManager.java | UpdateManager.downloadPlugin | protected Path downloadPlugin(String id, String version) throws PluginException {
try {
PluginRelease release = findReleaseForPlugin(id, version);
Path downloaded = getFileDownloader(id).downloadFile(new URL(release.url));
getFileVerifier(id).verify(new FileVerifier.Context(id, release), downloaded);
return downloaded;
} catch (IOException e) {
throw new PluginException(e, "Error during download of plugin {}", id);
}
} | java | protected Path downloadPlugin(String id, String version) throws PluginException {
try {
PluginRelease release = findReleaseForPlugin(id, version);
Path downloaded = getFileDownloader(id).downloadFile(new URL(release.url));
getFileVerifier(id).verify(new FileVerifier.Context(id, release), downloaded);
return downloaded;
} catch (IOException e) {
throw new PluginException(e, "Error during download of plugin {}", id);
}
} | [
"protected",
"Path",
"downloadPlugin",
"(",
"String",
"id",
",",
"String",
"version",
")",
"throws",
"PluginException",
"{",
"try",
"{",
"PluginRelease",
"release",
"=",
"findReleaseForPlugin",
"(",
"id",
",",
"version",
")",
";",
"Path",
"downloaded",
"=",
"g... | Downloads a plugin with given coordinates, runs all {@link FileVerifier}s
and returns a path to the downloaded file.
@param id of plugin
@param version of plugin or null to download latest
@return Path to file which will reside in a temporary folder in the system default temp area
@throws PluginException if download failed | [
"Downloads",
"a",
"plugin",
"with",
"given",
"coordinates",
"runs",
"all",
"{",
"@link",
"FileVerifier",
"}",
"s",
"and",
"returns",
"a",
"path",
"to",
"the",
"downloaded",
"file",
"."
] | train | https://github.com/pf4j/pf4j-update/blob/80cf04b8f2790808d0cf9dff3602dc5d730ac979/src/main/java/org/pf4j/update/UpdateManager.java#L259-L268 |
JakeWharton/butterknife | butterknife-runtime/src/main/java/butterknife/ViewCollections.java | ViewCollections.set | @UiThread
public static <T extends View, V> void set(@NonNull List<T> list,
@NonNull Property<? super T, V> setter, @Nullable V value) {
//noinspection ForLoopReplaceableByForEach
for (int i = 0, count = list.size(); i < count; i++) {
setter.set(list.get(i), value);
}
} | java | @UiThread
public static <T extends View, V> void set(@NonNull List<T> list,
@NonNull Property<? super T, V> setter, @Nullable V value) {
//noinspection ForLoopReplaceableByForEach
for (int i = 0, count = list.size(); i < count; i++) {
setter.set(list.get(i), value);
}
} | [
"@",
"UiThread",
"public",
"static",
"<",
"T",
"extends",
"View",
",",
"V",
">",
"void",
"set",
"(",
"@",
"NonNull",
"List",
"<",
"T",
">",
"list",
",",
"@",
"NonNull",
"Property",
"<",
"?",
"super",
"T",
",",
"V",
">",
"setter",
",",
"@",
"Nulla... | Apply the specified {@code value} across the {@code list} of views using the {@code property}. | [
"Apply",
"the",
"specified",
"{"
] | train | https://github.com/JakeWharton/butterknife/blob/0ead8a7b21620effcf78c728089fc16ae9d664c0/butterknife-runtime/src/main/java/butterknife/ViewCollections.java#L94-L101 |
vvakame/JsonPullParser | jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java | JsonUtil.put | public static void put(Writer writer, char value) throws IOException {
writer.write("\"");
writer.write(sanitize(value));
writer.write("\"");
} | java | public static void put(Writer writer, char value) throws IOException {
writer.write("\"");
writer.write(sanitize(value));
writer.write("\"");
} | [
"public",
"static",
"void",
"put",
"(",
"Writer",
"writer",
",",
"char",
"value",
")",
"throws",
"IOException",
"{",
"writer",
".",
"write",
"(",
"\"\\\"\"",
")",
";",
"writer",
".",
"write",
"(",
"sanitize",
"(",
"value",
")",
")",
";",
"writer",
".",... | Writes the given value with the given writer, sanitizing with {@link #sanitize(String)} as a valid JSON-formatted data.
@param writer
@param value
@throws IOException
@author vvakame | [
"Writes",
"the",
"given",
"value",
"with",
"the",
"given",
"writer",
"sanitizing",
"with",
"{"
] | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L182-L186 |
facebook/fresco | drawee/src/main/java/com/facebook/drawee/view/SimpleDraweeView.java | SimpleDraweeView.setImageURI | public void setImageURI(Uri uri, @Nullable Object callerContext) {
DraweeController controller =
mControllerBuilder
.setCallerContext(callerContext)
.setUri(uri)
.setOldController(getController())
.build();
setController(controller);
} | java | public void setImageURI(Uri uri, @Nullable Object callerContext) {
DraweeController controller =
mControllerBuilder
.setCallerContext(callerContext)
.setUri(uri)
.setOldController(getController())
.build();
setController(controller);
} | [
"public",
"void",
"setImageURI",
"(",
"Uri",
"uri",
",",
"@",
"Nullable",
"Object",
"callerContext",
")",
"{",
"DraweeController",
"controller",
"=",
"mControllerBuilder",
".",
"setCallerContext",
"(",
"callerContext",
")",
".",
"setUri",
"(",
"uri",
")",
".",
... | Displays an image given by the uri.
@param uri uri of the image
@param callerContext caller context | [
"Displays",
"an",
"image",
"given",
"by",
"the",
"uri",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/view/SimpleDraweeView.java#L162-L170 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.removeFailure | @Override
public void removeFailure(K key, StoreAccessException e) {
try {
loaderWriter.delete(key);
} catch(Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(key, e);
}
} | java | @Override
public void removeFailure(K key, StoreAccessException e) {
try {
loaderWriter.delete(key);
} catch(Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
} finally {
cleanup(key, e);
}
} | [
"@",
"Override",
"public",
"void",
"removeFailure",
"(",
"K",
"key",
",",
"StoreAccessException",
"e",
")",
"{",
"try",
"{",
"loaderWriter",
".",
"delete",
"(",
"key",
")",
";",
"}",
"catch",
"(",
"Exception",
"e1",
")",
"{",
"throw",
"ExceptionFactory",
... | Delete the key from the loader-writer.
@param key the key being removed
@param e the triggered failure | [
"Delete",
"the",
"key",
"from",
"the",
"loader",
"-",
"writer",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L103-L112 |
micronaut-projects/micronaut-core | http-server-netty/src/main/java/io/micronaut/http/server/netty/jackson/JsonViewMediaTypeCodecFactory.java | JsonViewMediaTypeCodecFactory.resolveJsonViewCodec | @Override
public @Nonnull JsonMediaTypeCodec resolveJsonViewCodec(@Nonnull Class<?> viewClass) {
ArgumentUtils.requireNonNull("viewClass", viewClass);
JsonMediaTypeCodec codec = jsonViewCodecs.get(viewClass);
if (codec == null) {
ObjectMapper viewMapper = objectMapper.copy();
viewMapper.setConfig(viewMapper.getSerializationConfig().withView(viewClass));
codec = new JsonMediaTypeCodec(viewMapper, applicationConfiguration, codecConfiguration);
jsonViewCodecs.put(viewClass, codec);
}
return codec;
} | java | @Override
public @Nonnull JsonMediaTypeCodec resolveJsonViewCodec(@Nonnull Class<?> viewClass) {
ArgumentUtils.requireNonNull("viewClass", viewClass);
JsonMediaTypeCodec codec = jsonViewCodecs.get(viewClass);
if (codec == null) {
ObjectMapper viewMapper = objectMapper.copy();
viewMapper.setConfig(viewMapper.getSerializationConfig().withView(viewClass));
codec = new JsonMediaTypeCodec(viewMapper, applicationConfiguration, codecConfiguration);
jsonViewCodecs.put(viewClass, codec);
}
return codec;
} | [
"@",
"Override",
"public",
"@",
"Nonnull",
"JsonMediaTypeCodec",
"resolveJsonViewCodec",
"(",
"@",
"Nonnull",
"Class",
"<",
"?",
">",
"viewClass",
")",
"{",
"ArgumentUtils",
".",
"requireNonNull",
"(",
"\"viewClass\"",
",",
"viewClass",
")",
";",
"JsonMediaTypeCod... | Creates a {@link JsonMediaTypeCodec} for the view class (specified as the JsonView annotation value).
@param viewClass The view class
@return The codec | [
"Creates",
"a",
"{"
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http-server-netty/src/main/java/io/micronaut/http/server/netty/jackson/JsonViewMediaTypeCodecFactory.java#L76-L88 |
vRallev/ECC-25519 | ECC-25519-Java/src/main/java/djb/Curve25519.java | Curve25519.keygen | public static final void keygen(byte[] P, byte[] s, byte[] k) {
clamp(k);
core(P, s, k, null);
} | java | public static final void keygen(byte[] P, byte[] s, byte[] k) {
clamp(k);
core(P, s, k, null);
} | [
"public",
"static",
"final",
"void",
"keygen",
"(",
"byte",
"[",
"]",
"P",
",",
"byte",
"[",
"]",
"s",
",",
"byte",
"[",
"]",
"k",
")",
"{",
"clamp",
"(",
"k",
")",
";",
"core",
"(",
"P",
",",
"s",
",",
"k",
",",
"null",
")",
";",
"}"
] | /* Key-pair generation
P [out] your public key
s [out] your private key for signing
k [out] your private key for key agreement
k [in] 32 random bytes
s may be NULL if you don't care
WARNING: if s is not NULL, this function has data-dependent timing | [
"/",
"*",
"Key",
"-",
"pair",
"generation",
"P",
"[",
"out",
"]",
"your",
"public",
"key",
"s",
"[",
"out",
"]",
"your",
"private",
"key",
"for",
"signing",
"k",
"[",
"out",
"]",
"your",
"private",
"key",
"for",
"key",
"agreement",
"k",
"[",
"in",
... | train | https://github.com/vRallev/ECC-25519/blob/5c4297933aabfa4fbe7675e36d6d923ffd22e2cb/ECC-25519-Java/src/main/java/djb/Curve25519.java#L67-L70 |
samskivert/samskivert | src/main/java/com/samskivert/servlet/user/UserRepository.java | UserRepository.refreshSession | public boolean refreshSession (String sessionKey, int expireDays)
throws PersistenceException
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date expires = new Date(cal.getTime().getTime());
// attempt to update an existing session row, returning true if we found and updated it
return (update("update sessions set expires = '" + expires + "' " +
"where authcode = " + JDBCUtil.escape(sessionKey)) == 1);
} | java | public boolean refreshSession (String sessionKey, int expireDays)
throws PersistenceException
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date expires = new Date(cal.getTime().getTime());
// attempt to update an existing session row, returning true if we found and updated it
return (update("update sessions set expires = '" + expires + "' " +
"where authcode = " + JDBCUtil.escape(sessionKey)) == 1);
} | [
"public",
"boolean",
"refreshSession",
"(",
"String",
"sessionKey",
",",
"int",
"expireDays",
")",
"throws",
"PersistenceException",
"{",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"add",
"(",
"Calendar",
".",
"DATE",
... | Validates that the supplied session key is still valid and if so, refreshes it for the
specified number of days.
@return true if the session was located and refreshed, false if it no longer exists. | [
"Validates",
"that",
"the",
"supplied",
"session",
"key",
"is",
"still",
"valid",
"and",
"if",
"so",
"refreshes",
"it",
"for",
"the",
"specified",
"number",
"of",
"days",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/user/UserRepository.java#L297-L307 |
undertow-io/undertow | core/src/main/java/io/undertow/Handlers.java | Handlers.jvmRoute | public static JvmRouteHandler jvmRoute(final String sessionCookieName, final String jvmRoute, HttpHandler next) {
return new JvmRouteHandler(next, sessionCookieName, jvmRoute);
} | java | public static JvmRouteHandler jvmRoute(final String sessionCookieName, final String jvmRoute, HttpHandler next) {
return new JvmRouteHandler(next, sessionCookieName, jvmRoute);
} | [
"public",
"static",
"JvmRouteHandler",
"jvmRoute",
"(",
"final",
"String",
"sessionCookieName",
",",
"final",
"String",
"jvmRoute",
",",
"HttpHandler",
"next",
")",
"{",
"return",
"new",
"JvmRouteHandler",
"(",
"next",
",",
"sessionCookieName",
",",
"jvmRoute",
")... | Handler that appends the JVM route to the session cookie
@param sessionCookieName The session cookie name
@param jvmRoute The JVM route to append
@param next The next handler
@return The handler | [
"Handler",
"that",
"appends",
"the",
"JVM",
"route",
"to",
"the",
"session",
"cookie"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L453-L455 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceService.java | BaseTraceService.captureSystemStreams | protected void captureSystemStreams() {
teeOut = new TeePrintStream(new TrOutputStream(systemOut, this), true);
System.setOut(teeOut);
teeErr = new TeePrintStream(new TrOutputStream(systemErr, this), true);
System.setErr(teeErr);
} | java | protected void captureSystemStreams() {
teeOut = new TeePrintStream(new TrOutputStream(systemOut, this), true);
System.setOut(teeOut);
teeErr = new TeePrintStream(new TrOutputStream(systemErr, this), true);
System.setErr(teeErr);
} | [
"protected",
"void",
"captureSystemStreams",
"(",
")",
"{",
"teeOut",
"=",
"new",
"TeePrintStream",
"(",
"new",
"TrOutputStream",
"(",
"systemOut",
",",
"this",
")",
",",
"true",
")",
";",
"System",
".",
"setOut",
"(",
"teeOut",
")",
";",
"teeErr",
"=",
... | Capture the system stream. The original streams are cached/remembered
when the special trace components are created. | [
"Capture",
"the",
"system",
"stream",
".",
"The",
"original",
"streams",
"are",
"cached",
"/",
"remembered",
"when",
"the",
"special",
"trace",
"components",
"are",
"created",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceService.java#L1256-L1262 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/DoubleStream.java | DoubleStream.mapToInt | @NotNull
public IntStream mapToInt(@NotNull final DoubleToIntFunction mapper) {
return new IntStream(params, new DoubleMapToInt(iterator, mapper));
} | java | @NotNull
public IntStream mapToInt(@NotNull final DoubleToIntFunction mapper) {
return new IntStream(params, new DoubleMapToInt(iterator, mapper));
} | [
"@",
"NotNull",
"public",
"IntStream",
"mapToInt",
"(",
"@",
"NotNull",
"final",
"DoubleToIntFunction",
"mapper",
")",
"{",
"return",
"new",
"IntStream",
"(",
"params",
",",
"new",
"DoubleMapToInt",
"(",
"iterator",
",",
"mapper",
")",
")",
";",
"}"
] | Returns an {@code IntStream} consisting of the results of applying the given
function to the elements of this stream.
<p> This is an intermediate operation.
@param mapper the mapper function used to apply to each element
@return the new {@code IntStream} | [
"Returns",
"an",
"{",
"@code",
"IntStream",
"}",
"consisting",
"of",
"the",
"results",
"of",
"applying",
"the",
"given",
"function",
"to",
"the",
"elements",
"of",
"this",
"stream",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/DoubleStream.java#L490-L493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.