repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
mapbox/mapbox-java | services-geojson/src/main/java/com/mapbox/geojson/FeatureCollection.java | FeatureCollection.fromFeature | public static FeatureCollection fromFeature(@NonNull Feature feature,
@Nullable BoundingBox bbox) {
List<Feature> featureList = Arrays.asList(feature);
return new FeatureCollection(TYPE, bbox, featureList);
} | java | public static FeatureCollection fromFeature(@NonNull Feature feature,
@Nullable BoundingBox bbox) {
List<Feature> featureList = Arrays.asList(feature);
return new FeatureCollection(TYPE, bbox, featureList);
} | [
"public",
"static",
"FeatureCollection",
"fromFeature",
"(",
"@",
"NonNull",
"Feature",
"feature",
",",
"@",
"Nullable",
"BoundingBox",
"bbox",
")",
"{",
"List",
"<",
"Feature",
">",
"featureList",
"=",
"Arrays",
".",
"asList",
"(",
"feature",
")",
";",
"ret... | Create a new instance of this class by giving the feature collection a single {@link Feature}.
@param feature a single feature
@param bbox optionally include a bbox definition as a double array
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0 | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"by",
"giving",
"the",
"feature",
"collection",
"a",
"single",
"{",
"@link",
"Feature",
"}",
"."
] | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/FeatureCollection.java#L152-L156 |
jbundle/jbundle | base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HBasePanel.java | HBasePanel.printHtmlFooter | public void printHtmlFooter(PrintWriter out, ResourceBundle reg)
{
String strHTML = reg.getString("htmlFooter");
if ((strHTML == null) || (strHTML.length() == 0))
strHTML = "</body>\n</html>";
out.println(strHTML);
out.flush();
} | java | public void printHtmlFooter(PrintWriter out, ResourceBundle reg)
{
String strHTML = reg.getString("htmlFooter");
if ((strHTML == null) || (strHTML.length() == 0))
strHTML = "</body>\n</html>";
out.println(strHTML);
out.flush();
} | [
"public",
"void",
"printHtmlFooter",
"(",
"PrintWriter",
"out",
",",
"ResourceBundle",
"reg",
")",
"{",
"String",
"strHTML",
"=",
"reg",
".",
"getString",
"(",
"\"htmlFooter\"",
")",
";",
"if",
"(",
"(",
"strHTML",
"==",
"null",
")",
"||",
"(",
"strHTML",
... | Bottom of HTML form.
@param out The html out stream.
@param reg The resources object. | [
"Bottom",
"of",
"HTML",
"form",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HBasePanel.java#L237-L244 |
lucee/Lucee | loader/src/main/java/lucee/loader/osgi/BundleUtil.java | BundleUtil.addBundle | public static Bundle addBundle(final CFMLEngineFactory factory, final BundleContext context, final File bundle, final Log log) throws IOException, BundleException {
return addBundle(factory, context, bundle.getAbsolutePath(), new FileInputStream(bundle), true, log);
} | java | public static Bundle addBundle(final CFMLEngineFactory factory, final BundleContext context, final File bundle, final Log log) throws IOException, BundleException {
return addBundle(factory, context, bundle.getAbsolutePath(), new FileInputStream(bundle), true, log);
} | [
"public",
"static",
"Bundle",
"addBundle",
"(",
"final",
"CFMLEngineFactory",
"factory",
",",
"final",
"BundleContext",
"context",
",",
"final",
"File",
"bundle",
",",
"final",
"Log",
"log",
")",
"throws",
"IOException",
",",
"BundleException",
"{",
"return",
"a... | /*
public static Bundle addBundlex(BundleContext context,File bundle, boolean start) throws
IOException, BundleException { return addBundle(context,bundle.getAbsolutePath(),bundle,start); } | [
"/",
"*",
"public",
"static",
"Bundle",
"addBundlex",
"(",
"BundleContext",
"context",
"File",
"bundle",
"boolean",
"start",
")",
"throws",
"IOException",
"BundleException",
"{",
"return",
"addBundle",
"(",
"context",
"bundle",
".",
"getAbsolutePath",
"()",
"bundl... | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/loader/src/main/java/lucee/loader/osgi/BundleUtil.java#L45-L48 |
infinispan/infinispan | server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/RemoveAliasCommand.java | RemoveAliasCommand.removeAliasFromList | private ModelNode removeAliasFromList(ModelNode list, String alias) throws OperationFailedException {
// check for empty string
if (alias == null || alias.equals(""))
return list ;
// check for undefined list (AS7-3476)
if (!list.isDefined()) {
throw InfinispanMessages.MESSAGES.cannotRemoveAliasFromEmptyList(alias);
}
ModelNode newList = new ModelNode() ;
List<ModelNode> listElements = list.asList();
for (ModelNode listElement : listElements) {
if (!listElement.asString().equals(alias)) {
newList.add().set(listElement);
}
}
return newList ;
} | java | private ModelNode removeAliasFromList(ModelNode list, String alias) throws OperationFailedException {
// check for empty string
if (alias == null || alias.equals(""))
return list ;
// check for undefined list (AS7-3476)
if (!list.isDefined()) {
throw InfinispanMessages.MESSAGES.cannotRemoveAliasFromEmptyList(alias);
}
ModelNode newList = new ModelNode() ;
List<ModelNode> listElements = list.asList();
for (ModelNode listElement : listElements) {
if (!listElement.asString().equals(alias)) {
newList.add().set(listElement);
}
}
return newList ;
} | [
"private",
"ModelNode",
"removeAliasFromList",
"(",
"ModelNode",
"list",
",",
"String",
"alias",
")",
"throws",
"OperationFailedException",
"{",
"// check for empty string",
"if",
"(",
"alias",
"==",
"null",
"||",
"alias",
".",
"equals",
"(",
"\"\"",
")",
")",
"... | Remove an alias from a LIST ModelNode of existing aliases.
@param list LIST ModelNode of aliases
@param alias
@return LIST ModelNode with the alias removed | [
"Remove",
"an",
"alias",
"from",
"a",
"LIST",
"ModelNode",
"of",
"existing",
"aliases",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/integration/infinispan/src/main/java/org/jboss/as/clustering/infinispan/subsystem/RemoveAliasCommand.java#L98-L118 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java | ContactsApi.getTaggingSuggestions | public Contacts getTaggingSuggestions(int page, int perPage) throws JinxException {
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.contacts.getTaggingSuggestions");
if (page > 0) {
params.put("page", Integer.toString(page));
}
if (perPage > 0) {
params.put("per_page", Integer.toString(perPage));
}
return jinx.flickrGet(params, Contacts.class);
} | java | public Contacts getTaggingSuggestions(int page, int perPage) throws JinxException {
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.contacts.getTaggingSuggestions");
if (page > 0) {
params.put("page", Integer.toString(page));
}
if (perPage > 0) {
params.put("per_page", Integer.toString(perPage));
}
return jinx.flickrGet(params, Contacts.class);
} | [
"public",
"Contacts",
"getTaggingSuggestions",
"(",
"int",
"page",
",",
"int",
"perPage",
")",
"throws",
"JinxException",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"TreeMap",
"<>",
"(",
")",
";",
"params",
".",
"put",
"(",
"\"m... | Get suggestions for tagging people in photos based on the calling user's contacts.
<br>
This method requires authentication with 'read' permission.
@param page Optional. The page of results to return. If this argument is ≤= zero, it defaults to 1.
@param perPage Optional. Number of contacts to return per page. If this argument is ≤= 0, all contacts will be returned.
@return object containing contacts matching the parameters.
@throws JinxException if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.contacts.getTaggingSuggestions.html">flickr.contacts.getTaggingSuggestions</a> | [
"Get",
"suggestions",
"for",
"tagging",
"people",
"in",
"photos",
"based",
"on",
"the",
"calling",
"user",
"s",
"contacts",
".",
"<br",
">",
"This",
"method",
"requires",
"authentication",
"with",
"read",
"permission",
"."
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/ContactsApi.java#L143-L153 |
palatable/lambda | src/main/java/com/jnape/palatable/lambda/optics/lenses/MapLens.java | MapLens.asCopy | public static <M extends Map<K, V>, K, V> Lens<Map<K, V>, M, M, M> asCopy(
Function<? super Map<K, V>, ? extends M> copyFn) {
return lens(copyFn, (__, copy) -> copy);
} | java | public static <M extends Map<K, V>, K, V> Lens<Map<K, V>, M, M, M> asCopy(
Function<? super Map<K, V>, ? extends M> copyFn) {
return lens(copyFn, (__, copy) -> copy);
} | [
"public",
"static",
"<",
"M",
"extends",
"Map",
"<",
"K",
",",
"V",
">",
",",
"K",
",",
"V",
">",
"Lens",
"<",
"Map",
"<",
"K",
",",
"V",
">",
",",
"M",
",",
"M",
",",
"M",
">",
"asCopy",
"(",
"Function",
"<",
"?",
"super",
"Map",
"<",
"K... | A lens that focuses on a copy of a {@link Map} as a subtype <code>M</code>. Useful for composition to avoid
mutating a map reference.
@param <M> the map subtype
@param <K> the key type
@param <V> the value type
@param copyFn the copy function
@return a lens that focuses on copies of maps as a specific subtype | [
"A",
"lens",
"that",
"focuses",
"on",
"a",
"copy",
"of",
"a",
"{",
"@link",
"Map",
"}",
"as",
"a",
"subtype",
"<code",
">",
"M<",
"/",
"code",
">",
".",
"Useful",
"for",
"composition",
"to",
"avoid",
"mutating",
"a",
"map",
"reference",
"."
] | train | https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/optics/lenses/MapLens.java#L49-L52 |
GenesysPureEngage/provisioning-client-java | src/main/java/com/genesys/internal/provisioning/api/UsersApi.java | UsersApi.addUserAsync | public com.squareup.okhttp.Call addUserAsync(AddUserData body, final ApiCallback<CreateUserSuccessResponse> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = addUserValidateBeforeCall(body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<CreateUserSuccessResponse>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call addUserAsync(AddUserData body, final ApiCallback<CreateUserSuccessResponse> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = addUserValidateBeforeCall(body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<CreateUserSuccessResponse>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"addUserAsync",
"(",
"AddUserData",
"body",
",",
"final",
"ApiCallback",
"<",
"CreateUserSuccessResponse",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"ProgressResponseBody",
".",
"ProgressListen... | Create a user. (asynchronously)
Create a user ([CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson)) with the specified attributes.
@param body Body Data (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Create",
"a",
"user",
".",
"(",
"asynchronously",
")",
"Create",
"a",
"user",
"(",
"[",
"CfgPerson",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"genesys",
".",
"com",
"/",
"Documentation",
"/",
"PSDK",
"/",
"latest",
"/",
"ConfigLayerRef",
"/",
"CfgPe... | train | https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/UsersApi.java#L158-L183 |
apereo/cas | support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java | DelegatedClientAuthenticationAction.hasDelegationRequestFailed | public static Optional<ModelAndView> hasDelegationRequestFailed(final HttpServletRequest request, final int status) {
val params = request.getParameterMap();
if (Stream.of("error", "error_code", "error_description", "error_message").anyMatch(params::containsKey)) {
val model = new HashMap<String, Object>();
if (params.containsKey("error_code")) {
model.put("code", StringEscapeUtils.escapeHtml4(request.getParameter("error_code")));
} else {
model.put("code", status);
}
model.put("error", StringEscapeUtils.escapeHtml4(request.getParameter("error")));
model.put("reason", StringEscapeUtils.escapeHtml4(request.getParameter("error_reason")));
if (params.containsKey("error_description")) {
model.put("description", StringEscapeUtils.escapeHtml4(request.getParameter("error_description")));
} else if (params.containsKey("error_message")) {
model.put("description", StringEscapeUtils.escapeHtml4(request.getParameter("error_message")));
}
model.put(CasProtocolConstants.PARAMETER_SERVICE, request.getAttribute(CasProtocolConstants.PARAMETER_SERVICE));
model.put("client", StringEscapeUtils.escapeHtml4(request.getParameter("client_name")));
LOGGER.debug("Delegation request has failed. Details are [{}]", model);
return Optional.of(new ModelAndView("casPac4jStopWebflow", model));
}
return Optional.empty();
} | java | public static Optional<ModelAndView> hasDelegationRequestFailed(final HttpServletRequest request, final int status) {
val params = request.getParameterMap();
if (Stream.of("error", "error_code", "error_description", "error_message").anyMatch(params::containsKey)) {
val model = new HashMap<String, Object>();
if (params.containsKey("error_code")) {
model.put("code", StringEscapeUtils.escapeHtml4(request.getParameter("error_code")));
} else {
model.put("code", status);
}
model.put("error", StringEscapeUtils.escapeHtml4(request.getParameter("error")));
model.put("reason", StringEscapeUtils.escapeHtml4(request.getParameter("error_reason")));
if (params.containsKey("error_description")) {
model.put("description", StringEscapeUtils.escapeHtml4(request.getParameter("error_description")));
} else if (params.containsKey("error_message")) {
model.put("description", StringEscapeUtils.escapeHtml4(request.getParameter("error_message")));
}
model.put(CasProtocolConstants.PARAMETER_SERVICE, request.getAttribute(CasProtocolConstants.PARAMETER_SERVICE));
model.put("client", StringEscapeUtils.escapeHtml4(request.getParameter("client_name")));
LOGGER.debug("Delegation request has failed. Details are [{}]", model);
return Optional.of(new ModelAndView("casPac4jStopWebflow", model));
}
return Optional.empty();
} | [
"public",
"static",
"Optional",
"<",
"ModelAndView",
">",
"hasDelegationRequestFailed",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"int",
"status",
")",
"{",
"val",
"params",
"=",
"request",
".",
"getParameterMap",
"(",
")",
";",
"if",
"(",
"... | Determine if request has errors.
@param request the request
@param status the status
@return the optional model and view, if request is an error. | [
"Determine",
"if",
"request",
"has",
"errors",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/flow/DelegatedClientAuthenticationAction.java#L480-L502 |
Alfresco/alfresco-sdk | plugins/alfresco-maven-plugin/src/main/java/org/alfresco/maven/plugin/AbstractRefreshWebappMojo.java | AbstractRefreshWebappMojo.clearDependencyCaches | protected void clearDependencyCaches(String url) {
// Create the Clear Cache URL for the Alfresco Tomcat server
URL alfrescoTomcatUrl = buildFinalUrl(url);
if (alfrescoTomcatUrl == null) {
getLog().error("Could not build clear dependency caches URL for " +
refreshWebappName + ", " + getAbortedMsg());
}
// Do the refresh
makePostCall(alfrescoTomcatUrl, null, "Clear Dependency Caches");
} | java | protected void clearDependencyCaches(String url) {
// Create the Clear Cache URL for the Alfresco Tomcat server
URL alfrescoTomcatUrl = buildFinalUrl(url);
if (alfrescoTomcatUrl == null) {
getLog().error("Could not build clear dependency caches URL for " +
refreshWebappName + ", " + getAbortedMsg());
}
// Do the refresh
makePostCall(alfrescoTomcatUrl, null, "Clear Dependency Caches");
} | [
"protected",
"void",
"clearDependencyCaches",
"(",
"String",
"url",
")",
"{",
"// Create the Clear Cache URL for the Alfresco Tomcat server",
"URL",
"alfrescoTomcatUrl",
"=",
"buildFinalUrl",
"(",
"url",
")",
";",
"if",
"(",
"alfrescoTomcatUrl",
"==",
"null",
")",
"{",
... | Perform a Clear Dependency Caches call on Share webapp.
Called by specific refresh mojo implementation, currently only applicable to Share webapp.
@param url the relative path to clear cache | [
"Perform",
"a",
"Clear",
"Dependency",
"Caches",
"call",
"on",
"Share",
"webapp",
".",
"Called",
"by",
"specific",
"refresh",
"mojo",
"implementation",
"currently",
"only",
"applicable",
"to",
"Share",
"webapp",
"."
] | train | https://github.com/Alfresco/alfresco-sdk/blob/7f861a96726edb776293e2363ee85ef05643368b/plugins/alfresco-maven-plugin/src/main/java/org/alfresco/maven/plugin/AbstractRefreshWebappMojo.java#L192-L202 |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireDeclaredRootCause | public static void fireDeclaredRootCause(Throwable t, Class... declaredTypes) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fireDeclared(root, declaredTypes);
} | java | public static void fireDeclaredRootCause(Throwable t, Class... declaredTypes) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fireDeclared(root, declaredTypes);
} | [
"public",
"static",
"void",
"fireDeclaredRootCause",
"(",
"Throwable",
"t",
",",
"Class",
"...",
"declaredTypes",
")",
"{",
"Throwable",
"root",
"=",
"t",
";",
"while",
"(",
"root",
"!=",
"null",
")",
"{",
"Throwable",
"cause",
"=",
"root",
".",
"getCause"... | Throws the root cause of the given exception if it is unchecked or an
instance of any of the given declared types. Otherwise, it is thrown as
an UndeclaredThrowableException. If the root cause is null, then the
original exception is thrown. This method only returns normally if the
exception is null.
@param t exception whose root cause is to be thrown
@param declaredTypes if exception is checked and is not an instance of
any of these types, then it is thrown as an
UndeclaredThrowableException. | [
"Throws",
"the",
"root",
"cause",
"of",
"the",
"given",
"exception",
"if",
"it",
"is",
"unchecked",
"or",
"an",
"instance",
"of",
"any",
"of",
"the",
"given",
"declared",
"types",
".",
"Otherwise",
"it",
"is",
"thrown",
"as",
"an",
"UndeclaredThrowableExcept... | train | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L283-L293 |
protostuff/protostuff | protostuff-runtime/src/main/java/io/protostuff/runtime/RuntimeCollectionFieldFactory.java | RuntimeCollectionFieldFactory.createCollectionInlineV | private static <T> Field<T> createCollectionInlineV(int number,
String name, java.lang.reflect.Field f,
MessageFactory messageFactory, final Delegate<Object> inline)
{
final Accessor accessor = AF.create(f);
return new RuntimeCollectionField<T, Object>(inline.getFieldType(),
number, name, f.getAnnotation(Tag.class), messageFactory)
{
@Override
protected void mergeFrom(Input input, T message) throws IOException
{
accessor.set(message, input.mergeObject(
accessor.<Collection<Object>>get(message), schema));
}
@Override
protected void writeTo(Output output, T message) throws IOException
{
final Collection<Object> existing = accessor.get(message);
if (existing != null)
output.writeObject(number, existing, schema, false);
}
@Override
protected void transfer(Pipe pipe, Input input, Output output,
boolean repeated) throws IOException
{
output.writeObject(number, pipe, schema.pipeSchema, repeated);
}
@Override
protected void addValueFrom(Input input,
Collection<Object> collection) throws IOException
{
collection.add(inline.readFrom(input));
}
@Override
protected void writeValueTo(Output output, int fieldNumber,
Object value, boolean repeated) throws IOException
{
inline.writeTo(output, fieldNumber, value, repeated);
}
@Override
protected void transferValue(Pipe pipe, Input input, Output output,
int number, boolean repeated) throws IOException
{
inline.transfer(pipe, input, output, number, repeated);
}
};
} | java | private static <T> Field<T> createCollectionInlineV(int number,
String name, java.lang.reflect.Field f,
MessageFactory messageFactory, final Delegate<Object> inline)
{
final Accessor accessor = AF.create(f);
return new RuntimeCollectionField<T, Object>(inline.getFieldType(),
number, name, f.getAnnotation(Tag.class), messageFactory)
{
@Override
protected void mergeFrom(Input input, T message) throws IOException
{
accessor.set(message, input.mergeObject(
accessor.<Collection<Object>>get(message), schema));
}
@Override
protected void writeTo(Output output, T message) throws IOException
{
final Collection<Object> existing = accessor.get(message);
if (existing != null)
output.writeObject(number, existing, schema, false);
}
@Override
protected void transfer(Pipe pipe, Input input, Output output,
boolean repeated) throws IOException
{
output.writeObject(number, pipe, schema.pipeSchema, repeated);
}
@Override
protected void addValueFrom(Input input,
Collection<Object> collection) throws IOException
{
collection.add(inline.readFrom(input));
}
@Override
protected void writeValueTo(Output output, int fieldNumber,
Object value, boolean repeated) throws IOException
{
inline.writeTo(output, fieldNumber, value, repeated);
}
@Override
protected void transferValue(Pipe pipe, Input input, Output output,
int number, boolean repeated) throws IOException
{
inline.transfer(pipe, input, output, number, repeated);
}
};
} | [
"private",
"static",
"<",
"T",
">",
"Field",
"<",
"T",
">",
"createCollectionInlineV",
"(",
"int",
"number",
",",
"String",
"name",
",",
"java",
".",
"lang",
".",
"reflect",
".",
"Field",
"f",
",",
"MessageFactory",
"messageFactory",
",",
"final",
"Delegat... | /*
private static final ObjectSchema OBJECT_COLLECTION_VALUE_SCHEMA = new ObjectSchema() {
@SuppressWarnings("unchecked") protected void setValue(Object value, Object owner) { // the owner will always be
a Collection ((Collection<Object>)owner).add(value); } }; | [
"/",
"*",
"private",
"static",
"final",
"ObjectSchema",
"OBJECT_COLLECTION_VALUE_SCHEMA",
"=",
"new",
"ObjectSchema",
"()",
"{"
] | train | https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-runtime/src/main/java/io/protostuff/runtime/RuntimeCollectionFieldFactory.java#L77-L128 |
google/closure-compiler | src/com/google/javascript/jscomp/FindModuleDependencies.java | FindModuleDependencies.getEs6ModuleNameFromImportNode | private String getEs6ModuleNameFromImportNode(NodeTraversal t, Node n) {
String importName = n.getLastChild().getString();
boolean isNamespaceImport = importName.startsWith("goog:");
if (isNamespaceImport) {
// Allow importing Closure namespace objects (e.g. from goog.provide or goog.module) as
// import ... from 'goog:my.ns.Object'.
// These are rewritten to plain namespace object accesses.
return importName.substring("goog:".length());
} else {
ModuleLoader.ModulePath modulePath =
t.getInput()
.getPath()
.resolveJsModule(importName, n.getSourceFileName(), n.getLineno(), n.getCharno());
if (modulePath == null) {
// The module loader issues an error
// Fall back to assuming the module is a file path
modulePath = t.getInput().getPath().resolveModuleAsPath(importName);
}
return modulePath.toModuleName();
}
} | java | private String getEs6ModuleNameFromImportNode(NodeTraversal t, Node n) {
String importName = n.getLastChild().getString();
boolean isNamespaceImport = importName.startsWith("goog:");
if (isNamespaceImport) {
// Allow importing Closure namespace objects (e.g. from goog.provide or goog.module) as
// import ... from 'goog:my.ns.Object'.
// These are rewritten to plain namespace object accesses.
return importName.substring("goog:".length());
} else {
ModuleLoader.ModulePath modulePath =
t.getInput()
.getPath()
.resolveJsModule(importName, n.getSourceFileName(), n.getLineno(), n.getCharno());
if (modulePath == null) {
// The module loader issues an error
// Fall back to assuming the module is a file path
modulePath = t.getInput().getPath().resolveModuleAsPath(importName);
}
return modulePath.toModuleName();
}
} | [
"private",
"String",
"getEs6ModuleNameFromImportNode",
"(",
"NodeTraversal",
"t",
",",
"Node",
"n",
")",
"{",
"String",
"importName",
"=",
"n",
".",
"getLastChild",
"(",
")",
".",
"getString",
"(",
")",
";",
"boolean",
"isNamespaceImport",
"=",
"importName",
"... | Get the module name from an import node (import or export statement). | [
"Get",
"the",
"module",
"name",
"from",
"an",
"import",
"node",
"(",
"import",
"or",
"export",
"statement",
")",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/FindModuleDependencies.java#L234-L254 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.unpackEntry | public static boolean unpackEntry(InputStream is, String name, File file) throws IOException {
return handle(is, name, new FileUnpacker(file));
} | java | public static boolean unpackEntry(InputStream is, String name, File file) throws IOException {
return handle(is, name, new FileUnpacker(file));
} | [
"public",
"static",
"boolean",
"unpackEntry",
"(",
"InputStream",
"is",
",",
"String",
"name",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"return",
"handle",
"(",
"is",
",",
"name",
",",
"new",
"FileUnpacker",
"(",
"file",
")",
")",
";",
"}"... | Unpacks a single file from a ZIP stream to a file.
@param is
ZIP stream.
@param name
entry name.
@param file
target file to be created or overwritten.
@return <code>true</code> if the entry was found and unpacked,
<code>false</code> if the entry was not found.
@throws java.io.IOException if file is not found or writing to it fails | [
"Unpacks",
"a",
"single",
"file",
"from",
"a",
"ZIP",
"stream",
"to",
"a",
"file",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L432-L434 |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationServiceCache.java | ClassificationServiceCache.isClassificationLinkedToFileModel | static boolean isClassificationLinkedToFileModel(GraphRewrite event, ClassificationModel classificationModel, FileModel fileModel)
{
String key = getClassificationFileModelCacheKey(classificationModel, fileModel);
Boolean linked = getCache(event).get(key);
if (linked == null)
{
GraphTraversal<Vertex, Vertex> existenceCheck = new GraphTraversalSource(event.getGraphContext().getGraph()).V(classificationModel.getElement());
existenceCheck.out(ClassificationModel.FILE_MODEL);
existenceCheck.filter(vertexTraverser -> vertexTraverser.get().equals(fileModel.getElement()));
linked = existenceCheck.hasNext();
cacheClassificationFileModel(event, classificationModel, fileModel, linked);
}
return linked;
} | java | static boolean isClassificationLinkedToFileModel(GraphRewrite event, ClassificationModel classificationModel, FileModel fileModel)
{
String key = getClassificationFileModelCacheKey(classificationModel, fileModel);
Boolean linked = getCache(event).get(key);
if (linked == null)
{
GraphTraversal<Vertex, Vertex> existenceCheck = new GraphTraversalSource(event.getGraphContext().getGraph()).V(classificationModel.getElement());
existenceCheck.out(ClassificationModel.FILE_MODEL);
existenceCheck.filter(vertexTraverser -> vertexTraverser.get().equals(fileModel.getElement()));
linked = existenceCheck.hasNext();
cacheClassificationFileModel(event, classificationModel, fileModel, linked);
}
return linked;
} | [
"static",
"boolean",
"isClassificationLinkedToFileModel",
"(",
"GraphRewrite",
"event",
",",
"ClassificationModel",
"classificationModel",
",",
"FileModel",
"fileModel",
")",
"{",
"String",
"key",
"=",
"getClassificationFileModelCacheKey",
"(",
"classificationModel",
",",
"... | Indicates whether or not the given {@link FileModel} is already attached to the {@link ClassificationModel}.
Note that this assumes all {@link ClassificationModel} attachments are handled via the {@link ClassificationService}.
Outside of tests, this should be a safe assumption to make. | [
"Indicates",
"whether",
"or",
"not",
"the",
"given",
"{",
"@link",
"FileModel",
"}",
"is",
"already",
"attached",
"to",
"the",
"{",
"@link",
"ClassificationModel",
"}",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationServiceCache.java#L44-L59 |
openengsb/openengsb | components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/ObjectDiff.java | ObjectDiff.updateDiff | private void updateDiff() throws EDBException {
List<String> keyList = loadKeyList();
for (String key : keyList) {
if (key.equals("id") || key.equals("prevTimestamp") || key.equals("timestamp")) {
continue;
}
Object first = startState.get(key);
Object last = endState.get(key);
// if the key value pair is exactly the same, skip it
if (last != null && first != null && first.equals(last)) {
continue;
}
diff.put(key, new Entry(first, last));
differences++;
}
} | java | private void updateDiff() throws EDBException {
List<String> keyList = loadKeyList();
for (String key : keyList) {
if (key.equals("id") || key.equals("prevTimestamp") || key.equals("timestamp")) {
continue;
}
Object first = startState.get(key);
Object last = endState.get(key);
// if the key value pair is exactly the same, skip it
if (last != null && first != null && first.equals(last)) {
continue;
}
diff.put(key, new Entry(first, last));
differences++;
}
} | [
"private",
"void",
"updateDiff",
"(",
")",
"throws",
"EDBException",
"{",
"List",
"<",
"String",
">",
"keyList",
"=",
"loadKeyList",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"keyList",
")",
"{",
"if",
"(",
"key",
".",
"equals",
"(",
"\"id\"",
... | checks for start state and end state which key/value pairs are in common and which have been changed, added or
deleted | [
"checks",
"for",
"start",
"state",
"and",
"end",
"state",
"which",
"key",
"/",
"value",
"pairs",
"are",
"in",
"common",
"and",
"which",
"have",
"been",
"changed",
"added",
"or",
"deleted"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/ObjectDiff.java#L68-L85 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/util/CmsPositionBean.java | CmsPositionBean.containsPoint | public boolean containsPoint(int x, int y) {
return isInRangeInclusive(getLeft(), (getLeft() + getWidth()) - 1, x)
&& isInRangeInclusive(getTop(), (getTop() + getHeight()) - 1, y);
} | java | public boolean containsPoint(int x, int y) {
return isInRangeInclusive(getLeft(), (getLeft() + getWidth()) - 1, x)
&& isInRangeInclusive(getTop(), (getTop() + getHeight()) - 1, y);
} | [
"public",
"boolean",
"containsPoint",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"return",
"isInRangeInclusive",
"(",
"getLeft",
"(",
")",
",",
"(",
"getLeft",
"(",
")",
"+",
"getWidth",
"(",
")",
")",
"-",
"1",
",",
"x",
")",
"&&",
"isInRangeInclus... | Checks if the rectangle defined by this bean contains the given point.<p>
@param x the horizontal coordinate
@param y the vertical coordinate
@return true if this object contains the given point | [
"Checks",
"if",
"the",
"rectangle",
"defined",
"by",
"this",
"bean",
"contains",
"the",
"given",
"point",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsPositionBean.java#L398-L402 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/JobScheduler.java | JobScheduler.runJob | public void runJob(Properties jobProps, JobListener jobListener)
throws JobException {
try {
runJob(jobProps, jobListener, buildJobLauncher(jobProps));
} catch (Exception e) {
throw new JobException("Failed to run job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e);
}
} | java | public void runJob(Properties jobProps, JobListener jobListener)
throws JobException {
try {
runJob(jobProps, jobListener, buildJobLauncher(jobProps));
} catch (Exception e) {
throw new JobException("Failed to run job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e);
}
} | [
"public",
"void",
"runJob",
"(",
"Properties",
"jobProps",
",",
"JobListener",
"jobListener",
")",
"throws",
"JobException",
"{",
"try",
"{",
"runJob",
"(",
"jobProps",
",",
"jobListener",
",",
"buildJobLauncher",
"(",
"jobProps",
")",
")",
";",
"}",
"catch",
... | Run a job.
<p>
This method runs the job immediately without going through the Quartz scheduler.
This is particularly useful for testing.
</p>
@param jobProps Job configuration properties
@param jobListener {@link JobListener} used for callback, can be <em>null</em> if no callback is needed.
@throws JobException when there is anything wrong with running the job | [
"Run",
"a",
"job",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/JobScheduler.java#L432-L439 |
xebia-france/xebia-logfilter-extras | src/main/java/fr/xebia/extras/filters/logfilters/RequestLoggerFilter.java | RequestLoggerFilter.dumpResponse | private void dumpResponse(final HttpServletResponseLoggingWrapper response, final int id) {
final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter);
printWriter.print("-- ID: ");
printWriter.println(id);
printWriter.println(response.getStatusCode());
if (LOG_HEADERS.isDebugEnabled()) {
final Map<String, List<String>> headers = response.headers;
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
printWriter.print(header.getKey());
printWriter.print(": ");
Iterator<String> values = header.getValue().iterator();
while (values.hasNext()) {
printWriter.print(values.next());
printWriter.println();
if (values.hasNext()) {
printWriter.print(' ');
}
}
}
}
printWriter.println("-- Begin response body");
final String body = response.getContentAsInputString();
if (body == null || body.length() == 0) {
printWriter.println("-- NO BODY WRITTEN IN RESPONSE");
} else {
printWriter.println(body);
}
printWriter.println();
printWriter.println("-- End response body");
printWriter.flush();
LOG_RESPONSE.debug(stringWriter.toString());
} | java | private void dumpResponse(final HttpServletResponseLoggingWrapper response, final int id) {
final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter);
printWriter.print("-- ID: ");
printWriter.println(id);
printWriter.println(response.getStatusCode());
if (LOG_HEADERS.isDebugEnabled()) {
final Map<String, List<String>> headers = response.headers;
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
printWriter.print(header.getKey());
printWriter.print(": ");
Iterator<String> values = header.getValue().iterator();
while (values.hasNext()) {
printWriter.print(values.next());
printWriter.println();
if (values.hasNext()) {
printWriter.print(' ');
}
}
}
}
printWriter.println("-- Begin response body");
final String body = response.getContentAsInputString();
if (body == null || body.length() == 0) {
printWriter.println("-- NO BODY WRITTEN IN RESPONSE");
} else {
printWriter.println(body);
}
printWriter.println();
printWriter.println("-- End response body");
printWriter.flush();
LOG_RESPONSE.debug(stringWriter.toString());
} | [
"private",
"void",
"dumpResponse",
"(",
"final",
"HttpServletResponseLoggingWrapper",
"response",
",",
"final",
"int",
"id",
")",
"{",
"final",
"StringWriter",
"stringWriter",
"=",
"new",
"StringWriter",
"(",
")",
";",
"final",
"PrintWriter",
"printWriter",
"=",
"... | This method handles the dumping of the reponse body, status code and headers if needed
@param response ResponseWrapper that handled the response populated by the webapp
@param id Generated unique identifier for the request/response couple | [
"This",
"method",
"handles",
"the",
"dumping",
"of",
"the",
"reponse",
"body",
"status",
"code",
"and",
"headers",
"if",
"needed"
] | train | https://github.com/xebia-france/xebia-logfilter-extras/blob/b1112329816d7f28fdba214425da8f15338a7157/src/main/java/fr/xebia/extras/filters/logfilters/RequestLoggerFilter.java#L140-L173 |
facebookarchive/hadoop-20 | src/contrib/hdfsproxy/src/java/org/apache/hadoop/hdfsproxy/ProxyUgiManager.java | ProxyUgiManager.getUgi | private static UnixUserGroupInformation getUgi(String userName)
throws IOException {
if (userName == null || !USERNAME_PATTERN.matcher(userName).matches())
throw new IOException("Invalid username=" + userName);
String[] cmd = new String[] { "bash", "-c", "id -Gn '" + userName + "'"};
String[] groups = Shell.execCommand(cmd).split("\\s+");
return new UnixUserGroupInformation(userName, groups);
} | java | private static UnixUserGroupInformation getUgi(String userName)
throws IOException {
if (userName == null || !USERNAME_PATTERN.matcher(userName).matches())
throw new IOException("Invalid username=" + userName);
String[] cmd = new String[] { "bash", "-c", "id -Gn '" + userName + "'"};
String[] groups = Shell.execCommand(cmd).split("\\s+");
return new UnixUserGroupInformation(userName, groups);
} | [
"private",
"static",
"UnixUserGroupInformation",
"getUgi",
"(",
"String",
"userName",
")",
"throws",
"IOException",
"{",
"if",
"(",
"userName",
"==",
"null",
"||",
"!",
"USERNAME_PATTERN",
".",
"matcher",
"(",
"userName",
")",
".",
"matches",
"(",
")",
")",
... | Get the ugi for a user by running shell command "id -Gn"
@param userName name of the user
@return ugi of the user
@throws IOException if encounter any error while running the command | [
"Get",
"the",
"ugi",
"for",
"a",
"user",
"by",
"running",
"shell",
"command",
"id",
"-",
"Gn"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/hdfsproxy/src/java/org/apache/hadoop/hdfsproxy/ProxyUgiManager.java#L103-L110 |
grpc/grpc-java | examples/example-tls/src/main/java/io/grpc/examples/helloworldtls/HelloWorldClientTls.java | HelloWorldClientTls.main | public static void main(String[] args) throws Exception {
if (args.length < 2 || args.length == 4 || args.length > 5) {
System.out.println("USAGE: HelloWorldClientTls host port [trustCertCollectionFilePath] " +
"[clientCertChainFilePath clientPrivateKeyFilePath]\n Note: clientCertChainFilePath and " +
"clientPrivateKeyFilePath are only needed if mutual auth is desired.");
System.exit(0);
}
HelloWorldClientTls client;
switch (args.length) {
case 2:
client = new HelloWorldClientTls(args[0], Integer.parseInt(args[1]),
buildSslContext(null, null, null));
break;
case 3:
client = new HelloWorldClientTls(args[0], Integer.parseInt(args[1]),
buildSslContext(args[2], null, null));
break;
default:
client = new HelloWorldClientTls(args[0], Integer.parseInt(args[1]),
buildSslContext(args[2], args[3], args[4]));
}
try {
/* Access a service running on the local machine on port 50051 */
String user = "world";
if (args.length > 0) {
user = args[0]; /* Use the arg as the name to greet if provided */
}
client.greet(user);
} finally {
client.shutdown();
}
} | java | public static void main(String[] args) throws Exception {
if (args.length < 2 || args.length == 4 || args.length > 5) {
System.out.println("USAGE: HelloWorldClientTls host port [trustCertCollectionFilePath] " +
"[clientCertChainFilePath clientPrivateKeyFilePath]\n Note: clientCertChainFilePath and " +
"clientPrivateKeyFilePath are only needed if mutual auth is desired.");
System.exit(0);
}
HelloWorldClientTls client;
switch (args.length) {
case 2:
client = new HelloWorldClientTls(args[0], Integer.parseInt(args[1]),
buildSslContext(null, null, null));
break;
case 3:
client = new HelloWorldClientTls(args[0], Integer.parseInt(args[1]),
buildSslContext(args[2], null, null));
break;
default:
client = new HelloWorldClientTls(args[0], Integer.parseInt(args[1]),
buildSslContext(args[2], args[3], args[4]));
}
try {
/* Access a service running on the local machine on port 50051 */
String user = "world";
if (args.length > 0) {
user = args[0]; /* Use the arg as the name to greet if provided */
}
client.greet(user);
} finally {
client.shutdown();
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"if",
"(",
"args",
".",
"length",
"<",
"2",
"||",
"args",
".",
"length",
"==",
"4",
"||",
"args",
".",
"length",
">",
"5",
")",
"{",
"System",
"... | Greet server. If provided, the first element of {@code args} is the name to use in the
greeting. | [
"Greet",
"server",
".",
"If",
"provided",
"the",
"first",
"element",
"of",
"{"
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/examples/example-tls/src/main/java/io/grpc/examples/helloworldtls/HelloWorldClientTls.java#L103-L137 |
sporniket/core | sporniket-core-io/src/main/java/com/sporniket/libre/io/AbstractTextFileConverter.java | AbstractTextFileConverter.openInputFile | private void openInputFile(final String inputFileName) throws IOException
{
myInputFile = new File(inputFileName);
myInputStream = new FileInputStream(myInputFile);
myStreamReader = new InputStreamReader(myInputStream, getInputEncodingCode());
myBufferedReader = new BufferedReader(myStreamReader);
myLineReader = new LineNumberReader(myBufferedReader);
} | java | private void openInputFile(final String inputFileName) throws IOException
{
myInputFile = new File(inputFileName);
myInputStream = new FileInputStream(myInputFile);
myStreamReader = new InputStreamReader(myInputStream, getInputEncodingCode());
myBufferedReader = new BufferedReader(myStreamReader);
myLineReader = new LineNumberReader(myBufferedReader);
} | [
"private",
"void",
"openInputFile",
"(",
"final",
"String",
"inputFileName",
")",
"throws",
"IOException",
"{",
"myInputFile",
"=",
"new",
"File",
"(",
"inputFileName",
")",
";",
"myInputStream",
"=",
"new",
"FileInputStream",
"(",
"myInputFile",
")",
";",
"mySt... | Prepare the input stream.
@param inputFileName
the file to read from.
@throws IOException
if a problem occurs. | [
"Prepare",
"the",
"input",
"stream",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/AbstractTextFileConverter.java#L403-L410 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/FileListUtils.java | FileListUtils.listPathsRecursively | public static List<FileStatus> listPathsRecursively(FileSystem fs, Path path, PathFilter fileFilter)
throws IOException {
return listPathsRecursivelyHelper(fs, Lists.<FileStatus>newArrayList(), fs.getFileStatus(path), fileFilter);
} | java | public static List<FileStatus> listPathsRecursively(FileSystem fs, Path path, PathFilter fileFilter)
throws IOException {
return listPathsRecursivelyHelper(fs, Lists.<FileStatus>newArrayList(), fs.getFileStatus(path), fileFilter);
} | [
"public",
"static",
"List",
"<",
"FileStatus",
">",
"listPathsRecursively",
"(",
"FileSystem",
"fs",
",",
"Path",
"path",
",",
"PathFilter",
"fileFilter",
")",
"throws",
"IOException",
"{",
"return",
"listPathsRecursivelyHelper",
"(",
"fs",
",",
"Lists",
".",
"<... | Helper method to list out all paths under a specified path. If the {@link org.apache.hadoop.fs.FileSystem} is
unable to list the contents of a relevant directory, will log an error and skip. | [
"Helper",
"method",
"to",
"list",
"out",
"all",
"paths",
"under",
"a",
"specified",
"path",
".",
"If",
"the",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/FileListUtils.java#L212-L215 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/AutoRegisterActionServlet.java | AutoRegisterActionServlet.processUnhandledAction | protected boolean processUnhandledAction( HttpServletRequest request, HttpServletResponse response, String uri )
throws IOException, ServletException
{
return false;
} | java | protected boolean processUnhandledAction( HttpServletRequest request, HttpServletResponse response, String uri )
throws IOException, ServletException
{
return false;
} | [
"protected",
"boolean",
"processUnhandledAction",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"String",
"uri",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"return",
"false",
";",
"}"
] | Last chance to handle an unhandled action URI.
@return <code>true</code> if this method handled it (by forwarding somewhere or writing to the response). | [
"Last",
"chance",
"to",
"handle",
"an",
"unhandled",
"action",
"URI",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/AutoRegisterActionServlet.java#L943-L947 |
RestComm/Restcomm-Connect | restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/PermissionEvaluator.java | PermissionEvaluator.checkPermission | public void checkPermission(final String permission,
UserIdentityContext userIdentityContext) {
//checkAuthenticatedAccount(); // ok there is a valid authenticated account
if ( checkPermission(permission, userIdentityContext.getEffectiveAccountRoles()) != AuthOutcome.OK )
throw new InsufficientPermission();
} | java | public void checkPermission(final String permission,
UserIdentityContext userIdentityContext) {
//checkAuthenticatedAccount(); // ok there is a valid authenticated account
if ( checkPermission(permission, userIdentityContext.getEffectiveAccountRoles()) != AuthOutcome.OK )
throw new InsufficientPermission();
} | [
"public",
"void",
"checkPermission",
"(",
"final",
"String",
"permission",
",",
"UserIdentityContext",
"userIdentityContext",
")",
"{",
"//checkAuthenticatedAccount(); // ok there is a valid authenticated account",
"if",
"(",
"checkPermission",
"(",
"permission",
",",
"userIden... | Grants access by permission. If the effective account has a role that resolves
to the specified permission (accoording to mappings of restcomm.xml) access is granted.
Administrator is granted access regardless of permissions.
@param permission - e.g. 'RestComm:Create:Accounts'
@param userIdentityContext | [
"Grants",
"access",
"by",
"permission",
".",
"If",
"the",
"effective",
"account",
"has",
"a",
"role",
"that",
"resolves",
"to",
"the",
"specified",
"permission",
"(",
"accoording",
"to",
"mappings",
"of",
"restcomm",
".",
"xml",
")",
"access",
"is",
"granted... | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/PermissionEvaluator.java#L127-L132 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueSelectBucketHandler.java | KeyValueSelectBucketHandler.channelRead0 | @Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
switch (msg.getStatus()) {
case SUCCESS:
originalPromise.setSuccess();
ctx.pipeline().remove(this);
ctx.fireChannelActive();
break;
case ACCESS_ERROR:
originalPromise.setFailure(new AuthenticationException("Authentication failure on Select Bucket command"));
break;
case NOTFOUND_ERROR:
originalPromise.setFailure(new AuthenticationException("Bucket not found on Select Bucket command"));
break;
default:
originalPromise.setFailure(new AuthenticationException("Unhandled select bucket status: "
+ msg.getStatus()));
}
} | java | @Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
switch (msg.getStatus()) {
case SUCCESS:
originalPromise.setSuccess();
ctx.pipeline().remove(this);
ctx.fireChannelActive();
break;
case ACCESS_ERROR:
originalPromise.setFailure(new AuthenticationException("Authentication failure on Select Bucket command"));
break;
case NOTFOUND_ERROR:
originalPromise.setFailure(new AuthenticationException("Bucket not found on Select Bucket command"));
break;
default:
originalPromise.setFailure(new AuthenticationException("Unhandled select bucket status: "
+ msg.getStatus()));
}
} | [
"@",
"Override",
"protected",
"void",
"channelRead0",
"(",
"ChannelHandlerContext",
"ctx",
",",
"FullBinaryMemcacheResponse",
"msg",
")",
"throws",
"Exception",
"{",
"switch",
"(",
"msg",
".",
"getStatus",
"(",
")",
")",
"{",
"case",
"SUCCESS",
":",
"originalPro... | Handles incoming Select bucket responses.
@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during communicating to the server. | [
"Handles",
"incoming",
"Select",
"bucket",
"responses",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueSelectBucketHandler.java#L142-L160 |
roboconf/roboconf-platform | core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java | Ec2MachineConfigurator.createVolume | private String createVolume(String storageId, String snapshotId, int size) {
String volumeType = Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_TYPE_PREFIX);
if(volumeType == null) volumeType = "standard";
CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest()
.withAvailabilityZone( this.availabilityZone )
.withVolumeType( volumeType )
.withSize( size ); // The size of the volume, in gigabytes.
// EC2 snapshot IDs start with "snap-"...
if(! Utils.isEmptyOrWhitespaces(snapshotId) && snapshotId.startsWith("snap-"))
createVolumeRequest.withSnapshotId(snapshotId);
CreateVolumeResult createVolumeResult = this.ec2Api.createVolume(createVolumeRequest);
return createVolumeResult.getVolume().getVolumeId();
} | java | private String createVolume(String storageId, String snapshotId, int size) {
String volumeType = Ec2IaasHandler.findStorageProperty(this.targetProperties, storageId, VOLUME_TYPE_PREFIX);
if(volumeType == null) volumeType = "standard";
CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest()
.withAvailabilityZone( this.availabilityZone )
.withVolumeType( volumeType )
.withSize( size ); // The size of the volume, in gigabytes.
// EC2 snapshot IDs start with "snap-"...
if(! Utils.isEmptyOrWhitespaces(snapshotId) && snapshotId.startsWith("snap-"))
createVolumeRequest.withSnapshotId(snapshotId);
CreateVolumeResult createVolumeResult = this.ec2Api.createVolume(createVolumeRequest);
return createVolumeResult.getVolume().getVolumeId();
} | [
"private",
"String",
"createVolume",
"(",
"String",
"storageId",
",",
"String",
"snapshotId",
",",
"int",
"size",
")",
"{",
"String",
"volumeType",
"=",
"Ec2IaasHandler",
".",
"findStorageProperty",
"(",
"this",
".",
"targetProperties",
",",
"storageId",
",",
"V... | Creates volume for EBS.
@return volume ID of newly created volume | [
"Creates",
"volume",
"for",
"EBS",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2MachineConfigurator.java#L284-L299 |
onelogin/onelogin-java-sdk | src/main/java/com/onelogin/sdk/conn/Client.java | Client.getUsers | public List<User> getUsers(HashMap<String, String> queryParameters) throws OAuthSystemException, OAuthProblemException, URISyntaxException {
return getUsers(queryParameters, this.maxResults);
} | java | public List<User> getUsers(HashMap<String, String> queryParameters) throws OAuthSystemException, OAuthProblemException, URISyntaxException {
return getUsers(queryParameters, this.maxResults);
} | [
"public",
"List",
"<",
"User",
">",
"getUsers",
"(",
"HashMap",
"<",
"String",
",",
"String",
">",
"queryParameters",
")",
"throws",
"OAuthSystemException",
",",
"OAuthProblemException",
",",
"URISyntaxException",
"{",
"return",
"getUsers",
"(",
"queryParameters",
... | Gets a list of User resources.
@param queryParameters Query parameters of the Resource
Parameters to filter the result of the list
@return List of User
@throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection
@throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled
@throws URISyntaxException - if there is an error when generating the target URL at the getResource call
@see com.onelogin.sdk.model.User
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/get-users">Get Users documentation</a> | [
"Gets",
"a",
"list",
"of",
"User",
"resources",
"."
] | train | https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L451-L453 |
Azure/azure-sdk-for-java | dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/ZonesInner.java | ZonesInner.getByResourceGroup | public ZoneInner getByResourceGroup(String resourceGroupName, String zoneName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, zoneName).toBlocking().single().body();
} | java | public ZoneInner getByResourceGroup(String resourceGroupName, String zoneName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, zoneName).toBlocking().single().body();
} | [
"public",
"ZoneInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"zoneName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"zoneName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(... | Gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone.
@param resourceGroupName The name of the resource group.
@param zoneName The name of the DNS zone (without a terminating dot).
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ZoneInner object if successful. | [
"Gets",
"a",
"DNS",
"zone",
".",
"Retrieves",
"the",
"zone",
"properties",
"but",
"not",
"the",
"record",
"sets",
"within",
"the",
"zone",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/ZonesInner.java#L620-L622 |
JOML-CI/JOML | src/org/joml/Matrix4f.java | Matrix4f.rotationTowardsXY | public Matrix4f rotationTowardsXY(float dirX, float dirY) {
if ((properties & PROPERTY_IDENTITY) == 0)
MemUtil.INSTANCE.identity(this);
this._m00(dirY);
this._m01(dirX);
this._m10(-dirX);
this._m11(dirY);
_properties(PROPERTY_AFFINE | PROPERTY_ORTHONORMAL);
return this;
} | java | public Matrix4f rotationTowardsXY(float dirX, float dirY) {
if ((properties & PROPERTY_IDENTITY) == 0)
MemUtil.INSTANCE.identity(this);
this._m00(dirY);
this._m01(dirX);
this._m10(-dirX);
this._m11(dirY);
_properties(PROPERTY_AFFINE | PROPERTY_ORTHONORMAL);
return this;
} | [
"public",
"Matrix4f",
"rotationTowardsXY",
"(",
"float",
"dirX",
",",
"float",
"dirY",
")",
"{",
"if",
"(",
"(",
"properties",
"&",
"PROPERTY_IDENTITY",
")",
"==",
"0",
")",
"MemUtil",
".",
"INSTANCE",
".",
"identity",
"(",
"this",
")",
";",
"this",
".",... | Set this matrix to a rotation transformation about the Z axis to align the local <code>+X</code> towards <code>(dirX, dirY)</code>.
<p>
The vector <code>(dirX, dirY)</code> must be a unit vector.
@param dirX
the x component of the normalized direction
@param dirY
the y component of the normalized direction
@return this | [
"Set",
"this",
"matrix",
"to",
"a",
"rotation",
"transformation",
"about",
"the",
"Z",
"axis",
"to",
"align",
"the",
"local",
"<code",
">",
"+",
"X<",
"/",
"code",
">",
"towards",
"<code",
">",
"(",
"dirX",
"dirY",
")",
"<",
"/",
"code",
">",
".",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L3582-L3591 |
VoltDB/voltdb | src/catgen/in/javasrc/CatalogDiffEngine.java | CatalogDiffEngine.processModifyResponses | private void processModifyResponses(String errorMessage, List<TablePopulationRequirements> responseList) {
assert(errorMessage != null);
// if no requirements, then it's just not possible
if (responseList == null) {
m_supported = false;
m_errors.append(errorMessage + "\n");
return;
}
// otherwise, it's possible if a specific table is empty
// collect the error message(s) and decide if it can be done inside @UAC
for (TablePopulationRequirements response : responseList) {
String objectName = response.getObjectName();
String nonEmptyErrorMessage = response.getErrorMessage();
assert (nonEmptyErrorMessage != null);
TablePopulationRequirements popreq = m_tablesThatMustBeEmpty.get(objectName);
if (popreq == null) {
popreq = response;
m_tablesThatMustBeEmpty.put(objectName, popreq);
} else {
String newErrorMessage = popreq.getErrorMessage() + "\n " + response.getErrorMessage();
popreq.setErrorMessage(newErrorMessage);
}
}
} | java | private void processModifyResponses(String errorMessage, List<TablePopulationRequirements> responseList) {
assert(errorMessage != null);
// if no requirements, then it's just not possible
if (responseList == null) {
m_supported = false;
m_errors.append(errorMessage + "\n");
return;
}
// otherwise, it's possible if a specific table is empty
// collect the error message(s) and decide if it can be done inside @UAC
for (TablePopulationRequirements response : responseList) {
String objectName = response.getObjectName();
String nonEmptyErrorMessage = response.getErrorMessage();
assert (nonEmptyErrorMessage != null);
TablePopulationRequirements popreq = m_tablesThatMustBeEmpty.get(objectName);
if (popreq == null) {
popreq = response;
m_tablesThatMustBeEmpty.put(objectName, popreq);
} else {
String newErrorMessage = popreq.getErrorMessage() + "\n " + response.getErrorMessage();
popreq.setErrorMessage(newErrorMessage);
}
}
} | [
"private",
"void",
"processModifyResponses",
"(",
"String",
"errorMessage",
",",
"List",
"<",
"TablePopulationRequirements",
">",
"responseList",
")",
"{",
"assert",
"(",
"errorMessage",
"!=",
"null",
")",
";",
"// if no requirements, then it's just not possible",
"if",
... | After we decide we can't modify, add or delete something on a full table,
we do a check to see if we can do that on an empty table. The original error
and any response from the empty table check is processed here. This code
is basically in this method so it's not repeated 3 times for modify, add
and delete. See where it's called for context.
If the responseList equals null, it is not possible to modify, otherwise we
do the check described above for every element in the responseList, if there
is no element in the responseList, it means no tables must be empty, which is
totally fine. | [
"After",
"we",
"decide",
"we",
"can",
"t",
"modify",
"add",
"or",
"delete",
"something",
"on",
"a",
"full",
"table",
"we",
"do",
"a",
"check",
"to",
"see",
"if",
"we",
"can",
"do",
"that",
"on",
"an",
"empty",
"table",
".",
"The",
"original",
"error"... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/catgen/in/javasrc/CatalogDiffEngine.java#L1403-L1428 |
ltsopensource/light-task-scheduler | lts-core/src/main/java/com/github/ltsopensource/core/commons/utils/WebUtils.java | WebUtils.doPost | public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException {
return _doPost(url, ctype, content, connectTimeout, readTimeout, null);
} | java | public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException {
return _doPost(url, ctype, content, connectTimeout, readTimeout, null);
} | [
"public",
"static",
"String",
"doPost",
"(",
"String",
"url",
",",
"String",
"ctype",
",",
"byte",
"[",
"]",
"content",
",",
"int",
"connectTimeout",
",",
"int",
"readTimeout",
")",
"throws",
"IOException",
"{",
"return",
"_doPost",
"(",
"url",
",",
"ctype... | 执行HTTP POST请求。
@param url 请求地址
@param ctype 请求类型
@param content 请求字节数组
@return 响应字符串 | [
"执行HTTP",
"POST请求。"
] | train | https://github.com/ltsopensource/light-task-scheduler/blob/64d3aa000ff5022be5e94f511b58f405e5f4c8eb/lts-core/src/main/java/com/github/ltsopensource/core/commons/utils/WebUtils.java#L85-L87 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java | DocTreeScanner.visitSerial | @Override
public R visitSerial(SerialTree node, P p) {
return scan(node.getDescription(), p);
} | java | @Override
public R visitSerial(SerialTree node, P p) {
return scan(node.getDescription(), p);
} | [
"@",
"Override",
"public",
"R",
"visitSerial",
"(",
"SerialTree",
"node",
",",
"P",
"p",
")",
"{",
"return",
"scan",
"(",
"node",
".",
"getDescription",
"(",
")",
",",
"p",
")",
";",
"}"
] | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java#L384-L387 |
alkacon/opencms-core | src/org/opencms/xml/containerpage/CmsADESessionCache.java | CmsADESessionCache.getCache | public static CmsADESessionCache getCache(HttpServletRequest request, CmsObject cms) {
CmsADESessionCache cache = (CmsADESessionCache)request.getSession().getAttribute(
CmsADESessionCache.SESSION_ATTR_ADE_CACHE);
if (cache == null) {
cache = new CmsADESessionCache(cms, request);
request.getSession().setAttribute(CmsADESessionCache.SESSION_ATTR_ADE_CACHE, cache);
}
return cache;
} | java | public static CmsADESessionCache getCache(HttpServletRequest request, CmsObject cms) {
CmsADESessionCache cache = (CmsADESessionCache)request.getSession().getAttribute(
CmsADESessionCache.SESSION_ATTR_ADE_CACHE);
if (cache == null) {
cache = new CmsADESessionCache(cms, request);
request.getSession().setAttribute(CmsADESessionCache.SESSION_ATTR_ADE_CACHE, cache);
}
return cache;
} | [
"public",
"static",
"CmsADESessionCache",
"getCache",
"(",
"HttpServletRequest",
"request",
",",
"CmsObject",
"cms",
")",
"{",
"CmsADESessionCache",
"cache",
"=",
"(",
"CmsADESessionCache",
")",
"request",
".",
"getSession",
"(",
")",
".",
"getAttribute",
"(",
"Cm... | Gets the session cache for the current session.<p>
In case the request is not editable, <code>null</code> will be returned.<p>
@param request the current request
@param cms the current CMS context
@return the ADE session cache for the current session | [
"Gets",
"the",
"session",
"cache",
"for",
"the",
"current",
"session",
".",
"<p",
">",
"In",
"case",
"the",
"request",
"is",
"not",
"editable",
"<code",
">",
"null<",
"/",
"code",
">",
"will",
"be",
"returned",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsADESessionCache.java#L212-L221 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/CmsGalleryController.java | CmsGalleryController.sortGalleries | public void sortGalleries(String sortParams, String filter) {
List<CmsGalleryFolderBean> galleries;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
galleries = new ArrayList<CmsGalleryFolderBean>();
for (CmsGalleryFolderBean galleryBean : m_dialogBean.getGalleries()) {
if (galleryBean.matchesFilter(filter)) {
galleries.add(galleryBean);
}
}
} else {
galleries = m_dialogBean.getGalleries();
}
SortParams sort = SortParams.valueOf(sortParams);
switch (sort) {
case title_asc:
Collections.sort(galleries, new CmsComparatorTitle(true));
break;
case title_desc:
Collections.sort(galleries, new CmsComparatorTitle(false));
break;
case type_asc:
Collections.sort(galleries, new CmsComparatorType(true));
break;
case type_desc:
Collections.sort(galleries, new CmsComparatorType(false));
break;
case path_asc:
Collections.sort(galleries, new CmsComparatorPath(true));
break;
case path_desc:
Collections.sort(galleries, new CmsComparatorPath(false));
break;
case tree:
m_handler.onUpdateGalleryTree(galleryListToTree(galleries), m_searchObject.getGalleries());
return;
case dateLastModified_asc:
case dateLastModified_desc:
default:
// not supported
return;
}
m_handler.onUpdateGalleries(galleries, m_searchObject.getGalleries());
} | java | public void sortGalleries(String sortParams, String filter) {
List<CmsGalleryFolderBean> galleries;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
galleries = new ArrayList<CmsGalleryFolderBean>();
for (CmsGalleryFolderBean galleryBean : m_dialogBean.getGalleries()) {
if (galleryBean.matchesFilter(filter)) {
galleries.add(galleryBean);
}
}
} else {
galleries = m_dialogBean.getGalleries();
}
SortParams sort = SortParams.valueOf(sortParams);
switch (sort) {
case title_asc:
Collections.sort(galleries, new CmsComparatorTitle(true));
break;
case title_desc:
Collections.sort(galleries, new CmsComparatorTitle(false));
break;
case type_asc:
Collections.sort(galleries, new CmsComparatorType(true));
break;
case type_desc:
Collections.sort(galleries, new CmsComparatorType(false));
break;
case path_asc:
Collections.sort(galleries, new CmsComparatorPath(true));
break;
case path_desc:
Collections.sort(galleries, new CmsComparatorPath(false));
break;
case tree:
m_handler.onUpdateGalleryTree(galleryListToTree(galleries), m_searchObject.getGalleries());
return;
case dateLastModified_asc:
case dateLastModified_desc:
default:
// not supported
return;
}
m_handler.onUpdateGalleries(galleries, m_searchObject.getGalleries());
} | [
"public",
"void",
"sortGalleries",
"(",
"String",
"sortParams",
",",
"String",
"filter",
")",
"{",
"List",
"<",
"CmsGalleryFolderBean",
">",
"galleries",
";",
"if",
"(",
"CmsStringUtil",
".",
"isNotEmptyOrWhitespaceOnly",
"(",
"filter",
")",
")",
"{",
"galleries... | Sorts the galleries according to given parameters and updates the list.<p>
@param sortParams the sort parameters
@param filter the filter to apply before sorting | [
"Sorts",
"the",
"galleries",
"according",
"to",
"given",
"parameters",
"and",
"updates",
"the",
"list",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/CmsGalleryController.java#L1392-L1435 |
pac4j/pac4j | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/FacebookProfileDefinition.java | FacebookProfileDefinition.computeAppSecretProof | public String computeAppSecretProof(final String url, final OAuth2AccessToken token, final FacebookConfiguration configuration) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(configuration.getSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);
String proof = org.apache.commons.codec.binary.Hex.encodeHexString(sha256_HMAC.doFinal(token.getAccessToken()
.getBytes(StandardCharsets.UTF_8)));
final String computedUrl = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof);
return computedUrl;
} catch (final InvalidKeyException | NoSuchAlgorithmException e) {
throw new TechnicalException("Unable to compute appsecret_proof", e);
}
} | java | public String computeAppSecretProof(final String url, final OAuth2AccessToken token, final FacebookConfiguration configuration) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(configuration.getSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);
String proof = org.apache.commons.codec.binary.Hex.encodeHexString(sha256_HMAC.doFinal(token.getAccessToken()
.getBytes(StandardCharsets.UTF_8)));
final String computedUrl = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof);
return computedUrl;
} catch (final InvalidKeyException | NoSuchAlgorithmException e) {
throw new TechnicalException("Unable to compute appsecret_proof", e);
}
} | [
"public",
"String",
"computeAppSecretProof",
"(",
"final",
"String",
"url",
",",
"final",
"OAuth2AccessToken",
"token",
",",
"final",
"FacebookConfiguration",
"configuration",
")",
"{",
"try",
"{",
"Mac",
"sha256_HMAC",
"=",
"Mac",
".",
"getInstance",
"(",
"\"Hmac... | The code in this method is based on this blog post:
https://www.sammyk.me/the-single-most-important-way-to-make-your-facebook-app-more-secure
and this answer: https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation
@param url the URL to which we're adding the proof
@param token the application token we pass back and forth
@param configuration the current configuration
@return URL with the appsecret_proof parameter added | [
"The",
"code",
"in",
"this",
"method",
"is",
"based",
"on",
"this",
"blog",
"post",
":",
"https",
":",
"//",
"www",
".",
"sammyk",
".",
"me",
"/",
"the",
"-",
"single",
"-",
"most",
"-",
"important",
"-",
"way",
"-",
"to",
"-",
"make",
"-",
"your... | train | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/FacebookProfileDefinition.java#L133-L145 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java | SARLQuickfixProvider.fixUnusedAgentCapacity | @Fix(io.sarl.lang.validation.IssueCodes.UNUSED_AGENT_CAPACITY)
public void fixUnusedAgentCapacity(final Issue issue, IssueResolutionAcceptor acceptor) {
CapacityReferenceRemoveModification.accept(this, issue, acceptor);
} | java | @Fix(io.sarl.lang.validation.IssueCodes.UNUSED_AGENT_CAPACITY)
public void fixUnusedAgentCapacity(final Issue issue, IssueResolutionAcceptor acceptor) {
CapacityReferenceRemoveModification.accept(this, issue, acceptor);
} | [
"@",
"Fix",
"(",
"io",
".",
"sarl",
".",
"lang",
".",
"validation",
".",
"IssueCodes",
".",
"UNUSED_AGENT_CAPACITY",
")",
"public",
"void",
"fixUnusedAgentCapacity",
"(",
"final",
"Issue",
"issue",
",",
"IssueResolutionAcceptor",
"acceptor",
")",
"{",
"CapacityR... | Quick fix for "Unused agent capacity".
@param issue the issue.
@param acceptor the quick fix acceptor. | [
"Quick",
"fix",
"for",
"Unused",
"agent",
"capacity",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L886-L889 |
greese/dasein-util | src/main/java/org/dasein/util/ConcurrentMultiCache.java | ConcurrentMultiCache.find | public T find(String key, Object val, CacheLoader<T> loader, Object ... args) {
ConcurrentCache<Object,T> cache = caches.get(key);
T item;
if( val instanceof BigDecimal ) {
val = ((BigDecimal)val).longValue();
}
item = cache.get(val);
if( item == null && loader != null ) {
item = loader.load(args);
if( item == null ) {
return null;
}
synchronized( this ) {
item = getCurrent(item);
put(item);
}
}
return item;
} | java | public T find(String key, Object val, CacheLoader<T> loader, Object ... args) {
ConcurrentCache<Object,T> cache = caches.get(key);
T item;
if( val instanceof BigDecimal ) {
val = ((BigDecimal)val).longValue();
}
item = cache.get(val);
if( item == null && loader != null ) {
item = loader.load(args);
if( item == null ) {
return null;
}
synchronized( this ) {
item = getCurrent(item);
put(item);
}
}
return item;
} | [
"public",
"T",
"find",
"(",
"String",
"key",
",",
"Object",
"val",
",",
"CacheLoader",
"<",
"T",
">",
"loader",
",",
"Object",
"...",
"args",
")",
"{",
"ConcurrentCache",
"<",
"Object",
",",
"T",
">",
"cache",
"=",
"caches",
".",
"get",
"(",
"key",
... | Seeks the item from the cache that is identified by the specified key having
the specified value. If no match is found, the specified loader will be called
with the specified arguments in order to place an instantiated item into the cache.
@param key the name of the unique identifier attribute whose value you have
@param val the value of the unique identifier that identifiers the desired item
@param loader a loader to load the desired object from the persistence store if it
is not in memory
@param args any arguments to pass to the loader
@return the object that matches the specified key/value | [
"Seeks",
"the",
"item",
"from",
"the",
"cache",
"that",
"is",
"identified",
"by",
"the",
"specified",
"key",
"having",
"the",
"specified",
"value",
".",
"If",
"no",
"match",
"is",
"found",
"the",
"specified",
"loader",
"will",
"be",
"called",
"with",
"the"... | train | https://github.com/greese/dasein-util/blob/648606dcb4bd382e3287a6c897a32e65d553dc47/src/main/java/org/dasein/util/ConcurrentMultiCache.java#L256-L275 |
biojava/biojava | biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java | Alignments.getPairwiseScorer | static <S extends Sequence<C>, C extends Compound> PairwiseSequenceScorer<S, C> getPairwiseScorer(
S query, S target, PairwiseSequenceScorerType type, GapPenalty gapPenalty,
SubstitutionMatrix<C> subMatrix) {
switch (type) {
default:
case GLOBAL:
return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix);
case GLOBAL_IDENTITIES:
return new FractionalIdentityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix));
case GLOBAL_SIMILARITIES:
return new FractionalSimilarityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix));
case LOCAL:
return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix);
case LOCAL_IDENTITIES:
return new FractionalIdentityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix));
case LOCAL_SIMILARITIES:
return new FractionalSimilarityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix));
case KMERS:
case WU_MANBER:
// TODO other scoring options
throw new UnsupportedOperationException(Alignments.class.getSimpleName() + " does not yet support " +
type + " scoring");
}
} | java | static <S extends Sequence<C>, C extends Compound> PairwiseSequenceScorer<S, C> getPairwiseScorer(
S query, S target, PairwiseSequenceScorerType type, GapPenalty gapPenalty,
SubstitutionMatrix<C> subMatrix) {
switch (type) {
default:
case GLOBAL:
return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix);
case GLOBAL_IDENTITIES:
return new FractionalIdentityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix));
case GLOBAL_SIMILARITIES:
return new FractionalSimilarityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix));
case LOCAL:
return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix);
case LOCAL_IDENTITIES:
return new FractionalIdentityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix));
case LOCAL_SIMILARITIES:
return new FractionalSimilarityScorer<S, C>(getPairwiseAligner(query, target,
PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix));
case KMERS:
case WU_MANBER:
// TODO other scoring options
throw new UnsupportedOperationException(Alignments.class.getSimpleName() + " does not yet support " +
type + " scoring");
}
} | [
"static",
"<",
"S",
"extends",
"Sequence",
"<",
"C",
">",
",",
"C",
"extends",
"Compound",
">",
"PairwiseSequenceScorer",
"<",
"S",
",",
"C",
">",
"getPairwiseScorer",
"(",
"S",
"query",
",",
"S",
"target",
",",
"PairwiseSequenceScorerType",
"type",
",",
"... | Factory method which constructs a pairwise sequence scorer.
@param <S> each {@link Sequence} of a pair is of type S
@param <C> each element of a {@link Sequence} is a {@link Compound} of type C
@param query the first {@link Sequence} to score
@param target the second {@link Sequence} to score
@param type chosen type from list of pairwise sequence scoring routines
@param gapPenalty the gap penalties used during alignment
@param subMatrix the set of substitution scores used during alignment
@return sequence pair scorer | [
"Factory",
"method",
"which",
"constructs",
"a",
"pairwise",
"sequence",
"scorer",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java#L369-L396 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/dialog/DateRangePicker.java | DateRangePicker.addChoice | public Dateitem addChoice(DateRange range, boolean isCustom) {
Dateitem item;
if (isCustom) {
item = findMatchingItem(range);
if (item != null) {
return item;
}
}
item = new Dateitem();
item.setLabel(range.getLabel());
item.setData(range);
addChild(item, isCustom ? null : customItem);
if (range.isDefault()) {
setSelectedItem(item);
}
return item;
} | java | public Dateitem addChoice(DateRange range, boolean isCustom) {
Dateitem item;
if (isCustom) {
item = findMatchingItem(range);
if (item != null) {
return item;
}
}
item = new Dateitem();
item.setLabel(range.getLabel());
item.setData(range);
addChild(item, isCustom ? null : customItem);
if (range.isDefault()) {
setSelectedItem(item);
}
return item;
} | [
"public",
"Dateitem",
"addChoice",
"(",
"DateRange",
"range",
",",
"boolean",
"isCustom",
")",
"{",
"Dateitem",
"item",
";",
"if",
"(",
"isCustom",
")",
"{",
"item",
"=",
"findMatchingItem",
"(",
"range",
")",
";",
"if",
"(",
"item",
"!=",
"null",
")",
... | Adds a date range to the choice list.
@param range Date range item
@param isCustom If true, range is a custom item. In this case, if another matching custom
item exists, it will not be added.
@return combo box item that was added (or found if duplicate custom item). | [
"Adds",
"a",
"date",
"range",
"to",
"the",
"choice",
"list",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/dialog/DateRangePicker.java#L124-L145 |
line/armeria | examples/annotated-http-service/src/main/java/example/armeria/server/annotated/MessageConverterService.java | MessageConverterService.json3 | @Post("/obj/obj")
@ProducesJson
public Response json3(@RequestObject Request request) {
return new Response(Response.SUCCESS, request.name());
} | java | @Post("/obj/obj")
@ProducesJson
public Response json3(@RequestObject Request request) {
return new Response(Response.SUCCESS, request.name());
} | [
"@",
"Post",
"(",
"\"/obj/obj\"",
")",
"@",
"ProducesJson",
"public",
"Response",
"json3",
"(",
"@",
"RequestObject",
"Request",
"request",
")",
"{",
"return",
"new",
"Response",
"(",
"Response",
".",
"SUCCESS",
",",
"request",
".",
"name",
"(",
")",
")",
... | Returns a {@link Response} object. A {@link Request} is automatically converted by
{@link JacksonRequestConverterFunction}.
<p>If you want to use a custom {@link ObjectMapper} for JSON converters, you can register a new
{@link JacksonRequestConverterFunction} with your custom {@link ObjectMapper} when adding an
annotated service as follows:
<pre>{@code
// Create a new JSON request converter with a custom ObjectMapper.
final JacksonRequestConverterFunction requestConverterFunction =
new JacksonRequestConverterFunction(
new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS));
// Register the converter when adding an annotated service to the ServerBuilder.
final Server = new ServerBuilder().port(0, SessionProtocol.HTTP)
.annotatedService("/messageConverter", new MessageConverterService(),
requestConverterFunction)
.build();
}</pre> | [
"Returns",
"a",
"{",
"@link",
"Response",
"}",
"object",
".",
"A",
"{",
"@link",
"Request",
"}",
"is",
"automatically",
"converted",
"by",
"{",
"@link",
"JacksonRequestConverterFunction",
"}",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/examples/annotated-http-service/src/main/java/example/armeria/server/annotated/MessageConverterService.java#L86-L90 |
Esri/geometry-api-java | src/main/java/com/esri/core/geometry/Point2D.java | Point2D.offset | double offset(/* const */Point2D pt1, /* const */Point2D pt2) {
double newDistance = distance(pt1, pt2);
Point2D p = construct(x, y);
if (newDistance == 0.0)
return distance(p, pt1);
// get vectors relative to pt_1
Point2D p2 = new Point2D();
p2.setCoords(pt2);
p2.sub(pt1);
p.sub(pt1);
double cross = p.crossProduct(p2);
return cross / newDistance;
} | java | double offset(/* const */Point2D pt1, /* const */Point2D pt2) {
double newDistance = distance(pt1, pt2);
Point2D p = construct(x, y);
if (newDistance == 0.0)
return distance(p, pt1);
// get vectors relative to pt_1
Point2D p2 = new Point2D();
p2.setCoords(pt2);
p2.sub(pt1);
p.sub(pt1);
double cross = p.crossProduct(p2);
return cross / newDistance;
} | [
"double",
"offset",
"(",
"/* const */",
"Point2D",
"pt1",
",",
"/* const */",
"Point2D",
"pt2",
")",
"{",
"double",
"newDistance",
"=",
"distance",
"(",
"pt1",
",",
"pt2",
")",
";",
"Point2D",
"p",
"=",
"construct",
"(",
"x",
",",
"y",
")",
";",
"if",
... | returns signed distance of point from infinite line represented by
pt_1...pt_2. The returned distance is positive if this point lies on the
right-hand side of the line, negative otherwise. If the two input points
are equal, the (positive) distance of this point to p_1 is returned. | [
"returns",
"signed",
"distance",
"of",
"point",
"from",
"infinite",
"line",
"represented",
"by",
"pt_1",
"...",
"pt_2",
".",
"The",
"returned",
"distance",
"is",
"positive",
"if",
"this",
"point",
"lies",
"on",
"the",
"right",
"-",
"hand",
"side",
"of",
"t... | train | https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/Point2D.java#L421-L435 |
davidmoten/rxjava-extras | src/main/java/com/github/davidmoten/rx/Transformers.java | Transformers.removePairs | public static <T> Transformer<T, T> removePairs(
final Func1<? super T, Boolean> isCandidateForFirst,
final Func2<? super T, ? super T, Boolean> remove) {
return new Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.compose(Transformers. //
stateMachine() //
.initialState(Optional.<T> absent()) //
.transition(new Transition<Optional<T>, T, T>() {
@Override
public Optional<T> call(Optional<T> state, T value,
Subscriber<T> subscriber) {
if (!state.isPresent()) {
if (isCandidateForFirst.call(value)) {
return Optional.of(value);
} else {
subscriber.onNext(value);
return Optional.absent();
}
} else {
if (remove.call(state.get(), value)) {
// emit nothing and reset state
return Optional.absent();
} else {
subscriber.onNext(state.get());
if (isCandidateForFirst.call(value)) {
return Optional.of(value);
} else {
subscriber.onNext(value);
return Optional.absent();
}
}
}
}
}).completion(new Completion<Optional<T>, T>() {
@Override
public Boolean call(Optional<T> state, Subscriber<T> subscriber) {
if (state.isPresent())
subscriber.onNext(state.get());
// yes, complete
return true;
}
}).build());
}
};
} | java | public static <T> Transformer<T, T> removePairs(
final Func1<? super T, Boolean> isCandidateForFirst,
final Func2<? super T, ? super T, Boolean> remove) {
return new Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.compose(Transformers. //
stateMachine() //
.initialState(Optional.<T> absent()) //
.transition(new Transition<Optional<T>, T, T>() {
@Override
public Optional<T> call(Optional<T> state, T value,
Subscriber<T> subscriber) {
if (!state.isPresent()) {
if (isCandidateForFirst.call(value)) {
return Optional.of(value);
} else {
subscriber.onNext(value);
return Optional.absent();
}
} else {
if (remove.call(state.get(), value)) {
// emit nothing and reset state
return Optional.absent();
} else {
subscriber.onNext(state.get());
if (isCandidateForFirst.call(value)) {
return Optional.of(value);
} else {
subscriber.onNext(value);
return Optional.absent();
}
}
}
}
}).completion(new Completion<Optional<T>, T>() {
@Override
public Boolean call(Optional<T> state, Subscriber<T> subscriber) {
if (state.isPresent())
subscriber.onNext(state.get());
// yes, complete
return true;
}
}).build());
}
};
} | [
"public",
"static",
"<",
"T",
">",
"Transformer",
"<",
"T",
",",
"T",
">",
"removePairs",
"(",
"final",
"Func1",
"<",
"?",
"super",
"T",
",",
"Boolean",
">",
"isCandidateForFirst",
",",
"final",
"Func2",
"<",
"?",
"super",
"T",
",",
"?",
"super",
"T"... | Removes pairs non-recursively from a stream. Uses
{@code Transformers.stateMachine()} under the covers to ensure items are
emitted as soon as possible (if an item can't be in a pair then it is
emitted straight away).
@param isCandidateForFirst
returns true if item is potentially the first of a pair that
we want to remove
@param remove
returns true if a pair should be removed
@param <T>
generic type of stream being transformed
@return transformed stream | [
"Removes",
"pairs",
"non",
"-",
"recursively",
"from",
"a",
"stream",
".",
"Uses",
"{",
"@code",
"Transformers",
".",
"stateMachine",
"()",
"}",
"under",
"the",
"covers",
"to",
"ensure",
"items",
"are",
"emitted",
"as",
"soon",
"as",
"possible",
"(",
"if",... | train | https://github.com/davidmoten/rxjava-extras/blob/a91d2ba7d454843250e0b0fce36084f9fb02a551/src/main/java/com/github/davidmoten/rx/Transformers.java#L958-L1007 |
SahaginOrg/sahagin-java | src/main/java/org/sahagin/runlib/runresultsgen/HookMethodManager.java | HookMethodManager.afterMethodHook | public void afterMethodHook(String hookedClassQualifiedName, String hookedMethodSimpleName) {
if (currentRunResult == null) {
return; // maybe called outside of the root method
}
TestMethod rootMethod = currentRunResult.getRootMethod();
if (!rootMethod.getTestClassKey().equals(hookedClassQualifiedName)
|| !rootMethod.getSimpleName().equals(hookedMethodSimpleName)) {
return; // hooked method is not current root method
}
long currentTime = System.currentTimeMillis();
currentRunResult.setExecutionTime((int) (currentTime - startMethodTime));
logger.info("afterMethodHook: " + hookedMethodSimpleName);
// use encoded name to avoid various possible file name encoding problem
// and to escape invalid file name character (Method name may contain such characters
// if method is Groovy method, for example).
File runResultFile = new File(String.format("%s/%s/%s", runResultsRootDir,
CommonUtils.encodeToSafeAsciiFileNameString(hookedClassQualifiedName, StandardCharsets.UTF_8),
CommonUtils.encodeToSafeAsciiFileNameString(hookedMethodSimpleName, StandardCharsets.UTF_8)));
if (runResultFile.getParentFile() != null) {
runResultFile.getParentFile().mkdirs();
}
// write runResult to YAML file
YamlUtils.dump(currentRunResult.toYamlObject(), runResultFile);
// clear current captureNo and runResult
currentCaptureNo = -1;
currentRunResult = null;
currentActualRootMethodSimpleName = null;
} | java | public void afterMethodHook(String hookedClassQualifiedName, String hookedMethodSimpleName) {
if (currentRunResult == null) {
return; // maybe called outside of the root method
}
TestMethod rootMethod = currentRunResult.getRootMethod();
if (!rootMethod.getTestClassKey().equals(hookedClassQualifiedName)
|| !rootMethod.getSimpleName().equals(hookedMethodSimpleName)) {
return; // hooked method is not current root method
}
long currentTime = System.currentTimeMillis();
currentRunResult.setExecutionTime((int) (currentTime - startMethodTime));
logger.info("afterMethodHook: " + hookedMethodSimpleName);
// use encoded name to avoid various possible file name encoding problem
// and to escape invalid file name character (Method name may contain such characters
// if method is Groovy method, for example).
File runResultFile = new File(String.format("%s/%s/%s", runResultsRootDir,
CommonUtils.encodeToSafeAsciiFileNameString(hookedClassQualifiedName, StandardCharsets.UTF_8),
CommonUtils.encodeToSafeAsciiFileNameString(hookedMethodSimpleName, StandardCharsets.UTF_8)));
if (runResultFile.getParentFile() != null) {
runResultFile.getParentFile().mkdirs();
}
// write runResult to YAML file
YamlUtils.dump(currentRunResult.toYamlObject(), runResultFile);
// clear current captureNo and runResult
currentCaptureNo = -1;
currentRunResult = null;
currentActualRootMethodSimpleName = null;
} | [
"public",
"void",
"afterMethodHook",
"(",
"String",
"hookedClassQualifiedName",
",",
"String",
"hookedMethodSimpleName",
")",
"{",
"if",
"(",
"currentRunResult",
"==",
"null",
")",
"{",
"return",
";",
"// maybe called outside of the root method",
"}",
"TestMethod",
"roo... | write runResult to YAML file if the method for the arguments is root method | [
"write",
"runResult",
"to",
"YAML",
"file",
"if",
"the",
"method",
"for",
"the",
"arguments",
"is",
"root",
"method"
] | train | https://github.com/SahaginOrg/sahagin-java/blob/7ace428adebe3466ceb5826bc9681f8e3d52be68/src/main/java/org/sahagin/runlib/runresultsgen/HookMethodManager.java#L124-L154 |
KayLerch/alexa-skills-kit-tellask-java | src/main/java/io/klerch/alexa/tellask/model/AlexaInput.java | AlexaInput.hasSlotIsCologneEqual | public boolean hasSlotIsCologneEqual(final String slotName, final String value) {
final String slotValue = getSlotValue(slotName);
return hasSlotNotBlank(slotName) && value != null &&
new ColognePhonetic().isEncodeEqual(slotValue, value);
} | java | public boolean hasSlotIsCologneEqual(final String slotName, final String value) {
final String slotValue = getSlotValue(slotName);
return hasSlotNotBlank(slotName) && value != null &&
new ColognePhonetic().isEncodeEqual(slotValue, value);
} | [
"public",
"boolean",
"hasSlotIsCologneEqual",
"(",
"final",
"String",
"slotName",
",",
"final",
"String",
"value",
")",
"{",
"final",
"String",
"slotValue",
"=",
"getSlotValue",
"(",
"slotName",
")",
";",
"return",
"hasSlotNotBlank",
"(",
"slotName",
")",
"&&",
... | Checks if a slot is contained in the intent request and has a value which is a
phonetic sibling of the string given to this method. Cologne phonetic algorithm
is optimized for German language and in this case is used to match slot value with
value given to this method.
@param slotName name of the slot to look after
@param value the value
@return True, if slot value and given value are phonetically equal with Cologne phonetic algorithm | [
"Checks",
"if",
"a",
"slot",
"is",
"contained",
"in",
"the",
"intent",
"request",
"and",
"has",
"a",
"value",
"which",
"is",
"a",
"phonetic",
"sibling",
"of",
"the",
"string",
"given",
"to",
"this",
"method",
".",
"Cologne",
"phonetic",
"algorithm",
"is",
... | train | https://github.com/KayLerch/alexa-skills-kit-tellask-java/blob/2c19028e775c2512dd4649d12962c0b48bf7f2bc/src/main/java/io/klerch/alexa/tellask/model/AlexaInput.java#L153-L157 |
jcustenborder/connect-utils | connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java | ConfigUtils.keyStore | public static KeyStore keyStore(AbstractConfig config, String key) {
final String keyStoreType = config.getString(key);
try {
return KeyStore.getInstance(keyStoreType);
} catch (KeyStoreException e) {
ConfigException exception = new ConfigException(
key,
keyStoreType,
"Invalid KeyStore type."
);
exception.initCause(e);
throw exception;
}
} | java | public static KeyStore keyStore(AbstractConfig config, String key) {
final String keyStoreType = config.getString(key);
try {
return KeyStore.getInstance(keyStoreType);
} catch (KeyStoreException e) {
ConfigException exception = new ConfigException(
key,
keyStoreType,
"Invalid KeyStore type."
);
exception.initCause(e);
throw exception;
}
} | [
"public",
"static",
"KeyStore",
"keyStore",
"(",
"AbstractConfig",
"config",
",",
"String",
"key",
")",
"{",
"final",
"String",
"keyStoreType",
"=",
"config",
".",
"getString",
"(",
"key",
")",
";",
"try",
"{",
"return",
"KeyStore",
".",
"getInstance",
"(",
... | Method will create a KeyStore based on the KeyStore type specified in the config.
@param config Config to read from.
@param key Key to read from
@return KeyStore based on the type specified in the config. | [
"Method",
"will",
"create",
"a",
"KeyStore",
"based",
"on",
"the",
"KeyStore",
"type",
"specified",
"in",
"the",
"config",
"."
] | train | https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java#L377-L390 |
leancloud/java-sdk-all | android-sdk/realtime-sample-app/src/main/java/cn/leancloud/realtime_sample_app/LoginActivity.java | LoginActivity.attemptLogin | private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
} | java | private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
} | [
"private",
"void",
"attemptLogin",
"(",
")",
"{",
"if",
"(",
"mAuthTask",
"!=",
"null",
")",
"{",
"return",
";",
"}",
"// Reset errors.",
"mEmailView",
".",
"setError",
"(",
"null",
")",
";",
"mPasswordView",
".",
"setError",
"(",
"null",
")",
";",
"// S... | Attempts to sign in or register the account specified by the login form.
If there are form errors (invalid email, missing fields, etc.), the
errors are presented and no actual login attempt is made. | [
"Attempts",
"to",
"sign",
"in",
"or",
"register",
"the",
"account",
"specified",
"by",
"the",
"login",
"form",
".",
"If",
"there",
"are",
"form",
"errors",
"(",
"invalid",
"email",
"missing",
"fields",
"etc",
".",
")",
"the",
"errors",
"are",
"presented",
... | train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/realtime-sample-app/src/main/java/cn/leancloud/realtime_sample_app/LoginActivity.java#L155-L200 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseShort | public static short parseShort (@Nullable final String sStr, @Nonnegative final int nRadix, final short nDefault)
{
if (sStr != null && sStr.length () > 0)
try
{
return Short.parseShort (sStr, nRadix);
}
catch (final NumberFormatException ex)
{
// Fall through
}
return nDefault;
} | java | public static short parseShort (@Nullable final String sStr, @Nonnegative final int nRadix, final short nDefault)
{
if (sStr != null && sStr.length () > 0)
try
{
return Short.parseShort (sStr, nRadix);
}
catch (final NumberFormatException ex)
{
// Fall through
}
return nDefault;
} | [
"public",
"static",
"short",
"parseShort",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nonnegative",
"final",
"int",
"nRadix",
",",
"final",
"short",
"nDefault",
")",
"{",
"if",
"(",
"sStr",
"!=",
"null",
"&&",
"sStr",
".",
"length",
"(",... | Parse the given {@link String} as short with the specified radix.
@param sStr
The string to parse. May be <code>null</code>.
@param nRadix
The radix to use. Must be ≥ {@link Character#MIN_RADIX} and ≤
{@link Character#MAX_RADIX}.
@param nDefault
The default value to be returned if the passed object could not be
converted to a valid value.
@return The default if the string does not represent a valid value. | [
"Parse",
"the",
"given",
"{",
"@link",
"String",
"}",
"as",
"short",
"with",
"the",
"specified",
"radix",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L1237-L1249 |
mnlipp/jgrapes | org.jgrapes.util/src/org/jgrapes/util/events/KeyValueStoreUpdate.java | KeyValueStoreUpdate.storeAs | public KeyValueStoreUpdate storeAs(String value, String... segments) {
actions.add(new Update("/" + String.join("/", segments), value));
return this;
} | java | public KeyValueStoreUpdate storeAs(String value, String... segments) {
actions.add(new Update("/" + String.join("/", segments), value));
return this;
} | [
"public",
"KeyValueStoreUpdate",
"storeAs",
"(",
"String",
"value",
",",
"String",
"...",
"segments",
")",
"{",
"actions",
".",
"add",
"(",
"new",
"Update",
"(",
"\"/\"",
"+",
"String",
".",
"join",
"(",
"\"/\"",
",",
"segments",
")",
",",
"value",
")",
... | Adds a new update action to the event that stores the given value
on the path formed by the path segments.
@param value the value
@param segments the path segments
@return the event for easy chaining | [
"Adds",
"a",
"new",
"update",
"action",
"to",
"the",
"event",
"that",
"stores",
"the",
"given",
"value",
"on",
"the",
"path",
"formed",
"by",
"the",
"path",
"segments",
"."
] | train | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.util/src/org/jgrapes/util/events/KeyValueStoreUpdate.java#L55-L58 |
pravega/pravega | controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java | StreamMetrics.sealStream | public void sealStream(String scope, String streamName, Duration latency) {
DYNAMIC_LOGGER.incCounterValue(SEAL_STREAM, 1);
DYNAMIC_LOGGER.reportGaugeValue(OPEN_TRANSACTIONS, 0, streamTags(scope, streamName));
sealStreamLatency.reportSuccessValue(latency.toMillis());
} | java | public void sealStream(String scope, String streamName, Duration latency) {
DYNAMIC_LOGGER.incCounterValue(SEAL_STREAM, 1);
DYNAMIC_LOGGER.reportGaugeValue(OPEN_TRANSACTIONS, 0, streamTags(scope, streamName));
sealStreamLatency.reportSuccessValue(latency.toMillis());
} | [
"public",
"void",
"sealStream",
"(",
"String",
"scope",
",",
"String",
"streamName",
",",
"Duration",
"latency",
")",
"{",
"DYNAMIC_LOGGER",
".",
"incCounterValue",
"(",
"SEAL_STREAM",
",",
"1",
")",
";",
"DYNAMIC_LOGGER",
".",
"reportGaugeValue",
"(",
"OPEN_TRA... | This method increments the global and Stream-specific counters of seal Stream operations, set the number of open
Transactions to 0, and reports the latency of the operation.
@param scope Scope.
@param streamName Name of the Stream.
@param latency Latency of the sealStream operation. | [
"This",
"method",
"increments",
"the",
"global",
"and",
"Stream",
"-",
"specific",
"counters",
"of",
"seal",
"Stream",
"operations",
"set",
"the",
"number",
"of",
"open",
"Transactions",
"to",
"0",
"and",
"reports",
"the",
"latency",
"of",
"the",
"operation",
... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java#L113-L117 |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/ThrottleFilter.java | ThrottleFilter.getContentType | private String getContentType(HttpServletRequest pRequest) {
if (responseMessageTypes != null) {
String accept = pRequest.getHeader("Accept");
for (String type : responseMessageTypes) {
// Note: This is not 100% correct way of doing content negotiation
// But we just want a compatible result, quick, so this is okay
if (StringUtil.contains(accept, type)) {
return type;
}
}
}
// If none found, return default
return DEFAULT_TYPE;
} | java | private String getContentType(HttpServletRequest pRequest) {
if (responseMessageTypes != null) {
String accept = pRequest.getHeader("Accept");
for (String type : responseMessageTypes) {
// Note: This is not 100% correct way of doing content negotiation
// But we just want a compatible result, quick, so this is okay
if (StringUtil.contains(accept, type)) {
return type;
}
}
}
// If none found, return default
return DEFAULT_TYPE;
} | [
"private",
"String",
"getContentType",
"(",
"HttpServletRequest",
"pRequest",
")",
"{",
"if",
"(",
"responseMessageTypes",
"!=",
"null",
")",
"{",
"String",
"accept",
"=",
"pRequest",
".",
"getHeader",
"(",
"\"Accept\"",
")",
";",
"for",
"(",
"String",
"type",... | Gets the content type for the response, suitable for the requesting user agent.
@param pRequest
@return the content type | [
"Gets",
"the",
"content",
"type",
"for",
"the",
"response",
"suitable",
"for",
"the",
"requesting",
"user",
"agent",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ThrottleFilter.java#L222-L237 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/BandwidthClient.java | BandwidthClient.setCredentials | public void setCredentials(final String userId, final String apiToken, final String apiSecret) {
if (userId != null && apiToken != null && apiSecret != null) {
this.usersUri = String.format(BandwidthConstants.USERS_URI_PATH, userId.replaceAll(" ", ""));
this.token = apiToken.replaceAll(" ", "");
this.secret = apiSecret.replaceAll(" ", "");
validateCredentials();
} else {
throw new MissingCredentialsException();
}
} | java | public void setCredentials(final String userId, final String apiToken, final String apiSecret) {
if (userId != null && apiToken != null && apiSecret != null) {
this.usersUri = String.format(BandwidthConstants.USERS_URI_PATH, userId.replaceAll(" ", ""));
this.token = apiToken.replaceAll(" ", "");
this.secret = apiSecret.replaceAll(" ", "");
validateCredentials();
} else {
throw new MissingCredentialsException();
}
} | [
"public",
"void",
"setCredentials",
"(",
"final",
"String",
"userId",
",",
"final",
"String",
"apiToken",
",",
"final",
"String",
"apiSecret",
")",
"{",
"if",
"(",
"userId",
"!=",
"null",
"&&",
"apiToken",
"!=",
"null",
"&&",
"apiSecret",
"!=",
"null",
")"... | The setCredentials() provides a convenience method to pass the userId, API-token and API-secret after
a client has been instantiated.
@param userId the user id.
@param apiToken the API token.
@param apiSecret the API secret. | [
"The",
"setCredentials",
"()",
"provides",
"a",
"convenience",
"method",
"to",
"pass",
"the",
"userId",
"API",
"-",
"token",
"and",
"API",
"-",
"secret",
"after",
"a",
"client",
"has",
"been",
"instantiated",
"."
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/BandwidthClient.java#L207-L217 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/SqlConnRunner.java | SqlConnRunner.findIn | public List<Entity> findIn(Connection conn, String tableName, String field, Object... values) throws SQLException{
return findAll(conn, Entity.create(tableName).set(field, values));
} | java | public List<Entity> findIn(Connection conn, String tableName, String field, Object... values) throws SQLException{
return findAll(conn, Entity.create(tableName).set(field, values));
} | [
"public",
"List",
"<",
"Entity",
">",
"findIn",
"(",
"Connection",
"conn",
",",
"String",
"tableName",
",",
"String",
"field",
",",
"Object",
"...",
"values",
")",
"throws",
"SQLException",
"{",
"return",
"findAll",
"(",
"conn",
",",
"Entity",
".",
"create... | 根据某个字段名条件查询数据列表,返回所有字段
@param conn 数据库连接对象
@param tableName 表名
@param field 字段名
@param values 字段值列表
@return 数据对象列表
@throws SQLException SQL执行异常 | [
"根据某个字段名条件查询数据列表,返回所有字段"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/SqlConnRunner.java#L428-L430 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/utils/PropertyLookup.java | PropertyLookup.hasProperty | public static boolean hasProperty(final String propKey, final File propFile) {
if (null == propKey) throw new IllegalArgumentException("propKey param was null");
if (null == propFile) throw new IllegalArgumentException("propFile param was null");
if (propFile.exists()) {
final Properties p = new Properties();
try {
FileInputStream fis = new FileInputStream(propFile);
try {
p.load(fis);
} finally {
if (null != fis) {
fis.close();
}
}
return p.containsKey(propKey);
} catch (IOException e) {
return false;
}
} else {
return false;
}
} | java | public static boolean hasProperty(final String propKey, final File propFile) {
if (null == propKey) throw new IllegalArgumentException("propKey param was null");
if (null == propFile) throw new IllegalArgumentException("propFile param was null");
if (propFile.exists()) {
final Properties p = new Properties();
try {
FileInputStream fis = new FileInputStream(propFile);
try {
p.load(fis);
} finally {
if (null != fis) {
fis.close();
}
}
return p.containsKey(propKey);
} catch (IOException e) {
return false;
}
} else {
return false;
}
} | [
"public",
"static",
"boolean",
"hasProperty",
"(",
"final",
"String",
"propKey",
",",
"final",
"File",
"propFile",
")",
"{",
"if",
"(",
"null",
"==",
"propKey",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"propKey param was null\"",
")",
";",
"if",
... | Reads propFile and then checks if specified key exists.
@param propKey property name
@param propFile property file
@return file if a property with that name exists. If an exception occurs while reading
the file, false is returned. | [
"Reads",
"propFile",
"and",
"then",
"checks",
"if",
"specified",
"key",
"exists",
"."
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/PropertyLookup.java#L333-L354 |
apache/incubator-gobblin | gobblin-modules/gobblin-crypto/src/main/java/org/apache/gobblin/crypto/JCEKSKeystoreCredentialStore.java | JCEKSKeystoreCredentialStore.generateAesKeys | public void generateAesKeys(int numKeys, int startOffset) throws IOException, KeyStoreException {
for (int i = 1; i <= numKeys; i++) {
SecretKey key = generateKey();
ks.setEntry(String.valueOf(i + startOffset), new KeyStore.SecretKeyEntry(key),
new KeyStore.PasswordProtection(password));
}
saveKeystore();
} | java | public void generateAesKeys(int numKeys, int startOffset) throws IOException, KeyStoreException {
for (int i = 1; i <= numKeys; i++) {
SecretKey key = generateKey();
ks.setEntry(String.valueOf(i + startOffset), new KeyStore.SecretKeyEntry(key),
new KeyStore.PasswordProtection(password));
}
saveKeystore();
} | [
"public",
"void",
"generateAesKeys",
"(",
"int",
"numKeys",
",",
"int",
"startOffset",
")",
"throws",
"IOException",
",",
"KeyStoreException",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<=",
"numKeys",
";",
"i",
"++",
")",
"{",
"SecretKey",
"key",... | Generate a set of AES keys for the store. The key ids will simple be (startOffset ... startOffset + numKeys).
@param numKeys Number of keys to generate
@param startOffset ID to start generating keys with
@throws IOException If there is an error serializing the keystore back to disk
@throws KeyStoreException If there is an error serializing the keystore back to disk | [
"Generate",
"a",
"set",
"of",
"AES",
"keys",
"for",
"the",
"store",
".",
"The",
"key",
"ids",
"will",
"simple",
"be",
"(",
"startOffset",
"...",
"startOffset",
"+",
"numKeys",
")",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-crypto/src/main/java/org/apache/gobblin/crypto/JCEKSKeystoreCredentialStore.java#L163-L171 |
dita-ot/dita-ot | src/main/java/org/dita/dost/ant/ExtensibleAntInvoker.java | ExtensibleAntInvoker.getJob | public static Job getJob(final File tempDir, final Project project) {
Job job = project.getReference(ANT_REFERENCE_JOB);
if (job != null && job.isStale()) {
project.log("Reload stale job configuration reference", Project.MSG_VERBOSE);
job = null;
}
if (job == null) {
try {
job = new Job(tempDir);
} catch (final IOException ioe) {
throw new BuildException(ioe);
}
project.addReference(ANT_REFERENCE_JOB, job);
}
return job;
} | java | public static Job getJob(final File tempDir, final Project project) {
Job job = project.getReference(ANT_REFERENCE_JOB);
if (job != null && job.isStale()) {
project.log("Reload stale job configuration reference", Project.MSG_VERBOSE);
job = null;
}
if (job == null) {
try {
job = new Job(tempDir);
} catch (final IOException ioe) {
throw new BuildException(ioe);
}
project.addReference(ANT_REFERENCE_JOB, job);
}
return job;
} | [
"public",
"static",
"Job",
"getJob",
"(",
"final",
"File",
"tempDir",
",",
"final",
"Project",
"project",
")",
"{",
"Job",
"job",
"=",
"project",
".",
"getReference",
"(",
"ANT_REFERENCE_JOB",
")",
";",
"if",
"(",
"job",
"!=",
"null",
"&&",
"job",
".",
... | Get job configuration from Ant project reference or create new.
@param tempDir configuration directory
@param project Ant project
@return job configuration | [
"Get",
"job",
"configuration",
"from",
"Ant",
"project",
"reference",
"or",
"create",
"new",
"."
] | train | https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/ant/ExtensibleAntInvoker.java#L292-L307 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/tiles/features/FeatureTiles.java | FeatureTiles.drawTileQueryAll | public BufferedImage drawTileQueryAll(int x, int y, int zoom) {
BoundingBox boundingBox = TileBoundingBoxUtils
.getWebMercatorBoundingBox(x, y, zoom);
BufferedImage image = null;
// Query for all features
FeatureResultSet resultSet = featureDao.queryForAll();
try {
int totalCount = resultSet.getCount();
// Draw if at least one geometry exists
if (totalCount > 0) {
if (maxFeaturesPerTile == null
|| totalCount <= maxFeaturesPerTile) {
// Draw the tile image
image = drawTile(zoom, boundingBox, resultSet);
} else if (maxFeaturesTileDraw != null) {
// Draw the unindexed max features tile
image = maxFeaturesTileDraw.drawUnindexedTile(tileWidth,
tileHeight, totalCount, resultSet);
}
}
} finally {
resultSet.close();
}
return image;
} | java | public BufferedImage drawTileQueryAll(int x, int y, int zoom) {
BoundingBox boundingBox = TileBoundingBoxUtils
.getWebMercatorBoundingBox(x, y, zoom);
BufferedImage image = null;
// Query for all features
FeatureResultSet resultSet = featureDao.queryForAll();
try {
int totalCount = resultSet.getCount();
// Draw if at least one geometry exists
if (totalCount > 0) {
if (maxFeaturesPerTile == null
|| totalCount <= maxFeaturesPerTile) {
// Draw the tile image
image = drawTile(zoom, boundingBox, resultSet);
} else if (maxFeaturesTileDraw != null) {
// Draw the unindexed max features tile
image = maxFeaturesTileDraw.drawUnindexedTile(tileWidth,
tileHeight, totalCount, resultSet);
}
}
} finally {
resultSet.close();
}
return image;
} | [
"public",
"BufferedImage",
"drawTileQueryAll",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"zoom",
")",
"{",
"BoundingBox",
"boundingBox",
"=",
"TileBoundingBoxUtils",
".",
"getWebMercatorBoundingBox",
"(",
"x",
",",
"y",
",",
"zoom",
")",
";",
"BufferedImag... | Draw a tile image from the x, y, and zoom level by querying all features.
This could be very slow if there are a lot of features
@param x
x coordinate
@param y
y coordinate
@param zoom
zoom level
@return drawn image, or null | [
"Draw",
"a",
"tile",
"image",
"from",
"the",
"x",
"y",
"and",
"zoom",
"level",
"by",
"querying",
"all",
"features",
".",
"This",
"could",
"be",
"very",
"slow",
"if",
"there",
"are",
"a",
"lot",
"of",
"features"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/tiles/features/FeatureTiles.java#L1193-L1229 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/requests/restaction/ChannelAction.java | ChannelAction.addPermissionOverride | @CheckReturnValue
public ChannelAction addPermissionOverride(IPermissionHolder target, Collection<Permission> allow, Collection<Permission> deny)
{
checkPermissions(allow);
checkPermissions(deny);
final long allowRaw = allow != null ? Permission.getRaw(allow) : 0;
final long denyRaw = deny != null ? Permission.getRaw(deny) : 0;
return addPermissionOverride(target, allowRaw, denyRaw);
} | java | @CheckReturnValue
public ChannelAction addPermissionOverride(IPermissionHolder target, Collection<Permission> allow, Collection<Permission> deny)
{
checkPermissions(allow);
checkPermissions(deny);
final long allowRaw = allow != null ? Permission.getRaw(allow) : 0;
final long denyRaw = deny != null ? Permission.getRaw(deny) : 0;
return addPermissionOverride(target, allowRaw, denyRaw);
} | [
"@",
"CheckReturnValue",
"public",
"ChannelAction",
"addPermissionOverride",
"(",
"IPermissionHolder",
"target",
",",
"Collection",
"<",
"Permission",
">",
"allow",
",",
"Collection",
"<",
"Permission",
">",
"deny",
")",
"{",
"checkPermissions",
"(",
"allow",
")",
... | Adds a new Role or Member {@link net.dv8tion.jda.core.entities.PermissionOverride PermissionOverride}
for the new Channel.
<p>Example:
<pre>{@code
Role role = guild.getPublicRole();
EnumSet<Permission> allow = EnumSet.of(Permission.MESSAGE_READ);
EnumSet<Permission> deny = EnumSet.of(Permission.MESSAGE_WRITE);
channelAction.addPermissionOverride(role, allow, deny);
}</pre>
@param target
The not-null {@link net.dv8tion.jda.core.entities.Role Role} or {@link net.dv8tion.jda.core.entities.Member Member} for the override
@param allow
The granted {@link net.dv8tion.jda.core.Permission Permissions} for the override or null
@param deny
The denied {@link net.dv8tion.jda.core.Permission Permissions} for the override or null
@throws java.lang.IllegalArgumentException
If the specified target is null or not within the same guild.
@return The current ChannelAction, for chaining convenience
@see java.util.EnumSet | [
"Adds",
"a",
"new",
"Role",
"or",
"Member",
"{",
"@link",
"net",
".",
"dv8tion",
".",
"jda",
".",
"core",
".",
"entities",
".",
"PermissionOverride",
"PermissionOverride",
"}",
"for",
"the",
"new",
"Channel",
"."
] | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/requests/restaction/ChannelAction.java#L255-L264 |
GoogleCloudPlatform/bigdata-interop | gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageImpl.java | GoogleCloudStorageImpl.getDeletionCallback | private JsonBatchCallback<Void> getDeletionCallback(
final StorageResourceId resourceId,
final KeySetView<IOException, Boolean> innerExceptions,
final BatchHelper batchHelper,
final int attempt,
final long generation) {
return new JsonBatchCallback<Void>() {
@Override
public void onSuccess(Void obj, HttpHeaders responseHeaders) {
logger.atFine().log("Successfully deleted %s at generation %s", resourceId, generation);
}
@Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
if (errorExtractor.itemNotFound(e)) {
// Ignore item-not-found errors. We do not have to delete what we cannot find. This
// error typically shows up when we make a request to delete something and the server
// receives the request but we get a retry-able error before we get a response.
// During a retry, we no longer find the item because the server had deleted
// it already.
logger.atFine().log("deleteObjects(%s): delete not found:%n%s", resourceId, e);
} else if (errorExtractor.preconditionNotMet(e)
&& attempt <= MAXIMUM_PRECONDITION_FAILURES_IN_DELETE) {
logger.atInfo().log(
"Precondition not met while deleting %s at generation %s. Attempt %s. Retrying:%n%s",
resourceId, generation, attempt, e);
queueSingleObjectDelete(resourceId, innerExceptions, batchHelper, attempt + 1);
} else {
innerExceptions.add(
new IOException(
String.format(
"Error deleting %s, stage 2 with generation %s:%n%s",
resourceId, generation, e)));
}
}
};
} | java | private JsonBatchCallback<Void> getDeletionCallback(
final StorageResourceId resourceId,
final KeySetView<IOException, Boolean> innerExceptions,
final BatchHelper batchHelper,
final int attempt,
final long generation) {
return new JsonBatchCallback<Void>() {
@Override
public void onSuccess(Void obj, HttpHeaders responseHeaders) {
logger.atFine().log("Successfully deleted %s at generation %s", resourceId, generation);
}
@Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
if (errorExtractor.itemNotFound(e)) {
// Ignore item-not-found errors. We do not have to delete what we cannot find. This
// error typically shows up when we make a request to delete something and the server
// receives the request but we get a retry-able error before we get a response.
// During a retry, we no longer find the item because the server had deleted
// it already.
logger.atFine().log("deleteObjects(%s): delete not found:%n%s", resourceId, e);
} else if (errorExtractor.preconditionNotMet(e)
&& attempt <= MAXIMUM_PRECONDITION_FAILURES_IN_DELETE) {
logger.atInfo().log(
"Precondition not met while deleting %s at generation %s. Attempt %s. Retrying:%n%s",
resourceId, generation, attempt, e);
queueSingleObjectDelete(resourceId, innerExceptions, batchHelper, attempt + 1);
} else {
innerExceptions.add(
new IOException(
String.format(
"Error deleting %s, stage 2 with generation %s:%n%s",
resourceId, generation, e)));
}
}
};
} | [
"private",
"JsonBatchCallback",
"<",
"Void",
">",
"getDeletionCallback",
"(",
"final",
"StorageResourceId",
"resourceId",
",",
"final",
"KeySetView",
"<",
"IOException",
",",
"Boolean",
">",
"innerExceptions",
",",
"final",
"BatchHelper",
"batchHelper",
",",
"final",
... | Helper to create a callback for a particular deletion request. | [
"Helper",
"to",
"create",
"a",
"callback",
"for",
"a",
"particular",
"deletion",
"request",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageImpl.java#L691-L727 |
codegist/crest | core/src/main/java/org/codegist/crest/CRestBuilder.java | CRestBuilder.deserializeXmlWith | public CRestBuilder deserializeXmlWith(Class<? extends Deserializer> deserializer, Map<String, Object> config) {
this.xmlDeserializer = deserializer;
this.xmlDeserializerConfig.clear();
this.xmlDeserializerConfig.putAll(config);
return this;
} | java | public CRestBuilder deserializeXmlWith(Class<? extends Deserializer> deserializer, Map<String, Object> config) {
this.xmlDeserializer = deserializer;
this.xmlDeserializerConfig.clear();
this.xmlDeserializerConfig.putAll(config);
return this;
} | [
"public",
"CRestBuilder",
"deserializeXmlWith",
"(",
"Class",
"<",
"?",
"extends",
"Deserializer",
">",
"deserializer",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"config",
")",
"{",
"this",
".",
"xmlDeserializer",
"=",
"deserializer",
";",
"this",
".",
... | <p>Overrides the default {@link org.codegist.crest.serializer.jaxb.JaxbDeserializer} XML deserializer with the given one</p>
<p>By default, <b>CRest</b> will use this deserializer for the following response Content-Type:</p>
<ul>
<li>application/xml</li>
<li>text/xml</li>
</ul>
@param deserializer deserializer to use for XML response Content-Type requests
@param config State that will be passed to the deserializer along with the CRestConfig object if the deserializer has declared a single argument constructor with CRestConfig parameter type
@return current builder
@see org.codegist.crest.serializer.jaxb.JaxbDeserializer
@see org.codegist.crest.serializer.simplexml.SimpleXmlDeserializer | [
"<p",
">",
"Overrides",
"the",
"default",
"{"
] | train | https://github.com/codegist/crest/blob/e99ba7728b27d2ddb2c247261350f1b6fa7a6698/core/src/main/java/org/codegist/crest/CRestBuilder.java#L757-L762 |
Stratio/bdt | src/main/java/com/stratio/qa/assertions/SeleniumAssert.java | SeleniumAssert.assertThat | public static SeleniumAssert assertThat(CommonG commong, List<WebElement> actual) {
return new SeleniumAssert(commong, actual);
} | java | public static SeleniumAssert assertThat(CommonG commong, List<WebElement> actual) {
return new SeleniumAssert(commong, actual);
} | [
"public",
"static",
"SeleniumAssert",
"assertThat",
"(",
"CommonG",
"commong",
",",
"List",
"<",
"WebElement",
">",
"actual",
")",
"{",
"return",
"new",
"SeleniumAssert",
"(",
"commong",
",",
"actual",
")",
";",
"}"
] | Checks a selenium list of WebElements.
@param commong common object that contains relevant execution info
@param actual webElement used in assert
@return SeleniumAssert | [
"Checks",
"a",
"selenium",
"list",
"of",
"WebElements",
"."
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/assertions/SeleniumAssert.java#L205-L207 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java | ParagraphVectors.predictSeveral | public Collection<String> predictSeveral(String rawText, int limit) {
if (tokenizerFactory == null)
throw new IllegalStateException("TokenizerFactory should be defined, prior to predict() call");
List<String> tokens = tokenizerFactory.create(rawText).getTokens();
List<VocabWord> document = new ArrayList<>();
for (String token : tokens) {
if (vocab.containsWord(token)) {
document.add(vocab.wordFor(token));
}
}
return predictSeveral(document, limit);
} | java | public Collection<String> predictSeveral(String rawText, int limit) {
if (tokenizerFactory == null)
throw new IllegalStateException("TokenizerFactory should be defined, prior to predict() call");
List<String> tokens = tokenizerFactory.create(rawText).getTokens();
List<VocabWord> document = new ArrayList<>();
for (String token : tokens) {
if (vocab.containsWord(token)) {
document.add(vocab.wordFor(token));
}
}
return predictSeveral(document, limit);
} | [
"public",
"Collection",
"<",
"String",
">",
"predictSeveral",
"(",
"String",
"rawText",
",",
"int",
"limit",
")",
"{",
"if",
"(",
"tokenizerFactory",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"TokenizerFactory should be defined, prior to predi... | Predict several labels based on the document.
Computes a similarity wrt the mean of the
representation of words in the document
@param rawText raw text of the document
@return possible labels in descending order | [
"Predict",
"several",
"labels",
"based",
"on",
"the",
"document",
".",
"Computes",
"a",
"similarity",
"wrt",
"the",
"mean",
"of",
"the",
"representation",
"of",
"words",
"in",
"the",
"document"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java#L464-L477 |
intellimate/Izou | src/main/java/org/intellimate/izou/threadpool/ThreadPoolManager.java | ThreadPoolManager.handleThrowable | public void handleThrowable(Throwable e, Object target) {
try {
ExceptionCallback exceptionCallback = (ExceptionCallback) target;
if (e instanceof Exception) {
exceptionCallback.exceptionThrown((Exception) e);
} else {
exceptionCallback.exceptionThrown(new RuntimeException(e));
}
} catch (IllegalArgumentException | ClassCastException e1) {
log.fatal("unable to provide callback for: " + target.toString(), e);
}
} | java | public void handleThrowable(Throwable e, Object target) {
try {
ExceptionCallback exceptionCallback = (ExceptionCallback) target;
if (e instanceof Exception) {
exceptionCallback.exceptionThrown((Exception) e);
} else {
exceptionCallback.exceptionThrown(new RuntimeException(e));
}
} catch (IllegalArgumentException | ClassCastException e1) {
log.fatal("unable to provide callback for: " + target.toString(), e);
}
} | [
"public",
"void",
"handleThrowable",
"(",
"Throwable",
"e",
",",
"Object",
"target",
")",
"{",
"try",
"{",
"ExceptionCallback",
"exceptionCallback",
"=",
"(",
"ExceptionCallback",
")",
"target",
";",
"if",
"(",
"e",
"instanceof",
"Exception",
")",
"{",
"except... | tries everything to log the exception
@param e the Throwable
@param target an instance of the thing which has thrown the Exception | [
"tries",
"everything",
"to",
"log",
"the",
"exception"
] | train | https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/threadpool/ThreadPoolManager.java#L50-L61 |
census-instrumentation/opencensus-java | api/src/main/java/io/opencensus/internal/Utils.java | Utils.format | private static String format(String template, @javax.annotation.Nullable Object... args) {
// If no arguments return the template.
if (args == null) {
return template;
}
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template, templateStart, placeholderStart);
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
} | java | private static String format(String template, @javax.annotation.Nullable Object... args) {
// If no arguments return the template.
if (args == null) {
return template;
}
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template, templateStart, placeholderStart);
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template, templateStart, template.length());
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
} | [
"private",
"static",
"String",
"format",
"(",
"String",
"template",
",",
"@",
"javax",
".",
"annotation",
".",
"Nullable",
"Object",
"...",
"args",
")",
"{",
"// If no arguments return the template.",
"if",
"(",
"args",
"==",
"null",
")",
"{",
"return",
"templ... | Note that this is somewhat-improperly used from Verify.java as well. | [
"Note",
"that",
"this",
"is",
"somewhat",
"-",
"improperly",
"used",
"from",
"Verify",
".",
"java",
"as",
"well",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/internal/Utils.java#L174-L207 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/servlet/job/impl/hibernate/PrintJobDao.java | PrintJobDao.getValue | public final Object getValue(final String id, final String property) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);
final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);
criteria.select(root.get(property));
criteria.where(builder.equal(root.get("referenceId"), id));
return getSession().createQuery(criteria).uniqueResult();
} | java | public final Object getValue(final String id, final String property) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);
final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);
criteria.select(root.get(property));
criteria.where(builder.equal(root.get("referenceId"), id));
return getSession().createQuery(criteria).uniqueResult();
} | [
"public",
"final",
"Object",
"getValue",
"(",
"final",
"String",
"id",
",",
"final",
"String",
"property",
")",
"{",
"final",
"CriteriaBuilder",
"builder",
"=",
"getSession",
"(",
")",
".",
"getCriteriaBuilder",
"(",
")",
";",
"final",
"CriteriaQuery",
"<",
... | get specific property value of job.
@param id the id
@param property the property name/path
@return the property value | [
"get",
"specific",
"property",
"value",
"of",
"job",
"."
] | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/servlet/job/impl/hibernate/PrintJobDao.java#L104-L111 |
selenide/selenide | src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java | SelenideProxyServer.addResponseFilter | public void addResponseFilter(String name, ResponseFilter responseFilter) {
if (responseFilters.containsKey(name)) {
throw new IllegalArgumentException("Duplicate response filter: " + name);
}
proxy.addResponseFilter(responseFilter);
responseFilters.put(name, responseFilter);
} | java | public void addResponseFilter(String name, ResponseFilter responseFilter) {
if (responseFilters.containsKey(name)) {
throw new IllegalArgumentException("Duplicate response filter: " + name);
}
proxy.addResponseFilter(responseFilter);
responseFilters.put(name, responseFilter);
} | [
"public",
"void",
"addResponseFilter",
"(",
"String",
"name",
",",
"ResponseFilter",
"responseFilter",
")",
"{",
"if",
"(",
"responseFilters",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Duplicate response filt... | Add a custom response filter which allows to track/modify all server responses to browser
@param name unique name of filter
@param responseFilter the filter | [
"Add",
"a",
"custom",
"response",
"filter",
"which",
"allows",
"to",
"track",
"/",
"modify",
"all",
"server",
"responses",
"to",
"browser"
] | train | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java#L96-L102 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/property/PropertyInfo.java | PropertyInfo.getPropertyValue | public Object getPropertyValue(Object instance, boolean forceDirect) {
try {
if (instance == null) {
return dflt == null || !isSerializable() ? null : getPropertyType().getSerializer().deserialize(dflt);
}
if (!forceDirect && instance instanceof IPropertyAccessor) {
return ((IPropertyAccessor) instance).getPropertyValue(this);
}
Method method = PropertyUtil.findGetter(getter, instance, null);
return method == null ? null : method.invoke(instance);
} catch (Exception e) {
throw MiscUtil.toUnchecked(e);
}
} | java | public Object getPropertyValue(Object instance, boolean forceDirect) {
try {
if (instance == null) {
return dflt == null || !isSerializable() ? null : getPropertyType().getSerializer().deserialize(dflt);
}
if (!forceDirect && instance instanceof IPropertyAccessor) {
return ((IPropertyAccessor) instance).getPropertyValue(this);
}
Method method = PropertyUtil.findGetter(getter, instance, null);
return method == null ? null : method.invoke(instance);
} catch (Exception e) {
throw MiscUtil.toUnchecked(e);
}
} | [
"public",
"Object",
"getPropertyValue",
"(",
"Object",
"instance",
",",
"boolean",
"forceDirect",
")",
"{",
"try",
"{",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"return",
"dflt",
"==",
"null",
"||",
"!",
"isSerializable",
"(",
")",
"?",
"null",
":"... | Returns the property value for a specified object instance.
@param instance The object instance.
@param forceDirect If true, a forces a direct read on the instance even if it implements
IPropertyAccessor
@return The object's property value. | [
"Returns",
"the",
"property",
"value",
"for",
"a",
"specified",
"object",
"instance",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/property/PropertyInfo.java#L188-L203 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/query/QueryToolChest.java | QueryToolChest.makePostComputeManipulatorFn | public Function<ResultType, ResultType> makePostComputeManipulatorFn(QueryType query, MetricManipulationFn fn)
{
return makePreComputeManipulatorFn(query, fn);
} | java | public Function<ResultType, ResultType> makePostComputeManipulatorFn(QueryType query, MetricManipulationFn fn)
{
return makePreComputeManipulatorFn(query, fn);
} | [
"public",
"Function",
"<",
"ResultType",
",",
"ResultType",
">",
"makePostComputeManipulatorFn",
"(",
"QueryType",
"query",
",",
"MetricManipulationFn",
"fn",
")",
"{",
"return",
"makePreComputeManipulatorFn",
"(",
"query",
",",
"fn",
")",
";",
"}"
] | Generally speaking this is the exact same thing as makePreComputeManipulatorFn. It is leveraged in
order to compute PostAggregators on results after they have been completely merged together, which
should actually be done in the mergeResults() call instead of here.
<p>
This should never actually be overridden and it should be removed as quickly as possible.
@param query The Query that is currently being processed
@param fn The function that should be applied to all metrics in the results
@return A function that will apply the provided fn to all metrics in the input ResultType object | [
"Generally",
"speaking",
"this",
"is",
"the",
"exact",
"same",
"thing",
"as",
"makePreComputeManipulatorFn",
".",
"It",
"is",
"leveraged",
"in",
"order",
"to",
"compute",
"PostAggregators",
"on",
"results",
"after",
"they",
"have",
"been",
"completely",
"merged",
... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/QueryToolChest.java#L141-L144 |
samskivert/pythagoras | src/main/java/pythagoras/d/Matrix4.java | Matrix4.setToOrtho | public Matrix4 setToOrtho (
double left, double right, double bottom, double top,
double near, double far, IVector3 nearFarNormal) {
double rlr = 1f / (left - right);
double rbt = 1f / (bottom - top);
double rnf = 1f / (near - far);
double s = 2f / (near*nearFarNormal.z() - far*nearFarNormal.z());
return set(-2f * rlr, 0f, 0f, (right + left) * rlr,
0f, -2f * rbt, 0f, (top + bottom) * rbt,
s * nearFarNormal.x(), s * nearFarNormal.y(), 2f * rnf, (far + near) * rnf,
0f, 0f, 0f, 1f);
} | java | public Matrix4 setToOrtho (
double left, double right, double bottom, double top,
double near, double far, IVector3 nearFarNormal) {
double rlr = 1f / (left - right);
double rbt = 1f / (bottom - top);
double rnf = 1f / (near - far);
double s = 2f / (near*nearFarNormal.z() - far*nearFarNormal.z());
return set(-2f * rlr, 0f, 0f, (right + left) * rlr,
0f, -2f * rbt, 0f, (top + bottom) * rbt,
s * nearFarNormal.x(), s * nearFarNormal.y(), 2f * rnf, (far + near) * rnf,
0f, 0f, 0f, 1f);
} | [
"public",
"Matrix4",
"setToOrtho",
"(",
"double",
"left",
",",
"double",
"right",
",",
"double",
"bottom",
",",
"double",
"top",
",",
"double",
"near",
",",
"double",
"far",
",",
"IVector3",
"nearFarNormal",
")",
"{",
"double",
"rlr",
"=",
"1f",
"/",
"("... | Sets this to an orthographic projection matrix.
@return a reference to this matrix, for chaining. | [
"Sets",
"this",
"to",
"an",
"orthographic",
"projection",
"matrix",
"."
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/Matrix4.java#L427-L438 |
liferay/com-liferay-commerce | commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java | CommerceUserSegmentEntryPersistenceImpl.findByGroupId | @Override
public List<CommerceUserSegmentEntry> findByGroupId(long groupId) {
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceUserSegmentEntry> findByGroupId(long groupId) {
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceUserSegmentEntry",
">",
"findByGroupId",
"(",
"long",
"groupId",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
... | Returns all the commerce user segment entries where groupId = ?.
@param groupId the group ID
@return the matching commerce user segment entries | [
"Returns",
"all",
"the",
"commerce",
"user",
"segment",
"entries",
"where",
"groupId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java#L127-L130 |
jbundle/jbundle | base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/html/HAppletHtmlScreen.java | HAppletHtmlScreen.printHtmlMenubar | public void printHtmlMenubar(PrintWriter out, ResourceBundle reg)
throws DBException
{
char chMenubar = ScreenFieldViewAdapter.getFirstToUpper(this.getProperty(DBParams.MENUBARS), 'Y');
if (chMenubar == 'Y')
{
String strUserName = this.getProperty(DBParams.USER_NAME);
String strUserID = this.getProperty(DBParams.USER_ID);
if ((strUserName == null) || (DBConstants.ANON_USER_ID.equals(strUserID)) || (Utility.isNumeric(strUserName)))
strUserName = DBConstants.BLANK;
String strNav = reg.getString((strUserName.length() > 0) ? "htmlMenubar" : "htmlMenubarAnon");
strNav = Utility.replaceResources(strNav, reg, null, null);
String strScreen = ((BasePanel)this.getScreenField()).getScreenURL();
strScreen = Utility.encodeXML(strScreen);
String strTitle = this.getProperty("title"); // Menu page
if ((strTitle == null) || (strTitle.length() == 0))
strTitle = ((BasePanel)this.getScreenField()).getTitle();
strNav = Utility.replace(strNav, HtmlConstants.URL_TAG, strScreen);
strNav = Utility.replace(strNav, HtmlConstants.TITLE_TAG, strTitle);
strNav = Utility.replace(strNav, HtmlConstants.USER_NAME_TAG, strUserName);
this.writeHtmlString(strNav, out);
}
} | java | public void printHtmlMenubar(PrintWriter out, ResourceBundle reg)
throws DBException
{
char chMenubar = ScreenFieldViewAdapter.getFirstToUpper(this.getProperty(DBParams.MENUBARS), 'Y');
if (chMenubar == 'Y')
{
String strUserName = this.getProperty(DBParams.USER_NAME);
String strUserID = this.getProperty(DBParams.USER_ID);
if ((strUserName == null) || (DBConstants.ANON_USER_ID.equals(strUserID)) || (Utility.isNumeric(strUserName)))
strUserName = DBConstants.BLANK;
String strNav = reg.getString((strUserName.length() > 0) ? "htmlMenubar" : "htmlMenubarAnon");
strNav = Utility.replaceResources(strNav, reg, null, null);
String strScreen = ((BasePanel)this.getScreenField()).getScreenURL();
strScreen = Utility.encodeXML(strScreen);
String strTitle = this.getProperty("title"); // Menu page
if ((strTitle == null) || (strTitle.length() == 0))
strTitle = ((BasePanel)this.getScreenField()).getTitle();
strNav = Utility.replace(strNav, HtmlConstants.URL_TAG, strScreen);
strNav = Utility.replace(strNav, HtmlConstants.TITLE_TAG, strTitle);
strNav = Utility.replace(strNav, HtmlConstants.USER_NAME_TAG, strUserName);
this.writeHtmlString(strNav, out);
}
} | [
"public",
"void",
"printHtmlMenubar",
"(",
"PrintWriter",
"out",
",",
"ResourceBundle",
"reg",
")",
"throws",
"DBException",
"{",
"char",
"chMenubar",
"=",
"ScreenFieldViewAdapter",
".",
"getFirstToUpper",
"(",
"this",
".",
"getProperty",
"(",
"DBParams",
".",
"ME... | Print the top nav menu.
@param out The html out stream.
@param reg The resources object.
@exception DBException File exception. | [
"Print",
"the",
"top",
"nav",
"menu",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/html/HAppletHtmlScreen.java#L135-L157 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Keys.java | Keys.fillRuntime | public static void fillRuntime(final Map<String, Object> dataModel) {
dataModel.put(Runtime.RUNTIME_CACHE, Latkes.getRuntimeCache().name());
dataModel.put(Runtime.RUNTIME_DATABASE, Latkes.getRuntimeDatabase().name());
dataModel.put(Runtime.RUNTIME_MODE, Latkes.getRuntimeMode().name());
} | java | public static void fillRuntime(final Map<String, Object> dataModel) {
dataModel.put(Runtime.RUNTIME_CACHE, Latkes.getRuntimeCache().name());
dataModel.put(Runtime.RUNTIME_DATABASE, Latkes.getRuntimeDatabase().name());
dataModel.put(Runtime.RUNTIME_MODE, Latkes.getRuntimeMode().name());
} | [
"public",
"static",
"void",
"fillRuntime",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"dataModel",
")",
"{",
"dataModel",
".",
"put",
"(",
"Runtime",
".",
"RUNTIME_CACHE",
",",
"Latkes",
".",
"getRuntimeCache",
"(",
")",
".",
"name",
"(",
")... | Fills the runtime info into the specified data model.
<ul>
<li>{@value org.b3log.latke.Keys.Runtime#RUNTIME_CACHE}</li>
<li>{@value org.b3log.latke.Keys.Runtime#RUNTIME_DATABASE}</li>
<li>{@value org.b3log.latke.Keys.Runtime#RUNTIME_MODE}</li>
</ul>
@param dataModel the specified data model | [
"Fills",
"the",
"runtime",
"info",
"into",
"the",
"specified",
"data",
"model",
".",
"<ul",
">",
"<li",
">",
"{",
"@value",
"org",
".",
"b3log",
".",
"latke",
".",
"Keys",
".",
"Runtime#RUNTIME_CACHE",
"}",
"<",
"/",
"li",
">",
"<li",
">",
"{",
"@val... | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Keys.java#L168-L172 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WDataTableRenderer.java | WDataTableRenderer.paintSortElement | private void paintSortElement(final WDataTable table, final XmlStringBuilder xml) {
int col = table.getSortColumnIndex();
boolean ascending = table.isSortAscending();
xml.appendTagOpen("ui:sort");
xml.appendOptionalAttribute("col", col >= 0, col);
xml.appendOptionalAttribute("descending", col >= 0 && !ascending, "true");
switch (table.getSortMode()) {
case SERVER:
case DYNAMIC:
xml.appendAttribute("mode", "dynamic");
break;
default:
throw new SystemException("Unknown sort mode: " + table.getSortMode());
}
xml.appendEnd();
} | java | private void paintSortElement(final WDataTable table, final XmlStringBuilder xml) {
int col = table.getSortColumnIndex();
boolean ascending = table.isSortAscending();
xml.appendTagOpen("ui:sort");
xml.appendOptionalAttribute("col", col >= 0, col);
xml.appendOptionalAttribute("descending", col >= 0 && !ascending, "true");
switch (table.getSortMode()) {
case SERVER:
case DYNAMIC:
xml.appendAttribute("mode", "dynamic");
break;
default:
throw new SystemException("Unknown sort mode: " + table.getSortMode());
}
xml.appendEnd();
} | [
"private",
"void",
"paintSortElement",
"(",
"final",
"WDataTable",
"table",
",",
"final",
"XmlStringBuilder",
"xml",
")",
"{",
"int",
"col",
"=",
"table",
".",
"getSortColumnIndex",
"(",
")",
";",
"boolean",
"ascending",
"=",
"table",
".",
"isSortAscending",
"... | Paint the rowSelection aspects of the WDataTable.
@param table the WDataTable being rendered
@param xml the string builder in use | [
"Paint",
"the",
"rowSelection",
"aspects",
"of",
"the",
"WDataTable",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WDataTableRenderer.java#L220-L238 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.multTransA | public static void multTransA(double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
// TODO add a matrix vectory multiply here
if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ||
b.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multTransA_reorder(alpha, a, b, c);
} else {
MatrixMatrixMult_DDRM.multTransA_small(alpha, a, b, c);
}
} | java | public static void multTransA(double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
// TODO add a matrix vectory multiply here
if( a.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ||
b.numCols >= EjmlParameters.MULT_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multTransA_reorder(alpha, a, b, c);
} else {
MatrixMatrixMult_DDRM.multTransA_small(alpha, a, b, c);
}
} | [
"public",
"static",
"void",
"multTransA",
"(",
"double",
"alpha",
",",
"DMatrix1Row",
"a",
",",
"DMatrix1Row",
"b",
",",
"DMatrix1Row",
"c",
")",
"{",
"// TODO add a matrix vectory multiply here",
"if",
"(",
"a",
".",
"numCols",
">=",
"EjmlParameters",
".",
"MUL... | <p>Performs the following operation:<br>
<br>
c = α * a<sup>T</sup> * b <br>
<br>
c<sub>ij</sub> = α ∑<sub>k=1:n</sub> { a<sub>ki</sub> * b<sub>kj</sub>}
</p>
@param alpha Scaling factor.
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"c",
"=",
"&alpha",
";",
"*",
"a<sup",
">",
"T<",
"/",
"sup",
">",
"*",
"b",
"<br",
">",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"&alpha",
";",
... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L152-L161 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/sql/SqlBuilder.java | SqlBuilder.in | @SuppressWarnings("unchecked")
public <T> SqlBuilder in(String field, T... values) {
sql.append(wrapper.wrap(field)).append(" IN ").append("(").append(ArrayUtil.join(values, StrUtil.COMMA)).append(")");
return this;
} | java | @SuppressWarnings("unchecked")
public <T> SqlBuilder in(String field, T... values) {
sql.append(wrapper.wrap(field)).append(" IN ").append("(").append(ArrayUtil.join(values, StrUtil.COMMA)).append(")");
return this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"SqlBuilder",
"in",
"(",
"String",
"field",
",",
"T",
"...",
"values",
")",
"{",
"sql",
".",
"append",
"(",
"wrapper",
".",
"wrap",
"(",
"field",
")",
")",
".",
"append",
"(... | 多值选择
@param <T> 值类型
@param field 字段名
@param values 值列表
@return 自身 | [
"多值选择"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/sql/SqlBuilder.java#L337-L341 |
rometools/rome | rome/src/main/java/com/rometools/rome/io/impl/RSS090Generator.java | RSS090Generator.populateChannel | protected void populateChannel(final Channel channel, final Element eChannel) {
final String title = channel.getTitle();
if (title != null) {
eChannel.addContent(generateSimpleElement("title", title));
}
final String link = channel.getLink();
if (link != null) {
eChannel.addContent(generateSimpleElement("link", link));
}
final String description = channel.getDescription();
if (description != null) {
eChannel.addContent(generateSimpleElement("description", description));
}
} | java | protected void populateChannel(final Channel channel, final Element eChannel) {
final String title = channel.getTitle();
if (title != null) {
eChannel.addContent(generateSimpleElement("title", title));
}
final String link = channel.getLink();
if (link != null) {
eChannel.addContent(generateSimpleElement("link", link));
}
final String description = channel.getDescription();
if (description != null) {
eChannel.addContent(generateSimpleElement("description", description));
}
} | [
"protected",
"void",
"populateChannel",
"(",
"final",
"Channel",
"channel",
",",
"final",
"Element",
"eChannel",
")",
"{",
"final",
"String",
"title",
"=",
"channel",
".",
"getTitle",
"(",
")",
";",
"if",
"(",
"title",
"!=",
"null",
")",
"{",
"eChannel",
... | Populates the given channel with parsed data from the ROME element that holds the channel
data.
@param channel the channel into which parsed data will be added.
@param eChannel the XML element that holds the data for the channel. | [
"Populates",
"the",
"given",
"channel",
"with",
"parsed",
"data",
"from",
"the",
"ROME",
"element",
"that",
"holds",
"the",
"channel",
"data",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/impl/RSS090Generator.java#L111-L124 |
BioPAX/Paxtools | json-converter/src/main/java/org/biopax/paxtools/io/jsonld/JsonldBiopaxConverter.java | JsonldBiopaxConverter.convertToJsonld | public void convertToJsonld(InputStream in, OutputStream os)
throws IOException {
File inputProcessedFile = preProcessFile(in);
LOG.info("OWl File processed successfully ");
// print current time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
LOG.info("Conversion RDF to JSONLD started "
+ sdf.format(Calendar.getInstance().getTime()));
// create an empty model
Model modelJena = ModelFactory.createDefaultModel();
InputStream internalInputStream = new FileInputStream(inputProcessedFile);
// read the RDF/XML file
RDFDataMgr.read(modelJena, internalInputStream, Lang.RDFXML);
LOG.info("Read into Model finished " + sdf.format(Calendar.getInstance().getTime()));
try { //close quietly and delete the temp. input file
internalInputStream.close();
inputProcessedFile.delete();
} catch(Exception e) {}
RDFDataMgr.write(os, modelJena, Lang.JSONLD);
LOG.info("Conversion RDF to JSONLD finished " + sdf.format(Calendar.getInstance().getTime()));
LOG.info(" JSONLD file " + " is written successfully.");
try { //close, flush quietly
os.close();
} catch(Exception e) {}
} | java | public void convertToJsonld(InputStream in, OutputStream os)
throws IOException {
File inputProcessedFile = preProcessFile(in);
LOG.info("OWl File processed successfully ");
// print current time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
LOG.info("Conversion RDF to JSONLD started "
+ sdf.format(Calendar.getInstance().getTime()));
// create an empty model
Model modelJena = ModelFactory.createDefaultModel();
InputStream internalInputStream = new FileInputStream(inputProcessedFile);
// read the RDF/XML file
RDFDataMgr.read(modelJena, internalInputStream, Lang.RDFXML);
LOG.info("Read into Model finished " + sdf.format(Calendar.getInstance().getTime()));
try { //close quietly and delete the temp. input file
internalInputStream.close();
inputProcessedFile.delete();
} catch(Exception e) {}
RDFDataMgr.write(os, modelJena, Lang.JSONLD);
LOG.info("Conversion RDF to JSONLD finished " + sdf.format(Calendar.getInstance().getTime()));
LOG.info(" JSONLD file " + " is written successfully.");
try { //close, flush quietly
os.close();
} catch(Exception e) {}
} | [
"public",
"void",
"convertToJsonld",
"(",
"InputStream",
"in",
",",
"OutputStream",
"os",
")",
"throws",
"IOException",
"{",
"File",
"inputProcessedFile",
"=",
"preProcessFile",
"(",
"in",
")",
";",
"LOG",
".",
"info",
"(",
"\"OWl File processed successfully \"",
... | /*
Convert inputstream in owl/rdf format to outputsream in jsonld format | [
"/",
"*",
"Convert",
"inputstream",
"in",
"owl",
"/",
"rdf",
"format",
"to",
"outputsream",
"in",
"jsonld",
"format"
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/json-converter/src/main/java/org/biopax/paxtools/io/jsonld/JsonldBiopaxConverter.java#L29-L59 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/parser/SimpleTextExtractingPdfContentStreamProcessor.java | SimpleTextExtractingPdfContentStreamProcessor.displayText | public void displayText(String text, Matrix endingTextMatrix){
boolean hardReturn = false;
if (lastTextLineMatrix != null && lastTextLineMatrix.get(Matrix.I32) != getCurrentTextLineMatrix().get(Matrix.I32)){
hardReturn = true;
}
float currentX = getCurrentTextMatrix().get(Matrix.I31);
if (hardReturn){
result.append('\n');
} else if (lastEndingTextMatrix != null){
float lastEndX = lastEndingTextMatrix.get(Matrix.I31);
float spaceGlyphWidth = gs().font.getWidth(' ')/1000f;
float spaceWidth = (spaceGlyphWidth * gs().fontSize + gs().characterSpacing + gs().wordSpacing) * gs().horizontalScaling; // this is unscaled!!
Matrix scaled = new Matrix(spaceWidth, 0).multiply(getCurrentTextMatrix());
float scaledSpaceWidth = scaled.get(Matrix.I31) - getCurrentTextMatrix().get(Matrix.I31);
if (currentX - lastEndX > scaledSpaceWidth/2f ){
result.append(' ');
}
}
if (text != null && result != null) {
result.append(text);
}
lastTextLineMatrix = getCurrentTextLineMatrix();
lastEndingTextMatrix = endingTextMatrix;
} | java | public void displayText(String text, Matrix endingTextMatrix){
boolean hardReturn = false;
if (lastTextLineMatrix != null && lastTextLineMatrix.get(Matrix.I32) != getCurrentTextLineMatrix().get(Matrix.I32)){
hardReturn = true;
}
float currentX = getCurrentTextMatrix().get(Matrix.I31);
if (hardReturn){
result.append('\n');
} else if (lastEndingTextMatrix != null){
float lastEndX = lastEndingTextMatrix.get(Matrix.I31);
float spaceGlyphWidth = gs().font.getWidth(' ')/1000f;
float spaceWidth = (spaceGlyphWidth * gs().fontSize + gs().characterSpacing + gs().wordSpacing) * gs().horizontalScaling; // this is unscaled!!
Matrix scaled = new Matrix(spaceWidth, 0).multiply(getCurrentTextMatrix());
float scaledSpaceWidth = scaled.get(Matrix.I31) - getCurrentTextMatrix().get(Matrix.I31);
if (currentX - lastEndX > scaledSpaceWidth/2f ){
result.append(' ');
}
}
if (text != null && result != null) {
result.append(text);
}
lastTextLineMatrix = getCurrentTextLineMatrix();
lastEndingTextMatrix = endingTextMatrix;
} | [
"public",
"void",
"displayText",
"(",
"String",
"text",
",",
"Matrix",
"endingTextMatrix",
")",
"{",
"boolean",
"hardReturn",
"=",
"false",
";",
"if",
"(",
"lastTextLineMatrix",
"!=",
"null",
"&&",
"lastTextLineMatrix",
".",
"get",
"(",
"Matrix",
".",
"I32",
... | Writes text to the result.
@param text The text that needs to be displayed
@param endingTextMatrix a text matrix
@see com.lowagie.text.pdf.parser.PdfContentStreamProcessor#displayText(java.lang.String, com.lowagie.text.pdf.parser.Matrix) | [
"Writes",
"text",
"to",
"the",
"result",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/parser/SimpleTextExtractingPdfContentStreamProcessor.java#L92-L121 |
Nexmo/nexmo-java | src/main/java/com/nexmo/client/sms/HexUtil.java | HexUtil.bytesToHex | public static String bytesToHex(byte[] bytes, String separator) {
StringBuilder tmpBuffer = new StringBuilder();
if (bytes != null) {
for (byte c : bytes) {
int b = c;
if (b < 0)
b += 256;
if (separator != null)
tmpBuffer.append(separator);
tmpBuffer.append(HEX_CHARS[(b & 0xf0) / 0x10]); // note, this benchmarks faster than using >> 4
tmpBuffer.append(HEX_CHARS[b & 0x0f]);
}
}
return tmpBuffer.toString();
} | java | public static String bytesToHex(byte[] bytes, String separator) {
StringBuilder tmpBuffer = new StringBuilder();
if (bytes != null) {
for (byte c : bytes) {
int b = c;
if (b < 0)
b += 256;
if (separator != null)
tmpBuffer.append(separator);
tmpBuffer.append(HEX_CHARS[(b & 0xf0) / 0x10]); // note, this benchmarks faster than using >> 4
tmpBuffer.append(HEX_CHARS[b & 0x0f]);
}
}
return tmpBuffer.toString();
} | [
"public",
"static",
"String",
"bytesToHex",
"(",
"byte",
"[",
"]",
"bytes",
",",
"String",
"separator",
")",
"{",
"StringBuilder",
"tmpBuffer",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"bytes",
"!=",
"null",
")",
"{",
"for",
"(",
"byte",
... | translate a byte array of raw data into a String with a hex representation of that data.
Each octet will be separated with a specific separator.
@param bytes raw binary data
@param separator This string will be injected into the output in between each octet in the stream
@return String Hex representation of the raw data with each octet separated by 'separator' | [
"translate",
"a",
"byte",
"array",
"of",
"raw",
"data",
"into",
"a",
"String",
"with",
"a",
"hex",
"representation",
"of",
"that",
"data",
".",
"Each",
"octet",
"will",
"be",
"separated",
"with",
"a",
"specific",
"separator",
"."
] | train | https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/sms/HexUtil.java#L62-L76 |
apache/incubator-atlas | webapp/src/main/java/org/apache/atlas/web/service/CuratorFactory.java | CuratorFactory.leaderLatchInstance | public LeaderLatch leaderLatchInstance(String serverId, String zkRoot) {
return new LeaderLatch(curatorFramework, zkRoot+APACHE_ATLAS_LEADER_ELECTOR_PATH, serverId);
} | java | public LeaderLatch leaderLatchInstance(String serverId, String zkRoot) {
return new LeaderLatch(curatorFramework, zkRoot+APACHE_ATLAS_LEADER_ELECTOR_PATH, serverId);
} | [
"public",
"LeaderLatch",
"leaderLatchInstance",
"(",
"String",
"serverId",
",",
"String",
"zkRoot",
")",
"{",
"return",
"new",
"LeaderLatch",
"(",
"curatorFramework",
",",
"zkRoot",
"+",
"APACHE_ATLAS_LEADER_ELECTOR_PATH",
",",
"serverId",
")",
";",
"}"
] | Create a new instance {@link LeaderLatch}
@param serverId the ID used to register this instance with curator.
This ID should typically be obtained using
{@link org.apache.atlas.ha.AtlasServerIdSelector#selectServerId(Configuration)}
@param zkRoot the root znode under which the leader latch node is added.
@return | [
"Create",
"a",
"new",
"instance",
"{"
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/service/CuratorFactory.java#L195-L197 |
getsentry/sentry-java | sentry/src/main/java/io/sentry/jul/SentryHandler.java | SentryHandler.formatMessage | protected String formatMessage(String message, Object[] parameters) {
String formatted;
if (printfStyle) {
formatted = String.format(message, parameters);
} else {
formatted = MessageFormat.format(message, parameters);
}
return formatted;
} | java | protected String formatMessage(String message, Object[] parameters) {
String formatted;
if (printfStyle) {
formatted = String.format(message, parameters);
} else {
formatted = MessageFormat.format(message, parameters);
}
return formatted;
} | [
"protected",
"String",
"formatMessage",
"(",
"String",
"message",
",",
"Object",
"[",
"]",
"parameters",
")",
"{",
"String",
"formatted",
";",
"if",
"(",
"printfStyle",
")",
"{",
"formatted",
"=",
"String",
".",
"format",
"(",
"message",
",",
"parameters",
... | Returns formatted Event message when provided the message template and
parameters.
@param message Message template body.
@param parameters Array of parameters for the message.
@return Formatted message. | [
"Returns",
"formatted",
"Event",
"message",
"when",
"provided",
"the",
"message",
"template",
"and",
"parameters",
"."
] | train | https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/jul/SentryHandler.java#L177-L185 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getLastIndexOf | public static int getLastIndexOf (@Nullable final String sText, final char cSearch)
{
return sText != null && sText.length () >= 1 ? sText.lastIndexOf (cSearch) : STRING_NOT_FOUND;
} | java | public static int getLastIndexOf (@Nullable final String sText, final char cSearch)
{
return sText != null && sText.length () >= 1 ? sText.lastIndexOf (cSearch) : STRING_NOT_FOUND;
} | [
"public",
"static",
"int",
"getLastIndexOf",
"(",
"@",
"Nullable",
"final",
"String",
"sText",
",",
"final",
"char",
"cSearch",
")",
"{",
"return",
"sText",
"!=",
"null",
"&&",
"sText",
".",
"length",
"(",
")",
">=",
"1",
"?",
"sText",
".",
"lastIndexOf"... | Get the last index of cSearch within sText.
@param sText
The text to search in. May be <code>null</code>.
@param cSearch
The character to search for. May be <code>null</code>.
@return The last index of sSearch within sText or {@value #STRING_NOT_FOUND}
if cSearch was not found or if any parameter was <code>null</code>.
@see String#lastIndexOf(int) | [
"Get",
"the",
"last",
"index",
"of",
"cSearch",
"within",
"sText",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2790-L2793 |
albfernandez/itext2 | src/main/java/com/lowagie/text/rtf/parser/destinations/RtfDestinationColorTable.java | RtfDestinationColorTable.processColor | private void processColor() {
if(red != -1 && green != -1 && blue != -1) {
if(this.rtfParser.isImport()) {
this.importHeader.importColor(Integer.toString(this.colorNr), new Color(this.red, this.green, this.blue));
}
if(this.rtfParser.isConvert()) {
colorMap.put(Integer.toString(this.colorNr), new Color(this.red, this.green, this.blue));
}
}
this.setToDefaults();
this.colorNr++;
} | java | private void processColor() {
if(red != -1 && green != -1 && blue != -1) {
if(this.rtfParser.isImport()) {
this.importHeader.importColor(Integer.toString(this.colorNr), new Color(this.red, this.green, this.blue));
}
if(this.rtfParser.isConvert()) {
colorMap.put(Integer.toString(this.colorNr), new Color(this.red, this.green, this.blue));
}
}
this.setToDefaults();
this.colorNr++;
} | [
"private",
"void",
"processColor",
"(",
")",
"{",
"if",
"(",
"red",
"!=",
"-",
"1",
"&&",
"green",
"!=",
"-",
"1",
"&&",
"blue",
"!=",
"-",
"1",
")",
"{",
"if",
"(",
"this",
".",
"rtfParser",
".",
"isImport",
"(",
")",
")",
"{",
"this",
".",
... | Processes the color triplet parsed from the document.
Add it to the import mapping so colors can be mapped when encountered
in the RTF import or conversion. | [
"Processes",
"the",
"color",
"triplet",
"parsed",
"from",
"the",
"document",
".",
"Add",
"it",
"to",
"the",
"import",
"mapping",
"so",
"colors",
"can",
"be",
"mapped",
"when",
"encountered",
"in",
"the",
"RTF",
"import",
"or",
"conversion",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/parser/destinations/RtfDestinationColorTable.java#L233-L245 |
DV8FromTheWorld/JDA | src/main/java/net/dv8tion/jda/core/managers/AccountManager.java | AccountManager.setName | @CheckReturnValue
public AccountManager setName(String name, String currentPassword)
{
Checks.notBlank(name, "Name");
Checks.check(name.length() >= 2 && name.length() <= 32, "Name must be between 2-32 characters long");
this.currentPassword = currentPassword;
this.name = name;
set |= NAME;
return this;
} | java | @CheckReturnValue
public AccountManager setName(String name, String currentPassword)
{
Checks.notBlank(name, "Name");
Checks.check(name.length() >= 2 && name.length() <= 32, "Name must be between 2-32 characters long");
this.currentPassword = currentPassword;
this.name = name;
set |= NAME;
return this;
} | [
"@",
"CheckReturnValue",
"public",
"AccountManager",
"setName",
"(",
"String",
"name",
",",
"String",
"currentPassword",
")",
"{",
"Checks",
".",
"notBlank",
"(",
"name",
",",
"\"Name\"",
")",
";",
"Checks",
".",
"check",
"(",
"name",
".",
"length",
"(",
"... | Sets the username for the currently logged in account
@param name
The new username
@param currentPassword
The current password for the represented account,
this is only required for {@link net.dv8tion.jda.core.AccountType#CLIENT AccountType.CLIENT}
@throws IllegalArgumentException
If this is action is performed on an account with the type {@link net.dv8tion.jda.core.AccountType#CLIENT CLIENT}
and the provided password is {@code null} or empty
<br>If the provided name is:
<ul>
<li>Equal to {@code null}</li>
<li>Less than 2 or more than 32 characters in length</li>
</ul>
@return AccountManager for chaining convenience | [
"Sets",
"the",
"username",
"for",
"the",
"currently",
"logged",
"in",
"account"
] | train | https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/managers/AccountManager.java#L206-L215 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/miner/MinerAdapter.java | MinerAdapter.toStringSet | public Set<String> toStringSet(Set<ModificationFeature> set)
{
List<ModificationFeature> list = new ArrayList<ModificationFeature>(set);
Collections.sort(list, new Comparator<ModificationFeature>()
{
@Override
public int compare(ModificationFeature o1, ModificationFeature o2)
{
String t1 = getModificationTerm(o1);
String t2 = getModificationTerm(o2);
Integer l1 = getPositionStart(o1);
Integer l2 = getPositionStart(o2);
if (t1 == null && t2 == null) return l1.compareTo(l2);
if (t1 == null) return 1;
if (t2 == null) return -1;
if (t1.equals(t2)) return l1.compareTo(l2);
return t1.compareTo(t2);
}
});
return getInString(list);
} | java | public Set<String> toStringSet(Set<ModificationFeature> set)
{
List<ModificationFeature> list = new ArrayList<ModificationFeature>(set);
Collections.sort(list, new Comparator<ModificationFeature>()
{
@Override
public int compare(ModificationFeature o1, ModificationFeature o2)
{
String t1 = getModificationTerm(o1);
String t2 = getModificationTerm(o2);
Integer l1 = getPositionStart(o1);
Integer l2 = getPositionStart(o2);
if (t1 == null && t2 == null) return l1.compareTo(l2);
if (t1 == null) return 1;
if (t2 == null) return -1;
if (t1.equals(t2)) return l1.compareTo(l2);
return t1.compareTo(t2);
}
});
return getInString(list);
} | [
"public",
"Set",
"<",
"String",
">",
"toStringSet",
"(",
"Set",
"<",
"ModificationFeature",
">",
"set",
")",
"{",
"List",
"<",
"ModificationFeature",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"ModificationFeature",
">",
"(",
"set",
")",
";",
"Collections",
... | Sorts the modifications and gets them in a String.
@param set modifications
@return a String listing the modifications | [
"Sorts",
"the",
"modifications",
"and",
"gets",
"them",
"in",
"a",
"String",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/miner/MinerAdapter.java#L273-L297 |
james-hu/jabb-core | src/main/java/net/sf/jabb/camel/RegistryUtility.java | RegistryUtility.addEncoder | @SuppressWarnings("unchecked")
static public void addEncoder(CamelContext context, String name, ChannelDownstreamHandler encoder){
CombinedRegistry registry = getCombinedRegistry(context);
addCodecOnly(registry, name, encoder);
List<ChannelDownstreamHandler> encoders;
Object o = registry.lookup(NAME_ENCODERS);
if (o == null){
encoders = new ArrayList<ChannelDownstreamHandler>();
registry.getDefaultSimpleRegistry().put(NAME_ENCODERS, encoders);
}else{
try{
encoders = (List<ChannelDownstreamHandler>)o;
}catch(Exception e){
throw new IllegalArgumentException("Preserved name '" + NAME_ENCODERS + "' is already being used by others in at least one of the registries.");
}
}
encoders.add(encoder);
} | java | @SuppressWarnings("unchecked")
static public void addEncoder(CamelContext context, String name, ChannelDownstreamHandler encoder){
CombinedRegistry registry = getCombinedRegistry(context);
addCodecOnly(registry, name, encoder);
List<ChannelDownstreamHandler> encoders;
Object o = registry.lookup(NAME_ENCODERS);
if (o == null){
encoders = new ArrayList<ChannelDownstreamHandler>();
registry.getDefaultSimpleRegistry().put(NAME_ENCODERS, encoders);
}else{
try{
encoders = (List<ChannelDownstreamHandler>)o;
}catch(Exception e){
throw new IllegalArgumentException("Preserved name '" + NAME_ENCODERS + "' is already being used by others in at least one of the registries.");
}
}
encoders.add(encoder);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"static",
"public",
"void",
"addEncoder",
"(",
"CamelContext",
"context",
",",
"String",
"name",
",",
"ChannelDownstreamHandler",
"encoder",
")",
"{",
"CombinedRegistry",
"registry",
"=",
"getCombinedRegistry",
"(",
... | Adds an Netty encoder to Registry.<br>
向Registry中增加一个给Netty用的encoder。
@param context The CamelContext must be based on CombinedRegistry, otherwise ClassCastException will be thrown.<br>
这个context必须是采用CombinedRegistry类型的Registry的,否则会抛出格式转换异常。
@param name Name of the encoder in Registry.<br>
encoder在Registry中的名字。
@param encoder The encoder that will be used by Netty.<br>
将被Netty用到的encoder。 | [
"Adds",
"an",
"Netty",
"encoder",
"to",
"Registry",
".",
"<br",
">",
"向Registry中增加一个给Netty用的encoder。"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/camel/RegistryUtility.java#L76-L94 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/reflect/TypeMatcher.java | TypeMatcher.matchType | public static boolean matchType(Object expectedType, Class<?> actualType) {
if (expectedType == null)
return true;
if (actualType == null)
throw new NullPointerException("Actual type cannot be null");
if (expectedType instanceof Class<?>)
return ((Class<?>) expectedType).isAssignableFrom(actualType);
if (expectedType instanceof String)
return matchTypeByName((String) expectedType, actualType);
if (expectedType instanceof TypeCode)
return TypeConverter.toTypeCode(actualType).equals(expectedType);
return false;
} | java | public static boolean matchType(Object expectedType, Class<?> actualType) {
if (expectedType == null)
return true;
if (actualType == null)
throw new NullPointerException("Actual type cannot be null");
if (expectedType instanceof Class<?>)
return ((Class<?>) expectedType).isAssignableFrom(actualType);
if (expectedType instanceof String)
return matchTypeByName((String) expectedType, actualType);
if (expectedType instanceof TypeCode)
return TypeConverter.toTypeCode(actualType).equals(expectedType);
return false;
} | [
"public",
"static",
"boolean",
"matchType",
"(",
"Object",
"expectedType",
",",
"Class",
"<",
"?",
">",
"actualType",
")",
"{",
"if",
"(",
"expectedType",
"==",
"null",
")",
"return",
"true",
";",
"if",
"(",
"actualType",
"==",
"null",
")",
"throw",
"new... | Matches expected type to an actual type. The types can be specified as types,
type names or TypeCode.
@param expectedType an expected type to match.
@param actualType an actual type to match.
@return true if types are matching and false if they don't.
@see #matchTypeByName(String, Class) | [
"Matches",
"expected",
"type",
"to",
"an",
"actual",
"type",
".",
"The",
"types",
"can",
"be",
"specified",
"as",
"types",
"type",
"names",
"or",
"TypeCode",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/TypeMatcher.java#L49-L65 |
oasp/oasp4j | modules/basic/src/main/java/io/oasp/module/basic/common/api/config/SimpleConfigProperties.java | SimpleConfigProperties.fromHierarchicalMap | @SuppressWarnings("unchecked")
protected void fromHierarchicalMap(Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) {
SimpleConfigProperties child = (SimpleConfigProperties) getChild(entry.getKey(), true);
Object childObject = entry.getValue();
if (childObject instanceof Map) {
child.fromHierarchicalMap((Map<String, Object>) childObject);
} else {
child.value = childObject.toString();
}
}
} | java | @SuppressWarnings("unchecked")
protected void fromHierarchicalMap(Map<String, Object> map) {
for (Entry<String, Object> entry : map.entrySet()) {
SimpleConfigProperties child = (SimpleConfigProperties) getChild(entry.getKey(), true);
Object childObject = entry.getValue();
if (childObject instanceof Map) {
child.fromHierarchicalMap((Map<String, Object>) childObject);
} else {
child.value = childObject.toString();
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"void",
"fromHierarchicalMap",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"map",
".",
"entrySet",
... | @see SimpleConfigProperties#ofHierarchicalMap(String, Map)
@param map the hierarchical {@link Map} of the configuration values. | [
"@see",
"SimpleConfigProperties#ofHierarchicalMap",
"(",
"String",
"Map",
")"
] | train | https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/basic/src/main/java/io/oasp/module/basic/common/api/config/SimpleConfigProperties.java#L271-L283 |
hawkular/hawkular-agent | hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/InventoryIdUtil.java | InventoryIdUtil.generateResourceId | public static ID generateResourceId(
String feedId,
MonitoredEndpoint<? extends AbstractEndpointConfiguration> endpoint,
String idPart) {
ID id = new ID(String.format("%s~%s~%s", feedId, endpoint.getName(), idPart));
return id;
} | java | public static ID generateResourceId(
String feedId,
MonitoredEndpoint<? extends AbstractEndpointConfiguration> endpoint,
String idPart) {
ID id = new ID(String.format("%s~%s~%s", feedId, endpoint.getName(), idPart));
return id;
} | [
"public",
"static",
"ID",
"generateResourceId",
"(",
"String",
"feedId",
",",
"MonitoredEndpoint",
"<",
"?",
"extends",
"AbstractEndpointConfiguration",
">",
"endpoint",
",",
"String",
"idPart",
")",
"{",
"ID",
"id",
"=",
"new",
"ID",
"(",
"String",
".",
"form... | Generates an ID for a resource.
@param feedId the ID of the feed that owns the resource whose ID is to be generated
@param endpoint the endpoint where the resource is found
@param idPart a unique string that identifies the resource within the managed server
@return the resource ID | [
"Generates",
"an",
"ID",
"for",
"a",
"resource",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/InventoryIdUtil.java#L80-L86 |
fengwenyi/JavaLib | src/main/java/com/fengwenyi/javalib/util/MathUtil.java | MathUtil.randomNum | public static double randomNum(int x, int y) {
int max = x + 1;
int min = y + 1;
Random random = new Random();
int result = random.nextInt(max)%(max-min+1) + min;
return result - 1;
} | java | public static double randomNum(int x, int y) {
int max = x + 1;
int min = y + 1;
Random random = new Random();
int result = random.nextInt(max)%(max-min+1) + min;
return result - 1;
} | [
"public",
"static",
"double",
"randomNum",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"int",
"max",
"=",
"x",
"+",
"1",
";",
"int",
"min",
"=",
"y",
"+",
"1",
";",
"Random",
"random",
"=",
"new",
"Random",
"(",
")",
";",
"int",
"result",
"=",
... | 在[y, x]范围内产生一个随机数
@param x 最大值
@param y 最小值
@return [y, x]范围内的随机数 | [
"在",
"[",
"y",
"x",
"]",
"范围内产生一个随机数"
] | train | https://github.com/fengwenyi/JavaLib/blob/14838b13fb11c024e41be766aa3e13ead4be1703/src/main/java/com/fengwenyi/javalib/util/MathUtil.java#L26-L32 |
jmxtrans/embedded-jmxtrans | src/main/java/org/jmxtrans/embedded/util/json/PropertyPlaceholderResolver.java | PropertyPlaceholderResolver.resolvePlaceholder | @Nonnull
protected String resolvePlaceholder(String property, @Nullable String defaultValue) throws EmbeddedJmxTransException {
// "graphite.host" -> "GRAPHITE_HOST"
String environmentVariableStyleProperty = property.toUpperCase();
environmentVariableStyleProperty = environmentVariableStyleProperty.replaceAll("\\.", "_");
String result;
if (System.getProperties().containsKey(property)) {
result = System.getProperty(property);
} else if (System.getenv().containsKey(property)) {
result = System.getenv(property);
} else if (System.getenv().containsKey(environmentVariableStyleProperty)) {
result = System.getenv(environmentVariableStyleProperty);
} else if (defaultValue != null) {
result = defaultValue;
} else {
throw new EmbeddedJmxTransException("Property '" + property + "' not found in System properties nor in Environment variables");
}
return result;
} | java | @Nonnull
protected String resolvePlaceholder(String property, @Nullable String defaultValue) throws EmbeddedJmxTransException {
// "graphite.host" -> "GRAPHITE_HOST"
String environmentVariableStyleProperty = property.toUpperCase();
environmentVariableStyleProperty = environmentVariableStyleProperty.replaceAll("\\.", "_");
String result;
if (System.getProperties().containsKey(property)) {
result = System.getProperty(property);
} else if (System.getenv().containsKey(property)) {
result = System.getenv(property);
} else if (System.getenv().containsKey(environmentVariableStyleProperty)) {
result = System.getenv(environmentVariableStyleProperty);
} else if (defaultValue != null) {
result = defaultValue;
} else {
throw new EmbeddedJmxTransException("Property '" + property + "' not found in System properties nor in Environment variables");
}
return result;
} | [
"@",
"Nonnull",
"protected",
"String",
"resolvePlaceholder",
"(",
"String",
"property",
",",
"@",
"Nullable",
"String",
"defaultValue",
")",
"throws",
"EmbeddedJmxTransException",
"{",
"// \"graphite.host\" -> \"GRAPHITE_HOST\"",
"String",
"environmentVariableStyleProperty",
... | Search for the given placeholder in system properties then in environment variables.
@param property property to resolve
@param defaultValue Default value if the placeholder is not found. <code>null</code> means not default value is
defined and the placeholder must exist
@return the resolved property or the default value if the placeholder is not found and the default value is defined
@throws org.jmxtrans.embedded.EmbeddedJmxTransException if the placeholder is not found and the given <code>defaultValue</code> is not
defined (<code>null</code>) | [
"Search",
"for",
"the",
"given",
"placeholder",
"in",
"system",
"properties",
"then",
"in",
"environment",
"variables",
"."
] | train | https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/util/json/PropertyPlaceholderResolver.java#L110-L132 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/view/ViewUtils.java | ViewUtils.dipToPixel | public static int dipToPixel(Resources resources, int dip) {
final float scale = resources.getDisplayMetrics().density;
// add 0.5f to round the figure up to the nearest whole number
return (int) (dip * scale + 0.5f);
} | java | public static int dipToPixel(Resources resources, int dip) {
final float scale = resources.getDisplayMetrics().density;
// add 0.5f to round the figure up to the nearest whole number
return (int) (dip * scale + 0.5f);
} | [
"public",
"static",
"int",
"dipToPixel",
"(",
"Resources",
"resources",
",",
"int",
"dip",
")",
"{",
"final",
"float",
"scale",
"=",
"resources",
".",
"getDisplayMetrics",
"(",
")",
".",
"density",
";",
"// add 0.5f to round the figure up to the nearest whole number",... | Convert the dips to pixels, based on density scale.
@param resources application resources.
@param dip to be converted value.
@return converted value(px). | [
"Convert",
"the",
"dips",
"to",
"pixels",
"based",
"on",
"density",
"scale",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/view/ViewUtils.java#L53-L57 |
openengsb/openengsb | components/console/src/main/java/org/openengsb/core/console/internal/util/ServicesHelper.java | ServicesHelper.deleteService | public void deleteService(String id, boolean force) {
try {
if (id == null || id.isEmpty()) {
id = selectRunningService();
}
final String idFinal = id;
int input = 'Y';
if (!force) {
OutputStreamFormater.printValue(String.format(
"Do you really want to delete the connector: %s (Y/n): ", id));
input = keyboard.read();
}
if ('n' != (char) input && 'N' != (char) input) {
SecurityContext.executeWithSystemPermissions(new Callable<Object>() {
@Override
public Object call() throws Exception {
serviceManager.delete(idFinal);
return null;
}
});
OutputStreamFormater.printValue(String.format("Service: %s successfully deleted", id));
}
} catch (ExecutionException e) {
e.printStackTrace();
System.err.println("Could not delete service");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Unexpected Error");
}
} | java | public void deleteService(String id, boolean force) {
try {
if (id == null || id.isEmpty()) {
id = selectRunningService();
}
final String idFinal = id;
int input = 'Y';
if (!force) {
OutputStreamFormater.printValue(String.format(
"Do you really want to delete the connector: %s (Y/n): ", id));
input = keyboard.read();
}
if ('n' != (char) input && 'N' != (char) input) {
SecurityContext.executeWithSystemPermissions(new Callable<Object>() {
@Override
public Object call() throws Exception {
serviceManager.delete(idFinal);
return null;
}
});
OutputStreamFormater.printValue(String.format("Service: %s successfully deleted", id));
}
} catch (ExecutionException e) {
e.printStackTrace();
System.err.println("Could not delete service");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Unexpected Error");
}
} | [
"public",
"void",
"deleteService",
"(",
"String",
"id",
",",
"boolean",
"force",
")",
"{",
"try",
"{",
"if",
"(",
"id",
"==",
"null",
"||",
"id",
".",
"isEmpty",
"(",
")",
")",
"{",
"id",
"=",
"selectRunningService",
"(",
")",
";",
"}",
"final",
"S... | delete a service identified by its id, if force is true, the user does not have to confirm | [
"delete",
"a",
"service",
"identified",
"by",
"its",
"id",
"if",
"force",
"is",
"true",
"the",
"user",
"does",
"not",
"have",
"to",
"confirm"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/console/src/main/java/org/openengsb/core/console/internal/util/ServicesHelper.java#L119-L148 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java | TheMovieDbApi.addItemToList | public StatusCode addItemToList(String sessionId, String listId, Integer mediaId) throws MovieDbException {
return tmdbList.addItem(sessionId, listId, mediaId);
} | java | public StatusCode addItemToList(String sessionId, String listId, Integer mediaId) throws MovieDbException {
return tmdbList.addItem(sessionId, listId, mediaId);
} | [
"public",
"StatusCode",
"addItemToList",
"(",
"String",
"sessionId",
",",
"String",
"listId",
",",
"Integer",
"mediaId",
")",
"throws",
"MovieDbException",
"{",
"return",
"tmdbList",
".",
"addItem",
"(",
"sessionId",
",",
"listId",
",",
"mediaId",
")",
";",
"}... | This method lets users add new items to a list that they created.
A valid session id is required.
@param sessionId sessionId
@param listId listId
@param mediaId mediaId
@return true if the movie is on the list
@throws MovieDbException exception | [
"This",
"method",
"lets",
"users",
"add",
"new",
"items",
"to",
"a",
"list",
"that",
"they",
"created",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L815-L817 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/base/base_resource.java | base_resource.post_request | private base_resource[] post_request(nitro_service service, options option) throws Exception
{
return add_resource(service, option);
} | java | private base_resource[] post_request(nitro_service service, options option) throws Exception
{
return add_resource(service, option);
} | [
"private",
"base_resource",
"[",
"]",
"post_request",
"(",
"nitro_service",
"service",
",",
"options",
"option",
")",
"throws",
"Exception",
"{",
"return",
"add_resource",
"(",
"service",
",",
"option",
")",
";",
"}"
] | Use this method to perform a Add operation on netscaler resource.
@param service nitro_service object.
@param option Options class object.
@return status of the operation performed.
@throws Exception if invalid input is given. | [
"Use",
"this",
"method",
"to",
"perform",
"a",
"Add",
"operation",
"on",
"netscaler",
"resource",
"."
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/base/base_resource.java#L193-L196 |
BioPAX/Paxtools | json-converter/src/main/java/org/biopax/paxtools/io/jsonld/JsonldBiopaxConverter.java | JsonldBiopaxConverter.convertFromJsonld | public void convertFromJsonld(InputStream in, OutputStream out) {
Model modelJena = ModelFactory.createDefaultModel();
if (in == null) {
throw new IllegalArgumentException("Input File: " + " not found");
}
if (out == null) {
throw new IllegalArgumentException("Output File: " + " not found");
}
// read the JSONLD file
modelJena.read(in, null, "JSONLD");
RDFDataMgr.write(out, modelJena, Lang.RDFXML);
LOG.info(" RDF file " + " is written successfully.");
} | java | public void convertFromJsonld(InputStream in, OutputStream out) {
Model modelJena = ModelFactory.createDefaultModel();
if (in == null) {
throw new IllegalArgumentException("Input File: " + " not found");
}
if (out == null) {
throw new IllegalArgumentException("Output File: " + " not found");
}
// read the JSONLD file
modelJena.read(in, null, "JSONLD");
RDFDataMgr.write(out, modelJena, Lang.RDFXML);
LOG.info(" RDF file " + " is written successfully.");
} | [
"public",
"void",
"convertFromJsonld",
"(",
"InputStream",
"in",
",",
"OutputStream",
"out",
")",
"{",
"Model",
"modelJena",
"=",
"ModelFactory",
".",
"createDefaultModel",
"(",
")",
";",
"if",
"(",
"in",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgum... | /*
Convert inputstream in jsonld format to outputsream if owl/rdf format | [
"/",
"*",
"Convert",
"inputstream",
"in",
"jsonld",
"format",
"to",
"outputsream",
"if",
"owl",
"/",
"rdf",
"format"
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/json-converter/src/main/java/org/biopax/paxtools/io/jsonld/JsonldBiopaxConverter.java#L65-L82 |
VoltDB/voltdb | src/frontend/org/voltdb/exportclient/ExportRow.java | ExportRow.decodeNextColumn | private static Object decodeNextColumn(ByteBuffer bb, VoltType columnType)
throws IOException {
Object retval = null;
switch (columnType) {
case TINYINT:
retval = decodeTinyInt(bb);
break;
case SMALLINT:
retval = decodeSmallInt(bb);
break;
case INTEGER:
retval = decodeInteger(bb);
break;
case BIGINT:
retval = decodeBigInt(bb);
break;
case FLOAT:
retval = decodeFloat(bb);
break;
case TIMESTAMP:
retval = decodeTimestamp(bb);
break;
case STRING:
retval = decodeString(bb);
break;
case VARBINARY:
retval = decodeVarbinary(bb);
break;
case DECIMAL:
retval = decodeDecimal(bb);
break;
case GEOGRAPHY_POINT:
retval = decodeGeographyPoint(bb);
break;
case GEOGRAPHY:
retval = decodeGeography(bb);
break;
default:
throw new IOException("Invalid column type: " + columnType);
}
return retval;
} | java | private static Object decodeNextColumn(ByteBuffer bb, VoltType columnType)
throws IOException {
Object retval = null;
switch (columnType) {
case TINYINT:
retval = decodeTinyInt(bb);
break;
case SMALLINT:
retval = decodeSmallInt(bb);
break;
case INTEGER:
retval = decodeInteger(bb);
break;
case BIGINT:
retval = decodeBigInt(bb);
break;
case FLOAT:
retval = decodeFloat(bb);
break;
case TIMESTAMP:
retval = decodeTimestamp(bb);
break;
case STRING:
retval = decodeString(bb);
break;
case VARBINARY:
retval = decodeVarbinary(bb);
break;
case DECIMAL:
retval = decodeDecimal(bb);
break;
case GEOGRAPHY_POINT:
retval = decodeGeographyPoint(bb);
break;
case GEOGRAPHY:
retval = decodeGeography(bb);
break;
default:
throw new IOException("Invalid column type: " + columnType);
}
return retval;
} | [
"private",
"static",
"Object",
"decodeNextColumn",
"(",
"ByteBuffer",
"bb",
",",
"VoltType",
"columnType",
")",
"throws",
"IOException",
"{",
"Object",
"retval",
"=",
"null",
";",
"switch",
"(",
"columnType",
")",
"{",
"case",
"TINYINT",
":",
"retval",
"=",
... | Rather, it decodes the next non-null column in the FastDeserializer | [
"Rather",
"it",
"decodes",
"the",
"next",
"non",
"-",
"null",
"column",
"in",
"the",
"FastDeserializer"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/exportclient/ExportRow.java#L224-L266 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata2/products/SwapAnnuity.java | SwapAnnuity.getSwapAnnuity | public static RandomVariable getSwapAnnuity(Schedule schedule, DiscountCurveInterface discountCurve) {
double evaluationTime = 0.0; // Consider only payment time > 0
return getSwapAnnuity(evaluationTime, schedule, discountCurve, null);
} | java | public static RandomVariable getSwapAnnuity(Schedule schedule, DiscountCurveInterface discountCurve) {
double evaluationTime = 0.0; // Consider only payment time > 0
return getSwapAnnuity(evaluationTime, schedule, discountCurve, null);
} | [
"public",
"static",
"RandomVariable",
"getSwapAnnuity",
"(",
"Schedule",
"schedule",
",",
"DiscountCurveInterface",
"discountCurve",
")",
"{",
"double",
"evaluationTime",
"=",
"0.0",
";",
"// Consider only payment time > 0",
"return",
"getSwapAnnuity",
"(",
"evaluationTime"... | Function to calculate an (idealized) swap annuity for a given schedule and discount curve.
Note: This method will consider evaluationTime being 0, see {@link net.finmath.marketdata2.products.SwapAnnuity#getSwapAnnuity(double, Schedule, DiscountCurveInterface, AnalyticModel)}.
@param schedule The schedule discretization, i.e., the period start and end dates. End dates are considered payment dates and start of the next period.
@param discountCurve The discount curve.
@return The swap annuity. | [
"Function",
"to",
"calculate",
"an",
"(",
"idealized",
")",
"swap",
"annuity",
"for",
"a",
"given",
"schedule",
"and",
"discount",
"curve",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/products/SwapAnnuity.java#L85-L88 |
m-m-m/util | value/src/main/java/net/sf/mmm/util/value/base/StringValueConverterImpl.java | StringValueConverterImpl.convertUnknownValue | protected <V> V convertUnknownValue(String value, Class<V> type, Object valueSource) throws ValueNotSetException, WrongValueTypeException {
// throw new UnknownValueType();
throw new WrongValueTypeException(value, valueSource, type);
} | java | protected <V> V convertUnknownValue(String value, Class<V> type, Object valueSource) throws ValueNotSetException, WrongValueTypeException {
// throw new UnknownValueType();
throw new WrongValueTypeException(value, valueSource, type);
} | [
"protected",
"<",
"V",
">",
"V",
"convertUnknownValue",
"(",
"String",
"value",
",",
"Class",
"<",
"V",
">",
"type",
",",
"Object",
"valueSource",
")",
"throws",
"ValueNotSetException",
",",
"WrongValueTypeException",
"{",
"// throw new UnknownValueType();",
"throw"... | This method converts the given {@link String}-{@code value} to the given {@code type}. It is called from
{@link #convertValue(String, Object, Class, Type)} if the given {@code type} is unknown. This default
implementation simply throws a new {@link WrongValueTypeException}. You can extend this class and
override this method in order to support the conversion for additional types. You should first handle the
conversion for all value types you like. Then for all other types you should delegate to the
{@code super} method implementation.
@param value is the value to convert.
@param type is the type the {@code value} should be converted to.
@param valueSource describes the source of the value. This may be the filename where the value was read
from, an XPath where the value was located in an XML document, etc. It is used in exceptions
thrown if something goes wrong. This will help to find the problem easier.
@param <V> is the type the {@code value} should be converted to.
@return the {@code value} converted to {@code type}.
@throws ValueNotSetException if the given {@code value} is {@code null}.
@throws WrongValueTypeException if the given {@code value} is NOT {@code null} but can NOT be converted
to the given {@code type} (e.g. if {@code value} is "12x" and {@code type} is
{@code Integer.class}). | [
"This",
"method",
"converts",
"the",
"given",
"{",
"@link",
"String",
"}",
"-",
"{",
"@code",
"value",
"}",
"to",
"the",
"given",
"{",
"@code",
"type",
"}",
".",
"It",
"is",
"called",
"from",
"{",
"@link",
"#convertValue",
"(",
"String",
"Object",
"Cla... | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/base/StringValueConverterImpl.java#L202-L206 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/trees/DecisionStump.java | DecisionStump.getGain | protected double getGain(ImpurityScore origScore, ClassificationDataSet source, List<IntList> aSplit)
{
ImpurityScore[] scores = getSplitScores(source, aSplit);
return ImpurityScore.gain(origScore, scores);
} | java | protected double getGain(ImpurityScore origScore, ClassificationDataSet source, List<IntList> aSplit)
{
ImpurityScore[] scores = getSplitScores(source, aSplit);
return ImpurityScore.gain(origScore, scores);
} | [
"protected",
"double",
"getGain",
"(",
"ImpurityScore",
"origScore",
",",
"ClassificationDataSet",
"source",
",",
"List",
"<",
"IntList",
">",
"aSplit",
")",
"{",
"ImpurityScore",
"[",
"]",
"scores",
"=",
"getSplitScores",
"(",
"source",
",",
"aSplit",
")",
";... | From the score for the original set that is being split, this computes
the gain as the improvement in classification from the original split.
@param origScore the score of the unsplit set
@param source
@param aSplit the splitting of the data points
@return the gain score for this split | [
"From",
"the",
"score",
"for",
"the",
"original",
"set",
"that",
"is",
"being",
"split",
"this",
"computes",
"the",
"gain",
"as",
"the",
"improvement",
"in",
"classification",
"from",
"the",
"original",
"split",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/trees/DecisionStump.java#L233-L239 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/typehandling/NumberMath.java | NumberMath.rightShift | public static Number rightShift(Number left, Number right) {
if (isFloatingPoint(right) || isBigDecimal(right)) {
throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied");
}
return getMath(left).rightShiftImpl(left, right);
} | java | public static Number rightShift(Number left, Number right) {
if (isFloatingPoint(right) || isBigDecimal(right)) {
throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied");
}
return getMath(left).rightShiftImpl(left, right);
} | [
"public",
"static",
"Number",
"rightShift",
"(",
"Number",
"left",
",",
"Number",
"right",
")",
"{",
"if",
"(",
"isFloatingPoint",
"(",
"right",
")",
"||",
"isBigDecimal",
"(",
"right",
")",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"... | For this operation, consider the operands independently. Throw an exception if the right operand
(shift distance) is not an integral type. For the left operand (shift value) also require an integral
type, but do NOT promote from Integer to Long. This is consistent with Java, and makes sense for the
shift operators. | [
"For",
"this",
"operation",
"consider",
"the",
"operands",
"independently",
".",
"Throw",
"an",
"exception",
"if",
"the",
"right",
"operand",
"(",
"shift",
"distance",
")",
"is",
"not",
"an",
"integral",
"type",
".",
"For",
"the",
"left",
"operand",
"(",
"... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/typehandling/NumberMath.java#L110-L115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.