repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseXcsr2bsrNnz | public static int cusparseXcsr2bsrNnz(
cusparseHandle handle,
int dirA,
int m,
int n,
cusparseMatDescr descrA,
Pointer csrSortedRowPtrA,
Pointer csrSortedColIndA,
int blockDim,
cusparseMatDescr descrC,
Pointer bsrSortedRowPtrC,
Pointer nnzTotalDevHostPtr)
{
return checkResult(cusparseXcsr2bsrNnzNative(handle, dirA, m, n, descrA, csrSortedRowPtrA, csrSortedColIndA, blockDim, descrC, bsrSortedRowPtrC, nnzTotalDevHostPtr));
} | java | public static int cusparseXcsr2bsrNnz(
cusparseHandle handle,
int dirA,
int m,
int n,
cusparseMatDescr descrA,
Pointer csrSortedRowPtrA,
Pointer csrSortedColIndA,
int blockDim,
cusparseMatDescr descrC,
Pointer bsrSortedRowPtrC,
Pointer nnzTotalDevHostPtr)
{
return checkResult(cusparseXcsr2bsrNnzNative(handle, dirA, m, n, descrA, csrSortedRowPtrA, csrSortedColIndA, blockDim, descrC, bsrSortedRowPtrC, nnzTotalDevHostPtr));
} | [
"public",
"static",
"int",
"cusparseXcsr2bsrNnz",
"(",
"cusparseHandle",
"handle",
",",
"int",
"dirA",
",",
"int",
"m",
",",
"int",
"n",
",",
"cusparseMatDescr",
"descrA",
",",
"Pointer",
"csrSortedRowPtrA",
",",
"Pointer",
"csrSortedColIndA",
",",
"int",
"block... | Description: This routine converts a sparse matrix in CSR storage format
to a sparse matrix in block-CSR storage format. | [
"Description",
":",
"This",
"routine",
"converts",
"a",
"sparse",
"matrix",
"in",
"CSR",
"storage",
"format",
"to",
"a",
"sparse",
"matrix",
"in",
"block",
"-",
"CSR",
"storage",
"format",
"."
] | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L12363-L12377 |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/Request.java | Request.newDeleteObjectRequest | public static Request newDeleteObjectRequest(Session session, String id, Callback callback) {
return new Request(session, id, null, HttpMethod.DELETE, callback);
} | java | public static Request newDeleteObjectRequest(Session session, String id, Callback callback) {
return new Request(session, id, null, HttpMethod.DELETE, callback);
} | [
"public",
"static",
"Request",
"newDeleteObjectRequest",
"(",
"Session",
"session",
",",
"String",
"id",
",",
"Callback",
"callback",
")",
"{",
"return",
"new",
"Request",
"(",
"session",
",",
"id",
",",
"null",
",",
"HttpMethod",
".",
"DELETE",
",",
"callba... | Creates a new Request configured to delete a resource through the Graph API.
@param session
the Session to use, or null; if non-null, the session must be in an opened state
@param id
the id of the object to delete
@param callback
a callback that will be called when the request is completed to handle success or error conditions
@return a Request that is ready to execute | [
"Creates",
"a",
"new",
"Request",
"configured",
"to",
"delete",
"a",
"resource",
"through",
"the",
"Graph",
"API",
"."
] | train | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L766-L768 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatednas/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednas.java | ApiOvhDedicatednas.serviceName_partition_partitionName_quota_uid_DELETE | public OvhTask serviceName_partition_partitionName_quota_uid_DELETE(String serviceName, String partitionName, Long uid) throws IOException {
String qPath = "/dedicated/nas/{serviceName}/partition/{partitionName}/quota/{uid}";
StringBuilder sb = path(qPath, serviceName, partitionName, uid);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_partition_partitionName_quota_uid_DELETE(String serviceName, String partitionName, Long uid) throws IOException {
String qPath = "/dedicated/nas/{serviceName}/partition/{partitionName}/quota/{uid}";
StringBuilder sb = path(qPath, serviceName, partitionName, uid);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_partition_partitionName_quota_uid_DELETE",
"(",
"String",
"serviceName",
",",
"String",
"partitionName",
",",
"Long",
"uid",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/nas/{serviceName}/partition/{partitionName}/qu... | Delete a given quota
REST: DELETE /dedicated/nas/{serviceName}/partition/{partitionName}/quota/{uid}
@param serviceName [required] The internal name of your storage
@param partitionName [required] the given name of partition
@param uid [required] the uid to set quota on | [
"Delete",
"a",
"given",
"quota"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatednas/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednas.java#L252-L257 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.cart_cartId_PUT | public OvhCart cart_cartId_PUT(String cartId, String description, Date expire) throws IOException {
String qPath = "/order/cart/{cartId}";
StringBuilder sb = path(qPath, cartId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "description", description);
addBody(o, "expire", expire);
String resp = execN(qPath, "PUT", sb.toString(), o);
return convertTo(resp, OvhCart.class);
} | java | public OvhCart cart_cartId_PUT(String cartId, String description, Date expire) throws IOException {
String qPath = "/order/cart/{cartId}";
StringBuilder sb = path(qPath, cartId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "description", description);
addBody(o, "expire", expire);
String resp = execN(qPath, "PUT", sb.toString(), o);
return convertTo(resp, OvhCart.class);
} | [
"public",
"OvhCart",
"cart_cartId_PUT",
"(",
"String",
"cartId",
",",
"String",
"description",
",",
"Date",
"expire",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cart/{cartId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",... | Modify information about a specific cart
REST: PUT /order/cart/{cartId}
@param cartId [required] Cart identifier
@param description [required] Description of your cart
@param expire [required] Time of expiration of the cart | [
"Modify",
"information",
"about",
"a",
"specific",
"cart"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L8856-L8864 |
Waikato/moa | moa/src/main/java/moa/clusterers/kmeanspm/ClusteringFeature.java | ClusteringFeature.calcKMeansCosts | public double calcKMeansCosts(double[] center, double[] point) {
assert (this.sumPoints.length == center.length &&
this.sumPoints.length == point.length);
return (this.sumSquaredLength + Metric.distanceSquared(point)) - 2
* Metric.dotProductWithAddition(this.sumPoints, point, center)
+ (this.numPoints + 1) * Metric.dotProduct(center);
} | java | public double calcKMeansCosts(double[] center, double[] point) {
assert (this.sumPoints.length == center.length &&
this.sumPoints.length == point.length);
return (this.sumSquaredLength + Metric.distanceSquared(point)) - 2
* Metric.dotProductWithAddition(this.sumPoints, point, center)
+ (this.numPoints + 1) * Metric.dotProduct(center);
} | [
"public",
"double",
"calcKMeansCosts",
"(",
"double",
"[",
"]",
"center",
",",
"double",
"[",
"]",
"point",
")",
"{",
"assert",
"(",
"this",
".",
"sumPoints",
".",
"length",
"==",
"center",
".",
"length",
"&&",
"this",
".",
"sumPoints",
".",
"length",
... | Calculates the k-means costs of the ClusteringFeature and a point too a
center.
@param center
the center too calculate the costs
@param point
the point too calculate the costs
@return the costs | [
"Calculates",
"the",
"k",
"-",
"means",
"costs",
"of",
"the",
"ClusteringFeature",
"and",
"a",
"point",
"too",
"a",
"center",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/ClusteringFeature.java#L279-L285 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java | StreamingEndpointsInner.updateAsync | public Observable<StreamingEndpointInner> updateAsync(String resourceGroupName, String accountName, String streamingEndpointName, StreamingEndpointInner parameters) {
return updateWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName, parameters).map(new Func1<ServiceResponse<StreamingEndpointInner>, StreamingEndpointInner>() {
@Override
public StreamingEndpointInner call(ServiceResponse<StreamingEndpointInner> response) {
return response.body();
}
});
} | java | public Observable<StreamingEndpointInner> updateAsync(String resourceGroupName, String accountName, String streamingEndpointName, StreamingEndpointInner parameters) {
return updateWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName, parameters).map(new Func1<ServiceResponse<StreamingEndpointInner>, StreamingEndpointInner>() {
@Override
public StreamingEndpointInner call(ServiceResponse<StreamingEndpointInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StreamingEndpointInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"streamingEndpointName",
",",
"StreamingEndpointInner",
"parameters",
")",
"{",
"return",
"updateWithServiceResponseAs... | Update StreamingEndpoint.
Updates a existing StreamingEndpoint.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param streamingEndpointName The name of the StreamingEndpoint.
@param parameters StreamingEndpoint properties needed for creation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Update",
"StreamingEndpoint",
".",
"Updates",
"a",
"existing",
"StreamingEndpoint",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java#L788-L795 |
jhy/jsoup | src/main/java/org/jsoup/nodes/Attribute.java | Attribute.createFromEncoded | public static Attribute createFromEncoded(String unencodedKey, String encodedValue) {
String value = Entities.unescape(encodedValue, true);
return new Attribute(unencodedKey, value, null); // parent will get set when Put
} | java | public static Attribute createFromEncoded(String unencodedKey, String encodedValue) {
String value = Entities.unescape(encodedValue, true);
return new Attribute(unencodedKey, value, null); // parent will get set when Put
} | [
"public",
"static",
"Attribute",
"createFromEncoded",
"(",
"String",
"unencodedKey",
",",
"String",
"encodedValue",
")",
"{",
"String",
"value",
"=",
"Entities",
".",
"unescape",
"(",
"encodedValue",
",",
"true",
")",
";",
"return",
"new",
"Attribute",
"(",
"u... | Create a new Attribute from an unencoded key and a HTML attribute encoded value.
@param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars.
@param encodedValue HTML attribute encoded value
@return attribute | [
"Create",
"a",
"new",
"Attribute",
"from",
"an",
"unencoded",
"key",
"and",
"a",
"HTML",
"attribute",
"encoded",
"value",
"."
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Attribute.java#L142-L145 |
JadiraOrg/jadira | jms/src/main/java/org/jadira/jms/template/BatchedJmsTemplate.java | BatchedJmsTemplate.receiveSelectedBatch | public List<Message> receiveSelectedBatch(String messageSelector, int batchSize) throws JmsException {
Destination defaultDestination = getDefaultDestination();
if (defaultDestination != null) {
return receiveSelectedBatch(defaultDestination, messageSelector, batchSize);
} else {
return receiveSelectedBatch(getRequiredDefaultDestinationName(), messageSelector, batchSize);
}
} | java | public List<Message> receiveSelectedBatch(String messageSelector, int batchSize) throws JmsException {
Destination defaultDestination = getDefaultDestination();
if (defaultDestination != null) {
return receiveSelectedBatch(defaultDestination, messageSelector, batchSize);
} else {
return receiveSelectedBatch(getRequiredDefaultDestinationName(), messageSelector, batchSize);
}
} | [
"public",
"List",
"<",
"Message",
">",
"receiveSelectedBatch",
"(",
"String",
"messageSelector",
",",
"int",
"batchSize",
")",
"throws",
"JmsException",
"{",
"Destination",
"defaultDestination",
"=",
"getDefaultDestination",
"(",
")",
";",
"if",
"(",
"defaultDestina... | Receive a batch of up to batchSize for default destination and given message selector. Other than batching this method is the same as {@link JmsTemplate#receiveSelected(String)}
@return A list of {@link Message}
@param messageSelector The Selector
@param batchSize The batch size
@throws JmsException The {@link JmsException} | [
"Receive",
"a",
"batch",
"of",
"up",
"to",
"batchSize",
"for",
"default",
"destination",
"and",
"given",
"message",
"selector",
".",
"Other",
"than",
"batching",
"this",
"method",
"is",
"the",
"same",
"as",
"{"
] | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/jms/src/main/java/org/jadira/jms/template/BatchedJmsTemplate.java#L200-L207 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/util/JavaBean.java | JavaBean.setProperty | public static void setProperty(Object bean, String propertyName, Object value)
{
setProperty(bean,propertyName,value,true);
} | java | public static void setProperty(Object bean, String propertyName, Object value)
{
setProperty(bean,propertyName,value,true);
} | [
"public",
"static",
"void",
"setProperty",
"(",
"Object",
"bean",
",",
"String",
"propertyName",
",",
"Object",
"value",
")",
"{",
"setProperty",
"(",
"bean",
",",
"propertyName",
",",
"value",
",",
"true",
")",
";",
"}"
] | Set property
@param bean the bean
@param propertyName the property name
@param value the value to set | [
"Set",
"property"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/JavaBean.java#L184-L187 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/util/BitMaskUtil.java | BitMaskUtil.isBitOn | public static boolean isBitOn(int value, int bitNumber) {
ensureBitRange(bitNumber);
return ((value & MASKS[bitNumber - 1]) == MASKS[bitNumber - 1]);
} | java | public static boolean isBitOn(int value, int bitNumber) {
ensureBitRange(bitNumber);
return ((value & MASKS[bitNumber - 1]) == MASKS[bitNumber - 1]);
} | [
"public",
"static",
"boolean",
"isBitOn",
"(",
"int",
"value",
",",
"int",
"bitNumber",
")",
"{",
"ensureBitRange",
"(",
"bitNumber",
")",
";",
"return",
"(",
"(",
"value",
"&",
"MASKS",
"[",
"bitNumber",
"-",
"1",
"]",
")",
"==",
"MASKS",
"[",
"bitNum... | Check if the bit is set to '1'
@param value integer to check bit
@param number of bit to check (right first bit starting at 1) | [
"Check",
"if",
"the",
"bit",
"is",
"set",
"to",
"1"
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/util/BitMaskUtil.java#L73-L76 |
baasbox/Android-SDK | library/src/main/java/com/baasbox/android/BaasUser.java | BaasUser.saveSync | public BaasResult<BaasUser> saveSync() {
BaasBox box = BaasBox.getDefaultChecked();
SaveUser task = new SaveUser(box, this, RequestOptions.DEFAULT, null);
return box.submitSync(task);
} | java | public BaasResult<BaasUser> saveSync() {
BaasBox box = BaasBox.getDefaultChecked();
SaveUser task = new SaveUser(box, this, RequestOptions.DEFAULT, null);
return box.submitSync(task);
} | [
"public",
"BaasResult",
"<",
"BaasUser",
">",
"saveSync",
"(",
")",
"{",
"BaasBox",
"box",
"=",
"BaasBox",
".",
"getDefaultChecked",
"(",
")",
";",
"SaveUser",
"task",
"=",
"new",
"SaveUser",
"(",
"box",
",",
"this",
",",
"RequestOptions",
".",
"DEFAULT",
... | Synchronously saves the updates made to the current user.
@return the result of the request | [
"Synchronously",
"saves",
"the",
"updates",
"made",
"to",
"the",
"current",
"user",
"."
] | train | https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L915-L919 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/streaming/JsonTextSequences.java | JsonTextSequences.fromPublisher | public static HttpResponse fromPublisher(HttpHeaders headers, Publisher<?> contentPublisher,
HttpHeaders trailingHeaders, ObjectMapper mapper) {
requireNonNull(mapper, "mapper");
return streamingFrom(contentPublisher, sanitizeHeaders(headers), trailingHeaders,
o -> toHttpData(mapper, o));
} | java | public static HttpResponse fromPublisher(HttpHeaders headers, Publisher<?> contentPublisher,
HttpHeaders trailingHeaders, ObjectMapper mapper) {
requireNonNull(mapper, "mapper");
return streamingFrom(contentPublisher, sanitizeHeaders(headers), trailingHeaders,
o -> toHttpData(mapper, o));
} | [
"public",
"static",
"HttpResponse",
"fromPublisher",
"(",
"HttpHeaders",
"headers",
",",
"Publisher",
"<",
"?",
">",
"contentPublisher",
",",
"HttpHeaders",
"trailingHeaders",
",",
"ObjectMapper",
"mapper",
")",
"{",
"requireNonNull",
"(",
"mapper",
",",
"\"mapper\"... | Creates a new JSON Text Sequences from the specified {@link Publisher}.
@param headers the HTTP headers supposed to send
@param contentPublisher the {@link Publisher} which publishes the objects supposed to send as contents
@param trailingHeaders the trailing HTTP headers supposed to send
@param mapper the mapper which converts the content object into JSON Text Sequences | [
"Creates",
"a",
"new",
"JSON",
"Text",
"Sequences",
"from",
"the",
"specified",
"{",
"@link",
"Publisher",
"}",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/streaming/JsonTextSequences.java#L142-L147 |
ysc/word | src/main/java/org/apdplat/word/recognition/RecognitionTool.java | RecognitionTool.isQuantifier | public static boolean isQuantifier(final String text, final int start, final int len){
if(len < 2){
return false;
}
//避免量词和不完整小数结合
//.的值是46,/的值是47
//判断前一个字符是否是.或/
int index = start-1;
if(index > -1 && (text.charAt(index) == 46 || text.charAt(index) == 47)){
return false;
}
char lastChar = text.charAt(start+len-1);
if(Quantifier.is(lastChar)
&&
(isNumber(text, start, len-1) ||
isChineseNumber(text, start, len-1) ||
isFraction(text, start, len-1)) ){
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("识别数量词:" + text.substring(start, start + len));
}
return true;
}
return false;
} | java | public static boolean isQuantifier(final String text, final int start, final int len){
if(len < 2){
return false;
}
//避免量词和不完整小数结合
//.的值是46,/的值是47
//判断前一个字符是否是.或/
int index = start-1;
if(index > -1 && (text.charAt(index) == 46 || text.charAt(index) == 47)){
return false;
}
char lastChar = text.charAt(start+len-1);
if(Quantifier.is(lastChar)
&&
(isNumber(text, start, len-1) ||
isChineseNumber(text, start, len-1) ||
isFraction(text, start, len-1)) ){
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("识别数量词:" + text.substring(start, start + len));
}
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"isQuantifier",
"(",
"final",
"String",
"text",
",",
"final",
"int",
"start",
",",
"final",
"int",
"len",
")",
"{",
"if",
"(",
"len",
"<",
"2",
")",
"{",
"return",
"false",
";",
"}",
"//避免量词和不完整小数结合",
"//.的值是46,/的值是47",
"//... | 数量词识别,如日期、时间、长度、容量、重量、面积等等
@param text 识别文本
@param start 待识别文本开始索引
@param len 识别长度
@return 是否识别 | [
"数量词识别,如日期、时间、长度、容量、重量、面积等等"
] | train | https://github.com/ysc/word/blob/5e45607f4e97207f55d1e3bc561abda6b34f7c54/src/main/java/org/apdplat/word/recognition/RecognitionTool.java#L210-L233 |
opendatatrentino/s-match | src/main/java/it/unitn/disi/smatch/oracles/wordnet/WordNet.java | WordNet.getRelationFromOracle | private boolean getRelationFromOracle(ISense source, ISense target, char rel) throws SenseMatcherException {
final String sensePairKey = source.toString() + target.toString();
Character cachedRelation = sensesCache.get(sensePairKey);
// if we don't have cached relation check which one exist and put it to cash
if (null == cachedRelation) {
// check for synonymy
if (isSourceSynonymTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.EQUIVALENCE);
return rel == IMappingElement.EQUIVALENCE;
} else {
// check for opposite meaning
if (isSourceOppositeToTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.DISJOINT);
return rel == IMappingElement.DISJOINT;
} else {
// check for less general than
if (isSourceLessGeneralThanTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.LESS_GENERAL);
return rel == IMappingElement.LESS_GENERAL;
} else {
// check for more general than
if (isSourceMoreGeneralThanTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.MORE_GENERAL);
return rel == IMappingElement.MORE_GENERAL;
} else {
sensesCache.put(sensePairKey, IMappingElement.IDK);
return false;
}
}
}
}
} else {
return rel == cachedRelation;
}
} | java | private boolean getRelationFromOracle(ISense source, ISense target, char rel) throws SenseMatcherException {
final String sensePairKey = source.toString() + target.toString();
Character cachedRelation = sensesCache.get(sensePairKey);
// if we don't have cached relation check which one exist and put it to cash
if (null == cachedRelation) {
// check for synonymy
if (isSourceSynonymTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.EQUIVALENCE);
return rel == IMappingElement.EQUIVALENCE;
} else {
// check for opposite meaning
if (isSourceOppositeToTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.DISJOINT);
return rel == IMappingElement.DISJOINT;
} else {
// check for less general than
if (isSourceLessGeneralThanTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.LESS_GENERAL);
return rel == IMappingElement.LESS_GENERAL;
} else {
// check for more general than
if (isSourceMoreGeneralThanTarget(source, target)) {
sensesCache.put(sensePairKey, IMappingElement.MORE_GENERAL);
return rel == IMappingElement.MORE_GENERAL;
} else {
sensesCache.put(sensePairKey, IMappingElement.IDK);
return false;
}
}
}
}
} else {
return rel == cachedRelation;
}
} | [
"private",
"boolean",
"getRelationFromOracle",
"(",
"ISense",
"source",
",",
"ISense",
"target",
",",
"char",
"rel",
")",
"throws",
"SenseMatcherException",
"{",
"final",
"String",
"sensePairKey",
"=",
"source",
".",
"toString",
"(",
")",
"+",
"target",
".",
"... | Method which returns whether particular type of relation between
two senses holds(according to oracle).
It uses cache to store already obtained relations in order to improve performance.
@param source the string of source
@param target the string of target
@param rel the relation between source and target
@return whether particular type of relation holds between two senses according to oracle
@throws SenseMatcherException SenseMatcherException | [
"Method",
"which",
"returns",
"whether",
"particular",
"type",
"of",
"relation",
"between",
"two",
"senses",
"holds",
"(",
"according",
"to",
"oracle",
")",
".",
"It",
"uses",
"cache",
"to",
"store",
"already",
"obtained",
"relations",
"in",
"order",
"to",
"... | train | https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/smatch/oracles/wordnet/WordNet.java#L272-L306 |
Coveros/selenified | src/main/java/com/coveros/selenified/element/Element.java | Element.scrollTo | public void scrollTo(long position) {
String action = "Scrolling screen to " + position + " pixels above " + prettyOutput();
String expected = prettyOutputStart() + " is now within the current viewport";
try {
// wait for element to be present
if (isNotPresent(action, expected, CANT_SCROLL)) {
return;
}
// perform the move action
JavascriptExecutor jse = (JavascriptExecutor) driver;
WebElement webElement = getWebElement();
long elementPosition = webElement.getLocation().getY();
long newPosition = elementPosition - position;
jse.executeScript("window.scrollBy(0, " + newPosition + ")");
} catch (Exception e) {
cantScroll(e, action, expected);
return;
}
isScrolledTo(action, expected);
} | java | public void scrollTo(long position) {
String action = "Scrolling screen to " + position + " pixels above " + prettyOutput();
String expected = prettyOutputStart() + " is now within the current viewport";
try {
// wait for element to be present
if (isNotPresent(action, expected, CANT_SCROLL)) {
return;
}
// perform the move action
JavascriptExecutor jse = (JavascriptExecutor) driver;
WebElement webElement = getWebElement();
long elementPosition = webElement.getLocation().getY();
long newPosition = elementPosition - position;
jse.executeScript("window.scrollBy(0, " + newPosition + ")");
} catch (Exception e) {
cantScroll(e, action, expected);
return;
}
isScrolledTo(action, expected);
} | [
"public",
"void",
"scrollTo",
"(",
"long",
"position",
")",
"{",
"String",
"action",
"=",
"\"Scrolling screen to \"",
"+",
"position",
"+",
"\" pixels above \"",
"+",
"prettyOutput",
"(",
")",
";",
"String",
"expected",
"=",
"prettyOutputStart",
"(",
")",
"+",
... | Scrolls the page to the element, leaving X pixels at the top of the
viewport above it, making it displayed on the current viewport, but only
if the element is present. If that condition is not met, the scroll action
will be logged, but skipped and the test will continue.
@param position - how many pixels above the element to scroll to | [
"Scrolls",
"the",
"page",
"to",
"the",
"element",
"leaving",
"X",
"pixels",
"at",
"the",
"top",
"of",
"the",
"viewport",
"above",
"it",
"making",
"it",
"displayed",
"on",
"the",
"current",
"viewport",
"but",
"only",
"if",
"the",
"element",
"is",
"present",... | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/element/Element.java#L1159-L1178 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java | ClientFactory.createMessageSenderFromEntityPath | public static IMessageSender createMessageSenderFromEntityPath(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings) throws InterruptedException, ServiceBusException {
return Utils.completeFuture(createMessageSenderFromEntityPathAsync(namespaceEndpointURI, entityPath, clientSettings));
} | java | public static IMessageSender createMessageSenderFromEntityPath(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings) throws InterruptedException, ServiceBusException {
return Utils.completeFuture(createMessageSenderFromEntityPathAsync(namespaceEndpointURI, entityPath, clientSettings));
} | [
"public",
"static",
"IMessageSender",
"createMessageSenderFromEntityPath",
"(",
"URI",
"namespaceEndpointURI",
",",
"String",
"entityPath",
",",
"ClientSettings",
"clientSettings",
")",
"throws",
"InterruptedException",
",",
"ServiceBusException",
"{",
"return",
"Utils",
".... | Creates a message sender to the entity using the client settings.
@param namespaceEndpointURI endpoint uri of entity namespace
@param entityPath path of entity
@param clientSettings client settings
@return IMessageSender instance
@throws InterruptedException if the current thread was interrupted while waiting
@throws ServiceBusException if the sender cannot be created | [
"Creates",
"a",
"message",
"sender",
"to",
"the",
"entity",
"using",
"the",
"client",
"settings",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L78-L80 |
apache/reef | lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/REEFLauncher.java | REEFLauncher.readConfigurationFromDisk | private static Configuration readConfigurationFromDisk(
final String configPath, final ConfigurationSerializer serializer) {
LOG.log(Level.FINER, "Loading configuration file: {0}", configPath);
final File evaluatorConfigFile = new File(configPath);
if (!evaluatorConfigFile.exists()) {
throw fatal(
"Configuration file " + configPath + " does not exist. Can be an issue in job submission.",
new FileNotFoundException(configPath));
}
if (!evaluatorConfigFile.canRead()) {
throw fatal(
"Configuration file " + configPath + " exists, but can't be read.",
new IOException(configPath));
}
try {
final Configuration config = serializer.fromFile(evaluatorConfigFile);
LOG.log(Level.FINEST, "Configuration file loaded: {0}", configPath);
return config;
} catch (final IOException e) {
throw fatal("Unable to parse the configuration file: " + configPath, e);
}
} | java | private static Configuration readConfigurationFromDisk(
final String configPath, final ConfigurationSerializer serializer) {
LOG.log(Level.FINER, "Loading configuration file: {0}", configPath);
final File evaluatorConfigFile = new File(configPath);
if (!evaluatorConfigFile.exists()) {
throw fatal(
"Configuration file " + configPath + " does not exist. Can be an issue in job submission.",
new FileNotFoundException(configPath));
}
if (!evaluatorConfigFile.canRead()) {
throw fatal(
"Configuration file " + configPath + " exists, but can't be read.",
new IOException(configPath));
}
try {
final Configuration config = serializer.fromFile(evaluatorConfigFile);
LOG.log(Level.FINEST, "Configuration file loaded: {0}", configPath);
return config;
} catch (final IOException e) {
throw fatal("Unable to parse the configuration file: " + configPath, e);
}
} | [
"private",
"static",
"Configuration",
"readConfigurationFromDisk",
"(",
"final",
"String",
"configPath",
",",
"final",
"ConfigurationSerializer",
"serializer",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINER",
",",
"\"Loading configuration file: {0}\"",
",",
"c... | Read configuration from a given file and deserialize it
into Tang configuration object that can be used for injection.
Configuration is currently serialized using Avro.
This method also prints full deserialized configuration into log.
@param configPath Path to the local file that contains serialized configuration
of a REEF component to launch (can be either Driver or Evaluator).
@param serializer An object to deserialize the configuration file.
@return Tang configuration read and deserialized from a given file. | [
"Read",
"configuration",
"from",
"a",
"given",
"file",
"and",
"deserialize",
"it",
"into",
"Tang",
"configuration",
"object",
"that",
"can",
"be",
"used",
"for",
"injection",
".",
"Configuration",
"is",
"currently",
"serialized",
"using",
"Avro",
".",
"This",
... | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/REEFLauncher.java#L124-L153 |
jayantk/jklol | src/com/jayantkrish/jklol/models/TableFactor.java | TableFactor.fromDelimitedFile | public static TableFactor fromDelimitedFile(List<VariableNumMap> variables,
List<? extends Function<String, ?>> inputConverters, Iterable<String> lines, String delimiter,
boolean ignoreInvalidAssignments, TensorFactory tensorFactory) {
int numVars = variables.size();
VariableNumMap allVars = VariableNumMap.unionAll(variables);
TableFactorBuilder builder = new TableFactorBuilder(allVars, tensorFactory);
for (String line : lines) {
// Ignore blank lines.
if (line.trim().length() == 0) {
continue;
}
String[] parts = line.split(delimiter);
Preconditions.checkState(parts.length == (numVars + 1), "\"%s\" is incorrectly formatted", line);
Assignment assignment = Assignment.EMPTY;
for (int i = 0; i < numVars; i++) {
Object value = inputConverters.get(i).apply(parts[i].intern());
assignment = assignment.union(variables.get(i).outcomeArrayToAssignment(value));
}
// Check if the assignment is valid, if its not, then don't add it to the
// feature set
Preconditions.checkState(ignoreInvalidAssignments || allVars.isValidAssignment(assignment),
"Invalid assignment: %s", assignment);
if (!allVars.isValidAssignment(assignment)) {
continue;
}
double weight = Double.parseDouble(parts[numVars]);
builder.setWeight(assignment, weight);
}
return builder.build();
} | java | public static TableFactor fromDelimitedFile(List<VariableNumMap> variables,
List<? extends Function<String, ?>> inputConverters, Iterable<String> lines, String delimiter,
boolean ignoreInvalidAssignments, TensorFactory tensorFactory) {
int numVars = variables.size();
VariableNumMap allVars = VariableNumMap.unionAll(variables);
TableFactorBuilder builder = new TableFactorBuilder(allVars, tensorFactory);
for (String line : lines) {
// Ignore blank lines.
if (line.trim().length() == 0) {
continue;
}
String[] parts = line.split(delimiter);
Preconditions.checkState(parts.length == (numVars + 1), "\"%s\" is incorrectly formatted", line);
Assignment assignment = Assignment.EMPTY;
for (int i = 0; i < numVars; i++) {
Object value = inputConverters.get(i).apply(parts[i].intern());
assignment = assignment.union(variables.get(i).outcomeArrayToAssignment(value));
}
// Check if the assignment is valid, if its not, then don't add it to the
// feature set
Preconditions.checkState(ignoreInvalidAssignments || allVars.isValidAssignment(assignment),
"Invalid assignment: %s", assignment);
if (!allVars.isValidAssignment(assignment)) {
continue;
}
double weight = Double.parseDouble(parts[numVars]);
builder.setWeight(assignment, weight);
}
return builder.build();
} | [
"public",
"static",
"TableFactor",
"fromDelimitedFile",
"(",
"List",
"<",
"VariableNumMap",
">",
"variables",
",",
"List",
"<",
"?",
"extends",
"Function",
"<",
"String",
",",
"?",
">",
">",
"inputConverters",
",",
"Iterable",
"<",
"String",
">",
"lines",
",... | Gets a {@code TableFactor} from a series of lines, each describing a single
assignment. Each line is {@code delimiter}-separated, and its ith entry is
the value of the ith variable in {@code variables}. The last value on each
line is the weight.
@param variables
@param inputConverters
@param lines
@param delimiter
@param ignoreInvalidAssignments if {@code true}, lines representing invalid
assignments to {@code variables} are skipped. If {@code false}, an error is
thrown.
@param tensorFactory
@return | [
"Gets",
"a",
"{",
"@code",
"TableFactor",
"}",
"from",
"a",
"series",
"of",
"lines",
"each",
"describing",
"a",
"single",
"assignment",
".",
"Each",
"line",
"is",
"{",
"@code",
"delimiter",
"}",
"-",
"separated",
"and",
"its",
"ith",
"entry",
"is",
"the"... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/TableFactor.java#L161-L194 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryRegistrationService.java | DirectoryRegistrationService.registerService | public void registerService(ProvidedServiceInstance serviceInstance, ServiceInstanceHealth registryHealth) {
registerService(serviceInstance);
getCacheServiceInstances().put(new ServiceInstanceToken(serviceInstance.getServiceName(), serviceInstance.getProviderId()),
new InstanceHealthPair(registryHealth));
} | java | public void registerService(ProvidedServiceInstance serviceInstance, ServiceInstanceHealth registryHealth) {
registerService(serviceInstance);
getCacheServiceInstances().put(new ServiceInstanceToken(serviceInstance.getServiceName(), serviceInstance.getProviderId()),
new InstanceHealthPair(registryHealth));
} | [
"public",
"void",
"registerService",
"(",
"ProvidedServiceInstance",
"serviceInstance",
",",
"ServiceInstanceHealth",
"registryHealth",
")",
"{",
"registerService",
"(",
"serviceInstance",
")",
";",
"getCacheServiceInstances",
"(",
")",
".",
"put",
"(",
"new",
"ServiceI... | Register a ProvidedServiceInstance with the OperationalStatus and the ServiceInstanceHealth callback.
@param serviceInstance
the ProvidedServiceInstance.
@param registryHealth
the ServiceInstanceHealth callback. | [
"Register",
"a",
"ProvidedServiceInstance",
"with",
"the",
"OperationalStatus",
"and",
"the",
"ServiceInstanceHealth",
"callback",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryRegistrationService.java#L128-L132 |
rackerlabs/clouddocs-maven-plugin | src/main/java/com/rackspace/cloud/api/docs/GitHelper.java | GitHelper.addCommitProperties | public static boolean addCommitProperties(Transformer transformer, File baseDir, int abbrevLen, Log log) {
try {
RepositoryBuilder builder = new RepositoryBuilder();
Repository repository = builder.findGitDir(baseDir).readEnvironment().build();
ObjectId objectId = repository.resolve(Constants.HEAD);
if (objectId != null) {
transformer.setParameter("repository.commit", objectId.getName());
transformer.setParameter("repository.commit.short", objectId.abbreviate(abbrevLen).name());
return true;
} else {
log.warn("Could not determine current repository commit hash.");
return false;
}
} catch (IOException ex) {
log.warn("Could not determine current repository commit hash.", ex);
return false;
}
} | java | public static boolean addCommitProperties(Transformer transformer, File baseDir, int abbrevLen, Log log) {
try {
RepositoryBuilder builder = new RepositoryBuilder();
Repository repository = builder.findGitDir(baseDir).readEnvironment().build();
ObjectId objectId = repository.resolve(Constants.HEAD);
if (objectId != null) {
transformer.setParameter("repository.commit", objectId.getName());
transformer.setParameter("repository.commit.short", objectId.abbreviate(abbrevLen).name());
return true;
} else {
log.warn("Could not determine current repository commit hash.");
return false;
}
} catch (IOException ex) {
log.warn("Could not determine current repository commit hash.", ex);
return false;
}
} | [
"public",
"static",
"boolean",
"addCommitProperties",
"(",
"Transformer",
"transformer",
",",
"File",
"baseDir",
",",
"int",
"abbrevLen",
",",
"Log",
"log",
")",
"{",
"try",
"{",
"RepositoryBuilder",
"builder",
"=",
"new",
"RepositoryBuilder",
"(",
")",
";",
"... | Adds properties to the specified {@code transformer} for the current Git
commit hash. The following properties are added to {@code transformer}:
<ul>
<li>{@code repository.commit}: The full commit hash, in lowercase
hexadecimal form.</li>
<li>{@code repository.commit.short}: The abbreviated commit hash, which
is the first {@code abbrevLen} hexadecimal characters of the full commit
hash.</li>
</ul>
<p/>
If {@code baseDir} is not currently stored in a Git repository, or if the
current Git commit hash could not be determined, this method logs a
warning and returns {@code false}.
@param transformer The transformer.
@param baseDir The base directory where versioned files are contained.
@param abbrevLen The length of the abbreviated commit hash to create, in
number of hexadecimal characters.
@param log The Maven log instance.
@return {@code true} if the commit hash was identified and the properties
added to the {@code transformer}; otherwise, {@code false}. | [
"Adds",
"properties",
"to",
"the",
"specified",
"{",
"@code",
"transformer",
"}",
"for",
"the",
"current",
"Git",
"commit",
"hash",
".",
"The",
"following",
"properties",
"are",
"added",
"to",
"{",
"@code",
"transformer",
"}",
":",
"<ul",
">",
"<li",
">",
... | train | https://github.com/rackerlabs/clouddocs-maven-plugin/blob/ba8554dc340db674307efdaac647c6fd2b58a34b/src/main/java/com/rackspace/cloud/api/docs/GitHelper.java#L43-L60 |
AltBeacon/android-beacon-library | lib/src/main/java/org/altbeacon/beacon/BeaconManager.java | BeaconManager.enableForegroundServiceScanning | public void enableForegroundServiceScanning(Notification notification, int notificationId)
throws IllegalStateException {
if (isAnyConsumerBound()) {
throw new IllegalStateException("May not be called after consumers are already bound.");
}
if (notification == null) {
throw new NullPointerException("Notification cannot be null");
}
setEnableScheduledScanJobs(false);
mForegroundServiceNotification = notification;
mForegroundServiceNotificationId = notificationId;
} | java | public void enableForegroundServiceScanning(Notification notification, int notificationId)
throws IllegalStateException {
if (isAnyConsumerBound()) {
throw new IllegalStateException("May not be called after consumers are already bound.");
}
if (notification == null) {
throw new NullPointerException("Notification cannot be null");
}
setEnableScheduledScanJobs(false);
mForegroundServiceNotification = notification;
mForegroundServiceNotificationId = notificationId;
} | [
"public",
"void",
"enableForegroundServiceScanning",
"(",
"Notification",
"notification",
",",
"int",
"notificationId",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"isAnyConsumerBound",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"M... | Configures the library to use a foreground service for bacon scanning. This allows nearly
constant scanning on most Android versions to get around background limits, and displays an
icon to the user to indicate that the app is doing something in the background, even on
Android 8+. This will disable the user of the JobScheduler on Android 8 to do scans. Note
that this method does not by itself enable constant scanning. The scan intervals will work
as normal and must be configurd to specific values depending on how often you wish to scan.
@see #setForegroundScanPeriod(long)
@see #setForegroundBetweenScanPeriod(long)
This method requires a notification to display a message to the user about why the app is
scanning in the background. The notification must include an icon that will be displayed
in the top bar whenever the scanning service is running.
If the BeaconService is configured to run in a different process, this call will have no
effect.
@param notification - the notification that will be displayed when beacon scanning is active,
along with the icon that shows up in the status bar.
@throws IllegalStateException if called after consumers are already bound to the scanning
service | [
"Configures",
"the",
"library",
"to",
"use",
"a",
"foreground",
"service",
"for",
"bacon",
"scanning",
".",
"This",
"allows",
"nearly",
"constant",
"scanning",
"on",
"most",
"Android",
"versions",
"to",
"get",
"around",
"background",
"limits",
"and",
"displays",... | train | https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/BeaconManager.java#L1393-L1404 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/FileUtil.java | FileUtil.createNewFile | public static void createNewFile(@NonNull final File file, final boolean overwrite)
throws IOException {
Condition.INSTANCE.ensureNotNull(file, "The file may not be null");
boolean result = file.createNewFile();
if (!result) {
if (overwrite) {
try {
delete(file);
createNewFile(file, false);
} catch (IOException e) {
throw new IOException("Failed to overwrite file \"" + file + "\"");
}
} else if (file.exists()) {
throw new IOException("File \"" + file + "\" does already exist");
} else {
throw new IllegalArgumentException("The file must not be a directory");
}
}
} | java | public static void createNewFile(@NonNull final File file, final boolean overwrite)
throws IOException {
Condition.INSTANCE.ensureNotNull(file, "The file may not be null");
boolean result = file.createNewFile();
if (!result) {
if (overwrite) {
try {
delete(file);
createNewFile(file, false);
} catch (IOException e) {
throw new IOException("Failed to overwrite file \"" + file + "\"");
}
} else if (file.exists()) {
throw new IOException("File \"" + file + "\" does already exist");
} else {
throw new IllegalArgumentException("The file must not be a directory");
}
}
} | [
"public",
"static",
"void",
"createNewFile",
"(",
"@",
"NonNull",
"final",
"File",
"file",
",",
"final",
"boolean",
"overwrite",
")",
"throws",
"IOException",
"{",
"Condition",
".",
"INSTANCE",
".",
"ensureNotNull",
"(",
"file",
",",
"\"The file may not be null\""... | Creates a new, empty file.
@param file
The file, which should be created, as an instance of the class {@link File}. The file
may not be null. If the file is a directory, an {@link IllegalArgumentException} will
be thrown
@param overwrite
True, if the file should be overwritten, if it does already exist, false otherwise
@throws IOException
The exception, which is thrown, if an error occurs while creating the file | [
"Creates",
"a",
"new",
"empty",
"file",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/FileUtil.java#L162-L181 |
qspin/qtaste | kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java | TextUtilities.findWordStart | public static int findWordStart(String text, int pos, String noWordSep, boolean joinNonWordChars) {
return findWordStart(text, pos, noWordSep, joinNonWordChars, false);
} | java | public static int findWordStart(String text, int pos, String noWordSep, boolean joinNonWordChars) {
return findWordStart(text, pos, noWordSep, joinNonWordChars, false);
} | [
"public",
"static",
"int",
"findWordStart",
"(",
"String",
"text",
",",
"int",
"pos",
",",
"String",
"noWordSep",
",",
"boolean",
"joinNonWordChars",
")",
"{",
"return",
"findWordStart",
"(",
"text",
",",
"pos",
",",
"noWordSep",
",",
"joinNonWordChars",
",",
... | Locates the start of the word at the specified position.
@param text the text
@param pos The position
@param noWordSep Characters that are non-alphanumeric, but
should be treated as word characters anyway
@param joinNonWordChars Treat consecutive non-alphanumeric
characters as one word | [
"Locates",
"the",
"start",
"of",
"the",
"word",
"at",
"the",
"specified",
"position",
"."
] | train | https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java#L48-L50 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java | ReflectionUtils.getGenericClassType | public static Type getGenericClassType(Class clazz, Class filterClass)
{
for (Type type : clazz.getGenericInterfaces()) {
if (type == filterClass) {
return type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
if (filterClass.isAssignableFrom((Class) pType.getRawType())) {
return type;
}
}
}
return null;
} | java | public static Type getGenericClassType(Class clazz, Class filterClass)
{
for (Type type : clazz.getGenericInterfaces()) {
if (type == filterClass) {
return type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
if (filterClass.isAssignableFrom((Class) pType.getRawType())) {
return type;
}
}
}
return null;
} | [
"public",
"static",
"Type",
"getGenericClassType",
"(",
"Class",
"clazz",
",",
"Class",
"filterClass",
")",
"{",
"for",
"(",
"Type",
"type",
":",
"clazz",
".",
"getGenericInterfaces",
"(",
")",
")",
"{",
"if",
"(",
"type",
"==",
"filterClass",
")",
"{",
... | Extract the real Type from the passed class. For example
<tt>public Class MyClass implements FilterClass<A, B>, SomeOtherClass<C></tt> will return
<tt>FilterClass<A, B>, SomeOtherClass<C></tt>.
@param clazz the class to extract from
@param filterClass the class of the generic type we're looking for
@return the real Type from the interfaces of the passed class, filtered by the passed filter class
@since 4.0M1 | [
"Extract",
"the",
"real",
"Type",
"from",
"the",
"passed",
"class",
".",
"For",
"example",
"<tt",
">",
"public",
"Class",
"MyClass",
"implements",
"FilterClass<",
";",
"A",
"B>",
";",
"SomeOtherClass<",
";",
"C>",
";",
"<",
"/",
"tt",
">",
"will",
... | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java#L267-L281 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/content/CmsPropertyDelete.java | CmsPropertyDelete.actionDelete | public void actionDelete() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
getCms().deletePropertyDefinition(getParamPropertyName());
// close the dialog
actionCloseDialog();
} catch (Throwable e) {
// error while deleting property definition, show error dialog
includeErrorpage(this, e);
}
} | java | public void actionDelete() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
getCms().deletePropertyDefinition(getParamPropertyName());
// close the dialog
actionCloseDialog();
} catch (Throwable e) {
// error while deleting property definition, show error dialog
includeErrorpage(this, e);
}
} | [
"public",
"void",
"actionDelete",
"(",
")",
"throws",
"JspException",
"{",
"// save initialized instance of this class in request attribute for included sub-elements",
"getJsp",
"(",
")",
".",
"getRequest",
"(",
")",
".",
"setAttribute",
"(",
"SESSION_WORKPLACE_CLASS",
",",
... | Deletes the property definition.<p>
@throws JspException if problems including sub-elements occur | [
"Deletes",
"the",
"property",
"definition",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/content/CmsPropertyDelete.java#L101-L113 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/Splitter.java | Splitter.split | public int split(T obj, int start, int length) throws IOException
{
int count = 0;
if (length > 0)
{
int end = (start + length) % size;
if (start < end)
{
count = op(obj, start, end);
}
else
{
if (end > 0)
{
count = op(obj, start, size, 0, end);
}
else
{
count = op(obj, start, size);
}
}
}
assert count <= length;
return count;
} | java | public int split(T obj, int start, int length) throws IOException
{
int count = 0;
if (length > 0)
{
int end = (start + length) % size;
if (start < end)
{
count = op(obj, start, end);
}
else
{
if (end > 0)
{
count = op(obj, start, size, 0, end);
}
else
{
count = op(obj, start, size);
}
}
}
assert count <= length;
return count;
} | [
"public",
"int",
"split",
"(",
"T",
"obj",
",",
"int",
"start",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"int",
"count",
"=",
"0",
";",
"if",
"(",
"length",
">",
"0",
")",
"{",
"int",
"end",
"=",
"(",
"start",
"+",
"length",
")",
... | Calls either of two op methods depending on start + length > size. If so
calls op with 5 parameters, otherwise op with 3 parameters.
@param obj
@param start
@param length
@return
@throws IOException | [
"Calls",
"either",
"of",
"two",
"op",
"methods",
"depending",
"on",
"start",
"+",
"length",
">",
"size",
".",
"If",
"so",
"calls",
"op",
"with",
"5",
"parameters",
"otherwise",
"op",
"with",
"3",
"parameters",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/Splitter.java#L47-L71 |
jbundle/jbundle | model/base/src/main/java/org/jbundle/model/util/Util.java | Util.getPackageName | public static String getPackageName(String className, boolean resource)
{
String packageName = null;
if (className != null)
{
if (resource)
if (className.endsWith(PROPERTIES))
className = className.substring(0, className.length() - PROPERTIES.length());
if (className.lastIndexOf('.') != -1)
packageName = className.substring(0, className.lastIndexOf('.'));
}
return packageName;
} | java | public static String getPackageName(String className, boolean resource)
{
String packageName = null;
if (className != null)
{
if (resource)
if (className.endsWith(PROPERTIES))
className = className.substring(0, className.length() - PROPERTIES.length());
if (className.lastIndexOf('.') != -1)
packageName = className.substring(0, className.lastIndexOf('.'));
}
return packageName;
} | [
"public",
"static",
"String",
"getPackageName",
"(",
"String",
"className",
",",
"boolean",
"resource",
")",
"{",
"String",
"packageName",
"=",
"null",
";",
"if",
"(",
"className",
"!=",
"null",
")",
"{",
"if",
"(",
"resource",
")",
"if",
"(",
"className",... | Get the package name of this class name
@param className
@return | [
"Get",
"the",
"package",
"name",
"of",
"this",
"class",
"name"
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/model/base/src/main/java/org/jbundle/model/util/Util.java#L553-L565 |
ops4j/org.ops4j.base | ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java | ResourceManager.getBaseResources | public static Resources getBaseResources( String baseName, Locale locale, ClassLoader classLoader )
{
synchronized( ResourceManager.class )
{
Resources resources = getCachedResource( baseName + "_" + locale.hashCode() );
if( null == resources )
{
resources = new Resources( baseName, locale, classLoader );
putCachedResource( baseName + "_" + locale.hashCode(), resources );
}
return resources;
}
} | java | public static Resources getBaseResources( String baseName, Locale locale, ClassLoader classLoader )
{
synchronized( ResourceManager.class )
{
Resources resources = getCachedResource( baseName + "_" + locale.hashCode() );
if( null == resources )
{
resources = new Resources( baseName, locale, classLoader );
putCachedResource( baseName + "_" + locale.hashCode(), resources );
}
return resources;
}
} | [
"public",
"static",
"Resources",
"getBaseResources",
"(",
"String",
"baseName",
",",
"Locale",
"locale",
",",
"ClassLoader",
"classLoader",
")",
"{",
"synchronized",
"(",
"ResourceManager",
".",
"class",
")",
"{",
"Resources",
"resources",
"=",
"getCachedResource",
... | Retrieve resource with specified basename.
@param baseName the basename
@param classLoader the classLoader to load resources from
@param locale the locale of the resources requested.
@return the Resources | [
"Retrieve",
"resource",
"with",
"specified",
"basename",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java#L96-L108 |
spring-projects/spring-social | spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java | OAuth2Template.getIntegerValue | private Long getIntegerValue(Map<String, Object> map, String key) {
try {
return Long.valueOf(String.valueOf(map.get(key))); // normalize to String before creating integer value;
} catch (NumberFormatException e) {
return null;
}
} | java | private Long getIntegerValue(Map<String, Object> map, String key) {
try {
return Long.valueOf(String.valueOf(map.get(key))); // normalize to String before creating integer value;
} catch (NumberFormatException e) {
return null;
}
} | [
"private",
"Long",
"getIntegerValue",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"String",
"key",
")",
"{",
"try",
"{",
"return",
"Long",
".",
"valueOf",
"(",
"String",
".",
"valueOf",
"(",
"map",
".",
"get",
"(",
"key",
")",
")",
"... | Retrieves object from map into an Integer, regardless of the object's actual type. Allows for flexibility in object type (eg, "3600" vs 3600). | [
"Retrieves",
"object",
"from",
"map",
"into",
"an",
"Integer",
"regardless",
"of",
"the",
"object",
"s",
"actual",
"type",
".",
"Allows",
"for",
"flexibility",
"in",
"object",
"type",
"(",
"eg",
"3600",
"vs",
"3600",
")",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java#L313-L319 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/utilities/StreamUtility.java | StreamUtility.pipeStream | public static void pipeStream(InputStream in, OutputStream out, int bufSize)
throws IOException {
try {
byte[] buf = new byte[bufSize];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
logger.warn("Unable to close stream", e);
}
}
} | java | public static void pipeStream(InputStream in, OutputStream out, int bufSize)
throws IOException {
try {
byte[] buf = new byte[bufSize];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
logger.warn("Unable to close stream", e);
}
}
} | [
"public",
"static",
"void",
"pipeStream",
"(",
"InputStream",
"in",
",",
"OutputStream",
"out",
",",
"int",
"bufSize",
")",
"throws",
"IOException",
"{",
"try",
"{",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"bufSize",
"]",
";",
"int",
"len",
"... | Copies the contents of an InputStream to an OutputStream, then closes
both.
@param in
The source stream.
@param out
The target stream.
@param bufSize
Number of bytes to attempt to copy at a time.
@throws IOException
If any sort of read/write error occurs on either stream. | [
"Copies",
"the",
"contents",
"of",
"an",
"InputStream",
"to",
"an",
"OutputStream",
"then",
"closes",
"both",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/utilities/StreamUtility.java#L250-L266 |
lucee/Lucee | core/src/main/java/lucee/commons/io/SystemUtil.java | SystemUtil.getSystemPropOrEnvVar | public static String getSystemPropOrEnvVar(String name, String defaultValue) {
// env
String value = System.getenv(name);
if (!StringUtil.isEmpty(value)) return value;
// prop
value = System.getProperty(name);
if (!StringUtil.isEmpty(value)) return value;
// env 2
name = convertSystemPropToEnvVar(name);
value = System.getenv(name);
if (!StringUtil.isEmpty(value)) return value;
return defaultValue;
} | java | public static String getSystemPropOrEnvVar(String name, String defaultValue) {
// env
String value = System.getenv(name);
if (!StringUtil.isEmpty(value)) return value;
// prop
value = System.getProperty(name);
if (!StringUtil.isEmpty(value)) return value;
// env 2
name = convertSystemPropToEnvVar(name);
value = System.getenv(name);
if (!StringUtil.isEmpty(value)) return value;
return defaultValue;
} | [
"public",
"static",
"String",
"getSystemPropOrEnvVar",
"(",
"String",
"name",
",",
"String",
"defaultValue",
")",
"{",
"// env",
"String",
"value",
"=",
"System",
".",
"getenv",
"(",
"name",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isEmpty",
"(",
"val... | returns a system setting by either a Java property name or a System environment variable
@param name - either a lowercased Java property name (e.g. lucee.controller.disabled) or an
UPPERCASED Environment variable name ((e.g. LUCEE_CONTROLLER_DISABLED))
@param defaultValue - value to return if the neither the property nor the environment setting was
found
@return - the value of the property referenced by propOrEnv or the defaultValue if not found | [
"returns",
"a",
"system",
"setting",
"by",
"either",
"a",
"Java",
"property",
"name",
"or",
"a",
"System",
"environment",
"variable"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/SystemUtil.java#L1165-L1180 |
padrig64/ValidationFramework | validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/utils/IconUtils.java | IconUtils.loadImageIcon | public static ImageIcon loadImageIcon(final String iconName, final Class<?> clazz) {
ImageIcon icon = null;
if (iconName != null) {
final URL iconResource = clazz.getResource(iconName);
if (iconResource == null) {
LOGGER.error("Icon could not be loaded: '" + iconName);
icon = null;
} else {
icon = new ImageIcon(iconResource);
}
}
return icon;
} | java | public static ImageIcon loadImageIcon(final String iconName, final Class<?> clazz) {
ImageIcon icon = null;
if (iconName != null) {
final URL iconResource = clazz.getResource(iconName);
if (iconResource == null) {
LOGGER.error("Icon could not be loaded: '" + iconName);
icon = null;
} else {
icon = new ImageIcon(iconResource);
}
}
return icon;
} | [
"public",
"static",
"ImageIcon",
"loadImageIcon",
"(",
"final",
"String",
"iconName",
",",
"final",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"ImageIcon",
"icon",
"=",
"null",
";",
"if",
"(",
"iconName",
"!=",
"null",
")",
"{",
"final",
"URL",
"iconReso... | Loads an image icon from a resource file.
@param iconName Name of the resource file to be loaded.
@param clazz Class for which the resource exists.
@return Image icon if it could be loaded, null otherwise. | [
"Loads",
"an",
"image",
"icon",
"from",
"a",
"resource",
"file",
"."
] | train | https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-swing/src/main/java/com/google/code/validationframework/swing/decoration/utils/IconUtils.java#L68-L82 |
looly/hutool | hutool-http/src/main/java/cn/hutool/http/HttpUtil.java | HttpUtil.downloadString | public static String downloadString(String url, Charset customCharset) {
return downloadString(url, customCharset, null);
} | java | public static String downloadString(String url, Charset customCharset) {
return downloadString(url, customCharset, null);
} | [
"public",
"static",
"String",
"downloadString",
"(",
"String",
"url",
",",
"Charset",
"customCharset",
")",
"{",
"return",
"downloadString",
"(",
"url",
",",
"customCharset",
",",
"null",
")",
";",
"}"
] | 下载远程文本
@param url 请求的url
@param customCharset 自定义的字符集,可以使用{@link CharsetUtil#charset} 方法转换
@return 文本 | [
"下载远程文本"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpUtil.java#L225-L227 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/Util.java | Util.mixHashCodes | public static int mixHashCodes(int hash1, int hash2, int hash3) {
long result = hash1 * HASHPRIME + hash2;
return (int) (result * HASHPRIME + hash3);
} | java | public static int mixHashCodes(int hash1, int hash2, int hash3) {
long result = hash1 * HASHPRIME + hash2;
return (int) (result * HASHPRIME + hash3);
} | [
"public",
"static",
"int",
"mixHashCodes",
"(",
"int",
"hash1",
",",
"int",
"hash2",
",",
"int",
"hash3",
")",
"{",
"long",
"result",
"=",
"hash1",
"*",
"HASHPRIME",
"+",
"hash2",
";",
"return",
"(",
"int",
")",
"(",
"result",
"*",
"HASHPRIME",
"+",
... | Mix multiple hashcodes into one.
@param hash1 First hashcode to mix
@param hash2 Second hashcode to mix
@param hash3 Third hashcode to mix
@return Mixed hash code | [
"Mix",
"multiple",
"hashcodes",
"into",
"one",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/Util.java#L64-L67 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/Socks4Message.java | Socks4Message.getString | private String getString(int offset, int maxLength) {
int index = offset;
int lastIndex = index + maxLength;
while (index < lastIndex && (buffer[index] != 0)) {
index++;
}
return new String(buffer, offset, index - offset, StandardCharsets.ISO_8859_1);
} | java | private String getString(int offset, int maxLength) {
int index = offset;
int lastIndex = index + maxLength;
while (index < lastIndex && (buffer[index] != 0)) {
index++;
}
return new String(buffer, offset, index - offset, StandardCharsets.ISO_8859_1);
} | [
"private",
"String",
"getString",
"(",
"int",
"offset",
",",
"int",
"maxLength",
")",
"{",
"int",
"index",
"=",
"offset",
";",
"int",
"lastIndex",
"=",
"index",
"+",
"maxLength",
";",
"while",
"(",
"index",
"<",
"lastIndex",
"&&",
"(",
"buffer",
"[",
"... | Get a String from the buffer at the offset given. The method reads until
it encounters a null value or reaches the maxLength given. | [
"Get",
"a",
"String",
"from",
"the",
"buffer",
"at",
"the",
"offset",
"given",
".",
"The",
"method",
"reads",
"until",
"it",
"encounters",
"a",
"null",
"value",
"or",
"reaches",
"the",
"maxLength",
"given",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/Socks4Message.java#L185-L192 |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/JMessageClient.java | JMessageClient.v2GetUserMessagesByCursor | public MessageListResult v2GetUserMessagesByCursor(String username, String cursor)
throws APIConnectionException, APIRequestException {
return _reportClient.v2GetUserMessagesByCursor(username, cursor);
} | java | public MessageListResult v2GetUserMessagesByCursor(String username, String cursor)
throws APIConnectionException, APIRequestException {
return _reportClient.v2GetUserMessagesByCursor(username, cursor);
} | [
"public",
"MessageListResult",
"v2GetUserMessagesByCursor",
"(",
"String",
"username",
",",
"String",
"cursor",
")",
"throws",
"APIConnectionException",
",",
"APIRequestException",
"{",
"return",
"_reportClient",
".",
"v2GetUserMessagesByCursor",
"(",
"username",
",",
"cu... | Get user's message list with cursor, the cursor will effective in 120 seconds.
And will return same count of messages as first request.
@param username Necessary parameter.
@param cursor First request will return cursor
@return MessageListResult
@throws APIConnectionException connect exception
@throws APIRequestException request exception | [
"Get",
"user",
"s",
"message",
"list",
"with",
"cursor",
"the",
"cursor",
"will",
"effective",
"in",
"120",
"seconds",
".",
"And",
"will",
"return",
"same",
"count",
"of",
"messages",
"as",
"first",
"request",
"."
] | train | https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/JMessageClient.java#L982-L985 |
alkacon/opencms-core | src/org/opencms/ade/configuration/CmsADEManager.java | CmsADEManager.internalLookupConfiguration | protected CmsADEConfigData internalLookupConfiguration(CmsObject cms, String rootPath) {
boolean online = (null == cms) || isOnline(cms);
CmsADEConfigCacheState state = getCacheState(online);
return state.lookupConfiguration(rootPath);
} | java | protected CmsADEConfigData internalLookupConfiguration(CmsObject cms, String rootPath) {
boolean online = (null == cms) || isOnline(cms);
CmsADEConfigCacheState state = getCacheState(online);
return state.lookupConfiguration(rootPath);
} | [
"protected",
"CmsADEConfigData",
"internalLookupConfiguration",
"(",
"CmsObject",
"cms",
",",
"String",
"rootPath",
")",
"{",
"boolean",
"online",
"=",
"(",
"null",
"==",
"cms",
")",
"||",
"isOnline",
"(",
"cms",
")",
";",
"CmsADEConfigCacheState",
"state",
"=",... | Internal configuration lookup method.<p>
@param cms the cms context
@param rootPath the root path for which to look up the configuration
@return the configuration for the given path | [
"Internal",
"configuration",
"lookup",
"method",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L1457-L1462 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/Expression.java | Expression.asIterator | public DTMIterator asIterator(XPathContext xctxt, int contextNode)
throws javax.xml.transform.TransformerException
{
try
{
xctxt.pushCurrentNodeAndExpression(contextNode, contextNode);
return execute(xctxt).iter();
}
finally
{
xctxt.popCurrentNodeAndExpression();
}
} | java | public DTMIterator asIterator(XPathContext xctxt, int contextNode)
throws javax.xml.transform.TransformerException
{
try
{
xctxt.pushCurrentNodeAndExpression(contextNode, contextNode);
return execute(xctxt).iter();
}
finally
{
xctxt.popCurrentNodeAndExpression();
}
} | [
"public",
"DTMIterator",
"asIterator",
"(",
"XPathContext",
"xctxt",
",",
"int",
"contextNode",
")",
"throws",
"javax",
".",
"xml",
".",
"transform",
".",
"TransformerException",
"{",
"try",
"{",
"xctxt",
".",
"pushCurrentNodeAndExpression",
"(",
"contextNode",
",... | Given an select expression and a context, evaluate the XPath
and return the resulting iterator.
@param xctxt The execution context.
@param contextNode The node that "." expresses.
@return A valid DTMIterator.
@throws TransformerException thrown if the active ProblemListener decides
the error condition is severe enough to halt processing.
@throws javax.xml.transform.TransformerException
@xsl.usage experimental | [
"Given",
"an",
"select",
"expression",
"and",
"a",
"context",
"evaluate",
"the",
"XPath",
"and",
"return",
"the",
"resulting",
"iterator",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/Expression.java#L244-L258 |
Alexey1Gavrilov/ExpectIt | expectit-core/src/main/java/net/sf/expectit/filter/Filters.java | Filters.replaceInBuffer | public static Filter replaceInBuffer(final String regexp, final String replacement) {
return replaceInBuffer(Pattern.compile(regexp), replacement);
} | java | public static Filter replaceInBuffer(final String regexp, final String replacement) {
return replaceInBuffer(Pattern.compile(regexp), replacement);
} | [
"public",
"static",
"Filter",
"replaceInBuffer",
"(",
"final",
"String",
"regexp",
",",
"final",
"String",
"replacement",
")",
"{",
"return",
"replaceInBuffer",
"(",
"Pattern",
".",
"compile",
"(",
"regexp",
")",
",",
"replacement",
")",
";",
"}"
] | Equivalent to {@link #replaceInBuffer(java.util.regex.Pattern,
String)} but takes the regular expression
as string.
@param regexp the regular expression
@param replacement the string to be substituted for each match
@return the filter | [
"Equivalent",
"to",
"{",
"@link",
"#replaceInBuffer",
"(",
"java",
".",
"util",
".",
"regex",
".",
"Pattern",
"String",
")",
"}",
"but",
"takes",
"the",
"regular",
"expression",
"as",
"string",
"."
] | train | https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-core/src/main/java/net/sf/expectit/filter/Filters.java#L151-L153 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-store/xwiki-commons-crypto-store-filesystem/src/main/java/org/xwiki/crypto/store/filesystem/internal/AbstractX509FileSystemStore.java | AbstractX509FileSystemStore.writeFooter | private static void writeFooter(BufferedWriter out, String type) throws IOException
{
out.write(PEM_END + type + DASHES);
out.newLine();
} | java | private static void writeFooter(BufferedWriter out, String type) throws IOException
{
out.write(PEM_END + type + DASHES);
out.newLine();
} | [
"private",
"static",
"void",
"writeFooter",
"(",
"BufferedWriter",
"out",
",",
"String",
"type",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"PEM_END",
"+",
"type",
"+",
"DASHES",
")",
";",
"out",
".",
"newLine",
"(",
")",
";",
"}"
] | Write a PEM like footer.
@param out the output buffered writer to write to.
@param type the type to be written in the footer.
@throws IOException on error. | [
"Write",
"a",
"PEM",
"like",
"footer",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-store/xwiki-commons-crypto-store-filesystem/src/main/java/org/xwiki/crypto/store/filesystem/internal/AbstractX509FileSystemStore.java#L130-L134 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nstrafficdomain_binding.java | nstrafficdomain_binding.get | public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{
nstrafficdomain_binding obj = new nstrafficdomain_binding();
obj.set_td(td);
nstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);
return response;
} | java | public static nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{
nstrafficdomain_binding obj = new nstrafficdomain_binding();
obj.set_td(td);
nstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"nstrafficdomain_binding",
"get",
"(",
"nitro_service",
"service",
",",
"Long",
"td",
")",
"throws",
"Exception",
"{",
"nstrafficdomain_binding",
"obj",
"=",
"new",
"nstrafficdomain_binding",
"(",
")",
";",
"obj",
".",
"set_td",
"(",
"td",
")... | Use this API to fetch nstrafficdomain_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"nstrafficdomain_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nstrafficdomain_binding.java#L126-L131 |
sporniket/core | sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/NodeListProcessor.java | NodeListProcessor.addProcessor | public void addProcessor(String nodeName, NodeProcessor processor)
{
if (null == processor)
{
throw new IllegalArgumentException("Processor should not be null.");
}
if (IS_EMPTY.test(nodeName))
{
throw new IllegalArgumentException("The node name should not be empty.");
}
getActionPool().put(nodeName, processor);
} | java | public void addProcessor(String nodeName, NodeProcessor processor)
{
if (null == processor)
{
throw new IllegalArgumentException("Processor should not be null.");
}
if (IS_EMPTY.test(nodeName))
{
throw new IllegalArgumentException("The node name should not be empty.");
}
getActionPool().put(nodeName, processor);
} | [
"public",
"void",
"addProcessor",
"(",
"String",
"nodeName",
",",
"NodeProcessor",
"processor",
")",
"{",
"if",
"(",
"null",
"==",
"processor",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Processor should not be null.\"",
")",
";",
"}",
"if",
"... | Add a specific processing that will be applied to nodes having the matching name.
@param nodeName
the name of nodes that will be processed.
@param processor
the processor. | [
"Add",
"a",
"specific",
"processing",
"that",
"will",
"be",
"applied",
"to",
"nodes",
"having",
"the",
"matching",
"name",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ml/src/main/java/com/sporniket/libre/lang/xml/NodeListProcessor.java#L120-L131 |
alkacon/opencms-core | src/org/opencms/search/CmsSearchManager.java | CmsSearchManager.updateIndex | protected void updateIndex(I_CmsSearchIndex index, I_CmsReport report, List<CmsPublishedResource> resourcesToIndex)
throws CmsException {
if (shouldUpdateAtAll(index)) {
try {
SEARCH_MANAGER_LOCK.lock();
// copy the stored admin context for the indexing
CmsObject cms = OpenCms.initCmsObject(m_adminCms);
// make sure a report is available
if (report == null) {
report = new CmsLogReport(cms.getRequestContext().getLocale(), CmsSearchManager.class);
}
// check if the index has been configured correctly
if (!index.checkConfiguration(cms)) {
// the index is disabled
return;
}
// set site root and project for this index
cms.getRequestContext().setSiteRoot("/");
// switch to the index project
cms.getRequestContext().setCurrentProject(cms.readProject(index.getProject()));
if ((resourcesToIndex == null) || resourcesToIndex.isEmpty()) {
// rebuild the complete index
updateIndexCompletely(cms, index, report);
} else {
updateIndexIncremental(cms, index, report, resourcesToIndex);
}
} finally {
SEARCH_MANAGER_LOCK.unlock();
}
}
} | java | protected void updateIndex(I_CmsSearchIndex index, I_CmsReport report, List<CmsPublishedResource> resourcesToIndex)
throws CmsException {
if (shouldUpdateAtAll(index)) {
try {
SEARCH_MANAGER_LOCK.lock();
// copy the stored admin context for the indexing
CmsObject cms = OpenCms.initCmsObject(m_adminCms);
// make sure a report is available
if (report == null) {
report = new CmsLogReport(cms.getRequestContext().getLocale(), CmsSearchManager.class);
}
// check if the index has been configured correctly
if (!index.checkConfiguration(cms)) {
// the index is disabled
return;
}
// set site root and project for this index
cms.getRequestContext().setSiteRoot("/");
// switch to the index project
cms.getRequestContext().setCurrentProject(cms.readProject(index.getProject()));
if ((resourcesToIndex == null) || resourcesToIndex.isEmpty()) {
// rebuild the complete index
updateIndexCompletely(cms, index, report);
} else {
updateIndexIncremental(cms, index, report, resourcesToIndex);
}
} finally {
SEARCH_MANAGER_LOCK.unlock();
}
}
} | [
"protected",
"void",
"updateIndex",
"(",
"I_CmsSearchIndex",
"index",
",",
"I_CmsReport",
"report",
",",
"List",
"<",
"CmsPublishedResource",
">",
"resourcesToIndex",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"shouldUpdateAtAll",
"(",
"index",
")",
")",
"{",
... | Updates (if required creates) the index with the given name.<p>
If the optional List of <code>{@link CmsPublishedResource}</code> instances is provided, the index will be
incrementally updated for these resources only. If this List is <code>null</code> or empty,
the index will be fully rebuild.<p>
@param index the index to update or rebuild
@param report the report to write output messages to
@param resourcesToIndex an (optional) list of <code>{@link CmsPublishedResource}</code> objects to update in the index
@throws CmsException if something goes wrong | [
"Updates",
"(",
"if",
"required",
"creates",
")",
"the",
"index",
"with",
"the",
"given",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchManager.java#L2766-L2802 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java | MultiUserChat.createOrJoinIfNecessary | public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException,
XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
if (isJoined()) {
return null;
}
MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword(
password).build();
try {
return createOrJoin(mucEnterConfiguration);
}
catch (MucAlreadyJoinedException e) {
return null;
}
} | java | public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException,
XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
if (isJoined()) {
return null;
}
MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword(
password).build();
try {
return createOrJoin(mucEnterConfiguration);
}
catch (MucAlreadyJoinedException e) {
return null;
}
} | [
"public",
"MucCreateConfigFormHandle",
"createOrJoinIfNecessary",
"(",
"Resourcepart",
"nickname",
",",
"String",
"password",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
",",
"NotAMucServiceExceptio... | Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined.
@param nickname the required nickname to use.
@param password the optional password required to join
@return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException
@throws NotAMucServiceException | [
"Create",
"or",
"join",
"a",
"MUC",
"if",
"it",
"is",
"necessary",
"i",
".",
"e",
".",
"if",
"not",
"the",
"MUC",
"is",
"not",
"already",
"joined",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/muc/MultiUserChat.java#L582-L595 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java | BingVideosImpl.detailsWithServiceResponseAsync | public Observable<ServiceResponse<VideoDetails>> detailsWithServiceResponseAsync(String query, DetailsOptionalParameter detailsOptionalParameter) {
if (query == null) {
throw new IllegalArgumentException("Parameter query is required and cannot be null.");
}
final String acceptLanguage = detailsOptionalParameter != null ? detailsOptionalParameter.acceptLanguage() : null;
final String userAgent = detailsOptionalParameter != null ? detailsOptionalParameter.userAgent() : this.client.userAgent();
final String clientId = detailsOptionalParameter != null ? detailsOptionalParameter.clientId() : null;
final String clientIp = detailsOptionalParameter != null ? detailsOptionalParameter.clientIp() : null;
final String location = detailsOptionalParameter != null ? detailsOptionalParameter.location() : null;
final String countryCode = detailsOptionalParameter != null ? detailsOptionalParameter.countryCode() : null;
final String id = detailsOptionalParameter != null ? detailsOptionalParameter.id() : null;
final List<VideoInsightModule> modules = detailsOptionalParameter != null ? detailsOptionalParameter.modules() : null;
final String market = detailsOptionalParameter != null ? detailsOptionalParameter.market() : null;
final VideoResolution resolution = detailsOptionalParameter != null ? detailsOptionalParameter.resolution() : null;
final SafeSearch safeSearch = detailsOptionalParameter != null ? detailsOptionalParameter.safeSearch() : null;
final String setLang = detailsOptionalParameter != null ? detailsOptionalParameter.setLang() : null;
final Boolean textDecorations = detailsOptionalParameter != null ? detailsOptionalParameter.textDecorations() : null;
final TextFormat textFormat = detailsOptionalParameter != null ? detailsOptionalParameter.textFormat() : null;
return detailsWithServiceResponseAsync(query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, id, modules, market, resolution, safeSearch, setLang, textDecorations, textFormat);
} | java | public Observable<ServiceResponse<VideoDetails>> detailsWithServiceResponseAsync(String query, DetailsOptionalParameter detailsOptionalParameter) {
if (query == null) {
throw new IllegalArgumentException("Parameter query is required and cannot be null.");
}
final String acceptLanguage = detailsOptionalParameter != null ? detailsOptionalParameter.acceptLanguage() : null;
final String userAgent = detailsOptionalParameter != null ? detailsOptionalParameter.userAgent() : this.client.userAgent();
final String clientId = detailsOptionalParameter != null ? detailsOptionalParameter.clientId() : null;
final String clientIp = detailsOptionalParameter != null ? detailsOptionalParameter.clientIp() : null;
final String location = detailsOptionalParameter != null ? detailsOptionalParameter.location() : null;
final String countryCode = detailsOptionalParameter != null ? detailsOptionalParameter.countryCode() : null;
final String id = detailsOptionalParameter != null ? detailsOptionalParameter.id() : null;
final List<VideoInsightModule> modules = detailsOptionalParameter != null ? detailsOptionalParameter.modules() : null;
final String market = detailsOptionalParameter != null ? detailsOptionalParameter.market() : null;
final VideoResolution resolution = detailsOptionalParameter != null ? detailsOptionalParameter.resolution() : null;
final SafeSearch safeSearch = detailsOptionalParameter != null ? detailsOptionalParameter.safeSearch() : null;
final String setLang = detailsOptionalParameter != null ? detailsOptionalParameter.setLang() : null;
final Boolean textDecorations = detailsOptionalParameter != null ? detailsOptionalParameter.textDecorations() : null;
final TextFormat textFormat = detailsOptionalParameter != null ? detailsOptionalParameter.textFormat() : null;
return detailsWithServiceResponseAsync(query, acceptLanguage, userAgent, clientId, clientIp, location, countryCode, id, modules, market, resolution, safeSearch, setLang, textDecorations, textFormat);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"VideoDetails",
">",
">",
"detailsWithServiceResponseAsync",
"(",
"String",
"query",
",",
"DetailsOptionalParameter",
"detailsOptionalParameter",
")",
"{",
"if",
"(",
"query",
"==",
"null",
")",
"{",
"throw",
"new... | The Video Detail Search API lets you search on Bing and get back insights about a video, such as related videos. This section provides technical details about the query parameters and headers that you use to request insights of videos and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the Web for Videos](https://docs.microsoft.com/azure/cognitive-services/bing-video-search/search-the-web).
@param query The user's search query string. The query string cannot be empty. The query string may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit videos to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. Use this parameter only with the Video Search API. Do not specify this parameter when calling the Trending Videos API.
@param detailsOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VideoDetails object | [
"The",
"Video",
"Detail",
"Search",
"API",
"lets",
"you",
"search",
"on",
"Bing",
"and",
"get",
"back",
"insights",
"about",
"a",
"video",
"such",
"as",
"related",
"videos",
".",
"This",
"section",
"provides",
"technical",
"details",
"about",
"the",
"query",... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java#L435-L455 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java | HttpFields.putDateField | public void putDateField(String name, long date)
{
if (_dateBuffer==null)
{
_dateBuffer=new StringBuffer(32);
_calendar=new HttpCal();
}
_dateBuffer.setLength(0);
_calendar.setTimeInMillis(date);
formatDate(_dateBuffer, _calendar, false);
put(name, _dateBuffer.toString());
} | java | public void putDateField(String name, long date)
{
if (_dateBuffer==null)
{
_dateBuffer=new StringBuffer(32);
_calendar=new HttpCal();
}
_dateBuffer.setLength(0);
_calendar.setTimeInMillis(date);
formatDate(_dateBuffer, _calendar, false);
put(name, _dateBuffer.toString());
} | [
"public",
"void",
"putDateField",
"(",
"String",
"name",
",",
"long",
"date",
")",
"{",
"if",
"(",
"_dateBuffer",
"==",
"null",
")",
"{",
"_dateBuffer",
"=",
"new",
"StringBuffer",
"(",
"32",
")",
";",
"_calendar",
"=",
"new",
"HttpCal",
"(",
")",
";",... | Sets the value of a date field.
@param name the field name
@param date the field date value | [
"Sets",
"the",
"value",
"of",
"a",
"date",
"field",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java#L1082-L1093 |
j256/ormlite-jdbc | src/main/java/com/j256/ormlite/jdbc/JdbcConnectionSource.java | JdbcConnectionSource.makeConnection | @SuppressWarnings("resource")
protected DatabaseConnection makeConnection(Logger logger) throws SQLException {
Properties properties = new Properties();
if (username != null) {
properties.setProperty("user", username);
}
if (password != null) {
properties.setProperty("password", password);
}
DatabaseConnection connection = new JdbcDatabaseConnection(DriverManager.getConnection(url, properties));
// by default auto-commit is set to true
connection.setAutoCommit(true);
if (connectionProxyFactory != null) {
connection = connectionProxyFactory.createProxy(connection);
}
logger.debug("opened connection to {} got #{}", url, connection.hashCode());
return connection;
} | java | @SuppressWarnings("resource")
protected DatabaseConnection makeConnection(Logger logger) throws SQLException {
Properties properties = new Properties();
if (username != null) {
properties.setProperty("user", username);
}
if (password != null) {
properties.setProperty("password", password);
}
DatabaseConnection connection = new JdbcDatabaseConnection(DriverManager.getConnection(url, properties));
// by default auto-commit is set to true
connection.setAutoCommit(true);
if (connectionProxyFactory != null) {
connection = connectionProxyFactory.createProxy(connection);
}
logger.debug("opened connection to {} got #{}", url, connection.hashCode());
return connection;
} | [
"@",
"SuppressWarnings",
"(",
"\"resource\"",
")",
"protected",
"DatabaseConnection",
"makeConnection",
"(",
"Logger",
"logger",
")",
"throws",
"SQLException",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"if",
"(",
"username",
"!=",
... | Make a connection to the database.
@param logger
This is here so we can use the right logger associated with the sub-class. | [
"Make",
"a",
"connection",
"to",
"the",
"database",
"."
] | train | https://github.com/j256/ormlite-jdbc/blob/a5ce794ce34bce7000730ebe8e15f3fb3a8a5381/src/main/java/com/j256/ormlite/jdbc/JdbcConnectionSource.java#L257-L274 |
rhuss/jolokia | agent/osgi/src/main/java/org/jolokia/osgi/servlet/JolokiaServlet.java | JolokiaServlet.createLogHandler | @Override
protected LogHandler createLogHandler(ServletConfig pServletConfig, boolean pDebug) {
// If there is a bundle context available, set up a tracker for tracking the logging
// service
BundleContext ctx = getBundleContext(pServletConfig);
if (ctx != null) {
// Track logging service
logTracker = new ServiceTracker(ctx, LogService.class.getName(), null);
logTracker.open();
return new ActivatorLogHandler(logTracker,pDebug);
} else {
// Use default log handler
return super.createLogHandler(pServletConfig, pDebug);
}
} | java | @Override
protected LogHandler createLogHandler(ServletConfig pServletConfig, boolean pDebug) {
// If there is a bundle context available, set up a tracker for tracking the logging
// service
BundleContext ctx = getBundleContext(pServletConfig);
if (ctx != null) {
// Track logging service
logTracker = new ServiceTracker(ctx, LogService.class.getName(), null);
logTracker.open();
return new ActivatorLogHandler(logTracker,pDebug);
} else {
// Use default log handler
return super.createLogHandler(pServletConfig, pDebug);
}
} | [
"@",
"Override",
"protected",
"LogHandler",
"createLogHandler",
"(",
"ServletConfig",
"pServletConfig",
",",
"boolean",
"pDebug",
")",
"{",
"// If there is a bundle context available, set up a tracker for tracking the logging",
"// service",
"BundleContext",
"ctx",
"=",
"getBundl... | Create a log handler which tracks a {@link LogService} and, if available, use the log service
for logging, in the other time uses the servlet's default logging facility
@param pServletConfig servlet configuration
@param pDebug | [
"Create",
"a",
"log",
"handler",
"which",
"tracks",
"a",
"{",
"@link",
"LogService",
"}",
"and",
"if",
"available",
"use",
"the",
"log",
"service",
"for",
"logging",
"in",
"the",
"other",
"time",
"uses",
"the",
"servlet",
"s",
"default",
"logging",
"facili... | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/osgi/src/main/java/org/jolokia/osgi/servlet/JolokiaServlet.java#L104-L118 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java | Utils.readPropertiesQuietly | public static Properties readPropertiesQuietly( String fileContent, Logger logger ) {
Properties result = new Properties();
try {
if( fileContent != null ) {
InputStream in = new ByteArrayInputStream( fileContent.getBytes( StandardCharsets.UTF_8 ));
result.load( in );
}
} catch( Exception e ) {
logger.severe( "Properties could not be read from a string." );
logException( logger, e );
}
return result;
} | java | public static Properties readPropertiesQuietly( String fileContent, Logger logger ) {
Properties result = new Properties();
try {
if( fileContent != null ) {
InputStream in = new ByteArrayInputStream( fileContent.getBytes( StandardCharsets.UTF_8 ));
result.load( in );
}
} catch( Exception e ) {
logger.severe( "Properties could not be read from a string." );
logException( logger, e );
}
return result;
} | [
"public",
"static",
"Properties",
"readPropertiesQuietly",
"(",
"String",
"fileContent",
",",
"Logger",
"logger",
")",
"{",
"Properties",
"result",
"=",
"new",
"Properties",
"(",
")",
";",
"try",
"{",
"if",
"(",
"fileContent",
"!=",
"null",
")",
"{",
"InputS... | Reads properties from a string.
@param file a properties file
@param logger a logger (not null)
@return a {@link Properties} instance | [
"Reads",
"properties",
"from",
"a",
"string",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L577-L592 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java | ResourceGroovyMethods.getText | public static String getText(URL url, String charset) throws IOException {
BufferedReader reader = newReader(url, charset);
return IOGroovyMethods.getText(reader);
} | java | public static String getText(URL url, String charset) throws IOException {
BufferedReader reader = newReader(url, charset);
return IOGroovyMethods.getText(reader);
} | [
"public",
"static",
"String",
"getText",
"(",
"URL",
"url",
",",
"String",
"charset",
")",
"throws",
"IOException",
"{",
"BufferedReader",
"reader",
"=",
"newReader",
"(",
"url",
",",
"charset",
")",
";",
"return",
"IOGroovyMethods",
".",
"getText",
"(",
"re... | Read the data from this URL and return it as a String. The connection
stream is closed before this method returns.
@param url URL to read content from
@param charset opens the stream with a specified charset
@return the text from that URL
@throws IOException if an IOException occurs.
@see java.net.URLConnection#getInputStream()
@since 1.0 | [
"Read",
"the",
"data",
"from",
"this",
"URL",
"and",
"return",
"it",
"as",
"a",
"String",
".",
"The",
"connection",
"stream",
"is",
"closed",
"before",
"this",
"method",
"returns",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L640-L643 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java | BouncyCastleCertProcessingFactory.createCertificateRequest | public byte[] createCertificateRequest(X509Certificate cert, KeyPair keyPair) throws GeneralSecurityException {
String issuer = cert.getSubjectDN().getName();
X509Name subjectDN = new X509Name(issuer + ",CN=proxy");
String sigAlgName = cert.getSigAlgName();
return createCertificateRequest(subjectDN, sigAlgName, keyPair);
} | java | public byte[] createCertificateRequest(X509Certificate cert, KeyPair keyPair) throws GeneralSecurityException {
String issuer = cert.getSubjectDN().getName();
X509Name subjectDN = new X509Name(issuer + ",CN=proxy");
String sigAlgName = cert.getSigAlgName();
return createCertificateRequest(subjectDN, sigAlgName, keyPair);
} | [
"public",
"byte",
"[",
"]",
"createCertificateRequest",
"(",
"X509Certificate",
"cert",
",",
"KeyPair",
"keyPair",
")",
"throws",
"GeneralSecurityException",
"{",
"String",
"issuer",
"=",
"cert",
".",
"getSubjectDN",
"(",
")",
".",
"getName",
"(",
")",
";",
"X... | Creates a certificate request from the specified certificate and a key pair. The certificate's subject
DN with <I>"CN=proxy"</I> name component appended to the subject is used as the subject of the
certificate request. Also the certificate's signing algorithm is used as the certificate request
signing algorithm.
@param cert
the certificate to create the certificate request from.
@param keyPair
the key pair of the certificate request
@return the certificate request.
@exception GeneralSecurityException
if security error occurs. | [
"Creates",
"a",
"certificate",
"request",
"from",
"the",
"specified",
"certificate",
"and",
"a",
"key",
"pair",
".",
"The",
"certificate",
"s",
"subject",
"DN",
"with",
"<I",
">",
"CN",
"=",
"proxy",
"<",
"/",
"I",
">",
"name",
"component",
"appended",
"... | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java#L962-L968 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.translationRotateTowards | public Matrix4d translationRotateTowards(Vector3dc pos, Vector3dc dir, Vector3dc up) {
return translationRotateTowards(pos.x(), pos.y(), pos.z(), dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z());
} | java | public Matrix4d translationRotateTowards(Vector3dc pos, Vector3dc dir, Vector3dc up) {
return translationRotateTowards(pos.x(), pos.y(), pos.z(), dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z());
} | [
"public",
"Matrix4d",
"translationRotateTowards",
"(",
"Vector3dc",
"pos",
",",
"Vector3dc",
"dir",
",",
"Vector3dc",
"up",
")",
"{",
"return",
"translationRotateTowards",
"(",
"pos",
".",
"x",
"(",
")",
",",
"pos",
".",
"y",
"(",
")",
",",
"pos",
".",
"... | Set this matrix to a model transformation for a right-handed coordinate system,
that translates to the given <code>pos</code> and aligns the local <code>-z</code>
axis with <code>dir</code>.
<p>
This method is equivalent to calling: <code>translation(pos).rotateTowards(dir, up)</code>
@see #translation(Vector3dc)
@see #rotateTowards(Vector3dc, Vector3dc)
@param pos
the position to translate to
@param dir
the direction to rotate towards
@param up
the up vector
@return this | [
"Set",
"this",
"matrix",
"to",
"a",
"model",
"transformation",
"for",
"a",
"right",
"-",
"handed",
"coordinate",
"system",
"that",
"translates",
"to",
"the",
"given",
"<code",
">",
"pos<",
"/",
"code",
">",
"and",
"aligns",
"the",
"local",
"<code",
">",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L15377-L15379 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/MediaUtils.java | MediaUtils.nonDuplicateFile | public static File nonDuplicateFile(File dir, String name){
int count = 1;
File outputFile = new File(dir, name);
while(outputFile.exists()){
String cleanName = cleanFilename(name);
int extIndex = name.lastIndexOf(".");
String extension = "";
if(extIndex != -1) {
extension = name.substring(extIndex + 1);
}
String revisedFileName = String.format(Locale.US, "%s(%d).%s", cleanName, count, extension);
outputFile = new File(dir, revisedFileName);
count++;
}
return outputFile;
} | java | public static File nonDuplicateFile(File dir, String name){
int count = 1;
File outputFile = new File(dir, name);
while(outputFile.exists()){
String cleanName = cleanFilename(name);
int extIndex = name.lastIndexOf(".");
String extension = "";
if(extIndex != -1) {
extension = name.substring(extIndex + 1);
}
String revisedFileName = String.format(Locale.US, "%s(%d).%s", cleanName, count, extension);
outputFile = new File(dir, revisedFileName);
count++;
}
return outputFile;
} | [
"public",
"static",
"File",
"nonDuplicateFile",
"(",
"File",
"dir",
",",
"String",
"name",
")",
"{",
"int",
"count",
"=",
"1",
";",
"File",
"outputFile",
"=",
"new",
"File",
"(",
"dir",
",",
"name",
")",
";",
"while",
"(",
"outputFile",
".",
"exists",
... | Create a non duplicate file in the given directory with the given name, appending a duplicate
counter to the end of the name but before the extension like: `some_file(1).jpg`
@param dir The parent directory of the desired file
@param name The desired name of the file
@return The non-duplicate file | [
"Create",
"a",
"non",
"duplicate",
"file",
"in",
"the",
"given",
"directory",
"with",
"the",
"given",
"name",
"appending",
"a",
"duplicate",
"counter",
"to",
"the",
"end",
"of",
"the",
"name",
"but",
"before",
"the",
"extension",
"like",
":",
"some_file",
... | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/MediaUtils.java#L317-L334 |
JoeKerouac/utils | src/main/java/com/joe/utils/collection/CollectionUtil.java | CollectionUtil.intersection | public static <T> List<T> intersection(List<T> arr1, List<T> arr2) {
return intersection(arr1, 0, arr1.size(), arr2, 0, arr2.size());
} | java | public static <T> List<T> intersection(List<T> arr1, List<T> arr2) {
return intersection(arr1, 0, arr1.size(), arr2, 0, arr2.size());
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"intersection",
"(",
"List",
"<",
"T",
">",
"arr1",
",",
"List",
"<",
"T",
">",
"arr2",
")",
"{",
"return",
"intersection",
"(",
"arr1",
",",
"0",
",",
"arr1",
".",
"size",
"(",
")",
","... | 求集合交集
@param arr1 集合1
@param arr2 集合2
@param <T> 集合中的数据
@return 集合的交集 | [
"求集合交集"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/collection/CollectionUtil.java#L467-L469 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java | OdsElements.writeSettings | public void writeSettings(final XMLUtil xmlUtil, final ZipUTF8Writer writer) throws IOException {
this.settingsElement.setTables(this.getTables());
this.logger.log(Level.FINER, "Writing odselement: settingsElement to zip file");
this.settingsElement.write(xmlUtil, writer);
} | java | public void writeSettings(final XMLUtil xmlUtil, final ZipUTF8Writer writer) throws IOException {
this.settingsElement.setTables(this.getTables());
this.logger.log(Level.FINER, "Writing odselement: settingsElement to zip file");
this.settingsElement.write(xmlUtil, writer);
} | [
"public",
"void",
"writeSettings",
"(",
"final",
"XMLUtil",
"xmlUtil",
",",
"final",
"ZipUTF8Writer",
"writer",
")",
"throws",
"IOException",
"{",
"this",
".",
"settingsElement",
".",
"setTables",
"(",
"this",
".",
"getTables",
"(",
")",
")",
";",
"this",
".... | Write the settings element to a writer.
@param xmlUtil the xml util
@param writer the writer
@throws IOException if write fails | [
"Write",
"the",
"settings",
"element",
"to",
"a",
"writer",
"."
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java#L411-L415 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java | ServletUtil.handleError | public static void handleError(final HttpServletHelper helper, final Throwable throwable) throws
ServletException,
IOException {
HttpServletRequest httpServletRequest = helper.getBackingRequest();
HttpServletResponse httpServletResponse = helper.getBackingResponse();
// Allow for multi part requests
Map<String, String[]> parameters = getRequestParameters(httpServletRequest);
// Set error code for AJAX, Content or data requests
boolean dataRequest = parameters.get(WServlet.DATA_LIST_PARAM_NAME) != null;
Object target = parameters.get(WServlet.AJAX_TRIGGER_PARAM_NAME);
if (target == null) {
target = parameters.get(WServlet.TARGET_ID_PARAM_NAME);
}
if (target != null || dataRequest) {
httpServletResponse.sendError(500, "Internal Error");
return;
}
// Decide whether we should use the ErrorPageFactory.
boolean handleErrorWithFatalErrorPageFactory = ConfigurationProperties.getHandleErrorWithFatalErrorPageFactory();
// use the new technique and delegate to the ErrorPageFactory.
if (handleErrorWithFatalErrorPageFactory) {
helper.handleError(throwable);
helper.dispose();
} else { // use the old technique and just display a raw message.
// First, decide whether we are in friendly mode or not.
boolean friendly = ConfigurationProperties.getDeveloperErrorHandling();
String message = InternalMessages.DEFAULT_SYSTEM_ERROR;
// If we are unfriendly, terminate the session
if (!friendly) {
HttpSession session = httpServletRequest.getSession(true);
session.invalidate();
message = InternalMessages.DEFAULT_SYSTEM_ERROR_SEVERE;
}
// Display an error to the user.
UIContext uic = helper.getUIContext();
Locale locale = uic == null ? null : uic.getLocale();
message = I18nUtilities.format(locale, message);
httpServletResponse.getWriter().println(message);
}
} | java | public static void handleError(final HttpServletHelper helper, final Throwable throwable) throws
ServletException,
IOException {
HttpServletRequest httpServletRequest = helper.getBackingRequest();
HttpServletResponse httpServletResponse = helper.getBackingResponse();
// Allow for multi part requests
Map<String, String[]> parameters = getRequestParameters(httpServletRequest);
// Set error code for AJAX, Content or data requests
boolean dataRequest = parameters.get(WServlet.DATA_LIST_PARAM_NAME) != null;
Object target = parameters.get(WServlet.AJAX_TRIGGER_PARAM_NAME);
if (target == null) {
target = parameters.get(WServlet.TARGET_ID_PARAM_NAME);
}
if (target != null || dataRequest) {
httpServletResponse.sendError(500, "Internal Error");
return;
}
// Decide whether we should use the ErrorPageFactory.
boolean handleErrorWithFatalErrorPageFactory = ConfigurationProperties.getHandleErrorWithFatalErrorPageFactory();
// use the new technique and delegate to the ErrorPageFactory.
if (handleErrorWithFatalErrorPageFactory) {
helper.handleError(throwable);
helper.dispose();
} else { // use the old technique and just display a raw message.
// First, decide whether we are in friendly mode or not.
boolean friendly = ConfigurationProperties.getDeveloperErrorHandling();
String message = InternalMessages.DEFAULT_SYSTEM_ERROR;
// If we are unfriendly, terminate the session
if (!friendly) {
HttpSession session = httpServletRequest.getSession(true);
session.invalidate();
message = InternalMessages.DEFAULT_SYSTEM_ERROR_SEVERE;
}
// Display an error to the user.
UIContext uic = helper.getUIContext();
Locale locale = uic == null ? null : uic.getLocale();
message = I18nUtilities.format(locale, message);
httpServletResponse.getWriter().println(message);
}
} | [
"public",
"static",
"void",
"handleError",
"(",
"final",
"HttpServletHelper",
"helper",
",",
"final",
"Throwable",
"throwable",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"HttpServletRequest",
"httpServletRequest",
"=",
"helper",
".",
"getBackingRequest... | Called if a Throwable is caught by the top-level service method. By default we display an error and terminate the
session.
@param helper the current servlet helper
@param throwable the throwable
@throws ServletException a servlet exception
@throws IOException an IO Exception | [
"Called",
"if",
"a",
"Throwable",
"is",
"caught",
"by",
"the",
"top",
"-",
"level",
"service",
"method",
".",
"By",
"default",
"we",
"display",
"an",
"error",
"and",
"terminate",
"the",
"session",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java#L465-L512 |
cloudiator/flexiant-client | src/main/java/de/uniulm/omi/cloudiator/flexiant/client/compute/FlexiantComputeClient.java | FlexiantComputeClient.createServer | public de.uniulm.omi.cloudiator.flexiant.client.domain.Server createServer(
final ServerTemplate serverTemplate) throws FlexiantException {
checkNotNull(serverTemplate);
io.github.cloudiator.flexiant.extility.Server server =
new io.github.cloudiator.flexiant.extility.Server();
server.setResourceName(serverTemplate.getServerName());
server.setCustomerUUID(this.getCustomerUUID());
server.setProductOfferUUID(serverTemplate.getServerProductOffer());
server.setVdcUUID(serverTemplate.getVdc());
server.setImageUUID(serverTemplate.getImage());
Disk disk = new Disk();
disk.setProductOfferUUID(serverTemplate.getDiskProductOffer());
disk.setIndex(0);
server.getDisks().add(disk);
final Set<String> networks = new HashSet<String>();
if (serverTemplate.getTemplateOptions().getNetworks().isEmpty()) {
//no network configured, find it out by ourselves.
if (this.getNetworks(serverTemplate.getVdc()).size() == 1) {
networks.add(this.getNetworks(serverTemplate.getVdc()).iterator().next().getId());
} else {
throw new FlexiantException("Could not uniquely identify network.");
}
} else {
networks.addAll(serverTemplate.getTemplateOptions().getNetworks());
}
//assign the networks
for (String network : networks) {
Nic nic = new Nic();
nic.setNetworkUUID(network);
server.getNics().add(nic);
}
try {
Job serverJob = this.getService().createServer(server, null, null, null);
this.waitForJob(serverJob);
final de.uniulm.omi.cloudiator.flexiant.client.domain.Server createdServer =
this.getServer(serverJob.getItemUUID());
checkState(createdServer != null, String.format(
"Execution of job %s for server %s was returned as successful, but the server could not be queried.",
serverJob.getResourceUUID(), serverJob.getItemUUID()));
this.startServer(createdServer);
return createdServer;
} catch (ExtilityException e) {
throw new FlexiantException("Could not create server", e);
}
} | java | public de.uniulm.omi.cloudiator.flexiant.client.domain.Server createServer(
final ServerTemplate serverTemplate) throws FlexiantException {
checkNotNull(serverTemplate);
io.github.cloudiator.flexiant.extility.Server server =
new io.github.cloudiator.flexiant.extility.Server();
server.setResourceName(serverTemplate.getServerName());
server.setCustomerUUID(this.getCustomerUUID());
server.setProductOfferUUID(serverTemplate.getServerProductOffer());
server.setVdcUUID(serverTemplate.getVdc());
server.setImageUUID(serverTemplate.getImage());
Disk disk = new Disk();
disk.setProductOfferUUID(serverTemplate.getDiskProductOffer());
disk.setIndex(0);
server.getDisks().add(disk);
final Set<String> networks = new HashSet<String>();
if (serverTemplate.getTemplateOptions().getNetworks().isEmpty()) {
//no network configured, find it out by ourselves.
if (this.getNetworks(serverTemplate.getVdc()).size() == 1) {
networks.add(this.getNetworks(serverTemplate.getVdc()).iterator().next().getId());
} else {
throw new FlexiantException("Could not uniquely identify network.");
}
} else {
networks.addAll(serverTemplate.getTemplateOptions().getNetworks());
}
//assign the networks
for (String network : networks) {
Nic nic = new Nic();
nic.setNetworkUUID(network);
server.getNics().add(nic);
}
try {
Job serverJob = this.getService().createServer(server, null, null, null);
this.waitForJob(serverJob);
final de.uniulm.omi.cloudiator.flexiant.client.domain.Server createdServer =
this.getServer(serverJob.getItemUUID());
checkState(createdServer != null, String.format(
"Execution of job %s for server %s was returned as successful, but the server could not be queried.",
serverJob.getResourceUUID(), serverJob.getItemUUID()));
this.startServer(createdServer);
return createdServer;
} catch (ExtilityException e) {
throw new FlexiantException("Could not create server", e);
}
} | [
"public",
"de",
".",
"uniulm",
".",
"omi",
".",
"cloudiator",
".",
"flexiant",
".",
"client",
".",
"domain",
".",
"Server",
"createServer",
"(",
"final",
"ServerTemplate",
"serverTemplate",
")",
"throws",
"FlexiantException",
"{",
"checkNotNull",
"(",
"serverTem... | Creates a server with the given properties.
@param serverTemplate A template describing the server which should be started.
@return the created server.
@throws FlexiantException | [
"Creates",
"a",
"server",
"with",
"the",
"given",
"properties",
"."
] | train | https://github.com/cloudiator/flexiant-client/blob/30024501a6ae034ea3646f71ec0761c8bc5daa69/src/main/java/de/uniulm/omi/cloudiator/flexiant/client/compute/FlexiantComputeClient.java#L216-L266 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java | SparkUtils.balancedRandomSplit | public static <T, U> JavaPairRDD<T, U>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit,
JavaPairRDD<T, U> data) {
return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong());
} | java | public static <T, U> JavaPairRDD<T, U>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit,
JavaPairRDD<T, U> data) {
return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong());
} | [
"public",
"static",
"<",
"T",
",",
"U",
">",
"JavaPairRDD",
"<",
"T",
",",
"U",
">",
"[",
"]",
"balancedRandomSplit",
"(",
"int",
"totalObjectCount",
",",
"int",
"numObjectsPerSplit",
",",
"JavaPairRDD",
"<",
"T",
",",
"U",
">",
"data",
")",
"{",
"retu... | Equivalent to {@link #balancedRandomSplit(int, int, JavaRDD)} but for Pair RDDs | [
"Equivalent",
"to",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L487-L490 |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/items/RealmSampleUserItem.java | RealmSampleUserItem.bindView | @Override
public void bindView(ViewHolder holder, List<Object> payloads) {
//set the selected state of this item. force this otherwise it may is missed when implementing an item
holder.itemView.setSelected(isSelected());
//set the name
holder.name.setText(name);
} | java | @Override
public void bindView(ViewHolder holder, List<Object> payloads) {
//set the selected state of this item. force this otherwise it may is missed when implementing an item
holder.itemView.setSelected(isSelected());
//set the name
holder.name.setText(name);
} | [
"@",
"Override",
"public",
"void",
"bindView",
"(",
"ViewHolder",
"holder",
",",
"List",
"<",
"Object",
">",
"payloads",
")",
"{",
"//set the selected state of this item. force this otherwise it may is missed when implementing an item",
"holder",
".",
"itemView",
".",
"setS... | Binds the data of this item to the given holder
@param holder | [
"Binds",
"the",
"data",
"of",
"this",
"item",
"to",
"the",
"given",
"holder"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/app/src/main/java/com/mikepenz/fastadapter/app/items/RealmSampleUserItem.java#L238-L245 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/DirectQuickSelectSketchR.java | DirectQuickSelectSketchR.readOnlyWrap | static DirectQuickSelectSketchR readOnlyWrap(final Memory srcMem, final long seed) {
final int preambleLongs = extractPreLongs(srcMem); //byte 0
final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3
final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4
UpdateSketch.checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs);
checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs);
final DirectQuickSelectSketchR dqssr =
new DirectQuickSelectSketchR(seed, (WritableMemory) srcMem);
dqssr.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs);
return dqssr;
} | java | static DirectQuickSelectSketchR readOnlyWrap(final Memory srcMem, final long seed) {
final int preambleLongs = extractPreLongs(srcMem); //byte 0
final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3
final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4
UpdateSketch.checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs);
checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs);
final DirectQuickSelectSketchR dqssr =
new DirectQuickSelectSketchR(seed, (WritableMemory) srcMem);
dqssr.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs);
return dqssr;
} | [
"static",
"DirectQuickSelectSketchR",
"readOnlyWrap",
"(",
"final",
"Memory",
"srcMem",
",",
"final",
"long",
"seed",
")",
"{",
"final",
"int",
"preambleLongs",
"=",
"extractPreLongs",
"(",
"srcMem",
")",
";",
"//byte 0",
"final",
"int",
"lgNomLongs",
"=",
"extr... | Wrap a sketch around the given source Memory containing sketch data that originated from
this sketch.
@param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
The given Memory object must be in hash table form and not read only.
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a>
@return instance of this sketch | [
"Wrap",
"a",
"sketch",
"around",
"the",
"given",
"source",
"Memory",
"containing",
"sketch",
"data",
"that",
"originated",
"from",
"this",
"sketch",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/DirectQuickSelectSketchR.java#L60-L72 |
carewebframework/carewebframework-core | org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/event/EventManager.java | EventManager.hostSubscribe | private void hostSubscribe(String eventName, boolean subscribe) {
if (globalEventDispatcher != null) {
try {
globalEventDispatcher.subscribeRemoteEvent(eventName, subscribe);
} catch (Throwable e) {
log.error(
"Error " + (subscribe ? "subscribing to" : "unsubscribing from") + " remote event '" + eventName + "'",
e);
}
}
} | java | private void hostSubscribe(String eventName, boolean subscribe) {
if (globalEventDispatcher != null) {
try {
globalEventDispatcher.subscribeRemoteEvent(eventName, subscribe);
} catch (Throwable e) {
log.error(
"Error " + (subscribe ? "subscribing to" : "unsubscribing from") + " remote event '" + eventName + "'",
e);
}
}
} | [
"private",
"void",
"hostSubscribe",
"(",
"String",
"eventName",
",",
"boolean",
"subscribe",
")",
"{",
"if",
"(",
"globalEventDispatcher",
"!=",
"null",
")",
"{",
"try",
"{",
"globalEventDispatcher",
".",
"subscribeRemoteEvent",
"(",
"eventName",
",",
"subscribe",... | Registers or unregisters a subscription with the global event dispatcher, if one is present.
@param eventName Name of event
@param subscribe If true, a subscription is registered. If false, it is unregistered. | [
"Registers",
"or",
"unregisters",
"a",
"subscription",
"with",
"the",
"global",
"event",
"dispatcher",
"if",
"one",
"is",
"present",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/event/EventManager.java#L144-L154 |
aalmiray/Json-lib | extensions/spring/src/main/java/net/sf/json/spring/web/servlet/view/JsonView.java | JsonView.createJSON | protected JSON createJSON( Map model, HttpServletRequest request, HttpServletResponse response ) {
return defaultCreateJSON( model );
} | java | protected JSON createJSON( Map model, HttpServletRequest request, HttpServletResponse response ) {
return defaultCreateJSON( model );
} | [
"protected",
"JSON",
"createJSON",
"(",
"Map",
"model",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"return",
"defaultCreateJSON",
"(",
"model",
")",
";",
"}"
] | Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values. | [
"Creates",
"a",
"JSON",
"[",
"JSONObject",
"JSONArray",
"JSONNUll",
"]",
"from",
"the",
"model",
"values",
"."
] | train | https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/extensions/spring/src/main/java/net/sf/json/spring/web/servlet/view/JsonView.java#L117-L119 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/RegExUtils.java | RegExUtils.removeAll | public static String removeAll(final String text, final Pattern regex) {
return replaceAll(text, regex, StringUtils.EMPTY);
} | java | public static String removeAll(final String text, final Pattern regex) {
return replaceAll(text, regex, StringUtils.EMPTY);
} | [
"public",
"static",
"String",
"removeAll",
"(",
"final",
"String",
"text",
",",
"final",
"Pattern",
"regex",
")",
"{",
"return",
"replaceAll",
"(",
"text",
",",
"regex",
",",
"StringUtils",
".",
"EMPTY",
")",
";",
"}"
] | <p>Removes each substring of the text String that matches the given regular expression pattern.</p>
This method is a {@code null} safe equivalent to:
<ul>
<li>{@code pattern.matcher(text).replaceAll(StringUtils.EMPTY)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<pre>
StringUtils.removeAll(null, *) = null
StringUtils.removeAll("any", (Pattern) null) = "any"
StringUtils.removeAll("any", Pattern.compile("")) = "any"
StringUtils.removeAll("any", Pattern.compile(".*")) = ""
StringUtils.removeAll("any", Pattern.compile(".+")) = ""
StringUtils.removeAll("abc", Pattern.compile(".?")) = ""
StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("<.*>")) = "A\nB"
StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("(?s)<.*>")) = "AB"
StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("<.*>", Pattern.DOTALL)) = "AB"
StringUtils.removeAll("ABCabc123abc", Pattern.compile("[a-z]")) = "ABC123"
</pre>
@param text text to remove from, may be null
@param regex the regular expression to which this string is to be matched
@return the text with any removes processed,
{@code null} if null String input
@see #replaceAll(String, Pattern, String)
@see java.util.regex.Matcher#replaceAll(String)
@see java.util.regex.Pattern | [
"<p",
">",
"Removes",
"each",
"substring",
"of",
"the",
"text",
"String",
"that",
"matches",
"the",
"given",
"regular",
"expression",
"pattern",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/RegExUtils.java#L60-L62 |
jboss-integration/fuse-bxms-integ | quickstarts/switchyard-rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java | Transformers.transformVerifyToApplicant | @Transformer(from = "{urn:switchyard-quickstart:rules-interview-dtable:0.1.0}verify")
public Applicant transformVerifyToApplicant(Element e) {
String name = getElementValue(e, "name");
int age = Integer.valueOf(getElementValue(e, "age")).intValue();
return new Applicant(name, age);
} | java | @Transformer(from = "{urn:switchyard-quickstart:rules-interview-dtable:0.1.0}verify")
public Applicant transformVerifyToApplicant(Element e) {
String name = getElementValue(e, "name");
int age = Integer.valueOf(getElementValue(e, "age")).intValue();
return new Applicant(name, age);
} | [
"@",
"Transformer",
"(",
"from",
"=",
"\"{urn:switchyard-quickstart:rules-interview-dtable:0.1.0}verify\"",
")",
"public",
"Applicant",
"transformVerifyToApplicant",
"(",
"Element",
"e",
")",
"{",
"String",
"name",
"=",
"getElementValue",
"(",
"e",
",",
"\"name\"",
")",... | Transform verify to applicant.
@param e the e
@return the applicant | [
"Transform",
"verify",
"to",
"applicant",
"."
] | train | https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/quickstarts/switchyard-rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java#L46-L51 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/distance/ST_ProjectPoint.java | ST_ProjectPoint.projectPoint | public static Point projectPoint(Geometry point, Geometry geometry) {
if (point == null || geometry==null) {
return null;
}
if (point.getDimension()==0 && geometry.getDimension() == 1) {
LengthIndexedLine ll = new LengthIndexedLine(geometry);
double index = ll.project(point.getCoordinate());
return geometry.getFactory().createPoint(ll.extractPoint(index));
} else {
return null;
}
} | java | public static Point projectPoint(Geometry point, Geometry geometry) {
if (point == null || geometry==null) {
return null;
}
if (point.getDimension()==0 && geometry.getDimension() == 1) {
LengthIndexedLine ll = new LengthIndexedLine(geometry);
double index = ll.project(point.getCoordinate());
return geometry.getFactory().createPoint(ll.extractPoint(index));
} else {
return null;
}
} | [
"public",
"static",
"Point",
"projectPoint",
"(",
"Geometry",
"point",
",",
"Geometry",
"geometry",
")",
"{",
"if",
"(",
"point",
"==",
"null",
"||",
"geometry",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"point",
".",
"getDimension",... | Project a point on a linestring or multilinestring
@param point
@param geometry
@return | [
"Project",
"a",
"point",
"on",
"a",
"linestring",
"or",
"multilinestring"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/distance/ST_ProjectPoint.java#L52-L63 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java | SqlQueryStatement.buildAliasKey | private String buildAliasKey(String aPath, List hintClasses)
{
if (hintClasses == null || hintClasses.isEmpty())
{
return aPath;
}
StringBuffer buf = new StringBuffer(aPath);
for (Iterator iter = hintClasses.iterator(); iter.hasNext();)
{
Class hint = (Class) iter.next();
buf.append(" ");
buf.append(hint.getName());
}
return buf.toString();
} | java | private String buildAliasKey(String aPath, List hintClasses)
{
if (hintClasses == null || hintClasses.isEmpty())
{
return aPath;
}
StringBuffer buf = new StringBuffer(aPath);
for (Iterator iter = hintClasses.iterator(); iter.hasNext();)
{
Class hint = (Class) iter.next();
buf.append(" ");
buf.append(hint.getName());
}
return buf.toString();
} | [
"private",
"String",
"buildAliasKey",
"(",
"String",
"aPath",
",",
"List",
"hintClasses",
")",
"{",
"if",
"(",
"hintClasses",
"==",
"null",
"||",
"hintClasses",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"aPath",
";",
"}",
"StringBuffer",
"buf",
"=",
... | Build the key for the TableAlias based on the path and the hints
@param aPath
@param hintClasses
@return the key for the TableAlias | [
"Build",
"the",
"key",
"for",
"the",
"TableAlias",
"based",
"on",
"the",
"path",
"and",
"the",
"hints"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L1381-L1396 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java | TransactionOutPoint.getConnectedRedeemData | @Nullable
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
TransactionOutput connectedOutput = getConnectedOutput();
checkNotNull(connectedOutput, "Input is not connected so cannot retrieve key");
Script connectedScript = connectedOutput.getScriptPubKey();
if (ScriptPattern.isP2PKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2PKH), connectedScript);
} else if (ScriptPattern.isP2WPKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2WH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2WPKH), connectedScript);
} else if (ScriptPattern.isP2PK(connectedScript)) {
byte[] pubkeyBytes = ScriptPattern.extractKeyFromP2PK(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKey(pubkeyBytes), connectedScript);
} else if (ScriptPattern.isP2SH(connectedScript)) {
byte[] scriptHash = ScriptPattern.extractHashFromP2SH(connectedScript);
return keyBag.findRedeemDataFromScriptHash(scriptHash);
} else {
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Could not understand form of connected output script: " + connectedScript);
}
} | java | @Nullable
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
TransactionOutput connectedOutput = getConnectedOutput();
checkNotNull(connectedOutput, "Input is not connected so cannot retrieve key");
Script connectedScript = connectedOutput.getScriptPubKey();
if (ScriptPattern.isP2PKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2PKH), connectedScript);
} else if (ScriptPattern.isP2WPKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2WH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2WPKH), connectedScript);
} else if (ScriptPattern.isP2PK(connectedScript)) {
byte[] pubkeyBytes = ScriptPattern.extractKeyFromP2PK(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKey(pubkeyBytes), connectedScript);
} else if (ScriptPattern.isP2SH(connectedScript)) {
byte[] scriptHash = ScriptPattern.extractHashFromP2SH(connectedScript);
return keyBag.findRedeemDataFromScriptHash(scriptHash);
} else {
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Could not understand form of connected output script: " + connectedScript);
}
} | [
"@",
"Nullable",
"public",
"RedeemData",
"getConnectedRedeemData",
"(",
"KeyBag",
"keyBag",
")",
"throws",
"ScriptException",
"{",
"TransactionOutput",
"connectedOutput",
"=",
"getConnectedOutput",
"(",
")",
";",
"checkNotNull",
"(",
"connectedOutput",
",",
"\"Input is ... | Returns the RedeemData identified in the connected output, for either P2PKH, P2WPKH, P2PK
or P2SH scripts.
If the script forms cannot be understood, throws ScriptException.
@return a RedeemData or null if the connected data cannot be found in the wallet. | [
"Returns",
"the",
"RedeemData",
"identified",
"in",
"the",
"connected",
"output",
"for",
"either",
"P2PKH",
"P2WPKH",
"P2PK",
"or",
"P2SH",
"scripts",
".",
"If",
"the",
"script",
"forms",
"cannot",
"be",
"understood",
"throws",
"ScriptException",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java#L165-L185 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata/products/SwapAnnuity.java | SwapAnnuity.getSwapAnnuity | public static double getSwapAnnuity(double evaluationTime, Schedule schedule, DiscountCurve discountCurve, AnalyticModel model) {
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex);
if(paymentDate <= evaluationTime) {
continue;
}
double periodLength = schedule.getPeriodLength(periodIndex);
double discountFactor = discountCurve.getDiscountFactor(model, paymentDate);
value += periodLength * discountFactor;
}
return value / discountCurve.getDiscountFactor(model, evaluationTime);
} | java | public static double getSwapAnnuity(double evaluationTime, Schedule schedule, DiscountCurve discountCurve, AnalyticModel model) {
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex);
if(paymentDate <= evaluationTime) {
continue;
}
double periodLength = schedule.getPeriodLength(periodIndex);
double discountFactor = discountCurve.getDiscountFactor(model, paymentDate);
value += periodLength * discountFactor;
}
return value / discountCurve.getDiscountFactor(model, evaluationTime);
} | [
"public",
"static",
"double",
"getSwapAnnuity",
"(",
"double",
"evaluationTime",
",",
"Schedule",
"schedule",
",",
"DiscountCurve",
"discountCurve",
",",
"AnalyticModel",
"model",
")",
"{",
"double",
"value",
"=",
"0.0",
";",
"for",
"(",
"int",
"periodIndex",
"=... | Function to calculate an (idealized) swap annuity for a given schedule and discount curve.
Note that, the value returned is divided by the discount factor at evaluation.
This matters, if the discount factor at evaluationTime is not equal to 1.0.
@param evaluationTime The evaluation time as double. Cash flows prior and including this time are not considered.
@param schedule The schedule discretization, i.e., the period start and end dates. End dates are considered payment dates and start of the next period.
@param discountCurve The discount curve.
@param model The model, needed only in case the discount curve evaluation depends on an additional curve.
@return The swap annuity. | [
"Function",
"to",
"calculate",
"an",
"(",
"idealized",
")",
"swap",
"annuity",
"for",
"a",
"given",
"schedule",
"and",
"discount",
"curve",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/products/SwapAnnuity.java#L117-L130 |
alibaba/otter | node/etl/src/main/java/com/alibaba/otter/node/etl/common/db/utils/SqlUtils.java | SqlUtils.getResultSetValue | private static String getResultSetValue(ResultSet rs, int index) throws SQLException {
Object obj = rs.getObject(index);
return (obj == null) ? null : convertUtilsBean.convert(obj);
} | java | private static String getResultSetValue(ResultSet rs, int index) throws SQLException {
Object obj = rs.getObject(index);
return (obj == null) ? null : convertUtilsBean.convert(obj);
} | [
"private",
"static",
"String",
"getResultSetValue",
"(",
"ResultSet",
"rs",
",",
"int",
"index",
")",
"throws",
"SQLException",
"{",
"Object",
"obj",
"=",
"rs",
".",
"getObject",
"(",
"index",
")",
";",
"return",
"(",
"obj",
"==",
"null",
")",
"?",
"null... | Retrieve a JDBC column value from a ResultSet, using the most appropriate
value type. The returned value should be a detached value object, not
having any ties to the active ResultSet: in particular, it should not be
a Blob or Clob object but rather a byte array respectively String
representation.
<p>
Uses the <code>getObject(index)</code> method, but includes additional
"hacks" to get around Oracle 10g returning a non-standard object for its
TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
leaving out the time portion: These columns will explicitly be extracted
as standard <code>java.sql.Timestamp</code> object.
@param rs is the ResultSet holding the data
@param index is the column index
@return the value object
@throws SQLException if thrown by the JDBC API
@see java.sql.Blob
@see java.sql.Clob
@see java.sql.Timestamp | [
"Retrieve",
"a",
"JDBC",
"column",
"value",
"from",
"a",
"ResultSet",
"using",
"the",
"most",
"appropriate",
"value",
"type",
".",
"The",
"returned",
"value",
"should",
"be",
"a",
"detached",
"value",
"object",
"not",
"having",
"any",
"ties",
"to",
"the",
... | train | https://github.com/alibaba/otter/blob/c7b5f94a0dd162e01ddffaf3a63cade7d23fca55/node/etl/src/main/java/com/alibaba/otter/node/etl/common/db/utils/SqlUtils.java#L310-L313 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Flowable.java | Flowable.groupJoin | @CheckReturnValue
@BackpressureSupport(BackpressureKind.ERROR)
@SchedulerSupport(SchedulerSupport.NONE)
public final <TRight, TLeftEnd, TRightEnd, R> Flowable<R> groupJoin(
Publisher<? extends TRight> other,
Function<? super T, ? extends Publisher<TLeftEnd>> leftEnd,
Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd,
BiFunction<? super T, ? super Flowable<TRight>, ? extends R> resultSelector) {
ObjectHelper.requireNonNull(other, "other is null");
ObjectHelper.requireNonNull(leftEnd, "leftEnd is null");
ObjectHelper.requireNonNull(rightEnd, "rightEnd is null");
ObjectHelper.requireNonNull(resultSelector, "resultSelector is null");
return RxJavaPlugins.onAssembly(new FlowableGroupJoin<T, TRight, TLeftEnd, TRightEnd, R>(
this, other, leftEnd, rightEnd, resultSelector));
} | java | @CheckReturnValue
@BackpressureSupport(BackpressureKind.ERROR)
@SchedulerSupport(SchedulerSupport.NONE)
public final <TRight, TLeftEnd, TRightEnd, R> Flowable<R> groupJoin(
Publisher<? extends TRight> other,
Function<? super T, ? extends Publisher<TLeftEnd>> leftEnd,
Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd,
BiFunction<? super T, ? super Flowable<TRight>, ? extends R> resultSelector) {
ObjectHelper.requireNonNull(other, "other is null");
ObjectHelper.requireNonNull(leftEnd, "leftEnd is null");
ObjectHelper.requireNonNull(rightEnd, "rightEnd is null");
ObjectHelper.requireNonNull(resultSelector, "resultSelector is null");
return RxJavaPlugins.onAssembly(new FlowableGroupJoin<T, TRight, TLeftEnd, TRightEnd, R>(
this, other, leftEnd, rightEnd, resultSelector));
} | [
"@",
"CheckReturnValue",
"@",
"BackpressureSupport",
"(",
"BackpressureKind",
".",
"ERROR",
")",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"NONE",
")",
"public",
"final",
"<",
"TRight",
",",
"TLeftEnd",
",",
"TRightEnd",
",",
"R",
">",
"Flowable",
... | Returns a Flowable that correlates two Publishers when they overlap in time and groups the results.
<p>
There are no guarantees in what order the items get combined when multiple
items from one or both source Publishers overlap.
<p>
<img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/groupJoin.png" alt="">
<dl>
<dt><b>Backpressure:</b></dt>
<dd>The operator doesn't support backpressure and consumes all participating {@code Publisher}s in
an unbounded mode (i.e., not applying any backpressure to them).</dd>
<dt><b>Scheduler:</b></dt>
<dd>{@code groupJoin} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param <TRight> the value type of the right Publisher source
@param <TLeftEnd> the element type of the left duration Publishers
@param <TRightEnd> the element type of the right duration Publishers
@param <R> the result type
@param other
the other Publisher to correlate items from the source Publisher with
@param leftEnd
a function that returns a Publisher whose emissions indicate the duration of the values of
the source Publisher
@param rightEnd
a function that returns a Publisher whose emissions indicate the duration of the values of
the {@code right} Publisher
@param resultSelector
a function that takes an item emitted by each Publisher and returns the value to be emitted
by the resulting Publisher
@return a Flowable that emits items based on combining those items emitted by the source Publishers
whose durations overlap
@see <a href="http://reactivex.io/documentation/operators/join.html">ReactiveX operators documentation: Join</a> | [
"Returns",
"a",
"Flowable",
"that",
"correlates",
"two",
"Publishers",
"when",
"they",
"overlap",
"in",
"time",
"and",
"groups",
"the",
"results",
".",
"<p",
">",
"There",
"are",
"no",
"guarantees",
"in",
"what",
"order",
"the",
"items",
"get",
"combined",
... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L10619-L10633 |
BioPAX/Paxtools | sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/L3ToSBGNPDConverter.java | L3ToSBGNPDConverter.createProcessAndConnections | private void createProcessAndConnections(TemplateReaction tr) {
// create the process for the reaction
Glyph process = factory.createGlyph();
process.setClazz(GlyphClazz.PROCESS.getClazz());
process.setId(convertID(tr.getUri()));
glyphMap.put(process.getId(), process);
final Set<PhysicalEntity> products = tr.getProduct();
final Set<PhysicalEntity> participants = new HashSet<PhysicalEntity>( //new modifiable set
new ClassFilterSet<Entity,PhysicalEntity>(tr.getParticipant(), PhysicalEntity.class));
// link products, if any
// ('participant' property is there defined sometimes instead of or in addition to 'product' or 'template')
for (PhysicalEntity pe : products) {
Glyph g = getGlyphToLink(pe, process.getId());
createArc(process, g, ArcClazz.PRODUCTION.getClazz(), null);
participants.remove(pe);
}
// link template, if present
PhysicalEntity template = tr.getTemplate();
if(template != null) {
Glyph g = getGlyphToLink(template, process.getId());
createArc(g, process, ArcClazz.CONSUMPTION.getClazz(), null);
participants.remove(template);
} else if(participants.isEmpty()) {
//when no template is defined and cannot be inferred, create a source-and-sink as the input
Glyph sas = factory.createGlyph();
sas.setClazz(GlyphClazz.SOURCE_AND_SINK.getClazz());
sas.setId("unknown-template_" + ModelUtils.md5hex(process.getId()));
glyphMap.put(sas.getId(), sas);
createArc(sas, process, ArcClazz.CONSUMPTION.getClazz(), null);
}
//infer input or output type arc for the rest of participants
for (PhysicalEntity pe : participants) {
Glyph g = getGlyphToLink(pe, process.getId());
if(template==null)
createArc(g, process, ArcClazz.CONSUMPTION.getClazz(), null);
else
createArc(process, g, ArcClazz.PRODUCTION.getClazz(), null);
}
// Associate controllers
processControllers(tr.getControlledOf(), process);
// Record mapping
sbgn2BPMap.put(process.getId(), new HashSet<String>(Collections.singleton(tr.getUri())));
} | java | private void createProcessAndConnections(TemplateReaction tr) {
// create the process for the reaction
Glyph process = factory.createGlyph();
process.setClazz(GlyphClazz.PROCESS.getClazz());
process.setId(convertID(tr.getUri()));
glyphMap.put(process.getId(), process);
final Set<PhysicalEntity> products = tr.getProduct();
final Set<PhysicalEntity> participants = new HashSet<PhysicalEntity>( //new modifiable set
new ClassFilterSet<Entity,PhysicalEntity>(tr.getParticipant(), PhysicalEntity.class));
// link products, if any
// ('participant' property is there defined sometimes instead of or in addition to 'product' or 'template')
for (PhysicalEntity pe : products) {
Glyph g = getGlyphToLink(pe, process.getId());
createArc(process, g, ArcClazz.PRODUCTION.getClazz(), null);
participants.remove(pe);
}
// link template, if present
PhysicalEntity template = tr.getTemplate();
if(template != null) {
Glyph g = getGlyphToLink(template, process.getId());
createArc(g, process, ArcClazz.CONSUMPTION.getClazz(), null);
participants.remove(template);
} else if(participants.isEmpty()) {
//when no template is defined and cannot be inferred, create a source-and-sink as the input
Glyph sas = factory.createGlyph();
sas.setClazz(GlyphClazz.SOURCE_AND_SINK.getClazz());
sas.setId("unknown-template_" + ModelUtils.md5hex(process.getId()));
glyphMap.put(sas.getId(), sas);
createArc(sas, process, ArcClazz.CONSUMPTION.getClazz(), null);
}
//infer input or output type arc for the rest of participants
for (PhysicalEntity pe : participants) {
Glyph g = getGlyphToLink(pe, process.getId());
if(template==null)
createArc(g, process, ArcClazz.CONSUMPTION.getClazz(), null);
else
createArc(process, g, ArcClazz.PRODUCTION.getClazz(), null);
}
// Associate controllers
processControllers(tr.getControlledOf(), process);
// Record mapping
sbgn2BPMap.put(process.getId(), new HashSet<String>(Collections.singleton(tr.getUri())));
} | [
"private",
"void",
"createProcessAndConnections",
"(",
"TemplateReaction",
"tr",
")",
"{",
"// create the process for the reaction",
"Glyph",
"process",
"=",
"factory",
".",
"createGlyph",
"(",
")",
";",
"process",
".",
"setClazz",
"(",
"GlyphClazz",
".",
"PROCESS",
... | /*
Creates a representation for TemplateReaction.
@param tr template reaction | [
"/",
"*",
"Creates",
"a",
"representation",
"for",
"TemplateReaction",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/L3ToSBGNPDConverter.java#L986-L1032 |
overturetool/overture | core/codegen/platform/src/main/java/org/overture/codegen/ir/CodeGenBase.java | CodeGenBase.emitCode | public static void emitCode(File outputFolder, String fileName, String code,
String encoding)
{
try
{
File javaFile = new File(outputFolder, File.separator + fileName);
javaFile.getParentFile().mkdirs();
javaFile.createNewFile();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(javaFile, false), encoding));
BufferedWriter out = new BufferedWriter(writer);
out.write(code);
out.close();
} catch (IOException e)
{
log.error("Error when saving class file: " + fileName);
e.printStackTrace();
}
} | java | public static void emitCode(File outputFolder, String fileName, String code,
String encoding)
{
try
{
File javaFile = new File(outputFolder, File.separator + fileName);
javaFile.getParentFile().mkdirs();
javaFile.createNewFile();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(javaFile, false), encoding));
BufferedWriter out = new BufferedWriter(writer);
out.write(code);
out.close();
} catch (IOException e)
{
log.error("Error when saving class file: " + fileName);
e.printStackTrace();
}
} | [
"public",
"static",
"void",
"emitCode",
"(",
"File",
"outputFolder",
",",
"String",
"fileName",
",",
"String",
"code",
",",
"String",
"encoding",
")",
"{",
"try",
"{",
"File",
"javaFile",
"=",
"new",
"File",
"(",
"outputFolder",
",",
"File",
".",
"separato... | Emits generated code to a file.
@param outputFolder
outputFolder The output folder that will store the generated code.
@param fileName
The name of the file that will store the generated code.
@param code
The generated code.
@param encoding
The encoding to use for the generated code. | [
"Emits",
"generated",
"code",
"to",
"a",
"file",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/codegen/platform/src/main/java/org/overture/codegen/ir/CodeGenBase.java#L611-L629 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java | CommerceOrderPersistenceImpl.removeByUuid_C | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommerceOrder commerceOrder : findByUuid_C(uuid, companyId,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceOrder);
}
} | java | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommerceOrder commerceOrder : findByUuid_C(uuid, companyId,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceOrder);
}
} | [
"@",
"Override",
"public",
"void",
"removeByUuid_C",
"(",
"String",
"uuid",
",",
"long",
"companyId",
")",
"{",
"for",
"(",
"CommerceOrder",
"commerceOrder",
":",
"findByUuid_C",
"(",
"uuid",
",",
"companyId",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil"... | Removes all the commerce orders where uuid = ? and companyId = ? from the database.
@param uuid the uuid
@param companyId the company ID | [
"Removes",
"all",
"the",
"commerce",
"orders",
"where",
"uuid",
"=",
"?",
";",
"and",
"companyId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L1400-L1406 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java | GitlabHTTPRequestor.withAttachment | public GitlabHTTPRequestor withAttachment(String key, File file) {
if (file != null && key != null) {
attachments.put(key, file);
}
return this;
} | java | public GitlabHTTPRequestor withAttachment(String key, File file) {
if (file != null && key != null) {
attachments.put(key, file);
}
return this;
} | [
"public",
"GitlabHTTPRequestor",
"withAttachment",
"(",
"String",
"key",
",",
"File",
"file",
")",
"{",
"if",
"(",
"file",
"!=",
"null",
"&&",
"key",
"!=",
"null",
")",
"{",
"attachments",
".",
"put",
"(",
"key",
",",
"file",
")",
";",
"}",
"return",
... | Sets the HTTP Form Post parameters for the request
Has a fluent api for method chaining
@param key Form parameter Key
@param file File data
@return this | [
"Sets",
"the",
"HTTP",
"Form",
"Post",
"parameters",
"for",
"the",
"request",
"Has",
"a",
"fluent",
"api",
"for",
"method",
"chaining"
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/http/GitlabHTTPRequestor.java#L108-L113 |
haifengl/smile | core/src/main/java/smile/feature/GAFeatureSelection.java | GAFeatureSelection.learn | public BitString[] learn(int size, int generation, ClassifierTrainer<double[]> trainer, ClassificationMeasure measure, double[][] x, int[] y, int k) {
if (size <= 0) {
throw new IllegalArgumentException("Invalid population size: " + size);
}
if (k < 2) {
throw new IllegalArgumentException("Invalid k-fold cross validation: " + k);
}
if (x.length != y.length) {
throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length));
}
int p = x[0].length;
ClassificationFitness fitness = new ClassificationFitness(trainer, measure, x, y, k);
BitString[] seeds = new BitString[size];
for (int i = 0; i < size; i++) {
seeds[i] = new BitString(p, fitness, crossover, crossoverRate, mutationRate);
}
GeneticAlgorithm<BitString> ga = new GeneticAlgorithm<>(seeds, selection);
ga.evolve(generation);
return seeds;
} | java | public BitString[] learn(int size, int generation, ClassifierTrainer<double[]> trainer, ClassificationMeasure measure, double[][] x, int[] y, int k) {
if (size <= 0) {
throw new IllegalArgumentException("Invalid population size: " + size);
}
if (k < 2) {
throw new IllegalArgumentException("Invalid k-fold cross validation: " + k);
}
if (x.length != y.length) {
throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length));
}
int p = x[0].length;
ClassificationFitness fitness = new ClassificationFitness(trainer, measure, x, y, k);
BitString[] seeds = new BitString[size];
for (int i = 0; i < size; i++) {
seeds[i] = new BitString(p, fitness, crossover, crossoverRate, mutationRate);
}
GeneticAlgorithm<BitString> ga = new GeneticAlgorithm<>(seeds, selection);
ga.evolve(generation);
return seeds;
} | [
"public",
"BitString",
"[",
"]",
"learn",
"(",
"int",
"size",
",",
"int",
"generation",
",",
"ClassifierTrainer",
"<",
"double",
"[",
"]",
">",
"trainer",
",",
"ClassificationMeasure",
"measure",
",",
"double",
"[",
"]",
"[",
"]",
"x",
",",
"int",
"[",
... | Genetic algorithm based feature selection for classification.
@param size the population size of Genetic Algorithm.
@param generation the maximum number of iterations.
@param trainer classifier trainer.
@param measure classification measure as the chromosome fitness measure.
@param x training instances.
@param y training labels.
@param k k-fold cross validation for the evaluation.
@return bit strings of last generation. | [
"Genetic",
"algorithm",
"based",
"feature",
"selection",
"for",
"classification",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/feature/GAFeatureSelection.java#L107-L132 |
OpenLiberty/open-liberty | dev/com.ibm.ws.mongo/src/com/ibm/ws/mongo/internal/MongoDBService.java | MongoDBService.modified | @Modified
protected void modified(ComponentContext context, Map<String, Object> props) throws Exception {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Dictionary<String, Object> oldProps = cctx.get().getProperties();
Tr.debug(this, tc, "MongoDBService modified: jndiName: " + oldProps.get(JNDI_NAME) + " -> " + props.get(JNDI_NAME)
+ ", database: " + oldProps.get(DATABASE_NAME) + " -> " + props.get(DATABASE_NAME));
}
cctx.set(context);
// Assuming for now that all changes require an App recycle
if (!applications.isEmpty()) {
Set<String> members = new HashSet<String>(applications);
applications.removeAll(members);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "recycling applications: " + members);
appRecycleSvcRef.recycleApplications(members);
}
} | java | @Modified
protected void modified(ComponentContext context, Map<String, Object> props) throws Exception {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Dictionary<String, Object> oldProps = cctx.get().getProperties();
Tr.debug(this, tc, "MongoDBService modified: jndiName: " + oldProps.get(JNDI_NAME) + " -> " + props.get(JNDI_NAME)
+ ", database: " + oldProps.get(DATABASE_NAME) + " -> " + props.get(DATABASE_NAME));
}
cctx.set(context);
// Assuming for now that all changes require an App recycle
if (!applications.isEmpty()) {
Set<String> members = new HashSet<String>(applications);
applications.removeAll(members);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "recycling applications: " + members);
appRecycleSvcRef.recycleApplications(members);
}
} | [
"@",
"Modified",
"protected",
"void",
"modified",
"(",
"ComponentContext",
"context",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"props",
")",
"throws",
"Exception",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",... | Modify the DeclarativeService instance that corresponds to an <mongoDB>
configuration element. <p>
This method is only called if the <mogoDB> configuration element changes
and not the <mongo> configuration element. MongoDBService is deactivated
if <mongo> is changed, since the MongoService to deactivated.
@param context DeclarativeService defined/populated component context
@param props the Component Properties from ComponentContext.getProperties. | [
"Modify",
"the",
"DeclarativeService",
"instance",
"that",
"corresponds",
"to",
"an",
"<mongoDB",
">",
"configuration",
"element",
".",
"<p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.mongo/src/com/ibm/ws/mongo/internal/MongoDBService.java#L184-L202 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/outbound/HttpOutboundServiceContextImpl.java | HttpOutboundServiceContextImpl.reConnect | protected void reConnect(VirtualConnection inVC, IOException ioe) {
if (getLink().isReconnectAllowed()) {
// start the reconnect
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Attempting reconnect: " + getLink().getVirtualConnection());
}
// 359362 - null out the JIT read buffers
getTSC().getReadInterface().setBuffer(null);
getLink().reConnectAsync(ioe);
} else {
callErrorCallback(inVC, ioe);
}
} | java | protected void reConnect(VirtualConnection inVC, IOException ioe) {
if (getLink().isReconnectAllowed()) {
// start the reconnect
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Attempting reconnect: " + getLink().getVirtualConnection());
}
// 359362 - null out the JIT read buffers
getTSC().getReadInterface().setBuffer(null);
getLink().reConnectAsync(ioe);
} else {
callErrorCallback(inVC, ioe);
}
} | [
"protected",
"void",
"reConnect",
"(",
"VirtualConnection",
"inVC",
",",
"IOException",
"ioe",
")",
"{",
"if",
"(",
"getLink",
"(",
")",
".",
"isReconnectAllowed",
"(",
")",
")",
"{",
"// start the reconnect",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabl... | If an error occurs during an attempted write of an outgoing request
message, this method will either reconnect for another try or pass the
error up the channel chain.
@param inVC
@param ioe | [
"If",
"an",
"error",
"occurs",
"during",
"an",
"attempted",
"write",
"of",
"an",
"outgoing",
"request",
"message",
"this",
"method",
"will",
"either",
"reconnect",
"for",
"another",
"try",
"or",
"pass",
"the",
"error",
"up",
"the",
"channel",
"chain",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/outbound/HttpOutboundServiceContextImpl.java#L213-L226 |
Abnaxos/markdown-doclet | doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java | PredefinedArgumentValidators.atLeast | public static ArgumentValidator atLeast(final int expectedMin) {
switch (expectedMin) {
case 0:
return ZERO_OR_MORE;
case 1:
return ONE_OR_MORE;
case 2:
return TWO_OR_MORE;
}
return atLeast(expectedMin, MessageFormat.format("{0}..*", expectedMin));
} | java | public static ArgumentValidator atLeast(final int expectedMin) {
switch (expectedMin) {
case 0:
return ZERO_OR_MORE;
case 1:
return ONE_OR_MORE;
case 2:
return TWO_OR_MORE;
}
return atLeast(expectedMin, MessageFormat.format("{0}..*", expectedMin));
} | [
"public",
"static",
"ArgumentValidator",
"atLeast",
"(",
"final",
"int",
"expectedMin",
")",
"{",
"switch",
"(",
"expectedMin",
")",
"{",
"case",
"0",
":",
"return",
"ZERO_OR_MORE",
";",
"case",
"1",
":",
"return",
"ONE_OR_MORE",
";",
"case",
"2",
":",
"re... | Creates a {@link ArgumentValidator} which checks for _#arguments >= expectedMin_
@param expectedMin the minimum number of expected arguments
@return the MissingArgumentsValidator | [
"Creates",
"a",
"{",
"@link",
"ArgumentValidator",
"}",
"which",
"checks",
"for",
"_#arguments",
">",
"=",
"expectedMin_"
] | train | https://github.com/Abnaxos/markdown-doclet/blob/e98a9630206fc9c8d813cf2349ff594be8630054/doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java#L135-L145 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapPath.java | ShrinkWrapPath.fromString | private Path fromString(final String path) {
if (path == null) {
throw new IllegalArgumentException("path must be specified");
}
// Delegate
return new ShrinkWrapPath(path, fileSystem);
} | java | private Path fromString(final String path) {
if (path == null) {
throw new IllegalArgumentException("path must be specified");
}
// Delegate
return new ShrinkWrapPath(path, fileSystem);
} | [
"private",
"Path",
"fromString",
"(",
"final",
"String",
"path",
")",
"{",
"if",
"(",
"path",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"path must be specified\"",
")",
";",
"}",
"// Delegate",
"return",
"new",
"ShrinkWrapPath",
... | Creates a new {@link ShrinkWrapPath} instance from the specified input {@link String}
@param path
@return | [
"Creates",
"a",
"new",
"{",
"@link",
"ShrinkWrapPath",
"}",
"instance",
"from",
"the",
"specified",
"input",
"{",
"@link",
"String",
"}"
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapPath.java#L620-L626 |
Polidea/RxAndroidBle | rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/operations/ServiceDiscoveryOperation.java | ServiceDiscoveryOperation.timeoutFallbackProcedure | @NonNull
@Override
protected Single<RxBleDeviceServices> timeoutFallbackProcedure(
final BluetoothGatt bluetoothGatt,
final RxBleGattCallback rxBleGattCallback,
final Scheduler timeoutScheduler
) {
return Single.defer(new Callable<SingleSource<? extends RxBleDeviceServices>>() {
@Override
public SingleSource<? extends RxBleDeviceServices> call() throws Exception {
final List<BluetoothGattService> services = bluetoothGatt.getServices();
if (services.size() == 0) {
// if after the timeout services are empty we have no other option to declare a failed discovery
return Single.error(new BleGattCallbackTimeoutException(bluetoothGatt, BleGattOperationType.SERVICE_DISCOVERY));
} else {
/*
it is observed that usually the Android OS is returning services, characteristics and descriptors in a short period of time
if there are some services available we will wait for 5 more seconds just to be sure that
the timeout was not triggered right in the moment of filling the services and then emit a value.
*/
return Single
.timer(5, TimeUnit.SECONDS, timeoutScheduler)
.flatMap(new Function<Long, Single<RxBleDeviceServices>>() {
@Override
public Single<RxBleDeviceServices> apply(Long delayedSeconds) {
return Single.fromCallable(new Callable<RxBleDeviceServices>() {
@Override
public RxBleDeviceServices call() throws Exception {
return new RxBleDeviceServices(bluetoothGatt.getServices());
}
});
}
});
}
}
});
} | java | @NonNull
@Override
protected Single<RxBleDeviceServices> timeoutFallbackProcedure(
final BluetoothGatt bluetoothGatt,
final RxBleGattCallback rxBleGattCallback,
final Scheduler timeoutScheduler
) {
return Single.defer(new Callable<SingleSource<? extends RxBleDeviceServices>>() {
@Override
public SingleSource<? extends RxBleDeviceServices> call() throws Exception {
final List<BluetoothGattService> services = bluetoothGatt.getServices();
if (services.size() == 0) {
// if after the timeout services are empty we have no other option to declare a failed discovery
return Single.error(new BleGattCallbackTimeoutException(bluetoothGatt, BleGattOperationType.SERVICE_DISCOVERY));
} else {
/*
it is observed that usually the Android OS is returning services, characteristics and descriptors in a short period of time
if there are some services available we will wait for 5 more seconds just to be sure that
the timeout was not triggered right in the moment of filling the services and then emit a value.
*/
return Single
.timer(5, TimeUnit.SECONDS, timeoutScheduler)
.flatMap(new Function<Long, Single<RxBleDeviceServices>>() {
@Override
public Single<RxBleDeviceServices> apply(Long delayedSeconds) {
return Single.fromCallable(new Callable<RxBleDeviceServices>() {
@Override
public RxBleDeviceServices call() throws Exception {
return new RxBleDeviceServices(bluetoothGatt.getServices());
}
});
}
});
}
}
});
} | [
"@",
"NonNull",
"@",
"Override",
"protected",
"Single",
"<",
"RxBleDeviceServices",
">",
"timeoutFallbackProcedure",
"(",
"final",
"BluetoothGatt",
"bluetoothGatt",
",",
"final",
"RxBleGattCallback",
"rxBleGattCallback",
",",
"final",
"Scheduler",
"timeoutScheduler",
")",... | Sometimes it happens that the {@link BluetoothGatt} will receive all {@link BluetoothGattService}'s,
{@link android.bluetooth.BluetoothGattCharacteristic}'s and {@link android.bluetooth.BluetoothGattDescriptor}
but it won't receive the final callback that the service discovery was completed. This is a potential workaround.
<p>
There is a change in Android 7.0.0_r1 where all data is received at once - in this situation returned services size will be always 0
https://android.googlesource.com/platform/frameworks/base/+/android-7.0.0_r1/core/java/android/bluetooth/BluetoothGatt.java#206
https://android.googlesource.com/platform/frameworks/base/+/android-6.0.1_r72/core/java/android/bluetooth/BluetoothGatt.java#205
@param bluetoothGatt the BluetoothGatt to use
@param rxBleGattCallback the RxBleGattCallback to use
@param timeoutScheduler the Scheduler for timeout to use
@return Observable that may emit {@link RxBleDeviceServices} or {@link TimeoutException} | [
"Sometimes",
"it",
"happens",
"that",
"the",
"{",
"@link",
"BluetoothGatt",
"}",
"will",
"receive",
"all",
"{",
"@link",
"BluetoothGattService",
"}",
"s",
"{",
"@link",
"android",
".",
"bluetooth",
".",
"BluetoothGattCharacteristic",
"}",
"s",
"and",
"{",
"@li... | train | https://github.com/Polidea/RxAndroidBle/blob/c6e4a9753c834d710e255306bb290e9244cdbc10/rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/operations/ServiceDiscoveryOperation.java#L70-L106 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java | AbstractMemberWriter.addComment | protected void addComment(ProgramElementDoc member, Content htmltree) {
if (member.inlineTags().length > 0) {
writer.addInlineComment(member, htmltree);
}
} | java | protected void addComment(ProgramElementDoc member, Content htmltree) {
if (member.inlineTags().length > 0) {
writer.addInlineComment(member, htmltree);
}
} | [
"protected",
"void",
"addComment",
"(",
"ProgramElementDoc",
"member",
",",
"Content",
"htmltree",
")",
"{",
"if",
"(",
"member",
".",
"inlineTags",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"writer",
".",
"addInlineComment",
"(",
"member",
",",
"htmltr... | Add the comment for the given member.
@param member the member being documented.
@param htmltree the content tree to which the comment will be added. | [
"Add",
"the",
"comment",
"for",
"the",
"given",
"member",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java#L369-L373 |
jhalterman/failsafe | src/main/java/net/jodah/failsafe/FailsafeExecutor.java | FailsafeExecutor.getAsync | public <T extends R> CompletableFuture<T> getAsync(CheckedSupplier<T> supplier) {
return callAsync(execution -> Functions.promiseOf(supplier, execution), false);
} | java | public <T extends R> CompletableFuture<T> getAsync(CheckedSupplier<T> supplier) {
return callAsync(execution -> Functions.promiseOf(supplier, execution), false);
} | [
"public",
"<",
"T",
"extends",
"R",
">",
"CompletableFuture",
"<",
"T",
">",
"getAsync",
"(",
"CheckedSupplier",
"<",
"T",
">",
"supplier",
")",
"{",
"return",
"callAsync",
"(",
"execution",
"->",
"Functions",
".",
"promiseOf",
"(",
"supplier",
",",
"execu... | Executes the {@code supplier} asynchronously until a successful result is returned or the configured policies are
exceeded.
<p>
If a configured circuit breaker is open, the resulting future is completed with {@link
CircuitBreakerOpenException}.
@throws NullPointerException if the {@code supplier} is null
@throws RejectedExecutionException if the {@code supplier} cannot be scheduled for execution | [
"Executes",
"the",
"{",
"@code",
"supplier",
"}",
"asynchronously",
"until",
"a",
"successful",
"result",
"is",
"returned",
"or",
"the",
"configured",
"policies",
"are",
"exceeded",
".",
"<p",
">",
"If",
"a",
"configured",
"circuit",
"breaker",
"is",
"open",
... | train | https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/FailsafeExecutor.java#L94-L96 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyStore.java | KeyStore.getEntry | public final Entry getEntry(String alias, ProtectionParameter protParam)
throws NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException {
if (alias == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetEntry(alias, protParam);
} | java | public final Entry getEntry(String alias, ProtectionParameter protParam)
throws NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException {
if (alias == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetEntry(alias, protParam);
} | [
"public",
"final",
"Entry",
"getEntry",
"(",
"String",
"alias",
",",
"ProtectionParameter",
"protParam",
")",
"throws",
"NoSuchAlgorithmException",
",",
"UnrecoverableEntryException",
",",
"KeyStoreException",
"{",
"if",
"(",
"alias",
"==",
"null",
")",
"{",
"throw"... | Gets a keystore <code>Entry</code> for the specified alias
with the specified protection parameter.
@param alias get the keystore <code>Entry</code> for this alias
@param protParam the <code>ProtectionParameter</code>
used to protect the <code>Entry</code>,
which may be <code>null</code>
@return the keystore <code>Entry</code> for the specified alias,
or <code>null</code> if there is no such entry
@exception NullPointerException if
<code>alias</code> is <code>null</code>
@exception NoSuchAlgorithmException if the algorithm for recovering the
entry cannot be found
@exception UnrecoverableEntryException if the specified
<code>protParam</code> were insufficient or invalid
@exception UnrecoverableKeyException if the entry is a
<code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
and the specified <code>protParam</code> does not contain
the information needed to recover the key (e.g. wrong password)
@exception KeyStoreException if the keystore has not been initialized
(loaded).
@see #setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
@since 1.5 | [
"Gets",
"a",
"keystore",
"<code",
">",
"Entry<",
"/",
"code",
">",
"for",
"the",
"specified",
"alias",
"with",
"the",
"specified",
"protection",
"parameter",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyStore.java#L1322-L1333 |
VueGWT/vue-gwt | processors/src/main/java/com/axellience/vuegwt/processors/component/factory/VueComponentFactoryGenerator.java | VueComponentFactoryGenerator.registerLocalDirectives | private void registerLocalDirectives(Component annotation, MethodSpec.Builder initBuilder) {
try {
Class<?>[] componentsClass = annotation.directives();
if (componentsClass.length > 0) {
addGetDirectivesStatement(initBuilder);
}
Stream
.of(componentsClass)
.forEach(clazz -> initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(clazz.getName()),
directiveOptionsName(clazz)));
} catch (MirroredTypesException mte) {
List<DeclaredType> classTypeMirrors = (List<DeclaredType>) mte.getTypeMirrors();
if (!classTypeMirrors.isEmpty()) {
addGetDirectivesStatement(initBuilder);
}
classTypeMirrors.forEach(classTypeMirror -> {
TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(classTypeElement.getSimpleName().toString()),
directiveOptionsName(classTypeElement));
});
}
} | java | private void registerLocalDirectives(Component annotation, MethodSpec.Builder initBuilder) {
try {
Class<?>[] componentsClass = annotation.directives();
if (componentsClass.length > 0) {
addGetDirectivesStatement(initBuilder);
}
Stream
.of(componentsClass)
.forEach(clazz -> initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(clazz.getName()),
directiveOptionsName(clazz)));
} catch (MirroredTypesException mte) {
List<DeclaredType> classTypeMirrors = (List<DeclaredType>) mte.getTypeMirrors();
if (!classTypeMirrors.isEmpty()) {
addGetDirectivesStatement(initBuilder);
}
classTypeMirrors.forEach(classTypeMirror -> {
TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
initBuilder.addStatement("directives.set($S, new $T())",
directiveToTagName(classTypeElement.getSimpleName().toString()),
directiveOptionsName(classTypeElement));
});
}
} | [
"private",
"void",
"registerLocalDirectives",
"(",
"Component",
"annotation",
",",
"MethodSpec",
".",
"Builder",
"initBuilder",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"componentsClass",
"=",
"annotation",
".",
"directives",
"(",
")",
";",
"i... | Register directives passed to the annotation.
@param annotation The Component annotation on the Component we generate for
@param initBuilder The builder for the init method | [
"Register",
"directives",
"passed",
"to",
"the",
"annotation",
"."
] | train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/factory/VueComponentFactoryGenerator.java#L179-L206 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java | H2StreamProcessor.updateStreamReadWindow | private void updateStreamReadWindow() throws Http2Exception {
if (currentFrame instanceof FrameData) {
long frameSize = currentFrame.getPayloadLength();
streamReadWindowSize -= frameSize; // decrement stream read window
muxLink.connectionReadWindowSize -= frameSize; // decrement connection read window
// if the stream or connection windows become too small, update the windows
// TODO: decide how often we should update the read window via WINDOW_UPDATE
if (streamReadWindowSize < (muxLink.maxReadWindowSize / 2) ||
muxLink.connectionReadWindowSize < (muxLink.maxReadWindowSize / 2)) {
int windowChange = (int) (muxLink.maxReadWindowSize - this.streamReadWindowSize);
Frame savedFrame = currentFrame; // save off the current frame
if (!this.isStreamClosed()) {
currentFrame = new FrameWindowUpdate(myID, windowChange, false);
writeFrameSync();
currentFrame = savedFrame;
}
long windowSizeIncrement = muxLink.getRemoteConnectionSettings().getMaxFrameSize();
FrameWindowUpdate wuf = new FrameWindowUpdate(0, (int) windowSizeIncrement, false);
this.muxLink.getStream(0).processNextFrame(wuf, Direction.WRITING_OUT);
}
}
} | java | private void updateStreamReadWindow() throws Http2Exception {
if (currentFrame instanceof FrameData) {
long frameSize = currentFrame.getPayloadLength();
streamReadWindowSize -= frameSize; // decrement stream read window
muxLink.connectionReadWindowSize -= frameSize; // decrement connection read window
// if the stream or connection windows become too small, update the windows
// TODO: decide how often we should update the read window via WINDOW_UPDATE
if (streamReadWindowSize < (muxLink.maxReadWindowSize / 2) ||
muxLink.connectionReadWindowSize < (muxLink.maxReadWindowSize / 2)) {
int windowChange = (int) (muxLink.maxReadWindowSize - this.streamReadWindowSize);
Frame savedFrame = currentFrame; // save off the current frame
if (!this.isStreamClosed()) {
currentFrame = new FrameWindowUpdate(myID, windowChange, false);
writeFrameSync();
currentFrame = savedFrame;
}
long windowSizeIncrement = muxLink.getRemoteConnectionSettings().getMaxFrameSize();
FrameWindowUpdate wuf = new FrameWindowUpdate(0, (int) windowSizeIncrement, false);
this.muxLink.getStream(0).processNextFrame(wuf, Direction.WRITING_OUT);
}
}
} | [
"private",
"void",
"updateStreamReadWindow",
"(",
")",
"throws",
"Http2Exception",
"{",
"if",
"(",
"currentFrame",
"instanceof",
"FrameData",
")",
"{",
"long",
"frameSize",
"=",
"currentFrame",
".",
"getPayloadLength",
"(",
")",
";",
"streamReadWindowSize",
"-=",
... | If this stream is receiving a DATA frame, the local read window needs to be updated. If the read window drops below a threshold,
a WINDOW_UPDATE frame will be sent for both the connection and stream to update the windows. | [
"If",
"this",
"stream",
"is",
"receiving",
"a",
"DATA",
"frame",
"the",
"local",
"read",
"window",
"needs",
"to",
"be",
"updated",
".",
"If",
"the",
"read",
"window",
"drops",
"below",
"a",
"threshold",
"a",
"WINDOW_UPDATE",
"frame",
"will",
"be",
"sent",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java#L756-L779 |
structlogging/structlogger | structlogger/src/main/java/com/github/structlogging/processor/LogInvocationScanner.java | LogInvocationScanner.formatWithStatementLocation | private String formatWithStatementLocation(String format, StatementInfo statementInfo, Object... args) {
return format(format, args) + format(" [%s:%s]", statementInfo.getSourceFileName(), statementInfo.getLineNumber());
} | java | private String formatWithStatementLocation(String format, StatementInfo statementInfo, Object... args) {
return format(format, args) + format(" [%s:%s]", statementInfo.getSourceFileName(), statementInfo.getLineNumber());
} | [
"private",
"String",
"formatWithStatementLocation",
"(",
"String",
"format",
",",
"StatementInfo",
"statementInfo",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"format",
"(",
"format",
",",
"args",
")",
"+",
"format",
"(",
"\" [%s:%s]\"",
",",
"statementIn... | System.format with string representing statement location added at the end | [
"System",
".",
"format",
"with",
"string",
"representing",
"statement",
"location",
"added",
"at",
"the",
"end"
] | train | https://github.com/structlogging/structlogger/blob/1fcca4e962ef53cbdb94bd72cb556de7f5f9469f/structlogger/src/main/java/com/github/structlogging/processor/LogInvocationScanner.java#L357-L359 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/fieldprocessor/RecordMethodFacatory.java | RecordMethodFacatory.create | public RecordMethodCache create(final Class<?> recordClass, final ProcessCase processCase) {
ArgUtils.notNull(recordClass, "recordClass");
final RecordMethodCache recordMethod = new RecordMethodCache();
setupIgnoreableMethod(recordMethod, recordClass, processCase);
setupListenerCallbackMethods(recordMethod, recordClass);
setupRecordCallbackMethods(recordMethod, recordClass);
return recordMethod;
} | java | public RecordMethodCache create(final Class<?> recordClass, final ProcessCase processCase) {
ArgUtils.notNull(recordClass, "recordClass");
final RecordMethodCache recordMethod = new RecordMethodCache();
setupIgnoreableMethod(recordMethod, recordClass, processCase);
setupListenerCallbackMethods(recordMethod, recordClass);
setupRecordCallbackMethods(recordMethod, recordClass);
return recordMethod;
} | [
"public",
"RecordMethodCache",
"create",
"(",
"final",
"Class",
"<",
"?",
">",
"recordClass",
",",
"final",
"ProcessCase",
"processCase",
")",
"{",
"ArgUtils",
".",
"notNull",
"(",
"recordClass",
",",
"\"recordClass\"",
")",
";",
"final",
"RecordMethodCache",
"r... | レコードクラスを元に、{@link RecordMethodCache}のインスタンスを組み立てる。
@param recordClass レコードクラス
@param processCase 現在の処理ケース
@return {@link RecordMethodCache}のインスタンス
@throws IllegalArgumentException {@literal recordClass == null} | [
"レコードクラスを元に、",
"{",
"@link",
"RecordMethodCache",
"}",
"のインスタンスを組み立てる。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/fieldprocessor/RecordMethodFacatory.java#L52-L63 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/MPXWriter.java | MPXWriter.writeNotes | private void writeNotes(int recordNumber, String text) throws IOException
{
m_buffer.setLength(0);
m_buffer.append(recordNumber);
m_buffer.append(m_delimiter);
if (text != null)
{
String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);
boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('"') != -1);
int length = note.length();
char c;
if (quote == true)
{
m_buffer.append('"');
}
for (int loop = 0; loop < length; loop++)
{
c = note.charAt(loop);
switch (c)
{
case '"':
{
m_buffer.append("\"\"");
break;
}
default:
{
m_buffer.append(c);
break;
}
}
}
if (quote == true)
{
m_buffer.append('"');
}
}
m_buffer.append(MPXConstants.EOL);
m_writer.write(m_buffer.toString());
} | java | private void writeNotes(int recordNumber, String text) throws IOException
{
m_buffer.setLength(0);
m_buffer.append(recordNumber);
m_buffer.append(m_delimiter);
if (text != null)
{
String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);
boolean quote = (note.indexOf(m_delimiter) != -1 || note.indexOf('"') != -1);
int length = note.length();
char c;
if (quote == true)
{
m_buffer.append('"');
}
for (int loop = 0; loop < length; loop++)
{
c = note.charAt(loop);
switch (c)
{
case '"':
{
m_buffer.append("\"\"");
break;
}
default:
{
m_buffer.append(c);
break;
}
}
}
if (quote == true)
{
m_buffer.append('"');
}
}
m_buffer.append(MPXConstants.EOL);
m_writer.write(m_buffer.toString());
} | [
"private",
"void",
"writeNotes",
"(",
"int",
"recordNumber",
",",
"String",
"text",
")",
"throws",
"IOException",
"{",
"m_buffer",
".",
"setLength",
"(",
"0",
")",
";",
"m_buffer",
".",
"append",
"(",
"recordNumber",
")",
";",
"m_buffer",
".",
"append",
"(... | Write notes.
@param recordNumber record number
@param text note text
@throws IOException | [
"Write",
"notes",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXWriter.java#L554-L602 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.iterateChars | public static void iterateChars (@Nullable final String sInputString, @Nonnull final ICharConsumer aConsumer)
{
ValueEnforcer.notNull (aConsumer, "Consumer");
if (sInputString != null)
{
final char [] aInput = sInputString.toCharArray ();
for (final char cInput : aInput)
aConsumer.accept (cInput);
}
} | java | public static void iterateChars (@Nullable final String sInputString, @Nonnull final ICharConsumer aConsumer)
{
ValueEnforcer.notNull (aConsumer, "Consumer");
if (sInputString != null)
{
final char [] aInput = sInputString.toCharArray ();
for (final char cInput : aInput)
aConsumer.accept (cInput);
}
} | [
"public",
"static",
"void",
"iterateChars",
"(",
"@",
"Nullable",
"final",
"String",
"sInputString",
",",
"@",
"Nonnull",
"final",
"ICharConsumer",
"aConsumer",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aConsumer",
",",
"\"Consumer\"",
")",
";",
"if",
"... | Iterate all characters and pass them to the provided consumer.
@param sInputString
Input String to use. May be <code>null</code> or empty.
@param aConsumer
The consumer to be used. May not be <code>null</code>. | [
"Iterate",
"all",
"characters",
"and",
"pass",
"them",
"to",
"the",
"provided",
"consumer",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L5225-L5235 |
cvent/pangaea | src/main/java/com/cvent/pangaea/MultiEnvAware.java | MultiEnvAware.convert | public <R> MultiEnvAware<R> convert(BiFunction<String, T, R> func) {
return convert(func, null);
} | java | public <R> MultiEnvAware<R> convert(BiFunction<String, T, R> func) {
return convert(func, null);
} | [
"public",
"<",
"R",
">",
"MultiEnvAware",
"<",
"R",
">",
"convert",
"(",
"BiFunction",
"<",
"String",
",",
"T",
",",
"R",
">",
"func",
")",
"{",
"return",
"convert",
"(",
"func",
",",
"null",
")",
";",
"}"
] | Utility method for MultiEnvAware config transformation
@param <R>
@param func - transformation function
@return new MultiEnvAware instance | [
"Utility",
"method",
"for",
"MultiEnvAware",
"config",
"transformation"
] | train | https://github.com/cvent/pangaea/blob/6cd213c370817905ae04a67db07347a4e29a708c/src/main/java/com/cvent/pangaea/MultiEnvAware.java#L45-L47 |
stratosphere/stratosphere | stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/BulkIterationNode.java | BulkIterationNode.setNextPartialSolution | public void setNextPartialSolution(OptimizerNode nextPartialSolution, OptimizerNode terminationCriterion) {
// check if the root of the step function has the same DOP as the iteration
if (nextPartialSolution.getDegreeOfParallelism() != getDegreeOfParallelism() ||
nextPartialSolution.getSubtasksPerInstance() != getSubtasksPerInstance() )
{
// add a no-op to the root to express the re-partitioning
NoOpNode noop = new NoOpNode();
noop.setDegreeOfParallelism(getDegreeOfParallelism());
noop.setSubtasksPerInstance(getSubtasksPerInstance());
PactConnection noOpConn = new PactConnection(nextPartialSolution, noop);
noop.setIncomingConnection(noOpConn);
nextPartialSolution.addOutgoingConnection(noOpConn);
nextPartialSolution = noop;
}
this.nextPartialSolution = nextPartialSolution;
this.terminationCriterion = terminationCriterion;
if (terminationCriterion == null) {
this.singleRoot = nextPartialSolution;
this.rootConnection = new PactConnection(nextPartialSolution);
}
else {
// we have a termination criterion
SingleRootJoiner singleRootJoiner = new SingleRootJoiner();
this.rootConnection = new PactConnection(nextPartialSolution, singleRootJoiner);
this.terminationCriterionRootConnection = new PactConnection(terminationCriterion, singleRootJoiner);
singleRootJoiner.setInputs(this.rootConnection, this.terminationCriterionRootConnection);
this.singleRoot = singleRootJoiner;
// add connection to terminationCriterion for interesting properties visitor
terminationCriterion.addOutgoingConnection(terminationCriterionRootConnection);
}
nextPartialSolution.addOutgoingConnection(rootConnection);
} | java | public void setNextPartialSolution(OptimizerNode nextPartialSolution, OptimizerNode terminationCriterion) {
// check if the root of the step function has the same DOP as the iteration
if (nextPartialSolution.getDegreeOfParallelism() != getDegreeOfParallelism() ||
nextPartialSolution.getSubtasksPerInstance() != getSubtasksPerInstance() )
{
// add a no-op to the root to express the re-partitioning
NoOpNode noop = new NoOpNode();
noop.setDegreeOfParallelism(getDegreeOfParallelism());
noop.setSubtasksPerInstance(getSubtasksPerInstance());
PactConnection noOpConn = new PactConnection(nextPartialSolution, noop);
noop.setIncomingConnection(noOpConn);
nextPartialSolution.addOutgoingConnection(noOpConn);
nextPartialSolution = noop;
}
this.nextPartialSolution = nextPartialSolution;
this.terminationCriterion = terminationCriterion;
if (terminationCriterion == null) {
this.singleRoot = nextPartialSolution;
this.rootConnection = new PactConnection(nextPartialSolution);
}
else {
// we have a termination criterion
SingleRootJoiner singleRootJoiner = new SingleRootJoiner();
this.rootConnection = new PactConnection(nextPartialSolution, singleRootJoiner);
this.terminationCriterionRootConnection = new PactConnection(terminationCriterion, singleRootJoiner);
singleRootJoiner.setInputs(this.rootConnection, this.terminationCriterionRootConnection);
this.singleRoot = singleRootJoiner;
// add connection to terminationCriterion for interesting properties visitor
terminationCriterion.addOutgoingConnection(terminationCriterionRootConnection);
}
nextPartialSolution.addOutgoingConnection(rootConnection);
} | [
"public",
"void",
"setNextPartialSolution",
"(",
"OptimizerNode",
"nextPartialSolution",
",",
"OptimizerNode",
"terminationCriterion",
")",
"{",
"// check if the root of the step function has the same DOP as the iteration",
"if",
"(",
"nextPartialSolution",
".",
"getDegreeOfParalleli... | Sets the nextPartialSolution for this BulkIterationNode.
@param nextPartialSolution The nextPartialSolution to set. | [
"Sets",
"the",
"nextPartialSolution",
"for",
"this",
"BulkIterationNode",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/BulkIterationNode.java#L119-L159 |
dasein-cloud/dasein-cloud-aws | src/main/java/org/dasein/cloud/aws/AWSCloud.java | AWSCloud.addIndexedParameters | public static void addIndexedParameters( @Nonnull Map<String, String> parameters, @Nonnull String prefix, String ... values ) {
if( values == null || values.length == 0 ) {
return;
}
int i = 1;
if( !prefix.endsWith(".") ) {
prefix += ".";
}
for( String value : values ) {
parameters.put(String.format("%s%d", prefix, i), value);
i++;
}
} | java | public static void addIndexedParameters( @Nonnull Map<String, String> parameters, @Nonnull String prefix, String ... values ) {
if( values == null || values.length == 0 ) {
return;
}
int i = 1;
if( !prefix.endsWith(".") ) {
prefix += ".";
}
for( String value : values ) {
parameters.put(String.format("%s%d", prefix, i), value);
i++;
}
} | [
"public",
"static",
"void",
"addIndexedParameters",
"(",
"@",
"Nonnull",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
",",
"@",
"Nonnull",
"String",
"prefix",
",",
"String",
"...",
"values",
")",
"{",
"if",
"(",
"values",
"==",
"null",
"||",
"... | Helper method for adding indexed member parameters, e.g. <i>AlarmNames.member.N</i>. Will overwrite existing
parameters if present. Assumes indexing starts at 1.
@param parameters the existing parameters map to add to
@param prefix the prefix value for each parameter key
@param values the values to add | [
"Helper",
"method",
"for",
"adding",
"indexed",
"member",
"parameters",
"e",
".",
"g",
".",
"<i",
">",
"AlarmNames",
".",
"member",
".",
"N<",
"/",
"i",
">",
".",
"Will",
"overwrite",
"existing",
"parameters",
"if",
"present",
".",
"Assumes",
"indexing",
... | train | https://github.com/dasein-cloud/dasein-cloud-aws/blob/05098574197a1f573f77447cadc39a76bf00b99d/src/main/java/org/dasein/cloud/aws/AWSCloud.java#L1393-L1405 |
FasterXML/jackson-jr | jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/impl/ValueReaderLocator.java | ValueReaderLocator.findReader | public ValueReader findReader(Class<?> raw)
{
ClassKey k = (_key == null) ? new ClassKey(raw, _features) : _key.with(raw, _features);
ValueReader vr = _knownReaders.get(k);
if (vr != null) {
return vr;
}
vr = createReader(null, raw, raw);
// 15-Jun-2016, tatu: Let's limit maximum number of readers to prevent
// unbounded memory retention (at least wrt readers)
if (_knownReaders.size() >= MAX_CACHED_READERS) {
_knownReaders.clear();
}
_knownReaders.putIfAbsent(new ClassKey(raw, _features), vr);
return vr;
} | java | public ValueReader findReader(Class<?> raw)
{
ClassKey k = (_key == null) ? new ClassKey(raw, _features) : _key.with(raw, _features);
ValueReader vr = _knownReaders.get(k);
if (vr != null) {
return vr;
}
vr = createReader(null, raw, raw);
// 15-Jun-2016, tatu: Let's limit maximum number of readers to prevent
// unbounded memory retention (at least wrt readers)
if (_knownReaders.size() >= MAX_CACHED_READERS) {
_knownReaders.clear();
}
_knownReaders.putIfAbsent(new ClassKey(raw, _features), vr);
return vr;
} | [
"public",
"ValueReader",
"findReader",
"(",
"Class",
"<",
"?",
">",
"raw",
")",
"{",
"ClassKey",
"k",
"=",
"(",
"_key",
"==",
"null",
")",
"?",
"new",
"ClassKey",
"(",
"raw",
",",
"_features",
")",
":",
"_key",
".",
"with",
"(",
"raw",
",",
"_featu... | Method used during deserialization to find handler for given
non-generic type. | [
"Method",
"used",
"during",
"deserialization",
"to",
"find",
"handler",
"for",
"given",
"non",
"-",
"generic",
"type",
"."
] | train | https://github.com/FasterXML/jackson-jr/blob/62ca7a82bd90a9be77028e0b62364307d7532837/jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/impl/ValueReaderLocator.java#L136-L151 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/UtilColor.java | UtilColor.getDelta | public static double getDelta(ColorRgba a, ColorRgba b)
{
Check.notNull(a);
Check.notNull(b);
final int dr = a.getRed() - b.getRed();
final int dg = a.getGreen() - b.getGreen();
final int db = a.getBlue() - b.getBlue();
return Math.sqrt(dr * dr + dg * dg + db * db);
} | java | public static double getDelta(ColorRgba a, ColorRgba b)
{
Check.notNull(a);
Check.notNull(b);
final int dr = a.getRed() - b.getRed();
final int dg = a.getGreen() - b.getGreen();
final int db = a.getBlue() - b.getBlue();
return Math.sqrt(dr * dr + dg * dg + db * db);
} | [
"public",
"static",
"double",
"getDelta",
"(",
"ColorRgba",
"a",
",",
"ColorRgba",
"b",
")",
"{",
"Check",
".",
"notNull",
"(",
"a",
")",
";",
"Check",
".",
"notNull",
"(",
"b",
")",
";",
"final",
"int",
"dr",
"=",
"a",
".",
"getRed",
"(",
")",
"... | Return the delta between two colors.
@param a The first color (must not be <code>null</code>).
@param b The second color (must not be <code>null</code>).
@return The delta between the two colors.
@throws LionEngineException If invalid arguments. | [
"Return",
"the",
"delta",
"between",
"two",
"colors",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/UtilColor.java#L97-L107 |
marklogic/java-client-api | marklogic-client-api/src/main/java/com/marklogic/client/DatabaseClientFactory.java | DatabaseClientFactory.newClient | static public DatabaseClient newClient(String host, int port, String database, SecurityContext securityContext) {
return newClient(host, port, database, securityContext, null);
} | java | static public DatabaseClient newClient(String host, int port, String database, SecurityContext securityContext) {
return newClient(host, port, database, securityContext, null);
} | [
"static",
"public",
"DatabaseClient",
"newClient",
"(",
"String",
"host",
",",
"int",
"port",
",",
"String",
"database",
",",
"SecurityContext",
"securityContext",
")",
"{",
"return",
"newClient",
"(",
"host",
",",
"port",
",",
"database",
",",
"securityContext"... | Creates a client to access the database by means of a REST server.
The CallManager interface can only call an endpoint for the configured content database
of the appserver. You cannot specify the database when constructing a client for working
with a CallManager.
@param host the host with the REST server
@param port the port for the REST server
@param database the database to access (default: configured database for
the REST server)
@param securityContext the security context created depending upon the
authentication type - BasicAuthContext, DigestAuthContext or KerberosAuthContext
and communication channel type (SSL)
@return a new client for making database requests | [
"Creates",
"a",
"client",
"to",
"access",
"the",
"database",
"by",
"means",
"of",
"a",
"REST",
"server",
"."
] | train | https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/DatabaseClientFactory.java#L1191-L1193 |
apache/groovy | src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java | StaticTypesCallSiteWriter.setField | private boolean setField(PropertyExpression expression, Expression objectExpression, ClassNode rType, String name) {
if (expression.isSafe()) return false;
FieldNode fn = AsmClassGenerator.getDeclaredFieldOfCurrentClassOrAccessibleFieldOfSuper(controller.getClassNode(), rType, name, false);
if (fn==null) return false;
OperandStack stack = controller.getOperandStack();
stack.doGroovyCast(fn.getType());
MethodVisitor mv = controller.getMethodVisitor();
String ownerName = BytecodeHelper.getClassInternalName(fn.getOwner());
if (!fn.isStatic()) {
controller.getCompileStack().pushLHS(false);
objectExpression.visit(controller.getAcg());
controller.getCompileStack().popLHS();
if (!rType.equals(stack.getTopOperand())) {
BytecodeHelper.doCast(mv, rType);
stack.replace(rType);
}
stack.swap();
mv.visitFieldInsn(PUTFIELD, ownerName, name, BytecodeHelper.getTypeDescription(fn.getType()));
stack.remove(1);
} else {
mv.visitFieldInsn(PUTSTATIC, ownerName, name, BytecodeHelper.getTypeDescription(fn.getType()));
}
//mv.visitInsn(ACONST_NULL);
//stack.replace(OBJECT_TYPE);
return true;
} | java | private boolean setField(PropertyExpression expression, Expression objectExpression, ClassNode rType, String name) {
if (expression.isSafe()) return false;
FieldNode fn = AsmClassGenerator.getDeclaredFieldOfCurrentClassOrAccessibleFieldOfSuper(controller.getClassNode(), rType, name, false);
if (fn==null) return false;
OperandStack stack = controller.getOperandStack();
stack.doGroovyCast(fn.getType());
MethodVisitor mv = controller.getMethodVisitor();
String ownerName = BytecodeHelper.getClassInternalName(fn.getOwner());
if (!fn.isStatic()) {
controller.getCompileStack().pushLHS(false);
objectExpression.visit(controller.getAcg());
controller.getCompileStack().popLHS();
if (!rType.equals(stack.getTopOperand())) {
BytecodeHelper.doCast(mv, rType);
stack.replace(rType);
}
stack.swap();
mv.visitFieldInsn(PUTFIELD, ownerName, name, BytecodeHelper.getTypeDescription(fn.getType()));
stack.remove(1);
} else {
mv.visitFieldInsn(PUTSTATIC, ownerName, name, BytecodeHelper.getTypeDescription(fn.getType()));
}
//mv.visitInsn(ACONST_NULL);
//stack.replace(OBJECT_TYPE);
return true;
} | [
"private",
"boolean",
"setField",
"(",
"PropertyExpression",
"expression",
",",
"Expression",
"objectExpression",
",",
"ClassNode",
"rType",
",",
"String",
"name",
")",
"{",
"if",
"(",
"expression",
".",
"isSafe",
"(",
")",
")",
"return",
"false",
";",
"FieldN... | this is just a simple set field handling static and non-static, but not Closure and inner classes | [
"this",
"is",
"just",
"a",
"simple",
"set",
"field",
"handling",
"static",
"and",
"non",
"-",
"static",
"but",
"not",
"Closure",
"and",
"inner",
"classes"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesCallSiteWriter.java#L902-L929 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/JMProgressiveManager.java | JMProgressiveManager.registerLastResultChangeListener | public JMProgressiveManager<T, R> registerLastResultChangeListener(
Consumer<Optional<R>> resultChangeListener) {
return registerListener(lastResult, resultChangeListener);
} | java | public JMProgressiveManager<T, R> registerLastResultChangeListener(
Consumer<Optional<R>> resultChangeListener) {
return registerListener(lastResult, resultChangeListener);
} | [
"public",
"JMProgressiveManager",
"<",
"T",
",",
"R",
">",
"registerLastResultChangeListener",
"(",
"Consumer",
"<",
"Optional",
"<",
"R",
">",
">",
"resultChangeListener",
")",
"{",
"return",
"registerListener",
"(",
"lastResult",
",",
"resultChangeListener",
")",
... | Register last result change listener jm progressive manager.
@param resultChangeListener the result change listener
@return the jm progressive manager | [
"Register",
"last",
"result",
"change",
"listener",
"jm",
"progressive",
"manager",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/JMProgressiveManager.java#L202-L205 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java | ObjectArrayList.beforeInsertDummies | protected void beforeInsertDummies(int index, int length) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
if (length > 0) {
ensureCapacity(size + length);
System.arraycopy(elements, index, elements, index + length, size-index);
size += length;
}
} | java | protected void beforeInsertDummies(int index, int length) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
if (length > 0) {
ensureCapacity(size + length);
System.arraycopy(elements, index, elements, index + length, size-index);
size += length;
}
} | [
"protected",
"void",
"beforeInsertDummies",
"(",
"int",
"index",
",",
"int",
"length",
")",
"{",
"if",
"(",
"index",
">",
"size",
"||",
"index",
"<",
"0",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Index: \"",
"+",
"index",
"+",
"\", Size: \""... | Inserts length dummies before the specified position into the receiver.
Shifts the element currently at that position (if any) and
any subsequent elements to the right.
@param index index before which to insert dummies (must be in [0,size])..
@param length number of dummies to be inserted. | [
"Inserts",
"length",
"dummies",
"before",
"the",
"specified",
"position",
"into",
"the",
"receiver",
".",
"Shifts",
"the",
"element",
"currently",
"at",
"that",
"position",
"(",
"if",
"any",
")",
"and",
"any",
"subsequent",
"elements",
"to",
"the",
"right",
... | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L119-L127 |
morimekta/providence | providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/program/extras/HazelcastPortableProgramFormatter.java | HazelcastPortableProgramFormatter.appendCollectionTypeField | private void appendCollectionTypeField(JField field, PDescriptor descriptor) {
switch (descriptor.getType()) {
case BYTE:
case BINARY:
writer.formatln(".addByteArrayField(\"%s\")", field.name());
break;
case BOOL:
writer.formatln(".addBooleanArrayField(\"%s\")", field.name());
break;
case DOUBLE:
writer.formatln(".addDoubleArrayField(\"%s\")", field.name());
break;
case I16:
writer.formatln(".addShortArrayField(\"%s\")", field.name());
break;
case I32:
case ENUM:
writer.formatln(".addIntArrayField(\"%s\")", field.name());
break;
case I64:
writer.formatln(".addLongArrayField(\"%s\")", field.name());
break;
case STRING:
writer.formatln(".addUTFArrayField(\"%s\")", field.name());
break;
case MESSAGE:
writer.formatln(".addPortableArrayField(\"%s\", %s(%s))",
field.name(),
camelCase("get", descriptor.getName() + "Definition"),
PORTABLE_VERSION);
break;
default:
throw new GeneratorException(
"Not implemented appendCollectionTypeField for list with type: " + descriptor.getType() + " in " +
this.getClass()
.getSimpleName());
}
} | java | private void appendCollectionTypeField(JField field, PDescriptor descriptor) {
switch (descriptor.getType()) {
case BYTE:
case BINARY:
writer.formatln(".addByteArrayField(\"%s\")", field.name());
break;
case BOOL:
writer.formatln(".addBooleanArrayField(\"%s\")", field.name());
break;
case DOUBLE:
writer.formatln(".addDoubleArrayField(\"%s\")", field.name());
break;
case I16:
writer.formatln(".addShortArrayField(\"%s\")", field.name());
break;
case I32:
case ENUM:
writer.formatln(".addIntArrayField(\"%s\")", field.name());
break;
case I64:
writer.formatln(".addLongArrayField(\"%s\")", field.name());
break;
case STRING:
writer.formatln(".addUTFArrayField(\"%s\")", field.name());
break;
case MESSAGE:
writer.formatln(".addPortableArrayField(\"%s\", %s(%s))",
field.name(),
camelCase("get", descriptor.getName() + "Definition"),
PORTABLE_VERSION);
break;
default:
throw new GeneratorException(
"Not implemented appendCollectionTypeField for list with type: " + descriptor.getType() + " in " +
this.getClass()
.getSimpleName());
}
} | [
"private",
"void",
"appendCollectionTypeField",
"(",
"JField",
"field",
",",
"PDescriptor",
"descriptor",
")",
"{",
"switch",
"(",
"descriptor",
".",
"getType",
"(",
")",
")",
"{",
"case",
"BYTE",
":",
"case",
"BINARY",
":",
"writer",
".",
"formatln",
"(",
... | Append a specific list type field to the definition.
@param field JField to append.
<pre>
{@code
.addShortArrayField("shortValues")
}
</pre> | [
"Append",
"a",
"specific",
"list",
"type",
"field",
"to",
"the",
"definition",
"."
] | train | https://github.com/morimekta/providence/blob/7c17dc1c96b1a1d4b9ff942c2cfeb725278bd3aa/providence-generator-java/src/main/java/net/morimekta/providence/generator/format/java/program/extras/HazelcastPortableProgramFormatter.java#L333-L370 |
looly/hutool | hutool-http/src/main/java/cn/hutool/http/HttpUtil.java | HttpUtil.addParam | private static void addParam(Map<String, List<String>> params, String name, String value, String charset) {
name = URLUtil.decode(name, charset);
value = URLUtil.decode(value, charset);
List<String> values = params.get(name);
if (values == null) {
values = new ArrayList<String>(1); // 一般是一个参数
params.put(name, values);
}
values.add(value);
} | java | private static void addParam(Map<String, List<String>> params, String name, String value, String charset) {
name = URLUtil.decode(name, charset);
value = URLUtil.decode(value, charset);
List<String> values = params.get(name);
if (values == null) {
values = new ArrayList<String>(1); // 一般是一个参数
params.put(name, values);
}
values.add(value);
} | [
"private",
"static",
"void",
"addParam",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"params",
",",
"String",
"name",
",",
"String",
"value",
",",
"String",
"charset",
")",
"{",
"name",
"=",
"URLUtil",
".",
"decode",
"(",
"name",
... | 将键值对加入到值为List类型的Map中
@param params 参数
@param name key
@param value value
@param charset 编码 | [
"将键值对加入到值为List类型的Map中"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpUtil.java#L763-L772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.