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 |
|---|---|---|---|---|---|---|---|---|---|---|
callstats-io/callstats.java | callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsBridgeKeepAliveManager.java | CallStatsBridgeKeepAliveManager.sendKeepAliveBridgeMessage | private void sendKeepAliveBridgeMessage(int appId, String bridgeId, String token,
final CallStatsHttp2Client httpClient) {
long apiTS = System.currentTimeMillis();
BridgeKeepAliveMessage message = new BridgeKeepAliveMessage(bridgeId, apiTS);
String requestMessageString = gson.toJson(message);
httpClient.sendBridgeAlive(keepAliveEventUrl, token, requestMessageString,
new CallStatsHttp2ResponseListener() {
public void onResponse(Response response) {
int responseStatus = response.code();
BridgeKeepAliveResponse keepAliveResponse;
try {
String responseString = response.body().string();
keepAliveResponse = gson.fromJson(responseString, BridgeKeepAliveResponse.class);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (JsonSyntaxException e) {
logger.error("Json Syntax Exception " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
}
httpClient.setDisrupted(false);
if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
keepAliveStatusListener.onSuccess();
} else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) {
stopKeepAliveSender();
keepAliveStatusListener.onKeepAliveError(CallStatsErrors.AUTH_ERROR,
keepAliveResponse.getMsg());
} else {
httpClient.setDisrupted(true);
}
}
public void onFailure(Exception e) {
logger.info("Response exception " + e.toString());
httpClient.setDisrupted(true);
}
});
} | java | private void sendKeepAliveBridgeMessage(int appId, String bridgeId, String token,
final CallStatsHttp2Client httpClient) {
long apiTS = System.currentTimeMillis();
BridgeKeepAliveMessage message = new BridgeKeepAliveMessage(bridgeId, apiTS);
String requestMessageString = gson.toJson(message);
httpClient.sendBridgeAlive(keepAliveEventUrl, token, requestMessageString,
new CallStatsHttp2ResponseListener() {
public void onResponse(Response response) {
int responseStatus = response.code();
BridgeKeepAliveResponse keepAliveResponse;
try {
String responseString = response.body().string();
keepAliveResponse = gson.fromJson(responseString, BridgeKeepAliveResponse.class);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (JsonSyntaxException e) {
logger.error("Json Syntax Exception " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
}
httpClient.setDisrupted(false);
if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
keepAliveStatusListener.onSuccess();
} else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) {
stopKeepAliveSender();
keepAliveStatusListener.onKeepAliveError(CallStatsErrors.AUTH_ERROR,
keepAliveResponse.getMsg());
} else {
httpClient.setDisrupted(true);
}
}
public void onFailure(Exception e) {
logger.info("Response exception " + e.toString());
httpClient.setDisrupted(true);
}
});
} | [
"private",
"void",
"sendKeepAliveBridgeMessage",
"(",
"int",
"appId",
",",
"String",
"bridgeId",
",",
"String",
"token",
",",
"final",
"CallStatsHttp2Client",
"httpClient",
")",
"{",
"long",
"apiTS",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"Bridg... | Send keep alive bridge message.
@param appId the app id
@param bridgeId the bridge id
@param token the token
@param httpClient the http client | [
"Send",
"keep",
"alive",
"bridge",
"message",
"."
] | train | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsBridgeKeepAliveManager.java#L124-L164 |
banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/model/handler/HandlerMethodMetaArgsFactory.java | HandlerMethodMetaArgsFactory.createCreateMethod | public MethodMetaArgs createCreateMethod(HandlerMetaDef handlerMetaDef, EventModel em) {
String p_methodName = handlerMetaDef.getCreateMethod();
if (p_methodName == null) {
Debug.logError("[JdonFramework] not configure the createMethod parameter: <createMethod name=XXXXX /> ", module);
}
return createCRUDMethodMetaArgs(p_methodName, em);
} | java | public MethodMetaArgs createCreateMethod(HandlerMetaDef handlerMetaDef, EventModel em) {
String p_methodName = handlerMetaDef.getCreateMethod();
if (p_methodName == null) {
Debug.logError("[JdonFramework] not configure the createMethod parameter: <createMethod name=XXXXX /> ", module);
}
return createCRUDMethodMetaArgs(p_methodName, em);
} | [
"public",
"MethodMetaArgs",
"createCreateMethod",
"(",
"HandlerMetaDef",
"handlerMetaDef",
",",
"EventModel",
"em",
")",
"{",
"String",
"p_methodName",
"=",
"handlerMetaDef",
".",
"getCreateMethod",
"(",
")",
";",
"if",
"(",
"p_methodName",
"==",
"null",
")",
"{",... | create insert/create method the service/s method parameter type must be
EventModel type;
@param handlerMetaDef
@param em
@return MethodMetaArgs instance | [
"create",
"insert",
"/",
"create",
"method",
"the",
"service",
"/",
"s",
"method",
"parameter",
"type",
"must",
"be",
"EventModel",
"type",
";"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/model/handler/HandlerMethodMetaArgsFactory.java#L82-L89 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/transform/pyramid/PyramidOps.java | PyramidOps.scaleImageUp | public static <T extends ImageGray<T>>
void scaleImageUp(T input , T output , int scale, InterpolatePixelS<T> interp ) {
if( scale <= 1 )
throw new IllegalArgumentException("Scale must be >= 2");
if( input instanceof GrayF32) {
ImplPyramidOps.scaleImageUp((GrayF32)input,(GrayF32)output,scale,(InterpolatePixelS)interp);
} else if( input instanceof GrayU8) {
ImplPyramidOps.scaleImageUp((GrayU8)input,(GrayU8)output,scale,(InterpolatePixelS)interp);
} else {
throw new IllegalArgumentException("Image type not yet supported");
}
} | java | public static <T extends ImageGray<T>>
void scaleImageUp(T input , T output , int scale, InterpolatePixelS<T> interp ) {
if( scale <= 1 )
throw new IllegalArgumentException("Scale must be >= 2");
if( input instanceof GrayF32) {
ImplPyramidOps.scaleImageUp((GrayF32)input,(GrayF32)output,scale,(InterpolatePixelS)interp);
} else if( input instanceof GrayU8) {
ImplPyramidOps.scaleImageUp((GrayU8)input,(GrayU8)output,scale,(InterpolatePixelS)interp);
} else {
throw new IllegalArgumentException("Image type not yet supported");
}
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
">",
"void",
"scaleImageUp",
"(",
"T",
"input",
",",
"T",
"output",
",",
"int",
"scale",
",",
"InterpolatePixelS",
"<",
"T",
">",
"interp",
")",
"{",
"if",
"(",
"scale",
"<=",
"1",
... | Scales an image up using interpolation
@param scale How much larger the output image will be. | [
"Scales",
"an",
"image",
"up",
"using",
"interpolation"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/pyramid/PyramidOps.java#L168-L179 |
jeremylong/DependencyCheck | utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java | Downloader.fetchFile | public void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException {
try (HttpResourceConnection conn = new HttpResourceConnection(settings, useProxy);
OutputStream out = new FileOutputStream(outputPath)) {
final InputStream in = conn.fetch(url);
IOUtils.copy(in, out);
} catch (IOException ex) {
final String msg = format("Download failed, unable to copy '%s' to '%s'", url.toString(), outputPath.getAbsolutePath());
throw new DownloadFailedException(msg, ex);
}
} | java | public void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException {
try (HttpResourceConnection conn = new HttpResourceConnection(settings, useProxy);
OutputStream out = new FileOutputStream(outputPath)) {
final InputStream in = conn.fetch(url);
IOUtils.copy(in, out);
} catch (IOException ex) {
final String msg = format("Download failed, unable to copy '%s' to '%s'", url.toString(), outputPath.getAbsolutePath());
throw new DownloadFailedException(msg, ex);
}
} | [
"public",
"void",
"fetchFile",
"(",
"URL",
"url",
",",
"File",
"outputPath",
",",
"boolean",
"useProxy",
")",
"throws",
"DownloadFailedException",
"{",
"try",
"(",
"HttpResourceConnection",
"conn",
"=",
"new",
"HttpResourceConnection",
"(",
"settings",
",",
"usePr... | Retrieves a file from a given URL and saves it to the outputPath.
@param url the URL of the file to download
@param outputPath the path to the save the file to
@param useProxy whether to use the configured proxy when downloading
files
@throws org.owasp.dependencycheck.utils.DownloadFailedException is thrown
if there is an error downloading the file | [
"Retrieves",
"a",
"file",
"from",
"a",
"given",
"URL",
"and",
"saves",
"it",
"to",
"the",
"outputPath",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java#L79-L88 |
csc19601128/Phynixx | phynixx/phynixx-logger/src/main/java/org/csc/phynixx/loggersystem/logrecord/PhynixxXADataRecorder.java | PhynixxXADataRecorder.openRecorderForWrite | static PhynixxXADataRecorder openRecorderForWrite(long messageSequenceId, XADataLogger xaDataLogger, IXADataRecorderLifecycleListener dataRecorderLifycycleListner) {
PhynixxXADataRecorder dataRecorder = new PhynixxXADataRecorder(messageSequenceId, xaDataLogger, dataRecorderLifycycleListner);
try {
dataRecorder.dataLogger.prepareForWrite(dataRecorder.getXADataRecorderId());
return dataRecorder;
} catch (Exception e) {
throw new DelegatedRuntimeException(e);
}
} | java | static PhynixxXADataRecorder openRecorderForWrite(long messageSequenceId, XADataLogger xaDataLogger, IXADataRecorderLifecycleListener dataRecorderLifycycleListner) {
PhynixxXADataRecorder dataRecorder = new PhynixxXADataRecorder(messageSequenceId, xaDataLogger, dataRecorderLifycycleListner);
try {
dataRecorder.dataLogger.prepareForWrite(dataRecorder.getXADataRecorderId());
return dataRecorder;
} catch (Exception e) {
throw new DelegatedRuntimeException(e);
}
} | [
"static",
"PhynixxXADataRecorder",
"openRecorderForWrite",
"(",
"long",
"messageSequenceId",
",",
"XADataLogger",
"xaDataLogger",
",",
"IXADataRecorderLifecycleListener",
"dataRecorderLifycycleListner",
")",
"{",
"PhynixxXADataRecorder",
"dataRecorder",
"=",
"new",
"PhynixxXAData... | opens an Recorder for read. If no recorder with the given ID exists recorder with no data is returned
@param messageSequenceId
@param xaDataLogger
@return
@throws IOException
@throws InterruptedException | [
"opens",
"an",
"Recorder",
"for",
"read",
".",
"If",
"no",
"recorder",
"with",
"the",
"given",
"ID",
"exists",
"recorder",
"with",
"no",
"data",
"is",
"returned"
] | train | https://github.com/csc19601128/Phynixx/blob/a26c03bc229a8882c647799834115bec6bdc0ac8/phynixx/phynixx-logger/src/main/java/org/csc/phynixx/loggersystem/logrecord/PhynixxXADataRecorder.java#L109-L117 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowTriggersInner.java | WorkflowTriggersInner.getAsync | public Observable<WorkflowTriggerInner> getAsync(String resourceGroupName, String workflowName, String triggerName) {
return getWithServiceResponseAsync(resourceGroupName, workflowName, triggerName).map(new Func1<ServiceResponse<WorkflowTriggerInner>, WorkflowTriggerInner>() {
@Override
public WorkflowTriggerInner call(ServiceResponse<WorkflowTriggerInner> response) {
return response.body();
}
});
} | java | public Observable<WorkflowTriggerInner> getAsync(String resourceGroupName, String workflowName, String triggerName) {
return getWithServiceResponseAsync(resourceGroupName, workflowName, triggerName).map(new Func1<ServiceResponse<WorkflowTriggerInner>, WorkflowTriggerInner>() {
@Override
public WorkflowTriggerInner call(ServiceResponse<WorkflowTriggerInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"WorkflowTriggerInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"workflowName",
",",
"String",
"triggerName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"workflowName",
",",
... | Gets a workflow trigger.
@param resourceGroupName The resource group name.
@param workflowName The workflow name.
@param triggerName The workflow trigger name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the WorkflowTriggerInner object | [
"Gets",
"a",
"workflow",
"trigger",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowTriggersInner.java#L388-L395 |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getHTMLOutputStream | protected final OutputStream getHTMLOutputStream(WebSiteRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
String[] headers=getAdditionalHeaders(req);
if(headers!=null) {
int len=headers.length;
for(int c=0; c<len; c+=2) resp.setHeader(headers[c], headers[c+1]);
}
return resp.getOutputStream();
} | java | protected final OutputStream getHTMLOutputStream(WebSiteRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
String[] headers=getAdditionalHeaders(req);
if(headers!=null) {
int len=headers.length;
for(int c=0; c<len; c+=2) resp.setHeader(headers[c], headers[c+1]);
}
return resp.getOutputStream();
} | [
"protected",
"final",
"OutputStream",
"getHTMLOutputStream",
"(",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"IOException",
"{",
"resp",
".",
"setContentType",
"(",
"\"text/html\"",
")",
";",
"resp",
".",
"setCharacterEncoding",
"(",
... | Sets the content type, encoding to UTF-8, sets the additional headers, then returns the <code>OutputStream</code>.
@see #getAdditionalHeaders | [
"Sets",
"the",
"content",
"type",
"encoding",
"to",
"UTF",
"-",
"8",
"sets",
"the",
"additional",
"headers",
"then",
"returns",
"the",
"<code",
">",
"OutputStream<",
"/",
"code",
">",
"."
] | train | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L612-L621 |
alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/blobstore/ClientBlobStore.java | ClientBlobStore.setBlobMeta | public final void setBlobMeta(String key, SettableBlobMeta meta) throws AuthorizationException, KeyNotFoundException {
setBlobMetaToExtend(key, meta);
} | java | public final void setBlobMeta(String key, SettableBlobMeta meta) throws AuthorizationException, KeyNotFoundException {
setBlobMetaToExtend(key, meta);
} | [
"public",
"final",
"void",
"setBlobMeta",
"(",
"String",
"key",
",",
"SettableBlobMeta",
"meta",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
"{",
"setBlobMetaToExtend",
"(",
"key",
",",
"meta",
")",
";",
"}"
] | Client facing API to set the metadata for a blob.
@param key blob key name.
@param meta contains ACL information.
@throws AuthorizationException
@throws KeyNotFoundException | [
"Client",
"facing",
"API",
"to",
"set",
"the",
"metadata",
"for",
"a",
"blob",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/blobstore/ClientBlobStore.java#L168-L170 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/builder/CompareToBuilder.java | CompareToBuilder.reflectionCompare | public static int reflectionCompare(final Object lhs, final Object rhs, final boolean compareTransients) {
return reflectionCompare(lhs, rhs, compareTransients, null);
} | java | public static int reflectionCompare(final Object lhs, final Object rhs, final boolean compareTransients) {
return reflectionCompare(lhs, rhs, compareTransients, null);
} | [
"public",
"static",
"int",
"reflectionCompare",
"(",
"final",
"Object",
"lhs",
",",
"final",
"Object",
"rhs",
",",
"final",
"boolean",
"compareTransients",
")",
"{",
"return",
"reflectionCompare",
"(",
"lhs",
",",
"rhs",
",",
"compareTransients",
",",
"null",
... | <p>Compares two <code>Object</code>s via reflection.</p>
<p>Fields can be private, thus <code>AccessibleObject.setAccessible</code>
is used to bypass normal access control checks. This will fail under a
security manager unless the appropriate permissions are set.</p>
<ul>
<li>Static fields will not be compared</li>
<li>If <code>compareTransients</code> is <code>true</code>,
compares transient members. Otherwise ignores them, as they
are likely derived fields.</li>
<li>Superclass fields will be compared</li>
</ul>
<p>If both <code>lhs</code> and <code>rhs</code> are <code>null</code>,
they are considered equal.</p>
@param lhs left-hand object
@param rhs right-hand object
@param compareTransients whether to compare transient fields
@return a negative integer, zero, or a positive integer as <code>lhs</code>
is less than, equal to, or greater than <code>rhs</code>
@throws NullPointerException if either <code>lhs</code> or <code>rhs</code>
(but not both) is <code>null</code>
@throws ClassCastException if <code>rhs</code> is not assignment-compatible
with <code>lhs</code> | [
"<p",
">",
"Compares",
"two",
"<code",
">",
"Object<",
"/",
"code",
">",
"s",
"via",
"reflection",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/builder/CompareToBuilder.java#L120-L122 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cp/internal/datastructures/countdownlatch/RaftCountDownLatch.java | RaftCountDownLatch.countDown | Tuple2<Integer, Collection<AwaitInvocationKey>> countDown(UUID invocationUuid, int expectedRound) {
if (expectedRound > round) {
throw new IllegalArgumentException("expected round: " + expectedRound + ", actual round: " + round);
}
if (expectedRound < round) {
Collection<AwaitInvocationKey> c = Collections.emptyList();
return Tuple2.of(0, c);
}
countDownUids.add(invocationUuid);
int remaining = getRemainingCount();
if (remaining > 0) {
Collection<AwaitInvocationKey> c = Collections.emptyList();
return Tuple2.of(remaining, c);
}
Collection<AwaitInvocationKey> w = getAllWaitKeys();
clearWaitKeys();
return Tuple2.of(0, w);
} | java | Tuple2<Integer, Collection<AwaitInvocationKey>> countDown(UUID invocationUuid, int expectedRound) {
if (expectedRound > round) {
throw new IllegalArgumentException("expected round: " + expectedRound + ", actual round: " + round);
}
if (expectedRound < round) {
Collection<AwaitInvocationKey> c = Collections.emptyList();
return Tuple2.of(0, c);
}
countDownUids.add(invocationUuid);
int remaining = getRemainingCount();
if (remaining > 0) {
Collection<AwaitInvocationKey> c = Collections.emptyList();
return Tuple2.of(remaining, c);
}
Collection<AwaitInvocationKey> w = getAllWaitKeys();
clearWaitKeys();
return Tuple2.of(0, w);
} | [
"Tuple2",
"<",
"Integer",
",",
"Collection",
"<",
"AwaitInvocationKey",
">",
">",
"countDown",
"(",
"UUID",
"invocationUuid",
",",
"int",
"expectedRound",
")",
"{",
"if",
"(",
"expectedRound",
">",
"round",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
... | Reduces remaining count of the latch.
If the expected round is smaller than the current round, it is either
a retry or a countDown() request sent before re-initialization
of the latch. In this case, this count down request is ignored. | [
"Reduces",
"remaining",
"count",
"of",
"the",
"latch",
".",
"If",
"the",
"expected",
"round",
"is",
"smaller",
"than",
"the",
"current",
"round",
"it",
"is",
"either",
"a",
"retry",
"or",
"a",
"countDown",
"()",
"request",
"sent",
"before",
"re",
"-",
"i... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/datastructures/countdownlatch/RaftCountDownLatch.java#L61-L82 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/MethodUtils.java | MethodUtils.getAccessibleMethod | public static Method getAccessibleMethod(Class<?> clazz, String methodName, Class<?> paramType) {
Class<?>[] paramTypes = { paramType };
return getAccessibleMethod(clazz, methodName, paramTypes);
} | java | public static Method getAccessibleMethod(Class<?> clazz, String methodName, Class<?> paramType) {
Class<?>[] paramTypes = { paramType };
return getAccessibleMethod(clazz, methodName, paramTypes);
} | [
"public",
"static",
"Method",
"getAccessibleMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"paramType",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
"=",
"{",
"paramType",
"}",
";",... | <p>Return an accessible method (that is, one that can be invoked via
reflection) with given name and a single parameter. If no such method
can be found, return {@code null}.
Basically, a convenience wrapper that constructs a {@code Class}
array for you.</p>
@param clazz get method from this class
@param methodName get method with this name
@param paramType taking this type of parameter
@return the accessible method | [
"<p",
">",
"Return",
"an",
"accessible",
"method",
"(",
"that",
"is",
"one",
"that",
"can",
"be",
"invoked",
"via",
"reflection",
")",
"with",
"given",
"name",
"and",
"a",
"single",
"parameter",
".",
"If",
"no",
"such",
"method",
"can",
"be",
"found",
... | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/MethodUtils.java#L623-L626 |
opensourceBIM/BIMserver | BimServer/src/org/bimserver/GenericGeometryGenerator.java | GenericGeometryGenerator.getPlaneAngle | private static double getPlaneAngle(float[] v1, float[] v2, float[] v3, float[] u1, float[] u2, float[] u3) {
float[] cross1 = Vector.crossProduct(new float[] { v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2] }, new float[] { v3[0] - v1[0], v3[1] - v1[1], v3[2] - v1[2] });
float[] cross2 = Vector.crossProduct(new float[] { u2[0] - u1[0], u2[1] - u1[1], u2[2] - u1[2] }, new float[] { u3[0] - u1[0], u3[1] - u1[1], u3[2] - u1[2] });
float num = Vector.dot(cross1, cross2);
float den = Vector.length(cross1) * Vector.length(cross2);
float a = num / den;
if (a > 1) {
a = 1;
}
if (a < -1) {
a = -1;
}
double result = Math.acos(a);
return result;
} | java | private static double getPlaneAngle(float[] v1, float[] v2, float[] v3, float[] u1, float[] u2, float[] u3) {
float[] cross1 = Vector.crossProduct(new float[] { v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2] }, new float[] { v3[0] - v1[0], v3[1] - v1[1], v3[2] - v1[2] });
float[] cross2 = Vector.crossProduct(new float[] { u2[0] - u1[0], u2[1] - u1[1], u2[2] - u1[2] }, new float[] { u3[0] - u1[0], u3[1] - u1[1], u3[2] - u1[2] });
float num = Vector.dot(cross1, cross2);
float den = Vector.length(cross1) * Vector.length(cross2);
float a = num / den;
if (a > 1) {
a = 1;
}
if (a < -1) {
a = -1;
}
double result = Math.acos(a);
return result;
} | [
"private",
"static",
"double",
"getPlaneAngle",
"(",
"float",
"[",
"]",
"v1",
",",
"float",
"[",
"]",
"v2",
",",
"float",
"[",
"]",
"v3",
",",
"float",
"[",
"]",
"u1",
",",
"float",
"[",
"]",
"u2",
",",
"float",
"[",
"]",
"u3",
")",
"{",
"float... | Get the angle in radians between two planes
@param v1
@param v2
@param v3
@param u1
@param u2
@param u3
@return | [
"Get",
"the",
"angle",
"in",
"radians",
"between",
"two",
"planes"
] | train | https://github.com/opensourceBIM/BIMserver/blob/116803c3047d1b32217366757cee1bb3880fda63/BimServer/src/org/bimserver/GenericGeometryGenerator.java#L162-L179 |
kiegroup/jbpm | jbpm-flow/src/main/java/org/jbpm/process/core/event/NonAcceptingEventTypeFilter.java | NonAcceptingEventTypeFilter.acceptsEvent | @Override
public boolean acceptsEvent(String type, Object event, Function<String, String> resolver) {
return false;
} | java | @Override
public boolean acceptsEvent(String type, Object event, Function<String, String> resolver) {
return false;
} | [
"@",
"Override",
"public",
"boolean",
"acceptsEvent",
"(",
"String",
"type",
",",
"Object",
"event",
",",
"Function",
"<",
"String",
",",
"String",
">",
"resolver",
")",
"{",
"return",
"false",
";",
"}"
] | Nodes that use this event filter should never be triggered by this event | [
"Nodes",
"that",
"use",
"this",
"event",
"filter",
"should",
"never",
"be",
"triggered",
"by",
"this",
"event"
] | train | https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-flow/src/main/java/org/jbpm/process/core/event/NonAcceptingEventTypeFilter.java#L37-L40 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_volume_volumeId_upsize_POST | public OvhVolume project_serviceName_volume_volumeId_upsize_POST(String serviceName, String volumeId, Long size) throws IOException {
String qPath = "/cloud/project/{serviceName}/volume/{volumeId}/upsize";
StringBuilder sb = path(qPath, serviceName, volumeId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "size", size);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhVolume.class);
} | java | public OvhVolume project_serviceName_volume_volumeId_upsize_POST(String serviceName, String volumeId, Long size) throws IOException {
String qPath = "/cloud/project/{serviceName}/volume/{volumeId}/upsize";
StringBuilder sb = path(qPath, serviceName, volumeId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "size", size);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhVolume.class);
} | [
"public",
"OvhVolume",
"project_serviceName_volume_volumeId_upsize_POST",
"(",
"String",
"serviceName",
",",
"String",
"volumeId",
",",
"Long",
"size",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/volume/{volumeId}/upsize\"",
";",... | Extend a volume
REST: POST /cloud/project/{serviceName}/volume/{volumeId}/upsize
@param serviceName [required] Service name
@param size [required] New volume size (in GiB) (must be greater than current one)
@param volumeId [required] Volume id | [
"Extend",
"a",
"volume"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1090-L1097 |
ixa-ehu/ixa-pipe-ml | src/main/java/eus/ixa/ixa/pipe/ml/document/features/DocumentFeatureAggregator.java | DocumentFeatureAggregator.createFeatures | public void createFeatures(List<String> features, String[] tokens) {
for (DocumentFeatureGenerator generator : generators) {
generator.createFeatures(features, tokens);
}
} | java | public void createFeatures(List<String> features, String[] tokens) {
for (DocumentFeatureGenerator generator : generators) {
generator.createFeatures(features, tokens);
}
} | [
"public",
"void",
"createFeatures",
"(",
"List",
"<",
"String",
">",
"features",
",",
"String",
"[",
"]",
"tokens",
")",
"{",
"for",
"(",
"DocumentFeatureGenerator",
"generator",
":",
"generators",
")",
"{",
"generator",
".",
"createFeatures",
"(",
"features",... | Calls the {@link DocumentFeatureGenerator#createFeatures(List, String[])}
method on all aggregated {@link DocumentFeatureGenerator}s. | [
"Calls",
"the",
"{"
] | train | https://github.com/ixa-ehu/ixa-pipe-ml/blob/c817fa1e40e96ed15fc79d22c3a7c25f1a40d172/src/main/java/eus/ixa/ixa/pipe/ml/document/features/DocumentFeatureAggregator.java#L75-L80 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/util/POIUtils.java | POIUtils.getCellFormatPattern | public static String getCellFormatPattern(final Cell cell, final CellFormatter cellFormatter) {
if(cell == null) {
return "";
}
String pattern = cellFormatter.getPattern(cell);
if(pattern.equalsIgnoreCase("general")) {
return "";
}
return pattern;
} | java | public static String getCellFormatPattern(final Cell cell, final CellFormatter cellFormatter) {
if(cell == null) {
return "";
}
String pattern = cellFormatter.getPattern(cell);
if(pattern.equalsIgnoreCase("general")) {
return "";
}
return pattern;
} | [
"public",
"static",
"String",
"getCellFormatPattern",
"(",
"final",
"Cell",
"cell",
",",
"final",
"CellFormatter",
"cellFormatter",
")",
"{",
"if",
"(",
"cell",
"==",
"null",
")",
"{",
"return",
"\"\"",
";",
"}",
"String",
"pattern",
"=",
"cellFormatter",
".... | セルに設定されている書式を取得する。
@since 1.1
@param cell セルのインスタンス。
@param cellFormatter セルのフォーマッタ
@return 書式が設定されていない場合は、空文字を返す。
cellがnullの場合も空文字を返す。
標準の書式の場合も空文字を返す。 | [
"セルに設定されている書式を取得する。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/POIUtils.java#L311-L323 |
trellis-ldp/trellis | auth/oauth/src/main/java/org/trellisldp/auth/oauth/OAuthUtils.java | OAuthUtils.buildRSAPublicKey | public static Optional<Key> buildRSAPublicKey(final String keyType, final BigInteger modulus,
final BigInteger exponent) {
try {
return of(KeyFactory.getInstance(keyType).generatePublic(new RSAPublicKeySpec(modulus, exponent)));
} catch (final NoSuchAlgorithmException | InvalidKeySpecException ex) {
LOGGER.error("Error generating RSA Key from JWKS entry", ex);
}
return empty();
} | java | public static Optional<Key> buildRSAPublicKey(final String keyType, final BigInteger modulus,
final BigInteger exponent) {
try {
return of(KeyFactory.getInstance(keyType).generatePublic(new RSAPublicKeySpec(modulus, exponent)));
} catch (final NoSuchAlgorithmException | InvalidKeySpecException ex) {
LOGGER.error("Error generating RSA Key from JWKS entry", ex);
}
return empty();
} | [
"public",
"static",
"Optional",
"<",
"Key",
">",
"buildRSAPublicKey",
"(",
"final",
"String",
"keyType",
",",
"final",
"BigInteger",
"modulus",
",",
"final",
"BigInteger",
"exponent",
")",
"{",
"try",
"{",
"return",
"of",
"(",
"KeyFactory",
".",
"getInstance",... | Build an RSA public key.
@param keyType the algorithm (should be "RSA")
@param modulus the modulus
@param exponent the exponent
@return an RSA public key, if one could be successfully generated | [
"Build",
"an",
"RSA",
"public",
"key",
"."
] | train | https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/auth/oauth/src/main/java/org/trellisldp/auth/oauth/OAuthUtils.java#L110-L118 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/slim/ValuesFileFixture.java | ValuesFileFixture.createContainingBase64Value | public String createContainingBase64Value(String basename, String key) {
String file;
Object value = value(key);
if (value == null) {
throw new SlimFixtureException(false, "No value for key: " + key);
} else if (value instanceof String) {
file = createFileFromBase64(basename, (String) value);
} else {
throw new SlimFixtureException(false, "Value for key: " + key + " is not a String, but: " + value);
}
return file;
} | java | public String createContainingBase64Value(String basename, String key) {
String file;
Object value = value(key);
if (value == null) {
throw new SlimFixtureException(false, "No value for key: " + key);
} else if (value instanceof String) {
file = createFileFromBase64(basename, (String) value);
} else {
throw new SlimFixtureException(false, "Value for key: " + key + " is not a String, but: " + value);
}
return file;
} | [
"public",
"String",
"createContainingBase64Value",
"(",
"String",
"basename",
",",
"String",
"key",
")",
"{",
"String",
"file",
";",
"Object",
"value",
"=",
"value",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"SlimF... | Saves content of a key's value as file in the files section.
@param basename filename to use.
@param key key to get value from.
@return file created. | [
"Saves",
"content",
"of",
"a",
"key",
"s",
"value",
"as",
"file",
"in",
"the",
"files",
"section",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/ValuesFileFixture.java#L63-L74 |
jimmoores/quandl4j | core/src/main/java/com/jimmoores/quandl/util/ArgumentChecker.java | ArgumentChecker.notNullOrEmpty | public static <E> void notNullOrEmpty(final E[] argument, final String name) {
if (argument == null) {
s_logger.error("Argument {} was null", name);
throw new QuandlRuntimeException("Value " + name + " was null");
} else if (argument.length == 0) {
s_logger.error("Argument {} was empty array", name);
throw new QuandlRuntimeException("Value " + name + " was empty array");
}
} | java | public static <E> void notNullOrEmpty(final E[] argument, final String name) {
if (argument == null) {
s_logger.error("Argument {} was null", name);
throw new QuandlRuntimeException("Value " + name + " was null");
} else if (argument.length == 0) {
s_logger.error("Argument {} was empty array", name);
throw new QuandlRuntimeException("Value " + name + " was empty array");
}
} | [
"public",
"static",
"<",
"E",
">",
"void",
"notNullOrEmpty",
"(",
"final",
"E",
"[",
"]",
"argument",
",",
"final",
"String",
"name",
")",
"{",
"if",
"(",
"argument",
"==",
"null",
")",
"{",
"s_logger",
".",
"error",
"(",
"\"Argument {} was null\"",
",",... | Throws an exception if the array argument is not null or empty.
@param <E> type of array
@param argument the object to check
@param name the name of the parameter | [
"Throws",
"an",
"exception",
"if",
"the",
"array",
"argument",
"is",
"not",
"null",
"or",
"empty",
"."
] | train | https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/core/src/main/java/com/jimmoores/quandl/util/ArgumentChecker.java#L37-L45 |
mapbox/mapbox-navigation-android | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationService.java | NavigationService.onStartCommand | @Override
public int onStartCommand(Intent intent, int flags, int startId) {
NavigationTelemetry.getInstance().initializeLifecycleMonitor(getApplication());
return START_STICKY;
} | java | @Override
public int onStartCommand(Intent intent, int flags, int startId) {
NavigationTelemetry.getInstance().initializeLifecycleMonitor(getApplication());
return START_STICKY;
} | [
"@",
"Override",
"public",
"int",
"onStartCommand",
"(",
"Intent",
"intent",
",",
"int",
"flags",
",",
"int",
"startId",
")",
"{",
"NavigationTelemetry",
".",
"getInstance",
"(",
")",
".",
"initializeLifecycleMonitor",
"(",
"getApplication",
"(",
")",
")",
";"... | Only should be called once since we want the service to continue running until the navigation
session ends. | [
"Only",
"should",
"be",
"called",
"once",
"since",
"we",
"want",
"the",
"service",
"to",
"continue",
"running",
"until",
"the",
"navigation",
"session",
"ends",
"."
] | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/NavigationService.java#L49-L53 |
GenesysPureEngage/authentication-client-java | src/main/java/com/genesys/authentication/AuthorizationApi.java | AuthorizationApi.authorize | public void authorize(Map<String, String> queryParams, String authorization) throws AuthenticationApiException {
HttpUrl.Builder httpBuilder = HttpUrl.parse(this.client.getBasePath() + "/oauth/authorize").newBuilder();
if (queryParams != null) {
for (Map.Entry<String, String> param : queryParams.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(), param.getValue());
}
}
Headers.Builder headerBuilder = new Headers.Builder();
if (authorization != null) {
headerBuilder.add("Authorization", authorization);
}
Request request = new Request.Builder()
.url(httpBuilder.build())
.headers(headerBuilder.build())
.get()
.build();
try {
this.client.getHttpClient().newCall(request).execute();
} catch (IOException e) {
throw new AuthenticationApiException("Authorization error", e);
}
} | java | public void authorize(Map<String, String> queryParams, String authorization) throws AuthenticationApiException {
HttpUrl.Builder httpBuilder = HttpUrl.parse(this.client.getBasePath() + "/oauth/authorize").newBuilder();
if (queryParams != null) {
for (Map.Entry<String, String> param : queryParams.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(), param.getValue());
}
}
Headers.Builder headerBuilder = new Headers.Builder();
if (authorization != null) {
headerBuilder.add("Authorization", authorization);
}
Request request = new Request.Builder()
.url(httpBuilder.build())
.headers(headerBuilder.build())
.get()
.build();
try {
this.client.getHttpClient().newCall(request).execute();
} catch (IOException e) {
throw new AuthenticationApiException("Authorization error", e);
}
} | [
"public",
"void",
"authorize",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"String",
"authorization",
")",
"throws",
"AuthenticationApiException",
"{",
"HttpUrl",
".",
"Builder",
"httpBuilder",
"=",
"HttpUrl",
".",
"parse",
"(",
"this",
... | Perform authorization
Perform authorization based on the code grant type &mdash; either Authorization Code Grant or Implicit Grant. For more information, see [Authorization Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1). **Note:** For the optional **scope** parameter, the Authentication API supports only the `*` value.
@param queryParams The form parameters, can be created via static methods
@param authorization Basic authorization. For example: 'Authorization: Basic Y3...MQ==' (optional)
@throws AuthenticationApiException if the call is unsuccessful. | [
"Perform",
"authorization",
"Perform",
"authorization",
"based",
"on",
"the",
"code",
"grant",
"type",
"&",
";",
"mdash",
";",
"either",
"Authorization",
"Code",
"Grant",
"or",
"Implicit",
"Grant",
".",
"For",
"more",
"information",
"see",
"[",
"Authorization... | train | https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/authentication/AuthorizationApi.java#L57-L78 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java | Shape.getDouble | public static double getDouble(INDArray arr, int[] indices) {
long offset = getOffset(arr.shapeInfo(), ArrayUtil.toLongArray(indices));
return arr.data().getDouble(offset);
} | java | public static double getDouble(INDArray arr, int[] indices) {
long offset = getOffset(arr.shapeInfo(), ArrayUtil.toLongArray(indices));
return arr.data().getDouble(offset);
} | [
"public",
"static",
"double",
"getDouble",
"(",
"INDArray",
"arr",
",",
"int",
"[",
"]",
"indices",
")",
"{",
"long",
"offset",
"=",
"getOffset",
"(",
"arr",
".",
"shapeInfo",
"(",
")",
",",
"ArrayUtil",
".",
"toLongArray",
"(",
"indices",
")",
")",
";... | Get a double based on the array and given indices
@param arr the array to retrieve the double from
@param indices the indices to iterate over
@return the double at the specified index | [
"Get",
"a",
"double",
"based",
"on",
"the",
"array",
"and",
"given",
"indices"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java#L679-L682 |
before/quality-check | modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java | Check.greaterThan | @ArgumentsChecked
@Throws(IllegalNotGreaterThanException.class)
public static byte greaterThan(final byte expected, final byte check, @Nonnull final String message) {
if (expected >= check) {
throw new IllegalNotGreaterThanException(message, check);
}
return check;
} | java | @ArgumentsChecked
@Throws(IllegalNotGreaterThanException.class)
public static byte greaterThan(final byte expected, final byte check, @Nonnull final String message) {
if (expected >= check) {
throw new IllegalNotGreaterThanException(message, check);
}
return check;
} | [
"@",
"ArgumentsChecked",
"@",
"Throws",
"(",
"IllegalNotGreaterThanException",
".",
"class",
")",
"public",
"static",
"byte",
"greaterThan",
"(",
"final",
"byte",
"expected",
",",
"final",
"byte",
"check",
",",
"@",
"Nonnull",
"final",
"String",
"message",
")",
... | Ensures that a passed {@code byte} is greater than another {@code byte}.
@param expected
Expected value
@param check
Comparable to be checked
@param message
an error message describing why the comparable must be greater than a value (will be passed to
{@code IllegalNotGreaterThanException})
@return the passed {@code Comparable} argument {@code check}
@throws IllegalNotGreaterThanException
if the argument value {@code check} is not greater than value {@code expected} | [
"Ensures",
"that",
"a",
"passed",
"{",
"@code",
"byte",
"}",
"is",
"greater",
"than",
"another",
"{",
"@code",
"byte",
"}",
"."
] | train | https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L756-L764 |
linkhub-sdk/popbill.sdk.java | src/main/java/com/popbill/api/statement/StatementServiceImp.java | StatementServiceImp.attachFile | @Override
public Response attachFile(String CorpNum, int ItemCode, String MgtKey,
String DisplayName, InputStream FileData, String UserID)
throws PopbillException {
if (MgtKey == null || MgtKey.isEmpty())
throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");
if (DisplayName == null || DisplayName.isEmpty())
throw new PopbillException(-99999999, "파일 표시명이 입력되지 않았습니다.");
if (FileData == null)
throw new PopbillException(-99999999, "파일 스트림이 입력되지 않았습니다.");
List<UploadFile> files = new ArrayList<BaseServiceImp.UploadFile>();
UploadFile file = new UploadFile();
file.fileName = DisplayName;
file.fieldName = "Filedata";
file.fileData = FileData;
files.add(file);
return httppostFiles("/Statement/" + ItemCode + "/" + MgtKey + "/Files",
CorpNum, null, files, UserID, Response.class);
} | java | @Override
public Response attachFile(String CorpNum, int ItemCode, String MgtKey,
String DisplayName, InputStream FileData, String UserID)
throws PopbillException {
if (MgtKey == null || MgtKey.isEmpty())
throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");
if (DisplayName == null || DisplayName.isEmpty())
throw new PopbillException(-99999999, "파일 표시명이 입력되지 않았습니다.");
if (FileData == null)
throw new PopbillException(-99999999, "파일 스트림이 입력되지 않았습니다.");
List<UploadFile> files = new ArrayList<BaseServiceImp.UploadFile>();
UploadFile file = new UploadFile();
file.fileName = DisplayName;
file.fieldName = "Filedata";
file.fileData = FileData;
files.add(file);
return httppostFiles("/Statement/" + ItemCode + "/" + MgtKey + "/Files",
CorpNum, null, files, UserID, Response.class);
} | [
"@",
"Override",
"public",
"Response",
"attachFile",
"(",
"String",
"CorpNum",
",",
"int",
"ItemCode",
",",
"String",
"MgtKey",
",",
"String",
"DisplayName",
",",
"InputStream",
"FileData",
",",
"String",
"UserID",
")",
"throws",
"PopbillException",
"{",
"if",
... | /* (non-Javadoc)
@see com.popbill.api.StatementService#attachFile(java.lang.String, java.number.Integer, java.lang.String, ,java.io.InputStream, java.lang.String) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/linkhub-sdk/popbill.sdk.java/blob/63a341fefe96d60a368776638f3d4c81888238b7/src/main/java/com/popbill/api/statement/StatementServiceImp.java#L540-L561 |
rsocket/rsocket-java | rsocket-core/src/main/java/io/rsocket/util/NumberUtils.java | NumberUtils.requirePositive | public static int requirePositive(int i, String message) {
Objects.requireNonNull(message, "message must not be null");
if (i <= 0) {
throw new IllegalArgumentException(message);
}
return i;
} | java | public static int requirePositive(int i, String message) {
Objects.requireNonNull(message, "message must not be null");
if (i <= 0) {
throw new IllegalArgumentException(message);
}
return i;
} | [
"public",
"static",
"int",
"requirePositive",
"(",
"int",
"i",
",",
"String",
"message",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"message",
",",
"\"message must not be null\"",
")",
";",
"if",
"(",
"i",
"<=",
"0",
")",
"{",
"throw",
"new",
"Illega... | Requires that an {@code int} is greater than zero.
@param i the {@code int} to test
@param message detail message to be used in the event that a {@link IllegalArgumentException}
is thrown
@return the {@code int} if greater than zero
@throws IllegalArgumentException if {@code i} is less than or equal to zero | [
"Requires",
"that",
"an",
"{",
"@code",
"int",
"}",
"is",
"greater",
"than",
"zero",
"."
] | train | https://github.com/rsocket/rsocket-java/blob/5101748fbd224ec86570351cebd24d079b63fbfc/rsocket-core/src/main/java/io/rsocket/util/NumberUtils.java#L87-L95 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/admin/datamodel/attributetype/DecimalType.java | DecimalType.parseLocalized | public static BigDecimal parseLocalized(final String _value) throws EFapsException
{
final DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Context.getThreadContext()
.getLocale());
format.setParseBigDecimal(true);
try {
return (BigDecimal) format.parse(_value);
} catch (final ParseException e) {
throw new EFapsException(DecimalType.class, "ParseException", e);
}
} | java | public static BigDecimal parseLocalized(final String _value) throws EFapsException
{
final DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Context.getThreadContext()
.getLocale());
format.setParseBigDecimal(true);
try {
return (BigDecimal) format.parse(_value);
} catch (final ParseException e) {
throw new EFapsException(DecimalType.class, "ParseException", e);
}
} | [
"public",
"static",
"BigDecimal",
"parseLocalized",
"(",
"final",
"String",
"_value",
")",
"throws",
"EFapsException",
"{",
"final",
"DecimalFormat",
"format",
"=",
"(",
"DecimalFormat",
")",
"NumberFormat",
".",
"getInstance",
"(",
"Context",
".",
"getThreadContext... | Method to parse a localized String to an BigDecimal.
@param _value value to be parsed
@return BigDecimal
@throws EFapsException on error | [
"Method",
"to",
"parse",
"a",
"localized",
"String",
"to",
"an",
"BigDecimal",
"."
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/datamodel/attributetype/DecimalType.java#L117-L127 |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java | MappingUtil.put | public <T, K> void put(ColumnFamily<K, String> columnFamily, T item)
throws Exception {
@SuppressWarnings({ "unchecked" })
Class<T> clazz = (Class<T>) item.getClass();
Mapping<T> mapping = getMapping(clazz);
@SuppressWarnings({ "unchecked" })
Class<K> idFieldClass = (Class<K>) mapping.getIdFieldClass(); // safe -
// after
// erasure,
// this is
// all
// just
// Class
// anyway
MutationBatch mutationBatch = keyspace.prepareMutationBatch();
ColumnListMutation<String> columnListMutation = mutationBatch.withRow(
columnFamily, mapping.getIdValue(item, idFieldClass));
mapping.fillMutation(item, columnListMutation);
mutationBatch.execute();
} | java | public <T, K> void put(ColumnFamily<K, String> columnFamily, T item)
throws Exception {
@SuppressWarnings({ "unchecked" })
Class<T> clazz = (Class<T>) item.getClass();
Mapping<T> mapping = getMapping(clazz);
@SuppressWarnings({ "unchecked" })
Class<K> idFieldClass = (Class<K>) mapping.getIdFieldClass(); // safe -
// after
// erasure,
// this is
// all
// just
// Class
// anyway
MutationBatch mutationBatch = keyspace.prepareMutationBatch();
ColumnListMutation<String> columnListMutation = mutationBatch.withRow(
columnFamily, mapping.getIdValue(item, idFieldClass));
mapping.fillMutation(item, columnListMutation);
mutationBatch.execute();
} | [
"public",
"<",
"T",
",",
"K",
">",
"void",
"put",
"(",
"ColumnFamily",
"<",
"K",
",",
"String",
">",
"columnFamily",
",",
"T",
"item",
")",
"throws",
"Exception",
"{",
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
"}",
")",
"Class",
"<",
"T",
"... | Add/update the given item
@param columnFamily
column family of the item
@param item
the item to add/update
@throws Exception
errors | [
"Add",
"/",
"update",
"the",
"given",
"item"
] | train | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java#L123-L144 |
jirkapinkas/jsitemapgenerator | src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractGenerator.java | AbstractGenerator.addPageNames | public <T> I addPageNames(Collection<T> webPages, Function<T, String> mapper) {
for (T element : webPages) {
addPage(WebPage.of(mapper.apply(element)));
}
return getThis();
} | java | public <T> I addPageNames(Collection<T> webPages, Function<T, String> mapper) {
for (T element : webPages) {
addPage(WebPage.of(mapper.apply(element)));
}
return getThis();
} | [
"public",
"<",
"T",
">",
"I",
"addPageNames",
"(",
"Collection",
"<",
"T",
">",
"webPages",
",",
"Function",
"<",
"T",
",",
"String",
">",
"mapper",
")",
"{",
"for",
"(",
"T",
"element",
":",
"webPages",
")",
"{",
"addPage",
"(",
"WebPage",
".",
"o... | Add collection of pages to sitemap
@param <T> This is the type parameter
@param webPages Collection of pages
@param mapper Mapper function which transforms some object to String. This will be passed to WebPage.of(name)
@return this | [
"Add",
"collection",
"of",
"pages",
"to",
"sitemap"
] | train | https://github.com/jirkapinkas/jsitemapgenerator/blob/42e1f57bd936e21fe9df642e722726e71f667442/src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractGenerator.java#L151-L156 |
acromusashi/acromusashi-stream | src/main/java/acromusashi/stream/util/JsonValueExtractor.java | JsonValueExtractor.extractValue | public static String extractValue(Object target, String parentKey, String childKey)
{
JSONObject jsonObj = JSONObject.fromObject(target);
JSONObject parentObj = jsonObj.getJSONObject(parentKey);
String value = parentObj.getString(childKey);
return value;
} | java | public static String extractValue(Object target, String parentKey, String childKey)
{
JSONObject jsonObj = JSONObject.fromObject(target);
JSONObject parentObj = jsonObj.getJSONObject(parentKey);
String value = parentObj.getString(childKey);
return value;
} | [
"public",
"static",
"String",
"extractValue",
"(",
"Object",
"target",
",",
"String",
"parentKey",
",",
"String",
"childKey",
")",
"{",
"JSONObject",
"jsonObj",
"=",
"JSONObject",
".",
"fromObject",
"(",
"target",
")",
";",
"JSONObject",
"parentObj",
"=",
"jso... | 指定したJSONオブジェクトから「parentKey」要素中の「key」の要素を抽出する。<br>
抽出に失敗した場合は例外が発生する。
@param target JSONオブジェクト
@param parentKey JSONオブジェクト中の親キー
@param childKey JSONオブジェクト中の子キー
@return 取得結果 | [
"指定したJSONオブジェクトから「parentKey」要素中の「key」の要素を抽出する。<br",
">",
"抽出に失敗した場合は例外が発生する。"
] | train | https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/util/JsonValueExtractor.java#L39-L45 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/BeanPath.java | BeanPath.createList | @SuppressWarnings("unchecked")
protected <A, E extends SimpleExpression<? super A>> ListPath<A, E> createList(String property, Class<? super A> type, Class<? super E> queryType, PathInits inits) {
return add(new ListPath<A, E>(type, (Class) queryType, forProperty(property), inits));
} | java | @SuppressWarnings("unchecked")
protected <A, E extends SimpleExpression<? super A>> ListPath<A, E> createList(String property, Class<? super A> type, Class<? super E> queryType, PathInits inits) {
return add(new ListPath<A, E>(type, (Class) queryType, forProperty(property), inits));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"<",
"A",
",",
"E",
"extends",
"SimpleExpression",
"<",
"?",
"super",
"A",
">",
">",
"ListPath",
"<",
"A",
",",
"E",
">",
"createList",
"(",
"String",
"property",
",",
"Class",
"<",
"?",
... | Create a new List typed path
@param <A>
@param <E>
@param property property name
@param type property type
@param queryType expression type
@return property path | [
"Create",
"a",
"new",
"List",
"typed",
"path"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/BeanPath.java#L216-L219 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/core/services/ArgumentConvertor.java | ArgumentConvertor.checkStringArgument | void checkStringArgument(Class cls, String arg) throws IOException {
if (arg.startsWith(Constants.QUOTE)) { // ca ressemble à une string
if (!cls.equals(String.class)) { // et on veut pas une string
throw new IOException();
}
} else // ca ressemble pas à une string
if (cls.equals(String.class)) { // mais on veut une string
throw new IOException();
}
} | java | void checkStringArgument(Class cls, String arg) throws IOException {
if (arg.startsWith(Constants.QUOTE)) { // ca ressemble à une string
if (!cls.equals(String.class)) { // et on veut pas une string
throw new IOException();
}
} else // ca ressemble pas à une string
if (cls.equals(String.class)) { // mais on veut une string
throw new IOException();
}
} | [
"void",
"checkStringArgument",
"(",
"Class",
"cls",
",",
"String",
"arg",
")",
"throws",
"IOException",
"{",
"if",
"(",
"arg",
".",
"startsWith",
"(",
"Constants",
".",
"QUOTE",
")",
")",
"{",
"// ca ressemble à une string\r",
"if",
"(",
"!",
"cls",
".",
"... | check if class and argument are string
@param cls
@param arg
@throws IOException | [
"check",
"if",
"class",
"and",
"argument",
"are",
"string"
] | train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/core/services/ArgumentConvertor.java#L157-L166 |
treelogic-swe/aws-mock | src/main/java/com/tlswe/awsmock/ec2/control/MockEC2QueryHandler.java | MockEC2QueryHandler.getXmlError | private String getXmlError(final String errorCode, final String errorMessage) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("errorCode", StringEscapeUtils.escapeXml(errorCode));
data.put("errorMessage", StringEscapeUtils.escapeXml(errorMessage));
// fake a random UUID as request ID
data.put("requestID", UUID.randomUUID().toString());
String ret = null;
try {
ret = TemplateUtils.get(ERROR_RESPONSE_TEMPLATE, data);
} catch (AwsMockException e) {
log.error("fatal exception caught: {}", e.getMessage());
e.printStackTrace();
}
return ret;
} | java | private String getXmlError(final String errorCode, final String errorMessage) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("errorCode", StringEscapeUtils.escapeXml(errorCode));
data.put("errorMessage", StringEscapeUtils.escapeXml(errorMessage));
// fake a random UUID as request ID
data.put("requestID", UUID.randomUUID().toString());
String ret = null;
try {
ret = TemplateUtils.get(ERROR_RESPONSE_TEMPLATE, data);
} catch (AwsMockException e) {
log.error("fatal exception caught: {}", e.getMessage());
e.printStackTrace();
}
return ret;
} | [
"private",
"String",
"getXmlError",
"(",
"final",
"String",
"errorCode",
",",
"final",
"String",
"errorMessage",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"data",
... | Generate error response body in xml and write it with writer.
@param errorCode
the error code wrapped in the xml response
@param errorMessage
the error message wrapped in the xml response
@return xml body for an error message which can be recognized by AWS clients | [
"Generate",
"error",
"response",
"body",
"in",
"xml",
"and",
"write",
"it",
"with",
"writer",
"."
] | train | https://github.com/treelogic-swe/aws-mock/blob/1d1058c0ebbd0615efa28695481e36ae3ffc58a0/src/main/java/com/tlswe/awsmock/ec2/control/MockEC2QueryHandler.java#L2014-L2030 |
diegossilveira/jcors | src/main/java/org/jcors/web/ActualRequestHandler.java | ActualRequestHandler.checkOriginHeader | private String checkOriginHeader(HttpServletRequest request, JCorsConfig config) {
String originHeader = request.getHeader(CorsHeaders.ORIGIN_HEADER);
Constraint.ensureNotEmpty(originHeader, "Cross-Origin requests must specify an Origin Header");
String[] origins = originHeader.split(" ");
for (String origin : origins) {
Constraint.ensureTrue(config.isOriginAllowed(origin), String.format("The specified origin is not allowed: '%s'", origin));
}
return originHeader;
} | java | private String checkOriginHeader(HttpServletRequest request, JCorsConfig config) {
String originHeader = request.getHeader(CorsHeaders.ORIGIN_HEADER);
Constraint.ensureNotEmpty(originHeader, "Cross-Origin requests must specify an Origin Header");
String[] origins = originHeader.split(" ");
for (String origin : origins) {
Constraint.ensureTrue(config.isOriginAllowed(origin), String.format("The specified origin is not allowed: '%s'", origin));
}
return originHeader;
} | [
"private",
"String",
"checkOriginHeader",
"(",
"HttpServletRequest",
"request",
",",
"JCorsConfig",
"config",
")",
"{",
"String",
"originHeader",
"=",
"request",
".",
"getHeader",
"(",
"CorsHeaders",
".",
"ORIGIN_HEADER",
")",
";",
"Constraint",
".",
"ensureNotEmpty... | Checks if the origin is allowed
@param request
@param config | [
"Checks",
"if",
"the",
"origin",
"is",
"allowed"
] | train | https://github.com/diegossilveira/jcors/blob/cd56a9e2055d629baa42f93b27dd5615ced9632f/src/main/java/org/jcors/web/ActualRequestHandler.java#L49-L61 |
lagom/lagom | service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java | Descriptor.replaceAllAcls | public Descriptor replaceAllAcls(PSequence<ServiceAcl> acls) {
return new Descriptor(name, calls, pathParamSerializers, messageSerializers, serializerFactory, exceptionSerializer, autoAcl, acls, headerFilter, locatableService, circuitBreaker, topicCalls);
} | java | public Descriptor replaceAllAcls(PSequence<ServiceAcl> acls) {
return new Descriptor(name, calls, pathParamSerializers, messageSerializers, serializerFactory, exceptionSerializer, autoAcl, acls, headerFilter, locatableService, circuitBreaker, topicCalls);
} | [
"public",
"Descriptor",
"replaceAllAcls",
"(",
"PSequence",
"<",
"ServiceAcl",
">",
"acls",
")",
"{",
"return",
"new",
"Descriptor",
"(",
"name",
",",
"calls",
",",
"pathParamSerializers",
",",
"messageSerializers",
",",
"serializerFactory",
",",
"exceptionSerialize... | Replace all the ACLs with the given ACL sequence.
This will not replace ACLs generated by autoAcl, to disable autoAcl, turn it off.
@param acls The ACLs to use.
@return A copy of this descriptor. | [
"Replace",
"all",
"the",
"ACLs",
"with",
"the",
"given",
"ACL",
"sequence",
"."
] | train | https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java#L810-L812 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java | SSLAlpnNegotiator.registerJettyAlpn | protected JettyServerNegotiator registerJettyAlpn(final SSLEngine engine, SSLConnectionLink link) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerJettyAlpn entry " + engine);
}
try {
JettyServerNegotiator negotiator = new JettyServerNegotiator(engine, link);
// invoke ALPN.put(engine, provider(this))
Method m = jettyAlpn.getMethod("put", SSLEngine.class, jettyProviderInterface);
m.invoke(null, new Object[] { engine, java.lang.reflect.Proxy.newProxyInstance(
jettyServerProviderInterface.getClassLoader(),
new java.lang.Class[] { jettyServerProviderInterface },
negotiator) });
return negotiator;
} catch (InvocationTargetException ie) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerJettyAlpn exception: " + ie.getTargetException());
}
} catch (Exception e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerJettyAlpn jetty-alpn exception: " + e);
}
}
return null;
} | java | protected JettyServerNegotiator registerJettyAlpn(final SSLEngine engine, SSLConnectionLink link) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerJettyAlpn entry " + engine);
}
try {
JettyServerNegotiator negotiator = new JettyServerNegotiator(engine, link);
// invoke ALPN.put(engine, provider(this))
Method m = jettyAlpn.getMethod("put", SSLEngine.class, jettyProviderInterface);
m.invoke(null, new Object[] { engine, java.lang.reflect.Proxy.newProxyInstance(
jettyServerProviderInterface.getClassLoader(),
new java.lang.Class[] { jettyServerProviderInterface },
negotiator) });
return negotiator;
} catch (InvocationTargetException ie) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerJettyAlpn exception: " + ie.getTargetException());
}
} catch (Exception e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerJettyAlpn jetty-alpn exception: " + e);
}
}
return null;
} | [
"protected",
"JettyServerNegotiator",
"registerJettyAlpn",
"(",
"final",
"SSLEngine",
"engine",
",",
"SSLConnectionLink",
"link",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
... | Using jetty-alpn, set up a new JettyServerNotiator to handle ALPN for a given SSLEngine and link
@param SSLEngine
@param SSLConnectionLink
@return JettyServerNegotiator or null if ALPN was not set up | [
"Using",
"jetty",
"-",
"alpn",
"set",
"up",
"a",
"new",
"JettyServerNotiator",
"to",
"handle",
"ALPN",
"for",
"a",
"given",
"SSLEngine",
"and",
"link"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java#L445-L469 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/filter/Filter.java | Filter.orNotExists | public final Filter<S> orNotExists(String propertyName, Filter<?> subFilter) {
ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty();
return or(ExistsFilter.build(prop, subFilter, true));
} | java | public final Filter<S> orNotExists(String propertyName, Filter<?> subFilter) {
ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty();
return or(ExistsFilter.build(prop, subFilter, true));
} | [
"public",
"final",
"Filter",
"<",
"S",
">",
"orNotExists",
"(",
"String",
"propertyName",
",",
"Filter",
"<",
"?",
">",
"subFilter",
")",
"{",
"ChainedProperty",
"<",
"S",
">",
"prop",
"=",
"new",
"FilterParser",
"<",
"S",
">",
"(",
"mType",
",",
"prop... | Returns a combined filter instance that accepts records which are
accepted either by this filter or the "not exists" test applied to a
join.
@param propertyName one-to-many join property name, which may be a chained property
@param subFilter sub-filter to apply to join, which may be null to test
for any not existing
@return canonical Filter instance
@throws IllegalArgumentException if property is not found
@since 1.2 | [
"Returns",
"a",
"combined",
"filter",
"instance",
"that",
"accepts",
"records",
"which",
"are",
"accepted",
"either",
"by",
"this",
"filter",
"or",
"the",
"not",
"exists",
"test",
"applied",
"to",
"a",
"join",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/filter/Filter.java#L411-L414 |
alibaba/ARouter | arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java | Postcard.withCharSequenceArrayList | public Postcard withCharSequenceArrayList(@Nullable String key, @Nullable ArrayList<CharSequence> value) {
mBundle.putCharSequenceArrayList(key, value);
return this;
} | java | public Postcard withCharSequenceArrayList(@Nullable String key, @Nullable ArrayList<CharSequence> value) {
mBundle.putCharSequenceArrayList(key, value);
return this;
} | [
"public",
"Postcard",
"withCharSequenceArrayList",
"(",
"@",
"Nullable",
"String",
"key",
",",
"@",
"Nullable",
"ArrayList",
"<",
"CharSequence",
">",
"value",
")",
"{",
"mBundle",
".",
"putCharSequenceArrayList",
"(",
"key",
",",
"value",
")",
";",
"return",
... | Inserts an ArrayList value into the mapping of this Bundle, replacing
any existing value for the given key. Either key or value may be null.
@param key a String, or null
@param value an ArrayList object, or null
@return current | [
"Inserts",
"an",
"ArrayList",
"value",
"into",
"the",
"mapping",
"of",
"this",
"Bundle",
"replacing",
"any",
"existing",
"value",
"for",
"the",
"given",
"key",
".",
"Either",
"key",
"or",
"value",
"may",
"be",
"null",
"."
] | train | https://github.com/alibaba/ARouter/blob/1a06912a6e14a57112db1204b43f81c43d721732/arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java#L455-L458 |
VoltDB/voltdb | src/frontend/org/voltdb/dr2/DRIDTrackerHelper.java | DRIDTrackerHelper.dejsonifyClusterTrackers | public static Map<Integer, Map<Integer, DRSiteDrIdTracker>> dejsonifyClusterTrackers(final String jsonData, boolean resetLastReceivedLogIds)
throws JSONException
{
Map<Integer, Map<Integer, DRSiteDrIdTracker>> producerTrackers = new HashMap<>();
JSONObject clusterData = new JSONObject(jsonData);
final JSONObject trackers = clusterData.getJSONObject("trackers");
Iterator<String> clusterIdKeys = trackers.keys();
while (clusterIdKeys.hasNext()) {
final String clusterIdStr = clusterIdKeys.next();
final int clusterId = Integer.parseInt(clusterIdStr);
final JSONObject trackerData = trackers.getJSONObject(clusterIdStr);
Iterator<String> srcPidKeys = trackerData.keys();
while (srcPidKeys.hasNext()) {
final String srcPidStr = srcPidKeys.next();
final int srcPid = Integer.valueOf(srcPidStr);
final JSONObject ids = trackerData.getJSONObject(srcPidStr);
final DRSiteDrIdTracker tracker = new DRSiteDrIdTracker(ids, resetLastReceivedLogIds);
Map<Integer, DRSiteDrIdTracker> clusterTrackers = producerTrackers.computeIfAbsent(clusterId, k -> new HashMap<>());
clusterTrackers.put(srcPid, tracker);
}
}
return producerTrackers;
} | java | public static Map<Integer, Map<Integer, DRSiteDrIdTracker>> dejsonifyClusterTrackers(final String jsonData, boolean resetLastReceivedLogIds)
throws JSONException
{
Map<Integer, Map<Integer, DRSiteDrIdTracker>> producerTrackers = new HashMap<>();
JSONObject clusterData = new JSONObject(jsonData);
final JSONObject trackers = clusterData.getJSONObject("trackers");
Iterator<String> clusterIdKeys = trackers.keys();
while (clusterIdKeys.hasNext()) {
final String clusterIdStr = clusterIdKeys.next();
final int clusterId = Integer.parseInt(clusterIdStr);
final JSONObject trackerData = trackers.getJSONObject(clusterIdStr);
Iterator<String> srcPidKeys = trackerData.keys();
while (srcPidKeys.hasNext()) {
final String srcPidStr = srcPidKeys.next();
final int srcPid = Integer.valueOf(srcPidStr);
final JSONObject ids = trackerData.getJSONObject(srcPidStr);
final DRSiteDrIdTracker tracker = new DRSiteDrIdTracker(ids, resetLastReceivedLogIds);
Map<Integer, DRSiteDrIdTracker> clusterTrackers = producerTrackers.computeIfAbsent(clusterId, k -> new HashMap<>());
clusterTrackers.put(srcPid, tracker);
}
}
return producerTrackers;
} | [
"public",
"static",
"Map",
"<",
"Integer",
",",
"Map",
"<",
"Integer",
",",
"DRSiteDrIdTracker",
">",
">",
"dejsonifyClusterTrackers",
"(",
"final",
"String",
"jsonData",
",",
"boolean",
"resetLastReceivedLogIds",
")",
"throws",
"JSONException",
"{",
"Map",
"<",
... | Deserialize the trackers retrieved from each consumer partitions.
@param jsonData Tracker data retrieved from each consumer partition.
@param partitionsMissingTracker
@return A map of producer cluster ID to tracker for each producer
partition. If no tracker information is found, the map will be empty.
@throws JSONException | [
"Deserialize",
"the",
"trackers",
"retrieved",
"from",
"each",
"consumer",
"partitions",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/dr2/DRIDTrackerHelper.java#L79-L104 |
lucmoreau/ProvToolbox | prov-model/src/main/java/org/openprovenance/prov/model/DOMProcessing.java | DOMProcessing.newElement | final static public Element newElement(QualifiedName elementName, QualifiedName value) {
org.w3c.dom.Document doc = builder.newDocument();
Element el = doc.createElementNS(elementName.getNamespaceURI(),
qualifiedNameToString(elementName.toQName()));
// 1. we add an xsi:type="xsd:QName" attribute
// making sure xsi and xsd prefixes are appropriately declared.
el.setAttributeNS(NamespacePrefixMapper.XSI_NS, "xsi:type", "xsd:QName");
el.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsd", XSD_NS_FOR_XML);
// 2. We add the QualifiedName's string representation as child of the element
// This representation depends on the extant prefix-namespace mapping
String valueAsString=qualifiedNameToString(value.toQName());
el.appendChild(doc.createTextNode(valueAsString));
// 3. We make sure that the QualifiedName's prefix is given the right namespace, or the default namespace is declared if there is no prefix
int index=valueAsString.indexOf(":");
if (index!=-1) {
String prefix = valueAsString.substring(0, index);
el.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:"+prefix, convertNsToXml(value.getNamespaceURI()));
} else {
el.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", convertNsToXml(value.getNamespaceURI()));
}
doc.appendChild(el);
return el;
} | java | final static public Element newElement(QualifiedName elementName, QualifiedName value) {
org.w3c.dom.Document doc = builder.newDocument();
Element el = doc.createElementNS(elementName.getNamespaceURI(),
qualifiedNameToString(elementName.toQName()));
// 1. we add an xsi:type="xsd:QName" attribute
// making sure xsi and xsd prefixes are appropriately declared.
el.setAttributeNS(NamespacePrefixMapper.XSI_NS, "xsi:type", "xsd:QName");
el.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsd", XSD_NS_FOR_XML);
// 2. We add the QualifiedName's string representation as child of the element
// This representation depends on the extant prefix-namespace mapping
String valueAsString=qualifiedNameToString(value.toQName());
el.appendChild(doc.createTextNode(valueAsString));
// 3. We make sure that the QualifiedName's prefix is given the right namespace, or the default namespace is declared if there is no prefix
int index=valueAsString.indexOf(":");
if (index!=-1) {
String prefix = valueAsString.substring(0, index);
el.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:"+prefix, convertNsToXml(value.getNamespaceURI()));
} else {
el.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", convertNsToXml(value.getNamespaceURI()));
}
doc.appendChild(el);
return el;
} | [
"final",
"static",
"public",
"Element",
"newElement",
"(",
"QualifiedName",
"elementName",
",",
"QualifiedName",
"value",
")",
"{",
"org",
".",
"w3c",
".",
"dom",
".",
"Document",
"doc",
"=",
"builder",
".",
"newDocument",
"(",
")",
";",
"Element",
"el",
"... | Creates a DOM {@link Element} for a {@link QualifiedName} and content given by value
@param elementName a {@link QualifiedName} to denote the element name
@param value for the created {@link Element}
@return a new {@link Element} | [
"Creates",
"a",
"DOM",
"{",
"@link",
"Element",
"}",
"for",
"a",
"{",
"@link",
"QualifiedName",
"}",
"and",
"content",
"given",
"by",
"value"
] | train | https://github.com/lucmoreau/ProvToolbox/blob/f865952868ffb69432937b08728c86bebbe4678a/prov-model/src/main/java/org/openprovenance/prov/model/DOMProcessing.java#L128-L154 |
JodaOrg/joda-time | src/main/java/org/joda/time/TimeOfDay.java | TimeOfDay.getField | protected DateTimeField getField(int index, Chronology chrono) {
switch (index) {
case HOUR_OF_DAY:
return chrono.hourOfDay();
case MINUTE_OF_HOUR:
return chrono.minuteOfHour();
case SECOND_OF_MINUTE:
return chrono.secondOfMinute();
case MILLIS_OF_SECOND:
return chrono.millisOfSecond();
default:
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
} | java | protected DateTimeField getField(int index, Chronology chrono) {
switch (index) {
case HOUR_OF_DAY:
return chrono.hourOfDay();
case MINUTE_OF_HOUR:
return chrono.minuteOfHour();
case SECOND_OF_MINUTE:
return chrono.secondOfMinute();
case MILLIS_OF_SECOND:
return chrono.millisOfSecond();
default:
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
} | [
"protected",
"DateTimeField",
"getField",
"(",
"int",
"index",
",",
"Chronology",
"chrono",
")",
"{",
"switch",
"(",
"index",
")",
"{",
"case",
"HOUR_OF_DAY",
":",
"return",
"chrono",
".",
"hourOfDay",
"(",
")",
";",
"case",
"MINUTE_OF_HOUR",
":",
"return",
... | Gets the field for a specific index in the chronology specified.
<p>
This method must not use any instance variables.
@param index the index to retrieve
@param chrono the chronology to use
@return the field | [
"Gets",
"the",
"field",
"for",
"a",
"specific",
"index",
"in",
"the",
"chronology",
"specified",
".",
"<p",
">",
"This",
"method",
"must",
"not",
"use",
"any",
"instance",
"variables",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/TimeOfDay.java#L441-L454 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionCommitmentClient.java | RegionCommitmentClient.insertRegionCommitment | @BetaApi
public final Operation insertRegionCommitment(String region, Commitment commitmentResource) {
InsertRegionCommitmentHttpRequest request =
InsertRegionCommitmentHttpRequest.newBuilder()
.setRegion(region)
.setCommitmentResource(commitmentResource)
.build();
return insertRegionCommitment(request);
} | java | @BetaApi
public final Operation insertRegionCommitment(String region, Commitment commitmentResource) {
InsertRegionCommitmentHttpRequest request =
InsertRegionCommitmentHttpRequest.newBuilder()
.setRegion(region)
.setCommitmentResource(commitmentResource)
.build();
return insertRegionCommitment(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertRegionCommitment",
"(",
"String",
"region",
",",
"Commitment",
"commitmentResource",
")",
"{",
"InsertRegionCommitmentHttpRequest",
"request",
"=",
"InsertRegionCommitmentHttpRequest",
".",
"newBuilder",
"(",
")",
"."... | Creates a commitment in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (RegionCommitmentClient regionCommitmentClient = RegionCommitmentClient.create()) {
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
Commitment commitmentResource = Commitment.newBuilder().build();
Operation response = regionCommitmentClient.insertRegionCommitment(region.toString(), commitmentResource);
}
</code></pre>
@param region Name of the region for this request.
@param commitmentResource Represents a Commitment resource. Creating a Commitment resource
means that you are purchasing a committed use contract with an explicit start and end time.
You can create commitments based on vCPUs and memory usage and receive discounted rates.
For full details, read Signing Up for Committed Use Discounts.
<p>Committed use discounts are subject to Google Cloud Platform's Service Specific Terms.
By purchasing a committed use discount, you agree to these terms. Committed use discounts
will not renew, so you must purchase a new commitment to continue receiving discounts. (==
resource_for beta.commitments ==) (== resource_for v1.commitments ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"commitment",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionCommitmentClient.java#L462-L471 |
ontop/ontop | engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/dialect/impl/SQL99DialectAdapter.java | SQL99DialectAdapter.buildDefaultName | protected final String buildDefaultName(String prefix, String intermediateName, String suffix) {
return prefix + intermediateName + suffix;
} | java | protected final String buildDefaultName(String prefix, String intermediateName, String suffix) {
return prefix + intermediateName + suffix;
} | [
"protected",
"final",
"String",
"buildDefaultName",
"(",
"String",
"prefix",
",",
"String",
"intermediateName",
",",
"String",
"suffix",
")",
"{",
"return",
"prefix",
"+",
"intermediateName",
"+",
"suffix",
";",
"}"
] | Concatenates the strings.
Default way to name a variable or a view.
<p>
Returns an UNQUOTED string. | [
"Concatenates",
"the",
"strings",
".",
"Default",
"way",
"to",
"name",
"a",
"variable",
"or",
"a",
"view",
".",
"<p",
">",
"Returns",
"an",
"UNQUOTED",
"string",
"."
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/engine/reformulation/sql/src/main/java/it/unibz/inf/ontop/answering/reformulation/generation/dialect/impl/SQL99DialectAdapter.java#L499-L501 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java | UnicodeSet.toPattern | @Override
public String toPattern(boolean escapeUnprintable) {
if (pat != null && !escapeUnprintable) {
return pat;
}
StringBuilder result = new StringBuilder();
return _toPattern(result, escapeUnprintable).toString();
} | java | @Override
public String toPattern(boolean escapeUnprintable) {
if (pat != null && !escapeUnprintable) {
return pat;
}
StringBuilder result = new StringBuilder();
return _toPattern(result, escapeUnprintable).toString();
} | [
"@",
"Override",
"public",
"String",
"toPattern",
"(",
"boolean",
"escapeUnprintable",
")",
"{",
"if",
"(",
"pat",
"!=",
"null",
"&&",
"!",
"escapeUnprintable",
")",
"{",
"return",
"pat",
";",
"}",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",... | Returns a string representation of this set. If the result of
calling this function is passed to a UnicodeSet constructor, it
will produce another set that is equal to this one. | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"set",
".",
"If",
"the",
"result",
"of",
"calling",
"this",
"function",
"is",
"passed",
"to",
"a",
"UnicodeSet",
"constructor",
"it",
"will",
"produce",
"another",
"set",
"that",
"is",
"equal",
"to",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java#L678-L685 |
google/closure-compiler | src/com/google/javascript/jscomp/ExpressionDecomposer.java | ExpressionDecomposer.isExpressionTreeUnsafe | private boolean isExpressionTreeUnsafe(Node tree, boolean followingSideEffectsExist) {
if (tree.isSpread()) {
// Spread expressions would cause recursive rewriting if not special cased here.
switch (tree.getParent().getToken()) {
case OBJECTLIT:
// Spreading an object, rather than an iterable, is assumed to be pure. That assesment is
// based on the compiler assumption that getters are pure. This check say nothing of the
// expression being spread.
break;
case ARRAYLIT:
case CALL:
case NEW:
// When extracted, spreads can't be assigned to a single variable and instead are put into
// an array-literal. However, that literal must be spread again at the original site. This
// check is what prevents the original spread from triggering recursion.
if (isTempConstantValueName(tree.getOnlyChild())) {
return false;
}
break;
default:
throw new IllegalStateException(
"Unexpected parent of SPREAD: " + tree.getParent().toStringTree());
}
}
if (followingSideEffectsExist) {
// If the call to be inlined has side-effects, check to see if this
// expression tree can be affected by any side-effects.
// Assume that "tmp1.call(...)" is safe (where tmp1 is a const temp variable created by
// ExpressionDecomposer) otherwise we end up trying to decompose the same tree
// an infinite number of times.
Node parent = tree.getParent();
if (NodeUtil.isObjectCallMethod(parent, "call")
&& tree.isFirstChildOf(parent)
&& isTempConstantValueName(tree.getFirstChild())) {
return false;
}
// This is a superset of "NodeUtil.mayHaveSideEffects".
return NodeUtil.canBeSideEffected(tree, this.knownConstants, scope);
} else {
// The function called doesn't have side-effects but check to see if there
// are side-effects that that may affect it.
return NodeUtil.mayHaveSideEffects(tree, compiler);
}
} | java | private boolean isExpressionTreeUnsafe(Node tree, boolean followingSideEffectsExist) {
if (tree.isSpread()) {
// Spread expressions would cause recursive rewriting if not special cased here.
switch (tree.getParent().getToken()) {
case OBJECTLIT:
// Spreading an object, rather than an iterable, is assumed to be pure. That assesment is
// based on the compiler assumption that getters are pure. This check say nothing of the
// expression being spread.
break;
case ARRAYLIT:
case CALL:
case NEW:
// When extracted, spreads can't be assigned to a single variable and instead are put into
// an array-literal. However, that literal must be spread again at the original site. This
// check is what prevents the original spread from triggering recursion.
if (isTempConstantValueName(tree.getOnlyChild())) {
return false;
}
break;
default:
throw new IllegalStateException(
"Unexpected parent of SPREAD: " + tree.getParent().toStringTree());
}
}
if (followingSideEffectsExist) {
// If the call to be inlined has side-effects, check to see if this
// expression tree can be affected by any side-effects.
// Assume that "tmp1.call(...)" is safe (where tmp1 is a const temp variable created by
// ExpressionDecomposer) otherwise we end up trying to decompose the same tree
// an infinite number of times.
Node parent = tree.getParent();
if (NodeUtil.isObjectCallMethod(parent, "call")
&& tree.isFirstChildOf(parent)
&& isTempConstantValueName(tree.getFirstChild())) {
return false;
}
// This is a superset of "NodeUtil.mayHaveSideEffects".
return NodeUtil.canBeSideEffected(tree, this.knownConstants, scope);
} else {
// The function called doesn't have side-effects but check to see if there
// are side-effects that that may affect it.
return NodeUtil.mayHaveSideEffects(tree, compiler);
}
} | [
"private",
"boolean",
"isExpressionTreeUnsafe",
"(",
"Node",
"tree",
",",
"boolean",
"followingSideEffectsExist",
")",
"{",
"if",
"(",
"tree",
".",
"isSpread",
"(",
")",
")",
"{",
"// Spread expressions would cause recursive rewriting if not special cased here.",
"switch",
... | Determines if there is any subexpression below {@code tree} that would make it incorrect for
some expression that follows {@code tree}, {@code E}, to be executed before {@code tree}.
@param followingSideEffectsExist whether {@code E} causes side-effects.
@return {@code true} if {@code tree} contains any subexpressions that would make movement
incorrect. | [
"Determines",
"if",
"there",
"is",
"any",
"subexpression",
"below",
"{",
"@code",
"tree",
"}",
"that",
"would",
"make",
"it",
"incorrect",
"for",
"some",
"expression",
"that",
"follows",
"{",
"@code",
"tree",
"}",
"{",
"@code",
"E",
"}",
"to",
"be",
"exe... | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L1047-L1093 |
Chorus-bdd/Chorus | extensions/chorus-websockets/src/main/java/org/chorusbdd/chorus/websockets/client/TimeoutStepExecutor.java | TimeoutStepExecutor.runWithinPeriod | void runWithinPeriod(Runnable runnable, ExecuteStepMessage executeStepMessage, int timeout, TimeUnit unit) {
if ( ! isRunningAStep.getAndSet(true)) {
this.currentlyExecutingStep = executeStepMessage;
Future<String> future = null;
try {
future = scheduledExecutorService.submit(runStepAndResetIsRunning(runnable), "OK");
future.get(timeout, unit);
} catch (TimeoutException e) {
//Timed out waiting for the step to run
//We should try to cancel and interrupt the thread which is running the step - although this isn't
//guaranteed to succeed.
future.cancel(true);
log.warn("A step failed to execute within " + timeout + " " + unit + ", attempting to cancel the step");
//Here the step server should have timed out the step and proceed already - we don't need to send a failure message
} catch (Exception e) {
String ms = "Exception while executing step [" + e.getMessage() + "]";
log.error(ms, e);
stepFailureConsumer.accept(ms, executeStepMessage);
}
} else {
//server will time out this step
String message = "Cannot execute a test step, a step is already in progress [" + currentlyExecutingStep.getStepId() + ", " + currentlyExecutingStep.getPattern() + "]";
log.error(message);
stepFailureConsumer.accept(message, executeStepMessage);
}
} | java | void runWithinPeriod(Runnable runnable, ExecuteStepMessage executeStepMessage, int timeout, TimeUnit unit) {
if ( ! isRunningAStep.getAndSet(true)) {
this.currentlyExecutingStep = executeStepMessage;
Future<String> future = null;
try {
future = scheduledExecutorService.submit(runStepAndResetIsRunning(runnable), "OK");
future.get(timeout, unit);
} catch (TimeoutException e) {
//Timed out waiting for the step to run
//We should try to cancel and interrupt the thread which is running the step - although this isn't
//guaranteed to succeed.
future.cancel(true);
log.warn("A step failed to execute within " + timeout + " " + unit + ", attempting to cancel the step");
//Here the step server should have timed out the step and proceed already - we don't need to send a failure message
} catch (Exception e) {
String ms = "Exception while executing step [" + e.getMessage() + "]";
log.error(ms, e);
stepFailureConsumer.accept(ms, executeStepMessage);
}
} else {
//server will time out this step
String message = "Cannot execute a test step, a step is already in progress [" + currentlyExecutingStep.getStepId() + ", " + currentlyExecutingStep.getPattern() + "]";
log.error(message);
stepFailureConsumer.accept(message, executeStepMessage);
}
} | [
"void",
"runWithinPeriod",
"(",
"Runnable",
"runnable",
",",
"ExecuteStepMessage",
"executeStepMessage",
",",
"int",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"if",
"(",
"!",
"isRunningAStep",
".",
"getAndSet",
"(",
"true",
")",
")",
"{",
"this",
".",
"c... | Run a task on the scheduled executor so that we can try to interrupt it and time out if it fails | [
"Run",
"a",
"task",
"on",
"the",
"scheduled",
"executor",
"so",
"that",
"we",
"can",
"try",
"to",
"interrupt",
"it",
"and",
"time",
"out",
"if",
"it",
"fails"
] | train | https://github.com/Chorus-bdd/Chorus/blob/1eea7ca858876bce821bb49b43fd5b6ba1737997/extensions/chorus-websockets/src/main/java/org/chorusbdd/chorus/websockets/client/TimeoutStepExecutor.java#L65-L90 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/ui/CmsElementSettingsDialog.java | CmsElementSettingsDialog.addCreateNewCheckbox | private void addCreateNewCheckbox(CmsContainerElementData elementBean, CmsFieldSet fieldSet) {
m_createNewCheckBox = new CmsCheckBox(Messages.get().key(Messages.GUI_CREATE_NEW_LABEL_0));
m_createNewCheckBox.setDisplayInline(false);
m_createNewCheckBox.getElement().getStyle().setMarginTop(7, Style.Unit.PX);
m_createNewCheckBox.setChecked(elementBean.isCreateNew());
fieldSet.add(m_createNewCheckBox);
} | java | private void addCreateNewCheckbox(CmsContainerElementData elementBean, CmsFieldSet fieldSet) {
m_createNewCheckBox = new CmsCheckBox(Messages.get().key(Messages.GUI_CREATE_NEW_LABEL_0));
m_createNewCheckBox.setDisplayInline(false);
m_createNewCheckBox.getElement().getStyle().setMarginTop(7, Style.Unit.PX);
m_createNewCheckBox.setChecked(elementBean.isCreateNew());
fieldSet.add(m_createNewCheckBox);
} | [
"private",
"void",
"addCreateNewCheckbox",
"(",
"CmsContainerElementData",
"elementBean",
",",
"CmsFieldSet",
"fieldSet",
")",
"{",
"m_createNewCheckBox",
"=",
"new",
"CmsCheckBox",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"key",
"(",
"Messages",
".",
"GUI_CREA... | Adds the create new checkbox to the given field set.<p>
@param elementBean the element bean
@param fieldSet the field set | [
"Adds",
"the",
"create",
"new",
"checkbox",
"to",
"the",
"given",
"field",
"set",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/ui/CmsElementSettingsDialog.java#L723-L730 |
martint/jmxutils | src/main/java/org/weakref/jmx/ObjectNames.java | ObjectNames.generatedNameOf | public static String generatedNameOf(Class<?> clazz, String name)
{
return builder(clazz, name).build();
} | java | public static String generatedNameOf(Class<?> clazz, String name)
{
return builder(clazz, name).build();
} | [
"public",
"static",
"String",
"generatedNameOf",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"name",
")",
"{",
"return",
"builder",
"(",
"clazz",
",",
"name",
")",
".",
"build",
"(",
")",
";",
"}"
] | Produce a generated JMX object name.
@return JMX object name of the form "[package_name]:type=[class_name],name=[named_value]" | [
"Produce",
"a",
"generated",
"JMX",
"object",
"name",
"."
] | train | https://github.com/martint/jmxutils/blob/f2770ba1f3c126fb841c388d631456afd68dbf25/src/main/java/org/weakref/jmx/ObjectNames.java#L59-L62 |
alkacon/opencms-core | src/org/opencms/webdav/CmsWebdavServlet.java | CmsWebdavServlet.executePartialPut | protected File executePartialPut(HttpServletRequest req, CmsWebdavRange range, String path) throws IOException {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
File tempDir = (File)getServletContext().getAttribute(ATT_SERVLET_TEMPDIR);
// Convert all '/' characters to '.' in resourcePath
String convertedResourcePath = path.replace('/', '.');
File contentFile = new File(tempDir, convertedResourcePath);
contentFile.createNewFile();
RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw");
InputStream oldResourceStream = null;
try {
I_CmsRepositoryItem item = m_session.getItem(path);
oldResourceStream = new ByteArrayInputStream(item.getContent());
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path), e);
}
}
// Copy data in oldRevisionContent to contentFile
if (oldResourceStream != null) {
int numBytesRead;
byte[] copyBuffer = new byte[BUFFER_SIZE];
while ((numBytesRead = oldResourceStream.read(copyBuffer)) != -1) {
randAccessContentFile.write(copyBuffer, 0, numBytesRead);
}
oldResourceStream.close();
}
randAccessContentFile.setLength(range.getLength());
// Append data in request input stream to contentFile
randAccessContentFile.seek(range.getStart());
int numBytesRead;
byte[] transferBuffer = new byte[BUFFER_SIZE];
BufferedInputStream requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE);
while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
randAccessContentFile.write(transferBuffer, 0, numBytesRead);
}
randAccessContentFile.close();
requestBufInStream.close();
return contentFile;
} | java | protected File executePartialPut(HttpServletRequest req, CmsWebdavRange range, String path) throws IOException {
// Append data specified in ranges to existing content for this
// resource - create a temp. file on the local filesystem to
// perform this operation
File tempDir = (File)getServletContext().getAttribute(ATT_SERVLET_TEMPDIR);
// Convert all '/' characters to '.' in resourcePath
String convertedResourcePath = path.replace('/', '.');
File contentFile = new File(tempDir, convertedResourcePath);
contentFile.createNewFile();
RandomAccessFile randAccessContentFile = new RandomAccessFile(contentFile, "rw");
InputStream oldResourceStream = null;
try {
I_CmsRepositoryItem item = m_session.getItem(path);
oldResourceStream = new ByteArrayInputStream(item.getContent());
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.LOG_ITEM_NOT_FOUND_1, path), e);
}
}
// Copy data in oldRevisionContent to contentFile
if (oldResourceStream != null) {
int numBytesRead;
byte[] copyBuffer = new byte[BUFFER_SIZE];
while ((numBytesRead = oldResourceStream.read(copyBuffer)) != -1) {
randAccessContentFile.write(copyBuffer, 0, numBytesRead);
}
oldResourceStream.close();
}
randAccessContentFile.setLength(range.getLength());
// Append data in request input stream to contentFile
randAccessContentFile.seek(range.getStart());
int numBytesRead;
byte[] transferBuffer = new byte[BUFFER_SIZE];
BufferedInputStream requestBufInStream = new BufferedInputStream(req.getInputStream(), BUFFER_SIZE);
while ((numBytesRead = requestBufInStream.read(transferBuffer)) != -1) {
randAccessContentFile.write(transferBuffer, 0, numBytesRead);
}
randAccessContentFile.close();
requestBufInStream.close();
return contentFile;
} | [
"protected",
"File",
"executePartialPut",
"(",
"HttpServletRequest",
"req",
",",
"CmsWebdavRange",
"range",
",",
"String",
"path",
")",
"throws",
"IOException",
"{",
"// Append data specified in ranges to existing content for this",
"// resource - create a temp. file on the local f... | Handle a partial PUT.<p>
New content specified in request is appended to
existing content in oldRevisionContent (if present). This code does
not support simultaneous partial updates to the same resource.<p>
@param req the servlet request we are processing
@param range the range of the content in the file
@param path the path where to find the resource
@return the new content file with the appended data
@throws IOException if an input/output error occurs | [
"Handle",
"a",
"partial",
"PUT",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/webdav/CmsWebdavServlet.java#L2163-L2214 |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectMapper.java | ObjectMapper.buildIdentitySQL | String buildIdentitySQL(String[] pKeys) {
mTables = new Hashtable();
mColumns = new Vector();
// Get columns to select
mColumns.addElement(getPrimaryKey());
// Get tables to select (and join) from and their joins
tableJoins(null, false);
for (int i = 0; i < pKeys.length; i++) {
tableJoins(getColumn(pKeys[i]), true);
}
// All data read, build SQL query string
return "SELECT " + getPrimaryKey() + " " + buildFromClause()
+ buildWhereClause();
} | java | String buildIdentitySQL(String[] pKeys) {
mTables = new Hashtable();
mColumns = new Vector();
// Get columns to select
mColumns.addElement(getPrimaryKey());
// Get tables to select (and join) from and their joins
tableJoins(null, false);
for (int i = 0; i < pKeys.length; i++) {
tableJoins(getColumn(pKeys[i]), true);
}
// All data read, build SQL query string
return "SELECT " + getPrimaryKey() + " " + buildFromClause()
+ buildWhereClause();
} | [
"String",
"buildIdentitySQL",
"(",
"String",
"[",
"]",
"pKeys",
")",
"{",
"mTables",
"=",
"new",
"Hashtable",
"(",
")",
";",
"mColumns",
"=",
"new",
"Vector",
"(",
")",
";",
"// Get columns to select\r",
"mColumns",
".",
"addElement",
"(",
"getPrimaryKey",
"... | Creates a SQL query string to get the primary keys for this
ObjectMapper. | [
"Creates",
"a",
"SQL",
"query",
"string",
"to",
"get",
"the",
"primary",
"keys",
"for",
"this",
"ObjectMapper",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectMapper.java#L462-L479 |
exoplatform/jcr | exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/WebDavServiceImpl.java | WebDavServiceImpl.isAllowedPath | private boolean isAllowedPath(String workspaceName, String path)
{
if(pattern == null)
return true;
Matcher matcher= pattern.matcher(workspaceName+":"+path);
if(!matcher.find())
{
log.warn("Access not allowed to webdav resource {}",path);
return false;
}
return true;
} | java | private boolean isAllowedPath(String workspaceName, String path)
{
if(pattern == null)
return true;
Matcher matcher= pattern.matcher(workspaceName+":"+path);
if(!matcher.find())
{
log.warn("Access not allowed to webdav resource {}",path);
return false;
}
return true;
} | [
"private",
"boolean",
"isAllowedPath",
"(",
"String",
"workspaceName",
",",
"String",
"path",
")",
"{",
"if",
"(",
"pattern",
"==",
"null",
")",
"return",
"true",
";",
"Matcher",
"matcher",
"=",
"pattern",
".",
"matcher",
"(",
"workspaceName",
"+",
"\":\"",
... | Check resource access allowed
@param workspaceName
@param path
@return true if access is allowed otherwise false | [
"Check",
"resource",
"access",
"allowed"
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/WebDavServiceImpl.java#L1508-L1519 |
m-m-m/util | core/src/main/java/net/sf/mmm/util/lang/api/StringTokenizer.java | StringTokenizer.containsDelimiter | private static boolean containsDelimiter(char[] escape, char[] delimiters) {
for (char c : escape) {
for (char d : delimiters) {
if (d == c) {
return true;
}
}
}
return false;
} | java | private static boolean containsDelimiter(char[] escape, char[] delimiters) {
for (char c : escape) {
for (char d : delimiters) {
if (d == c) {
return true;
}
}
}
return false;
} | [
"private",
"static",
"boolean",
"containsDelimiter",
"(",
"char",
"[",
"]",
"escape",
",",
"char",
"[",
"]",
"delimiters",
")",
"{",
"for",
"(",
"char",
"c",
":",
"escape",
")",
"{",
"for",
"(",
"char",
"d",
":",
"delimiters",
")",
"{",
"if",
"(",
... | This method checks that the given {@code escape} sequence does NOT contain any of the {@code delimiters}.
@param escape is the escape-sequence to check.
@param delimiters are the delimiters that should NOT be contained in {@code escape}.
@return {@code true} if {@code escape} contains a character of {@code delimiters}, {@code false} otherwise. | [
"This",
"method",
"checks",
"that",
"the",
"given",
"{",
"@code",
"escape",
"}",
"sequence",
"does",
"NOT",
"contain",
"any",
"of",
"the",
"{",
"@code",
"delimiters",
"}",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/core/src/main/java/net/sf/mmm/util/lang/api/StringTokenizer.java#L159-L169 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/ManagedPropertyPersistenceHelper.java | ManagedPropertyPersistenceHelper.generateFieldSerialize | public static void generateFieldSerialize(BindTypeContext context, PersistType persistType, BindProperty property, Modifier... modifiers) {
Converter<String, String> format = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
String methodName = "serialize" + format.convert(property.getName());
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName).addJavadoc("for attribute $L serialization\n", property.getName()).addParameter(ParameterSpec.builder(typeName(property.getElement()), "value").build())
.addModifiers(modifiers);
switch (persistType) {
case STRING:
methodBuilder.returns(className(String.class));
break;
case BYTE:
methodBuilder.returns(TypeUtility.arrayTypeName(Byte.TYPE));
break;
}
// if property type is byte[], return directly the value
if (ArrayTypeName.of(Byte.TYPE).equals(property.getPropertyType().getTypeName()) && persistType == PersistType.BYTE) {
methodBuilder.addStatement("return value");
} else {
methodBuilder.beginControlFlow("if (value==null)");
methodBuilder.addStatement("return null");
methodBuilder.endControlFlow();
methodBuilder.addStatement("$T context=$T.jsonBind()", KriptonJsonContext.class, KriptonBinder.class);
methodBuilder.beginControlFlow("try ($T stream=new $T(); $T wrapper=context.createSerializer(stream))", KriptonByteArrayOutputStream.class, KriptonByteArrayOutputStream.class,
JacksonWrapperSerializer.class);
methodBuilder.addStatement("$T jacksonSerializer=wrapper.jacksonGenerator", JsonGenerator.class);
if (!property.isBindedObject()) {
methodBuilder.addStatement("jacksonSerializer.writeStartObject()");
}
methodBuilder.addStatement("int fieldCount=0");
BindTransform bindTransform = BindTransformer.lookup(property);
String serializerName = "jacksonSerializer";
bindTransform.generateSerializeOnJackson(context, methodBuilder, serializerName, null, "value", property);
if (!property.isBindedObject()) {
methodBuilder.addStatement("jacksonSerializer.writeEndObject()");
}
methodBuilder.addStatement("jacksonSerializer.flush()");
switch (persistType) {
case STRING:
methodBuilder.addStatement("return stream.toString()");
break;
case BYTE:
methodBuilder.addStatement("return stream.toByteArray()");
break;
}
methodBuilder.nextControlFlow("catch($T e)", Exception.class);
methodBuilder.addStatement("throw(new $T(e.getMessage()))", KriptonRuntimeException.class);
methodBuilder.endControlFlow();
}
context.builder.addMethod(methodBuilder.build());
} | java | public static void generateFieldSerialize(BindTypeContext context, PersistType persistType, BindProperty property, Modifier... modifiers) {
Converter<String, String> format = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
String methodName = "serialize" + format.convert(property.getName());
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName).addJavadoc("for attribute $L serialization\n", property.getName()).addParameter(ParameterSpec.builder(typeName(property.getElement()), "value").build())
.addModifiers(modifiers);
switch (persistType) {
case STRING:
methodBuilder.returns(className(String.class));
break;
case BYTE:
methodBuilder.returns(TypeUtility.arrayTypeName(Byte.TYPE));
break;
}
// if property type is byte[], return directly the value
if (ArrayTypeName.of(Byte.TYPE).equals(property.getPropertyType().getTypeName()) && persistType == PersistType.BYTE) {
methodBuilder.addStatement("return value");
} else {
methodBuilder.beginControlFlow("if (value==null)");
methodBuilder.addStatement("return null");
methodBuilder.endControlFlow();
methodBuilder.addStatement("$T context=$T.jsonBind()", KriptonJsonContext.class, KriptonBinder.class);
methodBuilder.beginControlFlow("try ($T stream=new $T(); $T wrapper=context.createSerializer(stream))", KriptonByteArrayOutputStream.class, KriptonByteArrayOutputStream.class,
JacksonWrapperSerializer.class);
methodBuilder.addStatement("$T jacksonSerializer=wrapper.jacksonGenerator", JsonGenerator.class);
if (!property.isBindedObject()) {
methodBuilder.addStatement("jacksonSerializer.writeStartObject()");
}
methodBuilder.addStatement("int fieldCount=0");
BindTransform bindTransform = BindTransformer.lookup(property);
String serializerName = "jacksonSerializer";
bindTransform.generateSerializeOnJackson(context, methodBuilder, serializerName, null, "value", property);
if (!property.isBindedObject()) {
methodBuilder.addStatement("jacksonSerializer.writeEndObject()");
}
methodBuilder.addStatement("jacksonSerializer.flush()");
switch (persistType) {
case STRING:
methodBuilder.addStatement("return stream.toString()");
break;
case BYTE:
methodBuilder.addStatement("return stream.toByteArray()");
break;
}
methodBuilder.nextControlFlow("catch($T e)", Exception.class);
methodBuilder.addStatement("throw(new $T(e.getMessage()))", KriptonRuntimeException.class);
methodBuilder.endControlFlow();
}
context.builder.addMethod(methodBuilder.build());
} | [
"public",
"static",
"void",
"generateFieldSerialize",
"(",
"BindTypeContext",
"context",
",",
"PersistType",
"persistType",
",",
"BindProperty",
"property",
",",
"Modifier",
"...",
"modifiers",
")",
"{",
"Converter",
"<",
"String",
",",
"String",
">",
"format",
"=... | generates code to manage field serialization.
@param context the context
@param persistType the persist type
@param property the property
@param modifiers the modifiers | [
"generates",
"code",
"to",
"manage",
"field",
"serialization",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/ManagedPropertyPersistenceHelper.java#L101-L163 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountsInner.java | IntegrationAccountsInner.getCallbackUrlAsync | public Observable<CallbackUrlInner> getCallbackUrlAsync(String resourceGroupName, String integrationAccountName, GetCallbackUrlParameters parameters) {
return getCallbackUrlWithServiceResponseAsync(resourceGroupName, integrationAccountName, parameters).map(new Func1<ServiceResponse<CallbackUrlInner>, CallbackUrlInner>() {
@Override
public CallbackUrlInner call(ServiceResponse<CallbackUrlInner> response) {
return response.body();
}
});
} | java | public Observable<CallbackUrlInner> getCallbackUrlAsync(String resourceGroupName, String integrationAccountName, GetCallbackUrlParameters parameters) {
return getCallbackUrlWithServiceResponseAsync(resourceGroupName, integrationAccountName, parameters).map(new Func1<ServiceResponse<CallbackUrlInner>, CallbackUrlInner>() {
@Override
public CallbackUrlInner call(ServiceResponse<CallbackUrlInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"CallbackUrlInner",
">",
"getCallbackUrlAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"GetCallbackUrlParameters",
"parameters",
")",
"{",
"return",
"getCallbackUrlWithServiceResponseAsync",
"(",
"resourc... | Gets the integration account callback URL.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param parameters The callback URL parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CallbackUrlInner object | [
"Gets",
"the",
"integration",
"account",
"callback",
"URL",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountsInner.java#L965-L972 |
mygreen/excel-cellformatter | src/main/java/com/github/mygreen/cellformatter/JXLCellFormatter.java | JXLCellFormatter.formatAsString | public String formatAsString(final Cell cell, final boolean isStartDate1904) {
return formatAsString(cell, Locale.getDefault(), isStartDate1904);
} | java | public String formatAsString(final Cell cell, final boolean isStartDate1904) {
return formatAsString(cell, Locale.getDefault(), isStartDate1904);
} | [
"public",
"String",
"formatAsString",
"(",
"final",
"Cell",
"cell",
",",
"final",
"boolean",
"isStartDate1904",
")",
"{",
"return",
"formatAsString",
"(",
"cell",
",",
"Locale",
".",
"getDefault",
"(",
")",
",",
"isStartDate1904",
")",
";",
"}"
] | セルの値をフォーマットし、文字列として取得する
@param cell フォーマット対象のセル
@param isStartDate1904 ファイルの設定が1904年始まりかどうか。
{@link JXLUtils#isDateStart1904(jxl.Sheet)}で値を調べます。
@return フォーマットしたセルの値。
@throws IllegalArgumentException cell is null. | [
"セルの値をフォーマットし、文字列として取得する"
] | train | https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/JXLCellFormatter.java#L94-L96 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/AbstractTypeComputer.java | AbstractTypeComputer.getCommonSuperType | protected LightweightTypeReference getCommonSuperType(List<LightweightTypeReference> types, ITypeComputationState state) {
return getCommonSuperType(types, state.getReferenceOwner());
} | java | protected LightweightTypeReference getCommonSuperType(List<LightweightTypeReference> types, ITypeComputationState state) {
return getCommonSuperType(types, state.getReferenceOwner());
} | [
"protected",
"LightweightTypeReference",
"getCommonSuperType",
"(",
"List",
"<",
"LightweightTypeReference",
">",
"types",
",",
"ITypeComputationState",
"state",
")",
"{",
"return",
"getCommonSuperType",
"(",
"types",
",",
"state",
".",
"getReferenceOwner",
"(",
")",
... | Computes the common super type for the given list of types. The list may not be empty. | [
"Computes",
"the",
"common",
"super",
"type",
"for",
"the",
"given",
"list",
"of",
"types",
".",
"The",
"list",
"may",
"not",
"be",
"empty",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/AbstractTypeComputer.java#L125-L127 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/bmr/BmrClient.java | BmrClient.listSteps | public ListStepsResponse listSteps(String clusterId, String marker, int maxKeys) {
return listSteps(new ListStepsRequest().withClusterId(clusterId)
.withMaxKeys(maxKeys)
.withMarker(marker));
} | java | public ListStepsResponse listSteps(String clusterId, String marker, int maxKeys) {
return listSteps(new ListStepsRequest().withClusterId(clusterId)
.withMaxKeys(maxKeys)
.withMarker(marker));
} | [
"public",
"ListStepsResponse",
"listSteps",
"(",
"String",
"clusterId",
",",
"String",
"marker",
",",
"int",
"maxKeys",
")",
"{",
"return",
"listSteps",
"(",
"new",
"ListStepsRequest",
"(",
")",
".",
"withClusterId",
"(",
"clusterId",
")",
".",
"withMaxKeys",
... | List all the steps of the target BMR cluster.
@param clusterId The ID of the target BMR cluster.
@param marker The start record of steps.
@param maxKeys The maximum number of steps returned.
@return The response containing a list of the BMR steps owned by the cluster.
The steps' records start from the marker and the size of list is limited below maxKeys. | [
"List",
"all",
"the",
"steps",
"of",
"the",
"target",
"BMR",
"cluster",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bmr/BmrClient.java#L533-L537 |
knowm/Yank | src/main/java/org/knowm/yank/Yank.java | Yank.queryBeanSQLKey | public static <T> T queryBeanSQLKey(
String poolName, String sqlKey, Class<T> beanType, Object[] params)
throws SQLStatementNotFoundException, YankSQLException {
String sql = YANK_POOL_MANAGER.getMergedSqlProperties().getProperty(sqlKey);
if (sql == null || sql.equalsIgnoreCase("")) {
throw new SQLStatementNotFoundException();
} else {
return queryBean(poolName, sql, beanType, params);
}
} | java | public static <T> T queryBeanSQLKey(
String poolName, String sqlKey, Class<T> beanType, Object[] params)
throws SQLStatementNotFoundException, YankSQLException {
String sql = YANK_POOL_MANAGER.getMergedSqlProperties().getProperty(sqlKey);
if (sql == null || sql.equalsIgnoreCase("")) {
throw new SQLStatementNotFoundException();
} else {
return queryBean(poolName, sql, beanType, params);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"queryBeanSQLKey",
"(",
"String",
"poolName",
",",
"String",
"sqlKey",
",",
"Class",
"<",
"T",
">",
"beanType",
",",
"Object",
"[",
"]",
"params",
")",
"throws",
"SQLStatementNotFoundException",
",",
"YankSQLException",
... | Return just one Bean given a SQL Key using an SQL statement matching the sqlKey String in a
properties file loaded via Yank.addSQLStatements(...). If more than one row match the query,
only the first row is returned.
@param poolName The name of the connection pool to query against
@param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement
value
@param params The replacement parameters
@param beanType The Class of the desired return Object matching the table
@return The Object
@throws SQLStatementNotFoundException if an SQL statement could not be found for the given
sqlKey String | [
"Return",
"just",
"one",
"Bean",
"given",
"a",
"SQL",
"Key",
"using",
"an",
"SQL",
"statement",
"matching",
"the",
"sqlKey",
"String",
"in",
"a",
"properties",
"file",
"loaded",
"via",
"Yank",
".",
"addSQLStatements",
"(",
"...",
")",
".",
"If",
"more",
... | train | https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L358-L368 |
adorsys/hbci4java-adorsys | src/main/java/org/kapott/cryptalgs/PKCS1_PSS.java | PKCS1_PSS.emsa_pss_verify | public static boolean emsa_pss_verify(SignatureParamSpec spec, byte[] msg, byte[] EM, int emBits) {
int emLen = emBits >> 3;
if ((emBits & 7) != 0) {
emLen++;
}
byte[] mHash = hash(spec, msg);
// System.out.println("mHash: "+Utils.bytes2String(mHash));
MessageDigest dig = getMessageDigest(spec);
int hLen = dig.getDigestLength();
// System.out.println("hLen: "+hLen);
int sLen = hLen;
if (EM[EM.length - 1] != (byte) 0xBC) {
// System.out.println("no BC at the end");
return false;
}
byte[] maskedDB = new byte[emLen - hLen - 1];
byte[] H = new byte[hLen];
System.arraycopy(EM, 0, maskedDB, 0, emLen - hLen - 1);
System.arraycopy(EM, emLen - hLen - 1, H, 0, hLen);
// TODO: verify if first X bits of maskedDB are zero
byte[] dbMask = mgf1(spec, H, emLen - hLen - 1);
byte[] DB = xor_os(maskedDB, dbMask);
// set leftmost X bits of DB to zero
int tooMuchBits = (emLen << 3) - emBits;
byte mask = (byte) (0xFF >>> tooMuchBits);
DB[0] &= mask;
// TODO: another consistency check
byte[] salt = new byte[sLen];
System.arraycopy(DB, DB.length - sLen, salt, 0, sLen);
byte[] zeroes = new byte[8];
byte[] m2 = concat(concat(zeroes, mHash), salt);
byte[] H2 = hash(spec, m2);
return Arrays.equals(H, H2);
} | java | public static boolean emsa_pss_verify(SignatureParamSpec spec, byte[] msg, byte[] EM, int emBits) {
int emLen = emBits >> 3;
if ((emBits & 7) != 0) {
emLen++;
}
byte[] mHash = hash(spec, msg);
// System.out.println("mHash: "+Utils.bytes2String(mHash));
MessageDigest dig = getMessageDigest(spec);
int hLen = dig.getDigestLength();
// System.out.println("hLen: "+hLen);
int sLen = hLen;
if (EM[EM.length - 1] != (byte) 0xBC) {
// System.out.println("no BC at the end");
return false;
}
byte[] maskedDB = new byte[emLen - hLen - 1];
byte[] H = new byte[hLen];
System.arraycopy(EM, 0, maskedDB, 0, emLen - hLen - 1);
System.arraycopy(EM, emLen - hLen - 1, H, 0, hLen);
// TODO: verify if first X bits of maskedDB are zero
byte[] dbMask = mgf1(spec, H, emLen - hLen - 1);
byte[] DB = xor_os(maskedDB, dbMask);
// set leftmost X bits of DB to zero
int tooMuchBits = (emLen << 3) - emBits;
byte mask = (byte) (0xFF >>> tooMuchBits);
DB[0] &= mask;
// TODO: another consistency check
byte[] salt = new byte[sLen];
System.arraycopy(DB, DB.length - sLen, salt, 0, sLen);
byte[] zeroes = new byte[8];
byte[] m2 = concat(concat(zeroes, mHash), salt);
byte[] H2 = hash(spec, m2);
return Arrays.equals(H, H2);
} | [
"public",
"static",
"boolean",
"emsa_pss_verify",
"(",
"SignatureParamSpec",
"spec",
",",
"byte",
"[",
"]",
"msg",
",",
"byte",
"[",
"]",
"EM",
",",
"int",
"emBits",
")",
"{",
"int",
"emLen",
"=",
"emBits",
">>",
"3",
";",
"if",
"(",
"(",
"emBits",
"... | --- stuff from the PKCS#1-PSS specification --------------------------- | [
"---",
"stuff",
"from",
"the",
"PKCS#1",
"-",
"PSS",
"specification",
"---------------------------"
] | train | https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/cryptalgs/PKCS1_PSS.java#L215-L259 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/synthetic/SyntheticPropertyList.java | SyntheticPropertyList.addProperty | public void addProperty(String propertyName, Direction direction) {
if (propertyName == null) {
throw new IllegalArgumentException();
}
if (direction == null) {
direction = Direction.UNSPECIFIED;
}
if (direction != Direction.UNSPECIFIED) {
if (propertyName.length() > 0) {
if (propertyName.charAt(0) == '-' || propertyName.charAt(0) == '+') {
// Overrule the direction.
propertyName = propertyName.substring(1);
}
}
propertyName = direction.toCharacter() + propertyName;
}
mPropertyList.add(propertyName);
} | java | public void addProperty(String propertyName, Direction direction) {
if (propertyName == null) {
throw new IllegalArgumentException();
}
if (direction == null) {
direction = Direction.UNSPECIFIED;
}
if (direction != Direction.UNSPECIFIED) {
if (propertyName.length() > 0) {
if (propertyName.charAt(0) == '-' || propertyName.charAt(0) == '+') {
// Overrule the direction.
propertyName = propertyName.substring(1);
}
}
propertyName = direction.toCharacter() + propertyName;
}
mPropertyList.add(propertyName);
} | [
"public",
"void",
"addProperty",
"(",
"String",
"propertyName",
",",
"Direction",
"direction",
")",
"{",
"if",
"(",
"propertyName",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"if",
"(",
"direction",
"==",
"null",
... | Adds a property to this index, with the specified direction.
@param propertyName name of property to add to index
@param direction optional direction of property | [
"Adds",
"a",
"property",
"to",
"this",
"index",
"with",
"the",
"specified",
"direction",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/synthetic/SyntheticPropertyList.java#L56-L75 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/core/WaybackRequest.java | WaybackRequest.createUrlQueryRequest | public static WaybackRequest createUrlQueryRequest(String url, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setUrlQueryRequest();
r.setRequestUrl(url);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | java | public static WaybackRequest createUrlQueryRequest(String url, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setUrlQueryRequest();
r.setRequestUrl(url);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | [
"public",
"static",
"WaybackRequest",
"createUrlQueryRequest",
"(",
"String",
"url",
",",
"String",
"start",
",",
"String",
"end",
")",
"{",
"WaybackRequest",
"r",
"=",
"new",
"WaybackRequest",
"(",
")",
";",
"r",
".",
"setUrlQueryRequest",
"(",
")",
";",
"r... | create WaybackRequet for URL-Query request.
@param url target URL
@param start start timestamp (14-digit)
@param end end timestamp (14-digit)
@return WaybackRequest | [
"create",
"WaybackRequet",
"for",
"URL",
"-",
"Query",
"request",
"."
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/core/WaybackRequest.java#L469-L476 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java | ClassUtils.getReadMethod | public static Method getReadMethod(Class<?> clazz, String propertyName) throws NoSuchMethodError
{
String propertyNameCapitalized = capitalize(propertyName);
try
{
return clazz.getMethod("get" + propertyNameCapitalized);
}
catch (Exception e)
{
try
{
return clazz.getMethod("is" + propertyNameCapitalized);
}
catch (Exception e1)
{
throw new NoSuchMethodError("Could not find getter (getXX or isXXX) for property: "
+ propertyName);
}
}
} | java | public static Method getReadMethod(Class<?> clazz, String propertyName) throws NoSuchMethodError
{
String propertyNameCapitalized = capitalize(propertyName);
try
{
return clazz.getMethod("get" + propertyNameCapitalized);
}
catch (Exception e)
{
try
{
return clazz.getMethod("is" + propertyNameCapitalized);
}
catch (Exception e1)
{
throw new NoSuchMethodError("Could not find getter (getXX or isXXX) for property: "
+ propertyName);
}
}
} | [
"public",
"static",
"Method",
"getReadMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"propertyName",
")",
"throws",
"NoSuchMethodError",
"{",
"String",
"propertyNameCapitalized",
"=",
"capitalize",
"(",
"propertyName",
")",
";",
"try",
"{",
"retur... | Lookup the getter method for the given property. This can be a getXXX() or a isXXX() method.
@param clazz
type which contains the property.
@param propertyName
name of the property.
@return a Method with read-access for the property. | [
"Lookup",
"the",
"getter",
"method",
"for",
"the",
"given",
"property",
".",
"This",
"can",
"be",
"a",
"getXXX",
"()",
"or",
"a",
"isXXX",
"()",
"method",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java#L47-L66 |
apiman/apiman | manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java | EsMarshalling.unmarshallContractSummary | public static ContractSummaryBean unmarshallContractSummary(Map<String, Object> source) {
if (source == null) {
return null;
}
ContractSummaryBean bean = new ContractSummaryBean();
bean.setContractId(asLong(source.get("id")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setClientOrganizationId(asString(source.get("clientOrganizationId")));
bean.setClientOrganizationName(asString(source.get("clientOrganizationName")));
bean.setClientId(asString(source.get("clientId")));
bean.setClientName(asString(source.get("clientName")));
bean.setClientVersion(asString(source.get("clientVersion")));
bean.setApiOrganizationId(asString(source.get("apiOrganizationId")));
bean.setApiOrganizationName(asString(source.get("apiOrganizationName")));
bean.setApiId(asString(source.get("apiId")));
bean.setApiName(asString(source.get("apiName")));
bean.setApiVersion(asString(source.get("apiVersion")));
bean.setApiDescription(asString(source.get("apiDescription")));
bean.setPlanName(asString(source.get("planName")));
bean.setPlanId(asString(source.get("planId")));
bean.setPlanVersion(asString(source.get("planVersion")));
postMarshall(bean);
return bean;
} | java | public static ContractSummaryBean unmarshallContractSummary(Map<String, Object> source) {
if (source == null) {
return null;
}
ContractSummaryBean bean = new ContractSummaryBean();
bean.setContractId(asLong(source.get("id")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setClientOrganizationId(asString(source.get("clientOrganizationId")));
bean.setClientOrganizationName(asString(source.get("clientOrganizationName")));
bean.setClientId(asString(source.get("clientId")));
bean.setClientName(asString(source.get("clientName")));
bean.setClientVersion(asString(source.get("clientVersion")));
bean.setApiOrganizationId(asString(source.get("apiOrganizationId")));
bean.setApiOrganizationName(asString(source.get("apiOrganizationName")));
bean.setApiId(asString(source.get("apiId")));
bean.setApiName(asString(source.get("apiName")));
bean.setApiVersion(asString(source.get("apiVersion")));
bean.setApiDescription(asString(source.get("apiDescription")));
bean.setPlanName(asString(source.get("planName")));
bean.setPlanId(asString(source.get("planId")));
bean.setPlanVersion(asString(source.get("planVersion")));
postMarshall(bean);
return bean;
} | [
"public",
"static",
"ContractSummaryBean",
"unmarshallContractSummary",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"source",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"ContractSummaryBean",
"bean",
"=",
"new",
"Co... | Unmarshals the given map source into a bean.
@param source the source
@return the contract summary | [
"Unmarshals",
"the",
"given",
"map",
"source",
"into",
"a",
"bean",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L774-L797 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/NetworkUtils.java | NetworkUtils.setLearningRate | public static void setLearningRate(MultiLayerNetwork net, int layerNumber, ISchedule lrSchedule) {
setLearningRate(net, layerNumber, Double.NaN, lrSchedule, true);
} | java | public static void setLearningRate(MultiLayerNetwork net, int layerNumber, ISchedule lrSchedule) {
setLearningRate(net, layerNumber, Double.NaN, lrSchedule, true);
} | [
"public",
"static",
"void",
"setLearningRate",
"(",
"MultiLayerNetwork",
"net",
",",
"int",
"layerNumber",
",",
"ISchedule",
"lrSchedule",
")",
"{",
"setLearningRate",
"(",
"net",
",",
"layerNumber",
",",
"Double",
".",
"NaN",
",",
"lrSchedule",
",",
"true",
"... | Set the learning rate schedule for a single layer in the network to the specified value.<br>
Note also that {@link #setLearningRate(MultiLayerNetwork, ISchedule)} should also be used in preference, when all layers need
to be set to a new LR schedule.<br>
This schedule will replace any/all existing schedules, and also any fixed learning rate values.<br>
Note also that the iteration/epoch counts will <i>not</i> be reset. Use {@link MultiLayerConfiguration#setIterationCount(int)}
and {@link MultiLayerConfiguration#setEpochCount(int)} if this is required
@param layerNumber Number of the layer to set the LR schedule for
@param lrSchedule New learning rate for a single layer | [
"Set",
"the",
"learning",
"rate",
"schedule",
"for",
"a",
"single",
"layer",
"in",
"the",
"network",
"to",
"the",
"specified",
"value",
".",
"<br",
">",
"Note",
"also",
"that",
"{",
"@link",
"#setLearningRate",
"(",
"MultiLayerNetwork",
"ISchedule",
")",
"}"... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/NetworkUtils.java#L191-L193 |
DiUS/pact-jvm | pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonRootValue.java | PactDslJsonRootValue.matchUrl | public PactDslJsonRootValue matchUrl(String basePath, Object... pathFragments) {
UrlMatcherSupport urlMatcher = new UrlMatcherSupport(basePath, Arrays.asList(pathFragments));
PactDslJsonRootValue value = new PactDslJsonRootValue();
value.setValue(urlMatcher.getExampleValue());
value.setMatcher(value.regexp(urlMatcher.getRegexExpression()));
return value;
} | java | public PactDslJsonRootValue matchUrl(String basePath, Object... pathFragments) {
UrlMatcherSupport urlMatcher = new UrlMatcherSupport(basePath, Arrays.asList(pathFragments));
PactDslJsonRootValue value = new PactDslJsonRootValue();
value.setValue(urlMatcher.getExampleValue());
value.setMatcher(value.regexp(urlMatcher.getRegexExpression()));
return value;
} | [
"public",
"PactDslJsonRootValue",
"matchUrl",
"(",
"String",
"basePath",
",",
"Object",
"...",
"pathFragments",
")",
"{",
"UrlMatcherSupport",
"urlMatcher",
"=",
"new",
"UrlMatcherSupport",
"(",
"basePath",
",",
"Arrays",
".",
"asList",
"(",
"pathFragments",
")",
... | Matches a URL that is composed of a base path and a sequence of path expressions
@param basePath The base path for the URL (like "http://localhost:8080/") which will be excluded from the matching
@param pathFragments Series of path fragments to match on. These can be strings or regular expressions. | [
"Matches",
"a",
"URL",
"that",
"is",
"composed",
"of",
"a",
"base",
"path",
"and",
"a",
"sequence",
"of",
"path",
"expressions"
] | train | https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonRootValue.java#L793-L799 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java | Calc.plus | public static final void plus(Structure s, Matrix matrix){
AtomIterator iter = new AtomIterator(s) ;
Atom oldAtom = null;
Atom rotOldAtom = null;
while (iter.hasNext()) {
Atom atom = null ;
atom = iter.next() ;
try {
if ( oldAtom != null){
logger.debug("before {}", getDistance(oldAtom,atom));
}
} catch (Exception e){
logger.error("Exception: ", e);
}
oldAtom = (Atom)atom.clone();
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double[][] ad = new double[][]{{x,y,z}};
Matrix am = new Matrix(ad);
Matrix na = am.plus(matrix);
double[] coords = new double[3] ;
coords[0] = na.get(0,0);
coords[1] = na.get(0,1);
coords[2] = na.get(0,2);
atom.setCoords(coords);
try {
if ( rotOldAtom != null){
logger.debug("after {}", getDistance(rotOldAtom,atom));
}
} catch (Exception e){
logger.error("Exception: ", e);
}
rotOldAtom = (Atom) atom.clone();
}
} | java | public static final void plus(Structure s, Matrix matrix){
AtomIterator iter = new AtomIterator(s) ;
Atom oldAtom = null;
Atom rotOldAtom = null;
while (iter.hasNext()) {
Atom atom = null ;
atom = iter.next() ;
try {
if ( oldAtom != null){
logger.debug("before {}", getDistance(oldAtom,atom));
}
} catch (Exception e){
logger.error("Exception: ", e);
}
oldAtom = (Atom)atom.clone();
double x = atom.getX();
double y = atom.getY() ;
double z = atom.getZ();
double[][] ad = new double[][]{{x,y,z}};
Matrix am = new Matrix(ad);
Matrix na = am.plus(matrix);
double[] coords = new double[3] ;
coords[0] = na.get(0,0);
coords[1] = na.get(0,1);
coords[2] = na.get(0,2);
atom.setCoords(coords);
try {
if ( rotOldAtom != null){
logger.debug("after {}", getDistance(rotOldAtom,atom));
}
} catch (Exception e){
logger.error("Exception: ", e);
}
rotOldAtom = (Atom) atom.clone();
}
} | [
"public",
"static",
"final",
"void",
"plus",
"(",
"Structure",
"s",
",",
"Matrix",
"matrix",
")",
"{",
"AtomIterator",
"iter",
"=",
"new",
"AtomIterator",
"(",
"s",
")",
";",
"Atom",
"oldAtom",
"=",
"null",
";",
"Atom",
"rotOldAtom",
"=",
"null",
";",
... | calculate structure + Matrix coodinates ...
@param s
the structure to operate on
@param matrix
a Matrix object | [
"calculate",
"structure",
"+",
"Matrix",
"coodinates",
"..."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java#L649-L689 |
neo4j-contrib/neo4j-apoc-procedures | src/main/java/apoc/load/Xml.java | Xml.handleTextNode | private void handleTextNode(Node node, Map<String, Object> elementMap) {
Object text = "";
int nodeType = node.getNodeType();
switch (nodeType) {
case Node.TEXT_NODE:
text = normalizeText(node.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
text = normalizeText(((CharacterData) node).getData());
break;
default:
break;
}
// If the text is valid ...
if (!StringUtils.isEmpty(text.toString())) {
// We check if we have already collected some text previously
Object previousText = elementMap.get("_text");
if (previousText != null) {
// If we just have a "_text" key than we need to collect to a List
text = Arrays.asList(previousText.toString(), text);
}
elementMap.put("_text", text);
}
} | java | private void handleTextNode(Node node, Map<String, Object> elementMap) {
Object text = "";
int nodeType = node.getNodeType();
switch (nodeType) {
case Node.TEXT_NODE:
text = normalizeText(node.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
text = normalizeText(((CharacterData) node).getData());
break;
default:
break;
}
// If the text is valid ...
if (!StringUtils.isEmpty(text.toString())) {
// We check if we have already collected some text previously
Object previousText = elementMap.get("_text");
if (previousText != null) {
// If we just have a "_text" key than we need to collect to a List
text = Arrays.asList(previousText.toString(), text);
}
elementMap.put("_text", text);
}
} | [
"private",
"void",
"handleTextNode",
"(",
"Node",
"node",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"elementMap",
")",
"{",
"Object",
"text",
"=",
"\"\"",
";",
"int",
"nodeType",
"=",
"node",
".",
"getNodeType",
"(",
")",
";",
"switch",
"(",
"node... | Handle TEXT nodes and CDATA nodes
@param node
@param elementMap | [
"Handle",
"TEXT",
"nodes",
"and",
"CDATA",
"nodes"
] | train | https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/e8386975d1c512c0e4388a1a61f5496121c04f86/src/main/java/apoc/load/Xml.java#L289-L313 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/com/read/Buffer.java | Buffer.readStringNullEnd | public String readStringNullEnd(final Charset charset) {
int initialPosition = position;
int cnt = 0;
while (remaining() > 0 && (buf[position++] != 0)) {
cnt++;
}
return new String(buf, initialPosition, cnt, charset);
} | java | public String readStringNullEnd(final Charset charset) {
int initialPosition = position;
int cnt = 0;
while (remaining() > 0 && (buf[position++] != 0)) {
cnt++;
}
return new String(buf, initialPosition, cnt, charset);
} | [
"public",
"String",
"readStringNullEnd",
"(",
"final",
"Charset",
"charset",
")",
"{",
"int",
"initialPosition",
"=",
"position",
";",
"int",
"cnt",
"=",
"0",
";",
"while",
"(",
"remaining",
"(",
")",
">",
"0",
"&&",
"(",
"buf",
"[",
"position",
"++",
... | Reads a string from the buffer, looks for a 0 to end the string.
@param charset the charset to use, for example ASCII
@return the read string | [
"Reads",
"a",
"string",
"from",
"the",
"buffer",
"looks",
"for",
"a",
"0",
"to",
"end",
"the",
"string",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/Buffer.java#L90-L97 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/locator/TokenMetadata.java | TokenMetadata.updateNormalToken | public void updateNormalToken(Token token, InetAddress endpoint)
{
updateNormalTokens(Collections.singleton(token), endpoint);
} | java | public void updateNormalToken(Token token, InetAddress endpoint)
{
updateNormalTokens(Collections.singleton(token), endpoint);
} | [
"public",
"void",
"updateNormalToken",
"(",
"Token",
"token",
",",
"InetAddress",
"endpoint",
")",
"{",
"updateNormalTokens",
"(",
"Collections",
".",
"singleton",
"(",
"token",
")",
",",
"endpoint",
")",
";",
"}"
] | Update token map with a single token/endpoint pair in normal state. | [
"Update",
"token",
"map",
"with",
"a",
"single",
"token",
"/",
"endpoint",
"pair",
"in",
"normal",
"state",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/locator/TokenMetadata.java#L150-L153 |
yanzhenjie/Album | album/src/main/java/com/yanzhenjie/album/widget/photoview/PhotoViewAttacher.java | PhotoViewAttacher.updateBaseMatrix | private void updateBaseMatrix(Drawable d) {
ImageView imageView = getImageView();
if (null == imageView || null == d) {
return;
}
final float viewWidth = getImageViewWidth(imageView);
final float viewHeight = getImageViewHeight(imageView);
final int drawableWidth = d.getIntrinsicWidth();
final int drawableHeight = d.getIntrinsicHeight();
mBaseMatrix.reset();
final float widthScale = viewWidth / drawableWidth;
final float heightScale = viewHeight / drawableHeight;
if (mScaleType == ScaleType.CENTER) {
mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2F, (viewHeight - drawableHeight) / 2F);
} else if (mScaleType == ScaleType.CENTER_CROP) {
float scale = Math.max(widthScale, heightScale);
mBaseMatrix.postScale(scale, scale);
mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
(viewHeight - drawableHeight * scale) / 2F);
} else if (mScaleType == ScaleType.CENTER_INSIDE) {
float scale = Math.min(1.0f, Math.min(widthScale, heightScale));
mBaseMatrix.postScale(scale, scale);
mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
(viewHeight - drawableHeight * scale) / 2F);
} else {
RectF mTempSrc = new RectF(0, 0, drawableWidth, drawableHeight);
RectF mTempDst = new RectF(0, 0, viewWidth, viewHeight);
if ((int)mBaseRotation % 180 != 0) {
mTempSrc = new RectF(0, 0, drawableHeight, drawableWidth);
}
switch (mScaleType) {
case FIT_CENTER:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);
break;
case FIT_START:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);
break;
case FIT_END:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);
break;
case FIT_XY:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL);
break;
default:
break;
}
}
resetMatrix();
} | java | private void updateBaseMatrix(Drawable d) {
ImageView imageView = getImageView();
if (null == imageView || null == d) {
return;
}
final float viewWidth = getImageViewWidth(imageView);
final float viewHeight = getImageViewHeight(imageView);
final int drawableWidth = d.getIntrinsicWidth();
final int drawableHeight = d.getIntrinsicHeight();
mBaseMatrix.reset();
final float widthScale = viewWidth / drawableWidth;
final float heightScale = viewHeight / drawableHeight;
if (mScaleType == ScaleType.CENTER) {
mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2F, (viewHeight - drawableHeight) / 2F);
} else if (mScaleType == ScaleType.CENTER_CROP) {
float scale = Math.max(widthScale, heightScale);
mBaseMatrix.postScale(scale, scale);
mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
(viewHeight - drawableHeight * scale) / 2F);
} else if (mScaleType == ScaleType.CENTER_INSIDE) {
float scale = Math.min(1.0f, Math.min(widthScale, heightScale));
mBaseMatrix.postScale(scale, scale);
mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
(viewHeight - drawableHeight * scale) / 2F);
} else {
RectF mTempSrc = new RectF(0, 0, drawableWidth, drawableHeight);
RectF mTempDst = new RectF(0, 0, viewWidth, viewHeight);
if ((int)mBaseRotation % 180 != 0) {
mTempSrc = new RectF(0, 0, drawableHeight, drawableWidth);
}
switch (mScaleType) {
case FIT_CENTER:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);
break;
case FIT_START:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);
break;
case FIT_END:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);
break;
case FIT_XY:
mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL);
break;
default:
break;
}
}
resetMatrix();
} | [
"private",
"void",
"updateBaseMatrix",
"(",
"Drawable",
"d",
")",
"{",
"ImageView",
"imageView",
"=",
"getImageView",
"(",
")",
";",
"if",
"(",
"null",
"==",
"imageView",
"||",
"null",
"==",
"d",
")",
"{",
"return",
";",
"}",
"final",
"float",
"viewWidth... | Calculate Matrix for FIT_CENTER
@param d - Drawable being displayed | [
"Calculate",
"Matrix",
"for",
"FIT_CENTER"
] | train | https://github.com/yanzhenjie/Album/blob/b17506440d32909d42aba41f6a388041a25c8363/album/src/main/java/com/yanzhenjie/album/widget/photoview/PhotoViewAttacher.java#L838-L900 |
calimero-project/calimero-core | src/tuwien/auto/calimero/knxnetip/util/Srp.java | Srp.withDeviceDescription | public static Srp withDeviceDescription(final int descriptionType, final int... additionalDescriptionTypes) {
final ByteBuffer buffer = ByteBuffer.allocate(additionalDescriptionTypes.length + 1);
for (final int dt : additionalDescriptionTypes)
buffer.put((byte) dt);
buffer.put((byte) descriptionType);
return new Srp(Type.RequestDibs, true, buffer.array());
}
/**
* Returns the structure length of this SRP in bytes.
*
* @return structure length as unsigned byte
*/
public final int getStructLength() {
return size;
}
/**
* Returns the type of this SRP.
* <p>
* The type specifies which kind of search request parameter information is contained in
* the SRP.
*
* @return search request parameter type (see {@link Type})
*/
public final Srp.Type getType() {
return type;
}
/**
* Returns the mandatory flag of this SRP.
*
* @return <code>true</code> if the mandatory bit is set, <code>false</code> otherwise
*/
public final boolean isMandatory() {
return mandatory;
}
/**
* Returns a copy of the data field.
* <p>
* Data starts at offset 2 in the SRP structure.
*
* @return byte array with SRP data, can be empty
*/
public final byte[] getData() {
return data.clone();
}
/**
* Returns the byte representation of the whole SRP structure.
*
* @return byte array containing the SRP structure
*/
public final byte[] toByteArray() {
final byte[] buf = new byte[size];
buf[0] = (byte) size;
buf[1] = (byte) (mandatory ? 0x80 : 0x00);
buf[1] |= (byte) (type.getValue() & 0x07);
if (data.length > 0)
System.arraycopy(data, 0, buf, SrpHeaderSize, data.length);
return buf;
}
} | java | public static Srp withDeviceDescription(final int descriptionType, final int... additionalDescriptionTypes) {
final ByteBuffer buffer = ByteBuffer.allocate(additionalDescriptionTypes.length + 1);
for (final int dt : additionalDescriptionTypes)
buffer.put((byte) dt);
buffer.put((byte) descriptionType);
return new Srp(Type.RequestDibs, true, buffer.array());
}
/**
* Returns the structure length of this SRP in bytes.
*
* @return structure length as unsigned byte
*/
public final int getStructLength() {
return size;
}
/**
* Returns the type of this SRP.
* <p>
* The type specifies which kind of search request parameter information is contained in
* the SRP.
*
* @return search request parameter type (see {@link Type})
*/
public final Srp.Type getType() {
return type;
}
/**
* Returns the mandatory flag of this SRP.
*
* @return <code>true</code> if the mandatory bit is set, <code>false</code> otherwise
*/
public final boolean isMandatory() {
return mandatory;
}
/**
* Returns a copy of the data field.
* <p>
* Data starts at offset 2 in the SRP structure.
*
* @return byte array with SRP data, can be empty
*/
public final byte[] getData() {
return data.clone();
}
/**
* Returns the byte representation of the whole SRP structure.
*
* @return byte array containing the SRP structure
*/
public final byte[] toByteArray() {
final byte[] buf = new byte[size];
buf[0] = (byte) size;
buf[1] = (byte) (mandatory ? 0x80 : 0x00);
buf[1] |= (byte) (type.getValue() & 0x07);
if (data.length > 0)
System.arraycopy(data, 0, buf, SrpHeaderSize, data.length);
return buf;
}
} | [
"public",
"static",
"Srp",
"withDeviceDescription",
"(",
"final",
"int",
"descriptionType",
",",
"final",
"int",
"...",
"additionalDescriptionTypes",
")",
"{",
"final",
"ByteBuffer",
"buffer",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"additionalDescriptionTypes",
".",... | Creates a search request parameter block with a set of description types to indicate a KNXnet/IP router
or server to include corresponding DIBs in the search response. The mandatory flag of the SRP is not set.
@param descriptionType the description type used in the in the search request parameter block
@param additionalDescriptionTypes additional description types used in the in the search request parameter block
@return search request parameter block with a set of description types | [
"Creates",
"a",
"search",
"request",
"parameter",
"block",
"with",
"a",
"set",
"of",
"description",
"types",
"to",
"indicate",
"a",
"KNXnet",
"/",
"IP",
"router",
"or",
"server",
"to",
"include",
"corresponding",
"DIBs",
"in",
"the",
"search",
"response",
".... | train | https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/knxnetip/util/Srp.java#L225-L289 |
jcuda/jnvgraph | JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java | JNvgraph.nvgraphGetGraphStructure | public static int nvgraphGetGraphStructure(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
Object topologyData,
int[] TType)
{
return checkResult(nvgraphGetGraphStructureNative(handle, descrG, topologyData, TType));
} | java | public static int nvgraphGetGraphStructure(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
Object topologyData,
int[] TType)
{
return checkResult(nvgraphGetGraphStructureNative(handle, descrG, topologyData, TType));
} | [
"public",
"static",
"int",
"nvgraphGetGraphStructure",
"(",
"nvgraphHandle",
"handle",
",",
"nvgraphGraphDescr",
"descrG",
",",
"Object",
"topologyData",
",",
"int",
"[",
"]",
"TType",
")",
"{",
"return",
"checkResult",
"(",
"nvgraphGetGraphStructureNative",
"(",
"h... | Query size and topology information from the graph descriptor | [
"Query",
"size",
"and",
"topology",
"information",
"from",
"the",
"graph",
"descriptor"
] | train | https://github.com/jcuda/jnvgraph/blob/2c6bd7c58edac181753bacf30af2cceeb1989a78/JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java#L222-L229 |
aws/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/ListUniqueProblemsResult.java | ListUniqueProblemsResult.setUniqueProblems | public void setUniqueProblems(java.util.Map<String, java.util.List<UniqueProblem>> uniqueProblems) {
this.uniqueProblems = uniqueProblems;
} | java | public void setUniqueProblems(java.util.Map<String, java.util.List<UniqueProblem>> uniqueProblems) {
this.uniqueProblems = uniqueProblems;
} | [
"public",
"void",
"setUniqueProblems",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"UniqueProblem",
">",
">",
"uniqueProblems",
")",
"{",
"this",
".",
"uniqueProblems",
"=",
"uniqueProblems",
";",
"}"
] | <p>
Information about the unique problems.
</p>
<p>
Allowed values include:
</p>
<ul>
<li>
<p>
PENDING: A pending condition.
</p>
</li>
<li>
<p>
PASSED: A passing condition.
</p>
</li>
<li>
<p>
WARNED: A warning condition.
</p>
</li>
<li>
<p>
FAILED: A failed condition.
</p>
</li>
<li>
<p>
SKIPPED: A skipped condition.
</p>
</li>
<li>
<p>
ERRORED: An error condition.
</p>
</li>
<li>
<p>
STOPPED: A stopped condition.
</p>
</li>
</ul>
@param uniqueProblems
Information about the unique problems.</p>
<p>
Allowed values include:
</p>
<ul>
<li>
<p>
PENDING: A pending condition.
</p>
</li>
<li>
<p>
PASSED: A passing condition.
</p>
</li>
<li>
<p>
WARNED: A warning condition.
</p>
</li>
<li>
<p>
FAILED: A failed condition.
</p>
</li>
<li>
<p>
SKIPPED: A skipped condition.
</p>
</li>
<li>
<p>
ERRORED: An error condition.
</p>
</li>
<li>
<p>
STOPPED: A stopped condition.
</p>
</li> | [
"<p",
">",
"Information",
"about",
"the",
"unique",
"problems",
".",
"<",
"/",
"p",
">",
"<p",
">",
"Allowed",
"values",
"include",
":",
"<",
"/",
"p",
">",
"<ul",
">",
"<li",
">",
"<p",
">",
"PENDING",
":",
"A",
"pending",
"condition",
".",
"<",
... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/ListUniqueProblemsResult.java#L262-L264 |
aws/aws-sdk-java | aws-java-sdk-amplify/src/main/java/com/amazonaws/services/amplify/model/CreateAppRequest.java | CreateAppRequest.withTags | public CreateAppRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | java | public CreateAppRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateAppRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Tag for an Amplify App
</p>
@param tags
Tag for an Amplify App
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Tag",
"for",
"an",
"Amplify",
"App",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-amplify/src/main/java/com/amazonaws/services/amplify/model/CreateAppRequest.java#L686-L689 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasMethodAdapter.java | AbstractRasMethodAdapter.boxLocalVar | protected void boxLocalVar(final Type type, final int slot, final boolean isSensitive) {
visitVarInsn(type.getOpcode(ILOAD), slot);
box(type, isSensitive);
} | java | protected void boxLocalVar(final Type type, final int slot, final boolean isSensitive) {
visitVarInsn(type.getOpcode(ILOAD), slot);
box(type, isSensitive);
} | [
"protected",
"void",
"boxLocalVar",
"(",
"final",
"Type",
"type",
",",
"final",
"int",
"slot",
",",
"final",
"boolean",
"isSensitive",
")",
"{",
"visitVarInsn",
"(",
"type",
".",
"getOpcode",
"(",
"ILOAD",
")",
",",
"slot",
")",
";",
"box",
"(",
"type",
... | Generate the instruction sequence needed to "box" the local variable
if required.
@param type
the <code>Type</code> of the object in the specified local
variable slot on the stack.
@param slot
the local variable slot to box.
@param isSensitive
indication that the variable is sensitive and should
not be traced as is. | [
"Generate",
"the",
"instruction",
"sequence",
"needed",
"to",
"box",
"the",
"local",
"variable",
"if",
"required",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasMethodAdapter.java#L1141-L1144 |
landawn/AbacusUtil | src/com/landawn/abacus/util/CSVUtil.java | CSVUtil.exportCSV | public static long exportCSV(final File out, final PreparedStatement stmt, final Collection<String> selectColumnNames, final long offset, final long count,
final boolean writeTitle, final boolean quoted) throws UncheckedSQLException, UncheckedIOException {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
// rs.setFetchSize(200);
return exportCSV(out, rs, selectColumnNames, offset, count, writeTitle, quoted);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
JdbcUtil.closeQuietly(rs);
}
} | java | public static long exportCSV(final File out, final PreparedStatement stmt, final Collection<String> selectColumnNames, final long offset, final long count,
final boolean writeTitle, final boolean quoted) throws UncheckedSQLException, UncheckedIOException {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
// rs.setFetchSize(200);
return exportCSV(out, rs, selectColumnNames, offset, count, writeTitle, quoted);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
JdbcUtil.closeQuietly(rs);
}
} | [
"public",
"static",
"long",
"exportCSV",
"(",
"final",
"File",
"out",
",",
"final",
"PreparedStatement",
"stmt",
",",
"final",
"Collection",
"<",
"String",
">",
"selectColumnNames",
",",
"final",
"long",
"offset",
",",
"final",
"long",
"count",
",",
"final",
... | Exports the data from database to CVS.
@param out
@param stmt
@param selectColumnNames
@param offset
@param count
@param writeTitle
@param quoted
@return | [
"Exports",
"the",
"data",
"from",
"database",
"to",
"CVS",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CSVUtil.java#L782-L796 |
HsiangLeekwok/hlklib | hlklib/src/main/java/com/hlk/hlklib/etc/Utility.java | Utility.intToHex | public static String intToHex(int number, int hexSize) {
String tmp = Integer.toHexString(number & 0xFF);
while (tmp.length() < hexSize) {
tmp = "0" + tmp;
}
return tmp;
} | java | public static String intToHex(int number, int hexSize) {
String tmp = Integer.toHexString(number & 0xFF);
while (tmp.length() < hexSize) {
tmp = "0" + tmp;
}
return tmp;
} | [
"public",
"static",
"String",
"intToHex",
"(",
"int",
"number",
",",
"int",
"hexSize",
")",
"{",
"String",
"tmp",
"=",
"Integer",
".",
"toHexString",
"(",
"number",
"&",
"0xFF",
")",
";",
"while",
"(",
"tmp",
".",
"length",
"(",
")",
"<",
"hexSize",
... | Integer 数字转换成16进制代码
@param number 需要转换的 int 数据
@param hexSize 转换后的 hex 字符串长度,不足长度时左边补 0 | [
"Integer",
"数字转换成16进制代码"
] | train | https://github.com/HsiangLeekwok/hlklib/blob/b122f6dcab7cec60c8e5455e0c31613d08bec6ad/hlklib/src/main/java/com/hlk/hlklib/etc/Utility.java#L104-L110 |
overturetool/overture | core/codegen/platform/src/main/java/org/overture/codegen/assistant/DeclAssistantIR.java | DeclAssistantIR.isLocal | public boolean isLocal(AIdentifierStateDesignator id, IRInfo info)
{
PDefinition idDef = info.getIdStateDesignatorDefs().get(id);
if (idDef == null)
{
log.error("Could not find definition for identifier state designator ");
return false;
} else
{
return idDef instanceof AAssignmentDefinition;
}
} | java | public boolean isLocal(AIdentifierStateDesignator id, IRInfo info)
{
PDefinition idDef = info.getIdStateDesignatorDefs().get(id);
if (idDef == null)
{
log.error("Could not find definition for identifier state designator ");
return false;
} else
{
return idDef instanceof AAssignmentDefinition;
}
} | [
"public",
"boolean",
"isLocal",
"(",
"AIdentifierStateDesignator",
"id",
",",
"IRInfo",
"info",
")",
"{",
"PDefinition",
"idDef",
"=",
"info",
".",
"getIdStateDesignatorDefs",
"(",
")",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"idDef",
"==",
"null",
")"... | Based on the definition table computed by {@link IRGenerator#computeDefTable(List)} this method determines
whether a identifier state designator is local or not.
@param id
The identifier state designator
@param info
The IR info
@return True if <code>id</code> is local - false otherwise | [
"Based",
"on",
"the",
"definition",
"table",
"computed",
"by",
"{",
"@link",
"IRGenerator#computeDefTable",
"(",
"List",
")",
"}",
"this",
"method",
"determines",
"whether",
"a",
"identifier",
"state",
"designator",
"is",
"local",
"or",
"not",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/codegen/platform/src/main/java/org/overture/codegen/assistant/DeclAssistantIR.java#L986-L998 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java | SqlQueryStatement.createTableAlias | private TableAlias createTableAlias(ClassDescriptor cld, List hints, String path)
{
TableAlias alias;
boolean lookForExtents = false;
if (!cld.getExtentClasses().isEmpty() && path.length() > 0)
{
lookForExtents = true;
}
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // m_pathToAlias.size();
alias = new TableAlias(cld, aliasName, lookForExtents, hints);
setTableAliasForPath(path, hints, alias);
return alias;
} | java | private TableAlias createTableAlias(ClassDescriptor cld, List hints, String path)
{
TableAlias alias;
boolean lookForExtents = false;
if (!cld.getExtentClasses().isEmpty() && path.length() > 0)
{
lookForExtents = true;
}
String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // m_pathToAlias.size();
alias = new TableAlias(cld, aliasName, lookForExtents, hints);
setTableAliasForPath(path, hints, alias);
return alias;
} | [
"private",
"TableAlias",
"createTableAlias",
"(",
"ClassDescriptor",
"cld",
",",
"List",
"hints",
",",
"String",
"path",
")",
"{",
"TableAlias",
"alias",
";",
"boolean",
"lookForExtents",
"=",
"false",
";",
"if",
"(",
"!",
"cld",
".",
"getExtentClasses",
"(",
... | Create new TableAlias for path
@param cld the class descriptor for the TableAlias
@param path the path from the target table of the query to this TableAlias.
@param hints a List of Class objects to be used on path expressions | [
"Create",
"new",
"TableAlias",
"for",
"path"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L1295-L1310 |
datumbox/datumbox-framework | datumbox-framework-common/src/main/java/com/datumbox/framework/common/storage/abstracts/AbstractStorageEngine.java | AbstractStorageEngine.postSerializer | protected <T extends Serializable> void postSerializer(T serializableObject, Map<String, Object> objReferences) {
for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) {
String fieldName = field.getName();
Object ref = objReferences.remove(fieldName);
if(ref != null) { //if a reference is found in the map
field.setAccessible(true);
try {
//restore the reference in the object
field.set(serializableObject, ref);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
}
} | java | protected <T extends Serializable> void postSerializer(T serializableObject, Map<String, Object> objReferences) {
for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) {
String fieldName = field.getName();
Object ref = objReferences.remove(fieldName);
if(ref != null) { //if a reference is found in the map
field.setAccessible(true);
try {
//restore the reference in the object
field.set(serializableObject, ref);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
}
} | [
"protected",
"<",
"T",
"extends",
"Serializable",
">",
"void",
"postSerializer",
"(",
"T",
"serializableObject",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"objReferences",
")",
"{",
"for",
"(",
"Field",
"field",
":",
"ReflectionMethods",
".",
"getAllField... | This method is called after the object serialization. It moves all the not-serializable BigMap references from
the Map back to the provided object. The main idea is that once the serialization is completed, we are allowed to
restore back all the references which were removed by the preSerializer.
@param serializableObject
@param objReferences
@param <T> | [
"This",
"method",
"is",
"called",
"after",
"the",
"object",
"serialization",
".",
"It",
"moves",
"all",
"the",
"not",
"-",
"serializable",
"BigMap",
"references",
"from",
"the",
"Map",
"back",
"to",
"the",
"provided",
"object",
".",
"The",
"main",
"idea",
... | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/storage/abstracts/AbstractStorageEngine.java#L192-L209 |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/RDBMEntityLockStore.java | RDBMEntityLockStore.instanceFromResultSet | private IEntityLock instanceFromResultSet(java.sql.ResultSet rs)
throws SQLException, LockingException {
Integer entityTypeID = rs.getInt(1);
Class entityType = EntityTypesLocator.getEntityTypes().getEntityTypeFromID(entityTypeID);
String key = rs.getString(2);
int lockType = rs.getInt(3);
Timestamp ts = rs.getTimestamp(4);
String lockOwner = rs.getString(5);
return newInstance(entityType, key, lockType, ts, lockOwner);
} | java | private IEntityLock instanceFromResultSet(java.sql.ResultSet rs)
throws SQLException, LockingException {
Integer entityTypeID = rs.getInt(1);
Class entityType = EntityTypesLocator.getEntityTypes().getEntityTypeFromID(entityTypeID);
String key = rs.getString(2);
int lockType = rs.getInt(3);
Timestamp ts = rs.getTimestamp(4);
String lockOwner = rs.getString(5);
return newInstance(entityType, key, lockType, ts, lockOwner);
} | [
"private",
"IEntityLock",
"instanceFromResultSet",
"(",
"java",
".",
"sql",
".",
"ResultSet",
"rs",
")",
"throws",
"SQLException",
",",
"LockingException",
"{",
"Integer",
"entityTypeID",
"=",
"rs",
".",
"getInt",
"(",
"1",
")",
";",
"Class",
"entityType",
"="... | Extract values from ResultSet and create a new lock.
@return org.apereo.portal.groups.IEntityLock
@param rs java.sql.ResultSet | [
"Extract",
"values",
"from",
"ResultSet",
"and",
"create",
"a",
"new",
"lock",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/RDBMEntityLockStore.java#L324-L334 |
indeedeng/proctor | proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java | SvnWorkspaceProviderImpl.formatDirName | private static String formatDirName(final String prefix, final String suffix) {
// Replace all invalid characters with '-'
final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();
return String.format("%s-%s", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));
} | java | private static String formatDirName(final String prefix, final String suffix) {
// Replace all invalid characters with '-'
final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();
return String.format("%s-%s", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));
} | [
"private",
"static",
"String",
"formatDirName",
"(",
"final",
"String",
"prefix",
",",
"final",
"String",
"suffix",
")",
"{",
"// Replace all invalid characters with '-'",
"final",
"CharMatcher",
"invalidCharacters",
"=",
"VALID_SUFFIX_CHARS",
".",
"negate",
"(",
")",
... | Returns the expected name of a workspace for a given suffix
@param suffix
@return | [
"Returns",
"the",
"expected",
"name",
"of",
"a",
"workspace",
"for",
"a",
"given",
"suffix"
] | train | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java#L180-L184 |
aws/aws-sdk-java | aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/SetIdentityPoolRolesRequest.java | SetIdentityPoolRolesRequest.withRoles | public SetIdentityPoolRolesRequest withRoles(java.util.Map<String, String> roles) {
setRoles(roles);
return this;
} | java | public SetIdentityPoolRolesRequest withRoles(java.util.Map<String, String> roles) {
setRoles(roles);
return this;
} | [
"public",
"SetIdentityPoolRolesRequest",
"withRoles",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"roles",
")",
"{",
"setRoles",
"(",
"roles",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The map of roles associated with this pool. For a given role, the key will be either "authenticated" or
"unauthenticated" and the value will be the Role ARN.
</p>
@param roles
The map of roles associated with this pool. For a given role, the key will be either "authenticated" or
"unauthenticated" and the value will be the Role ARN.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"map",
"of",
"roles",
"associated",
"with",
"this",
"pool",
".",
"For",
"a",
"given",
"role",
"the",
"key",
"will",
"be",
"either",
"authenticated",
"or",
"unauthenticated",
"and",
"the",
"value",
"will",
"be",
"the",
"Role",
"ARN",
"."... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/SetIdentityPoolRolesRequest.java#L137-L140 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HiveJdbcConnector.java | HiveJdbcConnector.withHiveServerVersion | private HiveJdbcConnector withHiveServerVersion(int hiveServerVersion) {
try {
if (hiveServerVersion == 1) {
Class.forName(HIVE_JDBC_DRIVER_NAME);
} else if (hiveServerVersion == 2) {
Class.forName(HIVE2_JDBC_DRIVER_NAME);
} else {
throw new RuntimeException(hiveServerVersion + " is not a valid HiveServer version.");
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find a suitable driver of HiveServer version " + hiveServerVersion + ".", e);
}
this.hiveServerVersion = hiveServerVersion;
return this;
} | java | private HiveJdbcConnector withHiveServerVersion(int hiveServerVersion) {
try {
if (hiveServerVersion == 1) {
Class.forName(HIVE_JDBC_DRIVER_NAME);
} else if (hiveServerVersion == 2) {
Class.forName(HIVE2_JDBC_DRIVER_NAME);
} else {
throw new RuntimeException(hiveServerVersion + " is not a valid HiveServer version.");
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find a suitable driver of HiveServer version " + hiveServerVersion + ".", e);
}
this.hiveServerVersion = hiveServerVersion;
return this;
} | [
"private",
"HiveJdbcConnector",
"withHiveServerVersion",
"(",
"int",
"hiveServerVersion",
")",
"{",
"try",
"{",
"if",
"(",
"hiveServerVersion",
"==",
"1",
")",
"{",
"Class",
".",
"forName",
"(",
"HIVE_JDBC_DRIVER_NAME",
")",
";",
"}",
"else",
"if",
"(",
"hiveS... | Set the {@link HiveJdbcConnector#hiveServerVersion}. The hiveServerVersion must be either 1 or 2.
@param hiveServerVersion
@return | [
"Set",
"the",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HiveJdbcConnector.java#L136-L150 |
knowm/XChart | xchart/src/main/java/org/knowm/xchart/CategoryChart.java | CategoryChart.addSeries | public CategorySeries addSeries(String seriesName, double[] xData, double[] yData) {
return addSeries(seriesName, xData, yData, null);
} | java | public CategorySeries addSeries(String seriesName, double[] xData, double[] yData) {
return addSeries(seriesName, xData, yData, null);
} | [
"public",
"CategorySeries",
"addSeries",
"(",
"String",
"seriesName",
",",
"double",
"[",
"]",
"xData",
",",
"double",
"[",
"]",
"yData",
")",
"{",
"return",
"addSeries",
"(",
"seriesName",
",",
"xData",
",",
"yData",
",",
"null",
")",
";",
"}"
] | Add a series for a Category type chart using using double arrays
@param seriesName
@param xData the X-Axis data
@param xData the Y-Axis data
@return A Series object that you can set properties on | [
"Add",
"a",
"series",
"for",
"a",
"Category",
"type",
"chart",
"using",
"using",
"double",
"arrays"
] | train | https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/CategoryChart.java#L83-L86 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/compiler/batch/SarlBatchCompiler.java | SarlBatchCompiler.notifiesIssueMessageListeners | private void notifiesIssueMessageListeners(Issue issue, org.eclipse.emf.common.util.URI uri, String message) {
for (final IssueMessageListener listener : this.messageListeners) {
listener.onIssue(issue, uri, message);
}
} | java | private void notifiesIssueMessageListeners(Issue issue, org.eclipse.emf.common.util.URI uri, String message) {
for (final IssueMessageListener listener : this.messageListeners) {
listener.onIssue(issue, uri, message);
}
} | [
"private",
"void",
"notifiesIssueMessageListeners",
"(",
"Issue",
"issue",
",",
"org",
".",
"eclipse",
".",
"emf",
".",
"common",
".",
"util",
".",
"URI",
"uri",
",",
"String",
"message",
")",
"{",
"for",
"(",
"final",
"IssueMessageListener",
"listener",
":"... | Replies the message for the given issue.
@param issue the issue.
@param uri URI to the problem.
@param message the formatted message.
@since 0.6 | [
"Replies",
"the",
"message",
"for",
"the",
"given",
"issue",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/compiler/batch/SarlBatchCompiler.java#L449-L453 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java | SameDiff.addArgsFor | public void addArgsFor(SDVariable[] variables, DifferentialFunction function) {
String[] varNames = new String[variables.length];
for (int i = 0; i < varNames.length; i++) {
if (variables[i] == null)
throw new ND4JIllegalStateException("Found null variable at index " + i);
varNames[i] = variables[i].getVarName();
}
addArgsFor(varNames, function);
} | java | public void addArgsFor(SDVariable[] variables, DifferentialFunction function) {
String[] varNames = new String[variables.length];
for (int i = 0; i < varNames.length; i++) {
if (variables[i] == null)
throw new ND4JIllegalStateException("Found null variable at index " + i);
varNames[i] = variables[i].getVarName();
}
addArgsFor(varNames, function);
} | [
"public",
"void",
"addArgsFor",
"(",
"SDVariable",
"[",
"]",
"variables",
",",
"DifferentialFunction",
"function",
")",
"{",
"String",
"[",
"]",
"varNames",
"=",
"new",
"String",
"[",
"variables",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0"... | Adds incoming arguments for the specified differential function to the graph
@param variables variables that are arguments (inputs) to the specified function
@param function Function | [
"Adds",
"incoming",
"arguments",
"for",
"the",
"specified",
"differential",
"function",
"to",
"the",
"graph"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L1193-L1201 |
Viascom/groundwork | foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/builder/FoxHttpRequestBuilder.java | FoxHttpRequestBuilder.addRequestHeader | public FoxHttpRequestBuilder addRequestHeader(String name, String value) {
foxHttpRequest.getRequestHeader().addHeader(name, value);
return this;
} | java | public FoxHttpRequestBuilder addRequestHeader(String name, String value) {
foxHttpRequest.getRequestHeader().addHeader(name, value);
return this;
} | [
"public",
"FoxHttpRequestBuilder",
"addRequestHeader",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"foxHttpRequest",
".",
"getRequestHeader",
"(",
")",
".",
"addHeader",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Add a new header entry
@param name name of the header entry
@param value value of the header entry
@return FoxHttpRequestBuilder (this) | [
"Add",
"a",
"new",
"header",
"entry"
] | train | https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/builder/FoxHttpRequestBuilder.java#L192-L195 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java | PoolsImpl.enableAutoScale | public void enableAutoScale(String poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions) {
enableAutoScaleWithServiceResponseAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions).toBlocking().single().body();
} | java | public void enableAutoScale(String poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions) {
enableAutoScaleWithServiceResponseAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions).toBlocking().single().body();
} | [
"public",
"void",
"enableAutoScale",
"(",
"String",
"poolId",
",",
"PoolEnableAutoScaleParameter",
"poolEnableAutoScaleParameter",
",",
"PoolEnableAutoScaleOptions",
"poolEnableAutoScaleOptions",
")",
"{",
"enableAutoScaleWithServiceResponseAsync",
"(",
"poolId",
",",
"poolEnable... | Enables automatic scaling for a pool.
You cannot enable automatic scaling on a pool if a resize operation is in progress on the pool. If automatic scaling of the pool is currently disabled, you must specify a valid autoscale formula as part of the request. If automatic scaling of the pool is already enabled, you may specify a new autoscale formula and/or a new evaluation interval. You cannot call this API for the same pool more than once every 30 seconds.
@param poolId The ID of the pool on which to enable automatic scaling.
@param poolEnableAutoScaleParameter The parameters for the request.
@param poolEnableAutoScaleOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Enables",
"automatic",
"scaling",
"for",
"a",
"pool",
".",
"You",
"cannot",
"enable",
"automatic",
"scaling",
"on",
"a",
"pool",
"if",
"a",
"resize",
"operation",
"is",
"in",
"progress",
"on",
"the",
"pool",
".",
"If",
"automatic",
"scaling",
"of",
"the",... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L2369-L2371 |
korpling/ANNIS | annis-libgui/src/main/java/annis/libgui/Helper.java | Helper.getAnnisWebResource | public static WebResource getAnnisWebResource(String uri, AnnisUser user)
{
if (user != null)
{
try
{
return user.getClient().resource(uri);
}
catch (LoginDataLostException ex)
{
log.error(
"Could not restore the login-data from session, user will invalidated",
ex);
setUser(null);
UI ui = UI.getCurrent();
if (ui instanceof AnnisBaseUI)
{
((AnnisBaseUI) ui).getLoginDataLostBus().post(ex);
}
}
}
// use the anonymous client
if (anonymousClient.get() == null)
{
// anonymous client not created yet
anonymousClient.set(createRESTClient());
}
return anonymousClient.get().resource(uri);
} | java | public static WebResource getAnnisWebResource(String uri, AnnisUser user)
{
if (user != null)
{
try
{
return user.getClient().resource(uri);
}
catch (LoginDataLostException ex)
{
log.error(
"Could not restore the login-data from session, user will invalidated",
ex);
setUser(null);
UI ui = UI.getCurrent();
if (ui instanceof AnnisBaseUI)
{
((AnnisBaseUI) ui).getLoginDataLostBus().post(ex);
}
}
}
// use the anonymous client
if (anonymousClient.get() == null)
{
// anonymous client not created yet
anonymousClient.set(createRESTClient());
}
return anonymousClient.get().resource(uri);
} | [
"public",
"static",
"WebResource",
"getAnnisWebResource",
"(",
"String",
"uri",
",",
"AnnisUser",
"user",
")",
"{",
"if",
"(",
"user",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"user",
".",
"getClient",
"(",
")",
".",
"resource",
"(",
"uri",
")",
"... | Gets or creates a web resource to the ANNIS service.
@param uri The URI where the service can be found
@param user The user object or null (should be of type {@link AnnisUser}).
@return A reference to the ANNIS service root resource. | [
"Gets",
"or",
"creates",
"a",
"web",
"resource",
"to",
"the",
"ANNIS",
"service",
"."
] | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-libgui/src/main/java/annis/libgui/Helper.java#L239-L270 |
redkale/redkale | src/org/redkale/source/EntityInfo.java | EntityInfo.getSQLColumn | public String getSQLColumn(String tabalis, String fieldname) {
return this.aliasmap == null ? (tabalis == null ? fieldname : (tabalis + '.' + fieldname))
: (tabalis == null ? aliasmap.getOrDefault(fieldname, fieldname) : (tabalis + '.' + aliasmap.getOrDefault(fieldname, fieldname)));
} | java | public String getSQLColumn(String tabalis, String fieldname) {
return this.aliasmap == null ? (tabalis == null ? fieldname : (tabalis + '.' + fieldname))
: (tabalis == null ? aliasmap.getOrDefault(fieldname, fieldname) : (tabalis + '.' + aliasmap.getOrDefault(fieldname, fieldname)));
} | [
"public",
"String",
"getSQLColumn",
"(",
"String",
"tabalis",
",",
"String",
"fieldname",
")",
"{",
"return",
"this",
".",
"aliasmap",
"==",
"null",
"?",
"(",
"tabalis",
"==",
"null",
"?",
"fieldname",
":",
"(",
"tabalis",
"+",
"'",
"'",
"+",
"fieldname"... | 根据field字段名获取数据库对应的字段名
@param tabalis 表别名
@param fieldname 字段名
@return String | [
"根据field字段名获取数据库对应的字段名"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/EntityInfo.java#L877-L880 |
code4everything/util | src/main/java/com/zhazhapan/util/MailSender.java | MailSender.sendMail | public static void sendMail(String to, String title, String content) throws Exception {
if (!Checker.isEmail(to)) {
throw new Exception("this email address is not valid. please check it again");
}
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
if (port > 0) {
properties.setProperty("mail.smtp.port", String.valueOf(port));
}
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", sslEnable);
properties.put("mail.smtp.ssl.socketFactory", sf);
// 获取session对象
Session session = Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
// 发件人邮件用户名、密码
return new PasswordAuthentication(from, key);
}
});
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// Set From:头部头字段
message.setFrom(new InternetAddress(from, personal, "UTF-8"));
// Set To:头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject:头部头字段
message.setSubject(title, "UTF-8");
// 设置消息体
message.setContent(content, "text/html;charset=UTF-8");
message.setSentDate(new Date());
// 发送消息
Transport.send(message);
} | java | public static void sendMail(String to, String title, String content) throws Exception {
if (!Checker.isEmail(to)) {
throw new Exception("this email address is not valid. please check it again");
}
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
if (port > 0) {
properties.setProperty("mail.smtp.port", String.valueOf(port));
}
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", sslEnable);
properties.put("mail.smtp.ssl.socketFactory", sf);
// 获取session对象
Session session = Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
// 发件人邮件用户名、密码
return new PasswordAuthentication(from, key);
}
});
// 创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// Set From:头部头字段
message.setFrom(new InternetAddress(from, personal, "UTF-8"));
// Set To:头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject:头部头字段
message.setSubject(title, "UTF-8");
// 设置消息体
message.setContent(content, "text/html;charset=UTF-8");
message.setSentDate(new Date());
// 发送消息
Transport.send(message);
} | [
"public",
"static",
"void",
"sendMail",
"(",
"String",
"to",
",",
"String",
"title",
",",
"String",
"content",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"Checker",
".",
"isEmail",
"(",
"to",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"th... | 发送邮件,调用此方法前请先检查邮件服务器是否已经设置,如果没有设置,请先设置{@link MailSender#setHost(String)}, 如不设置将使用默认的QQ邮件服务器
@param to 收件箱
@param title 标题
@param content 内容
@throws Exception 异常 | [
"发送邮件,调用此方法前请先检查邮件服务器是否已经设置,如果没有设置,请先设置",
"{",
"@link",
"MailSender#setHost",
"(",
"String",
")",
"}",
",",
"如不设置将使用默认的QQ邮件服务器"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/MailSender.java#L194-L233 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.upsert | public <T> MutateInBuilder upsert(String path, T fragment) {
asyncBuilder.upsert(path, fragment);
return this;
} | java | public <T> MutateInBuilder upsert(String path, T fragment) {
asyncBuilder.upsert(path, fragment);
return this;
} | [
"public",
"<",
"T",
">",
"MutateInBuilder",
"upsert",
"(",
"String",
"path",
",",
"T",
"fragment",
")",
"{",
"asyncBuilder",
".",
"upsert",
"(",
"path",
",",
"fragment",
")",
";",
"return",
"this",
";",
"}"
] | Insert a fragment, replacing the old value if the path exists.
@param path the path where to insert (or replace) a dictionary value.
@param fragment the new dictionary value to be applied. | [
"Insert",
"a",
"fragment",
"replacing",
"the",
"old",
"value",
"if",
"the",
"path",
"exists",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L590-L593 |
krummas/DrizzleJDBC | src/main/java/org/drizzle/jdbc/DrizzleDataBaseMetaData.java | DrizzleDataBaseMetaData.getPrimaryKeys | @Override
public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table) throws SQLException {
String query = "SELECT null TABLE_CAT, " +
"columns.table_schema TABLE_SCHEM, " +
"columns.table_name, " +
"columns.column_name, " +
"kcu.ordinal_position KEY_SEQ," +
"null pk_name " +
"FROM information_schema.columns " +
"INNER JOIN information_schema.key_column_usage kcu "+
"ON kcu.constraint_schema = columns.table_schema AND " +
"columns.table_name = kcu.table_name AND " +
"columns.column_name = kcu.column_name " +
"WHERE columns.table_name='" + table + "' AND kcu.constraint_name='PRIMARY'";
if (schema != null) {
query += " AND columns.table_schema = '" + schema + "'";
}
query += " ORDER BY columns.column_name";
final Statement stmt = getConnection().createStatement();
return stmt.executeQuery(query);
} | java | @Override
public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table) throws SQLException {
String query = "SELECT null TABLE_CAT, " +
"columns.table_schema TABLE_SCHEM, " +
"columns.table_name, " +
"columns.column_name, " +
"kcu.ordinal_position KEY_SEQ," +
"null pk_name " +
"FROM information_schema.columns " +
"INNER JOIN information_schema.key_column_usage kcu "+
"ON kcu.constraint_schema = columns.table_schema AND " +
"columns.table_name = kcu.table_name AND " +
"columns.column_name = kcu.column_name " +
"WHERE columns.table_name='" + table + "' AND kcu.constraint_name='PRIMARY'";
if (schema != null) {
query += " AND columns.table_schema = '" + schema + "'";
}
query += " ORDER BY columns.column_name";
final Statement stmt = getConnection().createStatement();
return stmt.executeQuery(query);
} | [
"@",
"Override",
"public",
"ResultSet",
"getPrimaryKeys",
"(",
"final",
"String",
"catalog",
",",
"final",
"String",
"schema",
",",
"final",
"String",
"table",
")",
"throws",
"SQLException",
"{",
"String",
"query",
"=",
"\"SELECT null TABLE_CAT, \"",
"+",
"\"colum... | Retrieves a description of the given table's primary key columns. They are ordered by COLUMN_NAME.
<p/>
<P>Each primary key column description has the following columns: <OL> <LI><B>TABLE_CAT</B> String => table
catalog (may be <code>null</code>) <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
<LI><B>TABLE_NAME</B> String => table name <LI><B>COLUMN_NAME</B> String => column name <LI><B>KEY_SEQ</B> short
=> sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2
would represent the second column within the primary key). <LI><B>PK_NAME</B> String => primary key name (may be
<code>null</code>) </OL>
@param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those
without a catalog; <code>null</code> means that the catalog name should not be used to narrow the
search
@param schema a schema name; must match the schema name as it is stored in the database; "" retrieves those
without a schema; <code>null</code> means that the schema name should not be used to narrow the
search
@param table a table name; must match the table name as it is stored in the database
@return <code>ResultSet</code> - each row is a primary key column description
@throws java.sql.SQLException if a database access error occurs | [
"Retrieves",
"a",
"description",
"of",
"the",
"given",
"table",
"s",
"primary",
"key",
"columns",
".",
"They",
"are",
"ordered",
"by",
"COLUMN_NAME",
".",
"<p",
"/",
">",
"<P",
">",
"Each",
"primary",
"key",
"column",
"description",
"has",
"the",
"followin... | train | https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzleDataBaseMetaData.java#L58-L79 |
apache/reef | lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/cli/LogFetcher.java | LogFetcher.downloadToTempFolder | private File downloadToTempFolder(final String applicationId)
throws URISyntaxException, StorageException, IOException {
final File outputFolder = Files.createTempDirectory("reeflogs-" + applicationId).toFile();
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
LOG.log(Level.WARNING, "Failed to create [{0}]", outputFolder.getAbsolutePath());
}
final CloudBlobDirectory logFolder = this.container.getDirectoryReference(LOG_FOLDER_PREFIX + applicationId + "/");
int fileCounter = 0;
for (final ListBlobItem blobItem : logFolder.listBlobs()) {
if (blobItem instanceof CloudBlob) {
try (final OutputStream outputStream = new FileOutputStream(new File(outputFolder, "File-" + fileCounter))) {
((CloudBlob) blobItem).download(outputStream);
++fileCounter;
}
}
}
LOG.log(Level.FINE, "Downloaded logs to: {0}", outputFolder.getAbsolutePath());
return outputFolder;
} | java | private File downloadToTempFolder(final String applicationId)
throws URISyntaxException, StorageException, IOException {
final File outputFolder = Files.createTempDirectory("reeflogs-" + applicationId).toFile();
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
LOG.log(Level.WARNING, "Failed to create [{0}]", outputFolder.getAbsolutePath());
}
final CloudBlobDirectory logFolder = this.container.getDirectoryReference(LOG_FOLDER_PREFIX + applicationId + "/");
int fileCounter = 0;
for (final ListBlobItem blobItem : logFolder.listBlobs()) {
if (blobItem instanceof CloudBlob) {
try (final OutputStream outputStream = new FileOutputStream(new File(outputFolder, "File-" + fileCounter))) {
((CloudBlob) blobItem).download(outputStream);
++fileCounter;
}
}
}
LOG.log(Level.FINE, "Downloaded logs to: {0}", outputFolder.getAbsolutePath());
return outputFolder;
} | [
"private",
"File",
"downloadToTempFolder",
"(",
"final",
"String",
"applicationId",
")",
"throws",
"URISyntaxException",
",",
"StorageException",
",",
"IOException",
"{",
"final",
"File",
"outputFolder",
"=",
"Files",
".",
"createTempDirectory",
"(",
"\"reeflogs-\"",
... | Downloads the logs to a local temp folder.
@param applicationId
@return
@throws URISyntaxException
@throws StorageException
@throws IOException | [
"Downloads",
"the",
"logs",
"to",
"a",
"local",
"temp",
"folder",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-hdinsight/src/main/java/org/apache/reef/runtime/hdinsight/cli/LogFetcher.java#L118-L136 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryDialog.java | CmsGalleryDialog.selectTab | public void selectTab(GalleryTabId tabId, boolean fireEvent) {
A_CmsTab tab = getTab(tabId);
if (tab != null) {
m_tabbedPanel.selectTab(tab, fireEvent);
}
} | java | public void selectTab(GalleryTabId tabId, boolean fireEvent) {
A_CmsTab tab = getTab(tabId);
if (tab != null) {
m_tabbedPanel.selectTab(tab, fireEvent);
}
} | [
"public",
"void",
"selectTab",
"(",
"GalleryTabId",
"tabId",
",",
"boolean",
"fireEvent",
")",
"{",
"A_CmsTab",
"tab",
"=",
"getTab",
"(",
"tabId",
")",
";",
"if",
"(",
"tab",
"!=",
"null",
")",
"{",
"m_tabbedPanel",
".",
"selectTab",
"(",
"tab",
",",
... | Selects a tab by the given id.<p>
@param tabId the tab id
@param fireEvent <code>true</code> to fire the tab event | [
"Selects",
"a",
"tab",
"by",
"the",
"given",
"id",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryDialog.java#L587-L593 |
alkacon/opencms-core | src/org/opencms/jlan/CmsByteBuffer.java | CmsByteBuffer.readBytes | public void readBytes(byte[] dest, int srcStart, int destStart, int len) {
System.arraycopy(m_buffer, srcStart, dest, destStart, len);
} | java | public void readBytes(byte[] dest, int srcStart, int destStart, int len) {
System.arraycopy(m_buffer, srcStart, dest, destStart, len);
} | [
"public",
"void",
"readBytes",
"(",
"byte",
"[",
"]",
"dest",
",",
"int",
"srcStart",
",",
"int",
"destStart",
",",
"int",
"len",
")",
"{",
"System",
".",
"arraycopy",
"(",
"m_buffer",
",",
"srcStart",
",",
"dest",
",",
"destStart",
",",
"len",
")",
... | Transfers bytes from this buffer to a target byte array.<p>
@param dest the byte array to which the bytes should be transferred
@param srcStart the start index in this buffer
@param destStart the start index in the destination buffer
@param len the number of bytes to transfer | [
"Transfers",
"bytes",
"from",
"this",
"buffer",
"to",
"a",
"target",
"byte",
"array",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jlan/CmsByteBuffer.java#L86-L90 |
cdk/cdk | tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java | GeometricCumulativeDoubleBondFactory.axialEncoder | static StereoEncoder axialEncoder(IAtomContainer container, IAtom start, IAtom end) {
List<IBond> startBonds = container.getConnectedBondsList(start);
List<IBond> endBonds = container.getConnectedBondsList(end);
if (startBonds.size() < 2 || endBonds.size() < 2) return null;
if (has2DCoordinates(startBonds) && has2DCoordinates(endBonds)) {
return axial2DEncoder(container, start, startBonds, end, endBonds);
} else if (has3DCoordinates(startBonds) && has3DCoordinates(endBonds)) {
return axial3DEncoder(container, start, startBonds, end, endBonds);
}
return null;
} | java | static StereoEncoder axialEncoder(IAtomContainer container, IAtom start, IAtom end) {
List<IBond> startBonds = container.getConnectedBondsList(start);
List<IBond> endBonds = container.getConnectedBondsList(end);
if (startBonds.size() < 2 || endBonds.size() < 2) return null;
if (has2DCoordinates(startBonds) && has2DCoordinates(endBonds)) {
return axial2DEncoder(container, start, startBonds, end, endBonds);
} else if (has3DCoordinates(startBonds) && has3DCoordinates(endBonds)) {
return axial3DEncoder(container, start, startBonds, end, endBonds);
}
return null;
} | [
"static",
"StereoEncoder",
"axialEncoder",
"(",
"IAtomContainer",
"container",
",",
"IAtom",
"start",
",",
"IAtom",
"end",
")",
"{",
"List",
"<",
"IBond",
">",
"startBonds",
"=",
"container",
".",
"getConnectedBondsList",
"(",
"start",
")",
";",
"List",
"<",
... | Create an encoder for axial 2D stereochemistry for the given start and
end atoms.
@param container the molecule
@param start start of the cumulated system
@param end end of the cumulated system
@return an encoder or null if there are no coordinated | [
"Create",
"an",
"encoder",
"for",
"axial",
"2D",
"stereochemistry",
"for",
"the",
"given",
"start",
"and",
"end",
"atoms",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java#L144-L158 |
overturetool/overture | core/interpreter/src/main/java/org/overture/interpreter/runtime/Interpreter.java | Interpreter.setTracepoint | public Breakpoint setTracepoint(PStm stmt, String trace) throws Exception
{
BreakpointManager.setBreakpoint(stmt, new Tracepoint(stmt.getLocation(), ++nextbreakpoint, trace));
breakpoints.put(nextbreakpoint, BreakpointManager.getBreakpoint(stmt));
return BreakpointManager.getBreakpoint(stmt);
} | java | public Breakpoint setTracepoint(PStm stmt, String trace) throws Exception
{
BreakpointManager.setBreakpoint(stmt, new Tracepoint(stmt.getLocation(), ++nextbreakpoint, trace));
breakpoints.put(nextbreakpoint, BreakpointManager.getBreakpoint(stmt));
return BreakpointManager.getBreakpoint(stmt);
} | [
"public",
"Breakpoint",
"setTracepoint",
"(",
"PStm",
"stmt",
",",
"String",
"trace",
")",
"throws",
"Exception",
"{",
"BreakpointManager",
".",
"setBreakpoint",
"(",
"stmt",
",",
"new",
"Tracepoint",
"(",
"stmt",
".",
"getLocation",
"(",
")",
",",
"++",
"ne... | Set a statement tracepoint. A tracepoint does not stop execution, but evaluates and displays an expression before
continuing.
@param stmt
The statement to trace.
@param trace
The expression to evaluate.
@return The Breakpoint object created.
@throws Exception
Expression is not valid. | [
"Set",
"a",
"statement",
"tracepoint",
".",
"A",
"tracepoint",
"does",
"not",
"stop",
"execution",
"but",
"evaluates",
"and",
"displays",
"an",
"expression",
"before",
"continuing",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/runtime/Interpreter.java#L427-L432 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLAnnotationAssertionAxiomImpl_CustomFieldSerializer.java | OWLAnnotationAssertionAxiomImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLAnnotationAssertionAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLAnnotationAssertionAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLAnnotationAssertionAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"... | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLAnnotationAssertionAxiomImpl_CustomFieldSerializer.java#L94-L97 |
cchabanois/transmorph | src/main/java/net/entropysoft/transmorph/type/TypeUtils.java | TypeUtils.matches | private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
if (to.equals(from))
return true;
if (from instanceof TypeVariable) {
return to.equals(typeMap.get(((TypeVariable<?>) from).getName()));
}
return false;
} | java | private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
if (to.equals(from))
return true;
if (from instanceof TypeVariable) {
return to.equals(typeMap.get(((TypeVariable<?>) from).getName()));
}
return false;
} | [
"private",
"static",
"boolean",
"matches",
"(",
"Type",
"from",
",",
"Type",
"to",
",",
"Map",
"<",
"String",
",",
"Type",
">",
"typeMap",
")",
"{",
"if",
"(",
"to",
".",
"equals",
"(",
"from",
")",
")",
"return",
"true",
";",
"if",
"(",
"from",
... | Checks if two types are the same or are equivalent under a variable
mapping given in the type map that was provided. | [
"Checks",
"if",
"two",
"types",
"are",
"the",
"same",
"or",
"are",
"equivalent",
"under",
"a",
"variable",
"mapping",
"given",
"in",
"the",
"type",
"map",
"that",
"was",
"provided",
"."
] | train | https://github.com/cchabanois/transmorph/blob/118550f30b9680a84eab7496bd8b04118740dcec/src/main/java/net/entropysoft/transmorph/type/TypeUtils.java#L170-L179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.