repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
amazon-archives/aws-sdk-java-resources
|
aws-resources-core/src/main/java/com/amazonaws/resources/internal/ReflectionUtils.java
|
ReflectionUtils.getByPath
|
public static Object getByPath(Object target, List<String> path) {
"""
Evaluates the given path expression on the given object and returns the
object found.
@param target the object to reflect on
@param path the path to evaluate
@return the result of evaluating the path against the given object
"""
Object obj = target;
for (String field : path) {
if (obj == null) {
return null;
}
obj = evaluate(obj, trimType(field));
}
return obj;
}
|
java
|
public static Object getByPath(Object target, List<String> path) {
Object obj = target;
for (String field : path) {
if (obj == null) {
return null;
}
obj = evaluate(obj, trimType(field));
}
return obj;
}
|
[
"public",
"static",
"Object",
"getByPath",
"(",
"Object",
"target",
",",
"List",
"<",
"String",
">",
"path",
")",
"{",
"Object",
"obj",
"=",
"target",
";",
"for",
"(",
"String",
"field",
":",
"path",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"obj",
"=",
"evaluate",
"(",
"obj",
",",
"trimType",
"(",
"field",
")",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
Evaluates the given path expression on the given object and returns the
object found.
@param target the object to reflect on
@param path the path to evaluate
@return the result of evaluating the path against the given object
|
[
"Evaluates",
"the",
"given",
"path",
"expression",
"on",
"the",
"given",
"object",
"and",
"returns",
"the",
"object",
"found",
"."
] |
train
|
https://github.com/amazon-archives/aws-sdk-java-resources/blob/0f4fef2615d9687997b70a36eed1d62dd42df035/aws-resources-core/src/main/java/com/amazonaws/resources/internal/ReflectionUtils.java#L112-L123
|
rsqn/useful-things
|
lambda-utilities/src/main/java/tech/rsqn/useful/things/lambda/LambdaSpringUtil.java
|
LambdaSpringUtil.wireInSpring
|
public static void wireInSpring(Object o, String myBeanName) {
"""
wires spring into the passed in bean
@param o
@param myBeanName
"""
// Lambda does not do this for you - though serverless does have a library to do it
if (ctx == null) {
synchronized (lck) {
if (ctx == null) {
LOG.info("LamdaSpringUtil CTX is null - initialising spring");
ctx = new ClassPathXmlApplicationContext(globalRootContextPath);
}
}
} else {
LOG.debug("LamdaSpringUtil CTX is not null - not initialising spring");
}
AutowireCapableBeanFactory factory = ctx.getAutowireCapableBeanFactory();
factory.autowireBean(o);
factory.initializeBean(0, myBeanName);
}
|
java
|
public static void wireInSpring(Object o, String myBeanName) {
// Lambda does not do this for you - though serverless does have a library to do it
if (ctx == null) {
synchronized (lck) {
if (ctx == null) {
LOG.info("LamdaSpringUtil CTX is null - initialising spring");
ctx = new ClassPathXmlApplicationContext(globalRootContextPath);
}
}
} else {
LOG.debug("LamdaSpringUtil CTX is not null - not initialising spring");
}
AutowireCapableBeanFactory factory = ctx.getAutowireCapableBeanFactory();
factory.autowireBean(o);
factory.initializeBean(0, myBeanName);
}
|
[
"public",
"static",
"void",
"wireInSpring",
"(",
"Object",
"o",
",",
"String",
"myBeanName",
")",
"{",
"// Lambda does not do this for you - though serverless does have a library to do it",
"if",
"(",
"ctx",
"==",
"null",
")",
"{",
"synchronized",
"(",
"lck",
")",
"{",
"if",
"(",
"ctx",
"==",
"null",
")",
"{",
"LOG",
".",
"info",
"(",
"\"LamdaSpringUtil CTX is null - initialising spring\"",
")",
";",
"ctx",
"=",
"new",
"ClassPathXmlApplicationContext",
"(",
"globalRootContextPath",
")",
";",
"}",
"}",
"}",
"else",
"{",
"LOG",
".",
"debug",
"(",
"\"LamdaSpringUtil CTX is not null - not initialising spring\"",
")",
";",
"}",
"AutowireCapableBeanFactory",
"factory",
"=",
"ctx",
".",
"getAutowireCapableBeanFactory",
"(",
")",
";",
"factory",
".",
"autowireBean",
"(",
"o",
")",
";",
"factory",
".",
"initializeBean",
"(",
"0",
",",
"myBeanName",
")",
";",
"}"
] |
wires spring into the passed in bean
@param o
@param myBeanName
|
[
"wires",
"spring",
"into",
"the",
"passed",
"in",
"bean"
] |
train
|
https://github.com/rsqn/useful-things/blob/a21e6a9e07b97b0c239ff57a8efcb7385f645558/lambda-utilities/src/main/java/tech/rsqn/useful/things/lambda/LambdaSpringUtil.java#L63-L78
|
Azure/azure-sdk-for-java
|
recoveryservices.backup/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_06_01/implementation/BackupEnginesInner.java
|
BackupEnginesInner.getWithServiceResponseAsync
|
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> getWithServiceResponseAsync(final String vaultName, final String resourceGroupName, final String filter, final String skipToken) {
"""
The backup management servers registered to a Recovery Services vault. This returns a pageable list of servers.
@param vaultName The name of the Recovery Services vault.
@param resourceGroupName The name of the resource group associated with the Recovery Services vault.
@param filter Use this filter to choose the specific backup management server. backupManagementType { AzureIaasVM, MAB, DPM, AzureBackupServer, AzureSql }.
@param skipToken The Skip Token filter.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<BackupEngineBaseResourceInner> object
"""
return getSinglePageAsync(vaultName, resourceGroupName, filter, skipToken)
.concatMap(new Func1<ServiceResponse<Page<BackupEngineBaseResourceInner>>, Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> call(ServiceResponse<Page<BackupEngineBaseResourceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getNextWithServiceResponseAsync(nextPageLink));
}
});
}
|
java
|
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> getWithServiceResponseAsync(final String vaultName, final String resourceGroupName, final String filter, final String skipToken) {
return getSinglePageAsync(vaultName, resourceGroupName, filter, skipToken)
.concatMap(new Func1<ServiceResponse<Page<BackupEngineBaseResourceInner>>, Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> call(ServiceResponse<Page<BackupEngineBaseResourceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getNextWithServiceResponseAsync(nextPageLink));
}
});
}
|
[
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"BackupEngineBaseResourceInner",
">",
">",
">",
"getWithServiceResponseAsync",
"(",
"final",
"String",
"vaultName",
",",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"filter",
",",
"final",
"String",
"skipToken",
")",
"{",
"return",
"getSinglePageAsync",
"(",
"vaultName",
",",
"resourceGroupName",
",",
"filter",
",",
"skipToken",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"BackupEngineBaseResourceInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"BackupEngineBaseResourceInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"BackupEngineBaseResourceInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"BackupEngineBaseResourceInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"getNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
The backup management servers registered to a Recovery Services vault. This returns a pageable list of servers.
@param vaultName The name of the Recovery Services vault.
@param resourceGroupName The name of the resource group associated with the Recovery Services vault.
@param filter Use this filter to choose the specific backup management server. backupManagementType { AzureIaasVM, MAB, DPM, AzureBackupServer, AzureSql }.
@param skipToken The Skip Token filter.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<BackupEngineBaseResourceInner> object
|
[
"The",
"backup",
"management",
"servers",
"registered",
"to",
"a",
"Recovery",
"Services",
"vault",
".",
"This",
"returns",
"a",
"pageable",
"list",
"of",
"servers",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_06_01/implementation/BackupEnginesInner.java#L262-L274
|
Netflix/ndbench
|
ndbench-es-plugins/src/main/java/com/netflix/ndbench/plugin/es/EsAutoTuner.java
|
EsAutoTuner.recommendNewRate
|
double recommendNewRate(double currentRateLimit, List<WriteResult> event, NdBenchMonitor runStats) {
"""
Recommends the new write rate potentially taking into account the current rate, the result of the last write and
statistics accumulated to date. Currently only the success-to-failure ratio is considered and
compared against {@link com.netflix.ndbench.core.config.IConfiguration#getAutoTuneWriteFailureRatioThreshold()}
Note that we can ignore the possible race condition that arises if multiple threads call this method at around
the same time. In this case two threads will be attempting to set timeOfFirstAutoTuneRequest.. but the
target values they are using to set this variable be so close it will not affect the desired behavior of the
auto-tuning feature.
Note 2: this method will only be called after the ndbench driver tries to perform a writeSingle operation
"""
long currentTime = new Date().getTime();
if (timeOfFirstAutoTuneRequest < 0) { // race condition here when multiple writers, but can be ignored
timeOfFirstAutoTuneRequest = currentTime;
}
// Keep rate at current rate if calculated write failure ratio meets or exceeds configured threshold,
// But don't even do this check if a divide by zero error would result from calculating the write
// failure ratio via the formula: writesFailures / writeSuccesses
//
if (runStats.getWriteSuccess() > 0) {
double calculatedFailureRatio = runStats.getWriteFailure() / (1.0 * runStats.getWriteSuccess());
if (calculatedFailureRatio >= autoTuneFailureRatioThreshold) {
crossedAllowedFailureThreshold = true;
logger.info(
"Not considering increase of write rate limit. calculatedFailureRatio={}. threshold={}",
calculatedFailureRatio, autoTuneFailureRatioThreshold);
return currentRateLimit;
} else {
// by forgetting we crossed threshold and resetting timeOfFirstAutoTuneRequest we allow the
// write rate to drop back down to the specified initial value and we get another shot at
// trying to step wise increase to the max rate.
if (crossedAllowedFailureThreshold) {
crossedAllowedFailureThreshold = false;
timeOfFirstAutoTuneRequest = currentTime;
}
}
}
return rateIncreaser.getRateForGivenClockTime(timeOfFirstAutoTuneRequest, currentTime);
}
|
java
|
double recommendNewRate(double currentRateLimit, List<WriteResult> event, NdBenchMonitor runStats) {
long currentTime = new Date().getTime();
if (timeOfFirstAutoTuneRequest < 0) { // race condition here when multiple writers, but can be ignored
timeOfFirstAutoTuneRequest = currentTime;
}
// Keep rate at current rate if calculated write failure ratio meets or exceeds configured threshold,
// But don't even do this check if a divide by zero error would result from calculating the write
// failure ratio via the formula: writesFailures / writeSuccesses
//
if (runStats.getWriteSuccess() > 0) {
double calculatedFailureRatio = runStats.getWriteFailure() / (1.0 * runStats.getWriteSuccess());
if (calculatedFailureRatio >= autoTuneFailureRatioThreshold) {
crossedAllowedFailureThreshold = true;
logger.info(
"Not considering increase of write rate limit. calculatedFailureRatio={}. threshold={}",
calculatedFailureRatio, autoTuneFailureRatioThreshold);
return currentRateLimit;
} else {
// by forgetting we crossed threshold and resetting timeOfFirstAutoTuneRequest we allow the
// write rate to drop back down to the specified initial value and we get another shot at
// trying to step wise increase to the max rate.
if (crossedAllowedFailureThreshold) {
crossedAllowedFailureThreshold = false;
timeOfFirstAutoTuneRequest = currentTime;
}
}
}
return rateIncreaser.getRateForGivenClockTime(timeOfFirstAutoTuneRequest, currentTime);
}
|
[
"double",
"recommendNewRate",
"(",
"double",
"currentRateLimit",
",",
"List",
"<",
"WriteResult",
">",
"event",
",",
"NdBenchMonitor",
"runStats",
")",
"{",
"long",
"currentTime",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"timeOfFirstAutoTuneRequest",
"<",
"0",
")",
"{",
"// race condition here when multiple writers, but can be ignored",
"timeOfFirstAutoTuneRequest",
"=",
"currentTime",
";",
"}",
"// Keep rate at current rate if calculated write failure ratio meets or exceeds configured threshold,",
"// But don't even do this check if a divide by zero error would result from calculating the write",
"// failure ratio via the formula: writesFailures / writeSuccesses",
"//",
"if",
"(",
"runStats",
".",
"getWriteSuccess",
"(",
")",
">",
"0",
")",
"{",
"double",
"calculatedFailureRatio",
"=",
"runStats",
".",
"getWriteFailure",
"(",
")",
"/",
"(",
"1.0",
"*",
"runStats",
".",
"getWriteSuccess",
"(",
")",
")",
";",
"if",
"(",
"calculatedFailureRatio",
">=",
"autoTuneFailureRatioThreshold",
")",
"{",
"crossedAllowedFailureThreshold",
"=",
"true",
";",
"logger",
".",
"info",
"(",
"\"Not considering increase of write rate limit. calculatedFailureRatio={}. threshold={}\"",
",",
"calculatedFailureRatio",
",",
"autoTuneFailureRatioThreshold",
")",
";",
"return",
"currentRateLimit",
";",
"}",
"else",
"{",
"// by forgetting we crossed threshold and resetting timeOfFirstAutoTuneRequest we allow the",
"// write rate to drop back down to the specified initial value and we get another shot at",
"// trying to step wise increase to the max rate.",
"if",
"(",
"crossedAllowedFailureThreshold",
")",
"{",
"crossedAllowedFailureThreshold",
"=",
"false",
";",
"timeOfFirstAutoTuneRequest",
"=",
"currentTime",
";",
"}",
"}",
"}",
"return",
"rateIncreaser",
".",
"getRateForGivenClockTime",
"(",
"timeOfFirstAutoTuneRequest",
",",
"currentTime",
")",
";",
"}"
] |
Recommends the new write rate potentially taking into account the current rate, the result of the last write and
statistics accumulated to date. Currently only the success-to-failure ratio is considered and
compared against {@link com.netflix.ndbench.core.config.IConfiguration#getAutoTuneWriteFailureRatioThreshold()}
Note that we can ignore the possible race condition that arises if multiple threads call this method at around
the same time. In this case two threads will be attempting to set timeOfFirstAutoTuneRequest.. but the
target values they are using to set this variable be so close it will not affect the desired behavior of the
auto-tuning feature.
Note 2: this method will only be called after the ndbench driver tries to perform a writeSingle operation
|
[
"Recommends",
"the",
"new",
"write",
"rate",
"potentially",
"taking",
"into",
"account",
"the",
"current",
"rate",
"the",
"result",
"of",
"the",
"last",
"write",
"and",
"statistics",
"accumulated",
"to",
"date",
".",
"Currently",
"only",
"the",
"success",
"-",
"to",
"-",
"failure",
"ratio",
"is",
"considered",
"and",
"compared",
"against",
"{",
"@link",
"com",
".",
"netflix",
".",
"ndbench",
".",
"core",
".",
"config",
".",
"IConfiguration#getAutoTuneWriteFailureRatioThreshold",
"()",
"}"
] |
train
|
https://github.com/Netflix/ndbench/blob/8d664244b5f9d01395248a296b86a3c822e6d764/ndbench-es-plugins/src/main/java/com/netflix/ndbench/plugin/es/EsAutoTuner.java#L72-L103
|
Azure/azure-sdk-for-java
|
containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/WebhooksInner.java
|
WebhooksInner.updateAsync
|
public Observable<WebhookInner> updateAsync(String resourceGroupName, String registryName, String webhookName, WebhookUpdateParameters webhookUpdateParameters) {
"""
Updates a webhook with the specified parameters.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param webhookName The name of the webhook.
@param webhookUpdateParameters The parameters for updating a webhook.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return updateWithServiceResponseAsync(resourceGroupName, registryName, webhookName, webhookUpdateParameters).map(new Func1<ServiceResponse<WebhookInner>, WebhookInner>() {
@Override
public WebhookInner call(ServiceResponse<WebhookInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<WebhookInner> updateAsync(String resourceGroupName, String registryName, String webhookName, WebhookUpdateParameters webhookUpdateParameters) {
return updateWithServiceResponseAsync(resourceGroupName, registryName, webhookName, webhookUpdateParameters).map(new Func1<ServiceResponse<WebhookInner>, WebhookInner>() {
@Override
public WebhookInner call(ServiceResponse<WebhookInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"WebhookInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"String",
"webhookName",
",",
"WebhookUpdateParameters",
"webhookUpdateParameters",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
",",
"webhookName",
",",
"webhookUpdateParameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"WebhookInner",
">",
",",
"WebhookInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"WebhookInner",
"call",
"(",
"ServiceResponse",
"<",
"WebhookInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates a webhook with the specified parameters.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param webhookName The name of the webhook.
@param webhookUpdateParameters The parameters for updating a webhook.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
|
[
"Updates",
"a",
"webhook",
"with",
"the",
"specified",
"parameters",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/WebhooksInner.java#L601-L608
|
ModeShape/modeshape
|
modeshape-common/src/main/java/org/modeshape/common/text/TokenStream.java
|
TokenStream.consumeBoolean
|
public boolean consumeBoolean() throws ParsingException, IllegalStateException {
"""
Convert the value of this token to an integer, return it, and move to the next token.
@return the current token's value, converted to an integer
@throws ParsingException if there is no such token to consume, or if the token cannot be converted to an integer
@throws IllegalStateException if this method was called before the stream was {@link #start() started}
"""
if (completed) throwNoMoreContent();
// Get the value from the current token ...
String value = currentToken().value();
try {
boolean result = Boolean.parseBoolean(value);
moveToNextToken();
return result;
} catch (NumberFormatException e) {
Position position = currentToken().position();
String msg = CommonI18n.expectingValidBooleanAtLineAndColumn.text(value, position.getLine(), position.getColumn());
throw new ParsingException(position, msg);
}
}
|
java
|
public boolean consumeBoolean() throws ParsingException, IllegalStateException {
if (completed) throwNoMoreContent();
// Get the value from the current token ...
String value = currentToken().value();
try {
boolean result = Boolean.parseBoolean(value);
moveToNextToken();
return result;
} catch (NumberFormatException e) {
Position position = currentToken().position();
String msg = CommonI18n.expectingValidBooleanAtLineAndColumn.text(value, position.getLine(), position.getColumn());
throw new ParsingException(position, msg);
}
}
|
[
"public",
"boolean",
"consumeBoolean",
"(",
")",
"throws",
"ParsingException",
",",
"IllegalStateException",
"{",
"if",
"(",
"completed",
")",
"throwNoMoreContent",
"(",
")",
";",
"// Get the value from the current token ...",
"String",
"value",
"=",
"currentToken",
"(",
")",
".",
"value",
"(",
")",
";",
"try",
"{",
"boolean",
"result",
"=",
"Boolean",
".",
"parseBoolean",
"(",
"value",
")",
";",
"moveToNextToken",
"(",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"Position",
"position",
"=",
"currentToken",
"(",
")",
".",
"position",
"(",
")",
";",
"String",
"msg",
"=",
"CommonI18n",
".",
"expectingValidBooleanAtLineAndColumn",
".",
"text",
"(",
"value",
",",
"position",
".",
"getLine",
"(",
")",
",",
"position",
".",
"getColumn",
"(",
")",
")",
";",
"throw",
"new",
"ParsingException",
"(",
"position",
",",
"msg",
")",
";",
"}",
"}"
] |
Convert the value of this token to an integer, return it, and move to the next token.
@return the current token's value, converted to an integer
@throws ParsingException if there is no such token to consume, or if the token cannot be converted to an integer
@throws IllegalStateException if this method was called before the stream was {@link #start() started}
|
[
"Convert",
"the",
"value",
"of",
"this",
"token",
"to",
"an",
"integer",
"return",
"it",
"and",
"move",
"to",
"the",
"next",
"token",
"."
] |
train
|
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/text/TokenStream.java#L524-L537
|
groupon/odo
|
proxyserver/src/main/java/com/groupon/odo/RemoveHeaderFilter.java
|
RemoveHeaderFilter.doFilter
|
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
"""
This looks at the servlet attributes to get the list of response headers to remove while the response object gets created by the servlet
"""
final ServletRequest r1 = request;
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
@SuppressWarnings("unchecked")
public void setHeader(String name, String value) {
ArrayList<String> headersToRemove = new ArrayList<String>();
if (r1.getAttribute("com.groupon.odo.removeHeaders") != null)
headersToRemove = (ArrayList<String>) r1.getAttribute("com.groupon.odo.removeHeaders");
boolean removeHeader = false;
// need to loop through removeHeaders to make things case insensitive
for (String headerToRemove : headersToRemove) {
if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {
removeHeader = true;
break;
}
}
if (! removeHeader) {
super.setHeader(name, value);
}
}
});
}
|
java
|
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final ServletRequest r1 = request;
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
@SuppressWarnings("unchecked")
public void setHeader(String name, String value) {
ArrayList<String> headersToRemove = new ArrayList<String>();
if (r1.getAttribute("com.groupon.odo.removeHeaders") != null)
headersToRemove = (ArrayList<String>) r1.getAttribute("com.groupon.odo.removeHeaders");
boolean removeHeader = false;
// need to loop through removeHeaders to make things case insensitive
for (String headerToRemove : headersToRemove) {
if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {
removeHeader = true;
break;
}
}
if (! removeHeader) {
super.setHeader(name, value);
}
}
});
}
|
[
"@",
"Override",
"public",
"void",
"doFilter",
"(",
"ServletRequest",
"request",
",",
"ServletResponse",
"response",
",",
"FilterChain",
"chain",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"final",
"ServletRequest",
"r1",
"=",
"request",
";",
"chain",
".",
"doFilter",
"(",
"request",
",",
"new",
"HttpServletResponseWrapper",
"(",
"(",
"HttpServletResponse",
")",
"response",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"setHeader",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"ArrayList",
"<",
"String",
">",
"headersToRemove",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"r1",
".",
"getAttribute",
"(",
"\"com.groupon.odo.removeHeaders\"",
")",
"!=",
"null",
")",
"headersToRemove",
"=",
"(",
"ArrayList",
"<",
"String",
">",
")",
"r1",
".",
"getAttribute",
"(",
"\"com.groupon.odo.removeHeaders\"",
")",
";",
"boolean",
"removeHeader",
"=",
"false",
";",
"// need to loop through removeHeaders to make things case insensitive",
"for",
"(",
"String",
"headerToRemove",
":",
"headersToRemove",
")",
"{",
"if",
"(",
"headerToRemove",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"name",
".",
"toLowerCase",
"(",
")",
")",
")",
"{",
"removeHeader",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"removeHeader",
")",
"{",
"super",
".",
"setHeader",
"(",
"name",
",",
"value",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
This looks at the servlet attributes to get the list of response headers to remove while the response object gets created by the servlet
|
[
"This",
"looks",
"at",
"the",
"servlet",
"attributes",
"to",
"get",
"the",
"list",
"of",
"response",
"headers",
"to",
"remove",
"while",
"the",
"response",
"object",
"gets",
"created",
"by",
"the",
"servlet"
] |
train
|
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxyserver/src/main/java/com/groupon/odo/RemoveHeaderFilter.java#L28-L53
|
openbase/jul
|
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/MultiLanguageTextProcessor.java
|
MultiLanguageTextProcessor.getBestMatch
|
public static String getBestMatch(final MultiLanguageTextOrBuilder multiLanguageText, final String alternative) {
"""
Get the first multiLanguageText for the default language from a multiLanguageText type. This is equivalent to calling
{@link #getMultiLanguageTextByLanguage(String, MultiLanguageTextOrBuilder)} but the language code is extracted from the locale by calling
{@link Locale#getDefault()} . If no multiLanguageText matches the languageCode, than the first multiLanguageText of any other provided language is returned.
@param multiLanguageText the multiLanguageText type which is searched for multiLanguageTexts in the language
@param alternative an alternative string which is returned in error case.
@return the first multiLanguageText from the multiLanguageText type for the locale or if no multiLanguageText is provided by the {@code multiLanguageText} argument the {@code alternative} is returned.
"""
try {
return getBestMatch(Locale.getDefault(), multiLanguageText);
} catch (NotAvailableException e) {
return alternative;
}
}
|
java
|
public static String getBestMatch(final MultiLanguageTextOrBuilder multiLanguageText, final String alternative) {
try {
return getBestMatch(Locale.getDefault(), multiLanguageText);
} catch (NotAvailableException e) {
return alternative;
}
}
|
[
"public",
"static",
"String",
"getBestMatch",
"(",
"final",
"MultiLanguageTextOrBuilder",
"multiLanguageText",
",",
"final",
"String",
"alternative",
")",
"{",
"try",
"{",
"return",
"getBestMatch",
"(",
"Locale",
".",
"getDefault",
"(",
")",
",",
"multiLanguageText",
")",
";",
"}",
"catch",
"(",
"NotAvailableException",
"e",
")",
"{",
"return",
"alternative",
";",
"}",
"}"
] |
Get the first multiLanguageText for the default language from a multiLanguageText type. This is equivalent to calling
{@link #getMultiLanguageTextByLanguage(String, MultiLanguageTextOrBuilder)} but the language code is extracted from the locale by calling
{@link Locale#getDefault()} . If no multiLanguageText matches the languageCode, than the first multiLanguageText of any other provided language is returned.
@param multiLanguageText the multiLanguageText type which is searched for multiLanguageTexts in the language
@param alternative an alternative string which is returned in error case.
@return the first multiLanguageText from the multiLanguageText type for the locale or if no multiLanguageText is provided by the {@code multiLanguageText} argument the {@code alternative} is returned.
|
[
"Get",
"the",
"first",
"multiLanguageText",
"for",
"the",
"default",
"language",
"from",
"a",
"multiLanguageText",
"type",
".",
"This",
"is",
"equivalent",
"to",
"calling",
"{",
"@link",
"#getMultiLanguageTextByLanguage",
"(",
"String",
"MultiLanguageTextOrBuilder",
")",
"}",
"but",
"the",
"language",
"code",
"is",
"extracted",
"from",
"the",
"locale",
"by",
"calling",
"{",
"@link",
"Locale#getDefault",
"()",
"}",
".",
"If",
"no",
"multiLanguageText",
"matches",
"the",
"languageCode",
"than",
"the",
"first",
"multiLanguageText",
"of",
"any",
"other",
"provided",
"language",
"is",
"returned",
"."
] |
train
|
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/MultiLanguageTextProcessor.java#L224-L230
|
logic-ng/LogicNG
|
src/main/java/org/logicng/bdds/BDDFactory.java
|
BDDFactory.modelCount
|
public BigDecimal modelCount(final BDD bdd, final int unimportantVars) {
"""
Returns the model count of a given BDD with a given number of unimportant variables.
@param bdd the BDD
@param unimportantVars the number of unimportant variables
@return the model count
"""
return modelCount(bdd).divide(BigDecimal.valueOf((int) Math.pow(2, unimportantVars)));
}
|
java
|
public BigDecimal modelCount(final BDD bdd, final int unimportantVars) {
return modelCount(bdd).divide(BigDecimal.valueOf((int) Math.pow(2, unimportantVars)));
}
|
[
"public",
"BigDecimal",
"modelCount",
"(",
"final",
"BDD",
"bdd",
",",
"final",
"int",
"unimportantVars",
")",
"{",
"return",
"modelCount",
"(",
"bdd",
")",
".",
"divide",
"(",
"BigDecimal",
".",
"valueOf",
"(",
"(",
"int",
")",
"Math",
".",
"pow",
"(",
"2",
",",
"unimportantVars",
")",
")",
")",
";",
"}"
] |
Returns the model count of a given BDD with a given number of unimportant variables.
@param bdd the BDD
@param unimportantVars the number of unimportant variables
@return the model count
|
[
"Returns",
"the",
"model",
"count",
"of",
"a",
"given",
"BDD",
"with",
"a",
"given",
"number",
"of",
"unimportant",
"variables",
"."
] |
train
|
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/bdds/BDDFactory.java#L247-L249
|
google/closure-templates
|
java/src/com/google/template/soy/data/internal/DictImpl.java
|
DictImpl.forProviderMap
|
public static DictImpl forProviderMap(
Map<String, ? extends SoyValueProvider> providerMap, RuntimeMapTypeTracker.Type mapType) {
"""
Creates a SoyDict implementation for a particular underlying provider map.
<p>The map may be mutable, but will not be mutated by the DictImpl.
"""
return new DictImpl(providerMap, mapType);
}
|
java
|
public static DictImpl forProviderMap(
Map<String, ? extends SoyValueProvider> providerMap, RuntimeMapTypeTracker.Type mapType) {
return new DictImpl(providerMap, mapType);
}
|
[
"public",
"static",
"DictImpl",
"forProviderMap",
"(",
"Map",
"<",
"String",
",",
"?",
"extends",
"SoyValueProvider",
">",
"providerMap",
",",
"RuntimeMapTypeTracker",
".",
"Type",
"mapType",
")",
"{",
"return",
"new",
"DictImpl",
"(",
"providerMap",
",",
"mapType",
")",
";",
"}"
] |
Creates a SoyDict implementation for a particular underlying provider map.
<p>The map may be mutable, but will not be mutated by the DictImpl.
|
[
"Creates",
"a",
"SoyDict",
"implementation",
"for",
"a",
"particular",
"underlying",
"provider",
"map",
"."
] |
train
|
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/internal/DictImpl.java#L85-L88
|
i-net-software/jlessc
|
src/com/inet/lib/less/CssFormatter.java
|
CssFormatter.addGuardParameters
|
void addGuardParameters( Map<String, Expression> parameters, boolean isDefault ) {
"""
Add the parameters of a guard
@param parameters the parameters
@param isDefault if the default case will be evaluated, in this case the expression "default" in guard is true.
"""
isGuard = true;
wasDefaultFunction = false;
guardDefault = isDefault;
if( parameters != null ) {
addMixin( null, parameters, null );
}
}
|
java
|
void addGuardParameters( Map<String, Expression> parameters, boolean isDefault ) {
isGuard = true;
wasDefaultFunction = false;
guardDefault = isDefault;
if( parameters != null ) {
addMixin( null, parameters, null );
}
}
|
[
"void",
"addGuardParameters",
"(",
"Map",
"<",
"String",
",",
"Expression",
">",
"parameters",
",",
"boolean",
"isDefault",
")",
"{",
"isGuard",
"=",
"true",
";",
"wasDefaultFunction",
"=",
"false",
";",
"guardDefault",
"=",
"isDefault",
";",
"if",
"(",
"parameters",
"!=",
"null",
")",
"{",
"addMixin",
"(",
"null",
",",
"parameters",
",",
"null",
")",
";",
"}",
"}"
] |
Add the parameters of a guard
@param parameters the parameters
@param isDefault if the default case will be evaluated, in this case the expression "default" in guard is true.
|
[
"Add",
"the",
"parameters",
"of",
"a",
"guard"
] |
train
|
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/CssFormatter.java#L478-L485
|
netscaler/nitro
|
src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbsite_binding.java
|
gslbsite_binding.get
|
public static gslbsite_binding get(nitro_service service, String sitename) throws Exception {
"""
Use this API to fetch gslbsite_binding resource of given name .
"""
gslbsite_binding obj = new gslbsite_binding();
obj.set_sitename(sitename);
gslbsite_binding response = (gslbsite_binding) obj.get_resource(service);
return response;
}
|
java
|
public static gslbsite_binding get(nitro_service service, String sitename) throws Exception{
gslbsite_binding obj = new gslbsite_binding();
obj.set_sitename(sitename);
gslbsite_binding response = (gslbsite_binding) obj.get_resource(service);
return response;
}
|
[
"public",
"static",
"gslbsite_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"sitename",
")",
"throws",
"Exception",
"{",
"gslbsite_binding",
"obj",
"=",
"new",
"gslbsite_binding",
"(",
")",
";",
"obj",
".",
"set_sitename",
"(",
"sitename",
")",
";",
"gslbsite_binding",
"response",
"=",
"(",
"gslbsite_binding",
")",
"obj",
".",
"get_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
] |
Use this API to fetch gslbsite_binding resource of given name .
|
[
"Use",
"this",
"API",
"to",
"fetch",
"gslbsite_binding",
"resource",
"of",
"given",
"name",
"."
] |
train
|
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbsite_binding.java#L103-L108
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RetireJsAnalyzer.java
|
RetireJsAnalyzer.prepareFileTypeAnalyzer
|
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
"""
{@inheritDoc}
@param engine a reference to the dependency-check engine
@throws InitializationException thrown if there is an exception during
initialization
"""
File repoFile = null;
try {
repoFile = new File(getSettings().getDataDirectory(), "jsrepository.json");
} catch (FileNotFoundException ex) {
this.setEnabled(false);
throw new InitializationException(String.format("RetireJS repo does not exist locally (%s)", repoFile), ex);
} catch (IOException ex) {
this.setEnabled(false);
throw new InitializationException("Failed to initialize the RetireJS repo - data directory could not be created", ex);
}
try (FileInputStream in = new FileInputStream(repoFile)) {
this.jsRepository = new VulnerabilitiesRepositoryLoader().loadFromInputStream(in);
} catch (IOException ex) {
this.setEnabled(false);
throw new InitializationException("Failed to initialize the RetireJS repo", ex);
}
}
|
java
|
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
File repoFile = null;
try {
repoFile = new File(getSettings().getDataDirectory(), "jsrepository.json");
} catch (FileNotFoundException ex) {
this.setEnabled(false);
throw new InitializationException(String.format("RetireJS repo does not exist locally (%s)", repoFile), ex);
} catch (IOException ex) {
this.setEnabled(false);
throw new InitializationException("Failed to initialize the RetireJS repo - data directory could not be created", ex);
}
try (FileInputStream in = new FileInputStream(repoFile)) {
this.jsRepository = new VulnerabilitiesRepositoryLoader().loadFromInputStream(in);
} catch (IOException ex) {
this.setEnabled(false);
throw new InitializationException("Failed to initialize the RetireJS repo", ex);
}
}
|
[
"@",
"Override",
"protected",
"void",
"prepareFileTypeAnalyzer",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"File",
"repoFile",
"=",
"null",
";",
"try",
"{",
"repoFile",
"=",
"new",
"File",
"(",
"getSettings",
"(",
")",
".",
"getDataDirectory",
"(",
")",
",",
"\"jsrepository.json\"",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"ex",
")",
"{",
"this",
".",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"String",
".",
"format",
"(",
"\"RetireJS repo does not exist locally (%s)\"",
",",
"repoFile",
")",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"this",
".",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Failed to initialize the RetireJS repo - data directory could not be created\"",
",",
"ex",
")",
";",
"}",
"try",
"(",
"FileInputStream",
"in",
"=",
"new",
"FileInputStream",
"(",
"repoFile",
")",
")",
"{",
"this",
".",
"jsRepository",
"=",
"new",
"VulnerabilitiesRepositoryLoader",
"(",
")",
".",
"loadFromInputStream",
"(",
"in",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"this",
".",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Failed to initialize the RetireJS repo\"",
",",
"ex",
")",
";",
"}",
"}"
] |
{@inheritDoc}
@param engine a reference to the dependency-check engine
@throws InitializationException thrown if there is an exception during
initialization
|
[
"{",
"@inheritDoc",
"}"
] |
train
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RetireJsAnalyzer.java#L166-L185
|
datumbox/datumbox-framework
|
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/relatedsamples/KendallTauCorrelation.java
|
KendallTauCorrelation.scoreToPvalue
|
private static double scoreToPvalue(double score, int n) {
"""
Returns the Pvalue for a particular score
@param score
@param n
@return
"""
double variance=2.0*(2.0*n+5.0)/(9.0*n*(n-1.0));
double Z=score/Math.sqrt(variance); //follows approximately Normal with 0 mean and variance as calculated above
return ContinuousDistributions.gaussCdf(Z);
}
|
java
|
private static double scoreToPvalue(double score, int n) {
double variance=2.0*(2.0*n+5.0)/(9.0*n*(n-1.0));
double Z=score/Math.sqrt(variance); //follows approximately Normal with 0 mean and variance as calculated above
return ContinuousDistributions.gaussCdf(Z);
}
|
[
"private",
"static",
"double",
"scoreToPvalue",
"(",
"double",
"score",
",",
"int",
"n",
")",
"{",
"double",
"variance",
"=",
"2.0",
"*",
"(",
"2.0",
"*",
"n",
"+",
"5.0",
")",
"/",
"(",
"9.0",
"*",
"n",
"*",
"(",
"n",
"-",
"1.0",
")",
")",
";",
"double",
"Z",
"=",
"score",
"/",
"Math",
".",
"sqrt",
"(",
"variance",
")",
";",
"//follows approximately Normal with 0 mean and variance as calculated above",
"return",
"ContinuousDistributions",
".",
"gaussCdf",
"(",
"Z",
")",
";",
"}"
] |
Returns the Pvalue for a particular score
@param score
@param n
@return
|
[
"Returns",
"the",
"Pvalue",
"for",
"a",
"particular",
"score"
] |
train
|
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/relatedsamples/KendallTauCorrelation.java#L127-L133
|
beangle/beangle3
|
commons/web/src/main/java/org/beangle/commons/web/util/CookieUtils.java
|
CookieUtils.addCookie
|
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
String value, String path, int age) {
"""
Convenience method to set a cookie <br>
刚方法自动将value进行编码存储<br>
@param response
@param name
@param value
@param path
"""
LOG.debug("add cookie[name:{},value={},path={}]", new String[] { name, value, path });
Cookie cookie = null;
try {
cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
cookie.setSecure(false);
cookie.setPath(path);
cookie.setMaxAge(age);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
|
java
|
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
String value, String path, int age) {
LOG.debug("add cookie[name:{},value={},path={}]", new String[] { name, value, path });
Cookie cookie = null;
try {
cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
cookie.setSecure(false);
cookie.setPath(path);
cookie.setMaxAge(age);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
|
[
"public",
"static",
"void",
"addCookie",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"String",
"name",
",",
"String",
"value",
",",
"String",
"path",
",",
"int",
"age",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"add cookie[name:{},value={},path={}]\"",
",",
"new",
"String",
"[",
"]",
"{",
"name",
",",
"value",
",",
"path",
"}",
")",
";",
"Cookie",
"cookie",
"=",
"null",
";",
"try",
"{",
"cookie",
"=",
"new",
"Cookie",
"(",
"name",
",",
"URLEncoder",
".",
"encode",
"(",
"value",
",",
"\"utf-8\"",
")",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"cookie",
".",
"setSecure",
"(",
"false",
")",
";",
"cookie",
".",
"setPath",
"(",
"path",
")",
";",
"cookie",
".",
"setMaxAge",
"(",
"age",
")",
";",
"cookie",
".",
"setHttpOnly",
"(",
"true",
")",
";",
"response",
".",
"addCookie",
"(",
"cookie",
")",
";",
"}"
] |
Convenience method to set a cookie <br>
刚方法自动将value进行编码存储<br>
@param response
@param name
@param value
@param path
|
[
"Convenience",
"method",
"to",
"set",
"a",
"cookie",
"<br",
">",
"刚方法自动将value进行编码存储<br",
">"
] |
train
|
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/web/src/main/java/org/beangle/commons/web/util/CookieUtils.java#L107-L121
|
DDTH/ddth-commons
|
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java
|
TypesafeConfigUtils.loadConfig
|
public static Config loadConfig(File configFile, boolean useSystemEnvironment) {
"""
Load, Parse & Resolve configurations from a file, with default parse & resolve options.
@param configFile
@param useSystemEnvironment
{@code true} to resolve substitutions falling back to environment
variables
@return
"""
return loadConfig(ConfigParseOptions.defaults(),
ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment),
configFile);
}
|
java
|
public static Config loadConfig(File configFile, boolean useSystemEnvironment) {
return loadConfig(ConfigParseOptions.defaults(),
ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment),
configFile);
}
|
[
"public",
"static",
"Config",
"loadConfig",
"(",
"File",
"configFile",
",",
"boolean",
"useSystemEnvironment",
")",
"{",
"return",
"loadConfig",
"(",
"ConfigParseOptions",
".",
"defaults",
"(",
")",
",",
"ConfigResolveOptions",
".",
"defaults",
"(",
")",
".",
"setUseSystemEnvironment",
"(",
"useSystemEnvironment",
")",
",",
"configFile",
")",
";",
"}"
] |
Load, Parse & Resolve configurations from a file, with default parse & resolve options.
@param configFile
@param useSystemEnvironment
{@code true} to resolve substitutions falling back to environment
variables
@return
|
[
"Load",
"Parse",
"&",
"Resolve",
"configurations",
"from",
"a",
"file",
"with",
"default",
"parse",
"&",
"resolve",
"options",
"."
] |
train
|
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java#L56-L60
|
hawkular/hawkular-apm
|
client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FragmentBuilder.java
|
FragmentBuilder.addUncompletedCorrelationId
|
public void addUncompletedCorrelationId(String id, Node node, int position) {
"""
This method associates a parent node and child position with a
correlation id.
@param id The correlation id
@param node The parent node
@param position The child node position within the parent node
"""
NodePlaceholder placeholder = new NodePlaceholder();
placeholder.setNode(node);
placeholder.setPosition(position);
uncompletedCorrelationIdsNodeMap.put(id, placeholder);
}
|
java
|
public void addUncompletedCorrelationId(String id, Node node, int position) {
NodePlaceholder placeholder = new NodePlaceholder();
placeholder.setNode(node);
placeholder.setPosition(position);
uncompletedCorrelationIdsNodeMap.put(id, placeholder);
}
|
[
"public",
"void",
"addUncompletedCorrelationId",
"(",
"String",
"id",
",",
"Node",
"node",
",",
"int",
"position",
")",
"{",
"NodePlaceholder",
"placeholder",
"=",
"new",
"NodePlaceholder",
"(",
")",
";",
"placeholder",
".",
"setNode",
"(",
"node",
")",
";",
"placeholder",
".",
"setPosition",
"(",
"position",
")",
";",
"uncompletedCorrelationIdsNodeMap",
".",
"put",
"(",
"id",
",",
"placeholder",
")",
";",
"}"
] |
This method associates a parent node and child position with a
correlation id.
@param id The correlation id
@param node The parent node
@param position The child node position within the parent node
|
[
"This",
"method",
"associates",
"a",
"parent",
"node",
"and",
"child",
"position",
"with",
"a",
"correlation",
"id",
"."
] |
train
|
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/collector/src/main/java/org/hawkular/apm/client/collector/internal/FragmentBuilder.java#L406-L411
|
duracloud/duracloud
|
s3storageprovider/src/main/java/org/duracloud/s3storage/S3StorageProvider.java
|
S3StorageProvider.addHiddenContent
|
public String addHiddenContent(String spaceId,
String contentId,
String contentMimeType,
InputStream content) {
"""
Adds content to a hidden space.
@param spaceId hidden spaceId
@param contentId
@param contentMimeType
@param content
@return
"""
log.debug("addHiddenContent(" + spaceId + ", " + contentId + ", " +
contentMimeType + ")");
// Will throw if bucket does not exist
String bucketName = getBucketName(spaceId);
// Wrap the content in order to be able to retrieve a checksum
if (contentMimeType == null || contentMimeType.equals("")) {
contentMimeType = DEFAULT_MIMETYPE;
}
ObjectMetadata objMetadata = new ObjectMetadata();
objMetadata.setContentType(contentMimeType);
PutObjectRequest putRequest = new PutObjectRequest(bucketName,
contentId,
content,
objMetadata);
putRequest.setStorageClass(DEFAULT_STORAGE_CLASS);
putRequest.setCannedAcl(CannedAccessControlList.Private);
try {
PutObjectResult putResult = s3Client.putObject(putRequest);
return putResult.getETag();
} catch (AmazonClientException e) {
String err = "Could not add content " + contentId +
" with type " + contentMimeType +
" to S3 bucket " + bucketName + " due to error: " +
e.getMessage();
throw new StorageException(err, e, NO_RETRY);
}
}
|
java
|
public String addHiddenContent(String spaceId,
String contentId,
String contentMimeType,
InputStream content) {
log.debug("addHiddenContent(" + spaceId + ", " + contentId + ", " +
contentMimeType + ")");
// Will throw if bucket does not exist
String bucketName = getBucketName(spaceId);
// Wrap the content in order to be able to retrieve a checksum
if (contentMimeType == null || contentMimeType.equals("")) {
contentMimeType = DEFAULT_MIMETYPE;
}
ObjectMetadata objMetadata = new ObjectMetadata();
objMetadata.setContentType(contentMimeType);
PutObjectRequest putRequest = new PutObjectRequest(bucketName,
contentId,
content,
objMetadata);
putRequest.setStorageClass(DEFAULT_STORAGE_CLASS);
putRequest.setCannedAcl(CannedAccessControlList.Private);
try {
PutObjectResult putResult = s3Client.putObject(putRequest);
return putResult.getETag();
} catch (AmazonClientException e) {
String err = "Could not add content " + contentId +
" with type " + contentMimeType +
" to S3 bucket " + bucketName + " due to error: " +
e.getMessage();
throw new StorageException(err, e, NO_RETRY);
}
}
|
[
"public",
"String",
"addHiddenContent",
"(",
"String",
"spaceId",
",",
"String",
"contentId",
",",
"String",
"contentMimeType",
",",
"InputStream",
"content",
")",
"{",
"log",
".",
"debug",
"(",
"\"addHiddenContent(\"",
"+",
"spaceId",
"+",
"\", \"",
"+",
"contentId",
"+",
"\", \"",
"+",
"contentMimeType",
"+",
"\")\"",
")",
";",
"// Will throw if bucket does not exist",
"String",
"bucketName",
"=",
"getBucketName",
"(",
"spaceId",
")",
";",
"// Wrap the content in order to be able to retrieve a checksum",
"if",
"(",
"contentMimeType",
"==",
"null",
"||",
"contentMimeType",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"contentMimeType",
"=",
"DEFAULT_MIMETYPE",
";",
"}",
"ObjectMetadata",
"objMetadata",
"=",
"new",
"ObjectMetadata",
"(",
")",
";",
"objMetadata",
".",
"setContentType",
"(",
"contentMimeType",
")",
";",
"PutObjectRequest",
"putRequest",
"=",
"new",
"PutObjectRequest",
"(",
"bucketName",
",",
"contentId",
",",
"content",
",",
"objMetadata",
")",
";",
"putRequest",
".",
"setStorageClass",
"(",
"DEFAULT_STORAGE_CLASS",
")",
";",
"putRequest",
".",
"setCannedAcl",
"(",
"CannedAccessControlList",
".",
"Private",
")",
";",
"try",
"{",
"PutObjectResult",
"putResult",
"=",
"s3Client",
".",
"putObject",
"(",
"putRequest",
")",
";",
"return",
"putResult",
".",
"getETag",
"(",
")",
";",
"}",
"catch",
"(",
"AmazonClientException",
"e",
")",
"{",
"String",
"err",
"=",
"\"Could not add content \"",
"+",
"contentId",
"+",
"\" with type \"",
"+",
"contentMimeType",
"+",
"\" to S3 bucket \"",
"+",
"bucketName",
"+",
"\" due to error: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
";",
"throw",
"new",
"StorageException",
"(",
"err",
",",
"e",
",",
"NO_RETRY",
")",
";",
"}",
"}"
] |
Adds content to a hidden space.
@param spaceId hidden spaceId
@param contentId
@param contentMimeType
@param content
@return
|
[
"Adds",
"content",
"to",
"a",
"hidden",
"space",
"."
] |
train
|
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/s3storageprovider/src/main/java/org/duracloud/s3storage/S3StorageProvider.java#L519-L556
|
j-a-w-r/jawr-main-repo
|
jawr/jawr-core/src/main/java/net/jawr/web/util/js/JavascriptEngine.java
|
JavascriptEngine.evaluateString
|
public Object evaluateString(String scriptName, String source, Bindings bindings) {
"""
Evaluates the JS passed in parameter
@param scriptName
the script name
@param source
the JS script
@param bindings
the bindings to use
@return the result
"""
try {
scriptEngine.put(ScriptEngine.FILENAME, scriptName);
return scriptEngine.eval(source, bindings);
} catch (ScriptException e) {
throw new BundlingProcessException("Error while evaluating script : " + scriptName, e);
}
}
|
java
|
public Object evaluateString(String scriptName, String source, Bindings bindings) {
try {
scriptEngine.put(ScriptEngine.FILENAME, scriptName);
return scriptEngine.eval(source, bindings);
} catch (ScriptException e) {
throw new BundlingProcessException("Error while evaluating script : " + scriptName, e);
}
}
|
[
"public",
"Object",
"evaluateString",
"(",
"String",
"scriptName",
",",
"String",
"source",
",",
"Bindings",
"bindings",
")",
"{",
"try",
"{",
"scriptEngine",
".",
"put",
"(",
"ScriptEngine",
".",
"FILENAME",
",",
"scriptName",
")",
";",
"return",
"scriptEngine",
".",
"eval",
"(",
"source",
",",
"bindings",
")",
";",
"}",
"catch",
"(",
"ScriptException",
"e",
")",
"{",
"throw",
"new",
"BundlingProcessException",
"(",
"\"Error while evaluating script : \"",
"+",
"scriptName",
",",
"e",
")",
";",
"}",
"}"
] |
Evaluates the JS passed in parameter
@param scriptName
the script name
@param source
the JS script
@param bindings
the bindings to use
@return the result
|
[
"Evaluates",
"the",
"JS",
"passed",
"in",
"parameter"
] |
train
|
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/util/js/JavascriptEngine.java#L175-L182
|
Azure/azure-sdk-for-java
|
batch/data-plane/src/main/java/com/microsoft/azure/batch/FileOperations.java
|
FileOperations.getFilePropertiesFromTask
|
public FileProperties getFilePropertiesFromTask(String jobId, String taskId, String fileName, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
"""
Gets information about a file from the specified task's directory on its compute node.
@param jobId The ID of the job containing the task.
@param taskId The ID of the task.
@param fileName The name of the file to retrieve.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@return A {@link FileProperties} instance containing information about the file.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
"""
FileGetPropertiesFromTaskOptions options = new FileGetPropertiesFromTaskOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
ServiceResponseWithHeaders<Void, FileGetPropertiesFromTaskHeaders> response = this.parentBatchClient.protocolLayer().files().
getPropertiesFromTaskWithServiceResponseAsync(jobId, taskId, fileName, options).toBlocking().single();
return new FileProperties()
.withContentLength(response.headers().contentLength())
.withContentType(response.headers().contentType())
.withCreationTime(response.headers().ocpCreationTime())
.withLastModified(response.headers().lastModified())
.withFileMode(response.headers().ocpBatchFileMode());
}
|
java
|
public FileProperties getFilePropertiesFromTask(String jobId, String taskId, String fileName, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
FileGetPropertiesFromTaskOptions options = new FileGetPropertiesFromTaskOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
ServiceResponseWithHeaders<Void, FileGetPropertiesFromTaskHeaders> response = this.parentBatchClient.protocolLayer().files().
getPropertiesFromTaskWithServiceResponseAsync(jobId, taskId, fileName, options).toBlocking().single();
return new FileProperties()
.withContentLength(response.headers().contentLength())
.withContentType(response.headers().contentType())
.withCreationTime(response.headers().ocpCreationTime())
.withLastModified(response.headers().lastModified())
.withFileMode(response.headers().ocpBatchFileMode());
}
|
[
"public",
"FileProperties",
"getFilePropertiesFromTask",
"(",
"String",
"jobId",
",",
"String",
"taskId",
",",
"String",
"fileName",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"FileGetPropertiesFromTaskOptions",
"options",
"=",
"new",
"FileGetPropertiesFromTaskOptions",
"(",
")",
";",
"BehaviorManager",
"bhMgr",
"=",
"new",
"BehaviorManager",
"(",
"this",
".",
"customBehaviors",
"(",
")",
",",
"additionalBehaviors",
")",
";",
"bhMgr",
".",
"applyRequestBehaviors",
"(",
"options",
")",
";",
"ServiceResponseWithHeaders",
"<",
"Void",
",",
"FileGetPropertiesFromTaskHeaders",
">",
"response",
"=",
"this",
".",
"parentBatchClient",
".",
"protocolLayer",
"(",
")",
".",
"files",
"(",
")",
".",
"getPropertiesFromTaskWithServiceResponseAsync",
"(",
"jobId",
",",
"taskId",
",",
"fileName",
",",
"options",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
";",
"return",
"new",
"FileProperties",
"(",
")",
".",
"withContentLength",
"(",
"response",
".",
"headers",
"(",
")",
".",
"contentLength",
"(",
")",
")",
".",
"withContentType",
"(",
"response",
".",
"headers",
"(",
")",
".",
"contentType",
"(",
")",
")",
".",
"withCreationTime",
"(",
"response",
".",
"headers",
"(",
")",
".",
"ocpCreationTime",
"(",
")",
")",
".",
"withLastModified",
"(",
"response",
".",
"headers",
"(",
")",
".",
"lastModified",
"(",
")",
")",
".",
"withFileMode",
"(",
"response",
".",
"headers",
"(",
")",
".",
"ocpBatchFileMode",
"(",
")",
")",
";",
"}"
] |
Gets information about a file from the specified task's directory on its compute node.
@param jobId The ID of the job containing the task.
@param taskId The ID of the task.
@param fileName The name of the file to retrieve.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@return A {@link FileProperties} instance containing information about the file.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
|
[
"Gets",
"information",
"about",
"a",
"file",
"from",
"the",
"specified",
"task",
"s",
"directory",
"on",
"its",
"compute",
"node",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/FileOperations.java#L345-L359
|
datumbox/datumbox-framework
|
datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/AssociativeArray2D.java
|
AssociativeArray2D.put2d
|
public final Object put2d(Object key1, Object key2, Object value) {
"""
Convenience function used to put a value in a particular key positions.
@param key1
@param key2
@param value
@return
"""
AssociativeArray tmp = internalData.get(key1);
if(tmp == null) {
internalData.put(key1, new AssociativeArray());
}
return internalData.get(key1).internalData.put(key2, value);
}
|
java
|
public final Object put2d(Object key1, Object key2, Object value) {
AssociativeArray tmp = internalData.get(key1);
if(tmp == null) {
internalData.put(key1, new AssociativeArray());
}
return internalData.get(key1).internalData.put(key2, value);
}
|
[
"public",
"final",
"Object",
"put2d",
"(",
"Object",
"key1",
",",
"Object",
"key2",
",",
"Object",
"value",
")",
"{",
"AssociativeArray",
"tmp",
"=",
"internalData",
".",
"get",
"(",
"key1",
")",
";",
"if",
"(",
"tmp",
"==",
"null",
")",
"{",
"internalData",
".",
"put",
"(",
"key1",
",",
"new",
"AssociativeArray",
"(",
")",
")",
";",
"}",
"return",
"internalData",
".",
"get",
"(",
"key1",
")",
".",
"internalData",
".",
"put",
"(",
"key2",
",",
"value",
")",
";",
"}"
] |
Convenience function used to put a value in a particular key positions.
@param key1
@param key2
@param value
@return
|
[
"Convenience",
"function",
"used",
"to",
"put",
"a",
"value",
"in",
"a",
"particular",
"key",
"positions",
"."
] |
train
|
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/AssociativeArray2D.java#L144-L151
|
sdaschner/jaxrs-analyzer
|
src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/javadoc/JavaDocAnalyzer.java
|
JavaDocAnalyzer.equalsSimpleTypeNames
|
private boolean equalsSimpleTypeNames(MethodIdentifier identifier, MethodResult methodResult) {
"""
This is a best-effort approach combining only the simple types.
@see JavaDocParserVisitor#calculateMethodIdentifier(MethodDeclaration)
"""
MethodIdentifier originalIdentifier = methodResult.getOriginalMethodSignature();
return originalIdentifier.getMethodName().equals(identifier.getMethodName()) &&
matchesTypeBestEffort(originalIdentifier.getReturnType(), identifier.getReturnType()) &&
parameterMatch(originalIdentifier.getParameters(), identifier.getParameters());
}
|
java
|
private boolean equalsSimpleTypeNames(MethodIdentifier identifier, MethodResult methodResult) {
MethodIdentifier originalIdentifier = methodResult.getOriginalMethodSignature();
return originalIdentifier.getMethodName().equals(identifier.getMethodName()) &&
matchesTypeBestEffort(originalIdentifier.getReturnType(), identifier.getReturnType()) &&
parameterMatch(originalIdentifier.getParameters(), identifier.getParameters());
}
|
[
"private",
"boolean",
"equalsSimpleTypeNames",
"(",
"MethodIdentifier",
"identifier",
",",
"MethodResult",
"methodResult",
")",
"{",
"MethodIdentifier",
"originalIdentifier",
"=",
"methodResult",
".",
"getOriginalMethodSignature",
"(",
")",
";",
"return",
"originalIdentifier",
".",
"getMethodName",
"(",
")",
".",
"equals",
"(",
"identifier",
".",
"getMethodName",
"(",
")",
")",
"&&",
"matchesTypeBestEffort",
"(",
"originalIdentifier",
".",
"getReturnType",
"(",
")",
",",
"identifier",
".",
"getReturnType",
"(",
")",
")",
"&&",
"parameterMatch",
"(",
"originalIdentifier",
".",
"getParameters",
"(",
")",
",",
"identifier",
".",
"getParameters",
"(",
")",
")",
";",
"}"
] |
This is a best-effort approach combining only the simple types.
@see JavaDocParserVisitor#calculateMethodIdentifier(MethodDeclaration)
|
[
"This",
"is",
"a",
"best",
"-",
"effort",
"approach",
"combining",
"only",
"the",
"simple",
"types",
"."
] |
train
|
https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/javadoc/JavaDocAnalyzer.java#L96-L102
|
hdinsight/storm-eventhubs
|
src/main/java/org/apache/storm/eventhubs/spout/EventHubSpout.java
|
EventHubSpout.preparePartitions
|
public void preparePartitions(Map config, int totalTasks, int taskIndex, SpoutOutputCollector collector) throws Exception {
"""
This is a extracted method that is easy to test
@param config
@param totalTasks
@param taskIndex
@param collector
@throws Exception
"""
this.collector = collector;
if(stateStore == null) {
String zkEndpointAddress = eventHubConfig.getZkConnectionString();
if (zkEndpointAddress == null || zkEndpointAddress.length() == 0) {
//use storm's zookeeper servers if not specified.
@SuppressWarnings("unchecked")
List<String> zkServers = (List<String>) config.get(Config.STORM_ZOOKEEPER_SERVERS);
Integer zkPort = ((Number) config.get(Config.STORM_ZOOKEEPER_PORT)).intValue();
StringBuilder sb = new StringBuilder();
for (String zk : zkServers) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(zk+":"+zkPort);
}
zkEndpointAddress = sb.toString();
}
stateStore = new ZookeeperStateStore(zkEndpointAddress,
(Integer)config.get(Config.STORM_ZOOKEEPER_RETRY_TIMES),
(Integer)config.get(Config.STORM_ZOOKEEPER_RETRY_INTERVAL));
}
stateStore.open();
partitionCoordinator = new StaticPartitionCoordinator(
eventHubConfig, taskIndex, totalTasks, stateStore, pmFactory, recvFactory);
for (IPartitionManager partitionManager :
partitionCoordinator.getMyPartitionManagers()) {
partitionManager.open();
}
}
|
java
|
public void preparePartitions(Map config, int totalTasks, int taskIndex, SpoutOutputCollector collector) throws Exception {
this.collector = collector;
if(stateStore == null) {
String zkEndpointAddress = eventHubConfig.getZkConnectionString();
if (zkEndpointAddress == null || zkEndpointAddress.length() == 0) {
//use storm's zookeeper servers if not specified.
@SuppressWarnings("unchecked")
List<String> zkServers = (List<String>) config.get(Config.STORM_ZOOKEEPER_SERVERS);
Integer zkPort = ((Number) config.get(Config.STORM_ZOOKEEPER_PORT)).intValue();
StringBuilder sb = new StringBuilder();
for (String zk : zkServers) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(zk+":"+zkPort);
}
zkEndpointAddress = sb.toString();
}
stateStore = new ZookeeperStateStore(zkEndpointAddress,
(Integer)config.get(Config.STORM_ZOOKEEPER_RETRY_TIMES),
(Integer)config.get(Config.STORM_ZOOKEEPER_RETRY_INTERVAL));
}
stateStore.open();
partitionCoordinator = new StaticPartitionCoordinator(
eventHubConfig, taskIndex, totalTasks, stateStore, pmFactory, recvFactory);
for (IPartitionManager partitionManager :
partitionCoordinator.getMyPartitionManagers()) {
partitionManager.open();
}
}
|
[
"public",
"void",
"preparePartitions",
"(",
"Map",
"config",
",",
"int",
"totalTasks",
",",
"int",
"taskIndex",
",",
"SpoutOutputCollector",
"collector",
")",
"throws",
"Exception",
"{",
"this",
".",
"collector",
"=",
"collector",
";",
"if",
"(",
"stateStore",
"==",
"null",
")",
"{",
"String",
"zkEndpointAddress",
"=",
"eventHubConfig",
".",
"getZkConnectionString",
"(",
")",
";",
"if",
"(",
"zkEndpointAddress",
"==",
"null",
"||",
"zkEndpointAddress",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"//use storm's zookeeper servers if not specified.",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"List",
"<",
"String",
">",
"zkServers",
"=",
"(",
"List",
"<",
"String",
">",
")",
"config",
".",
"get",
"(",
"Config",
".",
"STORM_ZOOKEEPER_SERVERS",
")",
";",
"Integer",
"zkPort",
"=",
"(",
"(",
"Number",
")",
"config",
".",
"get",
"(",
"Config",
".",
"STORM_ZOOKEEPER_PORT",
")",
")",
".",
"intValue",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"String",
"zk",
":",
"zkServers",
")",
"{",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"sb",
".",
"append",
"(",
"zk",
"+",
"\":\"",
"+",
"zkPort",
")",
";",
"}",
"zkEndpointAddress",
"=",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"stateStore",
"=",
"new",
"ZookeeperStateStore",
"(",
"zkEndpointAddress",
",",
"(",
"Integer",
")",
"config",
".",
"get",
"(",
"Config",
".",
"STORM_ZOOKEEPER_RETRY_TIMES",
")",
",",
"(",
"Integer",
")",
"config",
".",
"get",
"(",
"Config",
".",
"STORM_ZOOKEEPER_RETRY_INTERVAL",
")",
")",
";",
"}",
"stateStore",
".",
"open",
"(",
")",
";",
"partitionCoordinator",
"=",
"new",
"StaticPartitionCoordinator",
"(",
"eventHubConfig",
",",
"taskIndex",
",",
"totalTasks",
",",
"stateStore",
",",
"pmFactory",
",",
"recvFactory",
")",
";",
"for",
"(",
"IPartitionManager",
"partitionManager",
":",
"partitionCoordinator",
".",
"getMyPartitionManagers",
"(",
")",
")",
"{",
"partitionManager",
".",
"open",
"(",
")",
";",
"}",
"}"
] |
This is a extracted method that is easy to test
@param config
@param totalTasks
@param taskIndex
@param collector
@throws Exception
|
[
"This",
"is",
"a",
"extracted",
"method",
"that",
"is",
"easy",
"to",
"test"
] |
train
|
https://github.com/hdinsight/storm-eventhubs/blob/86c99201e6df5e1caee3f664de8843bd656c0f1c/src/main/java/org/apache/storm/eventhubs/spout/EventHubSpout.java#L105-L136
|
exoplatform/jcr
|
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/AbstractValueData.java
|
AbstractValueData.validateAndAdjustLenght
|
protected long validateAndAdjustLenght(long length, long position, long dataLength) throws IOException {
"""
Validate parameters. <code>Length</code> and <code>position</code> should not be negative and
<code>length</code> should not be greater than <code>dataLength</code>
@return adjusted length of byte to read. Should not be possible to exceed array border.
"""
if (position < 0)
{
throw new IOException("Position must be higher or equals 0. But given " + position);
}
if (length < 0)
{
throw new IOException("Length must be higher or equals 0. But given " + length);
}
if (position >= dataLength && position > 0)
{
throw new IOException("Position " + position + " out of value size " + dataLength);
}
if (position + length >= dataLength)
{
return dataLength - position;
}
return length;
}
|
java
|
protected long validateAndAdjustLenght(long length, long position, long dataLength) throws IOException
{
if (position < 0)
{
throw new IOException("Position must be higher or equals 0. But given " + position);
}
if (length < 0)
{
throw new IOException("Length must be higher or equals 0. But given " + length);
}
if (position >= dataLength && position > 0)
{
throw new IOException("Position " + position + " out of value size " + dataLength);
}
if (position + length >= dataLength)
{
return dataLength - position;
}
return length;
}
|
[
"protected",
"long",
"validateAndAdjustLenght",
"(",
"long",
"length",
",",
"long",
"position",
",",
"long",
"dataLength",
")",
"throws",
"IOException",
"{",
"if",
"(",
"position",
"<",
"0",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Position must be higher or equals 0. But given \"",
"+",
"position",
")",
";",
"}",
"if",
"(",
"length",
"<",
"0",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Length must be higher or equals 0. But given \"",
"+",
"length",
")",
";",
"}",
"if",
"(",
"position",
">=",
"dataLength",
"&&",
"position",
">",
"0",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Position \"",
"+",
"position",
"+",
"\" out of value size \"",
"+",
"dataLength",
")",
";",
"}",
"if",
"(",
"position",
"+",
"length",
">=",
"dataLength",
")",
"{",
"return",
"dataLength",
"-",
"position",
";",
"}",
"return",
"length",
";",
"}"
] |
Validate parameters. <code>Length</code> and <code>position</code> should not be negative and
<code>length</code> should not be greater than <code>dataLength</code>
@return adjusted length of byte to read. Should not be possible to exceed array border.
|
[
"Validate",
"parameters",
".",
"<code",
">",
"Length<",
"/",
"code",
">",
"and",
"<code",
">",
"position<",
"/",
"code",
">",
"should",
"not",
"be",
"negative",
"and",
"<code",
">",
"length<",
"/",
"code",
">",
"should",
"not",
"be",
"greater",
"than",
"<code",
">",
"dataLength<",
"/",
"code",
">"
] |
train
|
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/dataflow/AbstractValueData.java#L148-L171
|
stephanenicolas/robospice
|
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/notifier/SpiceServiceListenerNotifier.java
|
SpiceServiceListenerNotifier.notifyObserversOfRequestCancellation
|
public void notifyObserversOfRequestCancellation(CachedSpiceRequest<?> request) {
"""
Notify interested observers that the request was cancelled.
@param request the request that was cancelled.
"""
RequestProcessingContext requestProcessingContext = new RequestProcessingContext();
requestProcessingContext.setExecutionThread(Thread.currentThread());
post(new RequestCancelledNotifier(request, spiceServiceListenerList, requestProcessingContext));
}
|
java
|
public void notifyObserversOfRequestCancellation(CachedSpiceRequest<?> request) {
RequestProcessingContext requestProcessingContext = new RequestProcessingContext();
requestProcessingContext.setExecutionThread(Thread.currentThread());
post(new RequestCancelledNotifier(request, spiceServiceListenerList, requestProcessingContext));
}
|
[
"public",
"void",
"notifyObserversOfRequestCancellation",
"(",
"CachedSpiceRequest",
"<",
"?",
">",
"request",
")",
"{",
"RequestProcessingContext",
"requestProcessingContext",
"=",
"new",
"RequestProcessingContext",
"(",
")",
";",
"requestProcessingContext",
".",
"setExecutionThread",
"(",
"Thread",
".",
"currentThread",
"(",
")",
")",
";",
"post",
"(",
"new",
"RequestCancelledNotifier",
"(",
"request",
",",
"spiceServiceListenerList",
",",
"requestProcessingContext",
")",
")",
";",
"}"
] |
Notify interested observers that the request was cancelled.
@param request the request that was cancelled.
|
[
"Notify",
"interested",
"observers",
"that",
"the",
"request",
"was",
"cancelled",
"."
] |
train
|
https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/notifier/SpiceServiceListenerNotifier.java#L111-L115
|
kite-sdk/kite
|
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/StorageKey.java
|
StorageKey.reuseFor
|
@SuppressWarnings("unchecked")
public <E> StorageKey reuseFor(E entity, EntityAccessor<E> accessor) {
"""
Replaces all of the values in this {@link StorageKey} with values from the given
{@code entity}.
@param entity an entity to reuse this {@code StorageKey} for
@return this updated {@code StorageKey}
@throws IllegalStateException
If the {@code entity} cannot be used to produce a value for each
field in the {@code PartitionStrategy}
@since 0.9.0
"""
accessor.keyFor(entity, null, this);
return this;
}
|
java
|
@SuppressWarnings("unchecked")
public <E> StorageKey reuseFor(E entity, EntityAccessor<E> accessor) {
accessor.keyFor(entity, null, this);
return this;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"E",
">",
"StorageKey",
"reuseFor",
"(",
"E",
"entity",
",",
"EntityAccessor",
"<",
"E",
">",
"accessor",
")",
"{",
"accessor",
".",
"keyFor",
"(",
"entity",
",",
"null",
",",
"this",
")",
";",
"return",
"this",
";",
"}"
] |
Replaces all of the values in this {@link StorageKey} with values from the given
{@code entity}.
@param entity an entity to reuse this {@code StorageKey} for
@return this updated {@code StorageKey}
@throws IllegalStateException
If the {@code entity} cannot be used to produce a value for each
field in the {@code PartitionStrategy}
@since 0.9.0
|
[
"Replaces",
"all",
"of",
"the",
"values",
"in",
"this",
"{",
"@link",
"StorageKey",
"}",
"with",
"values",
"from",
"the",
"given",
"{",
"@code",
"entity",
"}",
"."
] |
train
|
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/StorageKey.java#L154-L158
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/util/Util.java
|
Util.decodeCertChain
|
@SuppressWarnings("unchecked")
@Sensitive
public static X509Certificate[] decodeCertChain(Codec codec, @Sensitive byte[] encodedCertChain) throws SASException {
"""
Decode an X509 certificate chain.
@param codec The codec to do the decoding of the Any.
@param encodedCertChain The codec encoded byte[] containing the X509 certificate chain.
@return the X509 certificate chain
@throws SASException
"""
X509Certificate[] certificateChain = null;
try {
Any any = codec.decode_value(encodedCertChain, X509CertificateChainHelper.type());
byte[] decodedCertificateChain = X509CertificateChainHelper.extract(any);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(decodedCertificateChain);
CertPath certPath = certificateFactory.generateCertPath(bais);
List<X509Certificate> certificates = (List<X509Certificate>) certPath.getCertificates();
certificateChain = new X509Certificate[certificates.size()];
for (int i = 0; i < certificates.size(); i++) {
certificateChain[i] = certificates.get(i);
}
} catch (Exception e) {
throw new SASException(1, e);
}
return certificateChain;
}
|
java
|
@SuppressWarnings("unchecked")
@Sensitive
public static X509Certificate[] decodeCertChain(Codec codec, @Sensitive byte[] encodedCertChain) throws SASException {
X509Certificate[] certificateChain = null;
try {
Any any = codec.decode_value(encodedCertChain, X509CertificateChainHelper.type());
byte[] decodedCertificateChain = X509CertificateChainHelper.extract(any);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(decodedCertificateChain);
CertPath certPath = certificateFactory.generateCertPath(bais);
List<X509Certificate> certificates = (List<X509Certificate>) certPath.getCertificates();
certificateChain = new X509Certificate[certificates.size()];
for (int i = 0; i < certificates.size(); i++) {
certificateChain[i] = certificates.get(i);
}
} catch (Exception e) {
throw new SASException(1, e);
}
return certificateChain;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Sensitive",
"public",
"static",
"X509Certificate",
"[",
"]",
"decodeCertChain",
"(",
"Codec",
"codec",
",",
"@",
"Sensitive",
"byte",
"[",
"]",
"encodedCertChain",
")",
"throws",
"SASException",
"{",
"X509Certificate",
"[",
"]",
"certificateChain",
"=",
"null",
";",
"try",
"{",
"Any",
"any",
"=",
"codec",
".",
"decode_value",
"(",
"encodedCertChain",
",",
"X509CertificateChainHelper",
".",
"type",
"(",
")",
")",
";",
"byte",
"[",
"]",
"decodedCertificateChain",
"=",
"X509CertificateChainHelper",
".",
"extract",
"(",
"any",
")",
";",
"CertificateFactory",
"certificateFactory",
"=",
"CertificateFactory",
".",
"getInstance",
"(",
"\"X.509\"",
")",
";",
"ByteArrayInputStream",
"bais",
"=",
"new",
"ByteArrayInputStream",
"(",
"decodedCertificateChain",
")",
";",
"CertPath",
"certPath",
"=",
"certificateFactory",
".",
"generateCertPath",
"(",
"bais",
")",
";",
"List",
"<",
"X509Certificate",
">",
"certificates",
"=",
"(",
"List",
"<",
"X509Certificate",
">",
")",
"certPath",
".",
"getCertificates",
"(",
")",
";",
"certificateChain",
"=",
"new",
"X509Certificate",
"[",
"certificates",
".",
"size",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"certificates",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"certificateChain",
"[",
"i",
"]",
"=",
"certificates",
".",
"get",
"(",
"i",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"SASException",
"(",
"1",
",",
"e",
")",
";",
"}",
"return",
"certificateChain",
";",
"}"
] |
Decode an X509 certificate chain.
@param codec The codec to do the decoding of the Any.
@param encodedCertChain The codec encoded byte[] containing the X509 certificate chain.
@return the X509 certificate chain
@throws SASException
|
[
"Decode",
"an",
"X509",
"certificate",
"chain",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/util/Util.java#L783-L805
|
atomix/catalyst
|
common/src/main/java/io/atomix/catalyst/util/PropertiesReader.java
|
PropertiesReader.getDuration
|
public Duration getDuration(String property, Duration defaultValue) {
"""
Reads a duration property.
@param property The property name.
@param defaultValue The default value to return if the property is not present
@return The property value.
"""
return getProperty(property, defaultValue, value -> {
try {
return Durations.of(value);
} catch (NumberFormatException e) {
throw new ConfigurationException("malformed property value: " + property + " must be a number");
}
});
}
|
java
|
public Duration getDuration(String property, Duration defaultValue) {
return getProperty(property, defaultValue, value -> {
try {
return Durations.of(value);
} catch (NumberFormatException e) {
throw new ConfigurationException("malformed property value: " + property + " must be a number");
}
});
}
|
[
"public",
"Duration",
"getDuration",
"(",
"String",
"property",
",",
"Duration",
"defaultValue",
")",
"{",
"return",
"getProperty",
"(",
"property",
",",
"defaultValue",
",",
"value",
"->",
"{",
"try",
"{",
"return",
"Durations",
".",
"of",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"throw",
"new",
"ConfigurationException",
"(",
"\"malformed property value: \"",
"+",
"property",
"+",
"\" must be a number\"",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Reads a duration property.
@param property The property name.
@param defaultValue The default value to return if the property is not present
@return The property value.
|
[
"Reads",
"a",
"duration",
"property",
"."
] |
train
|
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/common/src/main/java/io/atomix/catalyst/util/PropertiesReader.java#L479-L487
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java
|
CacheProviderWrapper.invalidateByTemplate
|
@Override
public void invalidateByTemplate(String template, boolean waitOnInvalidation) {
"""
This invalidates all entries in this Cache having a dependency
on this template.
@param template The template name.
@param waitOnInvalidation True indicates that this method should
not return until the invalidations have taken effect on all caches.
False indicates that the invalidations will be queued for later
batch processing.
"""
final String methodName = "invalidateByTemplate()";
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " template=" + template);
}
this.invalidateExternalCaches(null, template);
this.coreCache.invalidateByTemplate(template, waitOnInvalidation);
}
|
java
|
@Override
public void invalidateByTemplate(String template, boolean waitOnInvalidation) {
final String methodName = "invalidateByTemplate()";
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " template=" + template);
}
this.invalidateExternalCaches(null, template);
this.coreCache.invalidateByTemplate(template, waitOnInvalidation);
}
|
[
"@",
"Override",
"public",
"void",
"invalidateByTemplate",
"(",
"String",
"template",
",",
"boolean",
"waitOnInvalidation",
")",
"{",
"final",
"String",
"methodName",
"=",
"\"invalidateByTemplate()\"",
";",
"if",
"(",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"methodName",
"+",
"\" cacheName=\"",
"+",
"cacheName",
"+",
"\" template=\"",
"+",
"template",
")",
";",
"}",
"this",
".",
"invalidateExternalCaches",
"(",
"null",
",",
"template",
")",
";",
"this",
".",
"coreCache",
".",
"invalidateByTemplate",
"(",
"template",
",",
"waitOnInvalidation",
")",
";",
"}"
] |
This invalidates all entries in this Cache having a dependency
on this template.
@param template The template name.
@param waitOnInvalidation True indicates that this method should
not return until the invalidations have taken effect on all caches.
False indicates that the invalidations will be queued for later
batch processing.
|
[
"This",
"invalidates",
"all",
"entries",
"in",
"this",
"Cache",
"having",
"a",
"dependency",
"on",
"this",
"template",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java#L535-L543
|
jbellis/jamm
|
src/org/github/jamm/MemoryLayoutSpecification.java
|
MemoryLayoutSpecification.sizeOfInstanceWithUnsafe
|
public static long sizeOfInstanceWithUnsafe(Class<?> type) {
"""
attemps to use sun.misc.Unsafe to find the maximum object offset, this work around helps deal with long alignment
"""
while (type != null)
{
long size = 0;
for (Field f : declaredFieldsOf(type))
size = Math.max(size, unsafe.objectFieldOffset(f) + sizeOf(f));
if (size > 0)
return roundTo(size, SPEC.getObjectPadding());
type = type.getSuperclass();
}
return roundTo(SPEC.getObjectHeaderSize(), SPEC.getObjectPadding());
}
|
java
|
public static long sizeOfInstanceWithUnsafe(Class<?> type) {
while (type != null)
{
long size = 0;
for (Field f : declaredFieldsOf(type))
size = Math.max(size, unsafe.objectFieldOffset(f) + sizeOf(f));
if (size > 0)
return roundTo(size, SPEC.getObjectPadding());
type = type.getSuperclass();
}
return roundTo(SPEC.getObjectHeaderSize(), SPEC.getObjectPadding());
}
|
[
"public",
"static",
"long",
"sizeOfInstanceWithUnsafe",
"(",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"while",
"(",
"type",
"!=",
"null",
")",
"{",
"long",
"size",
"=",
"0",
";",
"for",
"(",
"Field",
"f",
":",
"declaredFieldsOf",
"(",
"type",
")",
")",
"size",
"=",
"Math",
".",
"max",
"(",
"size",
",",
"unsafe",
".",
"objectFieldOffset",
"(",
"f",
")",
"+",
"sizeOf",
"(",
"f",
")",
")",
";",
"if",
"(",
"size",
">",
"0",
")",
"return",
"roundTo",
"(",
"size",
",",
"SPEC",
".",
"getObjectPadding",
"(",
")",
")",
";",
"type",
"=",
"type",
".",
"getSuperclass",
"(",
")",
";",
"}",
"return",
"roundTo",
"(",
"SPEC",
".",
"getObjectHeaderSize",
"(",
")",
",",
"SPEC",
".",
"getObjectPadding",
"(",
")",
")",
";",
"}"
] |
attemps to use sun.misc.Unsafe to find the maximum object offset, this work around helps deal with long alignment
|
[
"attemps",
"to",
"use",
"sun",
".",
"misc",
".",
"Unsafe",
"to",
"find",
"the",
"maximum",
"object",
"offset",
"this",
"work",
"around",
"helps",
"deal",
"with",
"long",
"alignment"
] |
train
|
https://github.com/jbellis/jamm/blob/b397a48705ff579028df258e08e28b9c97d8472b/src/org/github/jamm/MemoryLayoutSpecification.java#L103-L114
|
Azure/azure-sdk-for-java
|
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
|
ModelsImpl.deleteClosedListEntityRoleAsync
|
public Observable<OperationStatus> deleteClosedListEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId) {
"""
Delete an entity role.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity ID.
@param roleId The entity role Id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object
"""
return deleteClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
}
|
java
|
public Observable<OperationStatus> deleteClosedListEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId) {
return deleteClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"OperationStatus",
">",
"deleteClosedListEntityRoleAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
",",
"UUID",
"roleId",
")",
"{",
"return",
"deleteClosedListEntityRoleWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
",",
"roleId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"OperationStatus",
">",
",",
"OperationStatus",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"OperationStatus",
"call",
"(",
"ServiceResponse",
"<",
"OperationStatus",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Delete an entity role.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity ID.
@param roleId The entity role Id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object
|
[
"Delete",
"an",
"entity",
"role",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L11882-L11889
|
pietermartin/sqlg
|
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/TopologyManager.java
|
TopologyManager.addIndex
|
public static void addIndex(SqlgGraph sqlgGraph, String schema, String label, boolean vertex, String index, IndexType indexType, List<String> properties) {
"""
add an index from information schema
@param sqlgGraph the graph
@param schema the schema name
@param label the label name
@param vertex is it a vertex or an edge label?
@param index the index name
@param indexType index type
@param properties the column names
"""
BatchManager.BatchModeType batchModeType = flushAndSetTxToNone(sqlgGraph);
try {
//get the abstractLabel's vertex
GraphTraversalSource traversalSource = sqlgGraph.topology();
List<Vertex> abstractLabelVertexes;
if (vertex) {
abstractLabelVertexes = traversalSource.V()
.hasLabel(SQLG_SCHEMA + "." + SQLG_SCHEMA_SCHEMA)
.has(SQLG_SCHEMA_SCHEMA_NAME, schema)
.out(SQLG_SCHEMA_SCHEMA_VERTEX_EDGE)
.has("name", label)
.toList();
} else {
abstractLabelVertexes = traversalSource.V()
.hasLabel(SQLG_SCHEMA + "." + SQLG_SCHEMA_SCHEMA)
.has(SQLG_SCHEMA_SCHEMA_NAME, schema)
.out(SQLG_SCHEMA_SCHEMA_VERTEX_EDGE)
.out(SQLG_SCHEMA_OUT_EDGES_EDGE)
.has("name", label)
.dedup()
.toList();
}
Preconditions.checkState(!abstractLabelVertexes.isEmpty(), "AbstractLabel %s.%s does not exists", schema, label);
Preconditions.checkState(abstractLabelVertexes.size() == 1, "BUG: multiple AbstractLabels found for %s.%s", schema, label);
Vertex abstractLabelVertex = abstractLabelVertexes.get(0);
boolean createdIndexVertex = false;
Vertex indexVertex = null;
int ix = 0;
for (String property : properties) {
List<Vertex> propertyVertexes = traversalSource.V(abstractLabelVertex)
.out(vertex ? SQLG_SCHEMA_VERTEX_PROPERTIES_EDGE : SQLG_SCHEMA_EDGE_PROPERTIES_EDGE)
.has("name", property)
.toList();
//do not create indexes for properties that are not found.
//TODO, Sqlg needs to get more sophisticated support for indexes, i.e. function indexes on a property etc.
if (!createdIndexVertex && !propertyVertexes.isEmpty()) {
createdIndexVertex = true;
indexVertex = sqlgGraph.addVertex(
T.label, SQLG_SCHEMA + "." + SQLG_SCHEMA_INDEX,
SQLG_SCHEMA_INDEX_NAME, index,
SQLG_SCHEMA_INDEX_INDEX_TYPE, indexType.toString(),
CREATED_ON, LocalDateTime.now()
);
if (vertex) {
abstractLabelVertex.addEdge(SQLG_SCHEMA_VERTEX_INDEX_EDGE, indexVertex);
} else {
abstractLabelVertex.addEdge(SQLG_SCHEMA_EDGE_INDEX_EDGE, indexVertex);
}
}
if (!propertyVertexes.isEmpty()) {
Preconditions.checkState(propertyVertexes.size() == 1, "BUG: multiple Properties %s found for AbstractLabels found for %s.%s", property, schema, label);
Preconditions.checkState(indexVertex != null);
Vertex propertyVertex = propertyVertexes.get(0);
indexVertex.addEdge(SQLG_SCHEMA_INDEX_PROPERTY_EDGE, propertyVertex, SQLG_SCHEMA_INDEX_PROPERTY_EDGE_SEQUENCE, ix);
}
}
} finally {
sqlgGraph.tx().batchMode(batchModeType);
}
}
|
java
|
public static void addIndex(SqlgGraph sqlgGraph, String schema, String label, boolean vertex, String index, IndexType indexType, List<String> properties) {
BatchManager.BatchModeType batchModeType = flushAndSetTxToNone(sqlgGraph);
try {
//get the abstractLabel's vertex
GraphTraversalSource traversalSource = sqlgGraph.topology();
List<Vertex> abstractLabelVertexes;
if (vertex) {
abstractLabelVertexes = traversalSource.V()
.hasLabel(SQLG_SCHEMA + "." + SQLG_SCHEMA_SCHEMA)
.has(SQLG_SCHEMA_SCHEMA_NAME, schema)
.out(SQLG_SCHEMA_SCHEMA_VERTEX_EDGE)
.has("name", label)
.toList();
} else {
abstractLabelVertexes = traversalSource.V()
.hasLabel(SQLG_SCHEMA + "." + SQLG_SCHEMA_SCHEMA)
.has(SQLG_SCHEMA_SCHEMA_NAME, schema)
.out(SQLG_SCHEMA_SCHEMA_VERTEX_EDGE)
.out(SQLG_SCHEMA_OUT_EDGES_EDGE)
.has("name", label)
.dedup()
.toList();
}
Preconditions.checkState(!abstractLabelVertexes.isEmpty(), "AbstractLabel %s.%s does not exists", schema, label);
Preconditions.checkState(abstractLabelVertexes.size() == 1, "BUG: multiple AbstractLabels found for %s.%s", schema, label);
Vertex abstractLabelVertex = abstractLabelVertexes.get(0);
boolean createdIndexVertex = false;
Vertex indexVertex = null;
int ix = 0;
for (String property : properties) {
List<Vertex> propertyVertexes = traversalSource.V(abstractLabelVertex)
.out(vertex ? SQLG_SCHEMA_VERTEX_PROPERTIES_EDGE : SQLG_SCHEMA_EDGE_PROPERTIES_EDGE)
.has("name", property)
.toList();
//do not create indexes for properties that are not found.
//TODO, Sqlg needs to get more sophisticated support for indexes, i.e. function indexes on a property etc.
if (!createdIndexVertex && !propertyVertexes.isEmpty()) {
createdIndexVertex = true;
indexVertex = sqlgGraph.addVertex(
T.label, SQLG_SCHEMA + "." + SQLG_SCHEMA_INDEX,
SQLG_SCHEMA_INDEX_NAME, index,
SQLG_SCHEMA_INDEX_INDEX_TYPE, indexType.toString(),
CREATED_ON, LocalDateTime.now()
);
if (vertex) {
abstractLabelVertex.addEdge(SQLG_SCHEMA_VERTEX_INDEX_EDGE, indexVertex);
} else {
abstractLabelVertex.addEdge(SQLG_SCHEMA_EDGE_INDEX_EDGE, indexVertex);
}
}
if (!propertyVertexes.isEmpty()) {
Preconditions.checkState(propertyVertexes.size() == 1, "BUG: multiple Properties %s found for AbstractLabels found for %s.%s", property, schema, label);
Preconditions.checkState(indexVertex != null);
Vertex propertyVertex = propertyVertexes.get(0);
indexVertex.addEdge(SQLG_SCHEMA_INDEX_PROPERTY_EDGE, propertyVertex, SQLG_SCHEMA_INDEX_PROPERTY_EDGE_SEQUENCE, ix);
}
}
} finally {
sqlgGraph.tx().batchMode(batchModeType);
}
}
|
[
"public",
"static",
"void",
"addIndex",
"(",
"SqlgGraph",
"sqlgGraph",
",",
"String",
"schema",
",",
"String",
"label",
",",
"boolean",
"vertex",
",",
"String",
"index",
",",
"IndexType",
"indexType",
",",
"List",
"<",
"String",
">",
"properties",
")",
"{",
"BatchManager",
".",
"BatchModeType",
"batchModeType",
"=",
"flushAndSetTxToNone",
"(",
"sqlgGraph",
")",
";",
"try",
"{",
"//get the abstractLabel's vertex",
"GraphTraversalSource",
"traversalSource",
"=",
"sqlgGraph",
".",
"topology",
"(",
")",
";",
"List",
"<",
"Vertex",
">",
"abstractLabelVertexes",
";",
"if",
"(",
"vertex",
")",
"{",
"abstractLabelVertexes",
"=",
"traversalSource",
".",
"V",
"(",
")",
".",
"hasLabel",
"(",
"SQLG_SCHEMA",
"+",
"\".\"",
"+",
"SQLG_SCHEMA_SCHEMA",
")",
".",
"has",
"(",
"SQLG_SCHEMA_SCHEMA_NAME",
",",
"schema",
")",
".",
"out",
"(",
"SQLG_SCHEMA_SCHEMA_VERTEX_EDGE",
")",
".",
"has",
"(",
"\"name\"",
",",
"label",
")",
".",
"toList",
"(",
")",
";",
"}",
"else",
"{",
"abstractLabelVertexes",
"=",
"traversalSource",
".",
"V",
"(",
")",
".",
"hasLabel",
"(",
"SQLG_SCHEMA",
"+",
"\".\"",
"+",
"SQLG_SCHEMA_SCHEMA",
")",
".",
"has",
"(",
"SQLG_SCHEMA_SCHEMA_NAME",
",",
"schema",
")",
".",
"out",
"(",
"SQLG_SCHEMA_SCHEMA_VERTEX_EDGE",
")",
".",
"out",
"(",
"SQLG_SCHEMA_OUT_EDGES_EDGE",
")",
".",
"has",
"(",
"\"name\"",
",",
"label",
")",
".",
"dedup",
"(",
")",
".",
"toList",
"(",
")",
";",
"}",
"Preconditions",
".",
"checkState",
"(",
"!",
"abstractLabelVertexes",
".",
"isEmpty",
"(",
")",
",",
"\"AbstractLabel %s.%s does not exists\"",
",",
"schema",
",",
"label",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"abstractLabelVertexes",
".",
"size",
"(",
")",
"==",
"1",
",",
"\"BUG: multiple AbstractLabels found for %s.%s\"",
",",
"schema",
",",
"label",
")",
";",
"Vertex",
"abstractLabelVertex",
"=",
"abstractLabelVertexes",
".",
"get",
"(",
"0",
")",
";",
"boolean",
"createdIndexVertex",
"=",
"false",
";",
"Vertex",
"indexVertex",
"=",
"null",
";",
"int",
"ix",
"=",
"0",
";",
"for",
"(",
"String",
"property",
":",
"properties",
")",
"{",
"List",
"<",
"Vertex",
">",
"propertyVertexes",
"=",
"traversalSource",
".",
"V",
"(",
"abstractLabelVertex",
")",
".",
"out",
"(",
"vertex",
"?",
"SQLG_SCHEMA_VERTEX_PROPERTIES_EDGE",
":",
"SQLG_SCHEMA_EDGE_PROPERTIES_EDGE",
")",
".",
"has",
"(",
"\"name\"",
",",
"property",
")",
".",
"toList",
"(",
")",
";",
"//do not create indexes for properties that are not found.",
"//TODO, Sqlg needs to get more sophisticated support for indexes, i.e. function indexes on a property etc.",
"if",
"(",
"!",
"createdIndexVertex",
"&&",
"!",
"propertyVertexes",
".",
"isEmpty",
"(",
")",
")",
"{",
"createdIndexVertex",
"=",
"true",
";",
"indexVertex",
"=",
"sqlgGraph",
".",
"addVertex",
"(",
"T",
".",
"label",
",",
"SQLG_SCHEMA",
"+",
"\".\"",
"+",
"SQLG_SCHEMA_INDEX",
",",
"SQLG_SCHEMA_INDEX_NAME",
",",
"index",
",",
"SQLG_SCHEMA_INDEX_INDEX_TYPE",
",",
"indexType",
".",
"toString",
"(",
")",
",",
"CREATED_ON",
",",
"LocalDateTime",
".",
"now",
"(",
")",
")",
";",
"if",
"(",
"vertex",
")",
"{",
"abstractLabelVertex",
".",
"addEdge",
"(",
"SQLG_SCHEMA_VERTEX_INDEX_EDGE",
",",
"indexVertex",
")",
";",
"}",
"else",
"{",
"abstractLabelVertex",
".",
"addEdge",
"(",
"SQLG_SCHEMA_EDGE_INDEX_EDGE",
",",
"indexVertex",
")",
";",
"}",
"}",
"if",
"(",
"!",
"propertyVertexes",
".",
"isEmpty",
"(",
")",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"propertyVertexes",
".",
"size",
"(",
")",
"==",
"1",
",",
"\"BUG: multiple Properties %s found for AbstractLabels found for %s.%s\"",
",",
"property",
",",
"schema",
",",
"label",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"indexVertex",
"!=",
"null",
")",
";",
"Vertex",
"propertyVertex",
"=",
"propertyVertexes",
".",
"get",
"(",
"0",
")",
";",
"indexVertex",
".",
"addEdge",
"(",
"SQLG_SCHEMA_INDEX_PROPERTY_EDGE",
",",
"propertyVertex",
",",
"SQLG_SCHEMA_INDEX_PROPERTY_EDGE_SEQUENCE",
",",
"ix",
")",
";",
"}",
"}",
"}",
"finally",
"{",
"sqlgGraph",
".",
"tx",
"(",
")",
".",
"batchMode",
"(",
"batchModeType",
")",
";",
"}",
"}"
] |
add an index from information schema
@param sqlgGraph the graph
@param schema the schema name
@param label the label name
@param vertex is it a vertex or an edge label?
@param index the index name
@param indexType index type
@param properties the column names
|
[
"add",
"an",
"index",
"from",
"information",
"schema"
] |
train
|
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/TopologyManager.java#L966-L1029
|
elki-project/elki
|
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/dependence/DistanceCorrelationDependenceMeasure.java
|
DistanceCorrelationDependenceMeasure.computeDCovar
|
protected double computeDCovar(double[] dVarMatrixA, double[] dVarMatrixB, int n) {
"""
Computes the distance covariance for two axis. Can also be used to compute
the distance variance of one axis (dVarMatrixA = dVarMatrixB).
@param dVarMatrixA distance variance matrix of the first axis
@param dVarMatrixB distance variance matrix of the second axis
@param n number of points
@return distance covariance
"""
double result = 0.;
for(int i = 0, c = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
result += 2. * dVarMatrixA[c] * dVarMatrixB[c];
c++;
}
// Diagonal entry.
result += dVarMatrixA[c] * dVarMatrixB[c];
c++;
}
return result / (n * n);
}
|
java
|
protected double computeDCovar(double[] dVarMatrixA, double[] dVarMatrixB, int n) {
double result = 0.;
for(int i = 0, c = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
result += 2. * dVarMatrixA[c] * dVarMatrixB[c];
c++;
}
// Diagonal entry.
result += dVarMatrixA[c] * dVarMatrixB[c];
c++;
}
return result / (n * n);
}
|
[
"protected",
"double",
"computeDCovar",
"(",
"double",
"[",
"]",
"dVarMatrixA",
",",
"double",
"[",
"]",
"dVarMatrixB",
",",
"int",
"n",
")",
"{",
"double",
"result",
"=",
"0.",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"c",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"i",
";",
"j",
"++",
")",
"{",
"result",
"+=",
"2.",
"*",
"dVarMatrixA",
"[",
"c",
"]",
"*",
"dVarMatrixB",
"[",
"c",
"]",
";",
"c",
"++",
";",
"}",
"// Diagonal entry.",
"result",
"+=",
"dVarMatrixA",
"[",
"c",
"]",
"*",
"dVarMatrixB",
"[",
"c",
"]",
";",
"c",
"++",
";",
"}",
"return",
"result",
"/",
"(",
"n",
"*",
"n",
")",
";",
"}"
] |
Computes the distance covariance for two axis. Can also be used to compute
the distance variance of one axis (dVarMatrixA = dVarMatrixB).
@param dVarMatrixA distance variance matrix of the first axis
@param dVarMatrixB distance variance matrix of the second axis
@param n number of points
@return distance covariance
|
[
"Computes",
"the",
"distance",
"covariance",
"for",
"two",
"axis",
".",
"Can",
"also",
"be",
"used",
"to",
"compute",
"the",
"distance",
"variance",
"of",
"one",
"axis",
"(",
"dVarMatrixA",
"=",
"dVarMatrixB",
")",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/dependence/DistanceCorrelationDependenceMeasure.java#L178-L190
|
cose-wg/COSE-JAVA
|
src/main/java/COSE/Attribute.java
|
Attribute.AddProtected
|
@Deprecated
public void AddProtected(HeaderKeys label, byte[] value) throws CoseException {
"""
Set an attribute in the protect bucket of the COSE object
@param label CBOR object which identifies the attribute in the map
@param value byte array of value
@deprecated As of COSE 0.9.0, use addAttribute(HeaderKeys, byte[], Attribute.PROTECTED);
@exception CoseException COSE Package exception
"""
addAttribute(label, value, PROTECTED);
}
|
java
|
@Deprecated
public void AddProtected(HeaderKeys label, byte[] value) throws CoseException {
addAttribute(label, value, PROTECTED);
}
|
[
"@",
"Deprecated",
"public",
"void",
"AddProtected",
"(",
"HeaderKeys",
"label",
",",
"byte",
"[",
"]",
"value",
")",
"throws",
"CoseException",
"{",
"addAttribute",
"(",
"label",
",",
"value",
",",
"PROTECTED",
")",
";",
"}"
] |
Set an attribute in the protect bucket of the COSE object
@param label CBOR object which identifies the attribute in the map
@param value byte array of value
@deprecated As of COSE 0.9.0, use addAttribute(HeaderKeys, byte[], Attribute.PROTECTED);
@exception CoseException COSE Package exception
|
[
"Set",
"an",
"attribute",
"in",
"the",
"protect",
"bucket",
"of",
"the",
"COSE",
"object"
] |
train
|
https://github.com/cose-wg/COSE-JAVA/blob/f972b11ab4c9a18f911bc49a15225a6951cf6f63/src/main/java/COSE/Attribute.java#L205-L208
|
Azure/azure-sdk-for-java
|
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
|
KeyVaultClientBaseImpl.getSecretVersionsAsync
|
public Observable<Page<SecretItem>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName) {
"""
List all versions of the specified secret.
The full secret identifier and attributes are provided in the response. No values are returned for the secrets. This operations requires the secrets/list permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param secretName The name of the secret.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SecretItem> object
"""
return getSecretVersionsWithServiceResponseAsync(vaultBaseUrl, secretName)
.map(new Func1<ServiceResponse<Page<SecretItem>>, Page<SecretItem>>() {
@Override
public Page<SecretItem> call(ServiceResponse<Page<SecretItem>> response) {
return response.body();
}
});
}
|
java
|
public Observable<Page<SecretItem>> getSecretVersionsAsync(final String vaultBaseUrl, final String secretName) {
return getSecretVersionsWithServiceResponseAsync(vaultBaseUrl, secretName)
.map(new Func1<ServiceResponse<Page<SecretItem>>, Page<SecretItem>>() {
@Override
public Page<SecretItem> call(ServiceResponse<Page<SecretItem>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"Page",
"<",
"SecretItem",
">",
">",
"getSecretVersionsAsync",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"String",
"secretName",
")",
"{",
"return",
"getSecretVersionsWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"secretName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SecretItem",
">",
">",
",",
"Page",
"<",
"SecretItem",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"SecretItem",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"SecretItem",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
List all versions of the specified secret.
The full secret identifier and attributes are provided in the response. No values are returned for the secrets. This operations requires the secrets/list permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param secretName The name of the secret.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SecretItem> object
|
[
"List",
"all",
"versions",
"of",
"the",
"specified",
"secret",
".",
"The",
"full",
"secret",
"identifier",
"and",
"attributes",
"are",
"provided",
"in",
"the",
"response",
".",
"No",
"values",
"are",
"returned",
"for",
"the",
"secrets",
".",
"This",
"operations",
"requires",
"the",
"secrets",
"/",
"list",
"permission",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L4198-L4206
|
knowm/XChange
|
xchange-paribu/src/main/java/org/knowm/xchange/paribu/ParibuAdapters.java
|
ParibuAdapters.adaptTicker
|
public static Ticker adaptTicker(ParibuTicker paribuTicker, CurrencyPair currencyPair) {
"""
Adapts a ParibuTicker to a Ticker Object
@param paribuTicker The exchange specific ticker
@param currencyPair
@return The ticker
"""
if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) {
throw new NotAvailableFromExchangeException();
}
BTC_TL btcTL = paribuTicker.getBtcTL();
if (btcTL != null) {
BigDecimal last = btcTL.getLast();
BigDecimal lowestAsk = btcTL.getLowestAsk();
BigDecimal highestBid = btcTL.getHighestBid();
BigDecimal volume = btcTL.getVolume();
BigDecimal high24hr = btcTL.getHigh24hr();
BigDecimal low24hr = btcTL.getLow24hr();
return new Ticker.Builder()
.currencyPair(new CurrencyPair(BTC, Currency.TRY))
.last(last)
.bid(highestBid)
.ask(lowestAsk)
.high(high24hr)
.low(low24hr)
.volume(volume)
.build();
}
return null;
}
|
java
|
public static Ticker adaptTicker(ParibuTicker paribuTicker, CurrencyPair currencyPair) {
if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) {
throw new NotAvailableFromExchangeException();
}
BTC_TL btcTL = paribuTicker.getBtcTL();
if (btcTL != null) {
BigDecimal last = btcTL.getLast();
BigDecimal lowestAsk = btcTL.getLowestAsk();
BigDecimal highestBid = btcTL.getHighestBid();
BigDecimal volume = btcTL.getVolume();
BigDecimal high24hr = btcTL.getHigh24hr();
BigDecimal low24hr = btcTL.getLow24hr();
return new Ticker.Builder()
.currencyPair(new CurrencyPair(BTC, Currency.TRY))
.last(last)
.bid(highestBid)
.ask(lowestAsk)
.high(high24hr)
.low(low24hr)
.volume(volume)
.build();
}
return null;
}
|
[
"public",
"static",
"Ticker",
"adaptTicker",
"(",
"ParibuTicker",
"paribuTicker",
",",
"CurrencyPair",
"currencyPair",
")",
"{",
"if",
"(",
"!",
"currencyPair",
".",
"equals",
"(",
"new",
"CurrencyPair",
"(",
"BTC",
",",
"TRY",
")",
")",
")",
"{",
"throw",
"new",
"NotAvailableFromExchangeException",
"(",
")",
";",
"}",
"BTC_TL",
"btcTL",
"=",
"paribuTicker",
".",
"getBtcTL",
"(",
")",
";",
"if",
"(",
"btcTL",
"!=",
"null",
")",
"{",
"BigDecimal",
"last",
"=",
"btcTL",
".",
"getLast",
"(",
")",
";",
"BigDecimal",
"lowestAsk",
"=",
"btcTL",
".",
"getLowestAsk",
"(",
")",
";",
"BigDecimal",
"highestBid",
"=",
"btcTL",
".",
"getHighestBid",
"(",
")",
";",
"BigDecimal",
"volume",
"=",
"btcTL",
".",
"getVolume",
"(",
")",
";",
"BigDecimal",
"high24hr",
"=",
"btcTL",
".",
"getHigh24hr",
"(",
")",
";",
"BigDecimal",
"low24hr",
"=",
"btcTL",
".",
"getLow24hr",
"(",
")",
";",
"return",
"new",
"Ticker",
".",
"Builder",
"(",
")",
".",
"currencyPair",
"(",
"new",
"CurrencyPair",
"(",
"BTC",
",",
"Currency",
".",
"TRY",
")",
")",
".",
"last",
"(",
"last",
")",
".",
"bid",
"(",
"highestBid",
")",
".",
"ask",
"(",
"lowestAsk",
")",
".",
"high",
"(",
"high24hr",
")",
".",
"low",
"(",
"low24hr",
")",
".",
"volume",
"(",
"volume",
")",
".",
"build",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Adapts a ParibuTicker to a Ticker Object
@param paribuTicker The exchange specific ticker
@param currencyPair
@return The ticker
|
[
"Adapts",
"a",
"ParibuTicker",
"to",
"a",
"Ticker",
"Object"
] |
train
|
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-paribu/src/main/java/org/knowm/xchange/paribu/ParibuAdapters.java#L26-L49
|
codeprimate-software/cp-elements
|
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
|
ElementsExceptionsFactory.newConversionException
|
public static ConversionException newConversionException(String message, Object... args) {
"""
Constructs and initializes a new {@link ConversionException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link ConversionException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ConversionException} with the given {@link String message}.
@see #newConversionException(Throwable, String, Object...)
@see org.cp.elements.data.conversion.ConversionException
"""
return newConversionException(null, message, args);
}
|
java
|
public static ConversionException newConversionException(String message, Object... args) {
return newConversionException(null, message, args);
}
|
[
"public",
"static",
"ConversionException",
"newConversionException",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"newConversionException",
"(",
"null",
",",
"message",
",",
"args",
")",
";",
"}"
] |
Constructs and initializes a new {@link ConversionException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link ConversionException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ConversionException} with the given {@link String message}.
@see #newConversionException(Throwable, String, Object...)
@see org.cp.elements.data.conversion.ConversionException
|
[
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"ConversionException",
"}",
"with",
"the",
"given",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
] |
train
|
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L789-L791
|
jtmelton/appsensor
|
analysis-engines/appsensor-analysis-reference/src/main/java/org/owasp/appsensor/analysis/ReferenceAttackAnalysisEngine.java
|
ReferenceAttackAnalysisEngine.isPreviousResponse
|
protected boolean isPreviousResponse(Response response, Collection<Response> existingResponses) {
"""
Test a given {@link Response} to see if it's been executed before.
@param response {@link Response} to test to see if it's been executed before
@param existingResponses set of previously executed {@link Response}s
@return true if {@link Response} has been executed before
"""
boolean previousResponse = false;
for (Response existingResponse : existingResponses) {
if (response.getAction().equals(existingResponse.getAction())) {
previousResponse = true;
}
}
return previousResponse;
}
|
java
|
protected boolean isPreviousResponse(Response response, Collection<Response> existingResponses) {
boolean previousResponse = false;
for (Response existingResponse : existingResponses) {
if (response.getAction().equals(existingResponse.getAction())) {
previousResponse = true;
}
}
return previousResponse;
}
|
[
"protected",
"boolean",
"isPreviousResponse",
"(",
"Response",
"response",
",",
"Collection",
"<",
"Response",
">",
"existingResponses",
")",
"{",
"boolean",
"previousResponse",
"=",
"false",
";",
"for",
"(",
"Response",
"existingResponse",
":",
"existingResponses",
")",
"{",
"if",
"(",
"response",
".",
"getAction",
"(",
")",
".",
"equals",
"(",
"existingResponse",
".",
"getAction",
"(",
")",
")",
")",
"{",
"previousResponse",
"=",
"true",
";",
"}",
"}",
"return",
"previousResponse",
";",
"}"
] |
Test a given {@link Response} to see if it's been executed before.
@param response {@link Response} to test to see if it's been executed before
@param existingResponses set of previously executed {@link Response}s
@return true if {@link Response} has been executed before
|
[
"Test",
"a",
"given",
"{",
"@link",
"Response",
"}",
"to",
"see",
"if",
"it",
"s",
"been",
"executed",
"before",
"."
] |
train
|
https://github.com/jtmelton/appsensor/blob/c3b4e9ada50fdee974e0d618ec4bdfabc2163798/analysis-engines/appsensor-analysis-reference/src/main/java/org/owasp/appsensor/analysis/ReferenceAttackAnalysisEngine.java#L143-L153
|
Viascom/groundwork
|
foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/component/oauth2/OAuth2StoreBuilder.java
|
OAuth2StoreBuilder.addAdditionalParameter
|
public OAuth2StoreBuilder addAdditionalParameter(String key, String value) {
"""
Add an additional parameter which will be included in the token request
@param key additional parameter key
@param value additional parameter value
@return OAuth2StoreBuilder (this)
"""
oAuth2Store.getAdditionalParameters().put(key, value);
return this;
}
|
java
|
public OAuth2StoreBuilder addAdditionalParameter(String key, String value) {
oAuth2Store.getAdditionalParameters().put(key, value);
return this;
}
|
[
"public",
"OAuth2StoreBuilder",
"addAdditionalParameter",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"oAuth2Store",
".",
"getAdditionalParameters",
"(",
")",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] |
Add an additional parameter which will be included in the token request
@param key additional parameter key
@param value additional parameter value
@return OAuth2StoreBuilder (this)
|
[
"Add",
"an",
"additional",
"parameter",
"which",
"will",
"be",
"included",
"in",
"the",
"token",
"request"
] |
train
|
https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/component/oauth2/OAuth2StoreBuilder.java#L92-L95
|
exoplatform/jcr
|
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/JcrStandartAnalyzer.java
|
JcrStandartAnalyzer.tokenStream
|
@Override
public TokenStream tokenStream(String fieldName, Reader reader) {
"""
Creates a TokenStream which tokenizes all the text in the provided
Reader. If the fieldName (property) is configured to have a different
analyzer than the default, this analyzer is used for tokenization
"""
if (indexingConfig != null)
{
Analyzer propertyAnalyzer = indexingConfig.getPropertyAnalyzer(fieldName);
if (propertyAnalyzer != null)
{
return propertyAnalyzer.tokenStream(fieldName, reader);
}
}
return defaultAnalyzer.tokenStream(fieldName, reader);
}
|
java
|
@Override
public TokenStream tokenStream(String fieldName, Reader reader)
{
if (indexingConfig != null)
{
Analyzer propertyAnalyzer = indexingConfig.getPropertyAnalyzer(fieldName);
if (propertyAnalyzer != null)
{
return propertyAnalyzer.tokenStream(fieldName, reader);
}
}
return defaultAnalyzer.tokenStream(fieldName, reader);
}
|
[
"@",
"Override",
"public",
"TokenStream",
"tokenStream",
"(",
"String",
"fieldName",
",",
"Reader",
"reader",
")",
"{",
"if",
"(",
"indexingConfig",
"!=",
"null",
")",
"{",
"Analyzer",
"propertyAnalyzer",
"=",
"indexingConfig",
".",
"getPropertyAnalyzer",
"(",
"fieldName",
")",
";",
"if",
"(",
"propertyAnalyzer",
"!=",
"null",
")",
"{",
"return",
"propertyAnalyzer",
".",
"tokenStream",
"(",
"fieldName",
",",
"reader",
")",
";",
"}",
"}",
"return",
"defaultAnalyzer",
".",
"tokenStream",
"(",
"fieldName",
",",
"reader",
")",
";",
"}"
] |
Creates a TokenStream which tokenizes all the text in the provided
Reader. If the fieldName (property) is configured to have a different
analyzer than the default, this analyzer is used for tokenization
|
[
"Creates",
"a",
"TokenStream",
"which",
"tokenizes",
"all",
"the",
"text",
"in",
"the",
"provided",
"Reader",
".",
"If",
"the",
"fieldName",
"(",
"property",
")",
"is",
"configured",
"to",
"have",
"a",
"different",
"analyzer",
"than",
"the",
"default",
"this",
"analyzer",
"is",
"used",
"for",
"tokenization"
] |
train
|
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/JcrStandartAnalyzer.java#L80-L92
|
orbisgis/h2gis
|
postgis-jts/src/main/java/org/h2gis/postgis_jts/JtsBinaryParser.java
|
JtsBinaryParser.parseMultiPoint
|
private MultiPoint parseMultiPoint(ValueGetter data, int srid) {
"""
Parse the given {@link org.postgis.binary.ValueGetter} into a JTS
{@link org.locationtech.jts.geom.MultiPoint}.
@param data {@link org.postgis.binary.ValueGetter} to parse.
@param srid SRID of the parsed geometries.
@return The parsed {@link org.locationtech.jts.geom.MultiPoint}.
"""
Point[] points = new Point[data.getInt()];
this.parseGeometryArray(data, points, srid);
return JtsGeometry.geofac.createMultiPoint(points);
}
|
java
|
private MultiPoint parseMultiPoint(ValueGetter data, int srid) {
Point[] points = new Point[data.getInt()];
this.parseGeometryArray(data, points, srid);
return JtsGeometry.geofac.createMultiPoint(points);
}
|
[
"private",
"MultiPoint",
"parseMultiPoint",
"(",
"ValueGetter",
"data",
",",
"int",
"srid",
")",
"{",
"Point",
"[",
"]",
"points",
"=",
"new",
"Point",
"[",
"data",
".",
"getInt",
"(",
")",
"]",
";",
"this",
".",
"parseGeometryArray",
"(",
"data",
",",
"points",
",",
"srid",
")",
";",
"return",
"JtsGeometry",
".",
"geofac",
".",
"createMultiPoint",
"(",
"points",
")",
";",
"}"
] |
Parse the given {@link org.postgis.binary.ValueGetter} into a JTS
{@link org.locationtech.jts.geom.MultiPoint}.
@param data {@link org.postgis.binary.ValueGetter} to parse.
@param srid SRID of the parsed geometries.
@return The parsed {@link org.locationtech.jts.geom.MultiPoint}.
|
[
"Parse",
"the",
"given",
"{",
"@link",
"org",
".",
"postgis",
".",
"binary",
".",
"ValueGetter",
"}",
"into",
"a",
"JTS",
"{",
"@link",
"org",
".",
"locationtech",
".",
"jts",
".",
"geom",
".",
"MultiPoint",
"}",
"."
] |
train
|
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/postgis-jts/src/main/java/org/h2gis/postgis_jts/JtsBinaryParser.java#L237-L241
|
twilio/twilio-java
|
src/main/java/com/twilio/converter/Converter.java
|
Converter.mapToJson
|
public static String mapToJson(final Map<String, Object> map) {
"""
Convert a map to a JSON String.
@param map map to convert
@return converted JSON string
"""
try {
return MAPPER.writeValueAsString(map);
} catch (JsonProcessingException e) {
return null;
}
}
|
java
|
public static String mapToJson(final Map<String, Object> map) {
try {
return MAPPER.writeValueAsString(map);
} catch (JsonProcessingException e) {
return null;
}
}
|
[
"public",
"static",
"String",
"mapToJson",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"try",
"{",
"return",
"MAPPER",
".",
"writeValueAsString",
"(",
"map",
")",
";",
"}",
"catch",
"(",
"JsonProcessingException",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] |
Convert a map to a JSON String.
@param map map to convert
@return converted JSON string
|
[
"Convert",
"a",
"map",
"to",
"a",
"JSON",
"String",
"."
] |
train
|
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/converter/Converter.java#L19-L25
|
carewebframework/carewebframework-core
|
org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/messaging/ConsumerService.java
|
ConsumerService.dispatchMessages
|
protected void dispatchMessages(String channel, Message message, Set<IMessageCallback> callbacks) {
"""
Dispatch message to callback. Override to address special threading considerations.
@param channel The channel that delivered the message.
@param message The message to dispatch.
@param callbacks The callbacks to receive the message.
"""
for (IMessageCallback callback : callbacks) {
try {
callback.onMessage(channel, message);
} catch (Exception e) {
}
}
}
|
java
|
protected void dispatchMessages(String channel, Message message, Set<IMessageCallback> callbacks) {
for (IMessageCallback callback : callbacks) {
try {
callback.onMessage(channel, message);
} catch (Exception e) {
}
}
}
|
[
"protected",
"void",
"dispatchMessages",
"(",
"String",
"channel",
",",
"Message",
"message",
",",
"Set",
"<",
"IMessageCallback",
">",
"callbacks",
")",
"{",
"for",
"(",
"IMessageCallback",
"callback",
":",
"callbacks",
")",
"{",
"try",
"{",
"callback",
".",
"onMessage",
"(",
"channel",
",",
"message",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"}"
] |
Dispatch message to callback. Override to address special threading considerations.
@param channel The channel that delivered the message.
@param message The message to dispatch.
@param callbacks The callbacks to receive the message.
|
[
"Dispatch",
"message",
"to",
"callback",
".",
"Override",
"to",
"address",
"special",
"threading",
"considerations",
"."
] |
train
|
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/messaging/ConsumerService.java#L186-L194
|
xmlet/XsdAsmFaster
|
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmVisitor.java
|
XsdAsmVisitor.addVisitorElementMethod
|
@SuppressWarnings("Duplicates")
private static void addVisitorElementMethod(ClassWriter classWriter, String elementName, String apiName) {
"""
Adds a specific method for a visitElement call.
Example:
void visitElementHtml(Html<Z> html){
visitElement(html);
}
@param classWriter The ElementVisitor class {@link ClassWriter}.
@param elementName The specific element.
@param apiName The name of the generated fluent interface.
"""
elementName = getCleanName(elementName);
String classType = getFullClassTypeName(elementName, apiName);
String classTypeDesc = getFullClassTypeNameDesc(elementName, apiName);
MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, VISIT_ELEMENT_NAME + elementName, "(" + classTypeDesc + ")V", "<Z::" + elementTypeDesc + ">(L" + classType + "<TZ;>;)V", null);
mVisitor.visitCode();
mVisitor.visitVarInsn(ALOAD, 0);
mVisitor.visitVarInsn(ALOAD, 1);
mVisitor.visitMethodInsn(INVOKEVIRTUAL, elementVisitorType, VISIT_ELEMENT_NAME, "(" + elementTypeDesc + ")V", false);
mVisitor.visitInsn(RETURN);
mVisitor.visitMaxs(2, 2);
mVisitor.visitEnd();
}
|
java
|
@SuppressWarnings("Duplicates")
private static void addVisitorElementMethod(ClassWriter classWriter, String elementName, String apiName) {
elementName = getCleanName(elementName);
String classType = getFullClassTypeName(elementName, apiName);
String classTypeDesc = getFullClassTypeNameDesc(elementName, apiName);
MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, VISIT_ELEMENT_NAME + elementName, "(" + classTypeDesc + ")V", "<Z::" + elementTypeDesc + ">(L" + classType + "<TZ;>;)V", null);
mVisitor.visitCode();
mVisitor.visitVarInsn(ALOAD, 0);
mVisitor.visitVarInsn(ALOAD, 1);
mVisitor.visitMethodInsn(INVOKEVIRTUAL, elementVisitorType, VISIT_ELEMENT_NAME, "(" + elementTypeDesc + ")V", false);
mVisitor.visitInsn(RETURN);
mVisitor.visitMaxs(2, 2);
mVisitor.visitEnd();
}
|
[
"@",
"SuppressWarnings",
"(",
"\"Duplicates\"",
")",
"private",
"static",
"void",
"addVisitorElementMethod",
"(",
"ClassWriter",
"classWriter",
",",
"String",
"elementName",
",",
"String",
"apiName",
")",
"{",
"elementName",
"=",
"getCleanName",
"(",
"elementName",
")",
";",
"String",
"classType",
"=",
"getFullClassTypeName",
"(",
"elementName",
",",
"apiName",
")",
";",
"String",
"classTypeDesc",
"=",
"getFullClassTypeNameDesc",
"(",
"elementName",
",",
"apiName",
")",
";",
"MethodVisitor",
"mVisitor",
"=",
"classWriter",
".",
"visitMethod",
"(",
"ACC_PUBLIC",
",",
"VISIT_ELEMENT_NAME",
"+",
"elementName",
",",
"\"(\"",
"+",
"classTypeDesc",
"+",
"\")V\"",
",",
"\"<Z::\"",
"+",
"elementTypeDesc",
"+",
"\">(L\"",
"+",
"classType",
"+",
"\"<TZ;>;)V\"",
",",
"null",
")",
";",
"mVisitor",
".",
"visitCode",
"(",
")",
";",
"mVisitor",
".",
"visitVarInsn",
"(",
"ALOAD",
",",
"0",
")",
";",
"mVisitor",
".",
"visitVarInsn",
"(",
"ALOAD",
",",
"1",
")",
";",
"mVisitor",
".",
"visitMethodInsn",
"(",
"INVOKEVIRTUAL",
",",
"elementVisitorType",
",",
"VISIT_ELEMENT_NAME",
",",
"\"(\"",
"+",
"elementTypeDesc",
"+",
"\")V\"",
",",
"false",
")",
";",
"mVisitor",
".",
"visitInsn",
"(",
"RETURN",
")",
";",
"mVisitor",
".",
"visitMaxs",
"(",
"2",
",",
"2",
")",
";",
"mVisitor",
".",
"visitEnd",
"(",
")",
";",
"}"
] |
Adds a specific method for a visitElement call.
Example:
void visitElementHtml(Html<Z> html){
visitElement(html);
}
@param classWriter The ElementVisitor class {@link ClassWriter}.
@param elementName The specific element.
@param apiName The name of the generated fluent interface.
|
[
"Adds",
"a",
"specific",
"method",
"for",
"a",
"visitElement",
"call",
".",
"Example",
":",
"void",
"visitElementHtml",
"(",
"Html<Z",
">",
"html",
")",
"{",
"visitElement",
"(",
"html",
")",
";",
"}"
] |
train
|
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmVisitor.java#L130-L144
|
xhsun/gw2wrapper
|
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
|
AsynchronousRequest.getBackStoryQuestionInfo
|
public void getBackStoryQuestionInfo(int[] ids, Callback<List<BackStoryQuestion>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on back story questions API go <a href="https://wiki.guildwars2.com/wiki/API:2/backstory/questions">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of back story question id(s)
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception invalid API key
@throws NullPointerException if given {@link Callback} is empty
@see BackStoryQuestion back story question info
"""
isParamValid(new ParamChecker(ids));
gw2API.getBackStoryQuestionInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
}
|
java
|
public void getBackStoryQuestionInfo(int[] ids, Callback<List<BackStoryQuestion>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getBackStoryQuestionInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
}
|
[
"public",
"void",
"getBackStoryQuestionInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"BackStoryQuestion",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"gw2API",
".",
"getBackStoryQuestionInfo",
"(",
"processIds",
"(",
"ids",
")",
",",
"GuildWars2",
".",
"lang",
".",
"getValue",
"(",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] |
For more info on back story questions API go <a href="https://wiki.guildwars2.com/wiki/API:2/backstory/questions">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of back story question id(s)
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception invalid API key
@throws NullPointerException if given {@link Callback} is empty
@see BackStoryQuestion back story question info
|
[
"For",
"more",
"info",
"on",
"back",
"story",
"questions",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"backstory",
"/",
"questions",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"the",
"access",
"to",
"{",
"@link",
"Callback#onResponse",
"(",
"Call",
"Response",
")",
"}",
"and",
"{",
"@link",
"Callback#onFailure",
"(",
"Call",
"Throwable",
")",
"}",
"methods",
"for",
"custom",
"interactions"
] |
train
|
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L618-L621
|
sstrickx/yahoofinance-api
|
src/main/java/yahoofinance/YahooFinance.java
|
YahooFinance.getFx
|
public static Map<String, FxQuote> getFx(String[] symbols) throws IOException {
"""
Sends a single request to Yahoo Finance to retrieve a quote
for all the requested FX symbols.
See <code>getFx(String)</code> for more information on the
accepted FX symbols.
@param symbols an array of FX symbols
@return the requested FX symbols mapped to their respective quotes
@throws java.io.IOException when there's a connection problem or the request is incorrect
@see #getFx(java.lang.String)
"""
List<FxQuote> quotes;
if(YahooFinance.QUOTES_QUERY1V7_ENABLED.equalsIgnoreCase("true")) {
FxQuotesQuery1V7Request request = new FxQuotesQuery1V7Request(Utils.join(symbols, ","));
quotes = request.getResult();
} else {
FxQuotesRequest request = new FxQuotesRequest(Utils.join(symbols, ","));
quotes = request.getResult();
}
Map<String, FxQuote> result = new HashMap<String, FxQuote>();
for(FxQuote quote : quotes) {
result.put(quote.getSymbol(), quote);
}
return result;
}
|
java
|
public static Map<String, FxQuote> getFx(String[] symbols) throws IOException {
List<FxQuote> quotes;
if(YahooFinance.QUOTES_QUERY1V7_ENABLED.equalsIgnoreCase("true")) {
FxQuotesQuery1V7Request request = new FxQuotesQuery1V7Request(Utils.join(symbols, ","));
quotes = request.getResult();
} else {
FxQuotesRequest request = new FxQuotesRequest(Utils.join(symbols, ","));
quotes = request.getResult();
}
Map<String, FxQuote> result = new HashMap<String, FxQuote>();
for(FxQuote quote : quotes) {
result.put(quote.getSymbol(), quote);
}
return result;
}
|
[
"public",
"static",
"Map",
"<",
"String",
",",
"FxQuote",
">",
"getFx",
"(",
"String",
"[",
"]",
"symbols",
")",
"throws",
"IOException",
"{",
"List",
"<",
"FxQuote",
">",
"quotes",
";",
"if",
"(",
"YahooFinance",
".",
"QUOTES_QUERY1V7_ENABLED",
".",
"equalsIgnoreCase",
"(",
"\"true\"",
")",
")",
"{",
"FxQuotesQuery1V7Request",
"request",
"=",
"new",
"FxQuotesQuery1V7Request",
"(",
"Utils",
".",
"join",
"(",
"symbols",
",",
"\",\"",
")",
")",
";",
"quotes",
"=",
"request",
".",
"getResult",
"(",
")",
";",
"}",
"else",
"{",
"FxQuotesRequest",
"request",
"=",
"new",
"FxQuotesRequest",
"(",
"Utils",
".",
"join",
"(",
"symbols",
",",
"\",\"",
")",
")",
";",
"quotes",
"=",
"request",
".",
"getResult",
"(",
")",
";",
"}",
"Map",
"<",
"String",
",",
"FxQuote",
">",
"result",
"=",
"new",
"HashMap",
"<",
"String",
",",
"FxQuote",
">",
"(",
")",
";",
"for",
"(",
"FxQuote",
"quote",
":",
"quotes",
")",
"{",
"result",
".",
"put",
"(",
"quote",
".",
"getSymbol",
"(",
")",
",",
"quote",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Sends a single request to Yahoo Finance to retrieve a quote
for all the requested FX symbols.
See <code>getFx(String)</code> for more information on the
accepted FX symbols.
@param symbols an array of FX symbols
@return the requested FX symbols mapped to their respective quotes
@throws java.io.IOException when there's a connection problem or the request is incorrect
@see #getFx(java.lang.String)
|
[
"Sends",
"a",
"single",
"request",
"to",
"Yahoo",
"Finance",
"to",
"retrieve",
"a",
"quote",
"for",
"all",
"the",
"requested",
"FX",
"symbols",
".",
"See",
"<code",
">",
"getFx",
"(",
"String",
")",
"<",
"/",
"code",
">",
"for",
"more",
"information",
"on",
"the",
"accepted",
"FX",
"symbols",
"."
] |
train
|
https://github.com/sstrickx/yahoofinance-api/blob/2766ba52fc5cccf9b4da5c06423d68059cf0a6e6/src/main/java/yahoofinance/YahooFinance.java#L361-L375
|
FINRAOS/DataGenerator
|
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java
|
BoundaryDate.numOccurrences
|
public int numOccurrences(int year, int month, int day) {
"""
Given a year, month, and day, find the number of occurrences of that day in the month
@param year the year
@param month the month
@param day the day
@return the number of occurrences of the day in the month
"""
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01");
Calendar cal = Calendar.getInstance();
cal.setTime(date.toDate());
GregorianChronology calendar = GregorianChronology.getInstance();
DateTimeField field = calendar.dayOfMonth();
int days = 0;
int count = 0;
int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));
while (days < num) {
if (cal.get(Calendar.DAY_OF_WEEK) == day) {
count++;
}
date = date.plusDays(1);
cal.setTime(date.toDate());
days++;
}
return count;
}
|
java
|
public int numOccurrences(int year, int month, int day) {
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01");
Calendar cal = Calendar.getInstance();
cal.setTime(date.toDate());
GregorianChronology calendar = GregorianChronology.getInstance();
DateTimeField field = calendar.dayOfMonth();
int days = 0;
int count = 0;
int num = field.getMaximumValue(new LocalDate(year, month, day, calendar));
while (days < num) {
if (cal.get(Calendar.DAY_OF_WEEK) == day) {
count++;
}
date = date.plusDays(1);
cal.setTime(date.toDate());
days++;
}
return count;
}
|
[
"public",
"int",
"numOccurrences",
"(",
"int",
"year",
",",
"int",
"month",
",",
"int",
"day",
")",
"{",
"DateTimeFormatter",
"parser",
"=",
"ISODateTimeFormat",
".",
"date",
"(",
")",
";",
"DateTime",
"date",
"=",
"parser",
".",
"parseDateTime",
"(",
"year",
"+",
"\"-\"",
"+",
"month",
"+",
"\"-\"",
"+",
"\"01\"",
")",
";",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"date",
".",
"toDate",
"(",
")",
")",
";",
"GregorianChronology",
"calendar",
"=",
"GregorianChronology",
".",
"getInstance",
"(",
")",
";",
"DateTimeField",
"field",
"=",
"calendar",
".",
"dayOfMonth",
"(",
")",
";",
"int",
"days",
"=",
"0",
";",
"int",
"count",
"=",
"0",
";",
"int",
"num",
"=",
"field",
".",
"getMaximumValue",
"(",
"new",
"LocalDate",
"(",
"year",
",",
"month",
",",
"day",
",",
"calendar",
")",
")",
";",
"while",
"(",
"days",
"<",
"num",
")",
"{",
"if",
"(",
"cal",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_WEEK",
")",
"==",
"day",
")",
"{",
"count",
"++",
";",
"}",
"date",
"=",
"date",
".",
"plusDays",
"(",
"1",
")",
";",
"cal",
".",
"setTime",
"(",
"date",
".",
"toDate",
"(",
")",
")",
";",
"days",
"++",
";",
"}",
"return",
"count",
";",
"}"
] |
Given a year, month, and day, find the number of occurrences of that day in the month
@param year the year
@param month the month
@param day the day
@return the number of occurrences of the day in the month
|
[
"Given",
"a",
"year",
"month",
"and",
"day",
"find",
"the",
"number",
"of",
"occurrences",
"of",
"that",
"day",
"in",
"the",
"month"
] |
train
|
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L264-L285
|
dropbox/dropbox-sdk-java
|
src/main/java/com/dropbox/core/v1/DbxClientV1.java
|
DbxClientV1.startUploadFileChunked
|
public Uploader startUploadFileChunked(int chunkSize, String targetPath, DbxWriteMode writeMode, long numBytes) {
"""
Similar to {@link #startUploadFile}, except always uses the chunked upload API.
"""
DbxPathV1.checkArg("targetPath", targetPath);
if (writeMode == null) throw new IllegalArgumentException("'writeMode' can't be null");
return new ChunkedUploader(targetPath, writeMode, numBytes, new ChunkedUploadOutputStream(chunkSize));
}
|
java
|
public Uploader startUploadFileChunked(int chunkSize, String targetPath, DbxWriteMode writeMode, long numBytes)
{
DbxPathV1.checkArg("targetPath", targetPath);
if (writeMode == null) throw new IllegalArgumentException("'writeMode' can't be null");
return new ChunkedUploader(targetPath, writeMode, numBytes, new ChunkedUploadOutputStream(chunkSize));
}
|
[
"public",
"Uploader",
"startUploadFileChunked",
"(",
"int",
"chunkSize",
",",
"String",
"targetPath",
",",
"DbxWriteMode",
"writeMode",
",",
"long",
"numBytes",
")",
"{",
"DbxPathV1",
".",
"checkArg",
"(",
"\"targetPath\"",
",",
"targetPath",
")",
";",
"if",
"(",
"writeMode",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"'writeMode' can't be null\"",
")",
";",
"return",
"new",
"ChunkedUploader",
"(",
"targetPath",
",",
"writeMode",
",",
"numBytes",
",",
"new",
"ChunkedUploadOutputStream",
"(",
"chunkSize",
")",
")",
";",
"}"
] |
Similar to {@link #startUploadFile}, except always uses the chunked upload API.
|
[
"Similar",
"to",
"{"
] |
train
|
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L1238-L1244
|
stratosphere/stratosphere
|
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/execution/librarycache/LibraryCacheManager.java
|
LibraryCacheManager.addLibrary
|
public static void addLibrary(final JobID jobID, final Path name, final long size, final DataInput in)
throws IOException {
"""
Reads a library from the given input stream and adds it to the local library cache. The cache name of
the library is determined by the checksum of the received data and cannot be specified manually.
@param jobID
the ID of the job the library data belongs to
@param name
the name of the library at the clients host
@param size
the size of the library to be read from the input stream
@param in
the data input stream
@throws IOException
thrown if the library cache manager could not be instantiated or an error occurred while reading the
library data from the input stream
"""
final LibraryCacheManager lib = get();
lib.addLibraryInternal(jobID, name, size, in);
}
|
java
|
public static void addLibrary(final JobID jobID, final Path name, final long size, final DataInput in)
throws IOException {
final LibraryCacheManager lib = get();
lib.addLibraryInternal(jobID, name, size, in);
}
|
[
"public",
"static",
"void",
"addLibrary",
"(",
"final",
"JobID",
"jobID",
",",
"final",
"Path",
"name",
",",
"final",
"long",
"size",
",",
"final",
"DataInput",
"in",
")",
"throws",
"IOException",
"{",
"final",
"LibraryCacheManager",
"lib",
"=",
"get",
"(",
")",
";",
"lib",
".",
"addLibraryInternal",
"(",
"jobID",
",",
"name",
",",
"size",
",",
"in",
")",
";",
"}"
] |
Reads a library from the given input stream and adds it to the local library cache. The cache name of
the library is determined by the checksum of the received data and cannot be specified manually.
@param jobID
the ID of the job the library data belongs to
@param name
the name of the library at the clients host
@param size
the size of the library to be read from the input stream
@param in
the data input stream
@throws IOException
thrown if the library cache manager could not be instantiated or an error occurred while reading the
library data from the input stream
|
[
"Reads",
"a",
"library",
"from",
"the",
"given",
"input",
"stream",
"and",
"adds",
"it",
"to",
"the",
"local",
"library",
"cache",
".",
"The",
"cache",
"name",
"of",
"the",
"library",
"is",
"determined",
"by",
"the",
"checksum",
"of",
"the",
"received",
"data",
"and",
"cannot",
"be",
"specified",
"manually",
"."
] |
train
|
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/execution/librarycache/LibraryCacheManager.java#L614-L619
|
datumbox/datumbox-framework
|
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/SimpleRandomSampling.java
|
SimpleRandomSampling.weightedSampling
|
public static FlatDataCollection weightedSampling(AssociativeArray weightedTable, int n, boolean withReplacement) {
"""
Samples n ids based on their a Table which contains weights, probabilities
or frequencies.
@param weightedTable
@param n
@param withReplacement
@return
"""
FlatDataList sampledIds = new FlatDataList();
double sumOfFrequencies = Descriptives.sum(weightedTable.toFlatDataCollection());
int populationN = weightedTable.size();
for(int i=0;i<n;++i) {
if(withReplacement==false && populationN<=n) {
//if replacement is not allowed and we already sampled everything that it can stop
break;
}
double randomFrequency = PHPMethods.mt_rand(0.0, sumOfFrequencies);
double cumulativeFrequency=0;
for(Map.Entry<Object, Object> entry : weightedTable.entrySet()) {
Object pointID = entry.getKey();
cumulativeFrequency+= TypeInference.toDouble(entry.getValue());
if(cumulativeFrequency>=randomFrequency) {
if(withReplacement==false && sampledIds.contains(pointID)) {
continue;
}
sampledIds.add(pointID);
break;
}
}
}
return sampledIds.toFlatDataCollection();
}
|
java
|
public static FlatDataCollection weightedSampling(AssociativeArray weightedTable, int n, boolean withReplacement) {
FlatDataList sampledIds = new FlatDataList();
double sumOfFrequencies = Descriptives.sum(weightedTable.toFlatDataCollection());
int populationN = weightedTable.size();
for(int i=0;i<n;++i) {
if(withReplacement==false && populationN<=n) {
//if replacement is not allowed and we already sampled everything that it can stop
break;
}
double randomFrequency = PHPMethods.mt_rand(0.0, sumOfFrequencies);
double cumulativeFrequency=0;
for(Map.Entry<Object, Object> entry : weightedTable.entrySet()) {
Object pointID = entry.getKey();
cumulativeFrequency+= TypeInference.toDouble(entry.getValue());
if(cumulativeFrequency>=randomFrequency) {
if(withReplacement==false && sampledIds.contains(pointID)) {
continue;
}
sampledIds.add(pointID);
break;
}
}
}
return sampledIds.toFlatDataCollection();
}
|
[
"public",
"static",
"FlatDataCollection",
"weightedSampling",
"(",
"AssociativeArray",
"weightedTable",
",",
"int",
"n",
",",
"boolean",
"withReplacement",
")",
"{",
"FlatDataList",
"sampledIds",
"=",
"new",
"FlatDataList",
"(",
")",
";",
"double",
"sumOfFrequencies",
"=",
"Descriptives",
".",
"sum",
"(",
"weightedTable",
".",
"toFlatDataCollection",
"(",
")",
")",
";",
"int",
"populationN",
"=",
"weightedTable",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"if",
"(",
"withReplacement",
"==",
"false",
"&&",
"populationN",
"<=",
"n",
")",
"{",
"//if replacement is not allowed and we already sampled everything that it can stop",
"break",
";",
"}",
"double",
"randomFrequency",
"=",
"PHPMethods",
".",
"mt_rand",
"(",
"0.0",
",",
"sumOfFrequencies",
")",
";",
"double",
"cumulativeFrequency",
"=",
"0",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Object",
",",
"Object",
">",
"entry",
":",
"weightedTable",
".",
"entrySet",
"(",
")",
")",
"{",
"Object",
"pointID",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"cumulativeFrequency",
"+=",
"TypeInference",
".",
"toDouble",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"if",
"(",
"cumulativeFrequency",
">=",
"randomFrequency",
")",
"{",
"if",
"(",
"withReplacement",
"==",
"false",
"&&",
"sampledIds",
".",
"contains",
"(",
"pointID",
")",
")",
"{",
"continue",
";",
"}",
"sampledIds",
".",
"add",
"(",
"pointID",
")",
";",
"break",
";",
"}",
"}",
"}",
"return",
"sampledIds",
".",
"toFlatDataCollection",
"(",
")",
";",
"}"
] |
Samples n ids based on their a Table which contains weights, probabilities
or frequencies.
@param weightedTable
@param n
@param withReplacement
@return
|
[
"Samples",
"n",
"ids",
"based",
"on",
"their",
"a",
"Table",
"which",
"contains",
"weights",
"probabilities",
"or",
"frequencies",
"."
] |
train
|
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/sampling/SimpleRandomSampling.java#L44-L74
|
hazelcast/hazelcast
|
hazelcast/src/main/java/com/hazelcast/config/Config.java
|
Config.getMapConfigOrNull
|
public MapConfig getMapConfigOrNull(String name) {
"""
Returns the map config with the given name or {@code null} if there is none.
The name is matched by pattern to the configuration and by stripping the
partition ID qualifier from the given {@code name}.
@param name name of the map config
@return the map configuration or {@code null} if none was found
@throws ConfigurationException if ambiguous configurations are found
@see StringPartitioningStrategy#getBaseName(java.lang.String)
@see #setConfigPatternMatcher(ConfigPatternMatcher)
@see #getConfigPatternMatcher()
"""
name = getBaseName(name);
return lookupByPattern(configPatternMatcher, mapConfigs, name);
}
|
java
|
public MapConfig getMapConfigOrNull(String name) {
name = getBaseName(name);
return lookupByPattern(configPatternMatcher, mapConfigs, name);
}
|
[
"public",
"MapConfig",
"getMapConfigOrNull",
"(",
"String",
"name",
")",
"{",
"name",
"=",
"getBaseName",
"(",
"name",
")",
";",
"return",
"lookupByPattern",
"(",
"configPatternMatcher",
",",
"mapConfigs",
",",
"name",
")",
";",
"}"
] |
Returns the map config with the given name or {@code null} if there is none.
The name is matched by pattern to the configuration and by stripping the
partition ID qualifier from the given {@code name}.
@param name name of the map config
@return the map configuration or {@code null} if none was found
@throws ConfigurationException if ambiguous configurations are found
@see StringPartitioningStrategy#getBaseName(java.lang.String)
@see #setConfigPatternMatcher(ConfigPatternMatcher)
@see #getConfigPatternMatcher()
|
[
"Returns",
"the",
"map",
"config",
"with",
"the",
"given",
"name",
"or",
"{",
"@code",
"null",
"}",
"if",
"there",
"is",
"none",
".",
"The",
"name",
"is",
"matched",
"by",
"pattern",
"to",
"the",
"configuration",
"and",
"by",
"stripping",
"the",
"partition",
"ID",
"qualifier",
"from",
"the",
"given",
"{",
"@code",
"name",
"}",
"."
] |
train
|
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L427-L430
|
ckpoint/CheckPoint
|
src/main/java/hsim/checkpoint/core/msg/MsgChecker.java
|
MsgChecker.checkPoint
|
public void checkPoint(ValidationData param, ValidationRule rule, Object bodyObj, Object standardValue) {
"""
Check point.
@param param the param
@param rule the rule
@param bodyObj the body obj
@param standardValue the standard value
"""
//check
Object value = param.getValue(bodyObj);
BaseValidationCheck checker = this.validationRuleStore.getValidationChecker(rule);
if ((value != null && standardValue != null) || rule.getAssistType().isNullable()) {
boolean valid = checker.check(value, standardValue);
if (!valid) {
this.callExcpetion(param, rule, value, standardValue);
}
}
//replace value
Object replaceValue = checker.replace(value, standardValue, param);
if (replaceValue != null && replaceValue != value) {
param.replaceValue(bodyObj, replaceValue);
}
}
|
java
|
public void checkPoint(ValidationData param, ValidationRule rule, Object bodyObj, Object standardValue) {
//check
Object value = param.getValue(bodyObj);
BaseValidationCheck checker = this.validationRuleStore.getValidationChecker(rule);
if ((value != null && standardValue != null) || rule.getAssistType().isNullable()) {
boolean valid = checker.check(value, standardValue);
if (!valid) {
this.callExcpetion(param, rule, value, standardValue);
}
}
//replace value
Object replaceValue = checker.replace(value, standardValue, param);
if (replaceValue != null && replaceValue != value) {
param.replaceValue(bodyObj, replaceValue);
}
}
|
[
"public",
"void",
"checkPoint",
"(",
"ValidationData",
"param",
",",
"ValidationRule",
"rule",
",",
"Object",
"bodyObj",
",",
"Object",
"standardValue",
")",
"{",
"//check",
"Object",
"value",
"=",
"param",
".",
"getValue",
"(",
"bodyObj",
")",
";",
"BaseValidationCheck",
"checker",
"=",
"this",
".",
"validationRuleStore",
".",
"getValidationChecker",
"(",
"rule",
")",
";",
"if",
"(",
"(",
"value",
"!=",
"null",
"&&",
"standardValue",
"!=",
"null",
")",
"||",
"rule",
".",
"getAssistType",
"(",
")",
".",
"isNullable",
"(",
")",
")",
"{",
"boolean",
"valid",
"=",
"checker",
".",
"check",
"(",
"value",
",",
"standardValue",
")",
";",
"if",
"(",
"!",
"valid",
")",
"{",
"this",
".",
"callExcpetion",
"(",
"param",
",",
"rule",
",",
"value",
",",
"standardValue",
")",
";",
"}",
"}",
"//replace value",
"Object",
"replaceValue",
"=",
"checker",
".",
"replace",
"(",
"value",
",",
"standardValue",
",",
"param",
")",
";",
"if",
"(",
"replaceValue",
"!=",
"null",
"&&",
"replaceValue",
"!=",
"value",
")",
"{",
"param",
".",
"replaceValue",
"(",
"bodyObj",
",",
"replaceValue",
")",
";",
"}",
"}"
] |
Check point.
@param param the param
@param rule the rule
@param bodyObj the body obj
@param standardValue the standard value
|
[
"Check",
"point",
"."
] |
train
|
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/core/msg/MsgChecker.java#L59-L76
|
Azure/azure-sdk-for-java
|
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
|
AppServiceEnvironmentsInner.createOrUpdateWorkerPool
|
public WorkerPoolResourceInner createOrUpdateWorkerPool(String resourceGroupName, String name, String workerPoolName, WorkerPoolResourceInner workerPoolEnvelope) {
"""
Create or update a worker pool.
Create or update a worker pool.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@param workerPoolName Name of the worker pool.
@param workerPoolEnvelope Properties of the worker pool.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the WorkerPoolResourceInner object if successful.
"""
return createOrUpdateWorkerPoolWithServiceResponseAsync(resourceGroupName, name, workerPoolName, workerPoolEnvelope).toBlocking().last().body();
}
|
java
|
public WorkerPoolResourceInner createOrUpdateWorkerPool(String resourceGroupName, String name, String workerPoolName, WorkerPoolResourceInner workerPoolEnvelope) {
return createOrUpdateWorkerPoolWithServiceResponseAsync(resourceGroupName, name, workerPoolName, workerPoolEnvelope).toBlocking().last().body();
}
|
[
"public",
"WorkerPoolResourceInner",
"createOrUpdateWorkerPool",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"String",
"workerPoolName",
",",
"WorkerPoolResourceInner",
"workerPoolEnvelope",
")",
"{",
"return",
"createOrUpdateWorkerPoolWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"workerPoolName",
",",
"workerPoolEnvelope",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Create or update a worker pool.
Create or update a worker pool.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@param workerPoolName Name of the worker pool.
@param workerPoolEnvelope Properties of the worker pool.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the WorkerPoolResourceInner object if successful.
|
[
"Create",
"or",
"update",
"a",
"worker",
"pool",
".",
"Create",
"or",
"update",
"a",
"worker",
"pool",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L5190-L5192
|
bullhorn/sdk-rest
|
src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java
|
StandardBullhornData.handleGetMetaData
|
protected <T extends BullhornEntity> MetaData<T> handleGetMetaData(Class<T> type, MetaParameter metaParameter, Set<String> fieldSet, Integer privateLabelId) {
"""
Makes the "meta" api call
<p>
HttpMethod: GET
@param type the BullhornEntity type
@param metaParameter additional meta parameters
@param fieldSet fields to return meta information about. Pass in null for all fields.
@return the MetaData
"""
Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForMeta(BullhornEntityInfo.getTypesRestEntityName(type),
metaParameter, fieldSet, privateLabelId);
return handleGetMetaData(uriVariables, privateLabelId);
}
|
java
|
protected <T extends BullhornEntity> MetaData<T> handleGetMetaData(Class<T> type, MetaParameter metaParameter, Set<String> fieldSet, Integer privateLabelId) {
Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForMeta(BullhornEntityInfo.getTypesRestEntityName(type),
metaParameter, fieldSet, privateLabelId);
return handleGetMetaData(uriVariables, privateLabelId);
}
|
[
"protected",
"<",
"T",
"extends",
"BullhornEntity",
">",
"MetaData",
"<",
"T",
">",
"handleGetMetaData",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"MetaParameter",
"metaParameter",
",",
"Set",
"<",
"String",
">",
"fieldSet",
",",
"Integer",
"privateLabelId",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"uriVariables",
"=",
"restUriVariablesFactory",
".",
"getUriVariablesForMeta",
"(",
"BullhornEntityInfo",
".",
"getTypesRestEntityName",
"(",
"type",
")",
",",
"metaParameter",
",",
"fieldSet",
",",
"privateLabelId",
")",
";",
"return",
"handleGetMetaData",
"(",
"uriVariables",
",",
"privateLabelId",
")",
";",
"}"
] |
Makes the "meta" api call
<p>
HttpMethod: GET
@param type the BullhornEntity type
@param metaParameter additional meta parameters
@param fieldSet fields to return meta information about. Pass in null for all fields.
@return the MetaData
|
[
"Makes",
"the",
"meta",
"api",
"call",
"<p",
">",
"HttpMethod",
":",
"GET"
] |
train
|
https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java#L1241-L1246
|
ModeShape/modeshape
|
web/modeshape-web-explorer/src/main/java/org/modeshape/web/client/contents/Contents.java
|
Contents.getAndDisplayNode
|
public void getAndDisplayNode(final String path, final boolean changeHistory) {
"""
Reads node with given path and selected repository and workspace.
@param path the path to the node.
@param changeHistory if true then path will be reflected in browser
history.
"""
showLoadIcon();
console.jcrService().node(repository(), workspace(), path, new AsyncCallback<JcrNode>() {
@Override
public void onFailure(Throwable caught) {
hideLoadIcon();
SC.say(caught.getMessage());
}
@Override
public void onSuccess(JcrNode node) {
displayNode(node);
console.changeWorkspaceInURL(workspace(), changeHistory);
console.changePathInURL(path, changeHistory);
hideLoadIcon();
}
});
}
|
java
|
public void getAndDisplayNode(final String path, final boolean changeHistory) {
showLoadIcon();
console.jcrService().node(repository(), workspace(), path, new AsyncCallback<JcrNode>() {
@Override
public void onFailure(Throwable caught) {
hideLoadIcon();
SC.say(caught.getMessage());
}
@Override
public void onSuccess(JcrNode node) {
displayNode(node);
console.changeWorkspaceInURL(workspace(), changeHistory);
console.changePathInURL(path, changeHistory);
hideLoadIcon();
}
});
}
|
[
"public",
"void",
"getAndDisplayNode",
"(",
"final",
"String",
"path",
",",
"final",
"boolean",
"changeHistory",
")",
"{",
"showLoadIcon",
"(",
")",
";",
"console",
".",
"jcrService",
"(",
")",
".",
"node",
"(",
"repository",
"(",
")",
",",
"workspace",
"(",
")",
",",
"path",
",",
"new",
"AsyncCallback",
"<",
"JcrNode",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onFailure",
"(",
"Throwable",
"caught",
")",
"{",
"hideLoadIcon",
"(",
")",
";",
"SC",
".",
"say",
"(",
"caught",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onSuccess",
"(",
"JcrNode",
"node",
")",
"{",
"displayNode",
"(",
"node",
")",
";",
"console",
".",
"changeWorkspaceInURL",
"(",
"workspace",
"(",
")",
",",
"changeHistory",
")",
";",
"console",
".",
"changePathInURL",
"(",
"path",
",",
"changeHistory",
")",
";",
"hideLoadIcon",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Reads node with given path and selected repository and workspace.
@param path the path to the node.
@param changeHistory if true then path will be reflected in browser
history.
|
[
"Reads",
"node",
"with",
"given",
"path",
"and",
"selected",
"repository",
"and",
"workspace",
"."
] |
train
|
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/web/modeshape-web-explorer/src/main/java/org/modeshape/web/client/contents/Contents.java#L219-L236
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
|
ApiOvhHostingprivateDatabase.serviceName_PUT
|
public void serviceName_PUT(String serviceName, net.minidev.ovh.api.hosting.privatedatabase.OvhService body) throws IOException {
"""
Alter this object properties
REST: PUT /hosting/privateDatabase/{serviceName}
@param body [required] New object properties
@param serviceName [required] The internal name of your private database
"""
String qPath = "/hosting/privateDatabase/{serviceName}";
StringBuilder sb = path(qPath, serviceName);
exec(qPath, "PUT", sb.toString(), body);
}
|
java
|
public void serviceName_PUT(String serviceName, net.minidev.ovh.api.hosting.privatedatabase.OvhService body) throws IOException {
String qPath = "/hosting/privateDatabase/{serviceName}";
StringBuilder sb = path(qPath, serviceName);
exec(qPath, "PUT", sb.toString(), body);
}
|
[
"public",
"void",
"serviceName_PUT",
"(",
"String",
"serviceName",
",",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"hosting",
".",
"privatedatabase",
".",
"OvhService",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/hosting/privateDatabase/{serviceName}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"exec",
"(",
"qPath",
",",
"\"PUT\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"body",
")",
";",
"}"
] |
Alter this object properties
REST: PUT /hosting/privateDatabase/{serviceName}
@param body [required] New object properties
@param serviceName [required] The internal name of your private database
|
[
"Alter",
"this",
"object",
"properties"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L771-L775
|
cdapio/tigon
|
tigon-sql/src/main/java/co/cask/tigon/sql/internal/MetricsRecorder.java
|
MetricsRecorder.recordMetrics
|
public void recordMetrics(String processName, JsonObject metricsData) {
"""
This methods logs the received metrics into the underlying {@link Metrics} object.
This method should be invoked every time metrics are received from a SQL Compiler process.
@param processName Name of the process which sent these metrics
@param metricsData The metrics sent by the process in a JSON format
"""
for (Map.Entry<String, JsonElement> entry : metricsData.entrySet()) {
metrics.count(processName + "." + entry.getKey(),
Math.round(entry.getValue().getAsFloat()));
}
}
|
java
|
public void recordMetrics(String processName, JsonObject metricsData) {
for (Map.Entry<String, JsonElement> entry : metricsData.entrySet()) {
metrics.count(processName + "." + entry.getKey(),
Math.round(entry.getValue().getAsFloat()));
}
}
|
[
"public",
"void",
"recordMetrics",
"(",
"String",
"processName",
",",
"JsonObject",
"metricsData",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"JsonElement",
">",
"entry",
":",
"metricsData",
".",
"entrySet",
"(",
")",
")",
"{",
"metrics",
".",
"count",
"(",
"processName",
"+",
"\".\"",
"+",
"entry",
".",
"getKey",
"(",
")",
",",
"Math",
".",
"round",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"getAsFloat",
"(",
")",
")",
")",
";",
"}",
"}"
] |
This methods logs the received metrics into the underlying {@link Metrics} object.
This method should be invoked every time metrics are received from a SQL Compiler process.
@param processName Name of the process which sent these metrics
@param metricsData The metrics sent by the process in a JSON format
|
[
"This",
"methods",
"logs",
"the",
"received",
"metrics",
"into",
"the",
"underlying",
"{",
"@link",
"Metrics",
"}",
"object",
".",
"This",
"method",
"should",
"be",
"invoked",
"every",
"time",
"metrics",
"are",
"received",
"from",
"a",
"SQL",
"Compiler",
"process",
"."
] |
train
|
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/internal/MetricsRecorder.java#L49-L54
|
ical4j/ical4j
|
src/main/java/net/fortuna/ical4j/util/Dates.java
|
Dates.getAbsYearDay
|
public static int getAbsYearDay(final java.util.Date date, final int yearDay) {
"""
Returns the absolute year day for the year specified by the
supplied date. Note that a value of zero (0) is invalid for the
yearDay parameter and an <code>IllegalArgumentException</code>
will be thrown.
@param date a date instance representing a day of the year
@param yearDay a day of year offset
@return the absolute day of month for the specified offset
"""
if (yearDay == 0 || yearDay < -MAX_DAYS_PER_YEAR || yearDay > MAX_DAYS_PER_YEAR) {
throw new IllegalArgumentException(MessageFormat.format(INVALID_YEAR_DAY_MESSAGE,
yearDay));
}
if (yearDay > 0) {
return yearDay;
}
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int year = cal.get(Calendar.YEAR);
// construct a list of possible year days..
final List<Integer> days = new ArrayList<Integer>();
cal.set(Calendar.DAY_OF_YEAR, 1);
while (cal.get(Calendar.YEAR) == year) {
days.add(cal.get(Calendar.DAY_OF_YEAR));
cal.add(Calendar.DAY_OF_YEAR, 1);
}
return days.get(days.size() + yearDay);
}
|
java
|
public static int getAbsYearDay(final java.util.Date date, final int yearDay) {
if (yearDay == 0 || yearDay < -MAX_DAYS_PER_YEAR || yearDay > MAX_DAYS_PER_YEAR) {
throw new IllegalArgumentException(MessageFormat.format(INVALID_YEAR_DAY_MESSAGE,
yearDay));
}
if (yearDay > 0) {
return yearDay;
}
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
final int year = cal.get(Calendar.YEAR);
// construct a list of possible year days..
final List<Integer> days = new ArrayList<Integer>();
cal.set(Calendar.DAY_OF_YEAR, 1);
while (cal.get(Calendar.YEAR) == year) {
days.add(cal.get(Calendar.DAY_OF_YEAR));
cal.add(Calendar.DAY_OF_YEAR, 1);
}
return days.get(days.size() + yearDay);
}
|
[
"public",
"static",
"int",
"getAbsYearDay",
"(",
"final",
"java",
".",
"util",
".",
"Date",
"date",
",",
"final",
"int",
"yearDay",
")",
"{",
"if",
"(",
"yearDay",
"==",
"0",
"||",
"yearDay",
"<",
"-",
"MAX_DAYS_PER_YEAR",
"||",
"yearDay",
">",
"MAX_DAYS_PER_YEAR",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"MessageFormat",
".",
"format",
"(",
"INVALID_YEAR_DAY_MESSAGE",
",",
"yearDay",
")",
")",
";",
"}",
"if",
"(",
"yearDay",
">",
"0",
")",
"{",
"return",
"yearDay",
";",
"}",
"final",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"date",
")",
";",
"final",
"int",
"year",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
";",
"// construct a list of possible year days..",
"final",
"List",
"<",
"Integer",
">",
"days",
"=",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
")",
";",
"cal",
".",
"set",
"(",
"Calendar",
".",
"DAY_OF_YEAR",
",",
"1",
")",
";",
"while",
"(",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
"==",
"year",
")",
"{",
"days",
".",
"add",
"(",
"cal",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_YEAR",
")",
")",
";",
"cal",
".",
"add",
"(",
"Calendar",
".",
"DAY_OF_YEAR",
",",
"1",
")",
";",
"}",
"return",
"days",
".",
"get",
"(",
"days",
".",
"size",
"(",
")",
"+",
"yearDay",
")",
";",
"}"
] |
Returns the absolute year day for the year specified by the
supplied date. Note that a value of zero (0) is invalid for the
yearDay parameter and an <code>IllegalArgumentException</code>
will be thrown.
@param date a date instance representing a day of the year
@param yearDay a day of year offset
@return the absolute day of month for the specified offset
|
[
"Returns",
"the",
"absolute",
"year",
"day",
"for",
"the",
"year",
"specified",
"by",
"the",
"supplied",
"date",
".",
"Note",
"that",
"a",
"value",
"of",
"zero",
"(",
"0",
")",
"is",
"invalid",
"for",
"the",
"yearDay",
"parameter",
"and",
"an",
"<code",
">",
"IllegalArgumentException<",
"/",
"code",
">",
"will",
"be",
"thrown",
"."
] |
train
|
https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/util/Dates.java#L162-L181
|
facebookarchive/hadoop-20
|
src/core/org/apache/hadoop/metrics/file/FileContext.java
|
FileContext.startMonitoring
|
public void startMonitoring()
throws IOException {
"""
Starts or restarts monitoring, by opening in append-mode, the
file specified by the <code>fileName</code> attribute,
if specified. Otherwise the data will be written to standard
output.
"""
if (file == null) {
writer = new PrintWriter(new BufferedOutputStream(System.out));
} else {
writer = new PrintWriter(new FileWriter(file, true));
}
super.startMonitoring();
}
|
java
|
public void startMonitoring()
throws IOException
{
if (file == null) {
writer = new PrintWriter(new BufferedOutputStream(System.out));
} else {
writer = new PrintWriter(new FileWriter(file, true));
}
super.startMonitoring();
}
|
[
"public",
"void",
"startMonitoring",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"writer",
"=",
"new",
"PrintWriter",
"(",
"new",
"BufferedOutputStream",
"(",
"System",
".",
"out",
")",
")",
";",
"}",
"else",
"{",
"writer",
"=",
"new",
"PrintWriter",
"(",
"new",
"FileWriter",
"(",
"file",
",",
"true",
")",
")",
";",
"}",
"super",
".",
"startMonitoring",
"(",
")",
";",
"}"
] |
Starts or restarts monitoring, by opening in append-mode, the
file specified by the <code>fileName</code> attribute,
if specified. Otherwise the data will be written to standard
output.
|
[
"Starts",
"or",
"restarts",
"monitoring",
"by",
"opening",
"in",
"append",
"-",
"mode",
"the",
"file",
"specified",
"by",
"the",
"<code",
">",
"fileName<",
"/",
"code",
">",
"attribute",
"if",
"specified",
".",
"Otherwise",
"the",
"data",
"will",
"be",
"written",
"to",
"standard",
"output",
"."
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/metrics/file/FileContext.java#L108-L117
|
keyboardsurfer/Crouton
|
library/src/main/java/de/keyboardsurfer/android/widget/crouton/Crouton.java
|
Crouton.makeText
|
public static Crouton makeText(Activity activity, CharSequence text, Style style) {
"""
Creates a {@link Crouton} with provided text and style for a given
activity.
@param activity
The {@link Activity} that the {@link Crouton} should be attached
to.
@param text
The text you want to display.
@param style
The style that this {@link Crouton} should be created with.
@return The created {@link Crouton}.
"""
return new Crouton(activity, text, style);
}
|
java
|
public static Crouton makeText(Activity activity, CharSequence text, Style style) {
return new Crouton(activity, text, style);
}
|
[
"public",
"static",
"Crouton",
"makeText",
"(",
"Activity",
"activity",
",",
"CharSequence",
"text",
",",
"Style",
"style",
")",
"{",
"return",
"new",
"Crouton",
"(",
"activity",
",",
"text",
",",
"style",
")",
";",
"}"
] |
Creates a {@link Crouton} with provided text and style for a given
activity.
@param activity
The {@link Activity} that the {@link Crouton} should be attached
to.
@param text
The text you want to display.
@param style
The style that this {@link Crouton} should be created with.
@return The created {@link Crouton}.
|
[
"Creates",
"a",
"{",
"@link",
"Crouton",
"}",
"with",
"provided",
"text",
"and",
"style",
"for",
"a",
"given",
"activity",
"."
] |
train
|
https://github.com/keyboardsurfer/Crouton/blob/7806b15e4d52793e1f5aeaa4a55b1e220289e619/library/src/main/java/de/keyboardsurfer/android/widget/crouton/Crouton.java#L194-L196
|
Netflix/denominator
|
core/src/main/java/denominator/CredentialsConfiguration.java
|
CredentialsConfiguration.checkValidForProvider
|
public static Credentials checkValidForProvider(Credentials creds,
denominator.Provider provider) {
"""
checks that the supplied input is valid, or throws an {@code IllegalArgumentException} if not.
Users of this are guaranteed that the {@code input} matches the count of parameters of a
credential type listed in {@link denominator.Provider#credentialTypeToParameterNames()}.
<br> <br> <b>Coercion to {@code AnonymousCredentials}</b><br>
if {@link denominator.Provider#credentialTypeToParameterNames()} is empty, then no credentials
are required. When this is true, the following cases will return {@code AnonymousCredentials}.
<ul> <li>when {@code input} is null</li> <li>when {@code input} is an instance of {@code
AnonymousCredentials}</li> <li>when {@code input} is an empty instance of {@code Map} or {@code
List}</li> </ul>
<br> <br> <b>Validation Rules</b><br>
See {@link Credentials} for Validation Rules
@param creds nullable credentials to test
@param provider context which helps create a useful error message on failure.
@return correct Credentials value which can be {@link AnonymousCredentials} if {@code input}
was null and credentials are not needed.
@throws IllegalArgumentException if provider requires a different amount of credential parts
than {@code input}
"""
checkNotNull(provider, "provider cannot be null");
if (isAnonymous(creds) && provider.credentialTypeToParameterNames().isEmpty()) {
return AnonymousCredentials.INSTANCE;
} else if (creds instanceof Map) {
// check Map first as clojure Map implements List Map.Entry
if (credentialConfigurationHasKeys(provider, Map.class.cast(creds).keySet())) {
return creds;
}
} else if (creds instanceof List) {
if (credentialConfigurationHasPartCount(provider, List.class.cast(creds).size())) {
return creds;
}
}
throw new IllegalArgumentException(exceptionMessage(creds, provider));
}
|
java
|
public static Credentials checkValidForProvider(Credentials creds,
denominator.Provider provider) {
checkNotNull(provider, "provider cannot be null");
if (isAnonymous(creds) && provider.credentialTypeToParameterNames().isEmpty()) {
return AnonymousCredentials.INSTANCE;
} else if (creds instanceof Map) {
// check Map first as clojure Map implements List Map.Entry
if (credentialConfigurationHasKeys(provider, Map.class.cast(creds).keySet())) {
return creds;
}
} else if (creds instanceof List) {
if (credentialConfigurationHasPartCount(provider, List.class.cast(creds).size())) {
return creds;
}
}
throw new IllegalArgumentException(exceptionMessage(creds, provider));
}
|
[
"public",
"static",
"Credentials",
"checkValidForProvider",
"(",
"Credentials",
"creds",
",",
"denominator",
".",
"Provider",
"provider",
")",
"{",
"checkNotNull",
"(",
"provider",
",",
"\"provider cannot be null\"",
")",
";",
"if",
"(",
"isAnonymous",
"(",
"creds",
")",
"&&",
"provider",
".",
"credentialTypeToParameterNames",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"AnonymousCredentials",
".",
"INSTANCE",
";",
"}",
"else",
"if",
"(",
"creds",
"instanceof",
"Map",
")",
"{",
"// check Map first as clojure Map implements List Map.Entry",
"if",
"(",
"credentialConfigurationHasKeys",
"(",
"provider",
",",
"Map",
".",
"class",
".",
"cast",
"(",
"creds",
")",
".",
"keySet",
"(",
")",
")",
")",
"{",
"return",
"creds",
";",
"}",
"}",
"else",
"if",
"(",
"creds",
"instanceof",
"List",
")",
"{",
"if",
"(",
"credentialConfigurationHasPartCount",
"(",
"provider",
",",
"List",
".",
"class",
".",
"cast",
"(",
"creds",
")",
".",
"size",
"(",
")",
")",
")",
"{",
"return",
"creds",
";",
"}",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"exceptionMessage",
"(",
"creds",
",",
"provider",
")",
")",
";",
"}"
] |
checks that the supplied input is valid, or throws an {@code IllegalArgumentException} if not.
Users of this are guaranteed that the {@code input} matches the count of parameters of a
credential type listed in {@link denominator.Provider#credentialTypeToParameterNames()}.
<br> <br> <b>Coercion to {@code AnonymousCredentials}</b><br>
if {@link denominator.Provider#credentialTypeToParameterNames()} is empty, then no credentials
are required. When this is true, the following cases will return {@code AnonymousCredentials}.
<ul> <li>when {@code input} is null</li> <li>when {@code input} is an instance of {@code
AnonymousCredentials}</li> <li>when {@code input} is an empty instance of {@code Map} or {@code
List}</li> </ul>
<br> <br> <b>Validation Rules</b><br>
See {@link Credentials} for Validation Rules
@param creds nullable credentials to test
@param provider context which helps create a useful error message on failure.
@return correct Credentials value which can be {@link AnonymousCredentials} if {@code input}
was null and credentials are not needed.
@throws IllegalArgumentException if provider requires a different amount of credential parts
than {@code input}
|
[
"checks",
"that",
"the",
"supplied",
"input",
"is",
"valid",
"or",
"throws",
"an",
"{",
"@code",
"IllegalArgumentException",
"}",
"if",
"not",
".",
"Users",
"of",
"this",
"are",
"guaranteed",
"that",
"the",
"{",
"@code",
"input",
"}",
"matches",
"the",
"count",
"of",
"parameters",
"of",
"a",
"credential",
"type",
"listed",
"in",
"{",
"@link",
"denominator",
".",
"Provider#credentialTypeToParameterNames",
"()",
"}",
"."
] |
train
|
https://github.com/Netflix/denominator/blob/c565e3b8c6043051252e0947029511f9ac5d306f/core/src/main/java/denominator/CredentialsConfiguration.java#L107-L123
|
PistoiaHELM/HELM2NotationToolkit
|
src/main/java/org/helm/notation2/tools/HELM2NotationUtils.java
|
HELM2NotationUtils.getFormatedSirnaSequences
|
public static String[] getFormatedSirnaSequences(HELM2Notation helm2notation) throws NotationException, RNAUtilsException, HELM2HandledException, org.helm.notation2.exception.NotationException,
ChemistryException {
"""
generate formated siRNA sequence with default padding char " " and
base-pair char "|"
@param helm2notation HELM2Notation
@return string array of formated nucloeotide sequence
@throws NotationException if notation is not valid
@throws RNAUtilsException if the polymer is not a RNA/DNA
@throws HELM2HandledException if it contains HELM2 specific features, so that it can not be casted to HELM1 Format
@throws org.helm.notation2.exception.NotationException if notation is not valid
@throws ChemistryException if the Chemistry Engine can not be initialized
"""
return getFormatedSirnaSequences(helm2notation, DEFAULT_PADDING_CHAR, DEFAULT_BASE_PAIR_CHAR);
}
|
java
|
public static String[] getFormatedSirnaSequences(HELM2Notation helm2notation) throws NotationException, RNAUtilsException, HELM2HandledException, org.helm.notation2.exception.NotationException,
ChemistryException {
return getFormatedSirnaSequences(helm2notation, DEFAULT_PADDING_CHAR, DEFAULT_BASE_PAIR_CHAR);
}
|
[
"public",
"static",
"String",
"[",
"]",
"getFormatedSirnaSequences",
"(",
"HELM2Notation",
"helm2notation",
")",
"throws",
"NotationException",
",",
"RNAUtilsException",
",",
"HELM2HandledException",
",",
"org",
".",
"helm",
".",
"notation2",
".",
"exception",
".",
"NotationException",
",",
"ChemistryException",
"{",
"return",
"getFormatedSirnaSequences",
"(",
"helm2notation",
",",
"DEFAULT_PADDING_CHAR",
",",
"DEFAULT_BASE_PAIR_CHAR",
")",
";",
"}"
] |
generate formated siRNA sequence with default padding char " " and
base-pair char "|"
@param helm2notation HELM2Notation
@return string array of formated nucloeotide sequence
@throws NotationException if notation is not valid
@throws RNAUtilsException if the polymer is not a RNA/DNA
@throws HELM2HandledException if it contains HELM2 specific features, so that it can not be casted to HELM1 Format
@throws org.helm.notation2.exception.NotationException if notation is not valid
@throws ChemistryException if the Chemistry Engine can not be initialized
|
[
"generate",
"formated",
"siRNA",
"sequence",
"with",
"default",
"padding",
"char",
"and",
"base",
"-",
"pair",
"char",
"|"
] |
train
|
https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/HELM2NotationUtils.java#L390-L393
|
PeterisP/LVTagger
|
src/main/java/edu/stanford/nlp/stats/Counters.java
|
Counters.removeKeys
|
public static <E> void removeKeys(Counter<E> counter, Collection<E> removeKeysCollection) {
"""
Removes all entries with keys in the given collection
@param <E>
@param counter
@param removeKeysCollection
"""
for (E key : removeKeysCollection)
counter.remove(key);
}
|
java
|
public static <E> void removeKeys(Counter<E> counter, Collection<E> removeKeysCollection) {
for (E key : removeKeysCollection)
counter.remove(key);
}
|
[
"public",
"static",
"<",
"E",
">",
"void",
"removeKeys",
"(",
"Counter",
"<",
"E",
">",
"counter",
",",
"Collection",
"<",
"E",
">",
"removeKeysCollection",
")",
"{",
"for",
"(",
"E",
"key",
":",
"removeKeysCollection",
")",
"counter",
".",
"remove",
"(",
"key",
")",
";",
"}"
] |
Removes all entries with keys in the given collection
@param <E>
@param counter
@param removeKeysCollection
|
[
"Removes",
"all",
"entries",
"with",
"keys",
"in",
"the",
"given",
"collection"
] |
train
|
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L680-L684
|
Jasig/uPortal
|
uPortal-portlets/src/main/java/org/apereo/portal/portlets/jsp/JspInvokerPortletController.java
|
JspInvokerPortletController.addSecurityRoleChecksToModel
|
private void addSecurityRoleChecksToModel(PortletRequest req, Map<String, Object> model) {
"""
Run through the list of configured security roles and add an "is"+Rolename to the model. The
security roles must also be defined with a <code><security-role-ref></code> element in
the portlet.xml.
@param req Portlet request
@param model Model object to add security indicators to
"""
PortletPreferences prefs = req.getPreferences();
String[] securityRoles = prefs.getValues(PREF_SECURITY_ROLE_NAMES, new String[] {});
for (int i = 0; i < securityRoles.length; i++) {
model.put(
"is" + securityRoles[i].replace(" ", "_"), req.isUserInRole(securityRoles[i]));
}
}
|
java
|
private void addSecurityRoleChecksToModel(PortletRequest req, Map<String, Object> model) {
PortletPreferences prefs = req.getPreferences();
String[] securityRoles = prefs.getValues(PREF_SECURITY_ROLE_NAMES, new String[] {});
for (int i = 0; i < securityRoles.length; i++) {
model.put(
"is" + securityRoles[i].replace(" ", "_"), req.isUserInRole(securityRoles[i]));
}
}
|
[
"private",
"void",
"addSecurityRoleChecksToModel",
"(",
"PortletRequest",
"req",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"model",
")",
"{",
"PortletPreferences",
"prefs",
"=",
"req",
".",
"getPreferences",
"(",
")",
";",
"String",
"[",
"]",
"securityRoles",
"=",
"prefs",
".",
"getValues",
"(",
"PREF_SECURITY_ROLE_NAMES",
",",
"new",
"String",
"[",
"]",
"{",
"}",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"securityRoles",
".",
"length",
";",
"i",
"++",
")",
"{",
"model",
".",
"put",
"(",
"\"is\"",
"+",
"securityRoles",
"[",
"i",
"]",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
",",
"req",
".",
"isUserInRole",
"(",
"securityRoles",
"[",
"i",
"]",
")",
")",
";",
"}",
"}"
] |
Run through the list of configured security roles and add an "is"+Rolename to the model. The
security roles must also be defined with a <code><security-role-ref></code> element in
the portlet.xml.
@param req Portlet request
@param model Model object to add security indicators to
|
[
"Run",
"through",
"the",
"list",
"of",
"configured",
"security",
"roles",
"and",
"add",
"an",
"is",
"+",
"Rolename",
"to",
"the",
"model",
".",
"The",
"security",
"roles",
"must",
"also",
"be",
"defined",
"with",
"a",
"<code",
">",
"<",
";",
"security",
"-",
"role",
"-",
"ref>",
";",
"<",
"/",
"code",
">",
"element",
"in",
"the",
"portlet",
".",
"xml",
"."
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/jsp/JspInvokerPortletController.java#L157-L164
|
carewebframework/carewebframework-core
|
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandUtil.java
|
CommandUtil.dissociateCommand
|
public static void dissociateCommand(String commandName, BaseUIComponent component) {
"""
Dissociate a UI component with a command.
@param commandName Name of the command.
@param component Component to be associated.
"""
Command command = getCommand(commandName, false);
if (command != null) {
command.unbind(component);
}
}
|
java
|
public static void dissociateCommand(String commandName, BaseUIComponent component) {
Command command = getCommand(commandName, false);
if (command != null) {
command.unbind(component);
}
}
|
[
"public",
"static",
"void",
"dissociateCommand",
"(",
"String",
"commandName",
",",
"BaseUIComponent",
"component",
")",
"{",
"Command",
"command",
"=",
"getCommand",
"(",
"commandName",
",",
"false",
")",
";",
"if",
"(",
"command",
"!=",
"null",
")",
"{",
"command",
".",
"unbind",
"(",
"component",
")",
";",
"}",
"}"
] |
Dissociate a UI component with a command.
@param commandName Name of the command.
@param component Component to be associated.
|
[
"Dissociate",
"a",
"UI",
"component",
"with",
"a",
"command",
"."
] |
train
|
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandUtil.java#L209-L215
|
b3log/latke
|
latke-core/src/main/java/org/b3log/latke/Latkes.java
|
Latkes.setLocalProperty
|
public static void setLocalProperty(final String key, final String value) {
"""
Sets local.props with the specified key and value.
@param key the specified key
@param value the specified value
"""
if (null == key) {
LOGGER.log(Level.WARN, "local.props can not set null key");
return;
}
if (null == value) {
LOGGER.log(Level.WARN, "local.props can not set null value");
return;
}
localProps.setProperty(key, value);
}
|
java
|
public static void setLocalProperty(final String key, final String value) {
if (null == key) {
LOGGER.log(Level.WARN, "local.props can not set null key");
return;
}
if (null == value) {
LOGGER.log(Level.WARN, "local.props can not set null value");
return;
}
localProps.setProperty(key, value);
}
|
[
"public",
"static",
"void",
"setLocalProperty",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"null",
"==",
"key",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARN",
",",
"\"local.props can not set null key\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"null",
"==",
"value",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARN",
",",
"\"local.props can not set null value\"",
")",
";",
"return",
";",
"}",
"localProps",
".",
"setProperty",
"(",
"key",
",",
"value",
")",
";",
"}"
] |
Sets local.props with the specified key and value.
@param key the specified key
@param value the specified value
|
[
"Sets",
"local",
".",
"props",
"with",
"the",
"specified",
"key",
"and",
"value",
"."
] |
train
|
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L148-L161
|
molgenis/molgenis
|
molgenis-semantic-mapper/src/main/java/org/molgenis/semanticmapper/mapping/model/MappingTarget.java
|
MappingTarget.addSource
|
public EntityMapping addSource(EntityType source) {
"""
Adds a new {@link EntityMapping} to this target for a certain source.
@param source {@link EntityType} for the source entity that is mapped to this target
@return the newly created empty {@link EntityMapping}
"""
if (entityMappings.containsKey(source.getId())) {
throw new IllegalStateException("Mapping already present for source " + source.getId());
}
EntityMapping result = new EntityMapping(source, target);
entityMappings.put(source.getId(), result);
return result;
}
|
java
|
public EntityMapping addSource(EntityType source) {
if (entityMappings.containsKey(source.getId())) {
throw new IllegalStateException("Mapping already present for source " + source.getId());
}
EntityMapping result = new EntityMapping(source, target);
entityMappings.put(source.getId(), result);
return result;
}
|
[
"public",
"EntityMapping",
"addSource",
"(",
"EntityType",
"source",
")",
"{",
"if",
"(",
"entityMappings",
".",
"containsKey",
"(",
"source",
".",
"getId",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Mapping already present for source \"",
"+",
"source",
".",
"getId",
"(",
")",
")",
";",
"}",
"EntityMapping",
"result",
"=",
"new",
"EntityMapping",
"(",
"source",
",",
"target",
")",
";",
"entityMappings",
".",
"put",
"(",
"source",
".",
"getId",
"(",
")",
",",
"result",
")",
";",
"return",
"result",
";",
"}"
] |
Adds a new {@link EntityMapping} to this target for a certain source.
@param source {@link EntityType} for the source entity that is mapped to this target
@return the newly created empty {@link EntityMapping}
|
[
"Adds",
"a",
"new",
"{",
"@link",
"EntityMapping",
"}",
"to",
"this",
"target",
"for",
"a",
"certain",
"source",
"."
] |
train
|
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-semantic-mapper/src/main/java/org/molgenis/semanticmapper/mapping/model/MappingTarget.java#L67-L74
|
google/j2objc
|
jre_emul/openjdk/src/share/classes/java/math/BitSieve.java
|
BitSieve.sieveSearch
|
private int sieveSearch(int limit, int start) {
"""
This method returns the index of the first clear bit in the search
array that occurs at or after start. It will not search past the
specified limit. It returns -1 if there is no such clear bit.
"""
if (start >= limit)
return -1;
int index = start;
do {
if (!get(index))
return index;
index++;
} while(index < limit-1);
return -1;
}
|
java
|
private int sieveSearch(int limit, int start) {
if (start >= limit)
return -1;
int index = start;
do {
if (!get(index))
return index;
index++;
} while(index < limit-1);
return -1;
}
|
[
"private",
"int",
"sieveSearch",
"(",
"int",
"limit",
",",
"int",
"start",
")",
"{",
"if",
"(",
"start",
">=",
"limit",
")",
"return",
"-",
"1",
";",
"int",
"index",
"=",
"start",
";",
"do",
"{",
"if",
"(",
"!",
"get",
"(",
"index",
")",
")",
"return",
"index",
";",
"index",
"++",
";",
"}",
"while",
"(",
"index",
"<",
"limit",
"-",
"1",
")",
";",
"return",
"-",
"1",
";",
"}"
] |
This method returns the index of the first clear bit in the search
array that occurs at or after start. It will not search past the
specified limit. It returns -1 if there is no such clear bit.
|
[
"This",
"method",
"returns",
"the",
"index",
"of",
"the",
"first",
"clear",
"bit",
"in",
"the",
"search",
"array",
"that",
"occurs",
"at",
"or",
"after",
"start",
".",
"It",
"will",
"not",
"search",
"past",
"the",
"specified",
"limit",
".",
"It",
"returns",
"-",
"1",
"if",
"there",
"is",
"no",
"such",
"clear",
"bit",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BitSieve.java#L166-L177
|
alkacon/opencms-core
|
src-gwt/org/opencms/acacia/client/CmsAttributeHandler.java
|
CmsAttributeHandler.handleValueChange
|
public void handleValueChange(int valueIndex, String value) {
"""
Handles value changes from the view.<p>
@param valueIndex the value index
@param value the value
"""
changeEntityValue(value, valueIndex);
CmsUndoRedoHandler handler = CmsUndoRedoHandler.getInstance();
if (handler.isIntitalized()) {
handler.addChange(m_entity.getId(), m_attributeName, valueIndex, ChangeType.value);
}
}
|
java
|
public void handleValueChange(int valueIndex, String value) {
changeEntityValue(value, valueIndex);
CmsUndoRedoHandler handler = CmsUndoRedoHandler.getInstance();
if (handler.isIntitalized()) {
handler.addChange(m_entity.getId(), m_attributeName, valueIndex, ChangeType.value);
}
}
|
[
"public",
"void",
"handleValueChange",
"(",
"int",
"valueIndex",
",",
"String",
"value",
")",
"{",
"changeEntityValue",
"(",
"value",
",",
"valueIndex",
")",
";",
"CmsUndoRedoHandler",
"handler",
"=",
"CmsUndoRedoHandler",
".",
"getInstance",
"(",
")",
";",
"if",
"(",
"handler",
".",
"isIntitalized",
"(",
")",
")",
"{",
"handler",
".",
"addChange",
"(",
"m_entity",
".",
"getId",
"(",
")",
",",
"m_attributeName",
",",
"valueIndex",
",",
"ChangeType",
".",
"value",
")",
";",
"}",
"}"
] |
Handles value changes from the view.<p>
@param valueIndex the value index
@param value the value
|
[
"Handles",
"value",
"changes",
"from",
"the",
"view",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/CmsAttributeHandler.java#L565-L572
|
khuxtable/seaglass
|
src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java
|
CheckBoxMenuItemPainter.paintCheckIconEnabled
|
private void paintCheckIconEnabled(Graphics2D g, int width, int height) {
"""
Paint the check mark in enabled state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height.
"""
g.setPaint(iconEnabled);
g.drawRoundRect(0, 1, width-1, height-2, 4, 4);
}
|
java
|
private void paintCheckIconEnabled(Graphics2D g, int width, int height) {
g.setPaint(iconEnabled);
g.drawRoundRect(0, 1, width-1, height-2, 4, 4);
}
|
[
"private",
"void",
"paintCheckIconEnabled",
"(",
"Graphics2D",
"g",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"g",
".",
"setPaint",
"(",
"iconEnabled",
")",
";",
"g",
".",
"drawRoundRect",
"(",
"0",
",",
"1",
",",
"width",
"-",
"1",
",",
"height",
"-",
"2",
",",
"4",
",",
"4",
")",
";",
"}"
] |
Paint the check mark in enabled state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height.
|
[
"Paint",
"the",
"check",
"mark",
"in",
"enabled",
"state",
"."
] |
train
|
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java#L160-L163
|
jglobus/JGlobus
|
gridftp/src/main/java/org/globus/ftp/FTPClient.java
|
FTPClient.getChecksum
|
public String getChecksum(String algorithm,
long offset,
long length,
String path)
throws ClientException, ServerException, IOException {
"""
implement GridFTP v2 CKSM command from
<a href="http://www.ogf.org/documents/GFD.47.pdf">GridFTP v2 Protocol Description</a>
<pre>
5.1 CKSM
This command is used by the client to request checksum calculation over a portion or
whole file existing on the server. The syntax is:
CKSM <algorithm> <offset> <length> <path> CRLF
Server executes this command by calculating specified type of checksum over
portion of the file starting at the offset and of the specified length. If length is –1,
the checksum will be calculated through the end of the file. On success, the server
replies with
2xx <checksum value>
Actual format of checksum value depends on the algorithm used, but generally,
hexadecimal representation should be used.
</pre>
@param algorithm ckeckum alorithm
@param offset
@param length
@param path
@return ckecksum value returned by the server
@throws org.globus.ftp.exception.ClientException
@throws org.globus.ftp.exception.ServerException
@throws java.io.IOException
"""
// check if we the cksum commands and specific algorithm are supported
checkCksumSupport(algorithm);
// form CKSM command
String parameters = String.format("%s %d %d %s",algorithm, offset,length,path);
Command cmd = new Command("CKSM", parameters);
// transfer command, obtain reply
Reply cksumReply = doCommand(cmd);
// check for error
if( !Reply.isPositiveCompletion(cksumReply) ) {
throw new ServerException(ServerException.SERVER_REFUSED,
cksumReply.getMessage());
}
return cksumReply.getMessage();
}
|
java
|
public String getChecksum(String algorithm,
long offset,
long length,
String path)
throws ClientException, ServerException, IOException {
// check if we the cksum commands and specific algorithm are supported
checkCksumSupport(algorithm);
// form CKSM command
String parameters = String.format("%s %d %d %s",algorithm, offset,length,path);
Command cmd = new Command("CKSM", parameters);
// transfer command, obtain reply
Reply cksumReply = doCommand(cmd);
// check for error
if( !Reply.isPositiveCompletion(cksumReply) ) {
throw new ServerException(ServerException.SERVER_REFUSED,
cksumReply.getMessage());
}
return cksumReply.getMessage();
}
|
[
"public",
"String",
"getChecksum",
"(",
"String",
"algorithm",
",",
"long",
"offset",
",",
"long",
"length",
",",
"String",
"path",
")",
"throws",
"ClientException",
",",
"ServerException",
",",
"IOException",
"{",
"// check if we the cksum commands and specific algorithm are supported",
"checkCksumSupport",
"(",
"algorithm",
")",
";",
"// form CKSM command",
"String",
"parameters",
"=",
"String",
".",
"format",
"(",
"\"%s %d %d %s\"",
",",
"algorithm",
",",
"offset",
",",
"length",
",",
"path",
")",
";",
"Command",
"cmd",
"=",
"new",
"Command",
"(",
"\"CKSM\"",
",",
"parameters",
")",
";",
"// transfer command, obtain reply",
"Reply",
"cksumReply",
"=",
"doCommand",
"(",
"cmd",
")",
";",
"// check for error",
"if",
"(",
"!",
"Reply",
".",
"isPositiveCompletion",
"(",
"cksumReply",
")",
")",
"{",
"throw",
"new",
"ServerException",
"(",
"ServerException",
".",
"SERVER_REFUSED",
",",
"cksumReply",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"return",
"cksumReply",
".",
"getMessage",
"(",
")",
";",
"}"
] |
implement GridFTP v2 CKSM command from
<a href="http://www.ogf.org/documents/GFD.47.pdf">GridFTP v2 Protocol Description</a>
<pre>
5.1 CKSM
This command is used by the client to request checksum calculation over a portion or
whole file existing on the server. The syntax is:
CKSM <algorithm> <offset> <length> <path> CRLF
Server executes this command by calculating specified type of checksum over
portion of the file starting at the offset and of the specified length. If length is –1,
the checksum will be calculated through the end of the file. On success, the server
replies with
2xx <checksum value>
Actual format of checksum value depends on the algorithm used, but generally,
hexadecimal representation should be used.
</pre>
@param algorithm ckeckum alorithm
@param offset
@param length
@param path
@return ckecksum value returned by the server
@throws org.globus.ftp.exception.ClientException
@throws org.globus.ftp.exception.ServerException
@throws java.io.IOException
|
[
"implement",
"GridFTP",
"v2",
"CKSM",
"command",
"from",
"<a",
"href",
"=",
"http",
":",
"//",
"www",
".",
"ogf",
".",
"org",
"/",
"documents",
"/",
"GFD",
".",
"47",
".",
"pdf",
">",
"GridFTP",
"v2",
"Protocol",
"Description<",
"/",
"a",
">",
"<pre",
">",
"5",
".",
"1",
"CKSM",
"This",
"command",
"is",
"used",
"by",
"the",
"client",
"to",
"request",
"checksum",
"calculation",
"over",
"a",
"portion",
"or",
"whole",
"file",
"existing",
"on",
"the",
"server",
".",
"The",
"syntax",
"is",
":",
"CKSM",
"<",
";",
"algorithm>",
";",
"<",
";",
"offset>",
";",
"<",
";",
"length>",
";",
"<",
";",
"path>",
";",
"CRLF",
"Server",
"executes",
"this",
"command",
"by",
"calculating",
"specified",
"type",
"of",
"checksum",
"over",
"portion",
"of",
"the",
"file",
"starting",
"at",
"the",
"offset",
"and",
"of",
"the",
"specified",
"length",
".",
"If",
"length",
"is",
"–1",
"the",
"checksum",
"will",
"be",
"calculated",
"through",
"the",
"end",
"of",
"the",
"file",
".",
"On",
"success",
"the",
"server",
"replies",
"with",
"2xx",
"<",
";",
"checksum",
"value>",
";",
"Actual",
"format",
"of",
"checksum",
"value",
"depends",
"on",
"the",
"algorithm",
"used",
"but",
"generally",
"hexadecimal",
"representation",
"should",
"be",
"used",
".",
"<",
"/",
"pre",
">"
] |
train
|
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/FTPClient.java#L2152-L2175
|
alkacon/opencms-core
|
src-setup/org/opencms/setup/CmsSetupBean.java
|
CmsSetupBean.validateJdbc
|
public boolean validateJdbc() {
"""
Checks the jdbc driver.<p>
@return <code>true</code> if at least one of the recommended drivers is found
"""
boolean result = false;
String libFolder = getLibFolder();
Iterator<String> it = getDatabaseLibs(getDatabase()).iterator();
while (it.hasNext()) {
String libName = it.next();
File libFile = new File(libFolder, libName);
if (libFile.exists()) {
result = true;
}
}
return result;
}
|
java
|
public boolean validateJdbc() {
boolean result = false;
String libFolder = getLibFolder();
Iterator<String> it = getDatabaseLibs(getDatabase()).iterator();
while (it.hasNext()) {
String libName = it.next();
File libFile = new File(libFolder, libName);
if (libFile.exists()) {
result = true;
}
}
return result;
}
|
[
"public",
"boolean",
"validateJdbc",
"(",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"String",
"libFolder",
"=",
"getLibFolder",
"(",
")",
";",
"Iterator",
"<",
"String",
">",
"it",
"=",
"getDatabaseLibs",
"(",
"getDatabase",
"(",
")",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"String",
"libName",
"=",
"it",
".",
"next",
"(",
")",
";",
"File",
"libFile",
"=",
"new",
"File",
"(",
"libFolder",
",",
"libName",
")",
";",
"if",
"(",
"libFile",
".",
"exists",
"(",
")",
")",
"{",
"result",
"=",
"true",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Checks the jdbc driver.<p>
@return <code>true</code> if at least one of the recommended drivers is found
|
[
"Checks",
"the",
"jdbc",
"driver",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/CmsSetupBean.java#L2331-L2344
|
igniterealtime/Smack
|
smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/OpenPgpManager.java
|
OpenPgpManager.decryptOpenPgpElement
|
public OpenPgpMessage decryptOpenPgpElement(OpenPgpElement element, OpenPgpContact sender)
throws SmackException.NotLoggedInException, IOException, PGPException {
"""
Decrypt and or verify an {@link OpenPgpElement} and return the decrypted {@link OpenPgpMessage}.
@param element {@link OpenPgpElement} containing the message.
@param sender {@link OpenPgpContact} who sent the message.
@return decrypted and/or verified message
@throws SmackException.NotLoggedInException in case we aren't logged in (we need to know our jid)
@throws IOException IO error (reading keys, streams etc)
@throws PGPException in case of an PGP error
"""
return provider.decryptAndOrVerify(element, getOpenPgpSelf(), sender);
}
|
java
|
public OpenPgpMessage decryptOpenPgpElement(OpenPgpElement element, OpenPgpContact sender)
throws SmackException.NotLoggedInException, IOException, PGPException {
return provider.decryptAndOrVerify(element, getOpenPgpSelf(), sender);
}
|
[
"public",
"OpenPgpMessage",
"decryptOpenPgpElement",
"(",
"OpenPgpElement",
"element",
",",
"OpenPgpContact",
"sender",
")",
"throws",
"SmackException",
".",
"NotLoggedInException",
",",
"IOException",
",",
"PGPException",
"{",
"return",
"provider",
".",
"decryptAndOrVerify",
"(",
"element",
",",
"getOpenPgpSelf",
"(",
")",
",",
"sender",
")",
";",
"}"
] |
Decrypt and or verify an {@link OpenPgpElement} and return the decrypted {@link OpenPgpMessage}.
@param element {@link OpenPgpElement} containing the message.
@param sender {@link OpenPgpContact} who sent the message.
@return decrypted and/or verified message
@throws SmackException.NotLoggedInException in case we aren't logged in (we need to know our jid)
@throws IOException IO error (reading keys, streams etc)
@throws PGPException in case of an PGP error
|
[
"Decrypt",
"and",
"or",
"verify",
"an",
"{",
"@link",
"OpenPgpElement",
"}",
"and",
"return",
"the",
"decrypted",
"{",
"@link",
"OpenPgpMessage",
"}",
"."
] |
train
|
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-openpgp/src/main/java/org/jivesoftware/smackx/ox/OpenPgpManager.java#L545-L548
|
ykrasik/jaci
|
jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/param/CliParamParseContext.java
|
CliParamParseContext.createParamAssistInfo
|
public ParamAssistInfo createParamAssistInfo(String prefix) throws ParseException {
"""
Create {@link ParamAssistInfo} out of this context's state (already parsed values, and parameters still needing
to be parsed).
In case the last argument parsed by the context was a call-by-name (ended with '-{paramName}'),
the returned assist info will contain that parameter's auto complete.
Otherwise, if the given prefix starts with '-' (call-by-name prefix), the returned assist info will contain
suggestions for unbound parameter names.
Otherwise the returned assist info will contain suggestions for values for the next unbound positional parameter.
@param prefix Prefix to create assistance for.
@return A {@link ParamAssistInfo} if the context managed to construct one according to the above rules.
@throws ParseException If an error occurred, according to the above rules.
"""
if (nextNamedParam.isPresent()) {
// The last parsed value was a call-by-name (ended with '-{paramName}').
// Have that named parameter auto-complete the prefix.
final CliParam param = nextNamedParam.get();
final AutoComplete autoComplete = param.autoComplete(prefix);
final BoundParams boundParams = new BoundParams(parsedValues, nextNamedParam);
return new ParamAssistInfo(boundParams, autoComplete);
}
final CliParam nextParam = getNextUnboundParam(prefix);
// Check if 'prefix' starts with the named parameter call prefix.
final AutoComplete autoComplete;
if (prefix.startsWith(CliConstants.NAMED_PARAM_PREFIX)) {
// Prefix starts with the named parameter call prefix.
// Auto complete it with possible unbound parameter names.
// TODO: Can also be a negative number... which cannot be auto-completed.
final String paramNamePrefix = prefix.substring(1);
autoComplete = autoCompleteParamName(paramNamePrefix);
} else {
// Prefix doesn't start with the named parameter call prefix.
// Have the next unbound parameter auto complete it's value.
autoComplete = nextParam.autoComplete(prefix);
}
final BoundParams boundParams = new BoundParams(parsedValues, Opt.of(nextParam));
return new ParamAssistInfo(boundParams, autoComplete);
}
|
java
|
public ParamAssistInfo createParamAssistInfo(String prefix) throws ParseException {
if (nextNamedParam.isPresent()) {
// The last parsed value was a call-by-name (ended with '-{paramName}').
// Have that named parameter auto-complete the prefix.
final CliParam param = nextNamedParam.get();
final AutoComplete autoComplete = param.autoComplete(prefix);
final BoundParams boundParams = new BoundParams(parsedValues, nextNamedParam);
return new ParamAssistInfo(boundParams, autoComplete);
}
final CliParam nextParam = getNextUnboundParam(prefix);
// Check if 'prefix' starts with the named parameter call prefix.
final AutoComplete autoComplete;
if (prefix.startsWith(CliConstants.NAMED_PARAM_PREFIX)) {
// Prefix starts with the named parameter call prefix.
// Auto complete it with possible unbound parameter names.
// TODO: Can also be a negative number... which cannot be auto-completed.
final String paramNamePrefix = prefix.substring(1);
autoComplete = autoCompleteParamName(paramNamePrefix);
} else {
// Prefix doesn't start with the named parameter call prefix.
// Have the next unbound parameter auto complete it's value.
autoComplete = nextParam.autoComplete(prefix);
}
final BoundParams boundParams = new BoundParams(parsedValues, Opt.of(nextParam));
return new ParamAssistInfo(boundParams, autoComplete);
}
|
[
"public",
"ParamAssistInfo",
"createParamAssistInfo",
"(",
"String",
"prefix",
")",
"throws",
"ParseException",
"{",
"if",
"(",
"nextNamedParam",
".",
"isPresent",
"(",
")",
")",
"{",
"// The last parsed value was a call-by-name (ended with '-{paramName}').",
"// Have that named parameter auto-complete the prefix.",
"final",
"CliParam",
"param",
"=",
"nextNamedParam",
".",
"get",
"(",
")",
";",
"final",
"AutoComplete",
"autoComplete",
"=",
"param",
".",
"autoComplete",
"(",
"prefix",
")",
";",
"final",
"BoundParams",
"boundParams",
"=",
"new",
"BoundParams",
"(",
"parsedValues",
",",
"nextNamedParam",
")",
";",
"return",
"new",
"ParamAssistInfo",
"(",
"boundParams",
",",
"autoComplete",
")",
";",
"}",
"final",
"CliParam",
"nextParam",
"=",
"getNextUnboundParam",
"(",
"prefix",
")",
";",
"// Check if 'prefix' starts with the named parameter call prefix.",
"final",
"AutoComplete",
"autoComplete",
";",
"if",
"(",
"prefix",
".",
"startsWith",
"(",
"CliConstants",
".",
"NAMED_PARAM_PREFIX",
")",
")",
"{",
"// Prefix starts with the named parameter call prefix.",
"// Auto complete it with possible unbound parameter names.",
"// TODO: Can also be a negative number... which cannot be auto-completed.",
"final",
"String",
"paramNamePrefix",
"=",
"prefix",
".",
"substring",
"(",
"1",
")",
";",
"autoComplete",
"=",
"autoCompleteParamName",
"(",
"paramNamePrefix",
")",
";",
"}",
"else",
"{",
"// Prefix doesn't start with the named parameter call prefix.",
"// Have the next unbound parameter auto complete it's value.",
"autoComplete",
"=",
"nextParam",
".",
"autoComplete",
"(",
"prefix",
")",
";",
"}",
"final",
"BoundParams",
"boundParams",
"=",
"new",
"BoundParams",
"(",
"parsedValues",
",",
"Opt",
".",
"of",
"(",
"nextParam",
")",
")",
";",
"return",
"new",
"ParamAssistInfo",
"(",
"boundParams",
",",
"autoComplete",
")",
";",
"}"
] |
Create {@link ParamAssistInfo} out of this context's state (already parsed values, and parameters still needing
to be parsed).
In case the last argument parsed by the context was a call-by-name (ended with '-{paramName}'),
the returned assist info will contain that parameter's auto complete.
Otherwise, if the given prefix starts with '-' (call-by-name prefix), the returned assist info will contain
suggestions for unbound parameter names.
Otherwise the returned assist info will contain suggestions for values for the next unbound positional parameter.
@param prefix Prefix to create assistance for.
@return A {@link ParamAssistInfo} if the context managed to construct one according to the above rules.
@throws ParseException If an error occurred, according to the above rules.
|
[
"Create",
"{",
"@link",
"ParamAssistInfo",
"}",
"out",
"of",
"this",
"context",
"s",
"state",
"(",
"already",
"parsed",
"values",
"and",
"parameters",
"still",
"needing",
"to",
"be",
"parsed",
")",
".",
"In",
"case",
"the",
"last",
"argument",
"parsed",
"by",
"the",
"context",
"was",
"a",
"call",
"-",
"by",
"-",
"name",
"(",
"ended",
"with",
"-",
"{",
"paramName",
"}",
")",
"the",
"returned",
"assist",
"info",
"will",
"contain",
"that",
"parameter",
"s",
"auto",
"complete",
".",
"Otherwise",
"if",
"the",
"given",
"prefix",
"starts",
"with",
"-",
"(",
"call",
"-",
"by",
"-",
"name",
"prefix",
")",
"the",
"returned",
"assist",
"info",
"will",
"contain",
"suggestions",
"for",
"unbound",
"parameter",
"names",
".",
"Otherwise",
"the",
"returned",
"assist",
"info",
"will",
"contain",
"suggestions",
"for",
"values",
"for",
"the",
"next",
"unbound",
"positional",
"parameter",
"."
] |
train
|
https://github.com/ykrasik/jaci/blob/4615edef7c76288ad5ea8d678132b161645ca1e3/jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/param/CliParamParseContext.java#L214-L241
|
sksamuel/scrimage
|
scrimage-core/src/main/java/com/sksamuel/scrimage/nio/GifSequenceWriter.java
|
GifSequenceWriter.getNode
|
private IIOMetadataNode getNode(IIOMetadataNode rootNode, String nodeName) {
"""
Returns an existing child node, or creates and returns a new child node (if
the requested node does not exist).
@param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
@param nodeName the name of the child node.
@return the child node, if found or a new node created with the given name.
"""
IIOMetadataNode[] nodes = new IIOMetadataNode[rootNode.getLength()];
for (int i = 0; i < rootNode.getLength(); i++) {
nodes[i] = (IIOMetadataNode) rootNode.item(i);
}
return Arrays.stream(nodes)
.filter(n -> n.getNodeName().equalsIgnoreCase(nodeName))
.findFirst().orElseGet(() -> {
IIOMetadataNode node = new IIOMetadataNode(nodeName);
rootNode.appendChild(node);
return node;
});
}
|
java
|
private IIOMetadataNode getNode(IIOMetadataNode rootNode, String nodeName) {
IIOMetadataNode[] nodes = new IIOMetadataNode[rootNode.getLength()];
for (int i = 0; i < rootNode.getLength(); i++) {
nodes[i] = (IIOMetadataNode) rootNode.item(i);
}
return Arrays.stream(nodes)
.filter(n -> n.getNodeName().equalsIgnoreCase(nodeName))
.findFirst().orElseGet(() -> {
IIOMetadataNode node = new IIOMetadataNode(nodeName);
rootNode.appendChild(node);
return node;
});
}
|
[
"private",
"IIOMetadataNode",
"getNode",
"(",
"IIOMetadataNode",
"rootNode",
",",
"String",
"nodeName",
")",
"{",
"IIOMetadataNode",
"[",
"]",
"nodes",
"=",
"new",
"IIOMetadataNode",
"[",
"rootNode",
".",
"getLength",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rootNode",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"nodes",
"[",
"i",
"]",
"=",
"(",
"IIOMetadataNode",
")",
"rootNode",
".",
"item",
"(",
"i",
")",
";",
"}",
"return",
"Arrays",
".",
"stream",
"(",
"nodes",
")",
".",
"filter",
"(",
"n",
"->",
"n",
".",
"getNodeName",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"nodeName",
")",
")",
".",
"findFirst",
"(",
")",
".",
"orElseGet",
"(",
"(",
")",
"->",
"{",
"IIOMetadataNode",
"node",
"=",
"new",
"IIOMetadataNode",
"(",
"nodeName",
")",
";",
"rootNode",
".",
"appendChild",
"(",
"node",
")",
";",
"return",
"node",
";",
"}",
")",
";",
"}"
] |
Returns an existing child node, or creates and returns a new child node (if
the requested node does not exist).
@param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
@param nodeName the name of the child node.
@return the child node, if found or a new node created with the given name.
|
[
"Returns",
"an",
"existing",
"child",
"node",
"or",
"creates",
"and",
"returns",
"a",
"new",
"child",
"node",
"(",
"if",
"the",
"requested",
"node",
"does",
"not",
"exist",
")",
"."
] |
train
|
https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-core/src/main/java/com/sksamuel/scrimage/nio/GifSequenceWriter.java#L56-L71
|
Azure/azure-sdk-for-java
|
dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/RecordSetsInner.java
|
RecordSetsInner.listAllByDnsZoneWithServiceResponseAsync
|
public Observable<ServiceResponse<Page<RecordSetInner>>> listAllByDnsZoneWithServiceResponseAsync(final String resourceGroupName, final String zoneName, final Integer top, final String recordSetNameSuffix) {
"""
Lists all record sets in a DNS zone.
@param resourceGroupName The name of the resource group.
@param zoneName The name of the DNS zone (without a terminating dot).
@param top The maximum number of record sets to return. If not specified, returns up to 100 record sets.
@param recordSetNameSuffix The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .<recordSetNameSuffix>
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RecordSetInner> object
"""
return listAllByDnsZoneSinglePageAsync(resourceGroupName, zoneName, top, recordSetNameSuffix)
.concatMap(new Func1<ServiceResponse<Page<RecordSetInner>>, Observable<ServiceResponse<Page<RecordSetInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RecordSetInner>>> call(ServiceResponse<Page<RecordSetInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listAllByDnsZoneNextWithServiceResponseAsync(nextPageLink));
}
});
}
|
java
|
public Observable<ServiceResponse<Page<RecordSetInner>>> listAllByDnsZoneWithServiceResponseAsync(final String resourceGroupName, final String zoneName, final Integer top, final String recordSetNameSuffix) {
return listAllByDnsZoneSinglePageAsync(resourceGroupName, zoneName, top, recordSetNameSuffix)
.concatMap(new Func1<ServiceResponse<Page<RecordSetInner>>, Observable<ServiceResponse<Page<RecordSetInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RecordSetInner>>> call(ServiceResponse<Page<RecordSetInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listAllByDnsZoneNextWithServiceResponseAsync(nextPageLink));
}
});
}
|
[
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"RecordSetInner",
">",
">",
">",
"listAllByDnsZoneWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"zoneName",
",",
"final",
"Integer",
"top",
",",
"final",
"String",
"recordSetNameSuffix",
")",
"{",
"return",
"listAllByDnsZoneSinglePageAsync",
"(",
"resourceGroupName",
",",
"zoneName",
",",
"top",
",",
"recordSetNameSuffix",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"RecordSetInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"RecordSetInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"RecordSetInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"RecordSetInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listAllByDnsZoneNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Lists all record sets in a DNS zone.
@param resourceGroupName The name of the resource group.
@param zoneName The name of the DNS zone (without a terminating dot).
@param top The maximum number of record sets to return. If not specified, returns up to 100 record sets.
@param recordSetNameSuffix The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .<recordSetNameSuffix>
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RecordSetInner> object
|
[
"Lists",
"all",
"record",
"sets",
"in",
"a",
"DNS",
"zone",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/RecordSetsInner.java#L1550-L1562
|
Coveros/selenified
|
src/main/java/com/coveros/selenified/application/WaitFor.java
|
WaitFor.titleEquals
|
public void titleEquals(double seconds, String expectedTitle) {
"""
Waits up to the default wait time (5 seconds unless changed) for the provided title equals the actual title of the current page
the application is on. This information will be logged and recorded, with
a screenshot for traceability and added debugging support.
@param seconds the number of seconds to wait
@param expectedTitle - the title to wait for
"""
double end = System.currentTimeMillis() + (seconds * 1000);
try {
WebDriverWait wait = new WebDriverWait(app.getDriver(), (long) seconds, DEFAULT_POLLING_INTERVAL);
wait.until(ExpectedConditions.titleIs(expectedTitle));
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkTitleEquals(expectedTitle, seconds, timeTook);
} catch (TimeoutException e) {
checkTitleEquals(expectedTitle, seconds, seconds);
}
}
|
java
|
public void titleEquals(double seconds, String expectedTitle) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
WebDriverWait wait = new WebDriverWait(app.getDriver(), (long) seconds, DEFAULT_POLLING_INTERVAL);
wait.until(ExpectedConditions.titleIs(expectedTitle));
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkTitleEquals(expectedTitle, seconds, timeTook);
} catch (TimeoutException e) {
checkTitleEquals(expectedTitle, seconds, seconds);
}
}
|
[
"public",
"void",
"titleEquals",
"(",
"double",
"seconds",
",",
"String",
"expectedTitle",
")",
"{",
"double",
"end",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"(",
"seconds",
"*",
"1000",
")",
";",
"try",
"{",
"WebDriverWait",
"wait",
"=",
"new",
"WebDriverWait",
"(",
"app",
".",
"getDriver",
"(",
")",
",",
"(",
"long",
")",
"seconds",
",",
"DEFAULT_POLLING_INTERVAL",
")",
";",
"wait",
".",
"until",
"(",
"ExpectedConditions",
".",
"titleIs",
"(",
"expectedTitle",
")",
")",
";",
"double",
"timeTook",
"=",
"Math",
".",
"min",
"(",
"(",
"seconds",
"*",
"1000",
")",
"-",
"(",
"end",
"-",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
",",
"seconds",
"*",
"1000",
")",
"/",
"1000",
";",
"checkTitleEquals",
"(",
"expectedTitle",
",",
"seconds",
",",
"timeTook",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"checkTitleEquals",
"(",
"expectedTitle",
",",
"seconds",
",",
"seconds",
")",
";",
"}",
"}"
] |
Waits up to the default wait time (5 seconds unless changed) for the provided title equals the actual title of the current page
the application is on. This information will be logged and recorded, with
a screenshot for traceability and added debugging support.
@param seconds the number of seconds to wait
@param expectedTitle - the title to wait for
|
[
"Waits",
"up",
"to",
"the",
"default",
"wait",
"time",
"(",
"5",
"seconds",
"unless",
"changed",
")",
"for",
"the",
"provided",
"title",
"equals",
"the",
"actual",
"title",
"of",
"the",
"current",
"page",
"the",
"application",
"is",
"on",
".",
"This",
"information",
"will",
"be",
"logged",
"and",
"recorded",
"with",
"a",
"screenshot",
"for",
"traceability",
"and",
"added",
"debugging",
"support",
"."
] |
train
|
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/WaitFor.java#L368-L378
|
bbottema/simple-java-mail
|
modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java
|
ConfigLoader.loadProperties
|
public static Map<Property, Object> loadProperties(final File filename, final boolean addProperties) {
"""
Loads properties from property {@link File}, if provided. Calling this method only has effect on new Email and Mailer instances after this.
@param filename Any file reference that holds a properties list.
@param addProperties Flag to indicate if the new properties should be added or replacing the old properties.
@return The updated properties map that is used internally.
"""
try {
return loadProperties(new FileInputStream(filename), addProperties);
} catch (final FileNotFoundException e) {
throw new IllegalStateException("error reading properties file from File", e);
}
}
|
java
|
public static Map<Property, Object> loadProperties(final File filename, final boolean addProperties) {
try {
return loadProperties(new FileInputStream(filename), addProperties);
} catch (final FileNotFoundException e) {
throw new IllegalStateException("error reading properties file from File", e);
}
}
|
[
"public",
"static",
"Map",
"<",
"Property",
",",
"Object",
">",
"loadProperties",
"(",
"final",
"File",
"filename",
",",
"final",
"boolean",
"addProperties",
")",
"{",
"try",
"{",
"return",
"loadProperties",
"(",
"new",
"FileInputStream",
"(",
"filename",
")",
",",
"addProperties",
")",
";",
"}",
"catch",
"(",
"final",
"FileNotFoundException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"error reading properties file from File\"",
",",
"e",
")",
";",
"}",
"}"
] |
Loads properties from property {@link File}, if provided. Calling this method only has effect on new Email and Mailer instances after this.
@param filename Any file reference that holds a properties list.
@param addProperties Flag to indicate if the new properties should be added or replacing the old properties.
@return The updated properties map that is used internally.
|
[
"Loads",
"properties",
"from",
"property",
"{",
"@link",
"File",
"}",
"if",
"provided",
".",
"Calling",
"this",
"method",
"only",
"has",
"effect",
"on",
"new",
"Email",
"and",
"Mailer",
"instances",
"after",
"this",
"."
] |
train
|
https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java#L245-L251
|
gallandarakhneorg/afc
|
advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeImpl.java
|
AttributeImpl.compareAttrs
|
@Pure
public static int compareAttrs(Attribute arg0, Attribute arg1) {
"""
Compare the two specified attributes.
@param arg0 first attribute
@param arg1 second attribute.
@return replies a negative value if {@code arg0} is lesser than
{@code arg1}, a positive value if {@code arg0} is greater than
{@code arg1}, or <code>0</code> if they are equal.
@see AttributeComparator
"""
if (arg0 == arg1) {
return 0;
}
if (arg0 == null) {
return 1;
}
if (arg1 == null) {
return -1;
}
final String n0 = arg0.getName();
final String n1 = arg1.getName();
final int cmp = compareAttrNames(n0, n1);
if (cmp == 0) {
return compareValues(arg0, arg1);
}
return cmp;
}
|
java
|
@Pure
public static int compareAttrs(Attribute arg0, Attribute arg1) {
if (arg0 == arg1) {
return 0;
}
if (arg0 == null) {
return 1;
}
if (arg1 == null) {
return -1;
}
final String n0 = arg0.getName();
final String n1 = arg1.getName();
final int cmp = compareAttrNames(n0, n1);
if (cmp == 0) {
return compareValues(arg0, arg1);
}
return cmp;
}
|
[
"@",
"Pure",
"public",
"static",
"int",
"compareAttrs",
"(",
"Attribute",
"arg0",
",",
"Attribute",
"arg1",
")",
"{",
"if",
"(",
"arg0",
"==",
"arg1",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"arg0",
"==",
"null",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"arg1",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"final",
"String",
"n0",
"=",
"arg0",
".",
"getName",
"(",
")",
";",
"final",
"String",
"n1",
"=",
"arg1",
".",
"getName",
"(",
")",
";",
"final",
"int",
"cmp",
"=",
"compareAttrNames",
"(",
"n0",
",",
"n1",
")",
";",
"if",
"(",
"cmp",
"==",
"0",
")",
"{",
"return",
"compareValues",
"(",
"arg0",
",",
"arg1",
")",
";",
"}",
"return",
"cmp",
";",
"}"
] |
Compare the two specified attributes.
@param arg0 first attribute
@param arg1 second attribute.
@return replies a negative value if {@code arg0} is lesser than
{@code arg1}, a positive value if {@code arg0} is greater than
{@code arg1}, or <code>0</code> if they are equal.
@see AttributeComparator
|
[
"Compare",
"the",
"two",
"specified",
"attributes",
"."
] |
train
|
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/attributes/src/main/java/org/arakhne/afc/attrs/attr/AttributeImpl.java#L344-L365
|
cloudfoundry/uaa
|
server/src/main/java/org/cloudfoundry/identity/uaa/error/UaaException.java
|
UaaException.valueOf
|
public static UaaException valueOf(Map<String, String> errorParams) {
"""
Creates an {@link UaaException} from a {@link Map}.
@param errorParams a map with additional error information
@return the exception with error information
"""
String errorCode = errorParams.get(ERROR);
String errorMessage = errorParams.containsKey(DESCRIPTION) ? errorParams.get(DESCRIPTION) : null;
int status = DEFAULT_STATUS;
if (errorParams.containsKey(STATUS)) {
try {
status = Integer.valueOf(errorParams.get(STATUS));
} catch (NumberFormatException e) {
// ignore
}
}
UaaException ex = new UaaException(errorCode, errorMessage, status);
Set<Map.Entry<String, String>> entries = errorParams.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
if (!ERROR.equals(key) && !DESCRIPTION.equals(key)) {
ex.addAdditionalInformation(key, entry.getValue());
}
}
return ex;
}
|
java
|
public static UaaException valueOf(Map<String, String> errorParams) {
String errorCode = errorParams.get(ERROR);
String errorMessage = errorParams.containsKey(DESCRIPTION) ? errorParams.get(DESCRIPTION) : null;
int status = DEFAULT_STATUS;
if (errorParams.containsKey(STATUS)) {
try {
status = Integer.valueOf(errorParams.get(STATUS));
} catch (NumberFormatException e) {
// ignore
}
}
UaaException ex = new UaaException(errorCode, errorMessage, status);
Set<Map.Entry<String, String>> entries = errorParams.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
if (!ERROR.equals(key) && !DESCRIPTION.equals(key)) {
ex.addAdditionalInformation(key, entry.getValue());
}
}
return ex;
}
|
[
"public",
"static",
"UaaException",
"valueOf",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"errorParams",
")",
"{",
"String",
"errorCode",
"=",
"errorParams",
".",
"get",
"(",
"ERROR",
")",
";",
"String",
"errorMessage",
"=",
"errorParams",
".",
"containsKey",
"(",
"DESCRIPTION",
")",
"?",
"errorParams",
".",
"get",
"(",
"DESCRIPTION",
")",
":",
"null",
";",
"int",
"status",
"=",
"DEFAULT_STATUS",
";",
"if",
"(",
"errorParams",
".",
"containsKey",
"(",
"STATUS",
")",
")",
"{",
"try",
"{",
"status",
"=",
"Integer",
".",
"valueOf",
"(",
"errorParams",
".",
"get",
"(",
"STATUS",
")",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"// ignore",
"}",
"}",
"UaaException",
"ex",
"=",
"new",
"UaaException",
"(",
"errorCode",
",",
"errorMessage",
",",
"status",
")",
";",
"Set",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
">",
"entries",
"=",
"errorParams",
".",
"entrySet",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"entries",
")",
"{",
"String",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"!",
"ERROR",
".",
"equals",
"(",
"key",
")",
"&&",
"!",
"DESCRIPTION",
".",
"equals",
"(",
"key",
")",
")",
"{",
"ex",
".",
"addAdditionalInformation",
"(",
"key",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"return",
"ex",
";",
"}"
] |
Creates an {@link UaaException} from a {@link Map}.
@param errorParams a map with additional error information
@return the exception with error information
|
[
"Creates",
"an",
"{",
"@link",
"UaaException",
"}",
"from",
"a",
"{",
"@link",
"Map",
"}",
"."
] |
train
|
https://github.com/cloudfoundry/uaa/blob/e8df3d7060580c92d33461106399f9e4f36e3cd2/server/src/main/java/org/cloudfoundry/identity/uaa/error/UaaException.java#L120-L141
|
notnoop/java-apns
|
src/main/java/com/notnoop/apns/ApnsServiceBuilder.java
|
ApnsServiceBuilder.withCert
|
public ApnsServiceBuilder withCert(KeyStore keyStore, String password, String alias)
throws InvalidSSLConfig {
"""
Specify the certificate store used to connect to Apple APNS
servers. This relies on the stream of keystore (*.p12 | *.jks)
containing the keys and certificates, along with the given
password and alias.
The keystore can be either PKCS12 or JKS and the keystore
needs to be encrypted using the SunX509 algorithm.
This library does not support password-less p12 certificates, due to a
Oracle Java library <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6415637">
Bug 6415637</a>. There are three workarounds: use a password-protected
certificate, use a different boot Java SDK implementation, or constract
the `SSLContext` yourself! Needless to say, the password-protected
certificate is most recommended option.
@param keyStore the keystore
@param password the password of the keystore
@param alias the alias identifing the key to be used
@return this
@throws InvalidSSLConfig if stream is an invalid Keystore,
the password is invalid or the alias is not found
"""
assertPasswordNotEmpty(password);
return withSSLContext(new SSLContextBuilder()
.withAlgorithm(KEY_ALGORITHM)
.withCertificateKeyStore(keyStore, password, alias)
.withDefaultTrustKeyStore()
.build());
}
|
java
|
public ApnsServiceBuilder withCert(KeyStore keyStore, String password, String alias)
throws InvalidSSLConfig {
assertPasswordNotEmpty(password);
return withSSLContext(new SSLContextBuilder()
.withAlgorithm(KEY_ALGORITHM)
.withCertificateKeyStore(keyStore, password, alias)
.withDefaultTrustKeyStore()
.build());
}
|
[
"public",
"ApnsServiceBuilder",
"withCert",
"(",
"KeyStore",
"keyStore",
",",
"String",
"password",
",",
"String",
"alias",
")",
"throws",
"InvalidSSLConfig",
"{",
"assertPasswordNotEmpty",
"(",
"password",
")",
";",
"return",
"withSSLContext",
"(",
"new",
"SSLContextBuilder",
"(",
")",
".",
"withAlgorithm",
"(",
"KEY_ALGORITHM",
")",
".",
"withCertificateKeyStore",
"(",
"keyStore",
",",
"password",
",",
"alias",
")",
".",
"withDefaultTrustKeyStore",
"(",
")",
".",
"build",
"(",
")",
")",
";",
"}"
] |
Specify the certificate store used to connect to Apple APNS
servers. This relies on the stream of keystore (*.p12 | *.jks)
containing the keys and certificates, along with the given
password and alias.
The keystore can be either PKCS12 or JKS and the keystore
needs to be encrypted using the SunX509 algorithm.
This library does not support password-less p12 certificates, due to a
Oracle Java library <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6415637">
Bug 6415637</a>. There are three workarounds: use a password-protected
certificate, use a different boot Java SDK implementation, or constract
the `SSLContext` yourself! Needless to say, the password-protected
certificate is most recommended option.
@param keyStore the keystore
@param password the password of the keystore
@param alias the alias identifing the key to be used
@return this
@throws InvalidSSLConfig if stream is an invalid Keystore,
the password is invalid or the alias is not found
|
[
"Specify",
"the",
"certificate",
"store",
"used",
"to",
"connect",
"to",
"Apple",
"APNS",
"servers",
".",
"This",
"relies",
"on",
"the",
"stream",
"of",
"keystore",
"(",
"*",
".",
"p12",
"|",
"*",
".",
"jks",
")",
"containing",
"the",
"keys",
"and",
"certificates",
"along",
"with",
"the",
"given",
"password",
"and",
"alias",
"."
] |
train
|
https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/ApnsServiceBuilder.java#L281-L289
|
dlemmermann/CalendarFX
|
CalendarFXView/src/main/java/com/calendarfx/view/CalendarView.java
|
CalendarView.showWeek
|
public final void showWeek(Year year, int weekOfYear) {
"""
Sends the request to the calendar view to display the given week. The
view will try to switch to the {@link WeekPage} and set the value of
{@link #dateProperty()} to the date.
@param year the date to show in the view
@param weekOfYear the week to show in the view
"""
requireNonNull(year);
if (weekOfYear < 1) {
throw new IllegalArgumentException("illegal value for week of year: " + weekOfYear);
}
if (!weekPage.isHidden()) {
selectedPage.set(getWeekPage());
} else if (!monthPage.isHidden()) {
selectedPage.set(getMonthPage());
} else if (!yearPage.isHidden()) {
selectedPage.set(getYearPage());
}
setDate(LocalDate.of(year.getValue(), 1, 1).plusWeeks(weekOfYear));
}
|
java
|
public final void showWeek(Year year, int weekOfYear) {
requireNonNull(year);
if (weekOfYear < 1) {
throw new IllegalArgumentException("illegal value for week of year: " + weekOfYear);
}
if (!weekPage.isHidden()) {
selectedPage.set(getWeekPage());
} else if (!monthPage.isHidden()) {
selectedPage.set(getMonthPage());
} else if (!yearPage.isHidden()) {
selectedPage.set(getYearPage());
}
setDate(LocalDate.of(year.getValue(), 1, 1).plusWeeks(weekOfYear));
}
|
[
"public",
"final",
"void",
"showWeek",
"(",
"Year",
"year",
",",
"int",
"weekOfYear",
")",
"{",
"requireNonNull",
"(",
"year",
")",
";",
"if",
"(",
"weekOfYear",
"<",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"illegal value for week of year: \"",
"+",
"weekOfYear",
")",
";",
"}",
"if",
"(",
"!",
"weekPage",
".",
"isHidden",
"(",
")",
")",
"{",
"selectedPage",
".",
"set",
"(",
"getWeekPage",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"!",
"monthPage",
".",
"isHidden",
"(",
")",
")",
"{",
"selectedPage",
".",
"set",
"(",
"getMonthPage",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"!",
"yearPage",
".",
"isHidden",
"(",
")",
")",
"{",
"selectedPage",
".",
"set",
"(",
"getYearPage",
"(",
")",
")",
";",
"}",
"setDate",
"(",
"LocalDate",
".",
"of",
"(",
"year",
".",
"getValue",
"(",
")",
",",
"1",
",",
"1",
")",
".",
"plusWeeks",
"(",
"weekOfYear",
")",
")",
";",
"}"
] |
Sends the request to the calendar view to display the given week. The
view will try to switch to the {@link WeekPage} and set the value of
{@link #dateProperty()} to the date.
@param year the date to show in the view
@param weekOfYear the week to show in the view
|
[
"Sends",
"the",
"request",
"to",
"the",
"calendar",
"view",
"to",
"display",
"the",
"given",
"week",
".",
"The",
"view",
"will",
"try",
"to",
"switch",
"to",
"the",
"{",
"@link",
"WeekPage",
"}",
"and",
"set",
"the",
"value",
"of",
"{",
"@link",
"#dateProperty",
"()",
"}",
"to",
"the",
"date",
"."
] |
train
|
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/view/CalendarView.java#L772-L786
|
PunchThrough/bean-sdk-android
|
sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java
|
Bean.programWithSketch
|
public void programWithSketch(SketchHex hex, Callback<UploadProgress> onProgress, Runnable onComplete) {
"""
Programs the Bean with an Arduino sketch in hex form. The Bean's sketch name and
programmed-at timestamp will be set from the
{@link com.punchthrough.bean.sdk.upload.SketchHex} object.
@param hex The sketch to be sent to the Bean
@param onProgress Called with progress while the sketch upload is occurring
@param onComplete Called when the sketch upload is complete
"""
// Resetting client state means we have a clean state to start. Variables are cleared and
// the state timeout timer will not fire during firmware uploads.
resetSketchUploadState();
// Set onProgress and onComplete handlers
this.onSketchUploadProgress = onProgress;
this.onSketchUploadComplete = onComplete;
// Prepare the sketch blocks to be sent
sketchBlocksToSend = Chunk.chunksFrom(hex, MAX_BLOCK_SIZE_BYTES);
// Construct and send the START payload with sketch metadata
SketchMetadata metadata = SketchMetadata.create(hex, new Date());
Buffer payload = metadata.toPayload();
// If there's no data in the hex sketch, send the empty metadata to clear the Bean's sketch
// and don't worry about sending sketch blocks
if (hex.bytes().length > 0) {
sketchUploadState = SketchUploadState.SENDING_START_COMMAND;
resetSketchStateTimeout();
}
sendMessage(BeanMessageID.BL_CMD_START, payload);
}
|
java
|
public void programWithSketch(SketchHex hex, Callback<UploadProgress> onProgress, Runnable onComplete) {
// Resetting client state means we have a clean state to start. Variables are cleared and
// the state timeout timer will not fire during firmware uploads.
resetSketchUploadState();
// Set onProgress and onComplete handlers
this.onSketchUploadProgress = onProgress;
this.onSketchUploadComplete = onComplete;
// Prepare the sketch blocks to be sent
sketchBlocksToSend = Chunk.chunksFrom(hex, MAX_BLOCK_SIZE_BYTES);
// Construct and send the START payload with sketch metadata
SketchMetadata metadata = SketchMetadata.create(hex, new Date());
Buffer payload = metadata.toPayload();
// If there's no data in the hex sketch, send the empty metadata to clear the Bean's sketch
// and don't worry about sending sketch blocks
if (hex.bytes().length > 0) {
sketchUploadState = SketchUploadState.SENDING_START_COMMAND;
resetSketchStateTimeout();
}
sendMessage(BeanMessageID.BL_CMD_START, payload);
}
|
[
"public",
"void",
"programWithSketch",
"(",
"SketchHex",
"hex",
",",
"Callback",
"<",
"UploadProgress",
">",
"onProgress",
",",
"Runnable",
"onComplete",
")",
"{",
"// Resetting client state means we have a clean state to start. Variables are cleared and",
"// the state timeout timer will not fire during firmware uploads.",
"resetSketchUploadState",
"(",
")",
";",
"// Set onProgress and onComplete handlers",
"this",
".",
"onSketchUploadProgress",
"=",
"onProgress",
";",
"this",
".",
"onSketchUploadComplete",
"=",
"onComplete",
";",
"// Prepare the sketch blocks to be sent",
"sketchBlocksToSend",
"=",
"Chunk",
".",
"chunksFrom",
"(",
"hex",
",",
"MAX_BLOCK_SIZE_BYTES",
")",
";",
"// Construct and send the START payload with sketch metadata",
"SketchMetadata",
"metadata",
"=",
"SketchMetadata",
".",
"create",
"(",
"hex",
",",
"new",
"Date",
"(",
")",
")",
";",
"Buffer",
"payload",
"=",
"metadata",
".",
"toPayload",
"(",
")",
";",
"// If there's no data in the hex sketch, send the empty metadata to clear the Bean's sketch",
"// and don't worry about sending sketch blocks",
"if",
"(",
"hex",
".",
"bytes",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"sketchUploadState",
"=",
"SketchUploadState",
".",
"SENDING_START_COMMAND",
";",
"resetSketchStateTimeout",
"(",
")",
";",
"}",
"sendMessage",
"(",
"BeanMessageID",
".",
"BL_CMD_START",
",",
"payload",
")",
";",
"}"
] |
Programs the Bean with an Arduino sketch in hex form. The Bean's sketch name and
programmed-at timestamp will be set from the
{@link com.punchthrough.bean.sdk.upload.SketchHex} object.
@param hex The sketch to be sent to the Bean
@param onProgress Called with progress while the sketch upload is occurring
@param onComplete Called when the sketch upload is complete
|
[
"Programs",
"the",
"Bean",
"with",
"an",
"Arduino",
"sketch",
"in",
"hex",
"form",
".",
"The",
"Bean",
"s",
"sketch",
"name",
"and",
"programmed",
"-",
"at",
"timestamp",
"will",
"be",
"set",
"from",
"the",
"{",
"@link",
"com",
".",
"punchthrough",
".",
"bean",
".",
"sdk",
".",
"upload",
".",
"SketchHex",
"}",
"object",
"."
] |
train
|
https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1107-L1133
|
salesforce/Argus
|
ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java
|
AsyncHbaseSchemaService._canSkipWhileScanning
|
private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) {
"""
Check if we can perform a faster scan. We can only perform a faster scan when we are trying to discover scopes or metrics
without having information on any other fields.
"""
if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type))
&& !SchemaService.containsFilter(query.getTagKey())
&& !SchemaService.containsFilter(query.getTagValue())
&& !SchemaService.containsFilter(query.getNamespace())) {
if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) {
return false;
}
if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) {
return false;
}
return true;
}
return false;
}
|
java
|
private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) {
if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type))
&& !SchemaService.containsFilter(query.getTagKey())
&& !SchemaService.containsFilter(query.getTagValue())
&& !SchemaService.containsFilter(query.getNamespace())) {
if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) {
return false;
}
if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) {
return false;
}
return true;
}
return false;
}
|
[
"private",
"boolean",
"_canSkipWhileScanning",
"(",
"MetricSchemaRecordQuery",
"query",
",",
"RecordType",
"type",
")",
"{",
"if",
"(",
"(",
"RecordType",
".",
"METRIC",
".",
"equals",
"(",
"type",
")",
"||",
"RecordType",
".",
"SCOPE",
".",
"equals",
"(",
"type",
")",
")",
"&&",
"!",
"SchemaService",
".",
"containsFilter",
"(",
"query",
".",
"getTagKey",
"(",
")",
")",
"&&",
"!",
"SchemaService",
".",
"containsFilter",
"(",
"query",
".",
"getTagValue",
"(",
")",
")",
"&&",
"!",
"SchemaService",
".",
"containsFilter",
"(",
"query",
".",
"getNamespace",
"(",
")",
")",
")",
"{",
"if",
"(",
"RecordType",
".",
"METRIC",
".",
"equals",
"(",
"type",
")",
"&&",
"!",
"SchemaService",
".",
"containsFilter",
"(",
"query",
".",
"getMetric",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"RecordType",
".",
"SCOPE",
".",
"equals",
"(",
"type",
")",
"&&",
"!",
"SchemaService",
".",
"containsFilter",
"(",
"query",
".",
"getScope",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Check if we can perform a faster scan. We can only perform a faster scan when we are trying to discover scopes or metrics
without having information on any other fields.
|
[
"Check",
"if",
"we",
"can",
"perform",
"a",
"faster",
"scan",
".",
"We",
"can",
"only",
"perform",
"a",
"faster",
"scan",
"when",
"we",
"are",
"trying",
"to",
"discover",
"scopes",
"or",
"metrics",
"without",
"having",
"information",
"on",
"any",
"other",
"fields",
"."
] |
train
|
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java#L449-L468
|
mgormley/pacaya
|
src/main/java/edu/jhu/pacaya/autodiff/StochasticGradientApproximation.java
|
StochasticGradientApproximation.getGradDotDirApprox
|
public static double getGradDotDirApprox(Function fn, IntDoubleVector x, IntDoubleVector d, double c) {
"""
Compute f'(x)^T d = ( L(x + c * d) - L(x - c * d) ) / (2c)
@param fn Function, f.
@param x Point at which to evaluate the gradient, x.
@param d Random direction, d.
@param c Epsilon constant.
@return
"""
double dot = 0;
{
// L(\theta + c * d)
IntDoubleVector d1 = d.copy();
d1.scale(c);
IntDoubleVector x1 = x.copy();
x1.add(d1);
dot += fn.getValue(x1);
}
{
// - L(\theta - c * d)
IntDoubleVector d1 = d.copy();
d1.scale(-c);
IntDoubleVector x1 = x.copy();
x1.add(d1);
dot -= fn.getValue(x1);
}
dot /= (2.0 * c);
return dot;
}
|
java
|
public static double getGradDotDirApprox(Function fn, IntDoubleVector x, IntDoubleVector d, double c) {
double dot = 0;
{
// L(\theta + c * d)
IntDoubleVector d1 = d.copy();
d1.scale(c);
IntDoubleVector x1 = x.copy();
x1.add(d1);
dot += fn.getValue(x1);
}
{
// - L(\theta - c * d)
IntDoubleVector d1 = d.copy();
d1.scale(-c);
IntDoubleVector x1 = x.copy();
x1.add(d1);
dot -= fn.getValue(x1);
}
dot /= (2.0 * c);
return dot;
}
|
[
"public",
"static",
"double",
"getGradDotDirApprox",
"(",
"Function",
"fn",
",",
"IntDoubleVector",
"x",
",",
"IntDoubleVector",
"d",
",",
"double",
"c",
")",
"{",
"double",
"dot",
"=",
"0",
";",
"{",
"// L(\\theta + c * d)",
"IntDoubleVector",
"d1",
"=",
"d",
".",
"copy",
"(",
")",
";",
"d1",
".",
"scale",
"(",
"c",
")",
";",
"IntDoubleVector",
"x1",
"=",
"x",
".",
"copy",
"(",
")",
";",
"x1",
".",
"add",
"(",
"d1",
")",
";",
"dot",
"+=",
"fn",
".",
"getValue",
"(",
"x1",
")",
";",
"}",
"{",
"// - L(\\theta - c * d)",
"IntDoubleVector",
"d1",
"=",
"d",
".",
"copy",
"(",
")",
";",
"d1",
".",
"scale",
"(",
"-",
"c",
")",
";",
"IntDoubleVector",
"x1",
"=",
"x",
".",
"copy",
"(",
")",
";",
"x1",
".",
"add",
"(",
"d1",
")",
";",
"dot",
"-=",
"fn",
".",
"getValue",
"(",
"x1",
")",
";",
"}",
"dot",
"/=",
"(",
"2.0",
"*",
"c",
")",
";",
"return",
"dot",
";",
"}"
] |
Compute f'(x)^T d = ( L(x + c * d) - L(x - c * d) ) / (2c)
@param fn Function, f.
@param x Point at which to evaluate the gradient, x.
@param d Random direction, d.
@param c Epsilon constant.
@return
|
[
"Compute",
"f",
"(",
"x",
")",
"^T",
"d",
"=",
"(",
"L",
"(",
"x",
"+",
"c",
"*",
"d",
")",
"-",
"L",
"(",
"x",
"-",
"c",
"*",
"d",
")",
")",
"/",
"(",
"2c",
")"
] |
train
|
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/autodiff/StochasticGradientApproximation.java#L110-L130
|
groovy/groovy-core
|
src/main/org/codehaus/groovy/transform/trait/TraitComposer.java
|
TraitComposer.findDefaultMethodFromInterface
|
private static MethodNode findDefaultMethodFromInterface(final ClassNode cNode, final String name, final Parameter[] params) {
"""
An utility method which tries to find a method with default implementation (in the Java 8 semantics).
@param cNode a class node
@param name the name of the method
@param params the parameters of the method
@return a method node corresponding to a default method if it exists
"""
if (cNode == null) {
return null;
}
if (cNode.isInterface()) {
MethodNode method = cNode.getMethod(name, params);
if (method!=null && !method.isAbstract()) {
// this is a Java 8 only behavior!
return method;
}
}
ClassNode[] interfaces = cNode.getInterfaces();
for (ClassNode anInterface : interfaces) {
MethodNode res = findDefaultMethodFromInterface(anInterface, name, params);
if (res!=null) {
return res;
}
}
return findDefaultMethodFromInterface(cNode.getSuperClass(), name, params);
}
|
java
|
private static MethodNode findDefaultMethodFromInterface(final ClassNode cNode, final String name, final Parameter[] params) {
if (cNode == null) {
return null;
}
if (cNode.isInterface()) {
MethodNode method = cNode.getMethod(name, params);
if (method!=null && !method.isAbstract()) {
// this is a Java 8 only behavior!
return method;
}
}
ClassNode[] interfaces = cNode.getInterfaces();
for (ClassNode anInterface : interfaces) {
MethodNode res = findDefaultMethodFromInterface(anInterface, name, params);
if (res!=null) {
return res;
}
}
return findDefaultMethodFromInterface(cNode.getSuperClass(), name, params);
}
|
[
"private",
"static",
"MethodNode",
"findDefaultMethodFromInterface",
"(",
"final",
"ClassNode",
"cNode",
",",
"final",
"String",
"name",
",",
"final",
"Parameter",
"[",
"]",
"params",
")",
"{",
"if",
"(",
"cNode",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"cNode",
".",
"isInterface",
"(",
")",
")",
"{",
"MethodNode",
"method",
"=",
"cNode",
".",
"getMethod",
"(",
"name",
",",
"params",
")",
";",
"if",
"(",
"method",
"!=",
"null",
"&&",
"!",
"method",
".",
"isAbstract",
"(",
")",
")",
"{",
"// this is a Java 8 only behavior!",
"return",
"method",
";",
"}",
"}",
"ClassNode",
"[",
"]",
"interfaces",
"=",
"cNode",
".",
"getInterfaces",
"(",
")",
";",
"for",
"(",
"ClassNode",
"anInterface",
":",
"interfaces",
")",
"{",
"MethodNode",
"res",
"=",
"findDefaultMethodFromInterface",
"(",
"anInterface",
",",
"name",
",",
"params",
")",
";",
"if",
"(",
"res",
"!=",
"null",
")",
"{",
"return",
"res",
";",
"}",
"}",
"return",
"findDefaultMethodFromInterface",
"(",
"cNode",
".",
"getSuperClass",
"(",
")",
",",
"name",
",",
"params",
")",
";",
"}"
] |
An utility method which tries to find a method with default implementation (in the Java 8 semantics).
@param cNode a class node
@param name the name of the method
@param params the parameters of the method
@return a method node corresponding to a default method if it exists
|
[
"An",
"utility",
"method",
"which",
"tries",
"to",
"find",
"a",
"method",
"with",
"default",
"implementation",
"(",
"in",
"the",
"Java",
"8",
"semantics",
")",
"."
] |
train
|
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/trait/TraitComposer.java#L500-L519
|
Samsung/GearVRf
|
GVRf/Framework/framework/src/main/java/org/gearvrf/io/GVRCursorController.java
|
GVRCursorController.updatePicker
|
protected void updatePicker(MotionEvent event, boolean isActive) {
"""
Update the state of the picker. If it has an owner, the picker
will use that object to derive its position and orientation.
The "active" state of this controller is used to indicate touch.
The cursor position is updated after picking.
"""
final MotionEvent newEvent = (event != null) ? event : null;
final ControllerPick controllerPick = new ControllerPick(mPicker, newEvent, isActive);
context.runOnGlThread(controllerPick);
}
|
java
|
protected void updatePicker(MotionEvent event, boolean isActive)
{
final MotionEvent newEvent = (event != null) ? event : null;
final ControllerPick controllerPick = new ControllerPick(mPicker, newEvent, isActive);
context.runOnGlThread(controllerPick);
}
|
[
"protected",
"void",
"updatePicker",
"(",
"MotionEvent",
"event",
",",
"boolean",
"isActive",
")",
"{",
"final",
"MotionEvent",
"newEvent",
"=",
"(",
"event",
"!=",
"null",
")",
"?",
"event",
":",
"null",
";",
"final",
"ControllerPick",
"controllerPick",
"=",
"new",
"ControllerPick",
"(",
"mPicker",
",",
"newEvent",
",",
"isActive",
")",
";",
"context",
".",
"runOnGlThread",
"(",
"controllerPick",
")",
";",
"}"
] |
Update the state of the picker. If it has an owner, the picker
will use that object to derive its position and orientation.
The "active" state of this controller is used to indicate touch.
The cursor position is updated after picking.
|
[
"Update",
"the",
"state",
"of",
"the",
"picker",
".",
"If",
"it",
"has",
"an",
"owner",
"the",
"picker",
"will",
"use",
"that",
"object",
"to",
"derive",
"its",
"position",
"and",
"orientation",
".",
"The",
"active",
"state",
"of",
"this",
"controller",
"is",
"used",
"to",
"indicate",
"touch",
".",
"The",
"cursor",
"position",
"is",
"updated",
"after",
"picking",
"."
] |
train
|
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/io/GVRCursorController.java#L1120-L1125
|
aragozin/jvm-tools
|
sjk-core/src/main/java/org/gridkit/jvmtool/cmd/AntPathMatcher.java
|
AntPathMatcher.matchStrings
|
private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) {
"""
Tests whether or not a string matches against a pattern. The pattern may contain two special characters:
<br>'*' means zero or more characters
<br>'?' means one and only one character
@param pattern pattern to match against. Must not be {@code null}.
@param str string which must be matched against the pattern. Must not be {@code null}.
@return {@code true} if the string matches against the pattern, or {@code false} otherwise.
"""
AntPathStringMatcher matcher = this.stringMatcherCache.get(pattern);
if (matcher == null) {
matcher = new AntPathStringMatcher(pattern);
this.stringMatcherCache.put(pattern, matcher);
}
return matcher.matchStrings(str, uriTemplateVariables);
}
|
java
|
private boolean matchStrings(String pattern, String str, Map<String, String> uriTemplateVariables) {
AntPathStringMatcher matcher = this.stringMatcherCache.get(pattern);
if (matcher == null) {
matcher = new AntPathStringMatcher(pattern);
this.stringMatcherCache.put(pattern, matcher);
}
return matcher.matchStrings(str, uriTemplateVariables);
}
|
[
"private",
"boolean",
"matchStrings",
"(",
"String",
"pattern",
",",
"String",
"str",
",",
"Map",
"<",
"String",
",",
"String",
">",
"uriTemplateVariables",
")",
"{",
"AntPathStringMatcher",
"matcher",
"=",
"this",
".",
"stringMatcherCache",
".",
"get",
"(",
"pattern",
")",
";",
"if",
"(",
"matcher",
"==",
"null",
")",
"{",
"matcher",
"=",
"new",
"AntPathStringMatcher",
"(",
"pattern",
")",
";",
"this",
".",
"stringMatcherCache",
".",
"put",
"(",
"pattern",
",",
"matcher",
")",
";",
"}",
"return",
"matcher",
".",
"matchStrings",
"(",
"str",
",",
"uriTemplateVariables",
")",
";",
"}"
] |
Tests whether or not a string matches against a pattern. The pattern may contain two special characters:
<br>'*' means zero or more characters
<br>'?' means one and only one character
@param pattern pattern to match against. Must not be {@code null}.
@param str string which must be matched against the pattern. Must not be {@code null}.
@return {@code true} if the string matches against the pattern, or {@code false} otherwise.
|
[
"Tests",
"whether",
"or",
"not",
"a",
"string",
"matches",
"against",
"a",
"pattern",
".",
"The",
"pattern",
"may",
"contain",
"two",
"special",
"characters",
":",
"<br",
">",
"*",
"means",
"zero",
"or",
"more",
"characters",
"<br",
">",
"?",
"means",
"one",
"and",
"only",
"one",
"character"
] |
train
|
https://github.com/aragozin/jvm-tools/blob/d3a4d0c6a47fb9317f274988569655f30dcd2f76/sjk-core/src/main/java/org/gridkit/jvmtool/cmd/AntPathMatcher.java#L285-L292
|
biojava/biojava
|
biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java
|
UnitQuaternions.orientationMetric
|
public static double orientationMetric(Point3d[] a, Point3d[] b) {
"""
The orientation metric is obtained by comparing the quaternion
orientations of the principal axes of each set of points in 3D.
<p>
First, the quaternion orientation of each set of points is calculated
using their principal axes with {@link #orientation(Point3d[])}. Then,
the two quaternions are compared using the method
{@link #orientationMetric(Quat4d, Quat4d)}.
<p>
A requisite for this method to work properly is that both sets of points
have to define the same shape (or very low RMSD), otherwise some of the
principal axes might change or be inverted, resulting in an unreliable
metric. For shapes with some deviations in their shape, use the metric
{@link #orientationAngle(Point3d[], Point3d[])}.
@param a
array of Point3d
@param b
array of Point3d
@return the quaternion orientation metric
"""
Quat4d qa = orientation(a);
Quat4d qb = orientation(b);
return orientationMetric(qa, qb);
}
|
java
|
public static double orientationMetric(Point3d[] a, Point3d[] b) {
Quat4d qa = orientation(a);
Quat4d qb = orientation(b);
return orientationMetric(qa, qb);
}
|
[
"public",
"static",
"double",
"orientationMetric",
"(",
"Point3d",
"[",
"]",
"a",
",",
"Point3d",
"[",
"]",
"b",
")",
"{",
"Quat4d",
"qa",
"=",
"orientation",
"(",
"a",
")",
";",
"Quat4d",
"qb",
"=",
"orientation",
"(",
"b",
")",
";",
"return",
"orientationMetric",
"(",
"qa",
",",
"qb",
")",
";",
"}"
] |
The orientation metric is obtained by comparing the quaternion
orientations of the principal axes of each set of points in 3D.
<p>
First, the quaternion orientation of each set of points is calculated
using their principal axes with {@link #orientation(Point3d[])}. Then,
the two quaternions are compared using the method
{@link #orientationMetric(Quat4d, Quat4d)}.
<p>
A requisite for this method to work properly is that both sets of points
have to define the same shape (or very low RMSD), otherwise some of the
principal axes might change or be inverted, resulting in an unreliable
metric. For shapes with some deviations in their shape, use the metric
{@link #orientationAngle(Point3d[], Point3d[])}.
@param a
array of Point3d
@param b
array of Point3d
@return the quaternion orientation metric
|
[
"The",
"orientation",
"metric",
"is",
"obtained",
"by",
"comparing",
"the",
"quaternion",
"orientations",
"of",
"the",
"principal",
"axes",
"of",
"each",
"set",
"of",
"points",
"in",
"3D",
".",
"<p",
">",
"First",
"the",
"quaternion",
"orientation",
"of",
"each",
"set",
"of",
"points",
"is",
"calculated",
"using",
"their",
"principal",
"axes",
"with",
"{",
"@link",
"#orientation",
"(",
"Point3d",
"[]",
")",
"}",
".",
"Then",
"the",
"two",
"quaternions",
"are",
"compared",
"using",
"the",
"method",
"{",
"@link",
"#orientationMetric",
"(",
"Quat4d",
"Quat4d",
")",
"}",
".",
"<p",
">",
"A",
"requisite",
"for",
"this",
"method",
"to",
"work",
"properly",
"is",
"that",
"both",
"sets",
"of",
"points",
"have",
"to",
"define",
"the",
"same",
"shape",
"(",
"or",
"very",
"low",
"RMSD",
")",
"otherwise",
"some",
"of",
"the",
"principal",
"axes",
"might",
"change",
"or",
"be",
"inverted",
"resulting",
"in",
"an",
"unreliable",
"metric",
".",
"For",
"shapes",
"with",
"some",
"deviations",
"in",
"their",
"shape",
"use",
"the",
"metric",
"{",
"@link",
"#orientationAngle",
"(",
"Point3d",
"[]",
"Point3d",
"[]",
")",
"}",
"."
] |
train
|
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java#L72-L78
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.jmx.request/src/com/ibm/ws/jmx/request/RequestMetadata.java
|
RequestMetadata.initialize
|
private void initialize(Map<String, Object> metadata) {
"""
Generates a new metadata Map if none is given. Generates and adds a
request ID to the metadata.
@param metadata the metadata for a request
"""
if (metadata == null) {
metadata = new HashMap<String, Object>();
}
metadata.put(REQUEST_ID, generateRequestID());
this.metadata = metadata;
}
|
java
|
private void initialize(Map<String, Object> metadata) {
if (metadata == null) {
metadata = new HashMap<String, Object>();
}
metadata.put(REQUEST_ID, generateRequestID());
this.metadata = metadata;
}
|
[
"private",
"void",
"initialize",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"metadata",
")",
"{",
"if",
"(",
"metadata",
"==",
"null",
")",
"{",
"metadata",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"}",
"metadata",
".",
"put",
"(",
"REQUEST_ID",
",",
"generateRequestID",
"(",
")",
")",
";",
"this",
".",
"metadata",
"=",
"metadata",
";",
"}"
] |
Generates a new metadata Map if none is given. Generates and adds a
request ID to the metadata.
@param metadata the metadata for a request
|
[
"Generates",
"a",
"new",
"metadata",
"Map",
"if",
"none",
"is",
"given",
".",
"Generates",
"and",
"adds",
"a",
"request",
"ID",
"to",
"the",
"metadata",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.request/src/com/ibm/ws/jmx/request/RequestMetadata.java#L55-L61
|
codeprimate-software/cp-elements
|
src/main/java/org/cp/elements/util/CollectionUtils.java
|
CollectionUtils.findOne
|
public static <T> T findOne(Iterable<T> iterable, Filter<T> filter) {
"""
Searches the {@link Iterable} for the first element accepted by the {@link Filter}.
@param <T> Class type of the elements in the {@link Iterable}.
@param iterable {@link Iterable} collection of elements to search.
@param filter {@link Filter} used to find the first element from the {@link Iterable} accepted
by the {@link Filter}.
@return the first element from the {@link Iterable} accepted by the {@link Filter}, or {@literal null}
if no such element is found.
@throws IllegalArgumentException if {@link Filter} is null.
@see #findAll(Iterable, Filter)
@see #nullSafeIterable(Iterable)
@see org.cp.elements.lang.Filter
@see java.lang.Iterable
"""
Assert.notNull(filter, "Filter is required");
return StreamSupport.stream(nullSafeIterable(iterable).spliterator(), false)
.filter(filter::accept)
.findFirst().orElse(null);
}
|
java
|
public static <T> T findOne(Iterable<T> iterable, Filter<T> filter) {
Assert.notNull(filter, "Filter is required");
return StreamSupport.stream(nullSafeIterable(iterable).spliterator(), false)
.filter(filter::accept)
.findFirst().orElse(null);
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"findOne",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
",",
"Filter",
"<",
"T",
">",
"filter",
")",
"{",
"Assert",
".",
"notNull",
"(",
"filter",
",",
"\"Filter is required\"",
")",
";",
"return",
"StreamSupport",
".",
"stream",
"(",
"nullSafeIterable",
"(",
"iterable",
")",
".",
"spliterator",
"(",
")",
",",
"false",
")",
".",
"filter",
"(",
"filter",
"::",
"accept",
")",
".",
"findFirst",
"(",
")",
".",
"orElse",
"(",
"null",
")",
";",
"}"
] |
Searches the {@link Iterable} for the first element accepted by the {@link Filter}.
@param <T> Class type of the elements in the {@link Iterable}.
@param iterable {@link Iterable} collection of elements to search.
@param filter {@link Filter} used to find the first element from the {@link Iterable} accepted
by the {@link Filter}.
@return the first element from the {@link Iterable} accepted by the {@link Filter}, or {@literal null}
if no such element is found.
@throws IllegalArgumentException if {@link Filter} is null.
@see #findAll(Iterable, Filter)
@see #nullSafeIterable(Iterable)
@see org.cp.elements.lang.Filter
@see java.lang.Iterable
|
[
"Searches",
"the",
"{",
"@link",
"Iterable",
"}",
"for",
"the",
"first",
"element",
"accepted",
"by",
"the",
"{",
"@link",
"Filter",
"}",
"."
] |
train
|
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/CollectionUtils.java#L415-L422
|
GistLabs/mechanize
|
src/main/java/com/gistlabs/mechanize/util/apache/URLEncodedUtils.java
|
URLEncodedUtils.encFragment
|
static String encFragment(final String content, final Charset charset) {
"""
Encode a String using the {@link #FRAGMENT} set of characters.
<p>
Used by URIBuilder to encode the userinfo segment.
@param content the string to encode, does not convert space to '+'
@param charset the charset to use
@return the encoded string
"""
return urlencode(content, charset, FRAGMENT, false);
}
|
java
|
static String encFragment(final String content, final Charset charset) {
return urlencode(content, charset, FRAGMENT, false);
}
|
[
"static",
"String",
"encFragment",
"(",
"final",
"String",
"content",
",",
"final",
"Charset",
"charset",
")",
"{",
"return",
"urlencode",
"(",
"content",
",",
"charset",
",",
"FRAGMENT",
",",
"false",
")",
";",
"}"
] |
Encode a String using the {@link #FRAGMENT} set of characters.
<p>
Used by URIBuilder to encode the userinfo segment.
@param content the string to encode, does not convert space to '+'
@param charset the charset to use
@return the encoded string
|
[
"Encode",
"a",
"String",
"using",
"the",
"{",
"@link",
"#FRAGMENT",
"}",
"set",
"of",
"characters",
".",
"<p",
">",
"Used",
"by",
"URIBuilder",
"to",
"encode",
"the",
"userinfo",
"segment",
"."
] |
train
|
https://github.com/GistLabs/mechanize/blob/32ddd0774439a4c08513c05d7ac7416a3899efed/src/main/java/com/gistlabs/mechanize/util/apache/URLEncodedUtils.java#L507-L509
|
Impetus/Kundera
|
src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java
|
OracleNoSQLClient.findByRelation
|
@Override
public List<Object> findByRelation(String colName, Object colValue, Class entityClazz) {
"""
Find by relational column name and value.
@param colName
the col name
@param colValue
the col value
@param entityClazz
the entity clazz
@return the list
"""
// find by relational value !
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
entityMetadata.getPersistenceUnit());
EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());
Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());
Iterator<Row> rowsIter = null;
if (schemaTable.getPrimaryKey().contains(colName))
{
PrimaryKey rowKey = schemaTable.createPrimaryKey();
NoSqlDBUtils.add(schemaTable.getField(colName), rowKey, colValue, colName);
rowsIter = tableAPI.tableIterator(rowKey, null, null);
}
else
{
Index index = schemaTable.getIndex(colName);
IndexKey indexKey = index.createIndexKey();
NoSqlDBUtils.add(schemaTable.getField(colName), indexKey, colValue, colName);
rowsIter = tableAPI.tableIterator(indexKey, null, null);
}
try
{
Map<String, Object> relationMap = initialize(entityMetadata);
return scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap, null);
}
catch (Exception e)
{
log.error("Error while finding data for Key " + colName + ", Caused By :" + e + ".");
throw new PersistenceException(e);
}
}
|
java
|
@Override
public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
{
// find by relational value !
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
entityMetadata.getPersistenceUnit());
EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());
Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());
Iterator<Row> rowsIter = null;
if (schemaTable.getPrimaryKey().contains(colName))
{
PrimaryKey rowKey = schemaTable.createPrimaryKey();
NoSqlDBUtils.add(schemaTable.getField(colName), rowKey, colValue, colName);
rowsIter = tableAPI.tableIterator(rowKey, null, null);
}
else
{
Index index = schemaTable.getIndex(colName);
IndexKey indexKey = index.createIndexKey();
NoSqlDBUtils.add(schemaTable.getField(colName), indexKey, colValue, colName);
rowsIter = tableAPI.tableIterator(indexKey, null, null);
}
try
{
Map<String, Object> relationMap = initialize(entityMetadata);
return scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap, null);
}
catch (Exception e)
{
log.error("Error while finding data for Key " + colName + ", Caused By :" + e + ".");
throw new PersistenceException(e);
}
}
|
[
"@",
"Override",
"public",
"List",
"<",
"Object",
">",
"findByRelation",
"(",
"String",
"colName",
",",
"Object",
"colValue",
",",
"Class",
"entityClazz",
")",
"{",
"// find by relational value !",
"EntityMetadata",
"entityMetadata",
"=",
"KunderaMetadataManager",
".",
"getEntityMetadata",
"(",
"kunderaMetadata",
",",
"entityClazz",
")",
";",
"MetamodelImpl",
"metamodel",
"=",
"(",
"MetamodelImpl",
")",
"KunderaMetadataManager",
".",
"getMetamodel",
"(",
"kunderaMetadata",
",",
"entityMetadata",
".",
"getPersistenceUnit",
"(",
")",
")",
";",
"EntityType",
"entityType",
"=",
"metamodel",
".",
"entity",
"(",
"entityMetadata",
".",
"getEntityClazz",
"(",
")",
")",
";",
"Table",
"schemaTable",
"=",
"tableAPI",
".",
"getTable",
"(",
"entityMetadata",
".",
"getTableName",
"(",
")",
")",
";",
"Iterator",
"<",
"Row",
">",
"rowsIter",
"=",
"null",
";",
"if",
"(",
"schemaTable",
".",
"getPrimaryKey",
"(",
")",
".",
"contains",
"(",
"colName",
")",
")",
"{",
"PrimaryKey",
"rowKey",
"=",
"schemaTable",
".",
"createPrimaryKey",
"(",
")",
";",
"NoSqlDBUtils",
".",
"add",
"(",
"schemaTable",
".",
"getField",
"(",
"colName",
")",
",",
"rowKey",
",",
"colValue",
",",
"colName",
")",
";",
"rowsIter",
"=",
"tableAPI",
".",
"tableIterator",
"(",
"rowKey",
",",
"null",
",",
"null",
")",
";",
"}",
"else",
"{",
"Index",
"index",
"=",
"schemaTable",
".",
"getIndex",
"(",
"colName",
")",
";",
"IndexKey",
"indexKey",
"=",
"index",
".",
"createIndexKey",
"(",
")",
";",
"NoSqlDBUtils",
".",
"add",
"(",
"schemaTable",
".",
"getField",
"(",
"colName",
")",
",",
"indexKey",
",",
"colValue",
",",
"colName",
")",
";",
"rowsIter",
"=",
"tableAPI",
".",
"tableIterator",
"(",
"indexKey",
",",
"null",
",",
"null",
")",
";",
"}",
"try",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"relationMap",
"=",
"initialize",
"(",
"entityMetadata",
")",
";",
"return",
"scrollAndPopulate",
"(",
"null",
",",
"entityMetadata",
",",
"metamodel",
",",
"schemaTable",
",",
"rowsIter",
",",
"relationMap",
",",
"null",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Error while finding data for Key \"",
"+",
"colName",
"+",
"\", Caused By :\"",
"+",
"e",
"+",
"\".\"",
")",
";",
"throw",
"new",
"PersistenceException",
"(",
"e",
")",
";",
"}",
"}"
] |
Find by relational column name and value.
@param colName
the col name
@param colValue
the col value
@param entityClazz
the entity clazz
@return the list
|
[
"Find",
"by",
"relational",
"column",
"name",
"and",
"value",
"."
] |
train
|
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java#L715-L755
|
Hygieia/Hygieia
|
api/src/main/java/com/capitalone/dashboard/service/BusCompOwnerServiceImpl.java
|
BusCompOwnerServiceImpl.doesMatchFullName
|
private boolean doesMatchFullName(String firstName, String fullName) {
"""
Takes first name and full name and returns true or false if first name is found in full name
@param firstName
@param fullName
@return true or false if match found
"""
boolean matching = false;
if(firstName != null && !firstName.isEmpty() && fullName != null && !fullName.isEmpty()){
String firstFromCMDB;
String[] array = fullName.split(" ");
firstName = firstName.toLowerCase();
firstFromCMDB = array[0];
firstFromCMDB = firstFromCMDB.toLowerCase();
if(firstFromCMDB.length() < firstName.length()){
if(firstName.indexOf(firstFromCMDB) != -1){
matching = true;
}
}else if (firstFromCMDB.indexOf(firstName) != -1){
matching = true;
}
}
return matching;
}
|
java
|
private boolean doesMatchFullName(String firstName, String fullName){
boolean matching = false;
if(firstName != null && !firstName.isEmpty() && fullName != null && !fullName.isEmpty()){
String firstFromCMDB;
String[] array = fullName.split(" ");
firstName = firstName.toLowerCase();
firstFromCMDB = array[0];
firstFromCMDB = firstFromCMDB.toLowerCase();
if(firstFromCMDB.length() < firstName.length()){
if(firstName.indexOf(firstFromCMDB) != -1){
matching = true;
}
}else if (firstFromCMDB.indexOf(firstName) != -1){
matching = true;
}
}
return matching;
}
|
[
"private",
"boolean",
"doesMatchFullName",
"(",
"String",
"firstName",
",",
"String",
"fullName",
")",
"{",
"boolean",
"matching",
"=",
"false",
";",
"if",
"(",
"firstName",
"!=",
"null",
"&&",
"!",
"firstName",
".",
"isEmpty",
"(",
")",
"&&",
"fullName",
"!=",
"null",
"&&",
"!",
"fullName",
".",
"isEmpty",
"(",
")",
")",
"{",
"String",
"firstFromCMDB",
";",
"String",
"[",
"]",
"array",
"=",
"fullName",
".",
"split",
"(",
"\" \"",
")",
";",
"firstName",
"=",
"firstName",
".",
"toLowerCase",
"(",
")",
";",
"firstFromCMDB",
"=",
"array",
"[",
"0",
"]",
";",
"firstFromCMDB",
"=",
"firstFromCMDB",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"firstFromCMDB",
".",
"length",
"(",
")",
"<",
"firstName",
".",
"length",
"(",
")",
")",
"{",
"if",
"(",
"firstName",
".",
"indexOf",
"(",
"firstFromCMDB",
")",
"!=",
"-",
"1",
")",
"{",
"matching",
"=",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"firstFromCMDB",
".",
"indexOf",
"(",
"firstName",
")",
"!=",
"-",
"1",
")",
"{",
"matching",
"=",
"true",
";",
"}",
"}",
"return",
"matching",
";",
"}"
] |
Takes first name and full name and returns true or false if first name is found in full name
@param firstName
@param fullName
@return true or false if match found
|
[
"Takes",
"first",
"name",
"and",
"full",
"name",
"and",
"returns",
"true",
"or",
"false",
"if",
"first",
"name",
"is",
"found",
"in",
"full",
"name"
] |
train
|
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/BusCompOwnerServiceImpl.java#L134-L152
|
Azure/azure-sdk-for-java
|
resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourceGroupsInner.java
|
ResourceGroupsInner.updateAsync
|
public Observable<ResourceGroupInner> updateAsync(String resourceGroupName, ResourceGroupPatchable parameters) {
"""
Updates a resource group.
Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained.
@param resourceGroupName The name of the resource group to update. The name is case insensitive.
@param parameters Parameters supplied to update a resource group.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ResourceGroupInner object
"""
return updateWithServiceResponseAsync(resourceGroupName, parameters).map(new Func1<ServiceResponse<ResourceGroupInner>, ResourceGroupInner>() {
@Override
public ResourceGroupInner call(ServiceResponse<ResourceGroupInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<ResourceGroupInner> updateAsync(String resourceGroupName, ResourceGroupPatchable parameters) {
return updateWithServiceResponseAsync(resourceGroupName, parameters).map(new Func1<ServiceResponse<ResourceGroupInner>, ResourceGroupInner>() {
@Override
public ResourceGroupInner call(ServiceResponse<ResourceGroupInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"ResourceGroupInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"ResourceGroupPatchable",
"parameters",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ResourceGroupInner",
">",
",",
"ResourceGroupInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ResourceGroupInner",
"call",
"(",
"ServiceResponse",
"<",
"ResourceGroupInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates a resource group.
Resource groups can be updated through a simple PATCH operation to a group address. The format of the request is the same as that for creating a resource group. If a field is unspecified, the current value is retained.
@param resourceGroupName The name of the resource group to update. The name is case insensitive.
@param parameters Parameters supplied to update a resource group.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ResourceGroupInner object
|
[
"Updates",
"a",
"resource",
"group",
".",
"Resource",
"groups",
"can",
"be",
"updated",
"through",
"a",
"simple",
"PATCH",
"operation",
"to",
"a",
"group",
"address",
".",
"The",
"format",
"of",
"the",
"request",
"is",
"the",
"same",
"as",
"that",
"for",
"creating",
"a",
"resource",
"group",
".",
"If",
"a",
"field",
"is",
"unspecified",
"the",
"current",
"value",
"is",
"retained",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourceGroupsInner.java#L540-L547
|
btrplace/scheduler
|
btrpsl/src/main/java/org/btrplace/btrpsl/Script.java
|
Script.addExportable
|
public void addExportable(String name, BtrpOperand e, Set<String> scopes) {
"""
Add an external operand that can be accessed from several given scopes.
A scope is a namespace that can ends with a wildcard ('*'). In this situation. The beginning
of the scope is considered
@param name the name of the exported operand
@param e the operand to add
@param scopes the namespaces of the scripts that can use this variable. {@code null} to allow anyone
"""
this.exported.put(name, e);
this.exportScopes.put(name, scopes);
}
|
java
|
public void addExportable(String name, BtrpOperand e, Set<String> scopes) {
this.exported.put(name, e);
this.exportScopes.put(name, scopes);
}
|
[
"public",
"void",
"addExportable",
"(",
"String",
"name",
",",
"BtrpOperand",
"e",
",",
"Set",
"<",
"String",
">",
"scopes",
")",
"{",
"this",
".",
"exported",
".",
"put",
"(",
"name",
",",
"e",
")",
";",
"this",
".",
"exportScopes",
".",
"put",
"(",
"name",
",",
"scopes",
")",
";",
"}"
] |
Add an external operand that can be accessed from several given scopes.
A scope is a namespace that can ends with a wildcard ('*'). In this situation. The beginning
of the scope is considered
@param name the name of the exported operand
@param e the operand to add
@param scopes the namespaces of the scripts that can use this variable. {@code null} to allow anyone
|
[
"Add",
"an",
"external",
"operand",
"that",
"can",
"be",
"accessed",
"from",
"several",
"given",
"scopes",
".",
"A",
"scope",
"is",
"a",
"namespace",
"that",
"can",
"ends",
"with",
"a",
"wildcard",
"(",
"*",
")",
".",
"In",
"this",
"situation",
".",
"The",
"beginning",
"of",
"the",
"scope",
"is",
"considered"
] |
train
|
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/Script.java#L276-L279
|
alkacon/opencms-core
|
src-setup/org/opencms/setup/CmsSetupBean.java
|
CmsSetupBean.setDbParamaters
|
public boolean setDbParamaters(HttpServletRequest request, String provider) {
"""
Sets the needed database parameters.<p>
@param request the http request
@param provider the db provider
@return true if already submitted
"""
return setDbParamaters(request.getParameterMap(), provider, request.getContextPath(), request.getSession());
}
|
java
|
public boolean setDbParamaters(HttpServletRequest request, String provider) {
return setDbParamaters(request.getParameterMap(), provider, request.getContextPath(), request.getSession());
}
|
[
"public",
"boolean",
"setDbParamaters",
"(",
"HttpServletRequest",
"request",
",",
"String",
"provider",
")",
"{",
"return",
"setDbParamaters",
"(",
"request",
".",
"getParameterMap",
"(",
")",
",",
"provider",
",",
"request",
".",
"getContextPath",
"(",
")",
",",
"request",
".",
"getSession",
"(",
")",
")",
";",
"}"
] |
Sets the needed database parameters.<p>
@param request the http request
@param provider the db provider
@return true if already submitted
|
[
"Sets",
"the",
"needed",
"database",
"parameters",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/CmsSetupBean.java#L1933-L1936
|
Azure/azure-sdk-for-java
|
authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleAssignmentsInner.java
|
RoleAssignmentsInner.listForResourceAsync
|
public Observable<Page<RoleAssignmentInner>> listForResourceAsync(final String resourceGroupName, final String resourceProviderNamespace, final String parentResourcePath, final String resourceType, final String resourceName, final String filter) {
"""
Gets role assignments for a resource.
@param resourceGroupName The name of the resource group.
@param resourceProviderNamespace The namespace of the resource provider.
@param parentResourcePath The parent resource identity.
@param resourceType The resource type of the resource.
@param resourceName The name of the resource to get role assignments for.
@param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RoleAssignmentInner> object
"""
return listForResourceWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter)
.map(new Func1<ServiceResponse<Page<RoleAssignmentInner>>, Page<RoleAssignmentInner>>() {
@Override
public Page<RoleAssignmentInner> call(ServiceResponse<Page<RoleAssignmentInner>> response) {
return response.body();
}
});
}
|
java
|
public Observable<Page<RoleAssignmentInner>> listForResourceAsync(final String resourceGroupName, final String resourceProviderNamespace, final String parentResourcePath, final String resourceType, final String resourceName, final String filter) {
return listForResourceWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter)
.map(new Func1<ServiceResponse<Page<RoleAssignmentInner>>, Page<RoleAssignmentInner>>() {
@Override
public Page<RoleAssignmentInner> call(ServiceResponse<Page<RoleAssignmentInner>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"Page",
"<",
"RoleAssignmentInner",
">",
">",
"listForResourceAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"resourceProviderNamespace",
",",
"final",
"String",
"parentResourcePath",
",",
"final",
"String",
"resourceType",
",",
"final",
"String",
"resourceName",
",",
"final",
"String",
"filter",
")",
"{",
"return",
"listForResourceWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceProviderNamespace",
",",
"parentResourcePath",
",",
"resourceType",
",",
"resourceName",
",",
"filter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"RoleAssignmentInner",
">",
">",
",",
"Page",
"<",
"RoleAssignmentInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"RoleAssignmentInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"RoleAssignmentInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Gets role assignments for a resource.
@param resourceGroupName The name of the resource group.
@param resourceProviderNamespace The namespace of the resource provider.
@param parentResourcePath The parent resource identity.
@param resourceType The resource type of the resource.
@param resourceName The name of the resource to get role assignments for.
@param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<RoleAssignmentInner> object
|
[
"Gets",
"role",
"assignments",
"for",
"a",
"resource",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleAssignmentsInner.java#L328-L336
|
VoltDB/voltdb
|
src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java
|
JDBC4DatabaseMetaData.getColumns
|
@Override
public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException {
"""
Retrieves a description of table columns available in the specified catalog.
"""
checkClosed();
this.sysCatalog.setString(1, "COLUMNS");
JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
VoltTable vtable = res.getVoltTable().clone(0);
// If no pattern is specified, default to matching any/all.
if (tableNamePattern == null || tableNamePattern.length() == 0)
{
tableNamePattern = "%";
}
Pattern table_pattern = computeJavaPattern(tableNamePattern);
if (columnNamePattern == null || columnNamePattern.length() == 0)
{
columnNamePattern = "%";
}
Pattern column_pattern = computeJavaPattern(columnNamePattern);
// Filter columns based on table name and column name
while (res.next()) {
Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME"));
if (table_matcher.matches())
{
Matcher column_matcher = column_pattern.matcher(res.getString("COLUMN_NAME"));
if (column_matcher.matches())
{
vtable.addRow(res.getRowData());
}
}
}
return new JDBC4ResultSet(this.sysCatalog, vtable);
}
|
java
|
@Override
public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException
{
checkClosed();
this.sysCatalog.setString(1, "COLUMNS");
JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
VoltTable vtable = res.getVoltTable().clone(0);
// If no pattern is specified, default to matching any/all.
if (tableNamePattern == null || tableNamePattern.length() == 0)
{
tableNamePattern = "%";
}
Pattern table_pattern = computeJavaPattern(tableNamePattern);
if (columnNamePattern == null || columnNamePattern.length() == 0)
{
columnNamePattern = "%";
}
Pattern column_pattern = computeJavaPattern(columnNamePattern);
// Filter columns based on table name and column name
while (res.next()) {
Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME"));
if (table_matcher.matches())
{
Matcher column_matcher = column_pattern.matcher(res.getString("COLUMN_NAME"));
if (column_matcher.matches())
{
vtable.addRow(res.getRowData());
}
}
}
return new JDBC4ResultSet(this.sysCatalog, vtable);
}
|
[
"@",
"Override",
"public",
"ResultSet",
"getColumns",
"(",
"String",
"catalog",
",",
"String",
"schemaPattern",
",",
"String",
"tableNamePattern",
",",
"String",
"columnNamePattern",
")",
"throws",
"SQLException",
"{",
"checkClosed",
"(",
")",
";",
"this",
".",
"sysCatalog",
".",
"setString",
"(",
"1",
",",
"\"COLUMNS\"",
")",
";",
"JDBC4ResultSet",
"res",
"=",
"(",
"JDBC4ResultSet",
")",
"this",
".",
"sysCatalog",
".",
"executeQuery",
"(",
")",
";",
"VoltTable",
"vtable",
"=",
"res",
".",
"getVoltTable",
"(",
")",
".",
"clone",
"(",
"0",
")",
";",
"// If no pattern is specified, default to matching any/all.",
"if",
"(",
"tableNamePattern",
"==",
"null",
"||",
"tableNamePattern",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"tableNamePattern",
"=",
"\"%\"",
";",
"}",
"Pattern",
"table_pattern",
"=",
"computeJavaPattern",
"(",
"tableNamePattern",
")",
";",
"if",
"(",
"columnNamePattern",
"==",
"null",
"||",
"columnNamePattern",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"columnNamePattern",
"=",
"\"%\"",
";",
"}",
"Pattern",
"column_pattern",
"=",
"computeJavaPattern",
"(",
"columnNamePattern",
")",
";",
"// Filter columns based on table name and column name",
"while",
"(",
"res",
".",
"next",
"(",
")",
")",
"{",
"Matcher",
"table_matcher",
"=",
"table_pattern",
".",
"matcher",
"(",
"res",
".",
"getString",
"(",
"\"TABLE_NAME\"",
")",
")",
";",
"if",
"(",
"table_matcher",
".",
"matches",
"(",
")",
")",
"{",
"Matcher",
"column_matcher",
"=",
"column_pattern",
".",
"matcher",
"(",
"res",
".",
"getString",
"(",
"\"COLUMN_NAME\"",
")",
")",
";",
"if",
"(",
"column_matcher",
".",
"matches",
"(",
")",
")",
"{",
"vtable",
".",
"addRow",
"(",
"res",
".",
"getRowData",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"new",
"JDBC4ResultSet",
"(",
"this",
".",
"sysCatalog",
",",
"vtable",
")",
";",
"}"
] |
Retrieves a description of table columns available in the specified catalog.
|
[
"Retrieves",
"a",
"description",
"of",
"table",
"columns",
"available",
"in",
"the",
"specified",
"catalog",
"."
] |
train
|
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java#L196-L231
|
intuit/QuickBooks-V3-Java-SDK
|
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/BatchOperation.java
|
BatchOperation.addCDCQuery
|
public void addCDCQuery(List<? extends IEntity> entities, String changedSince, String bId) throws FMSException {
"""
Method to add the cdc query batch operation to batchItemRequest
@param entities the list of entities
@param changedSince the date where the entities should be listed from the last changed date
@param bId the batch Id
"""
if (entities == null || entities.isEmpty()) {
throw new FMSException("Entities is required.");
}
if (!StringUtils.hasText(changedSince)) {
throw new FMSException("changedSince is required.");
}
CDCQuery cdcQuery = new CDCQuery();
StringBuffer entityParam = new StringBuffer();
for (IEntity entity : entities) {
entityParam.append(entity.getClass().getSimpleName()).append(",");
}
entityParam.delete(entityParam.length() - 1, entityParam.length());
cdcQuery.setEntities(entityParam.toString());
try {
cdcQuery.setChangedSince(DateUtils.getDateFromString(changedSince));
} catch (ParseException e) {
LOG.error("ParseException while converting to Date.", e);
throw new FMSException("ParseException while converting to Date. Please provide valid DateTime (yyyy-MM-ddTHH:mm:ss.SSSZ).", e);
}
BatchItemRequest batchItemRequest = new BatchItemRequest();
batchItemRequest.setBId(bId);
batchItemRequest.setCDCQuery(cdcQuery);
batchItemRequests.add(batchItemRequest);
bIds.add(bId);
}
|
java
|
public void addCDCQuery(List<? extends IEntity> entities, String changedSince, String bId) throws FMSException {
if (entities == null || entities.isEmpty()) {
throw new FMSException("Entities is required.");
}
if (!StringUtils.hasText(changedSince)) {
throw new FMSException("changedSince is required.");
}
CDCQuery cdcQuery = new CDCQuery();
StringBuffer entityParam = new StringBuffer();
for (IEntity entity : entities) {
entityParam.append(entity.getClass().getSimpleName()).append(",");
}
entityParam.delete(entityParam.length() - 1, entityParam.length());
cdcQuery.setEntities(entityParam.toString());
try {
cdcQuery.setChangedSince(DateUtils.getDateFromString(changedSince));
} catch (ParseException e) {
LOG.error("ParseException while converting to Date.", e);
throw new FMSException("ParseException while converting to Date. Please provide valid DateTime (yyyy-MM-ddTHH:mm:ss.SSSZ).", e);
}
BatchItemRequest batchItemRequest = new BatchItemRequest();
batchItemRequest.setBId(bId);
batchItemRequest.setCDCQuery(cdcQuery);
batchItemRequests.add(batchItemRequest);
bIds.add(bId);
}
|
[
"public",
"void",
"addCDCQuery",
"(",
"List",
"<",
"?",
"extends",
"IEntity",
">",
"entities",
",",
"String",
"changedSince",
",",
"String",
"bId",
")",
"throws",
"FMSException",
"{",
"if",
"(",
"entities",
"==",
"null",
"||",
"entities",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"FMSException",
"(",
"\"Entities is required.\"",
")",
";",
"}",
"if",
"(",
"!",
"StringUtils",
".",
"hasText",
"(",
"changedSince",
")",
")",
"{",
"throw",
"new",
"FMSException",
"(",
"\"changedSince is required.\"",
")",
";",
"}",
"CDCQuery",
"cdcQuery",
"=",
"new",
"CDCQuery",
"(",
")",
";",
"StringBuffer",
"entityParam",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
"IEntity",
"entity",
":",
"entities",
")",
"{",
"entityParam",
".",
"append",
"(",
"entity",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
".",
"append",
"(",
"\",\"",
")",
";",
"}",
"entityParam",
".",
"delete",
"(",
"entityParam",
".",
"length",
"(",
")",
"-",
"1",
",",
"entityParam",
".",
"length",
"(",
")",
")",
";",
"cdcQuery",
".",
"setEntities",
"(",
"entityParam",
".",
"toString",
"(",
")",
")",
";",
"try",
"{",
"cdcQuery",
".",
"setChangedSince",
"(",
"DateUtils",
".",
"getDateFromString",
"(",
"changedSince",
")",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"ParseException while converting to Date.\"",
",",
"e",
")",
";",
"throw",
"new",
"FMSException",
"(",
"\"ParseException while converting to Date. Please provide valid DateTime (yyyy-MM-ddTHH:mm:ss.SSSZ).\"",
",",
"e",
")",
";",
"}",
"BatchItemRequest",
"batchItemRequest",
"=",
"new",
"BatchItemRequest",
"(",
")",
";",
"batchItemRequest",
".",
"setBId",
"(",
"bId",
")",
";",
"batchItemRequest",
".",
"setCDCQuery",
"(",
"cdcQuery",
")",
";",
"batchItemRequests",
".",
"add",
"(",
"batchItemRequest",
")",
";",
"bIds",
".",
"add",
"(",
"bId",
")",
";",
"}"
] |
Method to add the cdc query batch operation to batchItemRequest
@param entities the list of entities
@param changedSince the date where the entities should be listed from the last changed date
@param bId the batch Id
|
[
"Method",
"to",
"add",
"the",
"cdc",
"query",
"batch",
"operation",
"to",
"batchItemRequest"
] |
train
|
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/BatchOperation.java#L129-L161
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.