repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java | CmsContainerpageController.setElementView | public void setElementView(CmsElementViewInfo viewInfo, Runnable nextAction) {
if (viewInfo != null) {
m_elementView = viewInfo;
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
@SuppressWarnings("synthetic-access")
@Override
public void execute() {
getContainerpageService().setElementView(m_elementView.getElementViewId(), this);
}
@Override
protected void onResponse(Void result) {
// nothing to do
}
};
action.execute();
m_currentEditLevel = -1;
reinitializeButtons();
reInitInlineEditing();
updateGalleryData(true, nextAction);
}
} | java | public void setElementView(CmsElementViewInfo viewInfo, Runnable nextAction) {
if (viewInfo != null) {
m_elementView = viewInfo;
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
@SuppressWarnings("synthetic-access")
@Override
public void execute() {
getContainerpageService().setElementView(m_elementView.getElementViewId(), this);
}
@Override
protected void onResponse(Void result) {
// nothing to do
}
};
action.execute();
m_currentEditLevel = -1;
reinitializeButtons();
reInitInlineEditing();
updateGalleryData(true, nextAction);
}
} | [
"public",
"void",
"setElementView",
"(",
"CmsElementViewInfo",
"viewInfo",
",",
"Runnable",
"nextAction",
")",
"{",
"if",
"(",
"viewInfo",
"!=",
"null",
")",
"{",
"m_elementView",
"=",
"viewInfo",
";",
"CmsRpcAction",
"<",
"Void",
">",
"action",
"=",
"new",
... | Sets the element view.<p>
@param viewInfo the element view
@param nextAction the action to execute after setting the view | [
"Sets",
"the",
"element",
"view",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java#L3232-L3258 |
brutusin/commons | src/main/java/org/brutusin/commons/utils/Miscellaneous.java | Miscellaneous.formatFilePath | public static String formatFilePath(String filePath) {
if (filePath == null) {
return null;
}
return normalizePath(filePath.replaceAll("//*", "/").replaceAll("\\*", "\\").replaceAll("/", "\\" + System.getProperty("file.separator")).replaceAll("\\\\", "\\" + System.getProperty("file.separator")), System.getProperty("file.separator").equals("/"));
} | java | public static String formatFilePath(String filePath) {
if (filePath == null) {
return null;
}
return normalizePath(filePath.replaceAll("//*", "/").replaceAll("\\*", "\\").replaceAll("/", "\\" + System.getProperty("file.separator")).replaceAll("\\\\", "\\" + System.getProperty("file.separator")), System.getProperty("file.separator").equals("/"));
} | [
"public",
"static",
"String",
"formatFilePath",
"(",
"String",
"filePath",
")",
"{",
"if",
"(",
"filePath",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"normalizePath",
"(",
"filePath",
".",
"replaceAll",
"(",
"\"//*\"",
",",
"\"/\"",
")"... | Replaces all "\" and "/" in the specified file path by
<code>file.separator</code> system property.
@param filePath the original file path.
@return the formatted file path. | [
"Replaces",
"all",
"\\",
"and",
"/",
"in",
"the",
"specified",
"file",
"path",
"by",
"<code",
">",
"file",
".",
"separator<",
"/",
"code",
">",
"system",
"property",
"."
] | train | https://github.com/brutusin/commons/blob/70685df2b2456d0bf1e6a4754d72c87bba4949df/src/main/java/org/brutusin/commons/utils/Miscellaneous.java#L565-L571 |
notnoop/java-apns | src/main/java/com/notnoop/apns/ApnsServiceBuilder.java | ApnsServiceBuilder.asBatched | public ApnsServiceBuilder asBatched(int waitTimeInSec, int maxWaitTimeInSec, ThreadFactory threadFactory) {
return asBatched(waitTimeInSec, maxWaitTimeInSec, new ScheduledThreadPoolExecutor(1, threadFactory != null ? threadFactory : defaultThreadFactory()));
} | java | public ApnsServiceBuilder asBatched(int waitTimeInSec, int maxWaitTimeInSec, ThreadFactory threadFactory) {
return asBatched(waitTimeInSec, maxWaitTimeInSec, new ScheduledThreadPoolExecutor(1, threadFactory != null ? threadFactory : defaultThreadFactory()));
} | [
"public",
"ApnsServiceBuilder",
"asBatched",
"(",
"int",
"waitTimeInSec",
",",
"int",
"maxWaitTimeInSec",
",",
"ThreadFactory",
"threadFactory",
")",
"{",
"return",
"asBatched",
"(",
"waitTimeInSec",
",",
"maxWaitTimeInSec",
",",
"new",
"ScheduledThreadPoolExecutor",
"(... | Construct service which will process notification requests in batch.
After each request batch will wait <code>waitTimeInSec</code> for more request to come
before executing but not more than <code>maxWaitTimeInSec</code>
Each batch creates new connection and close it after finished.
In case reconnect policy is specified it will be applied by batch processing.
E.g.: {@link ReconnectPolicy.Provided#EVERY_HALF_HOUR} will reconnect the connection in case batch is running for more than half an hour
Note: It is not recommended to use pooled connection
@param waitTimeInSec
time to wait for more notification request before executing
batch
@param maxWaitTimeInSec
maximum wait time for batch before executing
@param threadFactory
thread factory to use for batch processing | [
"Construct",
"service",
"which",
"will",
"process",
"notification",
"requests",
"in",
"batch",
".",
"After",
"each",
"request",
"batch",
"will",
"wait",
"<code",
">",
"waitTimeInSec<",
"/",
"code",
">",
"for",
"more",
"request",
"to",
"come",
"before",
"execut... | train | https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/ApnsServiceBuilder.java#L641-L643 |
Falydoor/limesurvey-rc | src/main/java/com/github/falydoor/limesurveyrc/LimesurveyRC.java | LimesurveyRC.getQuestionAnswers | public Map<String, LsQuestionAnswer> getQuestionAnswers(int questionId) throws LimesurveyRCException {
LsApiBody.LsApiParams params = getParamsWithKey();
params.setQuestionId(questionId);
List<String> questionSettings = new ArrayList<>();
questionSettings.add("answeroptions");
params.setQuestionSettings(questionSettings);
JsonElement result = callRC(new LsApiBody("get_question_properties", params)).getAsJsonObject().get("answeroptions");
return gson.fromJson(result, new TypeToken<Map<String, LsQuestionAnswer>>() {
}.getType());
} | java | public Map<String, LsQuestionAnswer> getQuestionAnswers(int questionId) throws LimesurveyRCException {
LsApiBody.LsApiParams params = getParamsWithKey();
params.setQuestionId(questionId);
List<String> questionSettings = new ArrayList<>();
questionSettings.add("answeroptions");
params.setQuestionSettings(questionSettings);
JsonElement result = callRC(new LsApiBody("get_question_properties", params)).getAsJsonObject().get("answeroptions");
return gson.fromJson(result, new TypeToken<Map<String, LsQuestionAnswer>>() {
}.getType());
} | [
"public",
"Map",
"<",
"String",
",",
"LsQuestionAnswer",
">",
"getQuestionAnswers",
"(",
"int",
"questionId",
")",
"throws",
"LimesurveyRCException",
"{",
"LsApiBody",
".",
"LsApiParams",
"params",
"=",
"getParamsWithKey",
"(",
")",
";",
"params",
".",
"setQuestio... | Gets possible answers from a question.
@param questionId the question id you want to get the answers
@return the answers of the question
@throws LimesurveyRCException the limesurvey rc exception | [
"Gets",
"possible",
"answers",
"from",
"a",
"question",
"."
] | train | https://github.com/Falydoor/limesurvey-rc/blob/b8d573389086395e46a0bdeeddeef4d1c2c0a488/src/main/java/com/github/falydoor/limesurveyrc/LimesurveyRC.java#L235-L245 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/TaskInProgress.java | TaskInProgress.addDiagnosticInfo | public void addDiagnosticInfo(TaskAttemptID taskId, String diagInfo) {
List<String> diagHistory = taskDiagnosticData.get(taskId);
if (diagHistory == null) {
diagHistory = new ArrayList<String>();
taskDiagnosticData.put(taskId, diagHistory);
}
diagHistory.add(diagInfo);
} | java | public void addDiagnosticInfo(TaskAttemptID taskId, String diagInfo) {
List<String> diagHistory = taskDiagnosticData.get(taskId);
if (diagHistory == null) {
diagHistory = new ArrayList<String>();
taskDiagnosticData.put(taskId, diagHistory);
}
diagHistory.add(diagInfo);
} | [
"public",
"void",
"addDiagnosticInfo",
"(",
"TaskAttemptID",
"taskId",
",",
"String",
"diagInfo",
")",
"{",
"List",
"<",
"String",
">",
"diagHistory",
"=",
"taskDiagnosticData",
".",
"get",
"(",
"taskId",
")",
";",
"if",
"(",
"diagHistory",
"==",
"null",
")"... | Save diagnostic information for a given task.
@param taskId id of the task
@param diagInfo diagnostic information for the task | [
"Save",
"diagnostic",
"information",
"for",
"a",
"given",
"task",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskInProgress.java#L675-L682 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2016_06_27_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2016_06_27_preview/implementation/RegistriesInner.java | RegistriesInner.createOrUpdateAsync | public Observable<RegistryInner> createOrUpdateAsync(String resourceGroupName, String registryName, RegistryInner registry) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, registryName, registry).map(new Func1<ServiceResponse<RegistryInner>, RegistryInner>() {
@Override
public RegistryInner call(ServiceResponse<RegistryInner> response) {
return response.body();
}
});
} | java | public Observable<RegistryInner> createOrUpdateAsync(String resourceGroupName, String registryName, RegistryInner registry) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, registryName, registry).map(new Func1<ServiceResponse<RegistryInner>, RegistryInner>() {
@Override
public RegistryInner call(ServiceResponse<RegistryInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RegistryInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"RegistryInner",
"registry",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"reg... | Creates or updates a container registry 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 registry The parameters for creating or updating a container registry.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RegistryInner object | [
"Creates",
"or",
"updates",
"a",
"container",
"registry",
"with",
"the",
"specified",
"parameters",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2016_06_27_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2016_06_27_preview/implementation/RegistriesInner.java#L322-L329 |
square/phrase | src/main/java/com/squareup/phrase/ListPhrase.java | ListPhrase.from | @NonNull public static ListPhrase from(@NonNull CharSequence twoElementSeparator,
CharSequence nonFinalElementSeparator, CharSequence finalElementSeparator) {
return new ListPhrase(twoElementSeparator, nonFinalElementSeparator, finalElementSeparator);
} | java | @NonNull public static ListPhrase from(@NonNull CharSequence twoElementSeparator,
CharSequence nonFinalElementSeparator, CharSequence finalElementSeparator) {
return new ListPhrase(twoElementSeparator, nonFinalElementSeparator, finalElementSeparator);
} | [
"@",
"NonNull",
"public",
"static",
"ListPhrase",
"from",
"(",
"@",
"NonNull",
"CharSequence",
"twoElementSeparator",
",",
"CharSequence",
"nonFinalElementSeparator",
",",
"CharSequence",
"finalElementSeparator",
")",
"{",
"return",
"new",
"ListPhrase",
"(",
"twoElement... | Entry point into this API.
@param twoElementSeparator separator for 2-element lists
@param nonFinalElementSeparator separator for non-final elements of lists with 3 or more
elements
@param finalElementSeparator separator for final elements in lists with 3 or more elements | [
"Entry",
"point",
"into",
"this",
"API",
"."
] | train | https://github.com/square/phrase/blob/d91f18e80790832db11b811c462f8e5cd492d97e/src/main/java/com/squareup/phrase/ListPhrase.java#L79-L82 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/utils/MjdbcUtils.java | MjdbcUtils.loadDriver | public static boolean loadDriver(ClassLoader classLoader, String driverClassName) {
try {
classLoader.loadClass(driverClassName).newInstance();
return true;
} catch (IllegalAccessException e) {
// Constructor is private, OK for DriverManager contract
return true;
} catch (Exception e) {
return false;
}
} | java | public static boolean loadDriver(ClassLoader classLoader, String driverClassName) {
try {
classLoader.loadClass(driverClassName).newInstance();
return true;
} catch (IllegalAccessException e) {
// Constructor is private, OK for DriverManager contract
return true;
} catch (Exception e) {
return false;
}
} | [
"public",
"static",
"boolean",
"loadDriver",
"(",
"ClassLoader",
"classLoader",
",",
"String",
"driverClassName",
")",
"{",
"try",
"{",
"classLoader",
".",
"loadClass",
"(",
"driverClassName",
")",
".",
"newInstance",
"(",
")",
";",
"return",
"true",
";",
"}",... | Loads and registers a database driver class.
If this succeeds, it returns true, else it returns false.
@param classLoader the class loader used to load the driver class
@param driverClassName of driver to load
@return boolean <code>true</code> if the driver was found, otherwise <code>false</code> | [
"Loads",
"and",
"registers",
"a",
"database",
"driver",
"class",
".",
"If",
"this",
"succeeds",
"it",
"returns",
"true",
"else",
"it",
"returns",
"false",
"."
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/utils/MjdbcUtils.java#L185-L198 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/variant/VariantUtils.java | VariantUtils.getVariantBundleName | public static String getVariantBundleName(String bundleName, String variantKey, boolean iGeneratedResource) {
String newName = bundleName;
if (StringUtils.isNotEmpty(variantKey)) {
int idxSeparator = bundleName.lastIndexOf('.');
if (!iGeneratedResource && idxSeparator != -1) {
newName = bundleName.substring(0, idxSeparator);
newName += JawrConstant.VARIANT_SEPARATOR_CHAR + variantKey;
newName += bundleName.substring(idxSeparator);
} else {
newName += JawrConstant.VARIANT_SEPARATOR_CHAR + variantKey;
}
}
return newName;
} | java | public static String getVariantBundleName(String bundleName, String variantKey, boolean iGeneratedResource) {
String newName = bundleName;
if (StringUtils.isNotEmpty(variantKey)) {
int idxSeparator = bundleName.lastIndexOf('.');
if (!iGeneratedResource && idxSeparator != -1) {
newName = bundleName.substring(0, idxSeparator);
newName += JawrConstant.VARIANT_SEPARATOR_CHAR + variantKey;
newName += bundleName.substring(idxSeparator);
} else {
newName += JawrConstant.VARIANT_SEPARATOR_CHAR + variantKey;
}
}
return newName;
} | [
"public",
"static",
"String",
"getVariantBundleName",
"(",
"String",
"bundleName",
",",
"String",
"variantKey",
",",
"boolean",
"iGeneratedResource",
")",
"{",
"String",
"newName",
"=",
"bundleName",
";",
"if",
"(",
"StringUtils",
".",
"isNotEmpty",
"(",
"variantK... | Get the bundle name taking in account the variant key
@param bundleName
the bundle name
@param variantKey
the variant key
@param iGeneratedResource
the flag indicating if it's a generated resource
@return the variant bundle name | [
"Get",
"the",
"bundle",
"name",
"taking",
"in",
"account",
"the",
"variant",
"key"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/variant/VariantUtils.java#L249-L264 |
uber/NullAway | nullaway/src/main/java/com/uber/nullaway/NullAway.java | NullAway.constructorInvokesAnother | private boolean constructorInvokesAnother(MethodTree constructor, VisitorState state) {
BlockTree body = constructor.getBody();
List<? extends StatementTree> statements = body.getStatements();
if (statements.size() > 0) {
StatementTree statementTree = statements.get(0);
if (isThisCall(statementTree, state)) {
return true;
}
}
return false;
} | java | private boolean constructorInvokesAnother(MethodTree constructor, VisitorState state) {
BlockTree body = constructor.getBody();
List<? extends StatementTree> statements = body.getStatements();
if (statements.size() > 0) {
StatementTree statementTree = statements.get(0);
if (isThisCall(statementTree, state)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"constructorInvokesAnother",
"(",
"MethodTree",
"constructor",
",",
"VisitorState",
"state",
")",
"{",
"BlockTree",
"body",
"=",
"constructor",
".",
"getBody",
"(",
")",
";",
"List",
"<",
"?",
"extends",
"StatementTree",
">",
"statements",
... | does the constructor invoke another constructor in the same class via this(...)? | [
"does",
"the",
"constructor",
"invoke",
"another",
"constructor",
"in",
"the",
"same",
"class",
"via",
"this",
"(",
"...",
")",
"?"
] | train | https://github.com/uber/NullAway/blob/c3979b4241f80411dbba6aac3ff653acbb88d00b/nullaway/src/main/java/com/uber/nullaway/NullAway.java#L1571-L1581 |
impossibl/stencil | engine/src/main/java/com/impossibl/stencil/engine/internal/StencilInterpreter.java | StencilInterpreter.getLocation | ExecutionLocation getLocation(ParserRuleContext object) {
Token start = object.getStart();
return new ExecutionLocation(currentScope.declaringEnvironment.path, start.getLine(), start.getCharPositionInLine() + 1);
} | java | ExecutionLocation getLocation(ParserRuleContext object) {
Token start = object.getStart();
return new ExecutionLocation(currentScope.declaringEnvironment.path, start.getLine(), start.getCharPositionInLine() + 1);
} | [
"ExecutionLocation",
"getLocation",
"(",
"ParserRuleContext",
"object",
")",
"{",
"Token",
"start",
"=",
"object",
".",
"getStart",
"(",
")",
";",
"return",
"new",
"ExecutionLocation",
"(",
"currentScope",
".",
"declaringEnvironment",
".",
"path",
",",
"start",
... | Retrieves location information for a model object
@param object Model object to locate
@return Location for the provided model object | [
"Retrieves",
"location",
"information",
"for",
"a",
"model",
"object"
] | train | https://github.com/impossibl/stencil/blob/4aac1be605542b4248be95bf8916be4e2f755d1c/engine/src/main/java/com/impossibl/stencil/engine/internal/StencilInterpreter.java#L2903-L2906 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/Criteria.java | Criteria.addGreaterThan | public void addGreaterThan(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildGreaterCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildGreaterCriteria(attribute, value, getUserAlias(attribute)));
} | java | public void addGreaterThan(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildGreaterCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildGreaterCriteria(attribute, value, getUserAlias(attribute)));
} | [
"public",
"void",
"addGreaterThan",
"(",
"Object",
"attribute",
",",
"Object",
"value",
")",
"{",
"// PAW\r",
"// addSelectionCriteria(ValueCriteria.buildGreaterCriteria(attribute, value, getAlias()));\r",
"addSelectionCriteria",
"(",
"ValueCriteria",
".",
"buildGreaterCriteria",
... | Adds Greater Than (>) criteria,
customer_id > 10034
@param attribute The field name to be used
@param value An object representing the value of the field | [
"Adds",
"Greater",
"Than",
"(",
">",
")",
"criteria",
"customer_id",
">",
"10034"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L507-L512 |
json-path/JsonPath | json-path/src/main/java/com/jayway/jsonpath/spi/json/AbstractJsonProvider.java | AbstractJsonProvider.getMapValue | public Object getMapValue(Object obj, String key){
Map m = (Map) obj;
if(!m.containsKey(key)){
return JsonProvider.UNDEFINED;
} else {
return m.get(key);
}
} | java | public Object getMapValue(Object obj, String key){
Map m = (Map) obj;
if(!m.containsKey(key)){
return JsonProvider.UNDEFINED;
} else {
return m.get(key);
}
} | [
"public",
"Object",
"getMapValue",
"(",
"Object",
"obj",
",",
"String",
"key",
")",
"{",
"Map",
"m",
"=",
"(",
"Map",
")",
"obj",
";",
"if",
"(",
"!",
"m",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"return",
"JsonProvider",
".",
"UNDEFINED",
"... | Extracts a value from an map
@param obj a map
@param key property key
@return the map entry or {@link com.jayway.jsonpath.spi.json.JsonProvider#UNDEFINED} for missing properties | [
"Extracts",
"a",
"value",
"from",
"an",
"map"
] | train | https://github.com/json-path/JsonPath/blob/5a09489c3252b74bbf81992aadb3073be59c04f9/json-path/src/main/java/com/jayway/jsonpath/spi/json/AbstractJsonProvider.java#L72-L79 |
wisdom-framework/wisdom | core/wisdom-ipojo-module/src/main/java/org/wisdom/ipojo/module/WisdomControllerVisitor.java | WisdomControllerVisitor.visitEnd | public void visitEnd() {
String classname = workbench.getType().getClassName();
component.addAttribute(new Attribute("classname", classname));
// Generates the provides attribute.
component.addElement(ElementHelper.getProvidesElement(null));
// Detect that Controller is implemented
if (!workbench.getClassNode().interfaces.contains(Type.getInternalName(Controller.class))
&& !Type.getInternalName(DefaultController.class).equals(workbench.getClassNode().superName)) {
reporter.warn("Cannot ensure that the class " + workbench.getType().getClassName() + " implements the " +
Controller.class.getName() + " interface.");
}
if (workbench.getRoot() == null) {
workbench.setRoot(component);
// Add the instance
workbench.setInstance(ElementHelper.declareInstance(workbench));
} else {
// Error case: 2 component type's annotations (@Component and @Handler for example) on the same class
reporter.error("Multiple 'component type' annotations on the class '{%s}'.", classname);
reporter.warn("@Controller is ignored.");
}
} | java | public void visitEnd() {
String classname = workbench.getType().getClassName();
component.addAttribute(new Attribute("classname", classname));
// Generates the provides attribute.
component.addElement(ElementHelper.getProvidesElement(null));
// Detect that Controller is implemented
if (!workbench.getClassNode().interfaces.contains(Type.getInternalName(Controller.class))
&& !Type.getInternalName(DefaultController.class).equals(workbench.getClassNode().superName)) {
reporter.warn("Cannot ensure that the class " + workbench.getType().getClassName() + " implements the " +
Controller.class.getName() + " interface.");
}
if (workbench.getRoot() == null) {
workbench.setRoot(component);
// Add the instance
workbench.setInstance(ElementHelper.declareInstance(workbench));
} else {
// Error case: 2 component type's annotations (@Component and @Handler for example) on the same class
reporter.error("Multiple 'component type' annotations on the class '{%s}'.", classname);
reporter.warn("@Controller is ignored.");
}
} | [
"public",
"void",
"visitEnd",
"(",
")",
"{",
"String",
"classname",
"=",
"workbench",
".",
"getType",
"(",
")",
".",
"getClassName",
"(",
")",
";",
"component",
".",
"addAttribute",
"(",
"new",
"Attribute",
"(",
"\"classname\"",
",",
"classname",
")",
")",... | End of the visit.
Declare the "component", "provides" and "instance" elements.
@see org.objectweb.asm.AnnotationVisitor#visitEnd() | [
"End",
"of",
"the",
"visit",
".",
"Declare",
"the",
"component",
"provides",
"and",
"instance",
"elements",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-ipojo-module/src/main/java/org/wisdom/ipojo/module/WisdomControllerVisitor.java#L59-L84 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/DocumentReference.java | DocumentReference.set | @Nonnull
public ApiFuture<WriteResult> set(@Nonnull Object pojo) {
WriteBatch writeBatch = firestore.batch();
return extractFirst(writeBatch.set(this, pojo).commit());
} | java | @Nonnull
public ApiFuture<WriteResult> set(@Nonnull Object pojo) {
WriteBatch writeBatch = firestore.batch();
return extractFirst(writeBatch.set(this, pojo).commit());
} | [
"@",
"Nonnull",
"public",
"ApiFuture",
"<",
"WriteResult",
">",
"set",
"(",
"@",
"Nonnull",
"Object",
"pojo",
")",
"{",
"WriteBatch",
"writeBatch",
"=",
"firestore",
".",
"batch",
"(",
")",
";",
"return",
"extractFirst",
"(",
"writeBatch",
".",
"set",
"(",... | Overwrites the document referred to by this DocumentReference. If no document exists yet, it
will be created. If a document already exists, it will be overwritten.
@param pojo The POJO that will be used to populate the document contents.
@return An ApiFuture that will be resolved when the write finishes. | [
"Overwrites",
"the",
"document",
"referred",
"to",
"by",
"this",
"DocumentReference",
".",
"If",
"no",
"document",
"exists",
"yet",
"it",
"will",
"be",
"created",
".",
"If",
"a",
"document",
"already",
"exists",
"it",
"will",
"be",
"overwritten",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/DocumentReference.java#L198-L202 |
javagl/ND | nd-tuples/src/main/java/de/javagl/nd/tuples/Utils.java | Utils.checkForEqualSize | public static void checkForEqualSize(Tuple t0, Tuple t1)
{
if (t0.getSize() != t1.getSize())
{
throw new IllegalArgumentException(
"Sizes do not match: "+t0.getSize()+
" and "+t1.getSize());
}
} | java | public static void checkForEqualSize(Tuple t0, Tuple t1)
{
if (t0.getSize() != t1.getSize())
{
throw new IllegalArgumentException(
"Sizes do not match: "+t0.getSize()+
" and "+t1.getSize());
}
} | [
"public",
"static",
"void",
"checkForEqualSize",
"(",
"Tuple",
"t0",
",",
"Tuple",
"t1",
")",
"{",
"if",
"(",
"t0",
".",
"getSize",
"(",
")",
"!=",
"t1",
".",
"getSize",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Sizes do not... | Checks whether given given {@link Tuple}s have equal
{@link Tuple#getSize() size}, and throws an
<code>IllegalArgumentException</code> if not.
@param t0 The first tuple
@param t1 The second tuple
@throws IllegalArgumentException If the given tuples
do not have the same {@link Tuple#getSize() size} | [
"Checks",
"whether",
"given",
"given",
"{",
"@link",
"Tuple",
"}",
"s",
"have",
"equal",
"{",
"@link",
"Tuple#getSize",
"()",
"size",
"}",
"and",
"throws",
"an",
"<code",
">",
"IllegalArgumentException<",
"/",
"code",
">",
"if",
"not",
"."
] | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/Utils.java#L47-L55 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/io/retry/RetryPolicies.java | RetryPolicies.retryByException | public static final RetryPolicy retryByException(RetryPolicy defaultPolicy,
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap) {
return new ExceptionDependentRetry(defaultPolicy, exceptionToPolicyMap);
} | java | public static final RetryPolicy retryByException(RetryPolicy defaultPolicy,
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap) {
return new ExceptionDependentRetry(defaultPolicy, exceptionToPolicyMap);
} | [
"public",
"static",
"final",
"RetryPolicy",
"retryByException",
"(",
"RetryPolicy",
"defaultPolicy",
",",
"Map",
"<",
"Class",
"<",
"?",
"extends",
"Exception",
">",
",",
"RetryPolicy",
">",
"exceptionToPolicyMap",
")",
"{",
"return",
"new",
"ExceptionDependentRetry... | <p>
Set a default policy with some explicit handlers for specific exceptions.
</p> | [
"<p",
">",
"Set",
"a",
"default",
"policy",
"with",
"some",
"explicit",
"handlers",
"for",
"specific",
"exceptions",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/io/retry/RetryPolicies.java#L108-L111 |
sksamuel/scrimage | scrimage-filters/src/main/java/thirdparty/jhlabs/image/Gradient.java | Gradient.addKnot | public void addKnot(int x, int color, int type) {
int[] nx = new int[numKnots+1];
int[] ny = new int[numKnots+1];
byte[] nt = new byte[numKnots+1];
System.arraycopy(xKnots, 0, nx, 0, numKnots);
System.arraycopy(yKnots, 0, ny, 0, numKnots);
System.arraycopy(knotTypes, 0, nt, 0, numKnots);
xKnots = nx;
yKnots = ny;
knotTypes = nt;
// Insert one position before the end so the sort works correctly
xKnots[numKnots] = xKnots[numKnots-1];
yKnots[numKnots] = yKnots[numKnots-1];
knotTypes[numKnots] = knotTypes[numKnots-1];
xKnots[numKnots-1] = x;
yKnots[numKnots-1] = color;
knotTypes[numKnots-1] = (byte)type;
numKnots++;
sortKnots();
rebuildGradient();
} | java | public void addKnot(int x, int color, int type) {
int[] nx = new int[numKnots+1];
int[] ny = new int[numKnots+1];
byte[] nt = new byte[numKnots+1];
System.arraycopy(xKnots, 0, nx, 0, numKnots);
System.arraycopy(yKnots, 0, ny, 0, numKnots);
System.arraycopy(knotTypes, 0, nt, 0, numKnots);
xKnots = nx;
yKnots = ny;
knotTypes = nt;
// Insert one position before the end so the sort works correctly
xKnots[numKnots] = xKnots[numKnots-1];
yKnots[numKnots] = yKnots[numKnots-1];
knotTypes[numKnots] = knotTypes[numKnots-1];
xKnots[numKnots-1] = x;
yKnots[numKnots-1] = color;
knotTypes[numKnots-1] = (byte)type;
numKnots++;
sortKnots();
rebuildGradient();
} | [
"public",
"void",
"addKnot",
"(",
"int",
"x",
",",
"int",
"color",
",",
"int",
"type",
")",
"{",
"int",
"[",
"]",
"nx",
"=",
"new",
"int",
"[",
"numKnots",
"+",
"1",
"]",
";",
"int",
"[",
"]",
"ny",
"=",
"new",
"int",
"[",
"numKnots",
"+",
"1... | Add a new knot.
@param x the knot position
@param color the color
@param type the knot type
@see #removeKnot | [
"Add",
"a",
"new",
"knot",
"."
] | train | https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/jhlabs/image/Gradient.java#L240-L260 |
ow2-chameleon/fuchsia | importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/protocol/ZWaveController.java | ZWaveController.handleApplicationCommandRequest | private void handleApplicationCommandRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Application Command Request");
int nodeId = incomingMessage.getMessagePayloadByte(1);
logger.debug("Application Command Request from Node " + nodeId);
ZWaveNode node = getNode(nodeId);
if (node == null) {
logger.warn("Node {} not initialized yet, ignoring message.", nodeId);
return;
}
node.resetResendCount();
int commandClassCode = incomingMessage.getMessagePayloadByte(3);
ZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Incoming command class %s (0x%02x)", commandClass.getLabel(), commandClass.getKey()));
ZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);
// We got an unsupported command class, return.
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
logger.trace("Found Command Class {}, passing to handleApplicationCommandRequest", zwaveCommandClass.getCommandClass().getLabel());
zwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
} | java | private void handleApplicationCommandRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Application Command Request");
int nodeId = incomingMessage.getMessagePayloadByte(1);
logger.debug("Application Command Request from Node " + nodeId);
ZWaveNode node = getNode(nodeId);
if (node == null) {
logger.warn("Node {} not initialized yet, ignoring message.", nodeId);
return;
}
node.resetResendCount();
int commandClassCode = incomingMessage.getMessagePayloadByte(3);
ZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Incoming command class %s (0x%02x)", commandClass.getLabel(), commandClass.getKey()));
ZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);
// We got an unsupported command class, return.
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
logger.trace("Found Command Class {}, passing to handleApplicationCommandRequest", zwaveCommandClass.getCommandClass().getLabel());
zwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
} | [
"private",
"void",
"handleApplicationCommandRequest",
"(",
"SerialMessage",
"incomingMessage",
")",
"{",
"logger",
".",
"trace",
"(",
"\"Handle Message Application Command Request\"",
")",
";",
"int",
"nodeId",
"=",
"incomingMessage",
".",
"getMessagePayloadByte",
"(",
"1... | Handles incoming Application Command Request.
@param incomingMessage the request message to process. | [
"Handles",
"incoming",
"Application",
"Command",
"Request",
"."
] | train | https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/protocol/ZWaveController.java#L228-L266 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressRestrictionPersistenceImpl.java | CommerceAddressRestrictionPersistenceImpl.findAll | @Override
public List<CommerceAddressRestriction> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceAddressRestriction> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceAddressRestriction",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce address restrictions.
@return the commerce address restrictions | [
"Returns",
"all",
"the",
"commerce",
"address",
"restrictions",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressRestrictionPersistenceImpl.java#L2030-L2033 |
Jasig/uPortal | uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/AuthorizationPrincipalImpl.java | AuthorizationPrincipalImpl.canManage | @Override
public boolean canManage(PortletLifecycleState state, String categoryId)
throws AuthorizationException {
return getAuthorizationService().canPrincipalManage(this, state, categoryId);
} | java | @Override
public boolean canManage(PortletLifecycleState state, String categoryId)
throws AuthorizationException {
return getAuthorizationService().canPrincipalManage(this, state, categoryId);
} | [
"@",
"Override",
"public",
"boolean",
"canManage",
"(",
"PortletLifecycleState",
"state",
",",
"String",
"categoryId",
")",
"throws",
"AuthorizationException",
"{",
"return",
"getAuthorizationService",
"(",
")",
".",
"canPrincipalManage",
"(",
"this",
",",
"state",
... | Answers if this <code>IAuthorizationPrincipal</code> has permission to publish.
@return boolean
@exception AuthorizationException thrown when authorization information could not be
retrieved. | [
"Answers",
"if",
"this",
"<code",
">",
"IAuthorizationPrincipal<",
"/",
"code",
">",
"has",
"permission",
"to",
"publish",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/AuthorizationPrincipalImpl.java#L60-L64 |
jboss/jboss-jstl-api_spec | src/main/java/org/apache/taglibs/standard/tag/common/core/SetSupport.java | SetSupport.exportToMapProperty | void exportToMapProperty(Object target, String property, Object result) {
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) target;
if (result == null) {
map.remove(property);
} else {
map.put(property, result);
}
} | java | void exportToMapProperty(Object target, String property, Object result) {
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) target;
if (result == null) {
map.remove(property);
} else {
map.put(property, result);
}
} | [
"void",
"exportToMapProperty",
"(",
"Object",
"target",
",",
"String",
"property",
",",
"Object",
"result",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"Object",
",",
"Object",
">",
"map",
"=",
"(",
"Map",
"<",
"Object",
",",
... | Export the result into a Map.
@param target the Map to export into
@param property the key to export into
@param result the value to export | [
"Export",
"the",
"result",
"into",
"a",
"Map",
"."
] | train | https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/org/apache/taglibs/standard/tag/common/core/SetSupport.java#L200-L208 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.BitArray | public JBBPDslBuilder BitArray(final String name, final String bitLenExpression, final int size) {
return this.BitArray(name, bitLenExpression, arraySizeToString(size));
} | java | public JBBPDslBuilder BitArray(final String name, final String bitLenExpression, final int size) {
return this.BitArray(name, bitLenExpression, arraySizeToString(size));
} | [
"public",
"JBBPDslBuilder",
"BitArray",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"bitLenExpression",
",",
"final",
"int",
"size",
")",
"{",
"return",
"this",
".",
"BitArray",
"(",
"name",
",",
"bitLenExpression",
",",
"arraySizeToString",
"(",
"... | Add named fixed length bit array, size of one bit field is calculated by expression.
@param name name of the array, if null then anonymous one
@param bitLenExpression expression to calculate length of the bit field, must not be null
@param size number of elements in array, if negative then till the end of stream
@return the builder instance, must not be null | [
"Add",
"named",
"fixed",
"length",
"bit",
"array",
"size",
"of",
"one",
"bit",
"field",
"is",
"calculated",
"by",
"expression",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L688-L690 |
google/closure-compiler | src/com/google/javascript/jscomp/ExploitAssigns.java | ExploitAssigns.collapseAssign | private void collapseAssign(Node assign, Node expr, Node exprParent) {
Node leftValue = assign.getFirstChild();
Node rightValue = leftValue.getNext();
if (leftValue.isDestructuringPattern()) {
// We don't collapse expressions containing these because they can have side effects:
// - Reassigning RHS names. (e.g. `() => { ({c: a} = a); return a; }`).
// - Calling a getter defined on the RHS.
// - Evaluating a default value.
// TODO(b/123102446): Check for these issues and optimize when they aren't present.
return;
} else if (isCollapsibleValue(leftValue, true)
&& collapseAssignEqualTo(expr, exprParent, leftValue)) {
// Condition has side-effects.
} else if (isCollapsibleValue(rightValue, false)
&& collapseAssignEqualTo(expr, exprParent, rightValue)) {
// Condition has side-effects.
} else if (rightValue.isAssign()) {
// Recursively deal with nested assigns.
collapseAssign(rightValue, expr, exprParent);
}
} | java | private void collapseAssign(Node assign, Node expr, Node exprParent) {
Node leftValue = assign.getFirstChild();
Node rightValue = leftValue.getNext();
if (leftValue.isDestructuringPattern()) {
// We don't collapse expressions containing these because they can have side effects:
// - Reassigning RHS names. (e.g. `() => { ({c: a} = a); return a; }`).
// - Calling a getter defined on the RHS.
// - Evaluating a default value.
// TODO(b/123102446): Check for these issues and optimize when they aren't present.
return;
} else if (isCollapsibleValue(leftValue, true)
&& collapseAssignEqualTo(expr, exprParent, leftValue)) {
// Condition has side-effects.
} else if (isCollapsibleValue(rightValue, false)
&& collapseAssignEqualTo(expr, exprParent, rightValue)) {
// Condition has side-effects.
} else if (rightValue.isAssign()) {
// Recursively deal with nested assigns.
collapseAssign(rightValue, expr, exprParent);
}
} | [
"private",
"void",
"collapseAssign",
"(",
"Node",
"assign",
",",
"Node",
"expr",
",",
"Node",
"exprParent",
")",
"{",
"Node",
"leftValue",
"=",
"assign",
".",
"getFirstChild",
"(",
")",
";",
"Node",
"rightValue",
"=",
"leftValue",
".",
"getNext",
"(",
")",... | Try to collapse the given assign into subsequent expressions. | [
"Try",
"to",
"collapse",
"the",
"given",
"assign",
"into",
"subsequent",
"expressions",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExploitAssigns.java#L43-L64 |
strator-dev/greenpepper | greenpepper-open/extensions-external/php/src/main/java/com/greenpepper/phpsud/container/PHPMethodDescriptor.java | PHPMethodDescriptor.execNoResponse | public void execNoResponse(String id, String ... params) throws Exception {
container.run(getCmd(id, params));
} | java | public void execNoResponse(String id, String ... params) throws Exception {
container.run(getCmd(id, params));
} | [
"public",
"void",
"execNoResponse",
"(",
"String",
"id",
",",
"String",
"...",
"params",
")",
"throws",
"Exception",
"{",
"container",
".",
"run",
"(",
"getCmd",
"(",
"id",
",",
"params",
")",
")",
";",
"}"
] | <p>execNoResponse.</p>
@param id a {@link java.lang.String} object.
@param params a {@link java.lang.String} object.
@throws java.lang.Exception if any. | [
"<p",
">",
"execNoResponse",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/extensions-external/php/src/main/java/com/greenpepper/phpsud/container/PHPMethodDescriptor.java#L151-L153 |
gsi-upm/Shanks | shanks-core/src/main/java/es/upm/dit/gsi/shanks/agent/capability/reasoning/bayes/smile/ShanksAgentBayesianReasoningCapability.java | ShanksAgentBayesianReasoningCapability.getHypothesis | public static float getHypothesis(Network bn, String nodeName, String status)
throws ShanksException {
int node = ShanksAgentBayesianReasoningCapability.getNode(bn, nodeName);
String[] states = bn.getOutcomeIds(node);
for (int i = 0; i < states.length; i++) {
if (status.equals(states[i])) {
return (float) bn.getNodeValue(node)[i];
}
}
throw new UnknowkNodeStateException(bn, nodeName, status);
} | java | public static float getHypothesis(Network bn, String nodeName, String status)
throws ShanksException {
int node = ShanksAgentBayesianReasoningCapability.getNode(bn, nodeName);
String[] states = bn.getOutcomeIds(node);
for (int i = 0; i < states.length; i++) {
if (status.equals(states[i])) {
return (float) bn.getNodeValue(node)[i];
}
}
throw new UnknowkNodeStateException(bn, nodeName, status);
} | [
"public",
"static",
"float",
"getHypothesis",
"(",
"Network",
"bn",
",",
"String",
"nodeName",
",",
"String",
"status",
")",
"throws",
"ShanksException",
"{",
"int",
"node",
"=",
"ShanksAgentBayesianReasoningCapability",
".",
"getNode",
"(",
"bn",
",",
"nodeName",... | Get the value of a status in a node
@param bn
@param nodeName
@param status
@return a float with the probability
@throws UnknownNodeException
@throws UnknowkNodeStateException | [
"Get",
"the",
"value",
"of",
"a",
"status",
"in",
"a",
"node"
] | train | https://github.com/gsi-upm/Shanks/blob/35d87a81c22731f4f83bbd0571c9c6d466bd16be/shanks-core/src/main/java/es/upm/dit/gsi/shanks/agent/capability/reasoning/bayes/smile/ShanksAgentBayesianReasoningCapability.java#L364-L374 |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java | DataStoreStreaming.updateAll | public static void updateAll(DataStore dataStore, Iterable<Update> updates, Set<String> tags) {
updateAll(dataStore, updates.iterator(), tags);
} | java | public static void updateAll(DataStore dataStore, Iterable<Update> updates, Set<String> tags) {
updateAll(dataStore, updates.iterator(), tags);
} | [
"public",
"static",
"void",
"updateAll",
"(",
"DataStore",
"dataStore",
",",
"Iterable",
"<",
"Update",
">",
"updates",
",",
"Set",
"<",
"String",
">",
"tags",
")",
"{",
"updateAll",
"(",
"dataStore",
",",
"updates",
".",
"iterator",
"(",
")",
",",
"tags... | Creates, updates or deletes zero or more pieces of content in the data store.
You can attach a set of databus event tags for these updates | [
"Creates",
"updates",
"or",
"deletes",
"zero",
"or",
"more",
"pieces",
"of",
"content",
"in",
"the",
"data",
"store",
".",
"You",
"can",
"attach",
"a",
"set",
"of",
"databus",
"event",
"tags",
"for",
"these",
"updates"
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java#L143-L145 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/ParserDDL.java | ParserDDL.processAlterTableDropConstraint | void processAlterTableDropConstraint(Table table, String name,
boolean cascade) {
session.commit(false);
TableWorks tableWorks = new TableWorks(session, table);
tableWorks.dropConstraint(name, cascade);
return;
} | java | void processAlterTableDropConstraint(Table table, String name,
boolean cascade) {
session.commit(false);
TableWorks tableWorks = new TableWorks(session, table);
tableWorks.dropConstraint(name, cascade);
return;
} | [
"void",
"processAlterTableDropConstraint",
"(",
"Table",
"table",
",",
"String",
"name",
",",
"boolean",
"cascade",
")",
"{",
"session",
".",
"commit",
"(",
"false",
")",
";",
"TableWorks",
"tableWorks",
"=",
"new",
"TableWorks",
"(",
"session",
",",
"table",
... | Responsible for handling tail of ALTER TABLE ... DROP CONSTRAINT ... | [
"Responsible",
"for",
"handling",
"tail",
"of",
"ALTER",
"TABLE",
"...",
"DROP",
"CONSTRAINT",
"..."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/ParserDDL.java#L4275-L4285 |
redkale/redkale | src/org/redkale/util/SelectColumn.java | SelectColumn.includes | public static SelectColumn includes(String[] cols, String... columns) {
return new SelectColumn(Utility.append(cols, columns), false);
} | java | public static SelectColumn includes(String[] cols, String... columns) {
return new SelectColumn(Utility.append(cols, columns), false);
} | [
"public",
"static",
"SelectColumn",
"includes",
"(",
"String",
"[",
"]",
"cols",
",",
"String",
"...",
"columns",
")",
"{",
"return",
"new",
"SelectColumn",
"(",
"Utility",
".",
"append",
"(",
"cols",
",",
"columns",
")",
",",
"false",
")",
";",
"}"
] | class中的字段名
@param cols 包含的字段名集合
@param columns 包含的字段名集合
@return SelectColumn | [
"class中的字段名"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/util/SelectColumn.java#L118-L120 |
ops4j/org.ops4j.base | ops4j-base-util/src/main/java/org/ops4j/util/i18n/Resources.java | Resources.getLong | public long getLong( String key, long defaultValue )
throws MissingResourceException
{
try
{
return getLong( key );
}
catch( MissingResourceException mre )
{
return defaultValue;
}
} | java | public long getLong( String key, long defaultValue )
throws MissingResourceException
{
try
{
return getLong( key );
}
catch( MissingResourceException mre )
{
return defaultValue;
}
} | [
"public",
"long",
"getLong",
"(",
"String",
"key",
",",
"long",
"defaultValue",
")",
"throws",
"MissingResourceException",
"{",
"try",
"{",
"return",
"getLong",
"(",
"key",
")",
";",
"}",
"catch",
"(",
"MissingResourceException",
"mre",
")",
"{",
"return",
"... | Retrieve a long from bundle.
@param key the key of resource
@param defaultValue the default value if key is missing
@return the resource long
@throws MissingResourceException if the requested key is unknown | [
"Retrieve",
"a",
"long",
"from",
"bundle",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/Resources.java#L377-L388 |
mfornos/humanize | humanize-slim/src/main/java/humanize/Humanize.java | Humanize.paceFormat | public static String paceFormat(final Number value, final TimeMillis interval)
{
return paceFormat(value, interval.millis());
} | java | public static String paceFormat(final Number value, final TimeMillis interval)
{
return paceFormat(value, interval.millis());
} | [
"public",
"static",
"String",
"paceFormat",
"(",
"final",
"Number",
"value",
",",
"final",
"TimeMillis",
"interval",
")",
"{",
"return",
"paceFormat",
"(",
"value",
",",
"interval",
".",
"millis",
"(",
")",
")",
";",
"}"
] | Same as {@link #paceFormat(Number, long)}
@param value
The number of occurrences within the specified interval
@param interval
The interval in milliseconds
@return an human readable textual representation of the pace | [
"Same",
"as",
"{",
"@link",
"#paceFormat",
"(",
"Number",
"long",
")",
"}"
] | train | https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L2118-L2121 |
RogerParkinson/madura-objects-parent | madura-utils/src/main/java/nz/co/senanque/parser/Parser.java | Parser.exactOrError | public boolean exactOrError(String match,TextProvider textProvider)
{
if (!exact(match,textProvider,false))
{
throw new ParserException("Expected "+match,textProvider);
}
return true;
} | java | public boolean exactOrError(String match,TextProvider textProvider)
{
if (!exact(match,textProvider,false))
{
throw new ParserException("Expected "+match,textProvider);
}
return true;
} | [
"public",
"boolean",
"exactOrError",
"(",
"String",
"match",
",",
"TextProvider",
"textProvider",
")",
"{",
"if",
"(",
"!",
"exact",
"(",
"match",
",",
"textProvider",
",",
"false",
")",
")",
"{",
"throw",
"new",
"ParserException",
"(",
"\"Expected \"",
"+",... | Match against the passed string.
Case is ignored if the ignoreCase flag is set.
@param match
@param textProvider
@return true if matched | [
"Match",
"against",
"the",
"passed",
"string",
".",
"Case",
"is",
"ignored",
"if",
"the",
"ignoreCase",
"flag",
"is",
"set",
"."
] | train | https://github.com/RogerParkinson/madura-objects-parent/blob/9b5385dd0437611f0ce8506f63646e018d06fb8e/madura-utils/src/main/java/nz/co/senanque/parser/Parser.java#L225-L232 |
cdk/cdk | tool/sdg/src/main/java/org/openscience/cdk/layout/LayoutRefiner.java | LayoutRefiner.isCrossed | private boolean isCrossed(Point2d beg1, Point2d end1, Point2d beg2, Point2d end2) {
return Line2D.linesIntersect(beg1.x, beg1.y, end1.x, end1.y, beg2.x, beg2.y, end2.x, end2.y);
} | java | private boolean isCrossed(Point2d beg1, Point2d end1, Point2d beg2, Point2d end2) {
return Line2D.linesIntersect(beg1.x, beg1.y, end1.x, end1.y, beg2.x, beg2.y, end2.x, end2.y);
} | [
"private",
"boolean",
"isCrossed",
"(",
"Point2d",
"beg1",
",",
"Point2d",
"end1",
",",
"Point2d",
"beg2",
",",
"Point2d",
"end2",
")",
"{",
"return",
"Line2D",
".",
"linesIntersect",
"(",
"beg1",
".",
"x",
",",
"beg1",
".",
"y",
",",
"end1",
".",
"x",... | Check if two bonds are crossing.
@param beg1 first atom of first bond
@param end1 second atom of first bond
@param beg2 first atom of second bond
@param end2 first atom of second bond
@return bond is crossing | [
"Check",
"if",
"two",
"bonds",
"are",
"crossing",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/sdg/src/main/java/org/openscience/cdk/layout/LayoutRefiner.java#L293-L295 |
orbisgis/h2gis | h2gis-utilities/src/main/java/org/h2gis/utilities/SFSUtilities.java | SFSUtilities.getResultSetEnvelope | public static Envelope getResultSetEnvelope(ResultSet resultSet, String fieldName) throws SQLException {
Envelope aggregatedEnvelope = null;
while (resultSet.next()) {
Geometry geom = (Geometry) resultSet.getObject(fieldName);
if (aggregatedEnvelope != null) {
aggregatedEnvelope.expandToInclude(geom.getEnvelopeInternal());
} else {
aggregatedEnvelope = geom.getEnvelopeInternal();
}
}
return aggregatedEnvelope;
} | java | public static Envelope getResultSetEnvelope(ResultSet resultSet, String fieldName) throws SQLException {
Envelope aggregatedEnvelope = null;
while (resultSet.next()) {
Geometry geom = (Geometry) resultSet.getObject(fieldName);
if (aggregatedEnvelope != null) {
aggregatedEnvelope.expandToInclude(geom.getEnvelopeInternal());
} else {
aggregatedEnvelope = geom.getEnvelopeInternal();
}
}
return aggregatedEnvelope;
} | [
"public",
"static",
"Envelope",
"getResultSetEnvelope",
"(",
"ResultSet",
"resultSet",
",",
"String",
"fieldName",
")",
"throws",
"SQLException",
"{",
"Envelope",
"aggregatedEnvelope",
"=",
"null",
";",
"while",
"(",
"resultSet",
".",
"next",
"(",
")",
")",
"{",... | Compute the full extend of a ResultSet using a specified geometry field.
If the ResultSet does not contain this geometry field throw an exception
@param resultSet ResultSet to analyse
@param fieldName Field to analyse
@return The full extend of the field in the ResultSet
@throws SQLException | [
"Compute",
"the",
"full",
"extend",
"of",
"a",
"ResultSet",
"using",
"a",
"specified",
"geometry",
"field",
".",
"If",
"the",
"ResultSet",
"does",
"not",
"contain",
"this",
"geometry",
"field",
"throw",
"an",
"exception"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-utilities/src/main/java/org/h2gis/utilities/SFSUtilities.java#L468-L479 |
UrielCh/ovh-java-sdk | ovh-java-sdk-packxdsl/src/main/java/net/minidev/ovh/api/ApiOvhPackxdsl.java | ApiOvhPackxdsl.packName_domain_services_POST | public OvhTask packName_domain_services_POST(String packName, OvhDomainActionEnum action, String authInfo, String domain, String tld) throws IOException {
String qPath = "/pack/xdsl/{packName}/domain/services";
StringBuilder sb = path(qPath, packName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "action", action);
addBody(o, "authInfo", authInfo);
addBody(o, "domain", domain);
addBody(o, "tld", tld);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask packName_domain_services_POST(String packName, OvhDomainActionEnum action, String authInfo, String domain, String tld) throws IOException {
String qPath = "/pack/xdsl/{packName}/domain/services";
StringBuilder sb = path(qPath, packName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "action", action);
addBody(o, "authInfo", authInfo);
addBody(o, "domain", domain);
addBody(o, "tld", tld);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"packName_domain_services_POST",
"(",
"String",
"packName",
",",
"OvhDomainActionEnum",
"action",
",",
"String",
"authInfo",
",",
"String",
"domain",
",",
"String",
"tld",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/pack/xdsl/... | Activate a domain service
REST: POST /pack/xdsl/{packName}/domain/services
@param domain [required] Domain name
@param authInfo [required] Needed for transfer from another registrar
@param tld [required] TLD of the domain
@param action [required] Domain action
@param packName [required] The internal name of your pack | [
"Activate",
"a",
"domain",
"service"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-packxdsl/src/main/java/net/minidev/ovh/api/ApiOvhPackxdsl.java#L102-L112 |
vanilladb/vanillacore | src/main/java/org/vanilladb/core/query/algebra/SelectPlan.java | SelectPlan.joinFieldBucket | public static Bucket joinFieldBucket(Bucket bkt1, Bucket bkt2, double numRec) {
ConstantRange newRange = bkt1.valueRange().intersect(bkt2.valueRange());
if (!newRange.isValid())
return null;
double rdv1 = bkt1.distinctValues(newRange);
double rdv2 = bkt2.distinctValues(newRange);
double newDistVals = Math.min(rdv1, rdv2);
if (Double.compare(newDistVals, 1.0) < 0)
return null;
double newFreq = Math.min(
bkt1.frequency() * (bkt2.frequency() / numRec)
* (newDistVals / bkt1.distinctValues()) / rdv2,
bkt2.frequency() * (bkt1.frequency() / numRec)
* (newDistVals / bkt2.distinctValues()) / rdv1);
if (Double.compare(newFreq, 1.0) < 0)
return null;
Bucket smaller = rdv1 < rdv2 ? bkt1 : bkt2;
if (smaller.valuePercentiles() == null)
return new Bucket(newRange, newFreq, newDistVals);
Percentiles newPcts = smaller.valuePercentiles().percentiles(newRange);
return new Bucket(newRange, newFreq, newDistVals, newPcts);
} | java | public static Bucket joinFieldBucket(Bucket bkt1, Bucket bkt2, double numRec) {
ConstantRange newRange = bkt1.valueRange().intersect(bkt2.valueRange());
if (!newRange.isValid())
return null;
double rdv1 = bkt1.distinctValues(newRange);
double rdv2 = bkt2.distinctValues(newRange);
double newDistVals = Math.min(rdv1, rdv2);
if (Double.compare(newDistVals, 1.0) < 0)
return null;
double newFreq = Math.min(
bkt1.frequency() * (bkt2.frequency() / numRec)
* (newDistVals / bkt1.distinctValues()) / rdv2,
bkt2.frequency() * (bkt1.frequency() / numRec)
* (newDistVals / bkt2.distinctValues()) / rdv1);
if (Double.compare(newFreq, 1.0) < 0)
return null;
Bucket smaller = rdv1 < rdv2 ? bkt1 : bkt2;
if (smaller.valuePercentiles() == null)
return new Bucket(newRange, newFreq, newDistVals);
Percentiles newPcts = smaller.valuePercentiles().percentiles(newRange);
return new Bucket(newRange, newFreq, newDistVals, newPcts);
} | [
"public",
"static",
"Bucket",
"joinFieldBucket",
"(",
"Bucket",
"bkt1",
",",
"Bucket",
"bkt2",
",",
"double",
"numRec",
")",
"{",
"ConstantRange",
"newRange",
"=",
"bkt1",
".",
"valueRange",
"(",
")",
".",
"intersect",
"(",
"bkt2",
".",
"valueRange",
"(",
... | Creates a new bucket by keeping the statistics of joining records and
values from the two specified buckets.
<p>
Assumes that:
<ul>
<li>Values in a bucket have the same frequency (uniform frequency)</li>
<li>Given values within two equal ranges (of two joinable fields), all
values in the range having smaller number of values appear in the range
having larger number of values</li>
<li>Distributions of values in different fields are independent with each
other</li>
</ul>
@param bkt1
the input bucket 1
@param bkt2
the input bucket 2
@param numRec
the total number of records in the histogram where
<code>bkt1</code> and <code>bkt2</code> belong to
@return a new bucket that keeps the statistics of joining records and
values from the two specified buckets | [
"Creates",
"a",
"new",
"bucket",
"by",
"keeping",
"the",
"statistics",
"of",
"joining",
"records",
"and",
"values",
"from",
"the",
"two",
"specified",
"buckets",
"."
] | train | https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/query/algebra/SelectPlan.java#L290-L311 |
documents4j/documents4j | documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java | ConverterServerBuilder.processTimeout | public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) {
assertNumericArgument(processTimeout, false);
this.processTimeout = timeUnit.toMillis(processTimeout);
return this;
} | java | public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) {
assertNumericArgument(processTimeout, false);
this.processTimeout = timeUnit.toMillis(processTimeout);
return this;
} | [
"public",
"ConverterServerBuilder",
"processTimeout",
"(",
"long",
"processTimeout",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"assertNumericArgument",
"(",
"processTimeout",
",",
"false",
")",
";",
"this",
".",
"processTimeout",
"=",
"timeUnit",
".",
"toMillis",
"(",
... | Returns the specified process time out in milliseconds.
@return The process time out in milliseconds. | [
"Returns",
"the",
"specified",
"process",
"time",
"out",
"in",
"milliseconds",
"."
] | train | https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L148-L152 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/Jassimp.java | Jassimp.importFile | public static AiScene importFile(String filename,
Set<AiPostProcessSteps> postProcessing)
throws IOException {
return importFile(filename, postProcessing, null);
} | java | public static AiScene importFile(String filename,
Set<AiPostProcessSteps> postProcessing)
throws IOException {
return importFile(filename, postProcessing, null);
} | [
"public",
"static",
"AiScene",
"importFile",
"(",
"String",
"filename",
",",
"Set",
"<",
"AiPostProcessSteps",
">",
"postProcessing",
")",
"throws",
"IOException",
"{",
"return",
"importFile",
"(",
"filename",
",",
"postProcessing",
",",
"null",
")",
";",
"}"
] | Imports a file via assimp.
@param filename the file to import
@param postProcessing post processing flags
@return the loaded scene, or null if an error occurred
@throws IOException if an error occurs | [
"Imports",
"a",
"file",
"via",
"assimp",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/Jassimp.java#L105-L109 |
dmerkushov/os-helper | src/main/java/ru/dmerkushov/oshelper/OSHelper.java | OSHelper.procWaitWithProcessReturn | public static ProcessReturn procWaitWithProcessReturn (Process process, final long timeout) throws OSHelperException {
long endTime = Calendar.getInstance ().getTimeInMillis () + timeout;
boolean terminatedByItself = false;
ProcessReturn processReturn = new ProcessReturn ();
while (Calendar.getInstance ().getTimeInMillis () < endTime) {
try {
InputStream stdoutIs = process.getInputStream ();
processReturn.stdout = readInputStreamAsString (stdoutIs);
InputStream stderrIs = process.getErrorStream ();
processReturn.stderr = readInputStreamAsString (stderrIs);
processReturn.exitCode = process.exitValue ();
processReturn.exitStatus = ProcessReturn.osh_PROCESS_EXITED_BY_ITSELF;
terminatedByItself = true;
} catch (IllegalThreadStateException ex) { // the process has not yet terminated
terminatedByItself = false;
}
if (terminatedByItself) {
break;
}
}
if (!terminatedByItself) {
process.destroy ();
try {
InputStream stdoutIs = process.getInputStream ();
processReturn.stdout = readInputStreamAsString (stdoutIs);
InputStream stderrIs = process.getErrorStream ();
processReturn.stderr = readInputStreamAsString (stderrIs);
processReturn.exitCode = process.waitFor ();
} catch (InterruptedException ex) {
throw new OSHelperException (ex);
}
processReturn.exitStatus = ProcessReturn.osh_PROCESS_KILLED_BY_TIMEOUT;
}
return processReturn;
} | java | public static ProcessReturn procWaitWithProcessReturn (Process process, final long timeout) throws OSHelperException {
long endTime = Calendar.getInstance ().getTimeInMillis () + timeout;
boolean terminatedByItself = false;
ProcessReturn processReturn = new ProcessReturn ();
while (Calendar.getInstance ().getTimeInMillis () < endTime) {
try {
InputStream stdoutIs = process.getInputStream ();
processReturn.stdout = readInputStreamAsString (stdoutIs);
InputStream stderrIs = process.getErrorStream ();
processReturn.stderr = readInputStreamAsString (stderrIs);
processReturn.exitCode = process.exitValue ();
processReturn.exitStatus = ProcessReturn.osh_PROCESS_EXITED_BY_ITSELF;
terminatedByItself = true;
} catch (IllegalThreadStateException ex) { // the process has not yet terminated
terminatedByItself = false;
}
if (terminatedByItself) {
break;
}
}
if (!terminatedByItself) {
process.destroy ();
try {
InputStream stdoutIs = process.getInputStream ();
processReturn.stdout = readInputStreamAsString (stdoutIs);
InputStream stderrIs = process.getErrorStream ();
processReturn.stderr = readInputStreamAsString (stderrIs);
processReturn.exitCode = process.waitFor ();
} catch (InterruptedException ex) {
throw new OSHelperException (ex);
}
processReturn.exitStatus = ProcessReturn.osh_PROCESS_KILLED_BY_TIMEOUT;
}
return processReturn;
} | [
"public",
"static",
"ProcessReturn",
"procWaitWithProcessReturn",
"(",
"Process",
"process",
",",
"final",
"long",
"timeout",
")",
"throws",
"OSHelperException",
"{",
"long",
"endTime",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
".",
"getTimeInMillis",
"(",
")... | Waits for a specified process to terminate for the specified amount of
milliseconds. If it is not terminated in the desired time, it is
terminated explicitly.
NOT TESTED!!!
@param process
@param timeout
@return
@throws OSHelperException | [
"Waits",
"for",
"a",
"specified",
"process",
"to",
"terminate",
"for",
"the",
"specified",
"amount",
"of",
"milliseconds",
".",
"If",
"it",
"is",
"not",
"terminated",
"in",
"the",
"desired",
"time",
"it",
"is",
"terminated",
"explicitly",
"."
] | train | https://github.com/dmerkushov/os-helper/blob/a7c2b72d289d9bc23ae106d1c5e11769cf3463d6/src/main/java/ru/dmerkushov/oshelper/OSHelper.java#L106-L150 |
hypercube1024/firefly | firefly/src/main/java/com/firefly/codec/http2/model/HttpURI.java | HttpURI.parseRequestTarget | public void parseRequestTarget(String method, String uri) {
clear();
_uri = uri;
if (HttpMethod.CONNECT.is(method))
_path = uri;
else
parse(uri.startsWith("/") ? State.PATH : State.START, uri, 0, uri.length());
} | java | public void parseRequestTarget(String method, String uri) {
clear();
_uri = uri;
if (HttpMethod.CONNECT.is(method))
_path = uri;
else
parse(uri.startsWith("/") ? State.PATH : State.START, uri, 0, uri.length());
} | [
"public",
"void",
"parseRequestTarget",
"(",
"String",
"method",
",",
"String",
"uri",
")",
"{",
"clear",
"(",
")",
";",
"_uri",
"=",
"uri",
";",
"if",
"(",
"HttpMethod",
".",
"CONNECT",
".",
"is",
"(",
"method",
")",
")",
"_path",
"=",
"uri",
";",
... | Parse according to https://tools.ietf.org/html/rfc7230#section-5.3
@param method the request method
@param uri the request uri | [
"Parse",
"according",
"to",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc7230#section",
"-",
"5",
".",
"3"
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/model/HttpURI.java#L161-L169 |
jenkinsci/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java | JenkinsServer.createJob | public JenkinsServer createJob(String jobName, String jobXml) throws IOException {
return createJob(null, jobName, jobXml, false);
} | java | public JenkinsServer createJob(String jobName, String jobXml) throws IOException {
return createJob(null, jobName, jobXml, false);
} | [
"public",
"JenkinsServer",
"createJob",
"(",
"String",
"jobName",
",",
"String",
"jobXml",
")",
"throws",
"IOException",
"{",
"return",
"createJob",
"(",
"null",
",",
"jobName",
",",
"jobXml",
",",
"false",
")",
";",
"}"
] | Create a job on the server using the provided xml
@param jobName name of the job to be created.
@param jobXml the <code>config.xml</code> which should be used to create
the job.
@throws IOException in case of an error. | [
"Create",
"a",
"job",
"on",
"the",
"server",
"using",
"the",
"provided",
"xml"
] | train | https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L344-L346 |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.injectStructFields | private void injectStructFields(MethodDefinition read, LocalVariableDefinition instance, Map<Short, LocalVariableDefinition> structData)
{
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
injectField(read, field, instance, structData.get(field.getId()));
}
} | java | private void injectStructFields(MethodDefinition read, LocalVariableDefinition instance, Map<Short, LocalVariableDefinition> structData)
{
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
injectField(read, field, instance, structData.get(field.getId()));
}
} | [
"private",
"void",
"injectStructFields",
"(",
"MethodDefinition",
"read",
",",
"LocalVariableDefinition",
"instance",
",",
"Map",
"<",
"Short",
",",
"LocalVariableDefinition",
">",
"structData",
")",
"{",
"for",
"(",
"ThriftFieldMetadata",
"field",
":",
"metadata",
... | Defines the code to inject data into the struct public fields. | [
"Defines",
"the",
"code",
"to",
"inject",
"data",
"into",
"the",
"struct",
"public",
"fields",
"."
] | train | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L452-L457 |
ivanceras/orm | src/main/java/com/ivanceras/db/server/util/DAOGenerator.java | DAOGenerator.start | public void start() throws Exception{
if(cleanupDirectory){
CleanUp.start(conf);
}
IDatabaseDev db = (IDatabaseDev) em.getDB();//TODO make sure DB platform can be used for development
ModelDefinitionProvider provider = new ModelDefinitionProvider(db, conf.dbUser, null, conf.includeSchema);
ModelDef[] origModelList = provider.getTableDefinitions();
new ModelMetaDataGenerator().start(origModelList, conf);
//TODO: proper support for explicit ModelDefinitions
ModelDef[] withExplecitList = overrideModelDefFromExplicit(origModelList, explicitMeta);
ModelDef[] modelList = correctModelList(withExplecitList);
new DAOClassGenerator().start(modelList, conf, true, false);
new BeanGenerator().start(modelList, conf);
new MapperGenerator().start(modelList, conf);
ModelDef[] modelListOwned = setModelOwners(modelList, tableGroups);
ModelDef[] modelListChilded = setDirectChildren(modelListOwned);
new ColumnNameGenerator().start(modelListChilded, conf);
new TableNameGenerator().start(modelListChilded, conf);
new SchemaTableGenerator().start(modelListChilded, conf);
new TableColumnGenerator().start(modelListChilded, conf);
//new ModelMetaDataGenerator().start(modelListChilded, conf);
new DAOInstanceFactoryGenerator().start(modelListChilded, conf);
new ModelToDAOConversionGenerator().start(modelListChilded, conf);
} | java | public void start() throws Exception{
if(cleanupDirectory){
CleanUp.start(conf);
}
IDatabaseDev db = (IDatabaseDev) em.getDB();//TODO make sure DB platform can be used for development
ModelDefinitionProvider provider = new ModelDefinitionProvider(db, conf.dbUser, null, conf.includeSchema);
ModelDef[] origModelList = provider.getTableDefinitions();
new ModelMetaDataGenerator().start(origModelList, conf);
//TODO: proper support for explicit ModelDefinitions
ModelDef[] withExplecitList = overrideModelDefFromExplicit(origModelList, explicitMeta);
ModelDef[] modelList = correctModelList(withExplecitList);
new DAOClassGenerator().start(modelList, conf, true, false);
new BeanGenerator().start(modelList, conf);
new MapperGenerator().start(modelList, conf);
ModelDef[] modelListOwned = setModelOwners(modelList, tableGroups);
ModelDef[] modelListChilded = setDirectChildren(modelListOwned);
new ColumnNameGenerator().start(modelListChilded, conf);
new TableNameGenerator().start(modelListChilded, conf);
new SchemaTableGenerator().start(modelListChilded, conf);
new TableColumnGenerator().start(modelListChilded, conf);
//new ModelMetaDataGenerator().start(modelListChilded, conf);
new DAOInstanceFactoryGenerator().start(modelListChilded, conf);
new ModelToDAOConversionGenerator().start(modelListChilded, conf);
} | [
"public",
"void",
"start",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"cleanupDirectory",
")",
"{",
"CleanUp",
".",
"start",
"(",
"conf",
")",
";",
"}",
"IDatabaseDev",
"db",
"=",
"(",
"IDatabaseDev",
")",
"em",
".",
"getDB",
"(",
")",
";",
"//... | Curated will correct The ModelDef
@param curated
@throws Exception | [
"Curated",
"will",
"correct",
"The",
"ModelDef"
] | train | https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/server/util/DAOGenerator.java#L79-L107 |
apache/spark | common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java | ExternalShuffleBlockResolver.applicationRemoved | public void applicationRemoved(String appId, boolean cleanupLocalDirs) {
logger.info("Application {} removed, cleanupLocalDirs = {}", appId, cleanupLocalDirs);
Iterator<Map.Entry<AppExecId, ExecutorShuffleInfo>> it = executors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<AppExecId, ExecutorShuffleInfo> entry = it.next();
AppExecId fullId = entry.getKey();
final ExecutorShuffleInfo executor = entry.getValue();
// Only touch executors associated with the appId that was removed.
if (appId.equals(fullId.appId)) {
it.remove();
if (db != null) {
try {
db.delete(dbAppExecKey(fullId));
} catch (IOException e) {
logger.error("Error deleting {} from executor state db", appId, e);
}
}
if (cleanupLocalDirs) {
logger.info("Cleaning up executor {}'s {} local dirs", fullId, executor.localDirs.length);
// Execute the actual deletion in a different thread, as it may take some time.
directoryCleaner.execute(() -> deleteExecutorDirs(executor.localDirs));
}
}
}
} | java | public void applicationRemoved(String appId, boolean cleanupLocalDirs) {
logger.info("Application {} removed, cleanupLocalDirs = {}", appId, cleanupLocalDirs);
Iterator<Map.Entry<AppExecId, ExecutorShuffleInfo>> it = executors.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<AppExecId, ExecutorShuffleInfo> entry = it.next();
AppExecId fullId = entry.getKey();
final ExecutorShuffleInfo executor = entry.getValue();
// Only touch executors associated with the appId that was removed.
if (appId.equals(fullId.appId)) {
it.remove();
if (db != null) {
try {
db.delete(dbAppExecKey(fullId));
} catch (IOException e) {
logger.error("Error deleting {} from executor state db", appId, e);
}
}
if (cleanupLocalDirs) {
logger.info("Cleaning up executor {}'s {} local dirs", fullId, executor.localDirs.length);
// Execute the actual deletion in a different thread, as it may take some time.
directoryCleaner.execute(() -> deleteExecutorDirs(executor.localDirs));
}
}
}
} | [
"public",
"void",
"applicationRemoved",
"(",
"String",
"appId",
",",
"boolean",
"cleanupLocalDirs",
")",
"{",
"logger",
".",
"info",
"(",
"\"Application {} removed, cleanupLocalDirs = {}\"",
",",
"appId",
",",
"cleanupLocalDirs",
")",
";",
"Iterator",
"<",
"Map",
".... | Removes our metadata of all executors registered for the given application, and optionally
also deletes the local directories associated with the executors of that application in a
separate thread.
It is not valid to call registerExecutor() for an executor with this appId after invoking
this method. | [
"Removes",
"our",
"metadata",
"of",
"all",
"executors",
"registered",
"for",
"the",
"given",
"application",
"and",
"optionally",
"also",
"deletes",
"the",
"local",
"directories",
"associated",
"with",
"the",
"executors",
"of",
"that",
"application",
"in",
"a",
"... | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java#L190-L217 |
sap-production/xcode-maven-plugin | modules/xcode-maven-plugin/src/main/java/com/sap/prd/mobile/ios/mios/AbstractXCodeMojo.java | AbstractXCodeMojo.zipSubfolder | protected File zipSubfolder(File rootDir, String zipSubFolder, String zipFileName, String archiveFolder)
throws MojoExecutionException
{
int resultCode = 0;
try {
File scriptDirectory = new File(project.getBuild().getDirectory(), "scripts").getCanonicalFile();
scriptDirectory.deleteOnExit();
if (archiveFolder != null)
{
resultCode = ScriptRunner.copyAndExecuteScript(System.out, "/com/sap/prd/mobile/ios/mios/zip-subfolder.sh",
scriptDirectory, rootDir.getCanonicalPath(), zipSubFolder, zipFileName, archiveFolder);
}
else
{
resultCode = ScriptRunner.copyAndExecuteScript(System.out, "/com/sap/prd/mobile/ios/mios/zip-subfolder.sh",
scriptDirectory, rootDir.getCanonicalPath(), zipSubFolder, zipFileName);
}
}
catch (Exception ex) {
throw new MojoExecutionException("Cannot create zip file " + zipFileName + ". Check log for details.", ex);
}
if (resultCode != 0) {
throw new MojoExecutionException("Cannot create zip file " + zipFileName + ". Check log for details.");
}
getLog().info("Zip file '" + zipFileName + "' created.");
return new File(rootDir, zipFileName);
} | java | protected File zipSubfolder(File rootDir, String zipSubFolder, String zipFileName, String archiveFolder)
throws MojoExecutionException
{
int resultCode = 0;
try {
File scriptDirectory = new File(project.getBuild().getDirectory(), "scripts").getCanonicalFile();
scriptDirectory.deleteOnExit();
if (archiveFolder != null)
{
resultCode = ScriptRunner.copyAndExecuteScript(System.out, "/com/sap/prd/mobile/ios/mios/zip-subfolder.sh",
scriptDirectory, rootDir.getCanonicalPath(), zipSubFolder, zipFileName, archiveFolder);
}
else
{
resultCode = ScriptRunner.copyAndExecuteScript(System.out, "/com/sap/prd/mobile/ios/mios/zip-subfolder.sh",
scriptDirectory, rootDir.getCanonicalPath(), zipSubFolder, zipFileName);
}
}
catch (Exception ex) {
throw new MojoExecutionException("Cannot create zip file " + zipFileName + ". Check log for details.", ex);
}
if (resultCode != 0) {
throw new MojoExecutionException("Cannot create zip file " + zipFileName + ". Check log for details.");
}
getLog().info("Zip file '" + zipFileName + "' created.");
return new File(rootDir, zipFileName);
} | [
"protected",
"File",
"zipSubfolder",
"(",
"File",
"rootDir",
",",
"String",
"zipSubFolder",
",",
"String",
"zipFileName",
",",
"String",
"archiveFolder",
")",
"throws",
"MojoExecutionException",
"{",
"int",
"resultCode",
"=",
"0",
";",
"try",
"{",
"File",
"scrip... | Calls a shell script in order to zip a folder. We have to call a shell script as Java cannot
zip symbolic links.
@param rootDir
the directory where the zip command shall be executed
@param zipSubFolder
the subfolder to be zipped
@param zipFileName
the name of the zipFile (will be located in the rootDir)
@param archiveFolder
an optional folder name if the zipSubFolder folder shall be placed inside the zip into
a parent folder
@return the zip file
@throws MojoExecutionException | [
"Calls",
"a",
"shell",
"script",
"in",
"order",
"to",
"zip",
"a",
"folder",
".",
"We",
"have",
"to",
"call",
"a",
"shell",
"script",
"as",
"Java",
"cannot",
"zip",
"symbolic",
"links",
"."
] | train | https://github.com/sap-production/xcode-maven-plugin/blob/3f8aa380f501a1d7602f33fef2f6348354e7eb7c/modules/xcode-maven-plugin/src/main/java/com/sap/prd/mobile/ios/mios/AbstractXCodeMojo.java#L274-L303 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.unescapeUriFragmentId | public static void unescapeUriFragmentId(final String text, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(new InternalStringReader(text), writer, UriEscapeUtil.UriEscapeType.FRAGMENT_ID, encoding);
} | java | public static void unescapeUriFragmentId(final String text, final Writer writer, final String encoding)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
UriEscapeUtil.unescape(new InternalStringReader(text), writer, UriEscapeUtil.UriEscapeType.FRAGMENT_ID, encoding);
} | [
"public",
"static",
"void",
"unescapeUriFragmentId",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
",",
"final",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"Illega... | <p>
Perform am URI fragment identifier <strong>unescape</strong> operation
on a <tt>String</tt> input, writing results to a <tt>Writer</tt>.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use specified <tt>encoding</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@param encoding the encoding to be used for unescaping.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"am",
"URI",
"fragment",
"identifier",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">"... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2063-L2076 |
finmath/finmath-lib | src/main/java6/net/finmath/montecarlo/interestrate/products/Swaption.java | Swaption.getValue | @Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
/*
* Calculate value of the swap at exercise date on each path (beware of perfect foresight - all rates are simulationTime=exerciseDate)
*/
RandomVariableInterface valueOfSwapAtExerciseDate = model.getRandomVariableForConstant(/*fixingDates[fixingDates.length-1],*/0.0);
// Calculate the value of the swap by working backward through all periods
for(int period=fixingDates.length-1; period>=0; period--)
{
double fixingDate = fixingDates[period];
double paymentDate = paymentDates[period];
double swaprate = swaprates[period];
if(paymentDate <= evaluationTime) {
break;
}
double periodLength = periodLengths != null ? periodLengths[period] : paymentDate - fixingDate;
// Get random variables - note that this is the rate at simulation time = exerciseDate
RandomVariableInterface libor = model.getLIBOR(exerciseDate, fixingDate, paymentDate);
// Calculate payoff
RandomVariableInterface payoff = libor.sub(swaprate).mult(periodLength);
// Calculated the adjustment for the discounting curve, assuming a deterministic basis
// @TODO: Need to check if the model fulfills the assumptions (all models implementing the interface currently do so).
double discountingDate = Math.max(fixingDate,exerciseDate);
double discountingAdjustment = 1.0;
if(model.getModel() != null && model.getModel().getDiscountCurve() != null) {
AnalyticModelInterface analyticModel = model.getModel().getAnalyticModel();
DiscountCurveInterface discountCurve = model.getModel().getDiscountCurve();
ForwardCurveInterface forwardCurve = model.getModel().getForwardRateCurve();
DiscountCurveInterface discountCurveFromForwardCurve = new DiscountCurveFromForwardCurve(forwardCurve);
double forwardBondOnForwardCurve = discountCurveFromForwardCurve.getDiscountFactor(analyticModel, discountingDate) / discountCurveFromForwardCurve.getDiscountFactor(analyticModel, paymentDate);
double forwardBondOnDiscountCurve = discountCurve.getDiscountFactor(analyticModel, discountingDate) / discountCurve.getDiscountFactor(analyticModel, paymentDate);
discountingAdjustment = forwardBondOnForwardCurve / forwardBondOnDiscountCurve;
}
// Add payment received at end of period
valueOfSwapAtExerciseDate = valueOfSwapAtExerciseDate.add(payoff);
// Discount back to beginning of period
valueOfSwapAtExerciseDate = valueOfSwapAtExerciseDate.discount(libor, paymentDate - discountingDate).mult(discountingAdjustment);
}
/*
* Calculate swaption value
*/
RandomVariableInterface values = valueOfSwapAtExerciseDate.floor(0.0);
RandomVariableInterface numeraire = model.getNumeraire(exerciseDate);
RandomVariableInterface monteCarloProbabilities = model.getMonteCarloWeights(exerciseDate);
values = values.div(numeraire).mult(monteCarloProbabilities);
RandomVariableInterface numeraireAtZero = model.getNumeraire(evaluationTime);
RandomVariableInterface monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime);
values = values.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
return values;
} | java | @Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
/*
* Calculate value of the swap at exercise date on each path (beware of perfect foresight - all rates are simulationTime=exerciseDate)
*/
RandomVariableInterface valueOfSwapAtExerciseDate = model.getRandomVariableForConstant(/*fixingDates[fixingDates.length-1],*/0.0);
// Calculate the value of the swap by working backward through all periods
for(int period=fixingDates.length-1; period>=0; period--)
{
double fixingDate = fixingDates[period];
double paymentDate = paymentDates[period];
double swaprate = swaprates[period];
if(paymentDate <= evaluationTime) {
break;
}
double periodLength = periodLengths != null ? periodLengths[period] : paymentDate - fixingDate;
// Get random variables - note that this is the rate at simulation time = exerciseDate
RandomVariableInterface libor = model.getLIBOR(exerciseDate, fixingDate, paymentDate);
// Calculate payoff
RandomVariableInterface payoff = libor.sub(swaprate).mult(periodLength);
// Calculated the adjustment for the discounting curve, assuming a deterministic basis
// @TODO: Need to check if the model fulfills the assumptions (all models implementing the interface currently do so).
double discountingDate = Math.max(fixingDate,exerciseDate);
double discountingAdjustment = 1.0;
if(model.getModel() != null && model.getModel().getDiscountCurve() != null) {
AnalyticModelInterface analyticModel = model.getModel().getAnalyticModel();
DiscountCurveInterface discountCurve = model.getModel().getDiscountCurve();
ForwardCurveInterface forwardCurve = model.getModel().getForwardRateCurve();
DiscountCurveInterface discountCurveFromForwardCurve = new DiscountCurveFromForwardCurve(forwardCurve);
double forwardBondOnForwardCurve = discountCurveFromForwardCurve.getDiscountFactor(analyticModel, discountingDate) / discountCurveFromForwardCurve.getDiscountFactor(analyticModel, paymentDate);
double forwardBondOnDiscountCurve = discountCurve.getDiscountFactor(analyticModel, discountingDate) / discountCurve.getDiscountFactor(analyticModel, paymentDate);
discountingAdjustment = forwardBondOnForwardCurve / forwardBondOnDiscountCurve;
}
// Add payment received at end of period
valueOfSwapAtExerciseDate = valueOfSwapAtExerciseDate.add(payoff);
// Discount back to beginning of period
valueOfSwapAtExerciseDate = valueOfSwapAtExerciseDate.discount(libor, paymentDate - discountingDate).mult(discountingAdjustment);
}
/*
* Calculate swaption value
*/
RandomVariableInterface values = valueOfSwapAtExerciseDate.floor(0.0);
RandomVariableInterface numeraire = model.getNumeraire(exerciseDate);
RandomVariableInterface monteCarloProbabilities = model.getMonteCarloWeights(exerciseDate);
values = values.div(numeraire).mult(monteCarloProbabilities);
RandomVariableInterface numeraireAtZero = model.getNumeraire(evaluationTime);
RandomVariableInterface monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime);
values = values.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
return values;
} | [
"@",
"Override",
"public",
"RandomVariableInterface",
"getValue",
"(",
"double",
"evaluationTime",
",",
"LIBORModelMonteCarloSimulationInterface",
"model",
")",
"throws",
"CalculationException",
"{",
"/*\n\t\t * Calculate value of the swap at exercise date on each path (beware of perfe... | This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
Cashflows prior evaluationTime are not considered.
@param evaluationTime The time on which this products value should be observed.
@param model The model used to price the product.
@return The random variable representing the value of the product discounted to evaluation time
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. | [
"This",
"method",
"returns",
"the",
"value",
"random",
"variable",
"of",
"the",
"product",
"within",
"the",
"specified",
"model",
"evaluated",
"at",
"a",
"given",
"evalutationTime",
".",
"Note",
":",
"For",
"a",
"lattice",
"this",
"is",
"often",
"the",
"valu... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/products/Swaption.java#L117-L179 |
BigBadaboom/androidsvg | androidsvg/src/main/java/com/caverock/androidsvg/RenderOptions.java | RenderOptions.viewPort | public RenderOptions viewPort(float minX, float minY, float width, float height)
{
this.viewPort = new SVG.Box(minX, minY, width, height);
return this;
} | java | public RenderOptions viewPort(float minX, float minY, float width, float height)
{
this.viewPort = new SVG.Box(minX, minY, width, height);
return this;
} | [
"public",
"RenderOptions",
"viewPort",
"(",
"float",
"minX",
",",
"float",
"minY",
",",
"float",
"width",
",",
"float",
"height",
")",
"{",
"this",
".",
"viewPort",
"=",
"new",
"SVG",
".",
"Box",
"(",
"minX",
",",
"minY",
",",
"width",
",",
"height",
... | Describes the viewport into which the SVG should be rendered. If this is not specified,
then the whole of the canvas will be used as the viewport. If rendering to a <code>Picture</code>
then a default viewport width and height will be used.
@param minX The left X coordinate of the viewport
@param minY The top Y coordinate of the viewport
@param width The width of the viewport
@param height The height of the viewport
@return this same <code>RenderOptions</code> instance | [
"Describes",
"the",
"viewport",
"into",
"which",
"the",
"SVG",
"should",
"be",
"rendered",
".",
"If",
"this",
"is",
"not",
"specified",
"then",
"the",
"whole",
"of",
"the",
"canvas",
"will",
"be",
"used",
"as",
"the",
"viewport",
".",
"If",
"rendering",
... | train | https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/RenderOptions.java#L201-L205 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/ExamplePicker.java | ExamplePicker.preparePaintComponent | @Override
protected void preparePaintComponent(final Request request) {
super.preparePaintComponent(request);
if (!isInitialised()) {
// Check project versions for Wcomponents-examples and WComponents match
String egVersion = Config.getInstance().getString("wcomponents-examples.version");
String wcVersion = WebUtilities.getProjectVersion();
if (egVersion != null && !egVersion.equals(wcVersion)) {
String msg = "WComponents-Examples version (" + egVersion + ") does not match WComponents version ("
+ wcVersion + ").";
LOG.error(msg);
messages.addMessage(new Message(Message.ERROR_MESSAGE, msg));
}
setInitialised(true);
}
} | java | @Override
protected void preparePaintComponent(final Request request) {
super.preparePaintComponent(request);
if (!isInitialised()) {
// Check project versions for Wcomponents-examples and WComponents match
String egVersion = Config.getInstance().getString("wcomponents-examples.version");
String wcVersion = WebUtilities.getProjectVersion();
if (egVersion != null && !egVersion.equals(wcVersion)) {
String msg = "WComponents-Examples version (" + egVersion + ") does not match WComponents version ("
+ wcVersion + ").";
LOG.error(msg);
messages.addMessage(new Message(Message.ERROR_MESSAGE, msg));
}
setInitialised(true);
}
} | [
"@",
"Override",
"protected",
"void",
"preparePaintComponent",
"(",
"final",
"Request",
"request",
")",
"{",
"super",
".",
"preparePaintComponent",
"(",
"request",
")",
";",
"if",
"(",
"!",
"isInitialised",
"(",
")",
")",
"{",
"// Check project versions for Wcompo... | Override preparePaint in order to set up the resources on first access by a user.
@param request the request being responded to. | [
"Override",
"preparePaint",
"in",
"order",
"to",
"set",
"up",
"the",
"resources",
"on",
"first",
"access",
"by",
"a",
"user",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/picker/ExamplePicker.java#L79-L99 |
real-logic/agrona | agrona/src/main/java/org/agrona/collections/CollectionUtil.java | CollectionUtil.removeIf | public static <T> int removeIf(final List<T> values, final Predicate<T> predicate)
{
int size = values.size();
int total = 0;
for (int i = 0; i < size; )
{
final T value = values.get(i);
if (predicate.test(value))
{
values.remove(i);
total++;
size--;
}
else
{
i++;
}
}
return total;
} | java | public static <T> int removeIf(final List<T> values, final Predicate<T> predicate)
{
int size = values.size();
int total = 0;
for (int i = 0; i < size; )
{
final T value = values.get(i);
if (predicate.test(value))
{
values.remove(i);
total++;
size--;
}
else
{
i++;
}
}
return total;
} | [
"public",
"static",
"<",
"T",
">",
"int",
"removeIf",
"(",
"final",
"List",
"<",
"T",
">",
"values",
",",
"final",
"Predicate",
"<",
"T",
">",
"predicate",
")",
"{",
"int",
"size",
"=",
"values",
".",
"size",
"(",
")",
";",
"int",
"total",
"=",
"... | Remove element from a list if it matches a predicate.
<p>
<b>Note:</b> the list must implement {@link java.util.RandomAccess} to be efficient.
@param values to be iterated over.
@param predicate to test the value against
@param <T> type of the value.
@return the number of items remove. | [
"Remove",
"element",
"from",
"a",
"list",
"if",
"it",
"matches",
"a",
"predicate",
".",
"<p",
">",
"<b",
">",
"Note",
":",
"<",
"/",
"b",
">",
"the",
"list",
"must",
"implement",
"{",
"@link",
"java",
".",
"util",
".",
"RandomAccess",
"}",
"to",
"b... | train | https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/collections/CollectionUtil.java#L113-L134 |
Impetus/Kundera | src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/query/RethinkDBQuery.java | RethinkDBQuery.buildFunction | public static ReqlFunction1 buildFunction(final String colName, final Object obj, final String identifier)
{
return new ReqlFunction1()
{
@Override
public Object apply(ReqlExpr row)
{
switch (identifier)
{
case "<":
return row.g(colName).lt(obj);
case "<=":
return row.g(colName).le(obj);
case ">":
return row.g(colName).gt(obj);
case ">=":
return row.g(colName).ge(obj);
case "=":
return row.g(colName).eq(obj);
default:
logger.error("Operation not supported");
throw new KunderaException("Operation not supported");
}
}
};
} | java | public static ReqlFunction1 buildFunction(final String colName, final Object obj, final String identifier)
{
return new ReqlFunction1()
{
@Override
public Object apply(ReqlExpr row)
{
switch (identifier)
{
case "<":
return row.g(colName).lt(obj);
case "<=":
return row.g(colName).le(obj);
case ">":
return row.g(colName).gt(obj);
case ">=":
return row.g(colName).ge(obj);
case "=":
return row.g(colName).eq(obj);
default:
logger.error("Operation not supported");
throw new KunderaException("Operation not supported");
}
}
};
} | [
"public",
"static",
"ReqlFunction1",
"buildFunction",
"(",
"final",
"String",
"colName",
",",
"final",
"Object",
"obj",
",",
"final",
"String",
"identifier",
")",
"{",
"return",
"new",
"ReqlFunction1",
"(",
")",
"{",
"@",
"Override",
"public",
"Object",
"apply... | Builds the function.
@param colName
the col name
@param obj
the obj
@param identifier
the identifier
@return the reql function1 | [
"Builds",
"the",
"function",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/query/RethinkDBQuery.java#L233-L266 |
alkacon/opencms-core | src-gwt/org/opencms/ui/client/contextmenu/CmsContextMenuWidget.java | CmsContextMenuWidget.createEmptyItemWidget | private CmsContextMenuItemWidget createEmptyItemWidget(
String id,
String caption,
String description,
CmsContextMenuConnector contextMenuConnector) {
CmsContextMenuItemWidget widget = GWT.create(CmsContextMenuItemWidget.class);
widget.setId(id);
widget.setCaption(caption);
widget.setTitle(description);
widget.setIcon(contextMenuConnector.getConnection().getIcon(contextMenuConnector.getResourceUrl(id)));
CmsContextMenuItemWidgetHandler handler = new CmsContextMenuItemWidgetHandler(widget, contextMenuConnector);
widget.addClickHandler(handler);
widget.addMouseOutHandler(handler);
widget.addMouseOverHandler(handler);
widget.addKeyUpHandler(handler);
widget.setRootComponent(this);
return widget;
} | java | private CmsContextMenuItemWidget createEmptyItemWidget(
String id,
String caption,
String description,
CmsContextMenuConnector contextMenuConnector) {
CmsContextMenuItemWidget widget = GWT.create(CmsContextMenuItemWidget.class);
widget.setId(id);
widget.setCaption(caption);
widget.setTitle(description);
widget.setIcon(contextMenuConnector.getConnection().getIcon(contextMenuConnector.getResourceUrl(id)));
CmsContextMenuItemWidgetHandler handler = new CmsContextMenuItemWidgetHandler(widget, contextMenuConnector);
widget.addClickHandler(handler);
widget.addMouseOutHandler(handler);
widget.addMouseOverHandler(handler);
widget.addKeyUpHandler(handler);
widget.setRootComponent(this);
return widget;
} | [
"private",
"CmsContextMenuItemWidget",
"createEmptyItemWidget",
"(",
"String",
"id",
",",
"String",
"caption",
",",
"String",
"description",
",",
"CmsContextMenuConnector",
"contextMenuConnector",
")",
"{",
"CmsContextMenuItemWidget",
"widget",
"=",
"GWT",
".",
"create",
... | Creates new empty menu item.<p>
@param id the id
@param caption the caption
@param description the item description used as tool-tip
@param contextMenuConnector the connector
@return the menu item | [
"Creates",
"new",
"empty",
"menu",
"item",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ui/client/contextmenu/CmsContextMenuWidget.java#L233-L253 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/AnnotationsInner.java | AnnotationsInner.deleteAsync | public Observable<Object> deleteAsync(String resourceGroupName, String resourceName, String annotationId) {
return deleteWithServiceResponseAsync(resourceGroupName, resourceName, annotationId).map(new Func1<ServiceResponse<Object>, Object>() {
@Override
public Object call(ServiceResponse<Object> response) {
return response.body();
}
});
} | java | public Observable<Object> deleteAsync(String resourceGroupName, String resourceName, String annotationId) {
return deleteWithServiceResponseAsync(resourceGroupName, resourceName, annotationId).map(new Func1<ServiceResponse<Object>, Object>() {
@Override
public Object call(ServiceResponse<Object> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Object",
">",
"deleteAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
",",
"String",
"annotationId",
")",
"{",
"return",
"deleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
",",
"anno... | Delete an Annotation of an Application Insights component.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@param annotationId The unique annotation ID. This is unique within a Application Insights component.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Object object | [
"Delete",
"an",
"Annotation",
"of",
"an",
"Application",
"Insights",
"component",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/AnnotationsInner.java#L315-L322 |
Bearded-Hen/Android-Bootstrap | AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapDrawableFactory.java | BootstrapDrawableFactory.createArrowIcon | private static Drawable createArrowIcon(Context context, int width, int height, int color, ExpandDirection expandDirection) {
Bitmap canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(1);
paint.setColor(color);
paint.setAntiAlias(true);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
switch (expandDirection) {
case UP:
path.moveTo(0, (height / 3) * 2);
path.lineTo(width, (height / 3) * 2);
path.lineTo(width / 2, height / 3);
path.lineTo(0, (height / 3) * 2);
break;
case DOWN:
path.moveTo(0, height / 3);
path.lineTo(width, height / 3);
path.lineTo(width / 2, (height / 3) * 2);
path.lineTo(0, height / 3);
break;
}
path.close();
canvas.drawPath(path, paint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
} | java | private static Drawable createArrowIcon(Context context, int width, int height, int color, ExpandDirection expandDirection) {
Bitmap canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(1);
paint.setColor(color);
paint.setAntiAlias(true);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
switch (expandDirection) {
case UP:
path.moveTo(0, (height / 3) * 2);
path.lineTo(width, (height / 3) * 2);
path.lineTo(width / 2, height / 3);
path.lineTo(0, (height / 3) * 2);
break;
case DOWN:
path.moveTo(0, height / 3);
path.lineTo(width, height / 3);
path.lineTo(width / 2, (height / 3) * 2);
path.lineTo(0, height / 3);
break;
}
path.close();
canvas.drawPath(path, paint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
} | [
"private",
"static",
"Drawable",
"createArrowIcon",
"(",
"Context",
"context",
",",
"int",
"width",
",",
"int",
"height",
",",
"int",
"color",
",",
"ExpandDirection",
"expandDirection",
")",
"{",
"Bitmap",
"canvasBitmap",
"=",
"Bitmap",
".",
"createBitmap",
"(",... | Creates arrow icon that depends on ExpandDirection
@param context context
@param width width of icon in pixels
@param height height of icon in pixels
@param color arrow color
@param expandDirection arrow direction
@return icon drawable | [
"Creates",
"arrow",
"icon",
"that",
"depends",
"on",
"ExpandDirection"
] | train | https://github.com/Bearded-Hen/Android-Bootstrap/blob/b3d62cc1847e26d420c53c92665a4fe1e6ee7ecf/AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapDrawableFactory.java#L390-L417 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java | HtmlTree.HEADING | public static HtmlTree HEADING(HtmlTag headingTag, HtmlStyle styleClass, Content body) {
return HEADING(headingTag, false, styleClass, body);
} | java | public static HtmlTree HEADING(HtmlTag headingTag, HtmlStyle styleClass, Content body) {
return HEADING(headingTag, false, styleClass, body);
} | [
"public",
"static",
"HtmlTree",
"HEADING",
"(",
"HtmlTag",
"headingTag",
",",
"HtmlStyle",
"styleClass",
",",
"Content",
"body",
")",
"{",
"return",
"HEADING",
"(",
"headingTag",
",",
"false",
",",
"styleClass",
",",
"body",
")",
";",
"}"
] | Generates a heading tag (h1 to h6) with style class attribute. It also encloses
a content.
@param headingTag the heading tag to be generated
@param styleClass stylesheet class for the tag
@param body content for the tag
@return an HtmlTree object for the tag | [
"Generates",
"a",
"heading",
"tag",
"(",
"h1",
"to",
"h6",
")",
"with",
"style",
"class",
"attribute",
".",
"It",
"also",
"encloses",
"a",
"content",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L413-L415 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/AbstractRedisClient.java | AbstractRedisClient.shutdownAsync | @SuppressWarnings("rawtypes")
public CompletableFuture<Void> shutdownAsync(long quietPeriod, long timeout, TimeUnit timeUnit) {
if (shutdown.compareAndSet(false, true)) {
logger.debug("Initiate shutdown ({}, {}, {})", quietPeriod, timeout, timeUnit);
return closeResources().thenCompose((value) -> closeClientResources(quietPeriod, timeout, timeUnit));
}
return completedFuture(null);
} | java | @SuppressWarnings("rawtypes")
public CompletableFuture<Void> shutdownAsync(long quietPeriod, long timeout, TimeUnit timeUnit) {
if (shutdown.compareAndSet(false, true)) {
logger.debug("Initiate shutdown ({}, {}, {})", quietPeriod, timeout, timeUnit);
return closeResources().thenCompose((value) -> closeClientResources(quietPeriod, timeout, timeUnit));
}
return completedFuture(null);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"CompletableFuture",
"<",
"Void",
">",
"shutdownAsync",
"(",
"long",
"quietPeriod",
",",
"long",
"timeout",
",",
"TimeUnit",
"timeUnit",
")",
"{",
"if",
"(",
"shutdown",
".",
"compareAndSet",
"(",
"f... | Shutdown this client and close all open connections asynchronously. The client should be discarded after calling
shutdown.
@param quietPeriod the quiet period as described in the documentation
@param timeout the maximum amount of time to wait until the executor is shutdown regardless if a task was submitted
during the quiet period
@param timeUnit the unit of {@code quietPeriod} and {@code timeout}
@since 4.4 | [
"Shutdown",
"this",
"client",
"and",
"close",
"all",
"open",
"connections",
"asynchronously",
".",
"The",
"client",
"should",
"be",
"discarded",
"after",
"calling",
"shutdown",
"."
] | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/AbstractRedisClient.java#L431-L441 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java | CollUtil.sortPageAll | @SafeVarargs
public static <T> List<T> sortPageAll(int pageNo, int pageSize, Comparator<T> comparator, Collection<T>... colls) {
final List<T> list = new ArrayList<>(pageNo * pageSize);
for (Collection<T> coll : colls) {
list.addAll(coll);
}
if (null != comparator) {
Collections.sort(list, comparator);
}
return page(pageNo, pageSize, list);
} | java | @SafeVarargs
public static <T> List<T> sortPageAll(int pageNo, int pageSize, Comparator<T> comparator, Collection<T>... colls) {
final List<T> list = new ArrayList<>(pageNo * pageSize);
for (Collection<T> coll : colls) {
list.addAll(coll);
}
if (null != comparator) {
Collections.sort(list, comparator);
}
return page(pageNo, pageSize, list);
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"sortPageAll",
"(",
"int",
"pageNo",
",",
"int",
"pageSize",
",",
"Comparator",
"<",
"T",
">",
"comparator",
",",
"Collection",
"<",
"T",
">",
"...",
"colls",
")",
"{",
"fi... | 将多个集合排序并显示不同的段落(分页)<br>
采用{@link BoundedPriorityQueue}实现分页取局部
@param <T> 集合元素类型
@param pageNo 页码,从1开始计数,0和1效果相同
@param pageSize 每页的条目数
@param comparator 比较器
@param colls 集合数组
@return 分页后的段落内容 | [
"将多个集合排序并显示不同的段落(分页)<br",
">",
"采用",
"{",
"@link",
"BoundedPriorityQueue",
"}",
"实现分页取局部"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java#L2030-L2041 |
redisson/redisson | redisson/src/main/java/org/redisson/spring/cache/RedissonCacheMetrics.java | RedissonCacheMetrics.monitor | public static RedissonCache monitor(MeterRegistry registry, RedissonCache cache, Iterable<Tag> tags) {
new RedissonCacheMetrics(cache, tags).bindTo(registry);
return cache;
} | java | public static RedissonCache monitor(MeterRegistry registry, RedissonCache cache, Iterable<Tag> tags) {
new RedissonCacheMetrics(cache, tags).bindTo(registry);
return cache;
} | [
"public",
"static",
"RedissonCache",
"monitor",
"(",
"MeterRegistry",
"registry",
",",
"RedissonCache",
"cache",
",",
"Iterable",
"<",
"Tag",
">",
"tags",
")",
"{",
"new",
"RedissonCacheMetrics",
"(",
"cache",
",",
"tags",
")",
".",
"bindTo",
"(",
"registry",
... | Record metrics on a Redisson cache.
@param registry - registry to bind metrics to
@param cache - cache to instrument
@param tags - tags to apply to all recorded metrics
@return cache | [
"Record",
"metrics",
"on",
"a",
"Redisson",
"cache",
"."
] | train | https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/spring/cache/RedissonCacheMetrics.java#L44-L47 |
apache/flink | flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/utils/ParquetSchemaConverter.java | ParquetSchemaConverter.toParquetType | public static MessageType toParquetType(TypeInformation<?> typeInformation, boolean legacyMode) {
return (MessageType) convertField(null, typeInformation, Type.Repetition.OPTIONAL, legacyMode);
} | java | public static MessageType toParquetType(TypeInformation<?> typeInformation, boolean legacyMode) {
return (MessageType) convertField(null, typeInformation, Type.Repetition.OPTIONAL, legacyMode);
} | [
"public",
"static",
"MessageType",
"toParquetType",
"(",
"TypeInformation",
"<",
"?",
">",
"typeInformation",
",",
"boolean",
"legacyMode",
")",
"{",
"return",
"(",
"MessageType",
")",
"convertField",
"(",
"null",
",",
"typeInformation",
",",
"Type",
".",
"Repet... | Converts Flink Internal Type to Parquet schema.
@param typeInformation Flink type information
@param legacyMode is standard LIST and MAP schema or back-compatible schema
@return Parquet schema | [
"Converts",
"Flink",
"Internal",
"Type",
"to",
"Parquet",
"schema",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/utils/ParquetSchemaConverter.java#L70-L72 |
jhy/jsoup | src/main/java/org/jsoup/nodes/TextNode.java | TextNode.createFromEncoded | public static TextNode createFromEncoded(String encodedText, String baseUri) {
String text = Entities.unescape(encodedText);
return new TextNode(text);
} | java | public static TextNode createFromEncoded(String encodedText, String baseUri) {
String text = Entities.unescape(encodedText);
return new TextNode(text);
} | [
"public",
"static",
"TextNode",
"createFromEncoded",
"(",
"String",
"encodedText",
",",
"String",
"baseUri",
")",
"{",
"String",
"text",
"=",
"Entities",
".",
"unescape",
"(",
"encodedText",
")",
";",
"return",
"new",
"TextNode",
"(",
"text",
")",
";",
"}"
] | Create a new TextNode from HTML encoded (aka escaped) data.
@param encodedText Text containing encoded HTML (e.g. &lt;)
@param baseUri Base uri
@return TextNode containing unencoded data (e.g. <)
@deprecated use {@link TextNode#createFromEncoded(String)} instead, as LeafNodes don't carry base URIs. | [
"Create",
"a",
"new",
"TextNode",
"from",
"HTML",
"encoded",
"(",
"aka",
"escaped",
")",
"data",
"."
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/TextNode.java#L119-L122 |
Omertron/api-thetvdb | src/main/java/com/omertron/thetvdbapi/tools/TvdbParser.java | TvdbParser.parseList | private static List<String> parseList(String input, String delim) {
List<String> result = new ArrayList<>();
StringTokenizer st = new StringTokenizer(input, delim);
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.length() > 0) {
result.add(token);
}
}
return result;
} | java | private static List<String> parseList(String input, String delim) {
List<String> result = new ArrayList<>();
StringTokenizer st = new StringTokenizer(input, delim);
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.length() > 0) {
result.add(token);
}
}
return result;
} | [
"private",
"static",
"List",
"<",
"String",
">",
"parseList",
"(",
"String",
"input",
",",
"String",
"delim",
")",
"{",
"List",
"<",
"String",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"StringTokenizer",
"st",
"=",
"new",
"StringTokeni... | Create a List from a delimited string
@param input
@param delim | [
"Create",
"a",
"List",
"from",
"a",
"delimited",
"string"
] | train | https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/TvdbParser.java#L421-L433 |
lastaflute/lastaflute | src/main/java/org/lastaflute/core/mail/LaTypicalPostcard.java | LaTypicalPostcard.dryrunByGivenText | public void dryrunByGivenText(String subject, String plainBody, String htmlBody) {
postcard.dryrun();
postcard.overrideBodyFile(subject, plainBody).alsoHtmlBody(htmlBody);
} | java | public void dryrunByGivenText(String subject, String plainBody, String htmlBody) {
postcard.dryrun();
postcard.overrideBodyFile(subject, plainBody).alsoHtmlBody(htmlBody);
} | [
"public",
"void",
"dryrunByGivenText",
"(",
"String",
"subject",
",",
"String",
"plainBody",
",",
"String",
"htmlBody",
")",
"{",
"postcard",
".",
"dryrun",
"(",
")",
";",
"postcard",
".",
"overrideBodyFile",
"(",
"subject",
",",
"plainBody",
")",
".",
"also... | Set up as dry-run by given text. <br>
Not send it actually, only preparation, e.g. for preview. <br>
You can get complete plain or HTML text from postcard.
@param subject The subject as given text. (NotNull)
@param plainBody The plain body (template) as given text. (NotNull)
@param htmlBody The HTML body (template) as given text. (NotNull) | [
"Set",
"up",
"as",
"dry",
"-",
"run",
"by",
"given",
"text",
".",
"<br",
">",
"Not",
"send",
"it",
"actually",
"only",
"preparation",
"e",
".",
"g",
".",
"for",
"preview",
".",
"<br",
">",
"You",
"can",
"get",
"complete",
"plain",
"or",
"HTML",
"te... | train | https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/core/mail/LaTypicalPostcard.java#L340-L343 |
gallandarakhneorg/afc | advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/dfx/OrientedRectangle2dfx.java | OrientedRectangle2dfx.firstAxisProperty | @Pure
public UnitVectorProperty firstAxisProperty() {
if (this.raxis == null) {
this.raxis = new UnitVectorProperty(this, MathFXAttributeNames.FIRST_AXIS, getGeomFactory());
}
return this.raxis;
} | java | @Pure
public UnitVectorProperty firstAxisProperty() {
if (this.raxis == null) {
this.raxis = new UnitVectorProperty(this, MathFXAttributeNames.FIRST_AXIS, getGeomFactory());
}
return this.raxis;
} | [
"@",
"Pure",
"public",
"UnitVectorProperty",
"firstAxisProperty",
"(",
")",
"{",
"if",
"(",
"this",
".",
"raxis",
"==",
"null",
")",
"{",
"this",
".",
"raxis",
"=",
"new",
"UnitVectorProperty",
"(",
"this",
",",
"MathFXAttributeNames",
".",
"FIRST_AXIS",
","... | Replies the property for the first rectangle axis.
@return the firstAxis property. | [
"Replies",
"the",
"property",
"for",
"the",
"first",
"rectangle",
"axis",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/dfx/OrientedRectangle2dfx.java#L271-L277 |
Trilarion/java-vorbis-support | src/main/java/com/github/trilarion/sound/sampled/spi/TAudioFileReader.java | TAudioFileReader.getAudioInputStream | @Override
public AudioInputStream getAudioInputStream(InputStream inputStream)
throws UnsupportedAudioFileException, IOException {
LOG.log(Level.FINE, "TAudioFileReader.getAudioInputStream(InputStream): begin (class: {0})", getClass().getSimpleName());
long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED;
AudioInputStream audioInputStream = null;
if (!inputStream.markSupported()) {
inputStream = new BufferedInputStream(inputStream, getMarkLimit());
}
inputStream.mark(getMarkLimit());
try {
audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes);
} catch (UnsupportedAudioFileException e) {
inputStream.reset();
throw e;
} catch (IOException e) {
try {
inputStream.reset();
} catch (IOException e2) {
if (e2.getCause() == null) {
e2.initCause(e);
throw e2;
}
}
throw e;
}
LOG.log(Level.FINE, "TAudioFileReader.getAudioInputStream(InputStream): end");
return audioInputStream;
} | java | @Override
public AudioInputStream getAudioInputStream(InputStream inputStream)
throws UnsupportedAudioFileException, IOException {
LOG.log(Level.FINE, "TAudioFileReader.getAudioInputStream(InputStream): begin (class: {0})", getClass().getSimpleName());
long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED;
AudioInputStream audioInputStream = null;
if (!inputStream.markSupported()) {
inputStream = new BufferedInputStream(inputStream, getMarkLimit());
}
inputStream.mark(getMarkLimit());
try {
audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes);
} catch (UnsupportedAudioFileException e) {
inputStream.reset();
throw e;
} catch (IOException e) {
try {
inputStream.reset();
} catch (IOException e2) {
if (e2.getCause() == null) {
e2.initCause(e);
throw e2;
}
}
throw e;
}
LOG.log(Level.FINE, "TAudioFileReader.getAudioInputStream(InputStream): end");
return audioInputStream;
} | [
"@",
"Override",
"public",
"AudioInputStream",
"getAudioInputStream",
"(",
"InputStream",
"inputStream",
")",
"throws",
"UnsupportedAudioFileException",
",",
"IOException",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"TAudioFileReader.getAudioInputStream(Inp... | Get an AudioInputStream object for an InputStream. This method calls
getAudioInputStream(InputStream, long). Subclasses should not override
this method unless there are really severe reasons. Normally, it is
sufficient to implement getAudioFileFormat(InputStream, long) and perhaps
override getAudioInputStream(InputStream, long).
@param inputStream the stream to read from.
@return an AudioInputStream instance containing the audio data from this
stream.
@throws javax.sound.sampled.UnsupportedAudioFileException
@throws java.io.IOException | [
"Get",
"an",
"AudioInputStream",
"object",
"for",
"an",
"InputStream",
".",
"This",
"method",
"calls",
"getAudioInputStream",
"(",
"InputStream",
"long",
")",
".",
"Subclasses",
"should",
"not",
"override",
"this",
"method",
"unless",
"there",
"are",
"really",
"... | train | https://github.com/Trilarion/java-vorbis-support/blob/f72aba7d97167fe0ff20b1b719fdb5bb662ff736/src/main/java/com/github/trilarion/sound/sampled/spi/TAudioFileReader.java#L251-L279 |
wcm-io/wcm-io-handler | commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java | HtmlElement.setStyle | public final T setStyle(String styleAttribute, String styleValue) {
// Add style to style map
Map<String, String> styleMap = getStyles();
styleMap.put(styleAttribute, styleValue);
// Serialize style string
StringBuilder styleString = new StringBuilder();
for (Map.Entry style : styleMap.entrySet()) {
styleString.append(style.getKey());
styleString.append(':');
styleString.append(style.getValue());
styleString.append(';');
}
setStyleString(styleString.toString());
return (T)this;
} | java | public final T setStyle(String styleAttribute, String styleValue) {
// Add style to style map
Map<String, String> styleMap = getStyles();
styleMap.put(styleAttribute, styleValue);
// Serialize style string
StringBuilder styleString = new StringBuilder();
for (Map.Entry style : styleMap.entrySet()) {
styleString.append(style.getKey());
styleString.append(':');
styleString.append(style.getValue());
styleString.append(';');
}
setStyleString(styleString.toString());
return (T)this;
} | [
"public",
"final",
"T",
"setStyle",
"(",
"String",
"styleAttribute",
",",
"String",
"styleValue",
")",
"{",
"// Add style to style map",
"Map",
"<",
"String",
",",
"String",
">",
"styleMap",
"=",
"getStyles",
"(",
")",
";",
"styleMap",
".",
"put",
"(",
"styl... | Html "style" attribute. Sets single style attribute value.
@param styleAttribute Style attribute name
@param styleValue Style attribute value
@return Self reference | [
"Html",
"style",
"attribute",
".",
"Sets",
"single",
"style",
"attribute",
"value",
"."
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java#L195-L211 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/TemplateSubPatternAssociation.java | TemplateSubPatternAssociation.matchModes | private boolean matchModes(QName m1, QName m2)
{
return (((null == m1) && (null == m2))
|| ((null != m1) && (null != m2) && m1.equals(m2)));
} | java | private boolean matchModes(QName m1, QName m2)
{
return (((null == m1) && (null == m2))
|| ((null != m1) && (null != m2) && m1.equals(m2)));
} | [
"private",
"boolean",
"matchModes",
"(",
"QName",
"m1",
",",
"QName",
"m2",
")",
"{",
"return",
"(",
"(",
"(",
"null",
"==",
"m1",
")",
"&&",
"(",
"null",
"==",
"m2",
")",
")",
"||",
"(",
"(",
"null",
"!=",
"m1",
")",
"&&",
"(",
"null",
"!=",
... | Tell if two modes match according to the rules of XSLT.
@param m1 First mode to match
@param m2 Second mode to match
@return True if the two given modes match | [
"Tell",
"if",
"two",
"modes",
"match",
"according",
"to",
"the",
"rules",
"of",
"XSLT",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/TemplateSubPatternAssociation.java#L134-L138 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/imports/descriptors/tensorflow/TensorflowDescriptorParser.java | TensorflowDescriptorParser.opDescs | public static synchronized Map<String,OpDef> opDescs() {
if(DESCRIPTORS != null){
return DESCRIPTORS;
}
try (InputStream contents = new ClassPathResource("ops.proto").getInputStream(); BufferedInputStream bis2 = new BufferedInputStream(contents); BufferedReader reader = new BufferedReader(new InputStreamReader(bis2))) {
org.tensorflow.framework.OpList.Builder builder = org.tensorflow.framework.OpList.newBuilder();
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);//.append("\n");
}
TextFormat.getParser().merge(str.toString(), builder);
List<OpDef> list = builder.getOpList();
Map<String,OpDef> map = new HashMap<>();
for(OpDef opDef : list) {
map.put(opDef.getName(),opDef);
}
DESCRIPTORS = map;
return DESCRIPTORS;
} catch (Exception e) {
throw new ND4JIllegalStateException("Unable to load tensorflow descriptors", e);
}
} | java | public static synchronized Map<String,OpDef> opDescs() {
if(DESCRIPTORS != null){
return DESCRIPTORS;
}
try (InputStream contents = new ClassPathResource("ops.proto").getInputStream(); BufferedInputStream bis2 = new BufferedInputStream(contents); BufferedReader reader = new BufferedReader(new InputStreamReader(bis2))) {
org.tensorflow.framework.OpList.Builder builder = org.tensorflow.framework.OpList.newBuilder();
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);//.append("\n");
}
TextFormat.getParser().merge(str.toString(), builder);
List<OpDef> list = builder.getOpList();
Map<String,OpDef> map = new HashMap<>();
for(OpDef opDef : list) {
map.put(opDef.getName(),opDef);
}
DESCRIPTORS = map;
return DESCRIPTORS;
} catch (Exception e) {
throw new ND4JIllegalStateException("Unable to load tensorflow descriptors", e);
}
} | [
"public",
"static",
"synchronized",
"Map",
"<",
"String",
",",
"OpDef",
">",
"opDescs",
"(",
")",
"{",
"if",
"(",
"DESCRIPTORS",
"!=",
"null",
")",
"{",
"return",
"DESCRIPTORS",
";",
"}",
"try",
"(",
"InputStream",
"contents",
"=",
"new",
"ClassPathResourc... | Get the op descriptors for tensorflow
@return the op descriptors for tensorflow
@throws Exception | [
"Get",
"the",
"op",
"descriptors",
"for",
"tensorflow"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/imports/descriptors/tensorflow/TensorflowDescriptorParser.java#L41-L69 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/GroupApi.java | GroupApi.getMember | public Member getMember(Object groupIdOrPath, int userId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "groups", getGroupIdOrPath(groupIdOrPath), "members", userId);
return (response.readEntity(new GenericType<Member>() {}));
} | java | public Member getMember(Object groupIdOrPath, int userId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "groups", getGroupIdOrPath(groupIdOrPath), "members", userId);
return (response.readEntity(new GenericType<Member>() {}));
} | [
"public",
"Member",
"getMember",
"(",
"Object",
"groupIdOrPath",
",",
"int",
"userId",
")",
"throws",
"GitLabApiException",
"{",
"Response",
"response",
"=",
"get",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"getDefaultPerPageParam",
"(",
")",
",",
"\"gro... | Get a group member viewable by the authenticated user.
<pre><code>GitLab Endpoint: GET /groups/:id/members/:id</code></pre>
@param groupIdOrPath the group ID, path of the group, or a Group instance holding the group ID or path
@param userId the member ID of the member to get
@return a member viewable by the authenticated user
@throws GitLabApiException if any exception occurs | [
"Get",
"a",
"group",
"member",
"viewable",
"by",
"the",
"authenticated",
"user",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GroupApi.java#L731-L734 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java | DeferredAttr.isDeferred | boolean isDeferred(Env<AttrContext> env, JCExpression expr) {
DeferredChecker dc = new DeferredChecker(env);
dc.scan(expr);
return dc.result.isPoly();
} | java | boolean isDeferred(Env<AttrContext> env, JCExpression expr) {
DeferredChecker dc = new DeferredChecker(env);
dc.scan(expr);
return dc.result.isPoly();
} | [
"boolean",
"isDeferred",
"(",
"Env",
"<",
"AttrContext",
">",
"env",
",",
"JCExpression",
"expr",
")",
"{",
"DeferredChecker",
"dc",
"=",
"new",
"DeferredChecker",
"(",
"env",
")",
";",
"dc",
".",
"scan",
"(",
"expr",
")",
";",
"return",
"dc",
".",
"re... | Does the argument expression {@code expr} need speculative type-checking? | [
"Does",
"the",
"argument",
"expression",
"{"
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java#L1098-L1102 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java | ExceptionUtils.firstOrSuppressed | public static <T extends Throwable> T firstOrSuppressed(T newException, @Nullable T previous) {
checkNotNull(newException, "newException");
if (previous == null) {
return newException;
} else {
previous.addSuppressed(newException);
return previous;
}
} | java | public static <T extends Throwable> T firstOrSuppressed(T newException, @Nullable T previous) {
checkNotNull(newException, "newException");
if (previous == null) {
return newException;
} else {
previous.addSuppressed(newException);
return previous;
}
} | [
"public",
"static",
"<",
"T",
"extends",
"Throwable",
">",
"T",
"firstOrSuppressed",
"(",
"T",
"newException",
",",
"@",
"Nullable",
"T",
"previous",
")",
"{",
"checkNotNull",
"(",
"newException",
",",
"\"newException\"",
")",
";",
"if",
"(",
"previous",
"==... | Adds a new exception as a {@link Throwable#addSuppressed(Throwable) suppressed exception}
to a prior exception, or returns the new exception, if no prior exception exists.
<pre>{@code
public void closeAllThings() throws Exception {
Exception ex = null;
try {
component.shutdown();
} catch (Exception e) {
ex = firstOrSuppressed(e, ex);
}
try {
anotherComponent.stop();
} catch (Exception e) {
ex = firstOrSuppressed(e, ex);
}
try {
lastComponent.shutdown();
} catch (Exception e) {
ex = firstOrSuppressed(e, ex);
}
if (ex != null) {
throw ex;
}
}
}</pre>
@param newException The newly occurred exception
@param previous The previously occurred exception, possibly null.
@return The new exception, if no previous exception exists, or the previous exception with the
new exception in the list of suppressed exceptions. | [
"Adds",
"a",
"new",
"exception",
"as",
"a",
"{",
"@link",
"Throwable#addSuppressed",
"(",
"Throwable",
")",
"suppressed",
"exception",
"}",
"to",
"a",
"prior",
"exception",
"or",
"returns",
"the",
"new",
"exception",
"if",
"no",
"prior",
"exception",
"exists",... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java#L173-L182 |
hawtio/hawtio | hawtio-system/src/main/java/io/hawt/web/auth/keycloak/KeycloakUserServlet.java | KeycloakUserServlet.getKeycloakUsername | protected String getKeycloakUsername(final HttpServletRequest req, HttpServletResponse resp) {
AtomicReference<String> username = new AtomicReference<>();
Authenticator.authenticate(
authConfiguration, req,
subject -> {
username.set(AuthHelpers.getUsername(subject));
// Start httpSession
req.getSession(true);
}
);
return username.get();
} | java | protected String getKeycloakUsername(final HttpServletRequest req, HttpServletResponse resp) {
AtomicReference<String> username = new AtomicReference<>();
Authenticator.authenticate(
authConfiguration, req,
subject -> {
username.set(AuthHelpers.getUsername(subject));
// Start httpSession
req.getSession(true);
}
);
return username.get();
} | [
"protected",
"String",
"getKeycloakUsername",
"(",
"final",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"{",
"AtomicReference",
"<",
"String",
">",
"username",
"=",
"new",
"AtomicReference",
"<>",
"(",
")",
";",
"Authenticator",
".",
"aut... | With Keycloak integration, the Authorization header is available in the request to the UserServlet. | [
"With",
"Keycloak",
"integration",
"the",
"Authorization",
"header",
"is",
"available",
"in",
"the",
"request",
"to",
"the",
"UserServlet",
"."
] | train | https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/hawtio-system/src/main/java/io/hawt/web/auth/keycloak/KeycloakUserServlet.java#L39-L51 |
sailthru/sailthru-java-client | src/main/com/sailthru/client/AbstractSailthruClient.java | AbstractSailthruClient.apiPost | public JsonResponse apiPost(ApiAction action, Map<String, Object> data) throws IOException {
return httpRequestJson(action, HttpRequestMethod.POST, data);
} | java | public JsonResponse apiPost(ApiAction action, Map<String, Object> data) throws IOException {
return httpRequestJson(action, HttpRequestMethod.POST, data);
} | [
"public",
"JsonResponse",
"apiPost",
"(",
"ApiAction",
"action",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
")",
"throws",
"IOException",
"{",
"return",
"httpRequestJson",
"(",
"action",
",",
"HttpRequestMethod",
".",
"POST",
",",
"data",
")",
";... | HTTP POST Request with Map
@param action
@param data
@throws IOException | [
"HTTP",
"POST",
"Request",
"with",
"Map"
] | train | https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L271-L273 |
sdl/odata | odata_client/src/main/java/com/sdl/odata/client/URLConnectionRequestPropertiesBuilder.java | URLConnectionRequestPropertiesBuilder.withCookie | public URLConnectionRequestPropertiesBuilder withCookie(String cookieName, String cookieValue) {
if (requestProperties.containsKey("Cookie")) {
// there are existing cookies so just append the new cookie at the end
final String cookies = requestProperties.get("Cookie");
requestProperties.put("Cookie", cookies + COOKIES_SEPARATOR + buildCookie(cookieName, cookieValue));
} else {
// this is the first cookie to be added
requestProperties.put("Cookie", buildCookie(cookieName, cookieValue));
}
return this;
} | java | public URLConnectionRequestPropertiesBuilder withCookie(String cookieName, String cookieValue) {
if (requestProperties.containsKey("Cookie")) {
// there are existing cookies so just append the new cookie at the end
final String cookies = requestProperties.get("Cookie");
requestProperties.put("Cookie", cookies + COOKIES_SEPARATOR + buildCookie(cookieName, cookieValue));
} else {
// this is the first cookie to be added
requestProperties.put("Cookie", buildCookie(cookieName, cookieValue));
}
return this;
} | [
"public",
"URLConnectionRequestPropertiesBuilder",
"withCookie",
"(",
"String",
"cookieName",
",",
"String",
"cookieValue",
")",
"{",
"if",
"(",
"requestProperties",
".",
"containsKey",
"(",
"\"Cookie\"",
")",
")",
"{",
"// there are existing cookies so just append the new ... | Add provided cookie to 'Cookie' request property.
@param cookieName The cookie name
@param cookieValue The ccokie value
@return this | [
"Add",
"provided",
"cookie",
"to",
"Cookie",
"request",
"property",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_client/src/main/java/com/sdl/odata/client/URLConnectionRequestPropertiesBuilder.java#L36-L46 |
VoltDB/voltdb | src/frontend/org/voltdb/NonVoltDBBackend.java | NonVoltDBBackend.handleParens | protected String handleParens(String group, String prefix, String suffix, boolean debugPrint) {
return prefix + group + suffix;
} | java | protected String handleParens(String group, String prefix, String suffix, boolean debugPrint) {
return prefix + group + suffix;
} | [
"protected",
"String",
"handleParens",
"(",
"String",
"group",
",",
"String",
"prefix",
",",
"String",
"suffix",
",",
"boolean",
"debugPrint",
")",
"{",
"return",
"prefix",
"+",
"group",
"+",
"suffix",
";",
"}"
] | This base version simply returns a String consisting of the <i>prefix</i>,
<i>group</i>, and <i>suffix</i> concatenated (in that order); however,
it may be overridden to do something more complicated, to make sure that
the prefix and suffix go in the right place, relative to any parentheses
found in the group. | [
"This",
"base",
"version",
"simply",
"returns",
"a",
"String",
"consisting",
"of",
"the",
"<i",
">",
"prefix<",
"/",
"i",
">",
"<i",
">",
"group<",
"/",
"i",
">",
"and",
"<i",
">",
"suffix<",
"/",
"i",
">",
"concatenated",
"(",
"in",
"that",
"order",... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/NonVoltDBBackend.java#L704-L706 |
opengeospatial/teamengine | teamengine-spi-ctl/src/main/java/com/occamlab/te/spi/ctl/CtlExecutor.java | CtlExecutor.getResultsFile | File getResultsFile(String mediaType, String outputDirectory) throws FileNotFoundException {
// split out any media type parameters
String contentType = mediaType.split(";")[0];
String fileName = null;
if(contentType.endsWith("rdf+xml") || contentType.endsWith("rdf+earl")){
fileName = "earl-results.rdf";
} else if(contentType.endsWith("zip")){
File htmlResult = HtmlReport.getHtmlResultZip(outputDirectory);
fileName = "result.zip";
} else{
fileName = "report_logs.xml";
}
File resultsFile = new File(outputDirectory, fileName);
if (!resultsFile.exists()) {
throw new FileNotFoundException("Test run results not found at " + resultsFile.getAbsolutePath());
}
return resultsFile;
} | java | File getResultsFile(String mediaType, String outputDirectory) throws FileNotFoundException {
// split out any media type parameters
String contentType = mediaType.split(";")[0];
String fileName = null;
if(contentType.endsWith("rdf+xml") || contentType.endsWith("rdf+earl")){
fileName = "earl-results.rdf";
} else if(contentType.endsWith("zip")){
File htmlResult = HtmlReport.getHtmlResultZip(outputDirectory);
fileName = "result.zip";
} else{
fileName = "report_logs.xml";
}
File resultsFile = new File(outputDirectory, fileName);
if (!resultsFile.exists()) {
throw new FileNotFoundException("Test run results not found at " + resultsFile.getAbsolutePath());
}
return resultsFile;
} | [
"File",
"getResultsFile",
"(",
"String",
"mediaType",
",",
"String",
"outputDirectory",
")",
"throws",
"FileNotFoundException",
"{",
"// split out any media type parameters",
"String",
"contentType",
"=",
"mediaType",
".",
"split",
"(",
"\";\"",
")",
"[",
"0",
"]",
... | Returns the test results in the specified format. The default media type
is "application/xml", but "application/rdf+xml" (RDF/XML) is also
supported.
@param mediaType
The media type of the test results (XML or RDF/XML).
@param outputDirectory
The directory containing the test run output.
@return A File containing the test results.
@throws FileNotFoundException
If no test results are found. | [
"Returns",
"the",
"test",
"results",
"in",
"the",
"specified",
"format",
".",
"The",
"default",
"media",
"type",
"is",
"application",
"/",
"xml",
"but",
"application",
"/",
"rdf",
"+",
"xml",
"(",
"RDF",
"/",
"XML",
")",
"is",
"also",
"supported",
"."
] | train | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-spi-ctl/src/main/java/com/occamlab/te/spi/ctl/CtlExecutor.java#L169-L187 |
ThreeTen/threeten-extra | src/main/java/org/threeten/extra/scale/TaiInstant.java | TaiInstant.minus | public TaiInstant minus(Duration duration) {
long secsToSubtract = duration.getSeconds();
int nanosToSubtract = duration.getNano();
if ((secsToSubtract | nanosToSubtract) == 0) {
return this;
}
long secs = Math.subtractExact(seconds, secsToSubtract);
long nanoAdjustment = ((long) nanos) - nanosToSubtract; // safe int+int
return ofTaiSeconds(secs, nanoAdjustment);
} | java | public TaiInstant minus(Duration duration) {
long secsToSubtract = duration.getSeconds();
int nanosToSubtract = duration.getNano();
if ((secsToSubtract | nanosToSubtract) == 0) {
return this;
}
long secs = Math.subtractExact(seconds, secsToSubtract);
long nanoAdjustment = ((long) nanos) - nanosToSubtract; // safe int+int
return ofTaiSeconds(secs, nanoAdjustment);
} | [
"public",
"TaiInstant",
"minus",
"(",
"Duration",
"duration",
")",
"{",
"long",
"secsToSubtract",
"=",
"duration",
".",
"getSeconds",
"(",
")",
";",
"int",
"nanosToSubtract",
"=",
"duration",
".",
"getNano",
"(",
")",
";",
"if",
"(",
"(",
"secsToSubtract",
... | Returns a copy of this instant with the specified duration subtracted.
<p>
The duration is subtracted using simple subtraction of the seconds and nanoseconds
in the duration from the seconds and nanoseconds of this instant.
As a result, the duration is treated as being measured in TAI compatible seconds
for the purpose of this method.
<p>
This instance is immutable and unaffected by this method call.
@param duration the duration to subtract, not null
@return a {@code TaiInstant} based on this instant with the duration subtracted, not null
@throws ArithmeticException if the calculation exceeds the supported range | [
"Returns",
"a",
"copy",
"of",
"this",
"instant",
"with",
"the",
"specified",
"duration",
"subtracted",
".",
"<p",
">",
"The",
"duration",
"is",
"subtracted",
"using",
"simple",
"subtraction",
"of",
"the",
"seconds",
"and",
"nanoseconds",
"in",
"the",
"duration... | train | https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/scale/TaiInstant.java#L334-L343 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShippingMethodPersistenceImpl.java | CommerceShippingMethodPersistenceImpl.countByG_E | @Override
public int countByG_E(long groupId, String engineKey) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_E;
Object[] finderArgs = new Object[] { groupId, engineKey };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_COMMERCESHIPPINGMETHOD_WHERE);
query.append(_FINDER_COLUMN_G_E_GROUPID_2);
boolean bindEngineKey = false;
if (engineKey == null) {
query.append(_FINDER_COLUMN_G_E_ENGINEKEY_1);
}
else if (engineKey.equals("")) {
query.append(_FINDER_COLUMN_G_E_ENGINEKEY_3);
}
else {
bindEngineKey = true;
query.append(_FINDER_COLUMN_G_E_ENGINEKEY_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (bindEngineKey) {
qPos.add(engineKey);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | java | @Override
public int countByG_E(long groupId, String engineKey) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_E;
Object[] finderArgs = new Object[] { groupId, engineKey };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_COMMERCESHIPPINGMETHOD_WHERE);
query.append(_FINDER_COLUMN_G_E_GROUPID_2);
boolean bindEngineKey = false;
if (engineKey == null) {
query.append(_FINDER_COLUMN_G_E_ENGINEKEY_1);
}
else if (engineKey.equals("")) {
query.append(_FINDER_COLUMN_G_E_ENGINEKEY_3);
}
else {
bindEngineKey = true;
query.append(_FINDER_COLUMN_G_E_ENGINEKEY_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (bindEngineKey) {
qPos.add(engineKey);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | [
"@",
"Override",
"public",
"int",
"countByG_E",
"(",
"long",
"groupId",
",",
"String",
"engineKey",
")",
"{",
"FinderPath",
"finderPath",
"=",
"FINDER_PATH_COUNT_BY_G_E",
";",
"Object",
"[",
"]",
"finderArgs",
"=",
"new",
"Object",
"[",
"]",
"{",
"groupId",
... | Returns the number of commerce shipping methods where groupId = ? and engineKey = ?.
@param groupId the group ID
@param engineKey the engine key
@return the number of matching commerce shipping methods | [
"Returns",
"the",
"number",
"of",
"commerce",
"shipping",
"methods",
"where",
"groupId",
"=",
"?",
";",
"and",
"engineKey",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShippingMethodPersistenceImpl.java#L789-L850 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java | JBBPBitOutputStream.writeInt | public void writeInt(final int value, final JBBPByteOrder byteOrder) throws IOException {
if (byteOrder == JBBPByteOrder.BIG_ENDIAN) {
this.writeShort(value >>> 16, byteOrder);
this.writeShort(value, byteOrder);
} else {
this.writeShort(value, byteOrder);
this.writeShort(value >>> 16, byteOrder);
}
} | java | public void writeInt(final int value, final JBBPByteOrder byteOrder) throws IOException {
if (byteOrder == JBBPByteOrder.BIG_ENDIAN) {
this.writeShort(value >>> 16, byteOrder);
this.writeShort(value, byteOrder);
} else {
this.writeShort(value, byteOrder);
this.writeShort(value >>> 16, byteOrder);
}
} | [
"public",
"void",
"writeInt",
"(",
"final",
"int",
"value",
",",
"final",
"JBBPByteOrder",
"byteOrder",
")",
"throws",
"IOException",
"{",
"if",
"(",
"byteOrder",
"==",
"JBBPByteOrder",
".",
"BIG_ENDIAN",
")",
"{",
"this",
".",
"writeShort",
"(",
"value",
">... | Write an integer value into the output stream.
@param value a value to be written into the output stream.
@param byteOrder the byte order of the value bytes to be used for writing.
@throws IOException it will be thrown for transport errors
@see JBBPByteOrder#BIG_ENDIAN
@see JBBPByteOrder#LITTLE_ENDIAN | [
"Write",
"an",
"integer",
"value",
"into",
"the",
"output",
"stream",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPBitOutputStream.java#L111-L119 |
eclipse/xtext-core | org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/rename/RenameService2.java | RenameService2.mayPerformRename | protected boolean mayPerformRename(final Either<Range, PrepareRenameResult> prepareRenameResult, final RenameParams renameParams) {
return (((prepareRenameResult != null) && (prepareRenameResult.getLeft() != null)) &&
Ranges.containsPosition(prepareRenameResult.getLeft(), renameParams.getPosition()));
} | java | protected boolean mayPerformRename(final Either<Range, PrepareRenameResult> prepareRenameResult, final RenameParams renameParams) {
return (((prepareRenameResult != null) && (prepareRenameResult.getLeft() != null)) &&
Ranges.containsPosition(prepareRenameResult.getLeft(), renameParams.getPosition()));
} | [
"protected",
"boolean",
"mayPerformRename",
"(",
"final",
"Either",
"<",
"Range",
",",
"PrepareRenameResult",
">",
"prepareRenameResult",
",",
"final",
"RenameParams",
"renameParams",
")",
"{",
"return",
"(",
"(",
"(",
"prepareRenameResult",
"!=",
"null",
")",
"&&... | If this method returns {@code false}, it is sure, that the rename operation will fail.
There is no guarantee that it will succeed even if it returns {@code true}. | [
"If",
"this",
"method",
"returns",
"{"
] | train | https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/rename/RenameService2.java#L328-L331 |
google/jimfs | jimfs/src/main/java/com/google/common/jimfs/JimfsFileSystems.java | JimfsFileSystems.newFileSystem | public static JimfsFileSystem newFileSystem(
JimfsFileSystemProvider provider, URI uri, Configuration config) throws IOException {
PathService pathService = new PathService(config);
FileSystemState state = new FileSystemState(removeFileSystemRunnable(uri));
JimfsFileStore fileStore = createFileStore(config, pathService, state);
FileSystemView defaultView = createDefaultView(config, fileStore, pathService);
WatchServiceConfiguration watchServiceConfig = config.watchServiceConfig;
JimfsFileSystem fileSystem =
new JimfsFileSystem(provider, uri, fileStore, pathService, defaultView, watchServiceConfig);
pathService.setFileSystem(fileSystem);
return fileSystem;
} | java | public static JimfsFileSystem newFileSystem(
JimfsFileSystemProvider provider, URI uri, Configuration config) throws IOException {
PathService pathService = new PathService(config);
FileSystemState state = new FileSystemState(removeFileSystemRunnable(uri));
JimfsFileStore fileStore = createFileStore(config, pathService, state);
FileSystemView defaultView = createDefaultView(config, fileStore, pathService);
WatchServiceConfiguration watchServiceConfig = config.watchServiceConfig;
JimfsFileSystem fileSystem =
new JimfsFileSystem(provider, uri, fileStore, pathService, defaultView, watchServiceConfig);
pathService.setFileSystem(fileSystem);
return fileSystem;
} | [
"public",
"static",
"JimfsFileSystem",
"newFileSystem",
"(",
"JimfsFileSystemProvider",
"provider",
",",
"URI",
"uri",
",",
"Configuration",
"config",
")",
"throws",
"IOException",
"{",
"PathService",
"pathService",
"=",
"new",
"PathService",
"(",
"config",
")",
";"... | Initialize and configure a new file system with the given provider and URI, using the given
configuration. | [
"Initialize",
"and",
"configure",
"a",
"new",
"file",
"system",
"with",
"the",
"given",
"provider",
"and",
"URI",
"using",
"the",
"given",
"configuration",
"."
] | train | https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/JimfsFileSystems.java#L68-L82 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java | BinaryRowProtocol.getInternalBigInteger | public BigInteger getInternalBigInteger(ColumnInformation columnInfo) throws SQLException {
if (lastValueWasNull()) {
return null;
}
switch (columnInfo.getColumnType()) {
case BIT:
return BigInteger.valueOf((long) buf[pos]);
case TINYINT:
return BigInteger.valueOf((long)
(columnInfo.isSigned() ? buf[pos] : (buf[pos] & 0xff)));
case SMALLINT:
case YEAR:
short valueShort = (short) ((buf[pos] & 0xff) | ((buf[pos + 1] & 0xff) << 8));
return BigInteger
.valueOf((long) (columnInfo.isSigned() ? valueShort : (valueShort & 0xffff)));
case INTEGER:
case MEDIUMINT:
int valueInt = ((buf[pos] & 0xff)
+ ((buf[pos + 1] & 0xff) << 8)
+ ((buf[pos + 2] & 0xff) << 16)
+ ((buf[pos + 3] & 0xff) << 24));
return BigInteger.valueOf(((columnInfo.isSigned()) ? valueInt
: (valueInt >= 0) ? valueInt : valueInt & 0xffffffffL));
case BIGINT:
long value = ((buf[pos] & 0xff)
+ ((long) (buf[pos + 1] & 0xff) << 8)
+ ((long) (buf[pos + 2] & 0xff) << 16)
+ ((long) (buf[pos + 3] & 0xff) << 24)
+ ((long) (buf[pos + 4] & 0xff) << 32)
+ ((long) (buf[pos + 5] & 0xff) << 40)
+ ((long) (buf[pos + 6] & 0xff) << 48)
+ ((long) (buf[pos + 7] & 0xff) << 56)
);
if (columnInfo.isSigned()) {
return BigInteger.valueOf(value);
} else {
return new BigInteger(1, new byte[]{(byte) (value >> 56),
(byte) (value >> 48), (byte) (value >> 40), (byte) (value >> 32),
(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8),
(byte) value});
}
case FLOAT:
return BigInteger.valueOf((long) getInternalFloat(columnInfo));
case DOUBLE:
return BigInteger.valueOf((long) getInternalDouble(columnInfo));
case DECIMAL:
case OLDDECIMAL:
return BigInteger.valueOf(getInternalBigDecimal(columnInfo).longValue());
default:
return new BigInteger(new String(buf, pos, length, StandardCharsets.UTF_8));
}
} | java | public BigInteger getInternalBigInteger(ColumnInformation columnInfo) throws SQLException {
if (lastValueWasNull()) {
return null;
}
switch (columnInfo.getColumnType()) {
case BIT:
return BigInteger.valueOf((long) buf[pos]);
case TINYINT:
return BigInteger.valueOf((long)
(columnInfo.isSigned() ? buf[pos] : (buf[pos] & 0xff)));
case SMALLINT:
case YEAR:
short valueShort = (short) ((buf[pos] & 0xff) | ((buf[pos + 1] & 0xff) << 8));
return BigInteger
.valueOf((long) (columnInfo.isSigned() ? valueShort : (valueShort & 0xffff)));
case INTEGER:
case MEDIUMINT:
int valueInt = ((buf[pos] & 0xff)
+ ((buf[pos + 1] & 0xff) << 8)
+ ((buf[pos + 2] & 0xff) << 16)
+ ((buf[pos + 3] & 0xff) << 24));
return BigInteger.valueOf(((columnInfo.isSigned()) ? valueInt
: (valueInt >= 0) ? valueInt : valueInt & 0xffffffffL));
case BIGINT:
long value = ((buf[pos] & 0xff)
+ ((long) (buf[pos + 1] & 0xff) << 8)
+ ((long) (buf[pos + 2] & 0xff) << 16)
+ ((long) (buf[pos + 3] & 0xff) << 24)
+ ((long) (buf[pos + 4] & 0xff) << 32)
+ ((long) (buf[pos + 5] & 0xff) << 40)
+ ((long) (buf[pos + 6] & 0xff) << 48)
+ ((long) (buf[pos + 7] & 0xff) << 56)
);
if (columnInfo.isSigned()) {
return BigInteger.valueOf(value);
} else {
return new BigInteger(1, new byte[]{(byte) (value >> 56),
(byte) (value >> 48), (byte) (value >> 40), (byte) (value >> 32),
(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8),
(byte) value});
}
case FLOAT:
return BigInteger.valueOf((long) getInternalFloat(columnInfo));
case DOUBLE:
return BigInteger.valueOf((long) getInternalDouble(columnInfo));
case DECIMAL:
case OLDDECIMAL:
return BigInteger.valueOf(getInternalBigDecimal(columnInfo).longValue());
default:
return new BigInteger(new String(buf, pos, length, StandardCharsets.UTF_8));
}
} | [
"public",
"BigInteger",
"getInternalBigInteger",
"(",
"ColumnInformation",
"columnInfo",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"lastValueWasNull",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"switch",
"(",
"columnInfo",
".",
"getColumnType",
"(",
")... | Get BigInteger from raw binary format.
@param columnInfo column information
@return BigInteger value
@throws SQLException if column type doesn't permit conversion or value is not in BigInteger
range | [
"Get",
"BigInteger",
"from",
"raw",
"binary",
"format",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L1305-L1356 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java | EnumHelper.getFromIDOrNull | @Nullable
public static <KEYTYPE, ENUMTYPE extends Enum <ENUMTYPE> & IHasID <KEYTYPE>> ENUMTYPE getFromIDOrNull (@Nonnull final Class <ENUMTYPE> aClass,
@Nullable final KEYTYPE aID)
{
return getFromIDOrDefault (aClass, aID, null);
} | java | @Nullable
public static <KEYTYPE, ENUMTYPE extends Enum <ENUMTYPE> & IHasID <KEYTYPE>> ENUMTYPE getFromIDOrNull (@Nonnull final Class <ENUMTYPE> aClass,
@Nullable final KEYTYPE aID)
{
return getFromIDOrDefault (aClass, aID, null);
} | [
"@",
"Nullable",
"public",
"static",
"<",
"KEYTYPE",
",",
"ENUMTYPE",
"extends",
"Enum",
"<",
"ENUMTYPE",
">",
"&",
"IHasID",
"<",
"KEYTYPE",
">",
">",
"ENUMTYPE",
"getFromIDOrNull",
"(",
"@",
"Nonnull",
"final",
"Class",
"<",
"ENUMTYPE",
">",
"aClass",
",... | Get the enum value with the passed ID
@param <KEYTYPE>
The ID type
@param <ENUMTYPE>
The enum type
@param aClass
The enum class
@param aID
The ID to search
@return <code>null</code> if no enum item with the given ID is present. | [
"Get",
"the",
"enum",
"value",
"with",
"the",
"passed",
"ID"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/EnumHelper.java#L101-L106 |
twilio/twilio-java | src/main/java/com/twilio/base/Page.java | Page.getPreviousPageUrl | public String getPreviousPageUrl(String domain, String region) {
if (previousPageUrl != null) {
return previousPageUrl;
}
return urlFromUri(domain, region, previousPageUri);
} | java | public String getPreviousPageUrl(String domain, String region) {
if (previousPageUrl != null) {
return previousPageUrl;
}
return urlFromUri(domain, region, previousPageUri);
} | [
"public",
"String",
"getPreviousPageUrl",
"(",
"String",
"domain",
",",
"String",
"region",
")",
"{",
"if",
"(",
"previousPageUrl",
"!=",
"null",
")",
"{",
"return",
"previousPageUrl",
";",
"}",
"return",
"urlFromUri",
"(",
"domain",
",",
"region",
",",
"pre... | Generate previous page url for a list result.
@param domain domain to use
@param region region to use
@return the previous page url | [
"Generate",
"previous",
"page",
"url",
"for",
"a",
"list",
"result",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/base/Page.java#L83-L89 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java | BingImagesImpl.detailsAsync | public ServiceFuture<ImageInsights> detailsAsync(String query, DetailsOptionalParameter detailsOptionalParameter, final ServiceCallback<ImageInsights> serviceCallback) {
return ServiceFuture.fromResponse(detailsWithServiceResponseAsync(query, detailsOptionalParameter), serviceCallback);
} | java | public ServiceFuture<ImageInsights> detailsAsync(String query, DetailsOptionalParameter detailsOptionalParameter, final ServiceCallback<ImageInsights> serviceCallback) {
return ServiceFuture.fromResponse(detailsWithServiceResponseAsync(query, detailsOptionalParameter), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"ImageInsights",
">",
"detailsAsync",
"(",
"String",
"query",
",",
"DetailsOptionalParameter",
"detailsOptionalParameter",
",",
"final",
"ServiceCallback",
"<",
"ImageInsights",
">",
"serviceCallback",
")",
"{",
"return",
"ServiceFuture",
... | The Image Detail Search API lets you search on Bing and get back insights about an image, such as webpages that include the image. This section provides technical details about the query parameters and headers that you use to request insights of images and the JSON response objects that contain them. For examples that show how to make requests, see [Searching the Web for Images](https://docs.microsoft.com/azure/cognitive-services/bing-image-search/search-the-web).
@param query The user's search query term. The term cannot be empty. The term may contain [Bing Advanced Operators](http://msdn.microsoft.com/library/ff795620.aspx). For example, to limit images to a specific domain, use the [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To help improve relevance of an insights query (see [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)), you should always include the user's query term. Use this parameter only with the Image Search API.Do not specify this parameter when calling the Trending Images API.
@param detailsOptionalParameter the object representing the optional parameters to be set before calling this API
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"The",
"Image",
"Detail",
"Search",
"API",
"lets",
"you",
"search",
"on",
"Bing",
"and",
"get",
"back",
"insights",
"about",
"an",
"image",
"such",
"as",
"webpages",
"that",
"include",
"the",
"image",
".",
"This",
"section",
"provides",
"technical",
"details... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java#L490-L492 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java | CommerceOrderPersistenceImpl.findByG_U_O | @Override
public List<CommerceOrder> findByG_U_O(long groupId, long userId,
int orderStatus, int start, int end) {
return findByG_U_O(groupId, userId, orderStatus, start, end, null);
} | java | @Override
public List<CommerceOrder> findByG_U_O(long groupId, long userId,
int orderStatus, int start, int end) {
return findByG_U_O(groupId, userId, orderStatus, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceOrder",
">",
"findByG_U_O",
"(",
"long",
"groupId",
",",
"long",
"userId",
",",
"int",
"orderStatus",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByG_U_O",
"(",
"groupId",
",",
"userId",... | Returns a range of all the commerce orders where groupId = ? and userId = ? and orderStatus = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param userId the user ID
@param orderStatus the order status
@param start the lower bound of the range of commerce orders
@param end the upper bound of the range of commerce orders (not inclusive)
@return the range of matching commerce orders | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"orders",
"where",
"groupId",
"=",
"?",
";",
"and",
"userId",
"=",
"?",
";",
"and",
"orderStatus",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L4127-L4131 |
baratine/baratine | framework/src/main/java/com/caucho/v5/javac/JavaWriter.java | JavaWriter.setLocation | public void setLocation(String filename, int line) throws IOException
{
if (_lineMap != null && filename != null && line >= 0) {
_lineMap.add(filename, line, _destLine, _isPreferLast);
}
} | java | public void setLocation(String filename, int line) throws IOException
{
if (_lineMap != null && filename != null && line >= 0) {
_lineMap.add(filename, line, _destLine, _isPreferLast);
}
} | [
"public",
"void",
"setLocation",
"(",
"String",
"filename",
",",
"int",
"line",
")",
"throws",
"IOException",
"{",
"if",
"(",
"_lineMap",
"!=",
"null",
"&&",
"filename",
"!=",
"null",
"&&",
"line",
">=",
"0",
")",
"{",
"_lineMap",
".",
"add",
"(",
"fil... | Sets the source filename and line.
@param filename
the filename of the source file.
@param line
the line of the source file. | [
"Sets",
"the",
"source",
"filename",
"and",
"line",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/javac/JavaWriter.java#L114-L119 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/ShareLinkManager.java | ShareLinkManager.addLinkToClipBoard | @SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void addLinkToClipBoard(String url, String label) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(url);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText(label, url);
clipboard.setPrimaryClip(clip);
}
Toast.makeText(context_, builder_.getUrlCopiedMessage(), Toast.LENGTH_SHORT).show();
} | java | @SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void addLinkToClipBoard(String url, String label) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(url);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText(label, url);
clipboard.setPrimaryClip(clip);
}
Toast.makeText(context_, builder_.getUrlCopiedMessage(), Toast.LENGTH_SHORT).show();
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"@",
"SuppressLint",
"(",
"\"NewApi\"",
")",
"private",
"void",
"addLinkToClipBoard",
"(",
"String",
"url",
",",
"String",
"label",
")",
"{",
"int",
"sdk",
"=",
"android",
".",
"os",
".",
"Build",
".",
... | Adds a given link to the clip board.
@param url A {@link String} to add to the clip board
@param label A {@link String} label for the adding link | [
"Adds",
"a",
"given",
"link",
"to",
"the",
"clip",
"board",
"."
] | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ShareLinkManager.java#L345-L358 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexManager.java | IndexManager.fetchRelation | public final Map<String, Object> fetchRelation(Class<?> clazz, String query)
{
// TODO: need to return list.
return search(clazz, query, Constants.INVALID, Constants.INVALID, true);
} | java | public final Map<String, Object> fetchRelation(Class<?> clazz, String query)
{
// TODO: need to return list.
return search(clazz, query, Constants.INVALID, Constants.INVALID, true);
} | [
"public",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"fetchRelation",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"query",
")",
"{",
"// TODO: need to return list.",
"return",
"search",
"(",
"clazz",
",",
"query",
",",
"Constants",
".",
"I... | Searches on the index. Note: Query must be in Indexer's understandable
format
@param query
the query
@return the list | [
"Searches",
"on",
"the",
"index",
".",
"Note",
":",
"Query",
"must",
"be",
"in",
"Indexer",
"s",
"understandable",
"format"
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexManager.java#L327-L331 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/VirtualHubsInner.java | VirtualHubsInner.beginUpdateTagsAsync | public Observable<VirtualHubInner> beginUpdateTagsAsync(String resourceGroupName, String virtualHubName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualHubName, tags).map(new Func1<ServiceResponse<VirtualHubInner>, VirtualHubInner>() {
@Override
public VirtualHubInner call(ServiceResponse<VirtualHubInner> response) {
return response.body();
}
});
} | java | public Observable<VirtualHubInner> beginUpdateTagsAsync(String resourceGroupName, String virtualHubName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualHubName, tags).map(new Func1<ServiceResponse<VirtualHubInner>, VirtualHubInner>() {
@Override
public VirtualHubInner call(ServiceResponse<VirtualHubInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VirtualHubInner",
">",
"beginUpdateTagsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualHubName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"beginUpdateTagsWithServiceResponseAsync",
"(",... | Updates VirtualHub tags.
@param resourceGroupName The resource group name of the VirtualHub.
@param virtualHubName The name of the VirtualHub.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VirtualHubInner object | [
"Updates",
"VirtualHub",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/VirtualHubsInner.java#L629-L636 |
Frostman/dropbox4j | src/main/java/ru/frostman/dropbox/api/DropboxClient.java | DropboxClient.getAccountInfo | public AccountInfo getAccountInfo() {
OAuthRequest request = new OAuthRequest(Verb.GET, INFO_URL);
service.signRequest(accessToken, request);
String content = check(request.send()).getBody();
return Json.parse(content, AccountInfo.class);
} | java | public AccountInfo getAccountInfo() {
OAuthRequest request = new OAuthRequest(Verb.GET, INFO_URL);
service.signRequest(accessToken, request);
String content = check(request.send()).getBody();
return Json.parse(content, AccountInfo.class);
} | [
"public",
"AccountInfo",
"getAccountInfo",
"(",
")",
"{",
"OAuthRequest",
"request",
"=",
"new",
"OAuthRequest",
"(",
"Verb",
".",
"GET",
",",
"INFO_URL",
")",
";",
"service",
".",
"signRequest",
"(",
"accessToken",
",",
"request",
")",
";",
"String",
"conte... | Returns information about current user's account.
@return info about user's account
@see AccountInfo | [
"Returns",
"information",
"about",
"current",
"user",
"s",
"account",
"."
] | train | https://github.com/Frostman/dropbox4j/blob/774c817e5bf294d0139ecb5ac81399be50ada5e0/src/main/java/ru/frostman/dropbox/api/DropboxClient.java#L85-L91 |
languagetool-org/languagetool | languagetool-server/src/main/java/org/languagetool/server/ResultExtender.java | ResultExtender.getFilteredExtensionMatches | @NotNull
List<RuleMatch> getFilteredExtensionMatches(List<RuleMatch> matches, List<RemoteRuleMatch> extensionMatches) {
List<RuleMatch> filteredExtMatches = new ArrayList<>();
for (RemoteRuleMatch extensionMatch : extensionMatches) {
if (!extensionMatch.isTouchedByOneOf(matches)) {
AnalyzedSentence sentence = new AnalyzedSentence(new AnalyzedTokenReadings[]{});
HiddenRule hiddenRule = new HiddenRule(extensionMatch.getLocQualityIssueType().orElse(null), extensionMatch.estimatedContextForSureMatch());
RuleMatch hiddenRuleMatch = new RuleMatch(hiddenRule, sentence, extensionMatch.getErrorOffset(),
extensionMatch.getErrorOffset()+extensionMatch.getErrorLength(), "(hidden message)");
filteredExtMatches.add(hiddenRuleMatch);
}
}
return filteredExtMatches;
} | java | @NotNull
List<RuleMatch> getFilteredExtensionMatches(List<RuleMatch> matches, List<RemoteRuleMatch> extensionMatches) {
List<RuleMatch> filteredExtMatches = new ArrayList<>();
for (RemoteRuleMatch extensionMatch : extensionMatches) {
if (!extensionMatch.isTouchedByOneOf(matches)) {
AnalyzedSentence sentence = new AnalyzedSentence(new AnalyzedTokenReadings[]{});
HiddenRule hiddenRule = new HiddenRule(extensionMatch.getLocQualityIssueType().orElse(null), extensionMatch.estimatedContextForSureMatch());
RuleMatch hiddenRuleMatch = new RuleMatch(hiddenRule, sentence, extensionMatch.getErrorOffset(),
extensionMatch.getErrorOffset()+extensionMatch.getErrorLength(), "(hidden message)");
filteredExtMatches.add(hiddenRuleMatch);
}
}
return filteredExtMatches;
} | [
"@",
"NotNull",
"List",
"<",
"RuleMatch",
">",
"getFilteredExtensionMatches",
"(",
"List",
"<",
"RuleMatch",
">",
"matches",
",",
"List",
"<",
"RemoteRuleMatch",
">",
"extensionMatches",
")",
"{",
"List",
"<",
"RuleMatch",
">",
"filteredExtMatches",
"=",
"new",
... | Filter {@code extensionMatches} so that only those matches are left that don't cover or touch one of the {@code matches}. | [
"Filter",
"{"
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-server/src/main/java/org/languagetool/server/ResultExtender.java#L71-L84 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowControllerFactory.java | FlowControllerFactory.getPageFlowForPath | public PageFlowController getPageFlowForPath( RequestContext context, String path )
throws InstantiationException, IllegalAccessException
{
HttpServletRequest request = context.getHttpRequest();
HttpServletResponse response = context.getHttpResponse();
PageFlowController cur = PageFlowUtils.getCurrentPageFlow( request, getServletContext() );
String parentDir = PageFlowUtils.getModulePathForRelativeURI( path );
//
// Reinitialize transient data that may have been lost on session failover.
//
if ( cur != null )
cur.reinitialize( request, response, getServletContext() );
//
// If there's no current PageFlow, or if the current PageFlowController has a module path that
// is incompatible with the current request URI, then create the appropriate PageFlowController.
//
if ( cur == null || ! PageFlowUtils.getModulePathForRelativeURI( cur.getURI() ).equals( parentDir ) )
{
String className = null;
try
{
className = InternalUtils.getFlowControllerClassName( parentDir, request, getServletContext() );
return className != null ? createPageFlow( context, className ) : null;
}
catch ( ClassNotFoundException e )
{
if ( LOG.isInfoEnabled() )
LOG.info("No page flow exists for path " + path +
". Unable to load class \"" + className + "\". Cause: " + e, e);
return null;
}
}
return cur;
} | java | public PageFlowController getPageFlowForPath( RequestContext context, String path )
throws InstantiationException, IllegalAccessException
{
HttpServletRequest request = context.getHttpRequest();
HttpServletResponse response = context.getHttpResponse();
PageFlowController cur = PageFlowUtils.getCurrentPageFlow( request, getServletContext() );
String parentDir = PageFlowUtils.getModulePathForRelativeURI( path );
//
// Reinitialize transient data that may have been lost on session failover.
//
if ( cur != null )
cur.reinitialize( request, response, getServletContext() );
//
// If there's no current PageFlow, or if the current PageFlowController has a module path that
// is incompatible with the current request URI, then create the appropriate PageFlowController.
//
if ( cur == null || ! PageFlowUtils.getModulePathForRelativeURI( cur.getURI() ).equals( parentDir ) )
{
String className = null;
try
{
className = InternalUtils.getFlowControllerClassName( parentDir, request, getServletContext() );
return className != null ? createPageFlow( context, className ) : null;
}
catch ( ClassNotFoundException e )
{
if ( LOG.isInfoEnabled() )
LOG.info("No page flow exists for path " + path +
". Unable to load class \"" + className + "\". Cause: " + e, e);
return null;
}
}
return cur;
} | [
"public",
"PageFlowController",
"getPageFlowForPath",
"(",
"RequestContext",
"context",
",",
"String",
"path",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
"{",
"HttpServletRequest",
"request",
"=",
"context",
".",
"getHttpRequest",
"(",
")",
... | Get the page flow instance that should be associated with the given path. If it doesn't exist, create it.
If one is created, the page flow stack (for nesting) will be cleared or pushed, and the new instance will be
stored as the current page flow.
@param context a {@link RequestContext} object which contains the current request and response.
@param path a <strong>webapp-relative</strong> path. The path should not contain the webapp context path.
@return the {@link PageFlowController} for the given path, or <code>null</code> if none was found. | [
"Get",
"the",
"page",
"flow",
"instance",
"that",
"should",
"be",
"associated",
"with",
"the",
"given",
"path",
".",
"If",
"it",
"doesn",
"t",
"exist",
"create",
"it",
".",
"If",
"one",
"is",
"created",
"the",
"page",
"flow",
"stack",
"(",
"for",
"nest... | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowControllerFactory.java#L139-L175 |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java | KeyUtils.addMBeanIdentifier | private static void addMBeanIdentifier(Query query, Result result, StringBuilder sb) {
if (result.getKeyAlias() != null) {
sb.append(result.getKeyAlias());
} else if (query.isUseObjDomainAsKey()) {
sb.append(StringUtils.cleanupStr(result.getObjDomain(), query.isAllowDottedKeys()));
} else {
sb.append(StringUtils.cleanupStr(result.getClassName()));
}
} | java | private static void addMBeanIdentifier(Query query, Result result, StringBuilder sb) {
if (result.getKeyAlias() != null) {
sb.append(result.getKeyAlias());
} else if (query.isUseObjDomainAsKey()) {
sb.append(StringUtils.cleanupStr(result.getObjDomain(), query.isAllowDottedKeys()));
} else {
sb.append(StringUtils.cleanupStr(result.getClassName()));
}
} | [
"private",
"static",
"void",
"addMBeanIdentifier",
"(",
"Query",
"query",
",",
"Result",
"result",
",",
"StringBuilder",
"sb",
")",
"{",
"if",
"(",
"result",
".",
"getKeyAlias",
"(",
")",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"result",
".",
... | Adds a key to the StringBuilder
It uses in order of preference:
1. resultAlias if that was specified as part of the query
2. The domain portion of the ObjectName in the query if useObjDomainAsKey is set to true
3. else, the Class Name of the MBean. I.e. ClassName will be used by default if the
user doesn't specify anything special
@param query
@param result
@param sb | [
"Adds",
"a",
"key",
"to",
"the",
"StringBuilder"
] | train | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java#L127-L135 |
igniterealtime/Smack | smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java | SASLMechanism.challengeReceived | public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackSaslException, InterruptedException, NotConnectedException {
byte[] challenge = Base64.decode((challengeString != null && challengeString.equals("=")) ? "" : challengeString);
byte[] response = evaluateChallenge(challenge);
if (finalChallenge) {
return;
}
Response responseStanza;
if (response == null) {
responseStanza = new Response();
}
else {
responseStanza = new Response(Base64.encodeToString(response));
}
// Send the authentication to the server
connection.sendNonza(responseStanza);
} | java | public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackSaslException, InterruptedException, NotConnectedException {
byte[] challenge = Base64.decode((challengeString != null && challengeString.equals("=")) ? "" : challengeString);
byte[] response = evaluateChallenge(challenge);
if (finalChallenge) {
return;
}
Response responseStanza;
if (response == null) {
responseStanza = new Response();
}
else {
responseStanza = new Response(Base64.encodeToString(response));
}
// Send the authentication to the server
connection.sendNonza(responseStanza);
} | [
"public",
"final",
"void",
"challengeReceived",
"(",
"String",
"challengeString",
",",
"boolean",
"finalChallenge",
")",
"throws",
"SmackSaslException",
",",
"InterruptedException",
",",
"NotConnectedException",
"{",
"byte",
"[",
"]",
"challenge",
"=",
"Base64",
".",
... | The server is challenging the SASL mechanism for the stanza he just sent. Send a
response to the server's challenge.
@param challengeString a base64 encoded string representing the challenge.
@param finalChallenge true if this is the last challenge send by the server within the success stanza
@throws SmackSaslException if a SASL related error occurs.
@throws InterruptedException if the connection is interrupted
@throws NotConnectedException | [
"The",
"server",
"is",
"challenging",
"the",
"SASL",
"mechanism",
"for",
"the",
"stanza",
"he",
"just",
"sent",
".",
"Send",
"a",
"response",
"to",
"the",
"server",
"s",
"challenge",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/sasl/SASLMechanism.java#L227-L244 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java | JSONHelpers.hasBoolean | public static boolean hasBoolean(final JSONObject json, final String key,
final boolean coerce) {
if (!coerce) {
return hasBoolean(json, key);
}
// This could be trivially implemented as
// `return JSON.toBoolean(json.opt(key)) != null`
// but JSON is not public
Object o = json.opt(key);
if (o == null || o == JSONObject.NULL) {
return false;
}
if (o instanceof Boolean) {
return true;
}
if (o instanceof Integer || o instanceof Long) {
final Long num = (Long) o;
return num == 0 || num == 1;
}
if (o instanceof String) {
final String s = (String) o;
return s.compareToIgnoreCase("false") == 0
|| s.compareToIgnoreCase("true") == 0;
}
return false;
} | java | public static boolean hasBoolean(final JSONObject json, final String key,
final boolean coerce) {
if (!coerce) {
return hasBoolean(json, key);
}
// This could be trivially implemented as
// `return JSON.toBoolean(json.opt(key)) != null`
// but JSON is not public
Object o = json.opt(key);
if (o == null || o == JSONObject.NULL) {
return false;
}
if (o instanceof Boolean) {
return true;
}
if (o instanceof Integer || o instanceof Long) {
final Long num = (Long) o;
return num == 0 || num == 1;
}
if (o instanceof String) {
final String s = (String) o;
return s.compareToIgnoreCase("false") == 0
|| s.compareToIgnoreCase("true") == 0;
}
return false;
} | [
"public",
"static",
"boolean",
"hasBoolean",
"(",
"final",
"JSONObject",
"json",
",",
"final",
"String",
"key",
",",
"final",
"boolean",
"coerce",
")",
"{",
"if",
"(",
"!",
"coerce",
")",
"{",
"return",
"hasBoolean",
"(",
"json",
",",
"key",
")",
";",
... | Check if the value at {@code key} is a {@link Boolean} or can,
optionally, be coerced into a {@code Boolean}.
@param json {@link JSONObject} to inspect
@param key Item in object to check
@param coerce If {@code true}, check if the value can be coerced to
{@code Boolean}
@return {@code True} if the item exists and is a {@code Boolean};
{@code false} otherwise | [
"Check",
"if",
"the",
"value",
"at",
"{",
"@code",
"key",
"}",
"is",
"a",
"{",
"@link",
"Boolean",
"}",
"or",
"can",
"optionally",
"be",
"coerced",
"into",
"a",
"{",
"@code",
"Boolean",
"}",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L853-L879 |
osglworks/java-di | src/main/java/org/osgl/inject/util/AnnotationUtil.java | AnnotationUtil.tagAnnotation | public static <T extends Annotation> T tagAnnotation(Annotation annotation, Class<T> tagClass) {
Class<?> c = annotation.annotationType();
for (Annotation a : c.getAnnotations()) {
if (tagClass.isInstance(a)) {
return (T) a;
}
}
return null;
} | java | public static <T extends Annotation> T tagAnnotation(Annotation annotation, Class<T> tagClass) {
Class<?> c = annotation.annotationType();
for (Annotation a : c.getAnnotations()) {
if (tagClass.isInstance(a)) {
return (T) a;
}
}
return null;
} | [
"public",
"static",
"<",
"T",
"extends",
"Annotation",
">",
"T",
"tagAnnotation",
"(",
"Annotation",
"annotation",
",",
"Class",
"<",
"T",
">",
"tagClass",
")",
"{",
"Class",
"<",
"?",
">",
"c",
"=",
"annotation",
".",
"annotationType",
"(",
")",
";",
... | Returns the {@link Annotation} tagged on another annotation instance.
@param annotation
the annotation instance
@param tagClass
the expected annotation class
@param <T>
the generic type of the expected annotation
@return
the annotation tagged on annotation of type `tagClass` | [
"Returns",
"the",
"{",
"@link",
"Annotation",
"}",
"tagged",
"on",
"another",
"annotation",
"instance",
"."
] | train | https://github.com/osglworks/java-di/blob/d89871c62ff508733bfa645425596f6c917fd7ee/src/main/java/org/osgl/inject/util/AnnotationUtil.java#L75-L83 |
lestard/advanced-bindings | src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java | MathBindings.copySign | public static FloatBinding copySign(final ObservableFloatValue magnitude, ObservableFloatValue sign) {
return createFloatBinding(() -> Math.copySign(magnitude.get(), sign.get()), magnitude, sign);
} | java | public static FloatBinding copySign(final ObservableFloatValue magnitude, ObservableFloatValue sign) {
return createFloatBinding(() -> Math.copySign(magnitude.get(), sign.get()), magnitude, sign);
} | [
"public",
"static",
"FloatBinding",
"copySign",
"(",
"final",
"ObservableFloatValue",
"magnitude",
",",
"ObservableFloatValue",
"sign",
")",
"{",
"return",
"createFloatBinding",
"(",
"(",
")",
"->",
"Math",
".",
"copySign",
"(",
"magnitude",
".",
"get",
"(",
")"... | Binding for {@link java.lang.Math#copySign(float, float)}
@param magnitude the parameter providing the magnitude of the result
@param sign the parameter providing the sign of the result
@return a value with the magnitude of {@code magnitude}
and the sign of {@code sign}. | [
"Binding",
"for",
"{",
"@link",
"java",
".",
"lang",
".",
"Math#copySign",
"(",
"float",
"float",
")",
"}"
] | train | https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java#L300-L302 |
sonyxperiadev/gerrit-events | src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritJsonEventFactory.java | GerritJsonEventFactory.getDate | public static Date getDate(JSONObject json, String key) {
return getDate(json, key, null);
} | java | public static Date getDate(JSONObject json, String key) {
return getDate(json, key, null);
} | [
"public",
"static",
"Date",
"getDate",
"(",
"JSONObject",
"json",
",",
"String",
"key",
")",
"{",
"return",
"getDate",
"(",
"json",
",",
"key",
",",
"null",
")",
";",
"}"
] | Returns the value of a JSON property as a Date if it exists otherwise returns null.
@param json the JSONObject to check.
@param key the key.
@return the value for the key as a Date. | [
"Returns",
"the",
"value",
"of",
"a",
"JSON",
"property",
"as",
"a",
"Date",
"if",
"it",
"exists",
"otherwise",
"returns",
"null",
"."
] | train | https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritJsonEventFactory.java#L263-L265 |
Cornutum/tcases | tcases-io/src/main/java/org/cornutum/tcases/io/ProjectJson.java | ProjectJson.asRefBase | private static URI asRefBase( JsonString uri)
{
try
{
return
uri == null
? null
: new URI( uri.getChars().toString());
}
catch( Exception e)
{
throw new ProjectException( String.format( "Error defining reference base=%s", uri), e);
}
} | java | private static URI asRefBase( JsonString uri)
{
try
{
return
uri == null
? null
: new URI( uri.getChars().toString());
}
catch( Exception e)
{
throw new ProjectException( String.format( "Error defining reference base=%s", uri), e);
}
} | [
"private",
"static",
"URI",
"asRefBase",
"(",
"JsonString",
"uri",
")",
"{",
"try",
"{",
"return",
"uri",
"==",
"null",
"?",
"null",
":",
"new",
"URI",
"(",
"uri",
".",
"getChars",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"catch",
"(",
... | Returns the reference base URI represented by the given JSON string. | [
"Returns",
"the",
"reference",
"base",
"URI",
"represented",
"by",
"the",
"given",
"JSON",
"string",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/io/ProjectJson.java#L57-L70 |
apache/flink | flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java | ExecutionEnvironment.fromParallelCollection | public <X> DataSource<X> fromParallelCollection(SplittableIterator<X> iterator, TypeInformation<X> type) {
return fromParallelCollection(iterator, type, Utils.getCallLocationName());
} | java | public <X> DataSource<X> fromParallelCollection(SplittableIterator<X> iterator, TypeInformation<X> type) {
return fromParallelCollection(iterator, type, Utils.getCallLocationName());
} | [
"public",
"<",
"X",
">",
"DataSource",
"<",
"X",
">",
"fromParallelCollection",
"(",
"SplittableIterator",
"<",
"X",
">",
"iterator",
",",
"TypeInformation",
"<",
"X",
">",
"type",
")",
"{",
"return",
"fromParallelCollection",
"(",
"iterator",
",",
"type",
"... | Creates a new data set that contains elements in the iterator. The iterator is splittable, allowing the
framework to create a parallel data source that returns the elements in the iterator.
<p>Because the iterator will remain unmodified until the actual execution happens, the type of data
returned by the iterator must be given explicitly in the form of the type information.
This method is useful for cases where the type is generic. In that case, the type class
(as given in {@link #fromParallelCollection(SplittableIterator, Class)} does not supply all type information.
@param iterator The iterator that produces the elements of the data set.
@param type The TypeInformation for the produced data set.
@return A DataSet representing the elements in the iterator.
@see #fromParallelCollection(SplittableIterator, Class) | [
"Creates",
"a",
"new",
"data",
"set",
"that",
"contains",
"elements",
"in",
"the",
"iterator",
".",
"The",
"iterator",
"is",
"splittable",
"allowing",
"the",
"framework",
"to",
"create",
"a",
"parallel",
"data",
"source",
"that",
"returns",
"the",
"elements",
... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java#L779-L781 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.