repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
paymill/paymill-java | src/main/java/com/paymill/services/TransactionService.java | TransactionService.createWithPayment | public Transaction createWithPayment( Payment payment, Integer amount, String currency ) {
"""
Executes a {@link Transaction} with {@link Payment} for the given amount in the given currency.
@param payment
A PAYMILL {@link Payment} representing credit card or direct debit.
@param amount
Amount (in cents) which will be charged.
@param currency
ISO 4217 formatted currency code.
@return {@link Transaction} object indicating whether a the call was successful or not.
"""
return this.createWithPayment( payment, amount, currency, null );
} | java | public Transaction createWithPayment( Payment payment, Integer amount, String currency ) {
return this.createWithPayment( payment, amount, currency, null );
} | [
"public",
"Transaction",
"createWithPayment",
"(",
"Payment",
"payment",
",",
"Integer",
"amount",
",",
"String",
"currency",
")",
"{",
"return",
"this",
".",
"createWithPayment",
"(",
"payment",
",",
"amount",
",",
"currency",
",",
"null",
")",
";",
"}"
] | Executes a {@link Transaction} with {@link Payment} for the given amount in the given currency.
@param payment
A PAYMILL {@link Payment} representing credit card or direct debit.
@param amount
Amount (in cents) which will be charged.
@param currency
ISO 4217 formatted currency code.
@return {@link Transaction} object indicating whether a the call was successful or not. | [
"Executes",
"a",
"{"
] | train | https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/TransactionService.java#L193-L195 |
apache/flink | flink-core/src/main/java/org/apache/flink/api/java/tuple/Tuple3.java | Tuple3.setFields | public void setFields(T0 value0, T1 value1, T2 value2) {
"""
Sets new values to all fields of the tuple.
@param value0 The value for field 0
@param value1 The value for field 1
@param value2 The value for field 2
"""
this.f0 = value0;
this.f1 = value1;
this.f2 = value2;
} | java | public void setFields(T0 value0, T1 value1, T2 value2) {
this.f0 = value0;
this.f1 = value1;
this.f2 = value2;
} | [
"public",
"void",
"setFields",
"(",
"T0",
"value0",
",",
"T1",
"value1",
",",
"T2",
"value2",
")",
"{",
"this",
".",
"f0",
"=",
"value0",
";",
"this",
".",
"f1",
"=",
"value1",
";",
"this",
".",
"f2",
"=",
"value2",
";",
"}"
] | Sets new values to all fields of the tuple.
@param value0 The value for field 0
@param value1 The value for field 1
@param value2 The value for field 2 | [
"Sets",
"new",
"values",
"to",
"all",
"fields",
"of",
"the",
"tuple",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/java/tuple/Tuple3.java#L120-L124 |
Netflix/netflix-graph | src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java | NFBuildGraph.addConnection | public void addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal) {
"""
Add a connection to this graph. The connection will be in the given connection model. The connection will be from the node identified by the given
<code>nodeType</code> and <code>fromOrdinal</code>. The connection will be via the specified <code>viaProperty</code> in the {@link NFNodeSpec} for
the given <code>nodeType</code>. The connection will be to the node identified by the given <code>toOrdinal</code>. The type of the to node is implied
by the <code>viaProperty</code>.
"""
NFBuildGraphNode fromNode = nodeCache.getNode(nodeType, fromOrdinal);
NFPropertySpec propertySpec = getPropertySpec(nodeType, viaPropertyName);
int connectionModelIndex = modelHolder.getModelIndex(connectionModel);
NFBuildGraphNode toNode = nodeCache.getNode(propertySpec.getToNodeType(), toOrdinal);
addConnection(fromNode, propertySpec, connectionModelIndex, toNode);
} | java | public void addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal) {
NFBuildGraphNode fromNode = nodeCache.getNode(nodeType, fromOrdinal);
NFPropertySpec propertySpec = getPropertySpec(nodeType, viaPropertyName);
int connectionModelIndex = modelHolder.getModelIndex(connectionModel);
NFBuildGraphNode toNode = nodeCache.getNode(propertySpec.getToNodeType(), toOrdinal);
addConnection(fromNode, propertySpec, connectionModelIndex, toNode);
} | [
"public",
"void",
"addConnection",
"(",
"String",
"connectionModel",
",",
"String",
"nodeType",
",",
"int",
"fromOrdinal",
",",
"String",
"viaPropertyName",
",",
"int",
"toOrdinal",
")",
"{",
"NFBuildGraphNode",
"fromNode",
"=",
"nodeCache",
".",
"getNode",
"(",
... | Add a connection to this graph. The connection will be in the given connection model. The connection will be from the node identified by the given
<code>nodeType</code> and <code>fromOrdinal</code>. The connection will be via the specified <code>viaProperty</code> in the {@link NFNodeSpec} for
the given <code>nodeType</code>. The connection will be to the node identified by the given <code>toOrdinal</code>. The type of the to node is implied
by the <code>viaProperty</code>. | [
"Add",
"a",
"connection",
"to",
"this",
"graph",
".",
"The",
"connection",
"will",
"be",
"in",
"the",
"given",
"connection",
"model",
".",
"The",
"connection",
"will",
"be",
"from",
"the",
"node",
"identified",
"by",
"the",
"given",
"<code",
">",
"nodeType... | train | https://github.com/Netflix/netflix-graph/blob/ee129252a08a9f51dd296d6fca2f0b28b7be284e/src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java#L88-L95 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/FulfillmentInfoUrl.java | FulfillmentInfoUrl.setFulFillmentInfoUrl | public static MozuUrl setFulFillmentInfoUrl(String orderId, String responseFields, String updateMode, String version) {
"""
Get Resource Url for SetFulFillmentInfo
@param orderId Unique identifier of the order.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version Determines whether or not to check versioning of items for concurrency purposes.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/fulfillmentinfo?updatemode={updateMode}&version={version}&responseFields={responseFields}");
formatter.formatUrl("orderId", orderId);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("updateMode", updateMode);
formatter.formatUrl("version", version);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl setFulFillmentInfoUrl(String orderId, String responseFields, String updateMode, String version)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/fulfillmentinfo?updatemode={updateMode}&version={version}&responseFields={responseFields}");
formatter.formatUrl("orderId", orderId);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("updateMode", updateMode);
formatter.formatUrl("version", version);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"setFulFillmentInfoUrl",
"(",
"String",
"orderId",
",",
"String",
"responseFields",
",",
"String",
"updateMode",
",",
"String",
"version",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/orders/{o... | Get Resource Url for SetFulFillmentInfo
@param orderId Unique identifier of the order.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version Determines whether or not to check versioning of items for concurrency purposes.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"SetFulFillmentInfo"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/FulfillmentInfoUrl.java#L40-L48 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java | BitcoinSerializer.makeBlock | @Override
public Block makeBlock(final byte[] payloadBytes, final int offset, final int length) throws ProtocolException {
"""
Make a block from the payload. Extension point for alternative
serialization format support.
"""
return new Block(params, payloadBytes, offset, this, length);
} | java | @Override
public Block makeBlock(final byte[] payloadBytes, final int offset, final int length) throws ProtocolException {
return new Block(params, payloadBytes, offset, this, length);
} | [
"@",
"Override",
"public",
"Block",
"makeBlock",
"(",
"final",
"byte",
"[",
"]",
"payloadBytes",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"throws",
"ProtocolException",
"{",
"return",
"new",
"Block",
"(",
"params",
",",
"payloadByte... | Make a block from the payload. Extension point for alternative
serialization format support. | [
"Make",
"a",
"block",
"from",
"the",
"payload",
".",
"Extension",
"point",
"for",
"alternative",
"serialization",
"format",
"support",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L272-L275 |
overturetool/overture | ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java | VdmBreakpointPropertyPage.createComposite | protected Composite createComposite(Composite parent, int numColumns) {
"""
Creates a fully configured composite with the given number of columns
@param parent
@param numColumns
@return the configured composite
"""
return SWTFactory.createComposite(parent, parent.getFont(), numColumns, 1, GridData.FILL_HORIZONTAL, 0, 0);
} | java | protected Composite createComposite(Composite parent, int numColumns)
{
return SWTFactory.createComposite(parent, parent.getFont(), numColumns, 1, GridData.FILL_HORIZONTAL, 0, 0);
} | [
"protected",
"Composite",
"createComposite",
"(",
"Composite",
"parent",
",",
"int",
"numColumns",
")",
"{",
"return",
"SWTFactory",
".",
"createComposite",
"(",
"parent",
",",
"parent",
".",
"getFont",
"(",
")",
",",
"numColumns",
",",
"1",
",",
"GridData",
... | Creates a fully configured composite with the given number of columns
@param parent
@param numColumns
@return the configured composite | [
"Creates",
"a",
"fully",
"configured",
"composite",
"with",
"the",
"given",
"number",
"of",
"columns"
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java#L490-L493 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/ByteArray.java | ByteArray.copyFrom | public static final ByteArray copyFrom(String string) {
"""
Creates a {@code ByteArray} object given a string. The string is encoded in {@code UTF-8}. The
bytes are copied.
"""
return new ByteArray(ByteString.copyFrom(string, StandardCharsets.UTF_8));
} | java | public static final ByteArray copyFrom(String string) {
return new ByteArray(ByteString.copyFrom(string, StandardCharsets.UTF_8));
} | [
"public",
"static",
"final",
"ByteArray",
"copyFrom",
"(",
"String",
"string",
")",
"{",
"return",
"new",
"ByteArray",
"(",
"ByteString",
".",
"copyFrom",
"(",
"string",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"}"
] | Creates a {@code ByteArray} object given a string. The string is encoded in {@code UTF-8}. The
bytes are copied. | [
"Creates",
"a",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/ByteArray.java#L132-L134 |
apache/fluo-recipes | modules/spark/src/main/java/org/apache/fluo/recipes/spark/FluoSparkHelper.java | FluoSparkHelper.bulkImportKvToFluo | public void bulkImportKvToFluo(JavaPairRDD<Key, Value> data, BulkImportOptions opts) {
"""
Bulk import Key/Value data into into Fluo table (obtained from Fluo configuration). This method
does not repartition data. One RFile will be created for each partition in the passed in RDD.
Ensure the RDD is reasonably partitioned before calling this method.
@param data Key/Value data to import
@param opts Bulk import options
"""
bulkImportKvToAccumulo(data, fluoConfig.getAccumuloTable(), opts);
} | java | public void bulkImportKvToFluo(JavaPairRDD<Key, Value> data, BulkImportOptions opts) {
bulkImportKvToAccumulo(data, fluoConfig.getAccumuloTable(), opts);
} | [
"public",
"void",
"bulkImportKvToFluo",
"(",
"JavaPairRDD",
"<",
"Key",
",",
"Value",
">",
"data",
",",
"BulkImportOptions",
"opts",
")",
"{",
"bulkImportKvToAccumulo",
"(",
"data",
",",
"fluoConfig",
".",
"getAccumuloTable",
"(",
")",
",",
"opts",
")",
";",
... | Bulk import Key/Value data into into Fluo table (obtained from Fluo configuration). This method
does not repartition data. One RFile will be created for each partition in the passed in RDD.
Ensure the RDD is reasonably partitioned before calling this method.
@param data Key/Value data to import
@param opts Bulk import options | [
"Bulk",
"import",
"Key",
"/",
"Value",
"data",
"into",
"into",
"Fluo",
"table",
"(",
"obtained",
"from",
"Fluo",
"configuration",
")",
".",
"This",
"method",
"does",
"not",
"repartition",
"data",
".",
"One",
"RFile",
"will",
"be",
"created",
"for",
"each",... | train | https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/spark/src/main/java/org/apache/fluo/recipes/spark/FluoSparkHelper.java#L175-L177 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/util/bdb/BDBMap.java | BDBMap.getTimestampForId | public static String getTimestampForId(String context, String ip) {
"""
return the timestamp associated with the identifier argument, or now
if no value is associated or something goes wrong.
@param context
@param ip
@return timestamp string value
"""
BDBMap bdbMap = getContextMap(context);
String dateStr = bdbMap.get(ip);
return (dateStr != null) ? dateStr : Timestamp.currentTimestamp().getDateStr();
} | java | public static String getTimestampForId(String context, String ip) {
BDBMap bdbMap = getContextMap(context);
String dateStr = bdbMap.get(ip);
return (dateStr != null) ? dateStr : Timestamp.currentTimestamp().getDateStr();
} | [
"public",
"static",
"String",
"getTimestampForId",
"(",
"String",
"context",
",",
"String",
"ip",
")",
"{",
"BDBMap",
"bdbMap",
"=",
"getContextMap",
"(",
"context",
")",
";",
"String",
"dateStr",
"=",
"bdbMap",
".",
"get",
"(",
"ip",
")",
";",
"return",
... | return the timestamp associated with the identifier argument, or now
if no value is associated or something goes wrong.
@param context
@param ip
@return timestamp string value | [
"return",
"the",
"timestamp",
"associated",
"with",
"the",
"identifier",
"argument",
"or",
"now",
"if",
"no",
"value",
"is",
"associated",
"or",
"something",
"goes",
"wrong",
"."
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/bdb/BDBMap.java#L155-L159 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/PathMetadataFactory.java | PathMetadataFactory.forDelegate | public static <T> PathMetadata forDelegate(Path<T> delegate) {
"""
Create a new PathMetadata instance for delegate access
@param delegate delegate path
@return wrapped path
"""
return new PathMetadata(delegate, delegate, PathType.DELEGATE);
} | java | public static <T> PathMetadata forDelegate(Path<T> delegate) {
return new PathMetadata(delegate, delegate, PathType.DELEGATE);
} | [
"public",
"static",
"<",
"T",
">",
"PathMetadata",
"forDelegate",
"(",
"Path",
"<",
"T",
">",
"delegate",
")",
"{",
"return",
"new",
"PathMetadata",
"(",
"delegate",
",",
"delegate",
",",
"PathType",
".",
"DELEGATE",
")",
";",
"}"
] | Create a new PathMetadata instance for delegate access
@param delegate delegate path
@return wrapped path | [
"Create",
"a",
"new",
"PathMetadata",
"instance",
"for",
"delegate",
"access"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/PathMetadataFactory.java#L64-L66 |
groovy/groovy-core | src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java | StringGroovyMethods.isCase | public static boolean isCase(Pattern caseValue, Object switchValue) {
"""
'Case' implementation for the {@link java.util.regex.Pattern} class, which allows
testing a String against a number of regular expressions.
For example:
<pre>switch( str ) {
case ~/one/ :
// the regex 'one' matches the value of str
}
</pre>
Note that this returns true for the case where both the pattern and
the 'switch' values are <code>null</code>.
@param caseValue the case value
@param switchValue the switch value
@return true if the switchValue is deemed to match the caseValue
@since 1.0
"""
if (switchValue == null) {
return caseValue == null;
}
final Matcher matcher = caseValue.matcher(switchValue.toString());
if (matcher.matches()) {
RegexSupport.setLastMatcher(matcher);
return true;
} else {
return false;
}
} | java | public static boolean isCase(Pattern caseValue, Object switchValue) {
if (switchValue == null) {
return caseValue == null;
}
final Matcher matcher = caseValue.matcher(switchValue.toString());
if (matcher.matches()) {
RegexSupport.setLastMatcher(matcher);
return true;
} else {
return false;
}
} | [
"public",
"static",
"boolean",
"isCase",
"(",
"Pattern",
"caseValue",
",",
"Object",
"switchValue",
")",
"{",
"if",
"(",
"switchValue",
"==",
"null",
")",
"{",
"return",
"caseValue",
"==",
"null",
";",
"}",
"final",
"Matcher",
"matcher",
"=",
"caseValue",
... | 'Case' implementation for the {@link java.util.regex.Pattern} class, which allows
testing a String against a number of regular expressions.
For example:
<pre>switch( str ) {
case ~/one/ :
// the regex 'one' matches the value of str
}
</pre>
Note that this returns true for the case where both the pattern and
the 'switch' values are <code>null</code>.
@param caseValue the case value
@param switchValue the switch value
@return true if the switchValue is deemed to match the caseValue
@since 1.0 | [
"Case",
"implementation",
"for",
"the",
"{",
"@link",
"java",
".",
"util",
".",
"regex",
".",
"Pattern",
"}",
"class",
"which",
"allows",
"testing",
"a",
"String",
"against",
"a",
"number",
"of",
"regular",
"expressions",
".",
"For",
"example",
":",
"<pre"... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L1700-L1711 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/release/gradle/GradlePropertiesTransformer.java | GradlePropertiesTransformer.invoke | public Boolean invoke(File propertiesFile, VirtualChannel channel) throws IOException, InterruptedException {
"""
{@inheritDoc}
@return {@code True} in case the properties file was modified during the transformation. {@code false} otherwise
"""
if (!propertiesFile.exists()) {
throw new AbortException("Couldn't find properties file: " + propertiesFile.getAbsolutePath());
}
PropertiesTransformer transformer = new PropertiesTransformer(propertiesFile, versionsByName);
return transformer.transform();
} | java | public Boolean invoke(File propertiesFile, VirtualChannel channel) throws IOException, InterruptedException {
if (!propertiesFile.exists()) {
throw new AbortException("Couldn't find properties file: " + propertiesFile.getAbsolutePath());
}
PropertiesTransformer transformer = new PropertiesTransformer(propertiesFile, versionsByName);
return transformer.transform();
} | [
"public",
"Boolean",
"invoke",
"(",
"File",
"propertiesFile",
",",
"VirtualChannel",
"channel",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"if",
"(",
"!",
"propertiesFile",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"AbortException",... | {@inheritDoc}
@return {@code True} in case the properties file was modified during the transformation. {@code false} otherwise | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/release/gradle/GradlePropertiesTransformer.java#L45-L51 |
stapler/stapler | core/src/main/java/org/kohsuke/stapler/RequestImpl.java | RequestImpl.getPropertyType | private TypePair getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException {
"""
Gets the type of the field/property designate by the given name.
"""
try {
PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(bean, name);
if(propDescriptor!=null) {
Method m = propDescriptor.getWriteMethod();
if(m!=null)
return new TypePair(m.getGenericParameterTypes()[0], m.getParameterTypes()[0]);
}
} catch (NoSuchMethodException e) {
// no such property
}
// try a field
try {
return new TypePair(bean.getClass().getField(name));
} catch (NoSuchFieldException e) {
// no such field
}
return null;
} | java | private TypePair getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException {
try {
PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(bean, name);
if(propDescriptor!=null) {
Method m = propDescriptor.getWriteMethod();
if(m!=null)
return new TypePair(m.getGenericParameterTypes()[0], m.getParameterTypes()[0]);
}
} catch (NoSuchMethodException e) {
// no such property
}
// try a field
try {
return new TypePair(bean.getClass().getField(name));
} catch (NoSuchFieldException e) {
// no such field
}
return null;
} | [
"private",
"TypePair",
"getPropertyType",
"(",
"Object",
"bean",
",",
"String",
"name",
")",
"throws",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"try",
"{",
"PropertyDescriptor",
"propDescriptor",
"=",
"PropertyUtils",
".",
"getPropertyDescriptor",
... | Gets the type of the field/property designate by the given name. | [
"Gets",
"the",
"type",
"of",
"the",
"field",
"/",
"property",
"designate",
"by",
"the",
"given",
"name",
"."
] | train | https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/core/src/main/java/org/kohsuke/stapler/RequestImpl.java#L888-L908 |
transloadit/java-sdk | src/main/java/com/transloadit/sdk/Assembly.java | Assembly.addFile | public void addFile(File file, String name) {
"""
Adds a file to your assembly. If the field name specified already exists, it will override the content of the
existing name.
@param file {@link File} the file to be uploaded.
@param name {@link String} the field name of the file when submitted Transloadit.
"""
files.put(name, file);
// remove duplicate key
if (fileStreams.containsKey(name)) {
fileStreams.remove(name);
}
} | java | public void addFile(File file, String name) {
files.put(name, file);
// remove duplicate key
if (fileStreams.containsKey(name)) {
fileStreams.remove(name);
}
} | [
"public",
"void",
"addFile",
"(",
"File",
"file",
",",
"String",
"name",
")",
"{",
"files",
".",
"put",
"(",
"name",
",",
"file",
")",
";",
"// remove duplicate key",
"if",
"(",
"fileStreams",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"fileStreams"... | Adds a file to your assembly. If the field name specified already exists, it will override the content of the
existing name.
@param file {@link File} the file to be uploaded.
@param name {@link String} the field name of the file when submitted Transloadit. | [
"Adds",
"a",
"file",
"to",
"your",
"assembly",
".",
"If",
"the",
"field",
"name",
"specified",
"already",
"exists",
"it",
"will",
"override",
"the",
"content",
"of",
"the",
"existing",
"name",
"."
] | train | https://github.com/transloadit/java-sdk/blob/9326c540a66f77b3d907d0b2c05bff1145ca14f7/src/main/java/com/transloadit/sdk/Assembly.java#L57-L64 |
EdwardRaff/JSAT | JSAT/src/jsat/utils/IndexTable.java | IndexTable.apply | public void apply(List target, List tmp) {
"""
Applies this index table to the specified target, putting {@code target}
into the same ordering as this IndexTable. It will use the provided
{@code tmp} space to store the original values in target in the same
ordering. It will be modified, and may be expanded using the {@link
List#add(java.lang.Object) add} method if it does not contain sufficient
space. Extra size in the tmp list will be ignored. After this method is
called, {@code tmp} will contain the same ordering that was in
{@code target} <br>
<br>
This method is provided as a means to reducing memory use when multiple
lists need to be sorted.
@param target the list to sort, that should be the same size as the
previously sorted list.
@param tmp the temp list that may be of any size
"""
if (target.size() != length())
throw new RuntimeException("target array does not have the same length as the index table");
//fill tmp with the original ordering or target, adding when needed
for (int i = 0; i < target.size(); i++)
if (i >= tmp.size())
tmp.add(target.get(i));
else
tmp.set(i, target.get(i));
//place back into target from tmp to get sorted order
for(int i = 0; i < target.size(); i++)
target.set(i, tmp.get(index(i)));
} | java | public void apply(List target, List tmp)
{
if (target.size() != length())
throw new RuntimeException("target array does not have the same length as the index table");
//fill tmp with the original ordering or target, adding when needed
for (int i = 0; i < target.size(); i++)
if (i >= tmp.size())
tmp.add(target.get(i));
else
tmp.set(i, target.get(i));
//place back into target from tmp to get sorted order
for(int i = 0; i < target.size(); i++)
target.set(i, tmp.get(index(i)));
} | [
"public",
"void",
"apply",
"(",
"List",
"target",
",",
"List",
"tmp",
")",
"{",
"if",
"(",
"target",
".",
"size",
"(",
")",
"!=",
"length",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"target array does not have the same length as the index table\"... | Applies this index table to the specified target, putting {@code target}
into the same ordering as this IndexTable. It will use the provided
{@code tmp} space to store the original values in target in the same
ordering. It will be modified, and may be expanded using the {@link
List#add(java.lang.Object) add} method if it does not contain sufficient
space. Extra size in the tmp list will be ignored. After this method is
called, {@code tmp} will contain the same ordering that was in
{@code target} <br>
<br>
This method is provided as a means to reducing memory use when multiple
lists need to be sorted.
@param target the list to sort, that should be the same size as the
previously sorted list.
@param tmp the temp list that may be of any size | [
"Applies",
"this",
"index",
"table",
"to",
"the",
"specified",
"target",
"putting",
"{",
"@code",
"target",
"}",
"into",
"the",
"same",
"ordering",
"as",
"this",
"IndexTable",
".",
"It",
"will",
"use",
"the",
"provided",
"{",
"@code",
"tmp",
"}",
"space",
... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/IndexTable.java#L316-L329 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateModifier.java | DateModifier.modifyField | private static void modifyField(Calendar calendar, int field, ModifyType modifyType) {
"""
修改日期字段值
@param calendar {@link Calendar}
@param field 字段,见{@link Calendar}
@param modifyType {@link ModifyType}
"""
// Console.log("# {} {}", DateField.of(field), calendar.getActualMinimum(field));
switch (modifyType) {
case TRUNCATE:
calendar.set(field, DateUtil.getBeginValue(calendar, field));
break;
case CEILING:
calendar.set(field, DateUtil.getEndValue(calendar, field));
break;
case ROUND:
int min = DateUtil.getBeginValue(calendar, field);
int max = DateUtil.getEndValue(calendar, field);
int href;
if (Calendar.DAY_OF_WEEK == field) {
// 星期特殊处理,假设周一是第一天,中间的为周四
href = (min + 3) % 7;
} else {
href = (max - min) / 2 + 1;
}
int value = calendar.get(field);
calendar.set(field, (value < href) ? min : max);
break;
}
} | java | private static void modifyField(Calendar calendar, int field, ModifyType modifyType) {
// Console.log("# {} {}", DateField.of(field), calendar.getActualMinimum(field));
switch (modifyType) {
case TRUNCATE:
calendar.set(field, DateUtil.getBeginValue(calendar, field));
break;
case CEILING:
calendar.set(field, DateUtil.getEndValue(calendar, field));
break;
case ROUND:
int min = DateUtil.getBeginValue(calendar, field);
int max = DateUtil.getEndValue(calendar, field);
int href;
if (Calendar.DAY_OF_WEEK == field) {
// 星期特殊处理,假设周一是第一天,中间的为周四
href = (min + 3) % 7;
} else {
href = (max - min) / 2 + 1;
}
int value = calendar.get(field);
calendar.set(field, (value < href) ? min : max);
break;
}
} | [
"private",
"static",
"void",
"modifyField",
"(",
"Calendar",
"calendar",
",",
"int",
"field",
",",
"ModifyType",
"modifyType",
")",
"{",
"// Console.log(\"# {} {}\", DateField.of(field), calendar.getActualMinimum(field));\r",
"switch",
"(",
"modifyType",
")",
"{",
"case",
... | 修改日期字段值
@param calendar {@link Calendar}
@param field 字段,见{@link Calendar}
@param modifyType {@link ModifyType} | [
"修改日期字段值"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateModifier.java#L98-L121 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/record/Record.java | Record.readColumn | public final byte[] readColumn(byte[] buffer, int column) {
"""
Returns the {@code column's} byte array data contained in {@code buffer}.
@param buffer {@code byte[]}; must be non-null and of the same length as
{@link #getRecordSize()}
@param column Column to read
@return {@code byte[]}
@throws InvalidArgument Thrown if {@code buffer} is null or invalid
"""
if (buffer == null) {
throw new InvalidArgument("buffer", buffer);
} else if (buffer.length != recordSize) {
final String fmt = "invalid buffer (%d bytes, expected %d)";
final String msg = format(fmt, buffer.length, recordSize);
throw new InvalidArgument(msg);
}
int i = 0, offset = 0;
for (; i < column; i++) {
offset += columns[i].size;
}
Column<?> c = columns[i];
byte[] ret = new byte[c.size];
arraycopy(buffer, offset, ret, 0, c.size);
return ret;
} | java | public final byte[] readColumn(byte[] buffer, int column) {
if (buffer == null) {
throw new InvalidArgument("buffer", buffer);
} else if (buffer.length != recordSize) {
final String fmt = "invalid buffer (%d bytes, expected %d)";
final String msg = format(fmt, buffer.length, recordSize);
throw new InvalidArgument(msg);
}
int i = 0, offset = 0;
for (; i < column; i++) {
offset += columns[i].size;
}
Column<?> c = columns[i];
byte[] ret = new byte[c.size];
arraycopy(buffer, offset, ret, 0, c.size);
return ret;
} | [
"public",
"final",
"byte",
"[",
"]",
"readColumn",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"column",
")",
"{",
"if",
"(",
"buffer",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidArgument",
"(",
"\"buffer\"",
",",
"buffer",
")",
";",
"}",
"else... | Returns the {@code column's} byte array data contained in {@code buffer}.
@param buffer {@code byte[]}; must be non-null and of the same length as
{@link #getRecordSize()}
@param column Column to read
@return {@code byte[]}
@throws InvalidArgument Thrown if {@code buffer} is null or invalid | [
"Returns",
"the",
"{",
"@code",
"column",
"s",
"}",
"byte",
"array",
"data",
"contained",
"in",
"{",
"@code",
"buffer",
"}",
"."
] | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/record/Record.java#L126-L144 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxrs.2.0.server/src/com/ibm/ws/jaxrs20/server/LibertyJaxRsServerFactoryBean.java | LibertyJaxRsServerFactoryBean.injectContextApplication | void injectContextApplication(Application app) {
"""
Inject ThreadLocal proxy into Application if there is context injection:
Please be aware doesn't inject the application itself.
9.2.1 Application
The instance of the application-supplied Application subclass can be injected into a class field or method
parameter using the @Context annotation. Access to the Application subclass instance allows configuration
information to be centralized in that class. Note that this cannot be injected into the Application
subclass itself since this would create a circular dependency.
@param app
"""
ApplicationInfo appinfo = new ApplicationInfo(app, this.getBus());
if (appinfo.contextsAvailable()) {
InjectionRuntimeContext irc = InjectionRuntimeContextHelper.getRuntimeContext();
for (Map.Entry<Class<?>, Method> entry : appinfo.getContextMethods().entrySet()) {
Method method = entry.getValue();
Object value = method.getParameterTypes()[0] == Application.class ? null : appinfo.getContextSetterProxy(method);
irc.setRuntimeCtxObject(entry.getKey().getName(),
value);
InjectionUtils.injectThroughMethod(app, method, value);
}
//FIXME: what if we have a method and field with same name?
for (Field f : appinfo.getContextFields()) {
Object value = f.getType() == Application.class ? null : appinfo.getContextFieldProxy(f);
irc.setRuntimeCtxObject(f.getType().getName(), value);
InjectionUtils.injectFieldValue(f, app, value);
}
}
} | java | void injectContextApplication(Application app) {
ApplicationInfo appinfo = new ApplicationInfo(app, this.getBus());
if (appinfo.contextsAvailable()) {
InjectionRuntimeContext irc = InjectionRuntimeContextHelper.getRuntimeContext();
for (Map.Entry<Class<?>, Method> entry : appinfo.getContextMethods().entrySet()) {
Method method = entry.getValue();
Object value = method.getParameterTypes()[0] == Application.class ? null : appinfo.getContextSetterProxy(method);
irc.setRuntimeCtxObject(entry.getKey().getName(),
value);
InjectionUtils.injectThroughMethod(app, method, value);
}
//FIXME: what if we have a method and field with same name?
for (Field f : appinfo.getContextFields()) {
Object value = f.getType() == Application.class ? null : appinfo.getContextFieldProxy(f);
irc.setRuntimeCtxObject(f.getType().getName(), value);
InjectionUtils.injectFieldValue(f, app, value);
}
}
} | [
"void",
"injectContextApplication",
"(",
"Application",
"app",
")",
"{",
"ApplicationInfo",
"appinfo",
"=",
"new",
"ApplicationInfo",
"(",
"app",
",",
"this",
".",
"getBus",
"(",
")",
")",
";",
"if",
"(",
"appinfo",
".",
"contextsAvailable",
"(",
")",
")",
... | Inject ThreadLocal proxy into Application if there is context injection:
Please be aware doesn't inject the application itself.
9.2.1 Application
The instance of the application-supplied Application subclass can be injected into a class field or method
parameter using the @Context annotation. Access to the Application subclass instance allows configuration
information to be centralized in that class. Note that this cannot be injected into the Application
subclass itself since this would create a circular dependency.
@param app | [
"Inject",
"ThreadLocal",
"proxy",
"into",
"Application",
"if",
"there",
"is",
"context",
"injection",
":",
"Please",
"be",
"aware",
"doesn",
"t",
"inject",
"the",
"application",
"itself",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxrs.2.0.server/src/com/ibm/ws/jaxrs20/server/LibertyJaxRsServerFactoryBean.java#L127-L147 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/ProductUrl.java | ProductUrl.updateProductInCatalogUrl | public static MozuUrl updateProductInCatalogUrl(Integer catalogId, String productCode, String responseFields) {
"""
Get Resource Url for UpdateProductInCatalog
@param catalogId Unique identifier for a catalog.
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/ProductInCatalogs/{catalogId}?responseFields={responseFields}");
formatter.formatUrl("catalogId", catalogId);
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl updateProductInCatalogUrl(Integer catalogId, String productCode, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/ProductInCatalogs/{catalogId}?responseFields={responseFields}");
formatter.formatUrl("catalogId", catalogId);
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"updateProductInCatalogUrl",
"(",
"Integer",
"catalogId",
",",
"String",
"productCode",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/catalog/admin/products/{productCo... | Get Resource Url for UpdateProductInCatalog
@param catalogId Unique identifier for a catalog.
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"UpdateProductInCatalog"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/ProductUrl.java#L139-L146 |
jinahya/hex-codec | src/main/java/com/github/jinahya/codec/HexDecoder.java | HexDecoder.decodeMultiple | public static byte[] decodeMultiple(final byte[] input) {
"""
Encodes given sequence of nibbles into a sequence of octets.
@param input the nibbles to decode.
@return the decoded octets.
"""
if (input == null) {
throw new NullPointerException("input");
}
final byte[] output = new byte[input.length >> 1]; // /2
decodeMultiple(input, 0, output, 0, output.length);
return output;
} | java | public static byte[] decodeMultiple(final byte[] input) {
if (input == null) {
throw new NullPointerException("input");
}
final byte[] output = new byte[input.length >> 1]; // /2
decodeMultiple(input, 0, output, 0, output.length);
return output;
} | [
"public",
"static",
"byte",
"[",
"]",
"decodeMultiple",
"(",
"final",
"byte",
"[",
"]",
"input",
")",
"{",
"if",
"(",
"input",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"input\"",
")",
";",
"}",
"final",
"byte",
"[",
"]",
... | Encodes given sequence of nibbles into a sequence of octets.
@param input the nibbles to decode.
@return the decoded octets. | [
"Encodes",
"given",
"sequence",
"of",
"nibbles",
"into",
"a",
"sequence",
"of",
"octets",
"."
] | train | https://github.com/jinahya/hex-codec/blob/159aa54010821655496177e76a3ef35a49fbd433/src/main/java/com/github/jinahya/codec/HexDecoder.java#L181-L192 |
Wadpam/guja | guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java | GeneratedDContactDaoImpl.queryByCompanyName | public Iterable<DContact> queryByCompanyName(Object parent, java.lang.String companyName) {
"""
query-by method for field companyName
@param companyName the specified attribute
@return an Iterable of DContacts for the specified companyName
"""
return queryByField(parent, DContactMapper.Field.COMPANYNAME.getFieldName(), companyName);
} | java | public Iterable<DContact> queryByCompanyName(Object parent, java.lang.String companyName) {
return queryByField(parent, DContactMapper.Field.COMPANYNAME.getFieldName(), companyName);
} | [
"public",
"Iterable",
"<",
"DContact",
">",
"queryByCompanyName",
"(",
"Object",
"parent",
",",
"java",
".",
"lang",
".",
"String",
"companyName",
")",
"{",
"return",
"queryByField",
"(",
"parent",
",",
"DContactMapper",
".",
"Field",
".",
"COMPANYNAME",
".",
... | query-by method for field companyName
@param companyName the specified attribute
@return an Iterable of DContacts for the specified companyName | [
"query",
"-",
"by",
"method",
"for",
"field",
"companyName"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L115-L117 |
apache/spark | common/network-common/src/main/java/org/apache/spark/network/TransportContext.java | TransportContext.createChannelHandler | private TransportChannelHandler createChannelHandler(Channel channel, RpcHandler rpcHandler) {
"""
Creates the server- and client-side handler which is used to handle both RequestMessages and
ResponseMessages. The channel is expected to have been successfully created, though certain
properties (such as the remoteAddress()) may not be available yet.
"""
TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
TransportClient client = new TransportClient(channel, responseHandler);
TransportRequestHandler requestHandler = new TransportRequestHandler(channel, client,
rpcHandler, conf.maxChunksBeingTransferred());
return new TransportChannelHandler(client, responseHandler, requestHandler,
conf.connectionTimeoutMs(), closeIdleConnections, this);
} | java | private TransportChannelHandler createChannelHandler(Channel channel, RpcHandler rpcHandler) {
TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
TransportClient client = new TransportClient(channel, responseHandler);
TransportRequestHandler requestHandler = new TransportRequestHandler(channel, client,
rpcHandler, conf.maxChunksBeingTransferred());
return new TransportChannelHandler(client, responseHandler, requestHandler,
conf.connectionTimeoutMs(), closeIdleConnections, this);
} | [
"private",
"TransportChannelHandler",
"createChannelHandler",
"(",
"Channel",
"channel",
",",
"RpcHandler",
"rpcHandler",
")",
"{",
"TransportResponseHandler",
"responseHandler",
"=",
"new",
"TransportResponseHandler",
"(",
"channel",
")",
";",
"TransportClient",
"client",
... | Creates the server- and client-side handler which is used to handle both RequestMessages and
ResponseMessages. The channel is expected to have been successfully created, though certain
properties (such as the remoteAddress()) may not be available yet. | [
"Creates",
"the",
"server",
"-",
"and",
"client",
"-",
"side",
"handler",
"which",
"is",
"used",
"to",
"handle",
"both",
"RequestMessages",
"and",
"ResponseMessages",
".",
"The",
"channel",
"is",
"expected",
"to",
"have",
"been",
"successfully",
"created",
"th... | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/TransportContext.java#L217-L224 |
opengeospatial/teamengine | teamengine-spi/src/main/java/com/occamlab/te/spi/jaxrs/ErrorResponseBuilder.java | ErrorResponseBuilder.buildErrorResponse | public Response buildErrorResponse(int statusCode, String msg) {
"""
Builds a response message that indicates some kind of error has occurred.
The error message is included as the content of the xhtml:body/xhtml:p
element.
@param statusCode
The relevant HTTP error code (4xx, 5xx).
@param msg
A brief description of the error condition.
@return A <code>Response</code> instance containing an XHTML entity.
"""
ResponseBuilder rspBuilder = Response.status(statusCode);
rspBuilder.type("application/xhtml+xml; charset=UTF-8");
rspBuilder.entity(createErrorEntityAsString(statusCode, msg));
return rspBuilder.build();
} | java | public Response buildErrorResponse(int statusCode, String msg) {
ResponseBuilder rspBuilder = Response.status(statusCode);
rspBuilder.type("application/xhtml+xml; charset=UTF-8");
rspBuilder.entity(createErrorEntityAsString(statusCode, msg));
return rspBuilder.build();
} | [
"public",
"Response",
"buildErrorResponse",
"(",
"int",
"statusCode",
",",
"String",
"msg",
")",
"{",
"ResponseBuilder",
"rspBuilder",
"=",
"Response",
".",
"status",
"(",
"statusCode",
")",
";",
"rspBuilder",
".",
"type",
"(",
"\"application/xhtml+xml; charset=UTF-... | Builds a response message that indicates some kind of error has occurred.
The error message is included as the content of the xhtml:body/xhtml:p
element.
@param statusCode
The relevant HTTP error code (4xx, 5xx).
@param msg
A brief description of the error condition.
@return A <code>Response</code> instance containing an XHTML entity. | [
"Builds",
"a",
"response",
"message",
"that",
"indicates",
"some",
"kind",
"of",
"error",
"has",
"occurred",
".",
"The",
"error",
"message",
"is",
"included",
"as",
"the",
"content",
"of",
"the",
"xhtml",
":",
"body",
"/",
"xhtml",
":",
"p",
"element",
"... | train | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-spi/src/main/java/com/occamlab/te/spi/jaxrs/ErrorResponseBuilder.java#L26-L31 |
SonarSource/sonarqube | server/sonar-server/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.java | PermissionPrivilegeChecker.checkProjectAdmin | public static void checkProjectAdmin(UserSession userSession, String organizationUuid, Optional<ProjectId> projectId) {
"""
Checks that user is administrator of the specified project, or of the specified organization if project is not
defined.
@throws org.sonar.server.exceptions.ForbiddenException if user is not administrator
"""
userSession.checkLoggedIn();
if (userSession.hasPermission(OrganizationPermission.ADMINISTER, organizationUuid)) {
return;
}
if (projectId.isPresent()) {
userSession.checkComponentUuidPermission(UserRole.ADMIN, projectId.get().getUuid());
} else {
throw insufficientPrivilegesException();
}
} | java | public static void checkProjectAdmin(UserSession userSession, String organizationUuid, Optional<ProjectId> projectId) {
userSession.checkLoggedIn();
if (userSession.hasPermission(OrganizationPermission.ADMINISTER, organizationUuid)) {
return;
}
if (projectId.isPresent()) {
userSession.checkComponentUuidPermission(UserRole.ADMIN, projectId.get().getUuid());
} else {
throw insufficientPrivilegesException();
}
} | [
"public",
"static",
"void",
"checkProjectAdmin",
"(",
"UserSession",
"userSession",
",",
"String",
"organizationUuid",
",",
"Optional",
"<",
"ProjectId",
">",
"projectId",
")",
"{",
"userSession",
".",
"checkLoggedIn",
"(",
")",
";",
"if",
"(",
"userSession",
".... | Checks that user is administrator of the specified project, or of the specified organization if project is not
defined.
@throws org.sonar.server.exceptions.ForbiddenException if user is not administrator | [
"Checks",
"that",
"user",
"is",
"administrator",
"of",
"the",
"specified",
"project",
"or",
"of",
"the",
"specified",
"organization",
"if",
"project",
"is",
"not",
"defined",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/permission/PermissionPrivilegeChecker.java#L45-L57 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java | HttpPostMultipartRequestDecoder.readLineStandard | private static String readLineStandard(ByteBuf undecodedChunk, Charset charset) {
"""
Read one line up to the CRLF or LF
@return the String from one line
@throws NotEnoughDataDecoderException
Need more chunks and reset the {@code readerIndex} to the previous
value
"""
int readerIndex = undecodedChunk.readerIndex();
try {
ByteBuf line = buffer(64);
while (undecodedChunk.isReadable()) {
byte nextByte = undecodedChunk.readByte();
if (nextByte == HttpConstants.CR) {
// check but do not changed readerIndex
nextByte = undecodedChunk.getByte(undecodedChunk.readerIndex());
if (nextByte == HttpConstants.LF) {
// force read
undecodedChunk.readByte();
return line.toString(charset);
} else {
// Write CR (not followed by LF)
line.writeByte(HttpConstants.CR);
}
} else if (nextByte == HttpConstants.LF) {
return line.toString(charset);
} else {
line.writeByte(nextByte);
}
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException();
} | java | private static String readLineStandard(ByteBuf undecodedChunk, Charset charset) {
int readerIndex = undecodedChunk.readerIndex();
try {
ByteBuf line = buffer(64);
while (undecodedChunk.isReadable()) {
byte nextByte = undecodedChunk.readByte();
if (nextByte == HttpConstants.CR) {
// check but do not changed readerIndex
nextByte = undecodedChunk.getByte(undecodedChunk.readerIndex());
if (nextByte == HttpConstants.LF) {
// force read
undecodedChunk.readByte();
return line.toString(charset);
} else {
// Write CR (not followed by LF)
line.writeByte(HttpConstants.CR);
}
} else if (nextByte == HttpConstants.LF) {
return line.toString(charset);
} else {
line.writeByte(nextByte);
}
}
} catch (IndexOutOfBoundsException e) {
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException(e);
}
undecodedChunk.readerIndex(readerIndex);
throw new NotEnoughDataDecoderException();
} | [
"private",
"static",
"String",
"readLineStandard",
"(",
"ByteBuf",
"undecodedChunk",
",",
"Charset",
"charset",
")",
"{",
"int",
"readerIndex",
"=",
"undecodedChunk",
".",
"readerIndex",
"(",
")",
";",
"try",
"{",
"ByteBuf",
"line",
"=",
"buffer",
"(",
"64",
... | Read one line up to the CRLF or LF
@return the String from one line
@throws NotEnoughDataDecoderException
Need more chunks and reset the {@code readerIndex} to the previous
value | [
"Read",
"one",
"line",
"up",
"to",
"the",
"CRLF",
"or",
"LF"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java#L991-L1021 |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.createNewPortletDefinitionForm | private PortletDefinitionForm createNewPortletDefinitionForm() {
"""
/*
Create a {@code PortletDefinitionForm} and pre-populate it with default categories and principal permissions.
"""
final PortletDefinitionForm form = new PortletDefinitionForm();
// pre-populate with top-level category
final IEntityGroup portletCategoriesGroup =
GroupService.getDistinguishedGroup(IPortletDefinition.DISTINGUISHED_GROUP);
form.addCategory(
new JsonEntityBean(
portletCategoriesGroup,
groupListHelper.getEntityType(portletCategoriesGroup)));
// pre-populate with top-level group
final IEntityGroup everyoneGroup =
GroupService.getDistinguishedGroup(IPerson.DISTINGUISHED_GROUP);
final JsonEntityBean everyoneBean =
new JsonEntityBean(everyoneGroup, groupListHelper.getEntityType(everyoneGroup));
form.setPrincipals(Collections.singleton(everyoneBean), true);
return form;
} | java | private PortletDefinitionForm createNewPortletDefinitionForm() {
final PortletDefinitionForm form = new PortletDefinitionForm();
// pre-populate with top-level category
final IEntityGroup portletCategoriesGroup =
GroupService.getDistinguishedGroup(IPortletDefinition.DISTINGUISHED_GROUP);
form.addCategory(
new JsonEntityBean(
portletCategoriesGroup,
groupListHelper.getEntityType(portletCategoriesGroup)));
// pre-populate with top-level group
final IEntityGroup everyoneGroup =
GroupService.getDistinguishedGroup(IPerson.DISTINGUISHED_GROUP);
final JsonEntityBean everyoneBean =
new JsonEntityBean(everyoneGroup, groupListHelper.getEntityType(everyoneGroup));
form.setPrincipals(Collections.singleton(everyoneBean), true);
return form;
} | [
"private",
"PortletDefinitionForm",
"createNewPortletDefinitionForm",
"(",
")",
"{",
"final",
"PortletDefinitionForm",
"form",
"=",
"new",
"PortletDefinitionForm",
"(",
")",
";",
"// pre-populate with top-level category",
"final",
"IEntityGroup",
"portletCategoriesGroup",
"=",
... | /*
Create a {@code PortletDefinitionForm} and pre-populate it with default categories and principal permissions. | [
"/",
"*",
"Create",
"a",
"{"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L266-L285 |
mikepenz/FastAdapter | library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/SubItemUtil.java | SubItemUtil.notifyItemsChanged | public static <Item extends IItem & IExpandable> void notifyItemsChanged(final FastAdapter adapter, ExpandableExtension expandableExtension, Set<Long> identifiers) {
"""
notifies items (incl. sub items if they are currently extended)
@param adapter the adapter
@param identifiers set of identifiers that should be notified
"""
notifyItemsChanged(adapter, expandableExtension, identifiers, false);
} | java | public static <Item extends IItem & IExpandable> void notifyItemsChanged(final FastAdapter adapter, ExpandableExtension expandableExtension, Set<Long> identifiers) {
notifyItemsChanged(adapter, expandableExtension, identifiers, false);
} | [
"public",
"static",
"<",
"Item",
"extends",
"IItem",
"&",
"IExpandable",
">",
"void",
"notifyItemsChanged",
"(",
"final",
"FastAdapter",
"adapter",
",",
"ExpandableExtension",
"expandableExtension",
",",
"Set",
"<",
"Long",
">",
"identifiers",
")",
"{",
"notifyIte... | notifies items (incl. sub items if they are currently extended)
@param adapter the adapter
@param identifiers set of identifiers that should be notified | [
"notifies",
"items",
"(",
"incl",
".",
"sub",
"items",
"if",
"they",
"are",
"currently",
"extended",
")"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/SubItemUtil.java#L489-L491 |
riversun/d6 | src/main/java/org/riversun/d6/core/D6Crud.java | D6Crud.execDelete | public boolean execDelete(D6Model[] modelObjs) {
"""
Delete the appropriate lines in specified model objects
@param modelObjs
@return true:DB operation success false:failure
"""
if (modelObjs == null || modelObjs.length == 0) {
return false;
}
boolean retVal = false;
final D6CrudDeleteHelper dh = new D6CrudDeleteHelper(modelObjs[0].getClass());
final String deleteSQL = dh.createDeletePreparedSQLStatement();
log("#execDelete modelObjs=" + modelObjs + " delete SQL=" + deleteSQL);
final Connection conn = createConnection();
try {
PreparedStatement preparedStmt = null;
// There is a possibility that the error occurs in one single delete
// statement.
// Therefore, turn the auto commit off.
conn.setAutoCommit(false);
preparedStmt = conn.prepareStatement(deleteSQL);
for (D6Model modelObj : modelObjs) {
dh.map(modelObj, preparedStmt);
// execute SQL
preparedStmt.executeUpdate();
}
// Finally, commit.
conn.commit();
retVal = true;
} catch (SQLException e) {
loge("#execDelete", e);
retVal = false;
} catch (D6Exception e) {
// catch from helper
loge("#execDelete", e);
retVal = false;
} finally {
try {
conn.close();
} catch (SQLException e) {
retVal = false;
loge("#execDelete", e);
}
}
return retVal;
} | java | public boolean execDelete(D6Model[] modelObjs) {
if (modelObjs == null || modelObjs.length == 0) {
return false;
}
boolean retVal = false;
final D6CrudDeleteHelper dh = new D6CrudDeleteHelper(modelObjs[0].getClass());
final String deleteSQL = dh.createDeletePreparedSQLStatement();
log("#execDelete modelObjs=" + modelObjs + " delete SQL=" + deleteSQL);
final Connection conn = createConnection();
try {
PreparedStatement preparedStmt = null;
// There is a possibility that the error occurs in one single delete
// statement.
// Therefore, turn the auto commit off.
conn.setAutoCommit(false);
preparedStmt = conn.prepareStatement(deleteSQL);
for (D6Model modelObj : modelObjs) {
dh.map(modelObj, preparedStmt);
// execute SQL
preparedStmt.executeUpdate();
}
// Finally, commit.
conn.commit();
retVal = true;
} catch (SQLException e) {
loge("#execDelete", e);
retVal = false;
} catch (D6Exception e) {
// catch from helper
loge("#execDelete", e);
retVal = false;
} finally {
try {
conn.close();
} catch (SQLException e) {
retVal = false;
loge("#execDelete", e);
}
}
return retVal;
} | [
"public",
"boolean",
"execDelete",
"(",
"D6Model",
"[",
"]",
"modelObjs",
")",
"{",
"if",
"(",
"modelObjs",
"==",
"null",
"||",
"modelObjs",
".",
"length",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"boolean",
"retVal",
"=",
"false",
";",
"final... | Delete the appropriate lines in specified model objects
@param modelObjs
@return true:DB operation success false:failure | [
"Delete",
"the",
"appropriate",
"lines",
"in",
"specified",
"model",
"objects"
] | train | https://github.com/riversun/d6/blob/2798bd876b9380dbfea8182d11ad306cb1b0e114/src/main/java/org/riversun/d6/core/D6Crud.java#L150-L209 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java | CqlConfigHelper.setOutputCql | public static void setOutputCql(Configuration conf, String cql) {
"""
Set the CQL prepared statement for the output of this job.
@param conf Job configuration you are about to run
@param cql
"""
if (cql == null || cql.isEmpty())
return;
conf.set(OUTPUT_CQL, cql);
} | java | public static void setOutputCql(Configuration conf, String cql)
{
if (cql == null || cql.isEmpty())
return;
conf.set(OUTPUT_CQL, cql);
} | [
"public",
"static",
"void",
"setOutputCql",
"(",
"Configuration",
"conf",
",",
"String",
"cql",
")",
"{",
"if",
"(",
"cql",
"==",
"null",
"||",
"cql",
".",
"isEmpty",
"(",
")",
")",
"return",
";",
"conf",
".",
"set",
"(",
"OUTPUT_CQL",
",",
"cql",
")... | Set the CQL prepared statement for the output of this job.
@param conf Job configuration you are about to run
@param cql | [
"Set",
"the",
"CQL",
"prepared",
"statement",
"for",
"the",
"output",
"of",
"this",
"job",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java#L138-L144 |
DDTH/ddth-dao | ddth-dao-core/src/main/java/com/github/ddth/dao/BaseBo.java | BaseBo.getAttributeAsDate | public Date getAttributeAsDate(String attrName, String dateTimeFormat) {
"""
Get a BO's attribute as a date. If the attribute value is a string, parse
it as a {@link Date} using the specified date-time format.
@param attrName
@param dateTimeFormat
@return
@since 0.8.0
"""
Lock lock = lockForRead();
try {
return MapUtils.getDate(attributes, attrName, dateTimeFormat);
} finally {
lock.unlock();
}
} | java | public Date getAttributeAsDate(String attrName, String dateTimeFormat) {
Lock lock = lockForRead();
try {
return MapUtils.getDate(attributes, attrName, dateTimeFormat);
} finally {
lock.unlock();
}
} | [
"public",
"Date",
"getAttributeAsDate",
"(",
"String",
"attrName",
",",
"String",
"dateTimeFormat",
")",
"{",
"Lock",
"lock",
"=",
"lockForRead",
"(",
")",
";",
"try",
"{",
"return",
"MapUtils",
".",
"getDate",
"(",
"attributes",
",",
"attrName",
",",
"dateT... | Get a BO's attribute as a date. If the attribute value is a string, parse
it as a {@link Date} using the specified date-time format.
@param attrName
@param dateTimeFormat
@return
@since 0.8.0 | [
"Get",
"a",
"BO",
"s",
"attribute",
"as",
"a",
"date",
".",
"If",
"the",
"attribute",
"value",
"is",
"a",
"string",
"parse",
"it",
"as",
"a",
"{",
"@link",
"Date",
"}",
"using",
"the",
"specified",
"date",
"-",
"time",
"format",
"."
] | train | https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseBo.java#L290-L297 |
sargue/mailgun | src/main/java/net/sargue/mailgun/MailBuilder.java | MailBuilder.from | public MailBuilder from(String name, String email) {
"""
Sets the address of the sender.
@param name the name of the sender
@param email the address of the sender
@return this builder
"""
return param("from", email(name, email));
} | java | public MailBuilder from(String name, String email) {
return param("from", email(name, email));
} | [
"public",
"MailBuilder",
"from",
"(",
"String",
"name",
",",
"String",
"email",
")",
"{",
"return",
"param",
"(",
"\"from\"",
",",
"email",
"(",
"name",
",",
"email",
")",
")",
";",
"}"
] | Sets the address of the sender.
@param name the name of the sender
@param email the address of the sender
@return this builder | [
"Sets",
"the",
"address",
"of",
"the",
"sender",
"."
] | train | https://github.com/sargue/mailgun/blob/2ffb0a156f3f3666eb1bb2db661451b9377c3d11/src/main/java/net/sargue/mailgun/MailBuilder.java#L82-L84 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/GPXTablesFactory.java | GPXTablesFactory.createTrackTable | public static PreparedStatement createTrackTable(Connection connection, String trackTableName,boolean isH2) throws SQLException {
"""
Creat the track table
@param connection
@param trackTableName
@param isH2 set true if it's an H2 database
@return
@throws SQLException
"""
try (Statement stmt = connection.createStatement()) {
StringBuilder sb = new StringBuilder("CREATE TABLE ");
sb.append(trackTableName).append(" (");
if (isH2) {
sb.append("the_geom MULTILINESTRING CHECK ST_SRID(THE_GEOM) = 4326,");
} else {
sb.append("the_geom GEOMETRY(MULTILINESTRING, 4326),");
}
sb.append(" id INT,");
sb.append(GPXTags.NAME.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.CMT.toLowerCase()).append(" TEXT,");
sb.append("description").append(" TEXT,");
sb.append(GPXTags.SRC.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.HREF.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.HREFTITLE.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.NUMBER.toLowerCase()).append(" INT,");
sb.append(GPXTags.TYPE.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.EXTENSIONS.toLowerCase()).append(" TEXT);");
stmt.execute(sb.toString());
}
//We return the preparedstatement of the route table
StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackTableName).append(" VALUES ( ?");
for (int i = 1; i < GpxMetadata.RTEFIELDCOUNT; i++) {
insert.append(",?");
}
insert.append(");");
return connection.prepareStatement(insert.toString());
} | java | public static PreparedStatement createTrackTable(Connection connection, String trackTableName,boolean isH2) throws SQLException {
try (Statement stmt = connection.createStatement()) {
StringBuilder sb = new StringBuilder("CREATE TABLE ");
sb.append(trackTableName).append(" (");
if (isH2) {
sb.append("the_geom MULTILINESTRING CHECK ST_SRID(THE_GEOM) = 4326,");
} else {
sb.append("the_geom GEOMETRY(MULTILINESTRING, 4326),");
}
sb.append(" id INT,");
sb.append(GPXTags.NAME.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.CMT.toLowerCase()).append(" TEXT,");
sb.append("description").append(" TEXT,");
sb.append(GPXTags.SRC.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.HREF.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.HREFTITLE.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.NUMBER.toLowerCase()).append(" INT,");
sb.append(GPXTags.TYPE.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.EXTENSIONS.toLowerCase()).append(" TEXT);");
stmt.execute(sb.toString());
}
//We return the preparedstatement of the route table
StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackTableName).append(" VALUES ( ?");
for (int i = 1; i < GpxMetadata.RTEFIELDCOUNT; i++) {
insert.append(",?");
}
insert.append(");");
return connection.prepareStatement(insert.toString());
} | [
"public",
"static",
"PreparedStatement",
"createTrackTable",
"(",
"Connection",
"connection",
",",
"String",
"trackTableName",
",",
"boolean",
"isH2",
")",
"throws",
"SQLException",
"{",
"try",
"(",
"Statement",
"stmt",
"=",
"connection",
".",
"createStatement",
"("... | Creat the track table
@param connection
@param trackTableName
@param isH2 set true if it's an H2 database
@return
@throws SQLException | [
"Creat",
"the",
"track",
"table"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/GPXTablesFactory.java#L204-L233 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.getBlockingLockedResources | public List<CmsResource> getBlockingLockedResources(CmsResource resource) throws CmsException {
"""
Returns a list of child resources to the given resource that can not be locked by the current user.<p>
@param resource the resource
@return a list of child resources to the given resource that can not be locked by the current user
@throws CmsException if something goes wrong reading the resources
"""
if (resource.isFolder()) {
CmsLockFilter blockingFilter = CmsLockFilter.FILTER_ALL;
blockingFilter = blockingFilter.filterNotLockableByUser(getRequestContext().getCurrentUser());
return getLockedResources(resource, blockingFilter);
}
return Collections.<CmsResource> emptyList();
} | java | public List<CmsResource> getBlockingLockedResources(CmsResource resource) throws CmsException {
if (resource.isFolder()) {
CmsLockFilter blockingFilter = CmsLockFilter.FILTER_ALL;
blockingFilter = blockingFilter.filterNotLockableByUser(getRequestContext().getCurrentUser());
return getLockedResources(resource, blockingFilter);
}
return Collections.<CmsResource> emptyList();
} | [
"public",
"List",
"<",
"CmsResource",
">",
"getBlockingLockedResources",
"(",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"resource",
".",
"isFolder",
"(",
")",
")",
"{",
"CmsLockFilter",
"blockingFilter",
"=",
"CmsLockFilter",
".",
... | Returns a list of child resources to the given resource that can not be locked by the current user.<p>
@param resource the resource
@return a list of child resources to the given resource that can not be locked by the current user
@throws CmsException if something goes wrong reading the resources | [
"Returns",
"a",
"list",
"of",
"child",
"resources",
"to",
"the",
"given",
"resource",
"that",
"can",
"not",
"be",
"locked",
"by",
"the",
"current",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L1344-L1352 |
VoltDB/voltdb | src/frontend/org/voltdb/parser/SQLParser.java | SQLParser.hexDigitsToLong | public static long hexDigitsToLong(String hexDigits) throws SQLParser.Exception {
"""
Given a string of hex digits, produce a long value, assuming
a 2's complement representation.
"""
// BigInteger.longValue() will truncate to the lowest 64 bits,
// so we need to explicitly check if there's too many digits.
if (hexDigits.length() > 16) {
throw new SQLParser.Exception("Too many hexadecimal digits for BIGINT value");
}
if (hexDigits.length() == 0) {
throw new SQLParser.Exception("Zero hexadecimal digits is invalid for BIGINT value");
}
// The method
// Long.parseLong(<digits>, <radix>);
// Doesn't quite do what we want---it expects a '-' to
// indicate negative values, and doesn't want the sign bit set
// in the hex digits.
//
// Once we support Java 1.8, we can use Long.parseUnsignedLong(<digits>, 16)
// instead.
long val = new BigInteger(hexDigits, 16).longValue();
return val;
} | java | public static long hexDigitsToLong(String hexDigits) throws SQLParser.Exception {
// BigInteger.longValue() will truncate to the lowest 64 bits,
// so we need to explicitly check if there's too many digits.
if (hexDigits.length() > 16) {
throw new SQLParser.Exception("Too many hexadecimal digits for BIGINT value");
}
if (hexDigits.length() == 0) {
throw new SQLParser.Exception("Zero hexadecimal digits is invalid for BIGINT value");
}
// The method
// Long.parseLong(<digits>, <radix>);
// Doesn't quite do what we want---it expects a '-' to
// indicate negative values, and doesn't want the sign bit set
// in the hex digits.
//
// Once we support Java 1.8, we can use Long.parseUnsignedLong(<digits>, 16)
// instead.
long val = new BigInteger(hexDigits, 16).longValue();
return val;
} | [
"public",
"static",
"long",
"hexDigitsToLong",
"(",
"String",
"hexDigits",
")",
"throws",
"SQLParser",
".",
"Exception",
"{",
"// BigInteger.longValue() will truncate to the lowest 64 bits,",
"// so we need to explicitly check if there's too many digits.",
"if",
"(",
"hexDigits",
... | Given a string of hex digits, produce a long value, assuming
a 2's complement representation. | [
"Given",
"a",
"string",
"of",
"hex",
"digits",
"produce",
"a",
"long",
"value",
"assuming",
"a",
"2",
"s",
"complement",
"representation",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/parser/SQLParser.java#L1624-L1647 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/metadata/JdbcTypesHelper.java | JdbcTypesHelper.getObjectFromColumn | public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)
throws SQLException {
"""
Returns an java object read from the specified ResultSet column.
"""
return getObjectFromColumn(rs, null, jdbcType, null, columnId);
} | java | public static Object getObjectFromColumn(ResultSet rs, Integer jdbcType, int columnId)
throws SQLException
{
return getObjectFromColumn(rs, null, jdbcType, null, columnId);
} | [
"public",
"static",
"Object",
"getObjectFromColumn",
"(",
"ResultSet",
"rs",
",",
"Integer",
"jdbcType",
",",
"int",
"columnId",
")",
"throws",
"SQLException",
"{",
"return",
"getObjectFromColumn",
"(",
"rs",
",",
"null",
",",
"jdbcType",
",",
"null",
",",
"co... | Returns an java object read from the specified ResultSet column. | [
"Returns",
"an",
"java",
"object",
"read",
"from",
"the",
"specified",
"ResultSet",
"column",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/JdbcTypesHelper.java#L213-L217 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkProxy.java | WorkProxy.contextSetupFailure | private WorkCompletedException contextSetupFailure(Object context, String errorCode, Throwable cause) {
"""
Handle a work context setup failure.
@param workContext the work context.
@param errorCode error code from javax.resource.spi.work.WorkContextErrorCodes
@param cause Throwable to chain as the cause. Can be null.
@return WorkCompletedException to raise the the invoker.
"""
if (context instanceof WorkContextLifecycleListener)
((WorkContextLifecycleListener) context).contextSetupFailed(errorCode);
String message = null;
if (WorkContextErrorCodes.DUPLICATE_CONTEXTS.equals(errorCode))
message = Utils.getMessage("J2CA8624.work.context.duplicate", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (WorkContextErrorCodes.UNSUPPORTED_CONTEXT_TYPE.equals(errorCode))
message = Utils.getMessage("J2CA8625.work.context.unavailable", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (cause != null)
message = cause.getMessage();
WorkCompletedException wcex = new WorkCompletedException(message, errorCode);
if (cause != null)
wcex.initCause(cause);
return wcex;
} | java | private WorkCompletedException contextSetupFailure(Object context, String errorCode, Throwable cause) {
if (context instanceof WorkContextLifecycleListener)
((WorkContextLifecycleListener) context).contextSetupFailed(errorCode);
String message = null;
if (WorkContextErrorCodes.DUPLICATE_CONTEXTS.equals(errorCode))
message = Utils.getMessage("J2CA8624.work.context.duplicate", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (WorkContextErrorCodes.UNSUPPORTED_CONTEXT_TYPE.equals(errorCode))
message = Utils.getMessage("J2CA8625.work.context.unavailable", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (cause != null)
message = cause.getMessage();
WorkCompletedException wcex = new WorkCompletedException(message, errorCode);
if (cause != null)
wcex.initCause(cause);
return wcex;
} | [
"private",
"WorkCompletedException",
"contextSetupFailure",
"(",
"Object",
"context",
",",
"String",
"errorCode",
",",
"Throwable",
"cause",
")",
"{",
"if",
"(",
"context",
"instanceof",
"WorkContextLifecycleListener",
")",
"(",
"(",
"WorkContextLifecycleListener",
")",... | Handle a work context setup failure.
@param workContext the work context.
@param errorCode error code from javax.resource.spi.work.WorkContextErrorCodes
@param cause Throwable to chain as the cause. Can be null.
@return WorkCompletedException to raise the the invoker. | [
"Handle",
"a",
"work",
"context",
"setup",
"failure",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkProxy.java#L325-L343 |
alibaba/jstorm | jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/appmaster/JstormMaster.java | JstormMaster.setupContainerAskForRM | public ContainerRequest setupContainerAskForRM(int containerMemory, int containerVirtualCores, int priority, String host) {
"""
Setup the request that will be sent to the RM for the container ask.
@return the setup ResourceRequest to be sent to RM
"""
// setup requirements for hosts
// using * as any host will do for the jstorm app
// set the priority for the request
Priority pri = Priority.newInstance(priority);
// Set up resource type requirements
// For now, memory and CPU are supported so we set memory and cpu requirements
Resource capability = Resource.newInstance(containerMemory,
containerVirtualCores);
ContainerRequest request = new ContainerRequest(capability, null, null,
pri);
LOG.info("By Thrift Server Requested container ask: " + request.toString());
return request;
} | java | public ContainerRequest setupContainerAskForRM(int containerMemory, int containerVirtualCores, int priority, String host) {
// setup requirements for hosts
// using * as any host will do for the jstorm app
// set the priority for the request
Priority pri = Priority.newInstance(priority);
// Set up resource type requirements
// For now, memory and CPU are supported so we set memory and cpu requirements
Resource capability = Resource.newInstance(containerMemory,
containerVirtualCores);
ContainerRequest request = new ContainerRequest(capability, null, null,
pri);
LOG.info("By Thrift Server Requested container ask: " + request.toString());
return request;
} | [
"public",
"ContainerRequest",
"setupContainerAskForRM",
"(",
"int",
"containerMemory",
",",
"int",
"containerVirtualCores",
",",
"int",
"priority",
",",
"String",
"host",
")",
"{",
"// setup requirements for hosts",
"// using * as any host will do for the jstorm app",
"// set t... | Setup the request that will be sent to the RM for the container ask.
@return the setup ResourceRequest to be sent to RM | [
"Setup",
"the",
"request",
"that",
"will",
"be",
"sent",
"to",
"the",
"RM",
"for",
"the",
"container",
"ask",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/appmaster/JstormMaster.java#L1070-L1084 |
leadware/jpersistence-tools | jpersistence-tools-core/src/main/java/net/leadware/persistence/tools/core/dao/utils/ExpressionModel.java | ExpressionModel.addParameter | public void addParameter(String parameterName, String parameterExpression) {
"""
Methode d'ajout d'un Parametre
@param parameterName Nom du parametre
@param parameterExpression Expression du parametre
"""
// Si le nom du parametre est null
if(parameterName == null || parameterName.trim().length() == 0) return;
// Si l'expression est vide
if(parameterExpression == null || parameterExpression.trim().length() == 0) return;
// On ajoute le Parametre
this.parameters.put(parameterName, parameterExpression);
} | java | public void addParameter(String parameterName, String parameterExpression) {
// Si le nom du parametre est null
if(parameterName == null || parameterName.trim().length() == 0) return;
// Si l'expression est vide
if(parameterExpression == null || parameterExpression.trim().length() == 0) return;
// On ajoute le Parametre
this.parameters.put(parameterName, parameterExpression);
} | [
"public",
"void",
"addParameter",
"(",
"String",
"parameterName",
",",
"String",
"parameterExpression",
")",
"{",
"// Si le nom du parametre est null\r",
"if",
"(",
"parameterName",
"==",
"null",
"||",
"parameterName",
".",
"trim",
"(",
")",
".",
"length",
"(",
")... | Methode d'ajout d'un Parametre
@param parameterName Nom du parametre
@param parameterExpression Expression du parametre | [
"Methode",
"d",
"ajout",
"d",
"un",
"Parametre"
] | train | https://github.com/leadware/jpersistence-tools/blob/4c15372993584579d7dbb9b23dd4c0c0fdc9e789/jpersistence-tools-core/src/main/java/net/leadware/persistence/tools/core/dao/utils/ExpressionModel.java#L112-L122 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/ClusterManager.java | ClusterManager.nodeAppRemoved | public void nodeAppRemoved(String nodeName, ResourceType type) {
"""
This is an internal api called to tell the cluster manager that a
particular type of resource is no longer available on a node.
@param nodeName
Name of the node on which the resource is removed.
@param type
The type of resource to be removed.
"""
Set<String> sessions = nodeManager.getNodeSessions(nodeName);
Set<ClusterNode.GrantId> grantsToRevoke =
nodeManager.deleteAppFromNode(nodeName, type);
if (grantsToRevoke == null) {
return;
}
Set<String> affectedSessions = new HashSet<String>();
for (String sessionHandle : sessions) {
try {
if (sessionManager.getSession(sessionHandle).
getTypes().contains(type)) {
affectedSessions.add(sessionHandle);
}
} catch (InvalidSessionHandle ex) {
// ignore
LOG.warn("Found invalid session: " + sessionHandle
+ " while timing out node: " + nodeName);
}
}
handleDeadNode(nodeName, affectedSessions);
handleRevokedGrants(nodeName, grantsToRevoke);
scheduler.notifyScheduler();
} | java | public void nodeAppRemoved(String nodeName, ResourceType type) {
Set<String> sessions = nodeManager.getNodeSessions(nodeName);
Set<ClusterNode.GrantId> grantsToRevoke =
nodeManager.deleteAppFromNode(nodeName, type);
if (grantsToRevoke == null) {
return;
}
Set<String> affectedSessions = new HashSet<String>();
for (String sessionHandle : sessions) {
try {
if (sessionManager.getSession(sessionHandle).
getTypes().contains(type)) {
affectedSessions.add(sessionHandle);
}
} catch (InvalidSessionHandle ex) {
// ignore
LOG.warn("Found invalid session: " + sessionHandle
+ " while timing out node: " + nodeName);
}
}
handleDeadNode(nodeName, affectedSessions);
handleRevokedGrants(nodeName, grantsToRevoke);
scheduler.notifyScheduler();
} | [
"public",
"void",
"nodeAppRemoved",
"(",
"String",
"nodeName",
",",
"ResourceType",
"type",
")",
"{",
"Set",
"<",
"String",
">",
"sessions",
"=",
"nodeManager",
".",
"getNodeSessions",
"(",
"nodeName",
")",
";",
"Set",
"<",
"ClusterNode",
".",
"GrantId",
">"... | This is an internal api called to tell the cluster manager that a
particular type of resource is no longer available on a node.
@param nodeName
Name of the node on which the resource is removed.
@param type
The type of resource to be removed. | [
"This",
"is",
"an",
"internal",
"api",
"called",
"to",
"tell",
"the",
"cluster",
"manager",
"that",
"a",
"particular",
"type",
"of",
"resource",
"is",
"no",
"longer",
"available",
"on",
"a",
"node",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/ClusterManager.java#L847-L870 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java | AnnotationUtility.extractAsString | public static String extractAsString(final Element item, final Class<? extends Annotation> annotationClass, final AnnotationAttributeType attributeName) {
"""
Extract from an annotation of a method the attribute value specified.
@param item the item
@param annotationClass the annotation class
@param attributeName the attribute name
@return attribute value extracted as class typeName
"""
final Elements elementUtils=BaseProcessor.elementUtils;
final One<String> result = new One<String>();
extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
List<String> list = AnnotationUtility.extractAsArrayOfString(value);
if (list.size() > 0)
result.value0 = list.get(0);
else
result.value0 = value;
}
});
return result.value0;
} | java | public static String extractAsString(final Element item, final Class<? extends Annotation> annotationClass, final AnnotationAttributeType attributeName) {
final Elements elementUtils=BaseProcessor.elementUtils;
final One<String> result = new One<String>();
extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {
@Override
public void onFound(String value) {
List<String> list = AnnotationUtility.extractAsArrayOfString(value);
if (list.size() > 0)
result.value0 = list.get(0);
else
result.value0 = value;
}
});
return result.value0;
} | [
"public",
"static",
"String",
"extractAsString",
"(",
"final",
"Element",
"item",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
",",
"final",
"AnnotationAttributeType",
"attributeName",
")",
"{",
"final",
"Elements",
"elementUtils... | Extract from an annotation of a method the attribute value specified.
@param item the item
@param annotationClass the annotation class
@param attributeName the attribute name
@return attribute value extracted as class typeName | [
"Extract",
"from",
"an",
"annotation",
"of",
"a",
"method",
"the",
"attribute",
"value",
"specified",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/AnnotationUtility.java#L240-L259 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/util/CmsPositionBean.java | CmsPositionBean.avoidCollision | public static void avoidCollision(CmsPositionBean posA, CmsPositionBean posB, int margin) {
"""
Manipulates the position infos to ensure a minimum margin between the rectangles.<p>
@param posA the first position to check
@param posB the second position to check
@param margin the required margin
"""
Direction dir = null;
int diff = 0;
int diffTemp = (posB.getLeft() + posB.getWidth()) - posA.getLeft();
if (diffTemp > -margin) {
dir = Direction.left;
diff = diffTemp;
}
diffTemp = (posA.getLeft() + posA.getWidth()) - posB.getLeft();
if ((diffTemp > -margin) && (diffTemp < diff)) {
dir = Direction.right;
diff = diffTemp;
}
diffTemp = (posB.getTop() + posB.getHeight()) - posA.getTop();
if ((diffTemp > -margin) && (diffTemp < diff)) {
dir = Direction.top;
diff = diffTemp;
}
diffTemp = (posA.getTop() + posA.getHeight()) - posB.getTop();
if ((diffTemp > -margin) && (diffTemp < diff)) {
dir = Direction.bottom;
diff = diffTemp;
}
diff = (int)Math.ceil((1.0 * (diff + margin)) / 2);
if (dir != null) {
switch (dir) {
case left:
// move the left border of a
posA.setLeft(posA.getLeft() + diff);
posA.setWidth(posA.getWidth() - diff);
// move the right border of b
posB.setWidth(posB.getWidth() - diff);
break;
case right:
// move the left border of b
posB.setLeft(posB.getLeft() + diff);
posB.setWidth(posB.getWidth() - diff);
// move the right border of a
posA.setWidth(posA.getWidth() - diff);
break;
case top:
posA.setTop(posA.getTop() + diff);
posA.setHeight(posA.getHeight() - diff);
posB.setHeight(posB.getHeight() - diff);
break;
case bottom:
posB.setTop(posB.getTop() + diff);
posB.setHeight(posB.getHeight() - diff);
posA.setHeight(posA.getHeight() - diff);
break;
default:
// nothing to do
}
}
} | java | public static void avoidCollision(CmsPositionBean posA, CmsPositionBean posB, int margin) {
Direction dir = null;
int diff = 0;
int diffTemp = (posB.getLeft() + posB.getWidth()) - posA.getLeft();
if (diffTemp > -margin) {
dir = Direction.left;
diff = diffTemp;
}
diffTemp = (posA.getLeft() + posA.getWidth()) - posB.getLeft();
if ((diffTemp > -margin) && (diffTemp < diff)) {
dir = Direction.right;
diff = diffTemp;
}
diffTemp = (posB.getTop() + posB.getHeight()) - posA.getTop();
if ((diffTemp > -margin) && (diffTemp < diff)) {
dir = Direction.top;
diff = diffTemp;
}
diffTemp = (posA.getTop() + posA.getHeight()) - posB.getTop();
if ((diffTemp > -margin) && (diffTemp < diff)) {
dir = Direction.bottom;
diff = diffTemp;
}
diff = (int)Math.ceil((1.0 * (diff + margin)) / 2);
if (dir != null) {
switch (dir) {
case left:
// move the left border of a
posA.setLeft(posA.getLeft() + diff);
posA.setWidth(posA.getWidth() - diff);
// move the right border of b
posB.setWidth(posB.getWidth() - diff);
break;
case right:
// move the left border of b
posB.setLeft(posB.getLeft() + diff);
posB.setWidth(posB.getWidth() - diff);
// move the right border of a
posA.setWidth(posA.getWidth() - diff);
break;
case top:
posA.setTop(posA.getTop() + diff);
posA.setHeight(posA.getHeight() - diff);
posB.setHeight(posB.getHeight() - diff);
break;
case bottom:
posB.setTop(posB.getTop() + diff);
posB.setHeight(posB.getHeight() - diff);
posA.setHeight(posA.getHeight() - diff);
break;
default:
// nothing to do
}
}
} | [
"public",
"static",
"void",
"avoidCollision",
"(",
"CmsPositionBean",
"posA",
",",
"CmsPositionBean",
"posB",
",",
"int",
"margin",
")",
"{",
"Direction",
"dir",
"=",
"null",
";",
"int",
"diff",
"=",
"0",
";",
"int",
"diffTemp",
"=",
"(",
"posB",
".",
"g... | Manipulates the position infos to ensure a minimum margin between the rectangles.<p>
@param posA the first position to check
@param posB the second position to check
@param margin the required margin | [
"Manipulates",
"the",
"position",
"infos",
"to",
"ensure",
"a",
"minimum",
"margin",
"between",
"the",
"rectangles",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsPositionBean.java#L132-L195 |
sarl/sarl | main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/wizards/importproject/ImportMavenSarlProjectWizard.java | ImportMavenSarlProjectWizard.createImportJob | protected WorkspaceJob createImportJob(Collection<MavenProjectInfo> projects) {
"""
Create the import job.
@param projects the projects to import.
@return the import job.
"""
final WorkspaceJob job = new ImportMavenSarlProjectsJob(projects, this.workingSets, this.importConfiguration);
job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
return job;
} | java | protected WorkspaceJob createImportJob(Collection<MavenProjectInfo> projects) {
final WorkspaceJob job = new ImportMavenSarlProjectsJob(projects, this.workingSets, this.importConfiguration);
job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
return job;
} | [
"protected",
"WorkspaceJob",
"createImportJob",
"(",
"Collection",
"<",
"MavenProjectInfo",
">",
"projects",
")",
"{",
"final",
"WorkspaceJob",
"job",
"=",
"new",
"ImportMavenSarlProjectsJob",
"(",
"projects",
",",
"this",
".",
"workingSets",
",",
"this",
".",
"im... | Create the import job.
@param projects the projects to import.
@return the import job. | [
"Create",
"the",
"import",
"job",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/wizards/importproject/ImportMavenSarlProjectWizard.java#L154-L158 |
amzn/ion-java | src/com/amazon/ion/util/IonTextUtils.java | IonTextUtils.printJsonCodePoint | public static void printJsonCodePoint(Appendable out, int codePoint)
throws IOException {
"""
Prints a single Unicode code point for use in an ASCII-safe JSON string.
@param out the stream to receive the data.
@param codePoint a Unicode code point.
"""
// JSON only allows double-quote strings.
printCodePoint(out, codePoint, EscapeMode.JSON);
} | java | public static void printJsonCodePoint(Appendable out, int codePoint)
throws IOException
{
// JSON only allows double-quote strings.
printCodePoint(out, codePoint, EscapeMode.JSON);
} | [
"public",
"static",
"void",
"printJsonCodePoint",
"(",
"Appendable",
"out",
",",
"int",
"codePoint",
")",
"throws",
"IOException",
"{",
"// JSON only allows double-quote strings.",
"printCodePoint",
"(",
"out",
",",
"codePoint",
",",
"EscapeMode",
".",
"JSON",
")",
... | Prints a single Unicode code point for use in an ASCII-safe JSON string.
@param out the stream to receive the data.
@param codePoint a Unicode code point. | [
"Prints",
"a",
"single",
"Unicode",
"code",
"point",
"for",
"use",
"in",
"an",
"ASCII",
"-",
"safe",
"JSON",
"string",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonTextUtils.java#L224-L229 |
matthewhorridge/binaryowl | src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java | BinaryOWLMetadata.checkForNull | private void checkForNull(String name, Object value) {
"""
Checks the name and value of an attibute name/value pair to see if either of them are null. If either is null
a {@link NullPointerException} is thrown.
@param name The name of the attribute to check.
@param value The value of the attribute to check.
"""
if(name == null) {
throw new NullPointerException("name must not be null");
}
if(value == null) {
throw new NullPointerException("value must not be null");
}
} | java | private void checkForNull(String name, Object value) {
if(name == null) {
throw new NullPointerException("name must not be null");
}
if(value == null) {
throw new NullPointerException("value must not be null");
}
} | [
"private",
"void",
"checkForNull",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"name must not be null\"",
")",
";",
"}",
"if",
"(",
"value",
"==",
"null"... | Checks the name and value of an attibute name/value pair to see if either of them are null. If either is null
a {@link NullPointerException} is thrown.
@param name The name of the attribute to check.
@param value The value of the attribute to check. | [
"Checks",
"the",
"name",
"and",
"value",
"of",
"an",
"attibute",
"name",
"/",
"value",
"pair",
"to",
"see",
"if",
"either",
"of",
"them",
"are",
"null",
".",
"If",
"either",
"is",
"null",
"a",
"{"
] | train | https://github.com/matthewhorridge/binaryowl/blob/7fccfe804120f86b38ca855ddbb569a81a042257/src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java#L159-L166 |
facebook/fresco | animated-gif-lite/src/main/java/com/facebook/animated/giflite/drawable/GifAnimationBackend.java | GifAnimationBackend.scale | private void scale(int viewPortWidth, int viewPortHeight, int sourceWidth, int sourceHeight) {
"""
Measures the source, and sets the size based on them. Maintains aspect ratio of source, and
ensures that screen is filled in at least one dimension.
<p>Adapted from com.facebook.cameracore.common.RenderUtil#calculateFitRect
@param viewPortWidth the width of the display
@param viewPortHeight the height of the display
@param sourceWidth the width of the video
@param sourceHeight the height of the video
"""
float inputRatio = ((float) sourceWidth) / sourceHeight;
float outputRatio = ((float) viewPortWidth) / viewPortHeight;
int scaledWidth = viewPortWidth;
int scaledHeight = viewPortHeight;
if (outputRatio > inputRatio) {
// Not enough width to fill the output. (Black bars on left and right.)
scaledWidth = (int) (viewPortHeight * inputRatio);
scaledHeight = viewPortHeight;
} else if (outputRatio < inputRatio) {
// Not enough height to fill the output. (Black bars on top and bottom.)
scaledHeight = (int) (viewPortWidth / inputRatio);
scaledWidth = viewPortWidth;
}
float scale = scaledWidth / (float) sourceWidth;
mMidX = ((viewPortWidth - scaledWidth) / 2f) / scale;
mMidY = ((viewPortHeight - scaledHeight) / 2f) / scale;
} | java | private void scale(int viewPortWidth, int viewPortHeight, int sourceWidth, int sourceHeight) {
float inputRatio = ((float) sourceWidth) / sourceHeight;
float outputRatio = ((float) viewPortWidth) / viewPortHeight;
int scaledWidth = viewPortWidth;
int scaledHeight = viewPortHeight;
if (outputRatio > inputRatio) {
// Not enough width to fill the output. (Black bars on left and right.)
scaledWidth = (int) (viewPortHeight * inputRatio);
scaledHeight = viewPortHeight;
} else if (outputRatio < inputRatio) {
// Not enough height to fill the output. (Black bars on top and bottom.)
scaledHeight = (int) (viewPortWidth / inputRatio);
scaledWidth = viewPortWidth;
}
float scale = scaledWidth / (float) sourceWidth;
mMidX = ((viewPortWidth - scaledWidth) / 2f) / scale;
mMidY = ((viewPortHeight - scaledHeight) / 2f) / scale;
} | [
"private",
"void",
"scale",
"(",
"int",
"viewPortWidth",
",",
"int",
"viewPortHeight",
",",
"int",
"sourceWidth",
",",
"int",
"sourceHeight",
")",
"{",
"float",
"inputRatio",
"=",
"(",
"(",
"float",
")",
"sourceWidth",
")",
"/",
"sourceHeight",
";",
"float",... | Measures the source, and sets the size based on them. Maintains aspect ratio of source, and
ensures that screen is filled in at least one dimension.
<p>Adapted from com.facebook.cameracore.common.RenderUtil#calculateFitRect
@param viewPortWidth the width of the display
@param viewPortHeight the height of the display
@param sourceWidth the width of the video
@param sourceHeight the height of the video | [
"Measures",
"the",
"source",
"and",
"sets",
"the",
"size",
"based",
"on",
"them",
".",
"Maintains",
"aspect",
"ratio",
"of",
"source",
"and",
"ensures",
"that",
"screen",
"is",
"filled",
"in",
"at",
"least",
"one",
"dimension",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/animated-gif-lite/src/main/java/com/facebook/animated/giflite/drawable/GifAnimationBackend.java#L141-L161 |
dynjs/dynjs | src/main/java/org/dynjs/runtime/modules/ModuleProvider.java | ModuleProvider.setLocalVar | public static void setLocalVar(ExecutionContext context, String name, Object value) {
"""
A convenience for module providers. Sets a scoped variable on the provided
ExecutionContext.
@param context The execution context to bind the variable to
@param name The name of the variable
@param value The value to set the variable to
"""
LexicalEnvironment localEnv = context.getLexicalEnvironment();
localEnv.getRecord().createMutableBinding(context, name, false);
localEnv.getRecord().setMutableBinding(context, name, value, false);
} | java | public static void setLocalVar(ExecutionContext context, String name, Object value) {
LexicalEnvironment localEnv = context.getLexicalEnvironment();
localEnv.getRecord().createMutableBinding(context, name, false);
localEnv.getRecord().setMutableBinding(context, name, value, false);
} | [
"public",
"static",
"void",
"setLocalVar",
"(",
"ExecutionContext",
"context",
",",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"LexicalEnvironment",
"localEnv",
"=",
"context",
".",
"getLexicalEnvironment",
"(",
")",
";",
"localEnv",
".",
"getRecord",
"... | A convenience for module providers. Sets a scoped variable on the provided
ExecutionContext.
@param context The execution context to bind the variable to
@param name The name of the variable
@param value The value to set the variable to | [
"A",
"convenience",
"for",
"module",
"providers",
".",
"Sets",
"a",
"scoped",
"variable",
"on",
"the",
"provided",
"ExecutionContext",
"."
] | train | https://github.com/dynjs/dynjs/blob/4bc6715eff8768f8cd92c6a167d621bbfc1e1a91/src/main/java/org/dynjs/runtime/modules/ModuleProvider.java#L45-L49 |
alkacon/opencms-core | src/org/opencms/xml/containerpage/CmsDynamicFunctionParser.java | CmsDynamicFunctionParser.parseProperty | protected CmsXmlContentProperty parseProperty(CmsObject cms, I_CmsXmlContentLocation field) {
"""
Helper method for parsing a settings definition.<p>
@param cms the current CMS context
@param field the node from which to read the settings definition
@return the parsed setting definition
"""
String name = getString(cms, field.getSubValue("PropertyName"));
String widget = getString(cms, field.getSubValue("Widget"));
if (CmsStringUtil.isEmptyOrWhitespaceOnly(widget)) {
widget = "string";
}
String type = getString(cms, field.getSubValue("Type"));
if (CmsStringUtil.isEmptyOrWhitespaceOnly(type)) {
type = "string";
}
String widgetConfig = getString(cms, field.getSubValue("WidgetConfig"));
String ruleRegex = getString(cms, field.getSubValue("RuleRegex"));
String ruleType = getString(cms, field.getSubValue("RuleType"));
String default1 = getString(cms, field.getSubValue("Default"));
String error = getString(cms, field.getSubValue("Error"));
String niceName = getString(cms, field.getSubValue("DisplayName"));
String description = getString(cms, field.getSubValue("Description"));
CmsXmlContentProperty prop = new CmsXmlContentProperty(
name,
type,
widget,
widgetConfig,
ruleRegex,
ruleType,
default1,
niceName,
description,
error,
"true");
return prop;
} | java | protected CmsXmlContentProperty parseProperty(CmsObject cms, I_CmsXmlContentLocation field) {
String name = getString(cms, field.getSubValue("PropertyName"));
String widget = getString(cms, field.getSubValue("Widget"));
if (CmsStringUtil.isEmptyOrWhitespaceOnly(widget)) {
widget = "string";
}
String type = getString(cms, field.getSubValue("Type"));
if (CmsStringUtil.isEmptyOrWhitespaceOnly(type)) {
type = "string";
}
String widgetConfig = getString(cms, field.getSubValue("WidgetConfig"));
String ruleRegex = getString(cms, field.getSubValue("RuleRegex"));
String ruleType = getString(cms, field.getSubValue("RuleType"));
String default1 = getString(cms, field.getSubValue("Default"));
String error = getString(cms, field.getSubValue("Error"));
String niceName = getString(cms, field.getSubValue("DisplayName"));
String description = getString(cms, field.getSubValue("Description"));
CmsXmlContentProperty prop = new CmsXmlContentProperty(
name,
type,
widget,
widgetConfig,
ruleRegex,
ruleType,
default1,
niceName,
description,
error,
"true");
return prop;
} | [
"protected",
"CmsXmlContentProperty",
"parseProperty",
"(",
"CmsObject",
"cms",
",",
"I_CmsXmlContentLocation",
"field",
")",
"{",
"String",
"name",
"=",
"getString",
"(",
"cms",
",",
"field",
".",
"getSubValue",
"(",
"\"PropertyName\"",
")",
")",
";",
"String",
... | Helper method for parsing a settings definition.<p>
@param cms the current CMS context
@param field the node from which to read the settings definition
@return the parsed setting definition | [
"Helper",
"method",
"for",
"parsing",
"a",
"settings",
"definition",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsDynamicFunctionParser.java#L333-L365 |
Polidea/RxAndroidBle | sample/src/main/java/com/polidea/rxandroidble2/sample/example4_characteristic/advanced/Presenter.java | Presenter.transformToNotificationPresenterEvent | @NonNull
private static ObservableTransformer<Observable<byte[]>, PresenterEvent> transformToNotificationPresenterEvent(Type type) {
"""
A convenience function creating a transformer that will wrap the emissions in either {@link ResultEvent} or {@link ErrorEvent}
with a given {@link Type} for notification type {@link Observable} (Observable<Observable<byte[]>>)
@param type the type to wrap with
@return the transformer
"""
return observableObservable -> observableObservable
.flatMap(observable -> observable
.map(bytes -> ((PresenterEvent) new ResultEvent(bytes, type)))
)
.onErrorReturn(throwable -> new ErrorEvent(throwable, type));
} | java | @NonNull
private static ObservableTransformer<Observable<byte[]>, PresenterEvent> transformToNotificationPresenterEvent(Type type) {
return observableObservable -> observableObservable
.flatMap(observable -> observable
.map(bytes -> ((PresenterEvent) new ResultEvent(bytes, type)))
)
.onErrorReturn(throwable -> new ErrorEvent(throwable, type));
} | [
"@",
"NonNull",
"private",
"static",
"ObservableTransformer",
"<",
"Observable",
"<",
"byte",
"[",
"]",
">",
",",
"PresenterEvent",
">",
"transformToNotificationPresenterEvent",
"(",
"Type",
"type",
")",
"{",
"return",
"observableObservable",
"->",
"observableObservab... | A convenience function creating a transformer that will wrap the emissions in either {@link ResultEvent} or {@link ErrorEvent}
with a given {@link Type} for notification type {@link Observable} (Observable<Observable<byte[]>>)
@param type the type to wrap with
@return the transformer | [
"A",
"convenience",
"function",
"creating",
"a",
"transformer",
"that",
"will",
"wrap",
"the",
"emissions",
"in",
"either",
"{",
"@link",
"ResultEvent",
"}",
"or",
"{",
"@link",
"ErrorEvent",
"}",
"with",
"a",
"given",
"{",
"@link",
"Type",
"}",
"for",
"no... | train | https://github.com/Polidea/RxAndroidBle/blob/c6e4a9753c834d710e255306bb290e9244cdbc10/sample/src/main/java/com/polidea/rxandroidble2/sample/example4_characteristic/advanced/Presenter.java#L246-L253 |
apiman/apiman | gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/components/jdbc/VertxJdbcClientImpl.java | VertxJdbcClientImpl.parseConfig | @SuppressWarnings("nls")
protected JsonObject parseConfig(JdbcOptionsBean config) {
"""
Translate our abstracted {@link JdbcOptionsBean} into a Vert.x-specific config.
We are assuming that the user is using HikariCP.
"""
JsonObject jsonConfig = new JsonObject();
nullSafePut(jsonConfig, "provider_class", HikariCPDataSourceProvider.class.getCanonicalName()); // Vert.x thing
nullSafePut(jsonConfig, "jdbcUrl", config.getJdbcUrl());
nullSafePut(jsonConfig, "username", config.getUsername());
nullSafePut(jsonConfig, "password", config.getPassword());
nullSafePut(jsonConfig, "autoCommit", config.isAutoCommit());
nullSafePut(jsonConfig, "connectionTimeout", config.getConnectionTimeout());
nullSafePut(jsonConfig, "idleTimeout", config.getIdleTimeout());
nullSafePut(jsonConfig, "maxLifetime", config.getMaxLifetime());
nullSafePut(jsonConfig, "minimumIdle", config.getMinimumIdle());
nullSafePut(jsonConfig, "maximumPoolSize", config.getMaximumPoolSize());
nullSafePut(jsonConfig, "poolName", config.getPoolName());
JsonObject dsProperties = new JsonObject();
for (Entry<String, Object> entry : config.getDsProperties().entrySet()) {
dsProperties.put(entry.getKey(), entry.getValue());
}
jsonConfig.put("properties", dsProperties);
return jsonConfig;
} | java | @SuppressWarnings("nls")
protected JsonObject parseConfig(JdbcOptionsBean config) {
JsonObject jsonConfig = new JsonObject();
nullSafePut(jsonConfig, "provider_class", HikariCPDataSourceProvider.class.getCanonicalName()); // Vert.x thing
nullSafePut(jsonConfig, "jdbcUrl", config.getJdbcUrl());
nullSafePut(jsonConfig, "username", config.getUsername());
nullSafePut(jsonConfig, "password", config.getPassword());
nullSafePut(jsonConfig, "autoCommit", config.isAutoCommit());
nullSafePut(jsonConfig, "connectionTimeout", config.getConnectionTimeout());
nullSafePut(jsonConfig, "idleTimeout", config.getIdleTimeout());
nullSafePut(jsonConfig, "maxLifetime", config.getMaxLifetime());
nullSafePut(jsonConfig, "minimumIdle", config.getMinimumIdle());
nullSafePut(jsonConfig, "maximumPoolSize", config.getMaximumPoolSize());
nullSafePut(jsonConfig, "poolName", config.getPoolName());
JsonObject dsProperties = new JsonObject();
for (Entry<String, Object> entry : config.getDsProperties().entrySet()) {
dsProperties.put(entry.getKey(), entry.getValue());
}
jsonConfig.put("properties", dsProperties);
return jsonConfig;
} | [
"@",
"SuppressWarnings",
"(",
"\"nls\"",
")",
"protected",
"JsonObject",
"parseConfig",
"(",
"JdbcOptionsBean",
"config",
")",
"{",
"JsonObject",
"jsonConfig",
"=",
"new",
"JsonObject",
"(",
")",
";",
"nullSafePut",
"(",
"jsonConfig",
",",
"\"provider_class\"",
",... | Translate our abstracted {@link JdbcOptionsBean} into a Vert.x-specific config.
We are assuming that the user is using HikariCP. | [
"Translate",
"our",
"abstracted",
"{",
"@link",
"JdbcOptionsBean",
"}",
"into",
"a",
"Vert",
".",
"x",
"-",
"specific",
"config",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/components/jdbc/VertxJdbcClientImpl.java#L68-L91 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java | VirtualNetworksInner.checkIPAddressAvailability | public IPAddressAvailabilityResultInner checkIPAddressAvailability(String resourceGroupName, String virtualNetworkName, String ipAddress) {
"""
Checks whether a private IP address is available for use.
@param resourceGroupName The name of the resource group.
@param virtualNetworkName The name of the virtual network.
@param ipAddress The private IP address to be verified.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the IPAddressAvailabilityResultInner object if successful.
"""
return checkIPAddressAvailabilityWithServiceResponseAsync(resourceGroupName, virtualNetworkName, ipAddress).toBlocking().single().body();
} | java | public IPAddressAvailabilityResultInner checkIPAddressAvailability(String resourceGroupName, String virtualNetworkName, String ipAddress) {
return checkIPAddressAvailabilityWithServiceResponseAsync(resourceGroupName, virtualNetworkName, ipAddress).toBlocking().single().body();
} | [
"public",
"IPAddressAvailabilityResultInner",
"checkIPAddressAvailability",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkName",
",",
"String",
"ipAddress",
")",
"{",
"return",
"checkIPAddressAvailabilityWithServiceResponseAsync",
"(",
"resourceGroupName",
","... | Checks whether a private IP address is available for use.
@param resourceGroupName The name of the resource group.
@param virtualNetworkName The name of the virtual network.
@param ipAddress The private IP address to be verified.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the IPAddressAvailabilityResultInner object if successful. | [
"Checks",
"whether",
"a",
"private",
"IP",
"address",
"is",
"available",
"for",
"use",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java#L1234-L1236 |
dlemmermann/CalendarFX | CalendarFXView/src/main/java/com/calendarfx/view/DateControl.java | DateControl.setEntryFactory | public final void setEntryFactory(Callback<CreateEntryParameter, Entry<?>> factory) {
"""
Sets the value of {@link #entryFactoryProperty()}.
@param factory the factory used for creating a new entry
"""
Objects.requireNonNull(factory);
entryFactoryProperty().set(factory);
} | java | public final void setEntryFactory(Callback<CreateEntryParameter, Entry<?>> factory) {
Objects.requireNonNull(factory);
entryFactoryProperty().set(factory);
} | [
"public",
"final",
"void",
"setEntryFactory",
"(",
"Callback",
"<",
"CreateEntryParameter",
",",
"Entry",
"<",
"?",
">",
">",
"factory",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"factory",
")",
";",
"entryFactoryProperty",
"(",
")",
".",
"set",
"(",
... | Sets the value of {@link #entryFactoryProperty()}.
@param factory the factory used for creating a new entry | [
"Sets",
"the",
"value",
"of",
"{",
"@link",
"#entryFactoryProperty",
"()",
"}",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/view/DateControl.java#L879-L882 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java | HtmlDocletWriter.addPreQualifiedStrongClassLink | public void addPreQualifiedStrongClassLink(LinkInfoImpl.Kind context, ClassDoc cd, Content contentTree) {
"""
Add the class link, with only class name as the strong link and prefixing
plain package name.
@param context the id of the context where the link will be added
@param cd the class to link to
@param contentTree the content tree to which the link with be added
"""
addPreQualifiedClassLink(context, cd, true, contentTree);
} | java | public void addPreQualifiedStrongClassLink(LinkInfoImpl.Kind context, ClassDoc cd, Content contentTree) {
addPreQualifiedClassLink(context, cd, true, contentTree);
} | [
"public",
"void",
"addPreQualifiedStrongClassLink",
"(",
"LinkInfoImpl",
".",
"Kind",
"context",
",",
"ClassDoc",
"cd",
",",
"Content",
"contentTree",
")",
"{",
"addPreQualifiedClassLink",
"(",
"context",
",",
"cd",
",",
"true",
",",
"contentTree",
")",
";",
"}"... | Add the class link, with only class name as the strong link and prefixing
plain package name.
@param context the id of the context where the link will be added
@param cd the class to link to
@param contentTree the content tree to which the link with be added | [
"Add",
"the",
"class",
"link",
"with",
"only",
"class",
"name",
"as",
"the",
"strong",
"link",
"and",
"prefixing",
"plain",
"package",
"name",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L1162-L1164 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/serialization/SerializationUtils.java | SerializationUtils.serializeAndEncodeObject | public static byte[] serializeAndEncodeObject(final CipherExecutor cipher,
final Serializable object) {
"""
Serialize and encode object byte [ ].
@param cipher the cipher
@param object the object
@return the byte []
"""
return serializeAndEncodeObject(cipher, object, ArrayUtils.EMPTY_OBJECT_ARRAY);
} | java | public static byte[] serializeAndEncodeObject(final CipherExecutor cipher,
final Serializable object) {
return serializeAndEncodeObject(cipher, object, ArrayUtils.EMPTY_OBJECT_ARRAY);
} | [
"public",
"static",
"byte",
"[",
"]",
"serializeAndEncodeObject",
"(",
"final",
"CipherExecutor",
"cipher",
",",
"final",
"Serializable",
"object",
")",
"{",
"return",
"serializeAndEncodeObject",
"(",
"cipher",
",",
"object",
",",
"ArrayUtils",
".",
"EMPTY_OBJECT_AR... | Serialize and encode object byte [ ].
@param cipher the cipher
@param object the object
@return the byte [] | [
"Serialize",
"and",
"encode",
"object",
"byte",
"[",
"]",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/serialization/SerializationUtils.java#L116-L119 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.java | FileOutputCommitter.setupJob | public void setupJob(JobContext context) throws IOException {
"""
Create the temporary directory that is the root of all of the task
work directories.
@param context the job's context
"""
if (outputPath != null) {
Path tmpDir = new Path(outputPath, FileOutputCommitter.TEMP_DIR_NAME);
FileSystem fileSys = tmpDir.getFileSystem(context.getConfiguration());
if (!fileSys.mkdirs(tmpDir)) {
LOG.error("Mkdirs failed to create " + tmpDir.toString());
}
}
} | java | public void setupJob(JobContext context) throws IOException {
if (outputPath != null) {
Path tmpDir = new Path(outputPath, FileOutputCommitter.TEMP_DIR_NAME);
FileSystem fileSys = tmpDir.getFileSystem(context.getConfiguration());
if (!fileSys.mkdirs(tmpDir)) {
LOG.error("Mkdirs failed to create " + tmpDir.toString());
}
}
} | [
"public",
"void",
"setupJob",
"(",
"JobContext",
"context",
")",
"throws",
"IOException",
"{",
"if",
"(",
"outputPath",
"!=",
"null",
")",
"{",
"Path",
"tmpDir",
"=",
"new",
"Path",
"(",
"outputPath",
",",
"FileOutputCommitter",
".",
"TEMP_DIR_NAME",
")",
";... | Create the temporary directory that is the root of all of the task
work directories.
@param context the job's context | [
"Create",
"the",
"temporary",
"directory",
"that",
"is",
"the",
"root",
"of",
"all",
"of",
"the",
"task",
"work",
"directories",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.java#L77-L85 |
hypercube1024/firefly | firefly/src/main/java/com/firefly/codec/http2/model/MultiPartWriter.java | MultiPartWriter.startPart | public void startPart(String contentType, String[] headers) throws IOException {
"""
Start creation of the next Content.
@param contentType the content type of the part
@param headers the part headers
@throws IOException if unable to write the part
"""
if (inPart)
out.write(__CRLF);
out.write(__DASHDASH);
out.write(boundary);
out.write(__CRLF);
out.write("Content-Type: ");
out.write(contentType);
out.write(__CRLF);
for (int i = 0; headers != null && i < headers.length; i++) {
out.write(headers[i]);
out.write(__CRLF);
}
out.write(__CRLF);
inPart = true;
} | java | public void startPart(String contentType, String[] headers) throws IOException {
if (inPart)
out.write(__CRLF);
out.write(__DASHDASH);
out.write(boundary);
out.write(__CRLF);
out.write("Content-Type: ");
out.write(contentType);
out.write(__CRLF);
for (int i = 0; headers != null && i < headers.length; i++) {
out.write(headers[i]);
out.write(__CRLF);
}
out.write(__CRLF);
inPart = true;
} | [
"public",
"void",
"startPart",
"(",
"String",
"contentType",
",",
"String",
"[",
"]",
"headers",
")",
"throws",
"IOException",
"{",
"if",
"(",
"inPart",
")",
"out",
".",
"write",
"(",
"__CRLF",
")",
";",
"out",
".",
"write",
"(",
"__DASHDASH",
")",
";"... | Start creation of the next Content.
@param contentType the content type of the part
@param headers the part headers
@throws IOException if unable to write the part | [
"Start",
"creation",
"of",
"the",
"next",
"Content",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/model/MultiPartWriter.java#L87-L102 |
Jasig/uPortal | uPortal-security/uPortal-security-xslt/src/main/java/org/apereo/portal/security/xslt/XalanGroupMembershipHelperBean.java | XalanGroupMembershipHelperBean.isUserDeepMemberOfGroupName | @Override
public boolean isUserDeepMemberOfGroupName(String userName, String groupName) {
"""
/* (non-Javadoc)
@see org.apereo.portal.security.xslt.IXalanGroupMembershipHelper#isUserDeepMemberOfGroupName(java.lang.String, java.lang.String)
groupName is case sensitive.
"""
final EntityIdentifier[] results =
GroupService.searchForGroups(
groupName, GroupService.SearchMethod.DISCRETE, IPerson.class);
if (results == null || results.length == 0) {
return false;
}
if (results.length > 1) {
this.logger.warn(
results.length
+ " groups were found for '"
+ groupName
+ "'. The first result will be used.");
}
final IGroupMember group = GroupService.getGroupMember(results[0]);
final IEntity entity = GroupService.getEntity(userName, IPerson.class);
if (entity == null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("No user found for key '" + userName + "'");
}
return false;
}
return group.asGroup().deepContains(entity);
} | java | @Override
public boolean isUserDeepMemberOfGroupName(String userName, String groupName) {
final EntityIdentifier[] results =
GroupService.searchForGroups(
groupName, GroupService.SearchMethod.DISCRETE, IPerson.class);
if (results == null || results.length == 0) {
return false;
}
if (results.length > 1) {
this.logger.warn(
results.length
+ " groups were found for '"
+ groupName
+ "'. The first result will be used.");
}
final IGroupMember group = GroupService.getGroupMember(results[0]);
final IEntity entity = GroupService.getEntity(userName, IPerson.class);
if (entity == null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("No user found for key '" + userName + "'");
}
return false;
}
return group.asGroup().deepContains(entity);
} | [
"@",
"Override",
"public",
"boolean",
"isUserDeepMemberOfGroupName",
"(",
"String",
"userName",
",",
"String",
"groupName",
")",
"{",
"final",
"EntityIdentifier",
"[",
"]",
"results",
"=",
"GroupService",
".",
"searchForGroups",
"(",
"groupName",
",",
"GroupService"... | /* (non-Javadoc)
@see org.apereo.portal.security.xslt.IXalanGroupMembershipHelper#isUserDeepMemberOfGroupName(java.lang.String, java.lang.String)
groupName is case sensitive. | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")",
"@see",
"org",
".",
"apereo",
".",
"portal",
".",
"security",
".",
"xslt",
".",
"IXalanGroupMembershipHelper#isUserDeepMemberOfGroupName",
"(",
"java",
".",
"lang",
".",
"String",
"java",
".",
"lang",
".",
"String",... | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-xslt/src/main/java/org/apereo/portal/security/xslt/XalanGroupMembershipHelperBean.java#L121-L150 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/stat/ns/nsmemory_stats.java | nsmemory_stats.get | public static nsmemory_stats get(nitro_service service, String pool) throws Exception {
"""
Use this API to fetch statistics of nsmemory_stats resource of given name .
"""
nsmemory_stats obj = new nsmemory_stats();
obj.set_pool(pool);
nsmemory_stats response = (nsmemory_stats) obj.stat_resource(service);
return response;
} | java | public static nsmemory_stats get(nitro_service service, String pool) throws Exception{
nsmemory_stats obj = new nsmemory_stats();
obj.set_pool(pool);
nsmemory_stats response = (nsmemory_stats) obj.stat_resource(service);
return response;
} | [
"public",
"static",
"nsmemory_stats",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"pool",
")",
"throws",
"Exception",
"{",
"nsmemory_stats",
"obj",
"=",
"new",
"nsmemory_stats",
"(",
")",
";",
"obj",
".",
"set_pool",
"(",
"pool",
")",
";",
"nsmemo... | Use this API to fetch statistics of nsmemory_stats resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"statistics",
"of",
"nsmemory_stats",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/ns/nsmemory_stats.java#L159-L164 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/lang/ServiceLoaderHelper.java | ServiceLoaderHelper.getFirstSPIImplementation | @Nullable
public static <T> T getFirstSPIImplementation (@Nonnull final Class <T> aSPIClass) {
"""
Uses the {@link ServiceLoader} to load all SPI implementations of the
passed class and return only the first instance.
@param <T>
The implementation type to be loaded
@param aSPIClass
The SPI interface class. May not be <code>null</code>.
@return A collection of all currently available plugins. Never
<code>null</code>.
"""
return getFirstSPIImplementation (aSPIClass, ClassLoaderHelper.getDefaultClassLoader (), null);
} | java | @Nullable
public static <T> T getFirstSPIImplementation (@Nonnull final Class <T> aSPIClass)
{
return getFirstSPIImplementation (aSPIClass, ClassLoaderHelper.getDefaultClassLoader (), null);
} | [
"@",
"Nullable",
"public",
"static",
"<",
"T",
">",
"T",
"getFirstSPIImplementation",
"(",
"@",
"Nonnull",
"final",
"Class",
"<",
"T",
">",
"aSPIClass",
")",
"{",
"return",
"getFirstSPIImplementation",
"(",
"aSPIClass",
",",
"ClassLoaderHelper",
".",
"getDefault... | Uses the {@link ServiceLoader} to load all SPI implementations of the
passed class and return only the first instance.
@param <T>
The implementation type to be loaded
@param aSPIClass
The SPI interface class. May not be <code>null</code>.
@return A collection of all currently available plugins. Never
<code>null</code>. | [
"Uses",
"the",
"{",
"@link",
"ServiceLoader",
"}",
"to",
"load",
"all",
"SPI",
"implementations",
"of",
"the",
"passed",
"class",
"and",
"return",
"only",
"the",
"first",
"instance",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/ServiceLoaderHelper.java#L185-L189 |
apache/flink | flink-core/src/main/java/org/apache/flink/core/memory/MemorySegment.java | MemorySegment.copyFromUnsafe | public final void copyFromUnsafe(int offset, Object source, int sourcePointer, int numBytes) {
"""
Bulk copy method. Copies {@code numBytes} bytes from source unsafe object and pointer.
NOTE: This is a unsafe method, no check here, please be carefully.
@param offset The position where the bytes are started to be write in this memory segment.
@param source The unsafe memory to copy the bytes from.
@param sourcePointer The position in the source unsafe memory to copy the chunk from.
@param numBytes The number of bytes to copy.
@throws IndexOutOfBoundsException If this segment can not contain the given number
of bytes (starting from offset).
"""
final long thisPointer = this.address + offset;
if (thisPointer + numBytes > addressLimit) {
throw new IndexOutOfBoundsException(
String.format("offset=%d, numBytes=%d, address=%d",
offset, numBytes, this.address));
}
UNSAFE.copyMemory(source, sourcePointer, this.heapMemory, thisPointer, numBytes);
} | java | public final void copyFromUnsafe(int offset, Object source, int sourcePointer, int numBytes) {
final long thisPointer = this.address + offset;
if (thisPointer + numBytes > addressLimit) {
throw new IndexOutOfBoundsException(
String.format("offset=%d, numBytes=%d, address=%d",
offset, numBytes, this.address));
}
UNSAFE.copyMemory(source, sourcePointer, this.heapMemory, thisPointer, numBytes);
} | [
"public",
"final",
"void",
"copyFromUnsafe",
"(",
"int",
"offset",
",",
"Object",
"source",
",",
"int",
"sourcePointer",
",",
"int",
"numBytes",
")",
"{",
"final",
"long",
"thisPointer",
"=",
"this",
".",
"address",
"+",
"offset",
";",
"if",
"(",
"thisPoin... | Bulk copy method. Copies {@code numBytes} bytes from source unsafe object and pointer.
NOTE: This is a unsafe method, no check here, please be carefully.
@param offset The position where the bytes are started to be write in this memory segment.
@param source The unsafe memory to copy the bytes from.
@param sourcePointer The position in the source unsafe memory to copy the chunk from.
@param numBytes The number of bytes to copy.
@throws IndexOutOfBoundsException If this segment can not contain the given number
of bytes (starting from offset). | [
"Bulk",
"copy",
"method",
".",
"Copies",
"{",
"@code",
"numBytes",
"}",
"bytes",
"from",
"source",
"unsafe",
"object",
"and",
"pointer",
".",
"NOTE",
":",
"This",
"is",
"a",
"unsafe",
"method",
"no",
"check",
"here",
"please",
"be",
"carefully",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/core/memory/MemorySegment.java#L1307-L1315 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.pressText | public static void pressText(File imageFile, File destFile, String pressText, Color color, Font font, int x, int y, float alpha) {
"""
给图片添加文字水印
@param imageFile 源图像文件
@param destFile 目标图像文件
@param pressText 水印文字
@param color 水印的字体颜色
@param font {@link Font} 字体相关信息,如果默认则为{@code null}
@param x 修正值。 默认在中间,偏移量相对于中间偏移
@param y 修正值。 默认在中间,偏移量相对于中间偏移
@param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
"""
pressText(read(imageFile), destFile, pressText, color, font, x, y, alpha);
} | java | public static void pressText(File imageFile, File destFile, String pressText, Color color, Font font, int x, int y, float alpha) {
pressText(read(imageFile), destFile, pressText, color, font, x, y, alpha);
} | [
"public",
"static",
"void",
"pressText",
"(",
"File",
"imageFile",
",",
"File",
"destFile",
",",
"String",
"pressText",
",",
"Color",
"color",
",",
"Font",
"font",
",",
"int",
"x",
",",
"int",
"y",
",",
"float",
"alpha",
")",
"{",
"pressText",
"(",
"re... | 给图片添加文字水印
@param imageFile 源图像文件
@param destFile 目标图像文件
@param pressText 水印文字
@param color 水印的字体颜色
@param font {@link Font} 字体相关信息,如果默认则为{@code null}
@param x 修正值。 默认在中间,偏移量相对于中间偏移
@param y 修正值。 默认在中间,偏移量相对于中间偏移
@param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 | [
"给图片添加文字水印"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L754-L756 |
Azure/azure-sdk-for-java | resources/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/resources/v2016_09_01/implementation/ResourceGroupsInner.java | ResourceGroupsInner.exportTemplate | public ResourceGroupExportResultInner exportTemplate(String resourceGroupName, ExportTemplateRequest parameters) {
"""
Captures the specified resource group as a template.
@param resourceGroupName The name of the resource group to export as a template.
@param parameters Parameters for exporting the template.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ResourceGroupExportResultInner object if successful.
"""
return exportTemplateWithServiceResponseAsync(resourceGroupName, parameters).toBlocking().single().body();
} | java | public ResourceGroupExportResultInner exportTemplate(String resourceGroupName, ExportTemplateRequest parameters) {
return exportTemplateWithServiceResponseAsync(resourceGroupName, parameters).toBlocking().single().body();
} | [
"public",
"ResourceGroupExportResultInner",
"exportTemplate",
"(",
"String",
"resourceGroupName",
",",
"ExportTemplateRequest",
"parameters",
")",
"{",
"return",
"exportTemplateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"parameters",
")",
".",
"toBlocking",
"("... | Captures the specified resource group as a template.
@param resourceGroupName The name of the resource group to export as a template.
@param parameters Parameters for exporting the template.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ResourceGroupExportResultInner object if successful. | [
"Captures",
"the",
"specified",
"resource",
"group",
"as",
"a",
"template",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/resources/v2016_09_01/implementation/ResourceGroupsInner.java#L851-L853 |
Alluxio/alluxio | job/server/src/main/java/alluxio/worker/job/task/TaskExecutorManager.java | TaskExecutorManager.cancelTask | public synchronized void cancelTask(long jobId, int taskId) {
"""
Cancels the given task.
@param jobId the job id
@param taskId the task id
"""
Pair<Long, Integer> id = new Pair<>(jobId, taskId);
TaskInfo.Builder taskInfo = mUnfinishedTasks.get(id);
if (!mTaskFutures.containsKey(id) || taskInfo.getStatus().equals(Status.CANCELED)) {
// job has finished, or failed, or canceled
return;
}
Future<?> future = mTaskFutures.get(id);
if (!future.cancel(true)) {
taskInfo.setStatus(Status.FAILED);
taskInfo.setErrorMessage("Failed to cancel the task");
finishTask(id);
}
} | java | public synchronized void cancelTask(long jobId, int taskId) {
Pair<Long, Integer> id = new Pair<>(jobId, taskId);
TaskInfo.Builder taskInfo = mUnfinishedTasks.get(id);
if (!mTaskFutures.containsKey(id) || taskInfo.getStatus().equals(Status.CANCELED)) {
// job has finished, or failed, or canceled
return;
}
Future<?> future = mTaskFutures.get(id);
if (!future.cancel(true)) {
taskInfo.setStatus(Status.FAILED);
taskInfo.setErrorMessage("Failed to cancel the task");
finishTask(id);
}
} | [
"public",
"synchronized",
"void",
"cancelTask",
"(",
"long",
"jobId",
",",
"int",
"taskId",
")",
"{",
"Pair",
"<",
"Long",
",",
"Integer",
">",
"id",
"=",
"new",
"Pair",
"<>",
"(",
"jobId",
",",
"taskId",
")",
";",
"TaskInfo",
".",
"Builder",
"taskInfo... | Cancels the given task.
@param jobId the job id
@param taskId the task id | [
"Cancels",
"the",
"given",
"task",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/worker/job/task/TaskExecutorManager.java#L149-L163 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java | JobExecutionsInner.beginCreate | public JobExecutionInner beginCreate(String resourceGroupName, String serverName, String jobAgentName, String jobName) {
"""
Starts an elastic job execution.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param jobAgentName The name of the job agent.
@param jobName The name of the job to get.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the JobExecutionInner object if successful.
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName).toBlocking().single().body();
} | java | public JobExecutionInner beginCreate(String resourceGroupName, String serverName, String jobAgentName, String jobName) {
return beginCreateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName).toBlocking().single().body();
} | [
"public",
"JobExecutionInner",
"beginCreate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"jobAgentName",
",",
"String",
"jobName",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
... | Starts an elastic job execution.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param jobAgentName The name of the job agent.
@param jobName The name of the job to get.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the JobExecutionInner object if successful. | [
"Starts",
"an",
"elastic",
"job",
"execution",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java#L604-L606 |
line/armeria | core/src/main/java/com/linecorp/armeria/client/Clients.java | Clients.newDerivedClient | public static <T> T newDerivedClient(
T client, Function<? super ClientOptions, ClientOptions> configurator) {
"""
Creates a new derived client that connects to the same {@link URI} with the specified {@code client}
but with different {@link ClientOption}s. For example:
<pre>{@code
HttpClient derivedHttpClient = Clients.newDerivedClient(httpClient, options -> {
ClientOptionsBuilder builder = new ClientOptionsBuilder(options);
builder.decorator(...); // Add a decorator.
builder.addHttpHeader(...); // Add an HTTP header.
return builder.build();
});
}</pre>
@param configurator a {@link Function} whose input is the original {@link ClientOptions} of the client
being derived from and whose output is the {@link ClientOptions} of the new derived
client
@see ClientBuilder ClientBuilder, for more information about how the base options and
additional options are merged when a derived client is created.
@see ClientOptionsBuilder
"""
final ClientBuilderParams params = builderParams(client);
final ClientBuilder builder = new ClientBuilder(params.uri());
builder.factory(params.factory());
builder.options(configurator.apply(params.options()));
return newDerivedClient(builder, params.clientType());
} | java | public static <T> T newDerivedClient(
T client, Function<? super ClientOptions, ClientOptions> configurator) {
final ClientBuilderParams params = builderParams(client);
final ClientBuilder builder = new ClientBuilder(params.uri());
builder.factory(params.factory());
builder.options(configurator.apply(params.options()));
return newDerivedClient(builder, params.clientType());
} | [
"public",
"static",
"<",
"T",
">",
"T",
"newDerivedClient",
"(",
"T",
"client",
",",
"Function",
"<",
"?",
"super",
"ClientOptions",
",",
"ClientOptions",
">",
"configurator",
")",
"{",
"final",
"ClientBuilderParams",
"params",
"=",
"builderParams",
"(",
"clie... | Creates a new derived client that connects to the same {@link URI} with the specified {@code client}
but with different {@link ClientOption}s. For example:
<pre>{@code
HttpClient derivedHttpClient = Clients.newDerivedClient(httpClient, options -> {
ClientOptionsBuilder builder = new ClientOptionsBuilder(options);
builder.decorator(...); // Add a decorator.
builder.addHttpHeader(...); // Add an HTTP header.
return builder.build();
});
}</pre>
@param configurator a {@link Function} whose input is the original {@link ClientOptions} of the client
being derived from and whose output is the {@link ClientOptions} of the new derived
client
@see ClientBuilder ClientBuilder, for more information about how the base options and
additional options are merged when a derived client is created.
@see ClientOptionsBuilder | [
"Creates",
"a",
"new",
"derived",
"client",
"that",
"connects",
"to",
"the",
"same",
"{",
"@link",
"URI",
"}",
"with",
"the",
"specified",
"{",
"@code",
"client",
"}",
"but",
"with",
"different",
"{",
"@link",
"ClientOption",
"}",
"s",
".",
"For",
"examp... | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/Clients.java#L220-L228 |
google/closure-compiler | src/com/google/javascript/rhino/jstype/JSTypeRegistry.java | JSTypeRegistry.createParameters | private Node createParameters(boolean lastVarArgs, JSType... parameterTypes) {
"""
Creates a tree hierarchy representing a typed argument list.
@param lastVarArgs whether the last type should considered as a variable length argument.
@param parameterTypes the parameter types. The last element of this array is considered a
variable length argument is {@code lastVarArgs} is {@code true}.
@return a tree hierarchy representing a typed argument list
"""
FunctionParamBuilder builder = new FunctionParamBuilder(this);
int max = parameterTypes.length - 1;
for (int i = 0; i <= max; i++) {
if (lastVarArgs && i == max) {
builder.addVarArgs(parameterTypes[i]);
} else {
builder.addRequiredParams(parameterTypes[i]);
}
}
return builder.build();
} | java | private Node createParameters(boolean lastVarArgs, JSType... parameterTypes) {
FunctionParamBuilder builder = new FunctionParamBuilder(this);
int max = parameterTypes.length - 1;
for (int i = 0; i <= max; i++) {
if (lastVarArgs && i == max) {
builder.addVarArgs(parameterTypes[i]);
} else {
builder.addRequiredParams(parameterTypes[i]);
}
}
return builder.build();
} | [
"private",
"Node",
"createParameters",
"(",
"boolean",
"lastVarArgs",
",",
"JSType",
"...",
"parameterTypes",
")",
"{",
"FunctionParamBuilder",
"builder",
"=",
"new",
"FunctionParamBuilder",
"(",
"this",
")",
";",
"int",
"max",
"=",
"parameterTypes",
".",
"length"... | Creates a tree hierarchy representing a typed argument list.
@param lastVarArgs whether the last type should considered as a variable length argument.
@param parameterTypes the parameter types. The last element of this array is considered a
variable length argument is {@code lastVarArgs} is {@code true}.
@return a tree hierarchy representing a typed argument list | [
"Creates",
"a",
"tree",
"hierarchy",
"representing",
"a",
"typed",
"argument",
"list",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1665-L1676 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/ScrollableDataTableModelExample.java | ScrollableDataTableModelExample.createTable | private WDataTable createTable() {
"""
Creates and configures the table to be used by the example. The table is configured with global rather than user
data. Although this is not a realistic scenario, it will suffice for this example.
@return a new configured table.
"""
WDataTable table = new WDataTable();
table.addColumn(new WTableColumn("First name", WText.class));
table.addColumn(new WTableColumn("Last name", WText.class));
table.addColumn(new WTableColumn("DOB", WText.class));
table.setPaginationMode(PaginationMode.DYNAMIC);
table.setRowsPerPage(1);
table.setDataModel(createTableModel());
return table;
} | java | private WDataTable createTable() {
WDataTable table = new WDataTable();
table.addColumn(new WTableColumn("First name", WText.class));
table.addColumn(new WTableColumn("Last name", WText.class));
table.addColumn(new WTableColumn("DOB", WText.class));
table.setPaginationMode(PaginationMode.DYNAMIC);
table.setRowsPerPage(1);
table.setDataModel(createTableModel());
return table;
} | [
"private",
"WDataTable",
"createTable",
"(",
")",
"{",
"WDataTable",
"table",
"=",
"new",
"WDataTable",
"(",
")",
";",
"table",
".",
"addColumn",
"(",
"new",
"WTableColumn",
"(",
"\"First name\"",
",",
"WText",
".",
"class",
")",
")",
";",
"table",
".",
... | Creates and configures the table to be used by the example. The table is configured with global rather than user
data. Although this is not a realistic scenario, it will suffice for this example.
@return a new configured table. | [
"Creates",
"and",
"configures",
"the",
"table",
"to",
"be",
"used",
"by",
"the",
"example",
".",
"The",
"table",
"is",
"configured",
"with",
"global",
"rather",
"than",
"user",
"data",
".",
"Although",
"this",
"is",
"not",
"a",
"realistic",
"scenario",
"it... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/ScrollableDataTableModelExample.java#L40-L51 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/random/RandomFloat.java | RandomFloat.updateFloat | public static float updateFloat(float value, float range) {
"""
Updates (drifts) a float value within specified range defined
@param value a float value to drift.
@param range (optional) a range. Default: 10% of the value
@return updated random float value.
"""
range = range == 0 ? (float) (0.1 * value) : range;
float min = value - range;
float max = value + range;
return nextFloat(min, max);
} | java | public static float updateFloat(float value, float range) {
range = range == 0 ? (float) (0.1 * value) : range;
float min = value - range;
float max = value + range;
return nextFloat(min, max);
} | [
"public",
"static",
"float",
"updateFloat",
"(",
"float",
"value",
",",
"float",
"range",
")",
"{",
"range",
"=",
"range",
"==",
"0",
"?",
"(",
"float",
")",
"(",
"0.1",
"*",
"value",
")",
":",
"range",
";",
"float",
"min",
"=",
"value",
"-",
"rang... | Updates (drifts) a float value within specified range defined
@param value a float value to drift.
@param range (optional) a range. Default: 10% of the value
@return updated random float value. | [
"Updates",
"(",
"drifts",
")",
"a",
"float",
"value",
"within",
"specified",
"range",
"defined"
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/random/RandomFloat.java#L59-L64 |
stevespringett/Alpine | alpine/src/main/java/alpine/persistence/AlpineQueryManager.java | AlpineQueryManager.createTeam | public Team createTeam(final String name, final boolean createApiKey) {
"""
Creates a new Team with the specified name. If createApiKey is true,
then {@link #createApiKey} is invoked and a cryptographically secure
API key is generated.
@param name The name of th team
@param createApiKey whether or not to create an API key for the team
@return a Team
@since 1.0.0
"""
pm.currentTransaction().begin();
final Team team = new Team();
team.setName(name);
//todo assign permissions
pm.makePersistent(team);
pm.currentTransaction().commit();
if (createApiKey) {
createApiKey(team);
}
return getObjectByUuid(Team.class, team.getUuid(), Team.FetchGroup.ALL.name());
} | java | public Team createTeam(final String name, final boolean createApiKey) {
pm.currentTransaction().begin();
final Team team = new Team();
team.setName(name);
//todo assign permissions
pm.makePersistent(team);
pm.currentTransaction().commit();
if (createApiKey) {
createApiKey(team);
}
return getObjectByUuid(Team.class, team.getUuid(), Team.FetchGroup.ALL.name());
} | [
"public",
"Team",
"createTeam",
"(",
"final",
"String",
"name",
",",
"final",
"boolean",
"createApiKey",
")",
"{",
"pm",
".",
"currentTransaction",
"(",
")",
".",
"begin",
"(",
")",
";",
"final",
"Team",
"team",
"=",
"new",
"Team",
"(",
")",
";",
"team... | Creates a new Team with the specified name. If createApiKey is true,
then {@link #createApiKey} is invoked and a cryptographically secure
API key is generated.
@param name The name of th team
@param createApiKey whether or not to create an API key for the team
@return a Team
@since 1.0.0 | [
"Creates",
"a",
"new",
"Team",
"with",
"the",
"specified",
"name",
".",
"If",
"createApiKey",
"is",
"true",
"then",
"{"
] | train | https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AlpineQueryManager.java#L343-L354 |
cdapio/tigon | tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java | Bytes.putInt | public static int putInt(byte[] bytes, int offset, int val) {
"""
Put an int value out to the specified byte array position.
@param bytes the byte array
@param offset position in the array
@param val int to write out
@return incremented offset
@throws IllegalArgumentException if the byte array given doesn't have
enough room at the offset specified.
"""
if (bytes.length - offset < SIZEOF_INT) {
throw new IllegalArgumentException("Not enough room to put an int at"
+ " offset " + offset + " in a " + bytes.length + " byte array");
}
for (int i = offset + 3; i > offset; i--) {
bytes[i] = (byte) val;
val >>>= 8;
}
bytes[offset] = (byte) val;
return offset + SIZEOF_INT;
} | java | public static int putInt(byte[] bytes, int offset, int val) {
if (bytes.length - offset < SIZEOF_INT) {
throw new IllegalArgumentException("Not enough room to put an int at"
+ " offset " + offset + " in a " + bytes.length + " byte array");
}
for (int i = offset + 3; i > offset; i--) {
bytes[i] = (byte) val;
val >>>= 8;
}
bytes[offset] = (byte) val;
return offset + SIZEOF_INT;
} | [
"public",
"static",
"int",
"putInt",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
",",
"int",
"val",
")",
"{",
"if",
"(",
"bytes",
".",
"length",
"-",
"offset",
"<",
"SIZEOF_INT",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"N... | Put an int value out to the specified byte array position.
@param bytes the byte array
@param offset position in the array
@param val int to write out
@return incremented offset
@throws IllegalArgumentException if the byte array given doesn't have
enough room at the offset specified. | [
"Put",
"an",
"int",
"value",
"out",
"to",
"the",
"specified",
"byte",
"array",
"position",
"."
] | train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L588-L599 |
davetcc/tcMenu | tcMenuJavaApi/src/main/java/com/thecoderscorner/menu/remote/protocol/TagValTextParser.java | TagValTextParser.getValueAsIntWithDefault | public int getValueAsIntWithDefault(String keyIdField, int defaultVal) throws IOException {
"""
Calls the getValue method first and the converts to an integer.
@param keyIdField the key to obtain
@return the integer value associated
"""
if(keyToValue.containsKey(keyIdField)) {
return Integer.parseInt(getValue(keyIdField));
}
else return defaultVal;
} | java | public int getValueAsIntWithDefault(String keyIdField, int defaultVal) throws IOException {
if(keyToValue.containsKey(keyIdField)) {
return Integer.parseInt(getValue(keyIdField));
}
else return defaultVal;
} | [
"public",
"int",
"getValueAsIntWithDefault",
"(",
"String",
"keyIdField",
",",
"int",
"defaultVal",
")",
"throws",
"IOException",
"{",
"if",
"(",
"keyToValue",
".",
"containsKey",
"(",
"keyIdField",
")",
")",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"ge... | Calls the getValue method first and the converts to an integer.
@param keyIdField the key to obtain
@return the integer value associated | [
"Calls",
"the",
"getValue",
"method",
"first",
"and",
"the",
"converts",
"to",
"an",
"integer",
"."
] | train | https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuJavaApi/src/main/java/com/thecoderscorner/menu/remote/protocol/TagValTextParser.java#L110-L115 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/grid/Grid.java | Grid.getCellBounds | @Pure
public Rectangle2d getCellBounds(int row, int column) {
"""
Replies the bounds covered by a cell at the specified location.
@param row the row index.
@param column the column index.
@return the bounds.
"""
final double cellWidth = getCellWidth();
final double cellHeight = getCellHeight();
final double x = this.bounds.getMinX() + cellWidth * column;
final double y = this.bounds.getMinY() + cellHeight * row;
return new Rectangle2d(x, y, cellWidth, cellHeight);
} | java | @Pure
public Rectangle2d getCellBounds(int row, int column) {
final double cellWidth = getCellWidth();
final double cellHeight = getCellHeight();
final double x = this.bounds.getMinX() + cellWidth * column;
final double y = this.bounds.getMinY() + cellHeight * row;
return new Rectangle2d(x, y, cellWidth, cellHeight);
} | [
"@",
"Pure",
"public",
"Rectangle2d",
"getCellBounds",
"(",
"int",
"row",
",",
"int",
"column",
")",
"{",
"final",
"double",
"cellWidth",
"=",
"getCellWidth",
"(",
")",
";",
"final",
"double",
"cellHeight",
"=",
"getCellHeight",
"(",
")",
";",
"final",
"do... | Replies the bounds covered by a cell at the specified location.
@param row the row index.
@param column the column index.
@return the bounds. | [
"Replies",
"the",
"bounds",
"covered",
"by",
"a",
"cell",
"at",
"the",
"specified",
"location",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/grid/Grid.java#L152-L159 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsUserDriver.java | CmsUserDriver.internalCreateUser | protected CmsUser internalCreateUser(CmsDbContext dbc, ResultSet res) throws SQLException {
"""
Semi-constructor to create a {@link CmsUser} instance from a JDBC result set.<p>
@param dbc the current database context
@param res the JDBC ResultSet
@return the new CmsUser object
@throws SQLException in case the result set does not include a requested table attribute
"""
String userName = res.getString(m_sqlManager.readQuery("C_USERS_USER_NAME_0"));
String ou = CmsOrganizationalUnit.removeLeadingSeparator(
res.getString(m_sqlManager.readQuery("C_USERS_USER_OU_0")));
CmsUUID userId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_USERS_USER_ID_0")));
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_DBG_CREATE_USER_1, userName));
}
return new CmsUser(
userId,
ou + userName,
res.getString(m_sqlManager.readQuery("C_USERS_USER_PASSWORD_0")),
res.getString(m_sqlManager.readQuery("C_USERS_USER_FIRSTNAME_0")),
res.getString(m_sqlManager.readQuery("C_USERS_USER_LASTNAME_0")),
res.getString(m_sqlManager.readQuery("C_USERS_USER_EMAIL_0")),
res.getLong(m_sqlManager.readQuery("C_USERS_USER_LASTLOGIN_0")),
res.getInt(m_sqlManager.readQuery("C_USERS_USER_FLAGS_0")),
res.getLong(m_sqlManager.readQuery("C_USERS_USER_DATECREATED_0")),
null);
} | java | protected CmsUser internalCreateUser(CmsDbContext dbc, ResultSet res) throws SQLException {
String userName = res.getString(m_sqlManager.readQuery("C_USERS_USER_NAME_0"));
String ou = CmsOrganizationalUnit.removeLeadingSeparator(
res.getString(m_sqlManager.readQuery("C_USERS_USER_OU_0")));
CmsUUID userId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_USERS_USER_ID_0")));
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_DBG_CREATE_USER_1, userName));
}
return new CmsUser(
userId,
ou + userName,
res.getString(m_sqlManager.readQuery("C_USERS_USER_PASSWORD_0")),
res.getString(m_sqlManager.readQuery("C_USERS_USER_FIRSTNAME_0")),
res.getString(m_sqlManager.readQuery("C_USERS_USER_LASTNAME_0")),
res.getString(m_sqlManager.readQuery("C_USERS_USER_EMAIL_0")),
res.getLong(m_sqlManager.readQuery("C_USERS_USER_LASTLOGIN_0")),
res.getInt(m_sqlManager.readQuery("C_USERS_USER_FLAGS_0")),
res.getLong(m_sqlManager.readQuery("C_USERS_USER_DATECREATED_0")),
null);
} | [
"protected",
"CmsUser",
"internalCreateUser",
"(",
"CmsDbContext",
"dbc",
",",
"ResultSet",
"res",
")",
"throws",
"SQLException",
"{",
"String",
"userName",
"=",
"res",
".",
"getString",
"(",
"m_sqlManager",
".",
"readQuery",
"(",
"\"C_USERS_USER_NAME_0\"",
")",
"... | Semi-constructor to create a {@link CmsUser} instance from a JDBC result set.<p>
@param dbc the current database context
@param res the JDBC ResultSet
@return the new CmsUser object
@throws SQLException in case the result set does not include a requested table attribute | [
"Semi",
"-",
"constructor",
"to",
"create",
"a",
"{",
"@link",
"CmsUser",
"}",
"instance",
"from",
"a",
"JDBC",
"result",
"set",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2507-L2529 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/Utils4J.java | Utils4J.pathsFiles | public static List<File> pathsFiles(final String paths, final Predicate<File> predicate) {
"""
Returns a list of files from all given paths.
@param paths
Paths to search (Paths separated by {@link File#pathSeparator}.
@param predicate
Condition for files to return.
@return List of files in the given paths.
"""
final List<File> files = new ArrayList<File>();
for (final String filePathAndName : paths.split(File.pathSeparator)) {
final File file = new File(filePathAndName);
if (file.isDirectory()) {
try (final Stream<Path> stream = Files.walk(file.toPath(), Integer.MAX_VALUE)) {
stream.map(f -> f.toFile()).filter(predicate).forEach(files::add);
} catch (final IOException ex) {
throw new RuntimeException("Error walking path: " + file, ex);
}
} else {
if (predicate.test(file)) {
files.add(file);
}
}
}
return files;
} | java | public static List<File> pathsFiles(final String paths, final Predicate<File> predicate) {
final List<File> files = new ArrayList<File>();
for (final String filePathAndName : paths.split(File.pathSeparator)) {
final File file = new File(filePathAndName);
if (file.isDirectory()) {
try (final Stream<Path> stream = Files.walk(file.toPath(), Integer.MAX_VALUE)) {
stream.map(f -> f.toFile()).filter(predicate).forEach(files::add);
} catch (final IOException ex) {
throw new RuntimeException("Error walking path: " + file, ex);
}
} else {
if (predicate.test(file)) {
files.add(file);
}
}
}
return files;
} | [
"public",
"static",
"List",
"<",
"File",
">",
"pathsFiles",
"(",
"final",
"String",
"paths",
",",
"final",
"Predicate",
"<",
"File",
">",
"predicate",
")",
"{",
"final",
"List",
"<",
"File",
">",
"files",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",... | Returns a list of files from all given paths.
@param paths
Paths to search (Paths separated by {@link File#pathSeparator}.
@param predicate
Condition for files to return.
@return List of files in the given paths. | [
"Returns",
"a",
"list",
"of",
"files",
"from",
"all",
"given",
"paths",
"."
] | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L1705-L1722 |
forge/furnace | manager/impl/src/main/java/org/jboss/forge/furnace/manager/impl/AddonManagerImpl.java | AddonManagerImpl.collectRequiredAddons | private void collectRequiredAddons(AddonInfo addonInfo, List<AddonInfo> addons) {
"""
Collect all required addons for a specific addon.
It traverses the whole graph
@param addonInfo
@param addons
"""
// Move this addon to the top of the list
addons.remove(addonInfo);
addons.add(0, addonInfo);
for (AddonId addonId : addonInfo.getRequiredAddons())
{
if (!addons.contains(addonId) && (!isDeployed(addonId) || !isEnabled(addonId)))
{
AddonInfo childInfo = info(addonId);
collectRequiredAddons(childInfo, addons);
}
}
} | java | private void collectRequiredAddons(AddonInfo addonInfo, List<AddonInfo> addons)
{
// Move this addon to the top of the list
addons.remove(addonInfo);
addons.add(0, addonInfo);
for (AddonId addonId : addonInfo.getRequiredAddons())
{
if (!addons.contains(addonId) && (!isDeployed(addonId) || !isEnabled(addonId)))
{
AddonInfo childInfo = info(addonId);
collectRequiredAddons(childInfo, addons);
}
}
} | [
"private",
"void",
"collectRequiredAddons",
"(",
"AddonInfo",
"addonInfo",
",",
"List",
"<",
"AddonInfo",
">",
"addons",
")",
"{",
"// Move this addon to the top of the list",
"addons",
".",
"remove",
"(",
"addonInfo",
")",
";",
"addons",
".",
"add",
"(",
"0",
"... | Collect all required addons for a specific addon.
It traverses the whole graph
@param addonInfo
@param addons | [
"Collect",
"all",
"required",
"addons",
"for",
"a",
"specific",
"addon",
"."
] | train | https://github.com/forge/furnace/blob/bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a/manager/impl/src/main/java/org/jboss/forge/furnace/manager/impl/AddonManagerImpl.java#L256-L269 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java | SqlDateTimeUtils.parseToTimeMillis | private static long parseToTimeMillis(String dateStr, TimeZone tz) {
"""
Parses a given datetime string to milli seconds since 1970-01-01 00:00:00 UTC
using the default format "yyyy-MM-dd" or "yyyy-MM-dd HH:mm:ss" depends on the string length.
"""
String format;
if (dateStr.length() <= 10) {
format = DATE_FORMAT_STRING;
} else {
format = TIMESTAMP_FORMAT_STRING;
}
return parseToTimeMillis(dateStr, format, tz) + getMillis(dateStr);
} | java | private static long parseToTimeMillis(String dateStr, TimeZone tz) {
String format;
if (dateStr.length() <= 10) {
format = DATE_FORMAT_STRING;
} else {
format = TIMESTAMP_FORMAT_STRING;
}
return parseToTimeMillis(dateStr, format, tz) + getMillis(dateStr);
} | [
"private",
"static",
"long",
"parseToTimeMillis",
"(",
"String",
"dateStr",
",",
"TimeZone",
"tz",
")",
"{",
"String",
"format",
";",
"if",
"(",
"dateStr",
".",
"length",
"(",
")",
"<=",
"10",
")",
"{",
"format",
"=",
"DATE_FORMAT_STRING",
";",
"}",
"els... | Parses a given datetime string to milli seconds since 1970-01-01 00:00:00 UTC
using the default format "yyyy-MM-dd" or "yyyy-MM-dd HH:mm:ss" depends on the string length. | [
"Parses",
"a",
"given",
"datetime",
"string",
"to",
"milli",
"seconds",
"since",
"1970",
"-",
"01",
"-",
"01",
"00",
":",
"00",
":",
"00",
"UTC",
"using",
"the",
"default",
"format",
"yyyy",
"-",
"MM",
"-",
"dd",
"or",
"yyyy",
"-",
"MM",
"-",
"dd",... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java#L449-L457 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java | DistributionBeanQuery.loadBeans | @Override
protected List<ProxyDistribution> loadBeans(final int startIndex, final int count) {
"""
Load all the Distribution set.
@param startIndex
as page start
@param count
as total data
"""
Page<DistributionSet> distBeans;
final List<ProxyDistribution> proxyDistributions = new ArrayList<>();
if (startIndex == 0 && firstPageDistributionSets != null) {
distBeans = firstPageDistributionSets;
} else if (pinnedTarget != null) {
final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder()
.setIsDeleted(false).setIsComplete(true).setSearchText(searchText)
.setSelectDSWithNoTag(noTagClicked).setTagNames(distributionTags);
distBeans = getDistributionSetManagement().findByFilterAndAssignedInstalledDsOrderedByLinkTarget(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilterBuilder,
pinnedTarget.getControllerId());
} else if (distributionTags.isEmpty() && StringUtils.isEmpty(searchText) && !noTagClicked) {
// if no search filters available
distBeans = getDistributionSetManagement()
.findByCompleted(new OffsetBasedPageRequest(startIndex, count, sort), true);
} else {
final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false)
.setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked)
.setTagNames(distributionTags).build();
distBeans = getDistributionSetManagement().findByDistributionSetFilter(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilter);
}
for (final DistributionSet distributionSet : distBeans) {
final ProxyDistribution proxyDistribution = new ProxyDistribution();
proxyDistribution.setName(distributionSet.getName());
proxyDistribution.setDescription(distributionSet.getDescription());
proxyDistribution.setId(distributionSet.getId());
proxyDistribution.setDistId(distributionSet.getId());
proxyDistribution.setVersion(distributionSet.getVersion());
proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt()));
proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt()));
proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet));
proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet));
proxyDistribution.setNameVersion(
HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion()));
proxyDistributions.add(proxyDistribution);
}
return proxyDistributions;
} | java | @Override
protected List<ProxyDistribution> loadBeans(final int startIndex, final int count) {
Page<DistributionSet> distBeans;
final List<ProxyDistribution> proxyDistributions = new ArrayList<>();
if (startIndex == 0 && firstPageDistributionSets != null) {
distBeans = firstPageDistributionSets;
} else if (pinnedTarget != null) {
final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder()
.setIsDeleted(false).setIsComplete(true).setSearchText(searchText)
.setSelectDSWithNoTag(noTagClicked).setTagNames(distributionTags);
distBeans = getDistributionSetManagement().findByFilterAndAssignedInstalledDsOrderedByLinkTarget(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilterBuilder,
pinnedTarget.getControllerId());
} else if (distributionTags.isEmpty() && StringUtils.isEmpty(searchText) && !noTagClicked) {
// if no search filters available
distBeans = getDistributionSetManagement()
.findByCompleted(new OffsetBasedPageRequest(startIndex, count, sort), true);
} else {
final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false)
.setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked)
.setTagNames(distributionTags).build();
distBeans = getDistributionSetManagement().findByDistributionSetFilter(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilter);
}
for (final DistributionSet distributionSet : distBeans) {
final ProxyDistribution proxyDistribution = new ProxyDistribution();
proxyDistribution.setName(distributionSet.getName());
proxyDistribution.setDescription(distributionSet.getDescription());
proxyDistribution.setId(distributionSet.getId());
proxyDistribution.setDistId(distributionSet.getId());
proxyDistribution.setVersion(distributionSet.getVersion());
proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt()));
proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt()));
proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet));
proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet));
proxyDistribution.setNameVersion(
HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion()));
proxyDistributions.add(proxyDistribution);
}
return proxyDistributions;
} | [
"@",
"Override",
"protected",
"List",
"<",
"ProxyDistribution",
">",
"loadBeans",
"(",
"final",
"int",
"startIndex",
",",
"final",
"int",
"count",
")",
"{",
"Page",
"<",
"DistributionSet",
">",
"distBeans",
";",
"final",
"List",
"<",
"ProxyDistribution",
">",
... | Load all the Distribution set.
@param startIndex
as page start
@param count
as total data | [
"Load",
"all",
"the",
"Distribution",
"set",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java#L97-L139 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/Expression.java | Expression.equalTo | @NonNull
public Expression equalTo(@NonNull Expression expression) {
"""
Create an equal to expression that evaluates whether or not the current expression
is equal to the given expression.
@param expression the expression to compare with the current expression.
@return an equal to expression.
"""
if (expression == null) {
throw new IllegalArgumentException("expression cannot be null.");
}
return new BinaryExpression(this, expression, BinaryExpression.OpType.EqualTo);
} | java | @NonNull
public Expression equalTo(@NonNull Expression expression) {
if (expression == null) {
throw new IllegalArgumentException("expression cannot be null.");
}
return new BinaryExpression(this, expression, BinaryExpression.OpType.EqualTo);
} | [
"@",
"NonNull",
"public",
"Expression",
"equalTo",
"(",
"@",
"NonNull",
"Expression",
"expression",
")",
"{",
"if",
"(",
"expression",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"expression cannot be null.\"",
")",
";",
"}",
"retu... | Create an equal to expression that evaluates whether or not the current expression
is equal to the given expression.
@param expression the expression to compare with the current expression.
@return an equal to expression. | [
"Create",
"an",
"equal",
"to",
"expression",
"that",
"evaluates",
"whether",
"or",
"not",
"the",
"current",
"expression",
"is",
"equal",
"to",
"the",
"given",
"expression",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/Expression.java#L675-L681 |
threerings/nenya | core/src/main/java/com/threerings/media/sprite/FadableImageSprite.java | FadableImageSprite.moveAndFadeOut | public void moveAndFadeOut (Path path, long pathDuration, float fadePortion) {
"""
Puts this sprite on the specified path and fades it out over the specified duration.
@param path the path to move along
@param pathDuration the duration of the path
@param fadePortion the portion of time to spend fading out, from 0.0f (no time) to 1.0f
(the entire time)
"""
move(path);
setAlpha(1.0f);
_fadeStamp = 0;
_pathDuration = pathDuration;
_fadeOutDuration = (long)(pathDuration * fadePortion);
_fadeDelay = _pathDuration - _fadeOutDuration;
} | java | public void moveAndFadeOut (Path path, long pathDuration, float fadePortion)
{
move(path);
setAlpha(1.0f);
_fadeStamp = 0;
_pathDuration = pathDuration;
_fadeOutDuration = (long)(pathDuration * fadePortion);
_fadeDelay = _pathDuration - _fadeOutDuration;
} | [
"public",
"void",
"moveAndFadeOut",
"(",
"Path",
"path",
",",
"long",
"pathDuration",
",",
"float",
"fadePortion",
")",
"{",
"move",
"(",
"path",
")",
";",
"setAlpha",
"(",
"1.0f",
")",
";",
"_fadeStamp",
"=",
"0",
";",
"_pathDuration",
"=",
"pathDuration"... | Puts this sprite on the specified path and fades it out over the specified duration.
@param path the path to move along
@param pathDuration the duration of the path
@param fadePortion the portion of time to spend fading out, from 0.0f (no time) to 1.0f
(the entire time) | [
"Puts",
"this",
"sprite",
"on",
"the",
"specified",
"path",
"and",
"fades",
"it",
"out",
"over",
"the",
"specified",
"duration",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/sprite/FadableImageSprite.java#L106-L116 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java | ResourceGroovyMethods.filterLine | public static Writable filterLine(File self, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
"""
Filters the lines of a File and creates a Writable in return to
stream the filtered lines.
@param self a File
@param closure a closure which returns a boolean indicating to filter
the line or not
@return a Writable closure
@throws IOException if <code>self</code> is not readable
@see IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure)
@since 1.0
"""
return IOGroovyMethods.filterLine(newReader(self), closure);
} | java | public static Writable filterLine(File self, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException {
return IOGroovyMethods.filterLine(newReader(self), closure);
} | [
"public",
"static",
"Writable",
"filterLine",
"(",
"File",
"self",
",",
"@",
"ClosureParams",
"(",
"value",
"=",
"SimpleType",
".",
"class",
",",
"options",
"=",
"\"java.lang.String\"",
")",
"Closure",
"closure",
")",
"throws",
"IOException",
"{",
"return",
"I... | Filters the lines of a File and creates a Writable in return to
stream the filtered lines.
@param self a File
@param closure a closure which returns a boolean indicating to filter
the line or not
@return a Writable closure
@throws IOException if <code>self</code> is not readable
@see IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure)
@since 1.0 | [
"Filters",
"the",
"lines",
"of",
"a",
"File",
"and",
"creates",
"a",
"Writable",
"in",
"return",
"to",
"stream",
"the",
"filtered",
"lines",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L2371-L2373 |
kiegroup/drools | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java | EvalHelper.getGenericAccessor | public static Method getGenericAccessor(Class<?> clazz, String field) {
"""
FEEL annotated or else Java accessor.
@param clazz
@param field
@return
"""
LOG.trace( "getGenericAccessor({}, {})", clazz, field );
String accessorQualifiedName = new StringBuilder(clazz.getCanonicalName())
.append(".").append(field).toString();
return accessorCache.computeIfAbsent(accessorQualifiedName, key ->
Stream.of( clazz.getMethods() )
.filter( m -> Optional.ofNullable( m.getAnnotation( FEELProperty.class ) )
.map( ann -> ann.value().equals( field ) )
.orElse( false )
)
.findFirst()
.orElse( getAccessor( clazz, field ) ));
} | java | public static Method getGenericAccessor(Class<?> clazz, String field) {
LOG.trace( "getGenericAccessor({}, {})", clazz, field );
String accessorQualifiedName = new StringBuilder(clazz.getCanonicalName())
.append(".").append(field).toString();
return accessorCache.computeIfAbsent(accessorQualifiedName, key ->
Stream.of( clazz.getMethods() )
.filter( m -> Optional.ofNullable( m.getAnnotation( FEELProperty.class ) )
.map( ann -> ann.value().equals( field ) )
.orElse( false )
)
.findFirst()
.orElse( getAccessor( clazz, field ) ));
} | [
"public",
"static",
"Method",
"getGenericAccessor",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"field",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"getGenericAccessor({}, {})\"",
",",
"clazz",
",",
"field",
")",
";",
"String",
"accessorQualifiedName",
"="... | FEEL annotated or else Java accessor.
@param clazz
@param field
@return | [
"FEEL",
"annotated",
"or",
"else",
"Java",
"accessor",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java#L408-L422 |
google/closure-templates | java/src/com/google/template/soy/data/SoyListData.java | SoyListData.putSingle | @Override
public void putSingle(String key, SoyData value) {
"""
Important: Do not use outside of Soy code (treat as superpackage-private).
<p>Puts data into this data object at the specified key.
@param key An individual key.
@param value The data to put at the specified key.
"""
set(Integer.parseInt(key), value);
} | java | @Override
public void putSingle(String key, SoyData value) {
set(Integer.parseInt(key), value);
} | [
"@",
"Override",
"public",
"void",
"putSingle",
"(",
"String",
"key",
",",
"SoyData",
"value",
")",
"{",
"set",
"(",
"Integer",
".",
"parseInt",
"(",
"key",
")",
",",
"value",
")",
";",
"}"
] | Important: Do not use outside of Soy code (treat as superpackage-private).
<p>Puts data into this data object at the specified key.
@param key An individual key.
@param value The data to put at the specified key. | [
"Important",
":",
"Do",
"not",
"use",
"outside",
"of",
"Soy",
"code",
"(",
"treat",
"as",
"superpackage",
"-",
"private",
")",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyListData.java#L399-L402 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/AbstractController.java | AbstractController.callCommand | protected Wave callCommand(final Class<? extends Command> commandClass, final WaveData<?>... data) {
"""
Redirect to {@link Model#callCommand(Class, WaveData...)}.
@param commandClass the command class to call
@param data the data to transport
@return the wave created and sent to JIT, be careful when you use a strong reference it can hold a lot of objects
"""
return model().callCommand(commandClass, data);
} | java | protected Wave callCommand(final Class<? extends Command> commandClass, final WaveData<?>... data) {
return model().callCommand(commandClass, data);
} | [
"protected",
"Wave",
"callCommand",
"(",
"final",
"Class",
"<",
"?",
"extends",
"Command",
">",
"commandClass",
",",
"final",
"WaveData",
"<",
"?",
">",
"...",
"data",
")",
"{",
"return",
"model",
"(",
")",
".",
"callCommand",
"(",
"commandClass",
",",
"... | Redirect to {@link Model#callCommand(Class, WaveData...)}.
@param commandClass the command class to call
@param data the data to transport
@return the wave created and sent to JIT, be careful when you use a strong reference it can hold a lot of objects | [
"Redirect",
"to",
"{",
"@link",
"Model#callCommand",
"(",
"Class",
"WaveData",
"...",
")",
"}",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/AbstractController.java#L268-L270 |
twilio/twilio-java | src/main/java/com/twilio/rest/monitor/v1/AlertReader.java | AlertReader.previousPage | @Override
public Page<Alert> previousPage(final Page<Alert> page,
final TwilioRestClient client) {
"""
Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page
"""
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.MONITOR.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<Alert> previousPage(final Page<Alert> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.MONITOR.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"Alert",
">",
"previousPage",
"(",
"final",
"Page",
"<",
"Alert",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
",",
... | Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page | [
"Retrieve",
"the",
"previous",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/monitor/v1/AlertReader.java#L147-L158 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.setCertificateIssuerAsync | public Observable<IssuerBundle> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider) {
"""
Sets the specified certificate issuer.
The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@param provider The issuer provider.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IssuerBundle object
"""
return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).map(new Func1<ServiceResponse<IssuerBundle>, IssuerBundle>() {
@Override
public IssuerBundle call(ServiceResponse<IssuerBundle> response) {
return response.body();
}
});
} | java | public Observable<IssuerBundle> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider) {
return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).map(new Func1<ServiceResponse<IssuerBundle>, IssuerBundle>() {
@Override
public IssuerBundle call(ServiceResponse<IssuerBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IssuerBundle",
">",
"setCertificateIssuerAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"issuerName",
",",
"String",
"provider",
")",
"{",
"return",
"setCertificateIssuerWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"issuerName"... | Sets the specified certificate issuer.
The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param issuerName The name of the issuer.
@param provider The issuer provider.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IssuerBundle object | [
"Sets",
"the",
"specified",
"certificate",
"issuer",
".",
"The",
"SetCertificateIssuer",
"operation",
"adds",
"or",
"updates",
"the",
"specified",
"certificate",
"issuer",
".",
"This",
"operation",
"requires",
"the",
"certificates",
"/",
"setissuers",
"permission",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5929-L5936 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.listCustomPrebuiltIntentsAsync | public Observable<List<IntentClassifier>> listCustomPrebuiltIntentsAsync(UUID appId, String versionId) {
"""
Gets custom prebuilt intents information of this application.
@param appId The application ID.
@param versionId The version ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<IntentClassifier> object
"""
return listCustomPrebuiltIntentsWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<List<IntentClassifier>>, List<IntentClassifier>>() {
@Override
public List<IntentClassifier> call(ServiceResponse<List<IntentClassifier>> response) {
return response.body();
}
});
} | java | public Observable<List<IntentClassifier>> listCustomPrebuiltIntentsAsync(UUID appId, String versionId) {
return listCustomPrebuiltIntentsWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<List<IntentClassifier>>, List<IntentClassifier>>() {
@Override
public List<IntentClassifier> call(ServiceResponse<List<IntentClassifier>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"IntentClassifier",
">",
">",
"listCustomPrebuiltIntentsAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
")",
"{",
"return",
"listCustomPrebuiltIntentsWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
")",
".... | Gets custom prebuilt intents information of this application.
@param appId The application ID.
@param versionId The version ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<IntentClassifier> object | [
"Gets",
"custom",
"prebuilt",
"intents",
"information",
"of",
"this",
"application",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L5829-L5836 |
apache/flink | flink-java/src/main/java/org/apache/flink/api/java/operators/join/JoinOperatorSetsBase.java | JoinOperatorSetsBase.where | public JoinOperatorSetsPredicateBase where(String... fields) {
"""
Continues a Join transformation.
<p>Defines the fields of the first join {@link DataSet} that should be used as grouping keys. Fields
are the names of member fields of the underlying type of the data set.
@param fields The fields of the first join DataSets that should be used as keys.
@return An incomplete Join transformation.
Call {@link org.apache.flink.api.java.operators.join.JoinOperatorSetsBase.JoinOperatorSetsPredicateBase#equalTo(int...)} or
{@link org.apache.flink.api.java.operators.join.JoinOperatorSetsBase.JoinOperatorSetsPredicateBase#equalTo(KeySelector)}
to continue the Join.
@see Tuple
@see DataSet
"""
return new JoinOperatorSetsPredicateBase(new Keys.ExpressionKeys<>(fields, input1.getType()));
} | java | public JoinOperatorSetsPredicateBase where(String... fields) {
return new JoinOperatorSetsPredicateBase(new Keys.ExpressionKeys<>(fields, input1.getType()));
} | [
"public",
"JoinOperatorSetsPredicateBase",
"where",
"(",
"String",
"...",
"fields",
")",
"{",
"return",
"new",
"JoinOperatorSetsPredicateBase",
"(",
"new",
"Keys",
".",
"ExpressionKeys",
"<>",
"(",
"fields",
",",
"input1",
".",
"getType",
"(",
")",
")",
")",
"... | Continues a Join transformation.
<p>Defines the fields of the first join {@link DataSet} that should be used as grouping keys. Fields
are the names of member fields of the underlying type of the data set.
@param fields The fields of the first join DataSets that should be used as keys.
@return An incomplete Join transformation.
Call {@link org.apache.flink.api.java.operators.join.JoinOperatorSetsBase.JoinOperatorSetsPredicateBase#equalTo(int...)} or
{@link org.apache.flink.api.java.operators.join.JoinOperatorSetsBase.JoinOperatorSetsPredicateBase#equalTo(KeySelector)}
to continue the Join.
@see Tuple
@see DataSet | [
"Continues",
"a",
"Join",
"transformation",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-java/src/main/java/org/apache/flink/api/java/operators/join/JoinOperatorSetsBase.java#L109-L111 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/SimpleFormatterImpl.java | SimpleFormatterImpl.formatAndAppend | public static StringBuilder formatAndAppend(
String compiledPattern, StringBuilder appendTo, int[] offsets, CharSequence... values) {
"""
Formats the given values, appending to the appendTo builder.
@param compiledPattern Compiled form of a pattern string.
@param appendTo Gets the formatted pattern and values appended.
@param offsets offsets[i] receives the offset of where
values[i] replaced pattern argument {i}.
Can be null, or can be shorter or longer than values.
If there is no {i} in the pattern, then offsets[i] is set to -1.
@param values The argument values.
An argument value must not be the same object as appendTo.
values.length must be at least getArgumentLimit().
Can be null if getArgumentLimit()==0.
@return appendTo
"""
int valuesLength = values != null ? values.length : 0;
if (valuesLength < getArgumentLimit(compiledPattern)) {
throw new IllegalArgumentException("Too few values.");
}
return format(compiledPattern, values, appendTo, null, true, offsets);
} | java | public static StringBuilder formatAndAppend(
String compiledPattern, StringBuilder appendTo, int[] offsets, CharSequence... values) {
int valuesLength = values != null ? values.length : 0;
if (valuesLength < getArgumentLimit(compiledPattern)) {
throw new IllegalArgumentException("Too few values.");
}
return format(compiledPattern, values, appendTo, null, true, offsets);
} | [
"public",
"static",
"StringBuilder",
"formatAndAppend",
"(",
"String",
"compiledPattern",
",",
"StringBuilder",
"appendTo",
",",
"int",
"[",
"]",
"offsets",
",",
"CharSequence",
"...",
"values",
")",
"{",
"int",
"valuesLength",
"=",
"values",
"!=",
"null",
"?",
... | Formats the given values, appending to the appendTo builder.
@param compiledPattern Compiled form of a pattern string.
@param appendTo Gets the formatted pattern and values appended.
@param offsets offsets[i] receives the offset of where
values[i] replaced pattern argument {i}.
Can be null, or can be shorter or longer than values.
If there is no {i} in the pattern, then offsets[i] is set to -1.
@param values The argument values.
An argument value must not be the same object as appendTo.
values.length must be at least getArgumentLimit().
Can be null if getArgumentLimit()==0.
@return appendTo | [
"Formats",
"the",
"given",
"values",
"appending",
"to",
"the",
"appendTo",
"builder",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/SimpleFormatterImpl.java#L227-L234 |
hal/elemento | core/src/main/java/org/jboss/gwt/elemento/core/Elements.java | Elements.lazyInsertAfter | public static void lazyInsertAfter(Element newElement, Element after) {
"""
Inserts the specified element into the parent of the after element if not already present. If parent already
contains child, this method does nothing.
"""
if (!after.parentNode.contains(newElement)) {
after.parentNode.insertBefore(newElement, after.nextSibling);
}
} | java | public static void lazyInsertAfter(Element newElement, Element after) {
if (!after.parentNode.contains(newElement)) {
after.parentNode.insertBefore(newElement, after.nextSibling);
}
} | [
"public",
"static",
"void",
"lazyInsertAfter",
"(",
"Element",
"newElement",
",",
"Element",
"after",
")",
"{",
"if",
"(",
"!",
"after",
".",
"parentNode",
".",
"contains",
"(",
"newElement",
")",
")",
"{",
"after",
".",
"parentNode",
".",
"insertBefore",
... | Inserts the specified element into the parent of the after element if not already present. If parent already
contains child, this method does nothing. | [
"Inserts",
"the",
"specified",
"element",
"into",
"the",
"parent",
"of",
"the",
"after",
"element",
"if",
"not",
"already",
"present",
".",
"If",
"parent",
"already",
"contains",
"child",
"this",
"method",
"does",
"nothing",
"."
] | train | https://github.com/hal/elemento/blob/26da2d5a1fe2ec55b779737dbaeda25a942eee61/core/src/main/java/org/jboss/gwt/elemento/core/Elements.java#L663-L667 |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/protocol/BinaryConfigResponse.java | BinaryConfigResponse.createNotMyVbucket | public static BinaryResponse createNotMyVbucket(BinaryCommand command, MemcachedServer server) {
"""
Creates a response for {@code NOT_MY_VBUCKET} conditions
@param command The command which attempted to access the wrong vbucket
@param server The bucket which we own
@return A command of status {@code NOT_MY_VBUCKET}. This will contain
a config payload, if supported
"""
return create(command, server, ErrorCode.NOT_MY_VBUCKET, ErrorCode.NOT_MY_VBUCKET);
} | java | public static BinaryResponse createNotMyVbucket(BinaryCommand command, MemcachedServer server) {
return create(command, server, ErrorCode.NOT_MY_VBUCKET, ErrorCode.NOT_MY_VBUCKET);
} | [
"public",
"static",
"BinaryResponse",
"createNotMyVbucket",
"(",
"BinaryCommand",
"command",
",",
"MemcachedServer",
"server",
")",
"{",
"return",
"create",
"(",
"command",
",",
"server",
",",
"ErrorCode",
".",
"NOT_MY_VBUCKET",
",",
"ErrorCode",
".",
"NOT_MY_VBUCKE... | Creates a response for {@code NOT_MY_VBUCKET} conditions
@param command The command which attempted to access the wrong vbucket
@param server The bucket which we own
@return A command of status {@code NOT_MY_VBUCKET}. This will contain
a config payload, if supported | [
"Creates",
"a",
"response",
"for",
"{"
] | train | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/protocol/BinaryConfigResponse.java#L79-L81 |
gallandarakhneorg/afc | advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributeCollection.java | DBaseFileAttributeCollection.fireAttributeRenamedEvent | protected void fireAttributeRenamedEvent(String oldName, String newName, AttributeValue attr) {
"""
Fire the renaming event.
@param oldName is the previous name of the attribute (before renaming)
@param newName is the new name of the attribute (after renaming)
@param attr is the value of the attribute.
"""
if (this.listeners != null && isEventFirable()) {
final AttributeChangeEvent event = new AttributeChangeEvent(
//source
this,
//type
Type.RENAME,
//old name
oldName,
//old value
attr,
//current name
newName,
//current value
attr);
for (final AttributeChangeListener listener : this.listeners) {
listener.onAttributeChangeEvent(event);
}
}
} | java | protected void fireAttributeRenamedEvent(String oldName, String newName, AttributeValue attr) {
if (this.listeners != null && isEventFirable()) {
final AttributeChangeEvent event = new AttributeChangeEvent(
//source
this,
//type
Type.RENAME,
//old name
oldName,
//old value
attr,
//current name
newName,
//current value
attr);
for (final AttributeChangeListener listener : this.listeners) {
listener.onAttributeChangeEvent(event);
}
}
} | [
"protected",
"void",
"fireAttributeRenamedEvent",
"(",
"String",
"oldName",
",",
"String",
"newName",
",",
"AttributeValue",
"attr",
")",
"{",
"if",
"(",
"this",
".",
"listeners",
"!=",
"null",
"&&",
"isEventFirable",
"(",
")",
")",
"{",
"final",
"AttributeCha... | Fire the renaming event.
@param oldName is the previous name of the attribute (before renaming)
@param newName is the new name of the attribute (after renaming)
@param attr is the value of the attribute. | [
"Fire",
"the",
"renaming",
"event",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributeCollection.java#L963-L982 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/beans/PropertyChangeSupport.java | PropertyChangeSupport.firePropertyChange | public void firePropertyChange(String propertyName, int oldValue, int newValue) {
"""
Reports an integer bound property update to listeners
that have been registered to track updates of
all properties or a property with the specified name.
<p>
No event is fired if old and new values are equal.
<p>
This is merely a convenience wrapper around the more general
{@link #firePropertyChange(String, Object, Object)} method.
@param propertyName the programmatic name of the property that was changed
@param oldValue the old value of the property
@param newValue the new value of the property
"""
if (oldValue != newValue) {
firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
} | java | public void firePropertyChange(String propertyName, int oldValue, int newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
} | [
"public",
"void",
"firePropertyChange",
"(",
"String",
"propertyName",
",",
"int",
"oldValue",
",",
"int",
"newValue",
")",
"{",
"if",
"(",
"oldValue",
"!=",
"newValue",
")",
"{",
"firePropertyChange",
"(",
"propertyName",
",",
"Integer",
".",
"valueOf",
"(",
... | Reports an integer bound property update to listeners
that have been registered to track updates of
all properties or a property with the specified name.
<p>
No event is fired if old and new values are equal.
<p>
This is merely a convenience wrapper around the more general
{@link #firePropertyChange(String, Object, Object)} method.
@param propertyName the programmatic name of the property that was changed
@param oldValue the old value of the property
@param newValue the new value of the property | [
"Reports",
"an",
"integer",
"bound",
"property",
"update",
"to",
"listeners",
"that",
"have",
"been",
"registered",
"to",
"track",
"updates",
"of",
"all",
"properties",
"or",
"a",
"property",
"with",
"the",
"specified",
"name",
".",
"<p",
">",
"No",
"event",... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/beans/PropertyChangeSupport.java#L281-L285 |
Hygieia/Hygieia | api/src/main/java/com/capitalone/dashboard/service/CmdbRemoteServiceImpl.java | CmdbRemoteServiceImpl.buildCollectorItem | private CollectorItem buildCollectorItem( CmdbRequest request, Collector collector ) {
"""
Builds collector Item for new Cmdb item
@param request
@param collector
@return
"""
CollectorItem collectorItem = new CollectorItem();
collectorItem.setCollectorId( collector.getId() );
collectorItem.setEnabled( false );
collectorItem.setPushed( true );
collectorItem.setDescription( request.getCommonName() );
collectorItem.setLastUpdated( System.currentTimeMillis() );
collectorItem.getOptions().put( CONFIGURATION_ITEM, request.getConfigurationItem() );
collectorItem.getOptions().put( COMMON_NAME, request.getCommonName() );
return collectorService.createCollectorItem( collectorItem );
} | java | private CollectorItem buildCollectorItem( CmdbRequest request, Collector collector ) {
CollectorItem collectorItem = new CollectorItem();
collectorItem.setCollectorId( collector.getId() );
collectorItem.setEnabled( false );
collectorItem.setPushed( true );
collectorItem.setDescription( request.getCommonName() );
collectorItem.setLastUpdated( System.currentTimeMillis() );
collectorItem.getOptions().put( CONFIGURATION_ITEM, request.getConfigurationItem() );
collectorItem.getOptions().put( COMMON_NAME, request.getCommonName() );
return collectorService.createCollectorItem( collectorItem );
} | [
"private",
"CollectorItem",
"buildCollectorItem",
"(",
"CmdbRequest",
"request",
",",
"Collector",
"collector",
")",
"{",
"CollectorItem",
"collectorItem",
"=",
"new",
"CollectorItem",
"(",
")",
";",
"collectorItem",
".",
"setCollectorId",
"(",
"collector",
".",
"ge... | Builds collector Item for new Cmdb item
@param request
@param collector
@return | [
"Builds",
"collector",
"Item",
"for",
"new",
"Cmdb",
"item"
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/CmdbRemoteServiceImpl.java#L127-L139 |
joniles/mpxj | src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java | MSPDIReader.readDay | private void readDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day, boolean readExceptionsFromDays) {
"""
This method extracts data for a single day from an MSPDI file.
@param calendar Calendar data
@param day Day data
@param readExceptionsFromDays read exceptions form day definitions
"""
BigInteger dayType = day.getDayType();
if (dayType != null)
{
if (dayType.intValue() == 0)
{
if (readExceptionsFromDays)
{
readExceptionDay(calendar, day);
}
}
else
{
readNormalDay(calendar, day);
}
}
} | java | private void readDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay day, boolean readExceptionsFromDays)
{
BigInteger dayType = day.getDayType();
if (dayType != null)
{
if (dayType.intValue() == 0)
{
if (readExceptionsFromDays)
{
readExceptionDay(calendar, day);
}
}
else
{
readNormalDay(calendar, day);
}
}
} | [
"private",
"void",
"readDay",
"(",
"ProjectCalendar",
"calendar",
",",
"Project",
".",
"Calendars",
".",
"Calendar",
".",
"WeekDays",
".",
"WeekDay",
"day",
",",
"boolean",
"readExceptionsFromDays",
")",
"{",
"BigInteger",
"dayType",
"=",
"day",
".",
"getDayType... | This method extracts data for a single day from an MSPDI file.
@param calendar Calendar data
@param day Day data
@param readExceptionsFromDays read exceptions form day definitions | [
"This",
"method",
"extracts",
"data",
"for",
"a",
"single",
"day",
"from",
"an",
"MSPDI",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L491-L508 |
MKLab-ITI/simmo | src/main/java/gr/iti/mklab/simmo/core/morphia/ObjectDAO.java | ObjectDAO.createdInPeriod | public List<O> createdInPeriod(Date start, Date end, int numObjects) {
"""
Returns a list of images created in the time period specified by start and end
@param start
@param end
@param numObjects
@return
"""
return findByDate("creationDate", start, end, numObjects, true);
} | java | public List<O> createdInPeriod(Date start, Date end, int numObjects) {
return findByDate("creationDate", start, end, numObjects, true);
} | [
"public",
"List",
"<",
"O",
">",
"createdInPeriod",
"(",
"Date",
"start",
",",
"Date",
"end",
",",
"int",
"numObjects",
")",
"{",
"return",
"findByDate",
"(",
"\"creationDate\"",
",",
"start",
",",
"end",
",",
"numObjects",
",",
"true",
")",
";",
"}"
] | Returns a list of images created in the time period specified by start and end
@param start
@param end
@param numObjects
@return | [
"Returns",
"a",
"list",
"of",
"images",
"created",
"in",
"the",
"time",
"period",
"specified",
"by",
"start",
"and",
"end"
] | train | https://github.com/MKLab-ITI/simmo/blob/a78436e982e160fb0260746c563c7e4d24736486/src/main/java/gr/iti/mklab/simmo/core/morphia/ObjectDAO.java#L93-L95 |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationService.java | ClassificationService.attachClassification | public ClassificationModel attachClassification(GraphRewrite event, EvaluationContext context, FileModel fileModel, String classificationText, String description) {
"""
Attach a {@link ClassificationModel} with the given classificationText and description to the provided {@link FileModel}.
If an existing Model exists with the provided classificationText, that one will be used instead.
"""
return attachClassification(event, context, fileModel, IssueCategoryRegistry.DEFAULT, classificationText, description);
} | java | public ClassificationModel attachClassification(GraphRewrite event, EvaluationContext context, FileModel fileModel, String classificationText, String description)
{
return attachClassification(event, context, fileModel, IssueCategoryRegistry.DEFAULT, classificationText, description);
} | [
"public",
"ClassificationModel",
"attachClassification",
"(",
"GraphRewrite",
"event",
",",
"EvaluationContext",
"context",
",",
"FileModel",
"fileModel",
",",
"String",
"classificationText",
",",
"String",
"description",
")",
"{",
"return",
"attachClassification",
"(",
... | Attach a {@link ClassificationModel} with the given classificationText and description to the provided {@link FileModel}.
If an existing Model exists with the provided classificationText, that one will be used instead. | [
"Attach",
"a",
"{"
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationService.java#L276-L279 |
alkacon/opencms-core | src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java | CmsEditablePositionCalculator.intersectsHorizontally | protected boolean intersectsHorizontally(CmsPositionBean p1, CmsPositionBean p2) {
"""
Checks whether two positions intersect horizontally.<p>
@param p1 the first position
@param p2 the second position
@return true if the positions intersect horizontally
"""
return intersectIntervals(p1.getLeft(), p1.getLeft() + WIDTH, p2.getLeft(), p2.getLeft() + WIDTH);
} | java | protected boolean intersectsHorizontally(CmsPositionBean p1, CmsPositionBean p2) {
return intersectIntervals(p1.getLeft(), p1.getLeft() + WIDTH, p2.getLeft(), p2.getLeft() + WIDTH);
} | [
"protected",
"boolean",
"intersectsHorizontally",
"(",
"CmsPositionBean",
"p1",
",",
"CmsPositionBean",
"p2",
")",
"{",
"return",
"intersectIntervals",
"(",
"p1",
".",
"getLeft",
"(",
")",
",",
"p1",
".",
"getLeft",
"(",
")",
"+",
"WIDTH",
",",
"p2",
".",
... | Checks whether two positions intersect horizontally.<p>
@param p1 the first position
@param p2 the second position
@return true if the positions intersect horizontally | [
"Checks",
"whether",
"two",
"positions",
"intersect",
"horizontally",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java#L172-L175 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java | BufferUtil.iterateUntil | public static int iterateUntil(ShortBuffer array, int pos, int length, int min) {
"""
Find the smallest integer larger than pos such that array[pos]>= min. If none can be found,
return length.
@param array array to search within
@param pos starting position of the search
@param length length of the array to search
@param min minimum value
@return x greater than pos such that array[pos] is at least as large as min, pos is is equal to
length if it is not possible.
"""
while (pos < length && toIntUnsigned(array.get(pos)) < min) {
pos++;
}
return pos;
} | java | public static int iterateUntil(ShortBuffer array, int pos, int length, int min) {
while (pos < length && toIntUnsigned(array.get(pos)) < min) {
pos++;
}
return pos;
} | [
"public",
"static",
"int",
"iterateUntil",
"(",
"ShortBuffer",
"array",
",",
"int",
"pos",
",",
"int",
"length",
",",
"int",
"min",
")",
"{",
"while",
"(",
"pos",
"<",
"length",
"&&",
"toIntUnsigned",
"(",
"array",
".",
"get",
"(",
"pos",
")",
")",
"... | Find the smallest integer larger than pos such that array[pos]>= min. If none can be found,
return length.
@param array array to search within
@param pos starting position of the search
@param length length of the array to search
@param min minimum value
@return x greater than pos such that array[pos] is at least as large as min, pos is is equal to
length if it is not possible. | [
"Find",
"the",
"smallest",
"integer",
"larger",
"than",
"pos",
"such",
"that",
"array",
"[",
"pos",
"]",
">",
";",
"=",
"min",
".",
"If",
"none",
"can",
"be",
"found",
"return",
"length",
"."
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java#L178-L183 |
lagom/lagom | service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java | Descriptor.withCalls | public Descriptor withCalls(Call<?, ?>... calls) {
"""
Add the given service calls to this service.
@param calls The calls to add.
@return A copy of this descriptor with the new calls added.
"""
return replaceAllCalls(this.calls.plusAll(Arrays.asList(calls)));
} | java | public Descriptor withCalls(Call<?, ?>... calls) {
return replaceAllCalls(this.calls.plusAll(Arrays.asList(calls)));
} | [
"public",
"Descriptor",
"withCalls",
"(",
"Call",
"<",
"?",
",",
"?",
">",
"...",
"calls",
")",
"{",
"return",
"replaceAllCalls",
"(",
"this",
".",
"calls",
".",
"plusAll",
"(",
"Arrays",
".",
"asList",
"(",
"calls",
")",
")",
")",
";",
"}"
] | Add the given service calls to this service.
@param calls The calls to add.
@return A copy of this descriptor with the new calls added. | [
"Add",
"the",
"given",
"service",
"calls",
"to",
"this",
"service",
"."
] | train | https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java#L710-L712 |
devcon5io/common | classutils/src/main/java/io/devcon5/classutils/CallStack.java | CallStack.getCallerClass | public static Class<?> getCallerClass() {
"""
Returns the caller class of the calling method.<br> For example: <br> A.calling() -> B.called() B.called()
->
getCallerClass(): A <br> If a thread context classloader is defined, it will be used for loading the class,
otherwise the default class loader is used.
@return the class of the calling method's class
"""
final StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
try {
final StackTraceElement caller = findCaller(stElements);
return loadClass(caller.getClassName());
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not determine caller class", e);
}
} | java | public static Class<?> getCallerClass() {
final StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
try {
final StackTraceElement caller = findCaller(stElements);
return loadClass(caller.getClassName());
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not determine caller class", e);
}
} | [
"public",
"static",
"Class",
"<",
"?",
">",
"getCallerClass",
"(",
")",
"{",
"final",
"StackTraceElement",
"[",
"]",
"stElements",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getStackTrace",
"(",
")",
";",
"try",
"{",
"final",
"StackTraceElement",
... | Returns the caller class of the calling method.<br> For example: <br> A.calling() -> B.called() B.called()
->
getCallerClass(): A <br> If a thread context classloader is defined, it will be used for loading the class,
otherwise the default class loader is used.
@return the class of the calling method's class | [
"Returns",
"the",
"caller",
"class",
"of",
"the",
"calling",
"method",
".",
"<br",
">",
"For",
"example",
":",
"<br",
">",
"A",
".",
"calling",
"()",
"-",
">",
";",
"B",
".",
"called",
"()",
"B",
".",
"called",
"()",
"-",
">",
";",
"getCallerCl... | train | https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/classutils/src/main/java/io/devcon5/classutils/CallStack.java#L86-L95 |
recommenders/rival | rival-core/src/main/java/net/recommenders/rival/core/TemporalDataModel.java | TemporalDataModel.addTimestamp | @Override
public void addTimestamp(final U u, final I i, final Long t) {
"""
Method that adds a timestamp to the model between a user and an item.
@param u the user.
@param i the item.
@param t the timestamp.
"""
Map<I, Set<Long>> userTimestamps = userItemTimestamps.get(u);
if (userTimestamps == null) {
userTimestamps = new HashMap<>();
userItemTimestamps.put(u, userTimestamps);
}
Set<Long> timestamps = userTimestamps.get(i);
if (timestamps == null) {
timestamps = new HashSet<>();
userTimestamps.put(i, timestamps);
}
timestamps.add(t);
} | java | @Override
public void addTimestamp(final U u, final I i, final Long t) {
Map<I, Set<Long>> userTimestamps = userItemTimestamps.get(u);
if (userTimestamps == null) {
userTimestamps = new HashMap<>();
userItemTimestamps.put(u, userTimestamps);
}
Set<Long> timestamps = userTimestamps.get(i);
if (timestamps == null) {
timestamps = new HashSet<>();
userTimestamps.put(i, timestamps);
}
timestamps.add(t);
} | [
"@",
"Override",
"public",
"void",
"addTimestamp",
"(",
"final",
"U",
"u",
",",
"final",
"I",
"i",
",",
"final",
"Long",
"t",
")",
"{",
"Map",
"<",
"I",
",",
"Set",
"<",
"Long",
">",
">",
"userTimestamps",
"=",
"userItemTimestamps",
".",
"get",
"(",
... | Method that adds a timestamp to the model between a user and an item.
@param u the user.
@param i the item.
@param t the timestamp. | [
"Method",
"that",
"adds",
"a",
"timestamp",
"to",
"the",
"model",
"between",
"a",
"user",
"and",
"an",
"item",
"."
] | train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/TemporalDataModel.java#L95-L108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.