repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
lessthanoptimal/ddogleg | src/org/ddogleg/clustering/kmeans/InitializePlusPlus.java | InitializePlusPlus.updateDistances | protected final void updateDistances( List<double[]> points , double []clusterNew ) {
totalDistance = 0;
for (int i = 0; i < distance.size(); i++) {
double dOld = distance.get(i);
double dNew = StandardKMeans_F64.distanceSq(points.get(i),clusterNew);
if( dNew < dOld ) {
distance.data[i] = dNew;
totalDistance += dNew;
} else {
totalDistance += dOld;
}
}
} | java | protected final void updateDistances( List<double[]> points , double []clusterNew ) {
totalDistance = 0;
for (int i = 0; i < distance.size(); i++) {
double dOld = distance.get(i);
double dNew = StandardKMeans_F64.distanceSq(points.get(i),clusterNew);
if( dNew < dOld ) {
distance.data[i] = dNew;
totalDistance += dNew;
} else {
totalDistance += dOld;
}
}
} | [
"protected",
"final",
"void",
"updateDistances",
"(",
"List",
"<",
"double",
"[",
"]",
">",
"points",
",",
"double",
"[",
"]",
"clusterNew",
")",
"{",
"totalDistance",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"distance",
".",
... | Updates the list of distances from a point to the closest cluster. Update list of total distances | [
"Updates",
"the",
"list",
"of",
"distances",
"from",
"a",
"point",
"to",
"the",
"closest",
"cluster",
".",
"Update",
"list",
"of",
"total",
"distances"
] | train | https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/clustering/kmeans/InitializePlusPlus.java#L110-L122 |
jblas-project/jblas | src/main/java/org/jblas/Singular.java | Singular.fullSVD | public static DoubleMatrix[] fullSVD(DoubleMatrix A) {
int m = A.rows;
int n = A.columns;
DoubleMatrix U = new DoubleMatrix(m, m);
DoubleMatrix S = new DoubleMatrix(min(m, n));
DoubleMatrix V = new DoubleMatrix(n, n);
int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);
if (info > 0) {
throw new LapackConvergenceException("GESVD", info + " superdiagonals of an intermediate bidiagonal form failed to converge.");
}
return new DoubleMatrix[]{U, S, V.transpose()};
} | java | public static DoubleMatrix[] fullSVD(DoubleMatrix A) {
int m = A.rows;
int n = A.columns;
DoubleMatrix U = new DoubleMatrix(m, m);
DoubleMatrix S = new DoubleMatrix(min(m, n));
DoubleMatrix V = new DoubleMatrix(n, n);
int info = NativeBlas.dgesvd('A', 'A', m, n, A.dup().data, 0, m, S.data, 0, U.data, 0, m, V.data, 0, n);
if (info > 0) {
throw new LapackConvergenceException("GESVD", info + " superdiagonals of an intermediate bidiagonal form failed to converge.");
}
return new DoubleMatrix[]{U, S, V.transpose()};
} | [
"public",
"static",
"DoubleMatrix",
"[",
"]",
"fullSVD",
"(",
"DoubleMatrix",
"A",
")",
"{",
"int",
"m",
"=",
"A",
".",
"rows",
";",
"int",
"n",
"=",
"A",
".",
"columns",
";",
"DoubleMatrix",
"U",
"=",
"new",
"DoubleMatrix",
"(",
"m",
",",
"m",
")"... | Compute a singular-value decomposition of A.
@return A DoubleMatrix[3] array of U, S, V such that A = U * diag(S) * V' | [
"Compute",
"a",
"singular",
"-",
"value",
"decomposition",
"of",
"A",
"."
] | train | https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Singular.java#L21-L36 |
apereo/cas | support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/sso/SSOSamlProfileCallbackHandlerController.java | SSOSamlProfileCallbackHandlerController.handleCallbackProfileRequest | @GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK)
protected void handleCallbackProfileRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
LOGGER.info("Received SAML callback profile request [{}]", request.getRequestURI());
val authnRequest = retrieveSamlAuthenticationRequestFromHttpRequest(request);
if (authnRequest == null) {
LOGGER.error("Can not validate the request because the original Authn request can not be found.");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
if (StringUtils.isBlank(ticket)) {
LOGGER.error("Can not validate the request because no [{}] is provided via the request", CasProtocolConstants.PARAMETER_TICKET);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val authenticationContext = buildAuthenticationContextPair(request, authnRequest);
val assertion = validateRequestAndBuildCasAssertion(response, request, authenticationContext);
val binding = determineProfileBinding(authenticationContext, assertion);
buildSamlResponse(response, request, authenticationContext, assertion, binding);
} | java | @GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK)
protected void handleCallbackProfileRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
LOGGER.info("Received SAML callback profile request [{}]", request.getRequestURI());
val authnRequest = retrieveSamlAuthenticationRequestFromHttpRequest(request);
if (authnRequest == null) {
LOGGER.error("Can not validate the request because the original Authn request can not be found.");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
if (StringUtils.isBlank(ticket)) {
LOGGER.error("Can not validate the request because no [{}] is provided via the request", CasProtocolConstants.PARAMETER_TICKET);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
val authenticationContext = buildAuthenticationContextPair(request, authnRequest);
val assertion = validateRequestAndBuildCasAssertion(response, request, authenticationContext);
val binding = determineProfileBinding(authenticationContext, assertion);
buildSamlResponse(response, request, authenticationContext, assertion, binding);
} | [
"@",
"GetMapping",
"(",
"path",
"=",
"SamlIdPConstants",
".",
"ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK",
")",
"protected",
"void",
"handleCallbackProfileRequest",
"(",
"final",
"HttpServletResponse",
"response",
",",
"final",
"HttpServletRequest",
"request",
")",
"throws",... | Handle callback profile request.
@param response the response
@param request the request
@throws Exception the exception | [
"Handle",
"callback",
"profile",
"request",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/sso/SSOSamlProfileCallbackHandlerController.java#L67-L88 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java | RoutesInner.createOrUpdateAsync | public Observable<RouteInner> createOrUpdateAsync(String resourceGroupName, String routeTableName, String routeName, RouteInner routeParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, routeName, routeParameters).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() {
@Override
public RouteInner call(ServiceResponse<RouteInner> response) {
return response.body();
}
});
} | java | public Observable<RouteInner> createOrUpdateAsync(String resourceGroupName, String routeTableName, String routeName, RouteInner routeParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, routeName, routeParameters).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() {
@Override
public RouteInner call(ServiceResponse<RouteInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RouteInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"routeTableName",
",",
"String",
"routeName",
",",
"RouteInner",
"routeParameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",... | Creates or updates a route in the specified route table.
@param resourceGroupName The name of the resource group.
@param routeTableName The name of the route table.
@param routeName The name of the route.
@param routeParameters Parameters supplied to the create or update route operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"a",
"route",
"in",
"the",
"specified",
"route",
"table",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java#L391-L398 |
lucee/Lucee | core/src/main/java/lucee/runtime/type/util/ComponentUtil.java | ComponentUtil.getClientComponentPropertiesClass | public static Class getClientComponentPropertiesClass(PageContext pc, String className, ASMProperty[] properties, Class extendsClass) throws PageException {
try {
return _getComponentPropertiesClass(pc, pc.getConfig(), className, properties, extendsClass);
}
catch (Exception e) {
throw Caster.toPageException(e);
}
} | java | public static Class getClientComponentPropertiesClass(PageContext pc, String className, ASMProperty[] properties, Class extendsClass) throws PageException {
try {
return _getComponentPropertiesClass(pc, pc.getConfig(), className, properties, extendsClass);
}
catch (Exception e) {
throw Caster.toPageException(e);
}
} | [
"public",
"static",
"Class",
"getClientComponentPropertiesClass",
"(",
"PageContext",
"pc",
",",
"String",
"className",
",",
"ASMProperty",
"[",
"]",
"properties",
",",
"Class",
"extendsClass",
")",
"throws",
"PageException",
"{",
"try",
"{",
"return",
"_getComponen... | /*
includes the application context javasettings
@param pc
@param className
@param properties
@return
@throws PageException | [
"/",
"*",
"includes",
"the",
"application",
"context",
"javasettings"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/ComponentUtil.java#L357-L364 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java | XmlIO.save | public static void save(final AnnotationMappingInfo xmlInfo, final OutputStream out) throws XmlOperateException {
ArgUtils.notNull(xmlInfo, "xmlInfo");
ArgUtils.notNull(out, "out");
try {
JAXB.marshal(xmlInfo, out);
} catch (DataBindingException e) {
throw new XmlOperateException("fail save xml with JAXB.", e);
}
} | java | public static void save(final AnnotationMappingInfo xmlInfo, final OutputStream out) throws XmlOperateException {
ArgUtils.notNull(xmlInfo, "xmlInfo");
ArgUtils.notNull(out, "out");
try {
JAXB.marshal(xmlInfo, out);
} catch (DataBindingException e) {
throw new XmlOperateException("fail save xml with JAXB.", e);
}
} | [
"public",
"static",
"void",
"save",
"(",
"final",
"AnnotationMappingInfo",
"xmlInfo",
",",
"final",
"OutputStream",
"out",
")",
"throws",
"XmlOperateException",
"{",
"ArgUtils",
".",
"notNull",
"(",
"xmlInfo",
",",
"\"xmlInfo\"",
")",
";",
"ArgUtils",
".",
"notN... | XMLをファイルに保存する。
@since 1.1
@param xmlInfo XML情報。
@param out
@throws XmlOperateException XMLの書き込みに失敗した場合。
@throws IllegalArgumentException xmlInfo is null.
@throws IllegalArgumentException writer is null. | [
"XMLをファイルに保存する。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java#L109-L120 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/parse/cky/chart/Chart.java | Chart.getViterbiTree | private BinaryTree getViterbiTree(int start, int end, int rootSymbol) {
ChartCell cell = chart[start][end];
BackPointer bp = cell.getBp(rootSymbol);
if (bp == null) {
return null;
}
BinaryTree leftChild;
BinaryTree rightChild;
if (bp.r.isLexical()) {
String lcSymbolStr = grammar.getLexAlphabet().lookupObject(bp.r.getLeftChild());
leftChild = new BinaryTree(lcSymbolStr, start, end, null, null, true);
rightChild = null;
} else if (bp.r.isUnary()) {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = null;
} else {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = getViterbiTree(bp.mid, end, bp.r.getRightChild());
}
String rootSymbolStr = grammar.getNtAlphabet().lookupObject(rootSymbol);
return new BinaryTree(rootSymbolStr, start, end, leftChild, rightChild, false);
} | java | private BinaryTree getViterbiTree(int start, int end, int rootSymbol) {
ChartCell cell = chart[start][end];
BackPointer bp = cell.getBp(rootSymbol);
if (bp == null) {
return null;
}
BinaryTree leftChild;
BinaryTree rightChild;
if (bp.r.isLexical()) {
String lcSymbolStr = grammar.getLexAlphabet().lookupObject(bp.r.getLeftChild());
leftChild = new BinaryTree(lcSymbolStr, start, end, null, null, true);
rightChild = null;
} else if (bp.r.isUnary()) {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = null;
} else {
leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild());
rightChild = getViterbiTree(bp.mid, end, bp.r.getRightChild());
}
String rootSymbolStr = grammar.getNtAlphabet().lookupObject(rootSymbol);
return new BinaryTree(rootSymbolStr, start, end, leftChild, rightChild, false);
} | [
"private",
"BinaryTree",
"getViterbiTree",
"(",
"int",
"start",
",",
"int",
"end",
",",
"int",
"rootSymbol",
")",
"{",
"ChartCell",
"cell",
"=",
"chart",
"[",
"start",
"]",
"[",
"end",
"]",
";",
"BackPointer",
"bp",
"=",
"cell",
".",
"getBp",
"(",
"roo... | Gets the highest probability tree with the span (start, end) and the root symbol rootSymbol.
@param start The start of the span of the requested tree.
@param end The end of the span of the requested tree.
@param rootSymbol The symbol of the root of the requested tree.
@return The highest probability tree or null if no parse exists. | [
"Gets",
"the",
"highest",
"probability",
"tree",
"with",
"the",
"span",
"(",
"start",
"end",
")",
"and",
"the",
"root",
"symbol",
"rootSymbol",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/parse/cky/chart/Chart.java#L147-L170 |
Azure/azure-sdk-for-java | recoveryservices/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/v2016_06_01/implementation/VaultCertificatesInner.java | VaultCertificatesInner.create | public VaultCertificateResponseInner create(String resourceGroupName, String vaultName, String certificateName, RawCertificateData properties) {
return createWithServiceResponseAsync(resourceGroupName, vaultName, certificateName, properties).toBlocking().single().body();
} | java | public VaultCertificateResponseInner create(String resourceGroupName, String vaultName, String certificateName, RawCertificateData properties) {
return createWithServiceResponseAsync(resourceGroupName, vaultName, certificateName, properties).toBlocking().single().body();
} | [
"public",
"VaultCertificateResponseInner",
"create",
"(",
"String",
"resourceGroupName",
",",
"String",
"vaultName",
",",
"String",
"certificateName",
",",
"RawCertificateData",
"properties",
")",
"{",
"return",
"createWithServiceResponseAsync",
"(",
"resourceGroupName",
",... | Uploads a certificate for a resource.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param vaultName The name of the recovery services vault.
@param certificateName Certificate friendly name.
@param properties the RawCertificateData value
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VaultCertificateResponseInner object if successful. | [
"Uploads",
"a",
"certificate",
"for",
"a",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/recoveryservices/v2016_06_01/implementation/VaultCertificatesInner.java#L165-L167 |
twilio/twilio-java | src/main/java/com/twilio/converter/Promoter.java | Promoter.enumFromString | public static <T extends Enum<?>> T enumFromString(final String value, final T[] values) {
if (value == null) {
return null;
}
for (T v : values) {
if (v.toString().equalsIgnoreCase(value)) {
return v;
}
}
return null;
} | java | public static <T extends Enum<?>> T enumFromString(final String value, final T[] values) {
if (value == null) {
return null;
}
for (T v : values) {
if (v.toString().equalsIgnoreCase(value)) {
return v;
}
}
return null;
} | [
"public",
"static",
"<",
"T",
"extends",
"Enum",
"<",
"?",
">",
">",
"T",
"enumFromString",
"(",
"final",
"String",
"value",
",",
"final",
"T",
"[",
"]",
"values",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
... | Convert a string to a enum type.
@param value string value
@param values enum values
@param <T> enum type
@return converted enum if able to convert; null otherwise | [
"Convert",
"a",
"string",
"to",
"a",
"enum",
"type",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/converter/Promoter.java#L57-L69 |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java | AsteriskQueueImpl.createNewEntry | void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date dateReceived)
{
AsteriskQueueEntryImpl qe = new AsteriskQueueEntryImpl(server, this, channel, reportedPosition, dateReceived);
long delay = serviceLevel * 1000L;
if (delay > 0)
{
ServiceLevelTimerTask timerTask = new ServiceLevelTimerTask(qe);
timer.schedule(timerTask, delay);
synchronized (serviceLevelTimerTasks)
{
serviceLevelTimerTasks.put(qe, timerTask);
}
}
synchronized (entries)
{
entries.add(qe); // at the end of the list
// Keep the lock !
// This will fire PCE on the newly created queue entry
// but hopefully this one has no listeners yet
shift();
}
// Set the channel property ony here as queue entries and channels
// maintain a reciprocal reference.
// That way property change on channel and new entry event on queue will be
// lanched when BOTH channel and queue are correctly set.
channel.setQueueEntry(qe);
fireNewEntry(qe);
server.fireNewQueueEntry(qe);
} | java | void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date dateReceived)
{
AsteriskQueueEntryImpl qe = new AsteriskQueueEntryImpl(server, this, channel, reportedPosition, dateReceived);
long delay = serviceLevel * 1000L;
if (delay > 0)
{
ServiceLevelTimerTask timerTask = new ServiceLevelTimerTask(qe);
timer.schedule(timerTask, delay);
synchronized (serviceLevelTimerTasks)
{
serviceLevelTimerTasks.put(qe, timerTask);
}
}
synchronized (entries)
{
entries.add(qe); // at the end of the list
// Keep the lock !
// This will fire PCE on the newly created queue entry
// but hopefully this one has no listeners yet
shift();
}
// Set the channel property ony here as queue entries and channels
// maintain a reciprocal reference.
// That way property change on channel and new entry event on queue will be
// lanched when BOTH channel and queue are correctly set.
channel.setQueueEntry(qe);
fireNewEntry(qe);
server.fireNewQueueEntry(qe);
} | [
"void",
"createNewEntry",
"(",
"AsteriskChannelImpl",
"channel",
",",
"int",
"reportedPosition",
",",
"Date",
"dateReceived",
")",
"{",
"AsteriskQueueEntryImpl",
"qe",
"=",
"new",
"AsteriskQueueEntryImpl",
"(",
"server",
",",
"this",
",",
"channel",
",",
"reportedPo... | Creates a new AsteriskQueueEntry, adds it to this queue.<p>
Fires:
<ul>
<li>PCE on channel</li>
<li>NewEntry on this queue</li>
<li>PCE on other queue entries if shifted (never happens)</li>
<li>NewQueueEntry on server</li>
</ul>
@param channel the channel that joined the queue
@param reportedPosition the position as given by Asterisk (currently not used)
@param dateReceived the date the hannel joined the queue | [
"Creates",
"a",
"new",
"AsteriskQueueEntry",
"adds",
"it",
"to",
"this",
"queue",
".",
"<p",
">",
"Fires",
":",
"<ul",
">",
"<li",
">",
"PCE",
"on",
"channel<",
"/",
"li",
">",
"<li",
">",
"NewEntry",
"on",
"this",
"queue<",
"/",
"li",
">",
"<li",
... | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java#L353-L385 |
alkacon/opencms-core | src/org/opencms/main/CmsShell.java | CmsShell.validateUser | public boolean validateUser(String userName, String password, CmsRole requiredRole) {
boolean result = false;
try {
CmsUser user = m_cms.readUser(userName, password);
result = OpenCms.getRoleManager().hasRole(m_cms, user.getName(), requiredRole);
} catch (CmsException e) {
// nothing to do
}
return result;
} | java | public boolean validateUser(String userName, String password, CmsRole requiredRole) {
boolean result = false;
try {
CmsUser user = m_cms.readUser(userName, password);
result = OpenCms.getRoleManager().hasRole(m_cms, user.getName(), requiredRole);
} catch (CmsException e) {
// nothing to do
}
return result;
} | [
"public",
"boolean",
"validateUser",
"(",
"String",
"userName",
",",
"String",
"password",
",",
"CmsRole",
"requiredRole",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"try",
"{",
"CmsUser",
"user",
"=",
"m_cms",
".",
"readUser",
"(",
"userName",
",",
... | Validates the given user and password and checks if the user has the requested role.<p>
@param userName the user name
@param password the password
@param requiredRole the required role
@return <code>true</code> if the user is valid | [
"Validates",
"the",
"given",
"user",
"and",
"password",
"and",
"checks",
"if",
"the",
"user",
"has",
"the",
"requested",
"role",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShell.java#L1154-L1164 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/Channel.java | Channel.sendLifecycleApproveChaincodeDefinitionForMyOrgProposal | public LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(LifecycleApproveChaincodeDefinitionForMyOrgRequest lifecycleApproveChaincodeDefinitionForMyOrgRequest, Peer peer) throws ProposalException, InvalidArgumentException {
if (null == lifecycleApproveChaincodeDefinitionForMyOrgRequest) {
throw new InvalidArgumentException("The lifecycleApproveChaincodeDefinitionForMyOrgRequest parameter can not be null.");
}
Collection<LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse> lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses =
sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(lifecycleApproveChaincodeDefinitionForMyOrgRequest, Collections.singleton(peer));
return lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses.iterator().next();
} | java | public LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(LifecycleApproveChaincodeDefinitionForMyOrgRequest lifecycleApproveChaincodeDefinitionForMyOrgRequest, Peer peer) throws ProposalException, InvalidArgumentException {
if (null == lifecycleApproveChaincodeDefinitionForMyOrgRequest) {
throw new InvalidArgumentException("The lifecycleApproveChaincodeDefinitionForMyOrgRequest parameter can not be null.");
}
Collection<LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse> lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses =
sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(lifecycleApproveChaincodeDefinitionForMyOrgRequest, Collections.singleton(peer));
return lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses.iterator().next();
} | [
"public",
"LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse",
"sendLifecycleApproveChaincodeDefinitionForMyOrgProposal",
"(",
"LifecycleApproveChaincodeDefinitionForMyOrgRequest",
"lifecycleApproveChaincodeDefinitionForMyOrgRequest",
",",
"Peer",
"peer",
")",
"throws",
"ProposalExce... | Approve chaincode to be run on this peer's organization.
@param lifecycleApproveChaincodeDefinitionForMyOrgRequest the request see {@link LifecycleApproveChaincodeDefinitionForMyOrgRequest}
@param peer
@return A {@link LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse}
@throws ProposalException
@throws InvalidArgumentException | [
"Approve",
"chaincode",
"to",
"be",
"run",
"on",
"this",
"peer",
"s",
"organization",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L3431-L3441 |
apollographql/apollo-android | apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java | ResponseField.forDouble | public static ResponseField forDouble(String responseName, String fieldName, Map<String, Object> arguments,
boolean optional, List<Condition> conditions) {
return new ResponseField(Type.DOUBLE, responseName, fieldName, arguments, optional, conditions);
} | java | public static ResponseField forDouble(String responseName, String fieldName, Map<String, Object> arguments,
boolean optional, List<Condition> conditions) {
return new ResponseField(Type.DOUBLE, responseName, fieldName, arguments, optional, conditions);
} | [
"public",
"static",
"ResponseField",
"forDouble",
"(",
"String",
"responseName",
",",
"String",
"fieldName",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"arguments",
",",
"boolean",
"optional",
",",
"List",
"<",
"Condition",
">",
"conditions",
")",
"{",
"... | Factory method for creating a Field instance representing {@link Type#DOUBLE}.
@param responseName alias for the result of a field
@param fieldName name of the field in the GraphQL operation
@param arguments arguments to be passed along with the field
@param optional whether the arguments passed along are optional or required
@param conditions list of conditions for this field
@return Field instance representing {@link Type#DOUBLE} | [
"Factory",
"method",
"for",
"creating",
"a",
"Field",
"instance",
"representing",
"{",
"@link",
"Type#DOUBLE",
"}",
"."
] | train | https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java#L85-L88 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/BlockReader.java | BlockReader.sendReadResult | void sendReadResult(Socket sock, int statusCode) {
assert !sentStatusCode : "already sent status code to " + sock;
try {
OutputStream out = NetUtils.getOutputStream(sock, HdfsConstants.WRITE_TIMEOUT);
byte buf[] = { (byte) ((statusCode >>> 8) & 0xff),
(byte) ((statusCode) & 0xff) };
out.write(buf);
out.flush();
sentStatusCode = true;
} catch (IOException e) {
// its ok not to be able to send this.
LOG.debug("Could not write to datanode " + sock.getInetAddress() +
": " + e.getMessage());
}
} | java | void sendReadResult(Socket sock, int statusCode) {
assert !sentStatusCode : "already sent status code to " + sock;
try {
OutputStream out = NetUtils.getOutputStream(sock, HdfsConstants.WRITE_TIMEOUT);
byte buf[] = { (byte) ((statusCode >>> 8) & 0xff),
(byte) ((statusCode) & 0xff) };
out.write(buf);
out.flush();
sentStatusCode = true;
} catch (IOException e) {
// its ok not to be able to send this.
LOG.debug("Could not write to datanode " + sock.getInetAddress() +
": " + e.getMessage());
}
} | [
"void",
"sendReadResult",
"(",
"Socket",
"sock",
",",
"int",
"statusCode",
")",
"{",
"assert",
"!",
"sentStatusCode",
":",
"\"already sent status code to \"",
"+",
"sock",
";",
"try",
"{",
"OutputStream",
"out",
"=",
"NetUtils",
".",
"getOutputStream",
"(",
"soc... | When the reader reaches end of the read, it sends a status response
(e.g. CHECKSUM_OK) to the DN. Failure to do so could lead to the DN
closing our connection (which we will re-open), but won't affect
data correctness.
@param sock
@param statusCode | [
"When",
"the",
"reader",
"reaches",
"end",
"of",
"the",
"read",
"it",
"sends",
"a",
"status",
"response",
"(",
"e",
".",
"g",
".",
"CHECKSUM_OK",
")",
"to",
"the",
"DN",
".",
"Failure",
"to",
"do",
"so",
"could",
"lead",
"to",
"the",
"DN",
"closing",... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/BlockReader.java#L653-L668 |
Alluxio/alluxio | core/client/fs/src/main/java/alluxio/client/file/FileSystemUtils.java | FileSystemUtils.waitCompleted | public static boolean waitCompleted(FileSystem fs, AlluxioURI uri)
throws IOException, AlluxioException, InterruptedException {
return FileSystemUtils.waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS);
} | java | public static boolean waitCompleted(FileSystem fs, AlluxioURI uri)
throws IOException, AlluxioException, InterruptedException {
return FileSystemUtils.waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS);
} | [
"public",
"static",
"boolean",
"waitCompleted",
"(",
"FileSystem",
"fs",
",",
"AlluxioURI",
"uri",
")",
"throws",
"IOException",
",",
"AlluxioException",
",",
"InterruptedException",
"{",
"return",
"FileSystemUtils",
".",
"waitCompleted",
"(",
"fs",
",",
"uri",
",... | Shortcut for {@code waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS)}, i.e., wait for an
indefinite amount of time. Note that if a file is never completed, the thread will block
forever, so use with care.
@param fs a {@link FileSystem} instance
@param uri the URI of the file on which the thread should wait
@return true if the file is complete when this method returns and false if the method timed out
before the file was complete.
@throws InterruptedException if the thread receives an interrupt while waiting for file
completion
@see #waitCompleted(FileSystem, AlluxioURI, long, TimeUnit) | [
"Shortcut",
"for",
"{",
"@code",
"waitCompleted",
"(",
"fs",
"uri",
"-",
"1",
"TimeUnit",
".",
"MILLISECONDS",
")",
"}",
"i",
".",
"e",
".",
"wait",
"for",
"an",
"indefinite",
"amount",
"of",
"time",
".",
"Note",
"that",
"if",
"a",
"file",
"is",
"nev... | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/file/FileSystemUtils.java#L55-L58 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/translator/document/XMLEncodingDetector.java | XMLEncodingDetector.skipString | public boolean skipString(String s) throws IOException {
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip string
final int length = s.length();
for (int i = 0; i < length; i++) {
char c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c != s.charAt(i)) {
fCurrentEntity.position -= i + 1;
return false;
}
if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1);
// REVISIT: Can a string to be skipped cross an
// entity boundary? -Ac
if (load(i + 1, false)) {
fCurrentEntity.position -= i + 1;
return false;
}
}
}
fCurrentEntity.columnNumber += length;
return true;
} | java | public boolean skipString(String s) throws IOException {
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip string
final int length = s.length();
for (int i = 0; i < length; i++) {
char c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c != s.charAt(i)) {
fCurrentEntity.position -= i + 1;
return false;
}
if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1);
// REVISIT: Can a string to be skipped cross an
// entity boundary? -Ac
if (load(i + 1, false)) {
fCurrentEntity.position -= i + 1;
return false;
}
}
}
fCurrentEntity.columnNumber += length;
return true;
} | [
"public",
"boolean",
"skipString",
"(",
"String",
"s",
")",
"throws",
"IOException",
"{",
"// load more characters, if needed",
"if",
"(",
"fCurrentEntity",
".",
"position",
"==",
"fCurrentEntity",
".",
"count",
")",
"{",
"load",
"(",
"0",
",",
"true",
")",
";... | Skips the specified string appearing immediately on the input.
<p>
<strong>Note:</strong> The characters are consumed only if they are
space characters.
@param s The string to skip.
@return Returns true if the string was skipped.
@throws IOException Thrown if i/o error occurs.
@throws EOFException Thrown on end of file. | [
"Skips",
"the",
"specified",
"string",
"appearing",
"immediately",
"on",
"the",
"input",
".",
"<p",
">",
"<strong",
">",
"Note",
":",
"<",
"/",
"strong",
">",
"The",
"characters",
"are",
"consumed",
"only",
"if",
"they",
"are",
"space",
"characters",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/translator/document/XMLEncodingDetector.java#L940-L968 |
PureSolTechnologies/parsers | parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java | PackratParser.processIgnoredTokens | private void processIgnoredTokens(ParseTreeNode node, int position, int line, MemoEntry progress)
throws TreeException, ParserException {
MemoEntry newProgress = processIgnoredTokens(node, position + progress.getDeltaPosition(),
line + progress.getDeltaLine());
if ((!newProgress.getAnswer().equals(Status.FAILED)))
progress.add(newProgress);
} | java | private void processIgnoredTokens(ParseTreeNode node, int position, int line, MemoEntry progress)
throws TreeException, ParserException {
MemoEntry newProgress = processIgnoredTokens(node, position + progress.getDeltaPosition(),
line + progress.getDeltaLine());
if ((!newProgress.getAnswer().equals(Status.FAILED)))
progress.add(newProgress);
} | [
"private",
"void",
"processIgnoredTokens",
"(",
"ParseTreeNode",
"node",
",",
"int",
"position",
",",
"int",
"line",
",",
"MemoEntry",
"progress",
")",
"throws",
"TreeException",
",",
"ParserException",
"{",
"MemoEntry",
"newProgress",
"=",
"processIgnoredTokens",
"... | <p>
This method reads all hidden and ignored tokens from the text and puts them
into the node as children.
</p>
<p>
This is the non-recursive part of the procedure to be called by the packrat
parser. The procedure itself is implemented recursively in
{@link #processIgnoredTrailingTokens(ParseTreeNode, int, int, MemoEntry)}.
</p>
<p>
Attention: This method is package private for testing purposes!
</p>
@param node
is the current node in the {@link ParseTreeNode}
@param position
is the current parsing position.
@throws TreeException
@throws ParserException | [
"<p",
">",
"This",
"method",
"reads",
"all",
"hidden",
"and",
"ignored",
"tokens",
"from",
"the",
"text",
"and",
"puts",
"them",
"into",
"the",
"node",
"as",
"children",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"is",
"the",
"non",
"-",
"recursive"... | train | https://github.com/PureSolTechnologies/parsers/blob/61077223b90d3768ff9445ae13036343c98b63cd/parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java#L612-L618 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java | SVGUtil.svgRect | public static Element svgRect(Document document, double x, double y, double w, double h) {
Element rect = SVGUtil.svgElement(document, SVGConstants.SVG_RECT_TAG);
SVGUtil.setAtt(rect, SVGConstants.SVG_X_ATTRIBUTE, x);
SVGUtil.setAtt(rect, SVGConstants.SVG_Y_ATTRIBUTE, y);
SVGUtil.setAtt(rect, SVGConstants.SVG_WIDTH_ATTRIBUTE, w);
SVGUtil.setAtt(rect, SVGConstants.SVG_HEIGHT_ATTRIBUTE, h);
return rect;
} | java | public static Element svgRect(Document document, double x, double y, double w, double h) {
Element rect = SVGUtil.svgElement(document, SVGConstants.SVG_RECT_TAG);
SVGUtil.setAtt(rect, SVGConstants.SVG_X_ATTRIBUTE, x);
SVGUtil.setAtt(rect, SVGConstants.SVG_Y_ATTRIBUTE, y);
SVGUtil.setAtt(rect, SVGConstants.SVG_WIDTH_ATTRIBUTE, w);
SVGUtil.setAtt(rect, SVGConstants.SVG_HEIGHT_ATTRIBUTE, h);
return rect;
} | [
"public",
"static",
"Element",
"svgRect",
"(",
"Document",
"document",
",",
"double",
"x",
",",
"double",
"y",
",",
"double",
"w",
",",
"double",
"h",
")",
"{",
"Element",
"rect",
"=",
"SVGUtil",
".",
"svgElement",
"(",
"document",
",",
"SVGConstants",
"... | Create a SVG rectangle element.
@param document document to create in (factory)
@param x X coordinate
@param y Y coordinate
@param w Width
@param h Height
@return new element | [
"Create",
"a",
"SVG",
"rectangle",
"element",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java#L428-L435 |
LearnLib/learnlib | commons/counterexamples/src/main/java/de/learnlib/counterexamples/GlobalSuffixFinders.java | GlobalSuffixFinders.suffixesForLocalOutput | public static <I, D> List<Word<I>> suffixesForLocalOutput(Query<I, D> ceQuery, int localSuffixIdx) {
return suffixesForLocalOutput(ceQuery, localSuffixIdx, false);
} | java | public static <I, D> List<Word<I>> suffixesForLocalOutput(Query<I, D> ceQuery, int localSuffixIdx) {
return suffixesForLocalOutput(ceQuery, localSuffixIdx, false);
} | [
"public",
"static",
"<",
"I",
",",
"D",
">",
"List",
"<",
"Word",
"<",
"I",
">",
">",
"suffixesForLocalOutput",
"(",
"Query",
"<",
"I",
",",
"D",
">",
"ceQuery",
",",
"int",
"localSuffixIdx",
")",
"{",
"return",
"suffixesForLocalOutput",
"(",
"ceQuery",
... | Transforms a suffix index returned by a {@link LocalSuffixFinder} into a list containing the single
distinguishing suffix. | [
"Transforms",
"a",
"suffix",
"index",
"returned",
"by",
"a",
"{"
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/commons/counterexamples/src/main/java/de/learnlib/counterexamples/GlobalSuffixFinders.java#L182-L184 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java | AttributeDefinition.resolveModelAttribute | public ModelNode resolveModelAttribute(final OperationContext context, final ModelNode model) throws OperationFailedException {
return resolveModelAttribute(new ExpressionResolver() {
@Override
public ModelNode resolveExpressions(ModelNode node) throws OperationFailedException {
return context.resolveExpressions(node);
}
}, model);
} | java | public ModelNode resolveModelAttribute(final OperationContext context, final ModelNode model) throws OperationFailedException {
return resolveModelAttribute(new ExpressionResolver() {
@Override
public ModelNode resolveExpressions(ModelNode node) throws OperationFailedException {
return context.resolveExpressions(node);
}
}, model);
} | [
"public",
"ModelNode",
"resolveModelAttribute",
"(",
"final",
"OperationContext",
"context",
",",
"final",
"ModelNode",
"model",
")",
"throws",
"OperationFailedException",
"{",
"return",
"resolveModelAttribute",
"(",
"new",
"ExpressionResolver",
"(",
")",
"{",
"@",
"O... | Finds a value in the given {@code model} whose key matches this attribute's {@link #getName() name},
uses the given {@code context} to {@link OperationContext#resolveExpressions(org.jboss.dmr.ModelNode) resolve}
it and validates it using this attribute's {@link #getValidator() validator}. If the value is
undefined and a {@link #getDefaultValue() default value} is available, the default value is used.
@param context the operation context
@param model model node of type {@link ModelType#OBJECT}, typically representing a model resource
@return the resolved value, possibly the default value if the model does not have a defined value matching
this attribute's name
@throws OperationFailedException if the value is not valid | [
"Finds",
"a",
"value",
"in",
"the",
"given",
"{",
"@code",
"model",
"}",
"whose",
"key",
"matches",
"this",
"attribute",
"s",
"{",
"@link",
"#getName",
"()",
"name",
"}",
"uses",
"the",
"given",
"{",
"@code",
"context",
"}",
"to",
"{",
"@link",
"Operat... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java#L599-L606 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java | QrCodeUtil.generate | public static BufferedImage generate(String content, BarcodeFormat format, int width, int height) {
return generate(content, format, new QrConfig(width, height));
} | java | public static BufferedImage generate(String content, BarcodeFormat format, int width, int height) {
return generate(content, format, new QrConfig(width, height));
} | [
"public",
"static",
"BufferedImage",
"generate",
"(",
"String",
"content",
",",
"BarcodeFormat",
"format",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"return",
"generate",
"(",
"content",
",",
"format",
",",
"new",
"QrConfig",
"(",
"width",
",",
... | 生成二维码或条形码图片
@param content 文本内容
@param format 格式,可选二维码或者条形码
@param width 宽度
@param height 高度
@return 二维码图片(黑白) | [
"生成二维码或条形码图片"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java#L146-L148 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_easyHunting_serviceName_screenListConditions_conditions_conditionId_GET | public OvhEasyHuntingScreenListsConditions billingAccount_easyHunting_serviceName_screenListConditions_conditions_conditionId_GET(String billingAccount, String serviceName, Long conditionId) throws IOException {
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions/conditions/{conditionId}";
StringBuilder sb = path(qPath, billingAccount, serviceName, conditionId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhEasyHuntingScreenListsConditions.class);
} | java | public OvhEasyHuntingScreenListsConditions billingAccount_easyHunting_serviceName_screenListConditions_conditions_conditionId_GET(String billingAccount, String serviceName, Long conditionId) throws IOException {
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions/conditions/{conditionId}";
StringBuilder sb = path(qPath, billingAccount, serviceName, conditionId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhEasyHuntingScreenListsConditions.class);
} | [
"public",
"OvhEasyHuntingScreenListsConditions",
"billingAccount_easyHunting_serviceName_screenListConditions_conditions_conditionId_GET",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"Long",
"conditionId",
")",
"throws",
"IOException",
"{",
"String",
"qPath"... | Get this object properties
REST: GET /telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions/conditions/{conditionId}
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
@param conditionId [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3253-L3258 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/mq/kafka/Consumer.java | Consumer.initializeTopic | public void initializeTopic(String topic) {
if (_topics.get(topic) == null) {
synchronized (this) {
if (_topics.get(topic) == null) {
_logger.info("Initializing streams for topic: {}", topic);
Properties props = new Properties();
props.setProperty("zookeeper.connect",
_configuration.getValue(Property.ZOOKEEPER_CONNECT.getName(), Property.ZOOKEEPER_CONNECT.getDefaultValue()));
props.setProperty("group.id",
_configuration.getValue(Property.KAFKA_CONSUMER_GROUPID.getName(), Property.KAFKA_CONSUMER_GROUPID.getDefaultValue()));
props.setProperty("auto.offset.reset", _configuration.getValue(Property.KAFKA_CONSUMER_OFFSET_RESET.getName(), Property.KAFKA_CONSUMER_OFFSET_RESET.getDefaultValue()));
props.setProperty("auto.commit.interval.ms", "60000");
props.setProperty("fetch.message.max.bytes", "2000000");
ConsumerConnector consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props));
List<KafkaStream<byte[], byte[]>> streams = _createStreams(consumer, topic);
Topic t = new Topic(topic, consumer, streams.size());
_topics.put(topic, t);
_startStreamingMessages(topic, streams);
}
}
}
} | java | public void initializeTopic(String topic) {
if (_topics.get(topic) == null) {
synchronized (this) {
if (_topics.get(topic) == null) {
_logger.info("Initializing streams for topic: {}", topic);
Properties props = new Properties();
props.setProperty("zookeeper.connect",
_configuration.getValue(Property.ZOOKEEPER_CONNECT.getName(), Property.ZOOKEEPER_CONNECT.getDefaultValue()));
props.setProperty("group.id",
_configuration.getValue(Property.KAFKA_CONSUMER_GROUPID.getName(), Property.KAFKA_CONSUMER_GROUPID.getDefaultValue()));
props.setProperty("auto.offset.reset", _configuration.getValue(Property.KAFKA_CONSUMER_OFFSET_RESET.getName(), Property.KAFKA_CONSUMER_OFFSET_RESET.getDefaultValue()));
props.setProperty("auto.commit.interval.ms", "60000");
props.setProperty("fetch.message.max.bytes", "2000000");
ConsumerConnector consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props));
List<KafkaStream<byte[], byte[]>> streams = _createStreams(consumer, topic);
Topic t = new Topic(topic, consumer, streams.size());
_topics.put(topic, t);
_startStreamingMessages(topic, streams);
}
}
}
} | [
"public",
"void",
"initializeTopic",
"(",
"String",
"topic",
")",
"{",
"if",
"(",
"_topics",
".",
"get",
"(",
"topic",
")",
"==",
"null",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"_topics",
".",
"get",
"(",
"topic",
")",
"==",
"n... | This method creates Kafka streams for a topic so that messages can be streamed to the local buffer. If the streams for the given topic have
already been initialized the returns. Information about a particular topic is stored in a HashMap. This method uses double-checked locking to
make sure only one client thread can initialize streams for a topic. Moreover, it also helps subsequent calls, to check if the topic has been
initialized, be not synchronized and hence return faster.
@param topic The topic to initialize. | [
"This",
"method",
"creates",
"Kafka",
"streams",
"for",
"a",
"topic",
"so",
"that",
"messages",
"can",
"be",
"streamed",
"to",
"the",
"local",
"buffer",
".",
"If",
"the",
"streams",
"for",
"the",
"given",
"topic",
"have",
"already",
"been",
"initialized",
... | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/mq/kafka/Consumer.java#L103-L128 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/SegmentKeyCache.java | SegmentKeyCache.evictBefore | synchronized EvictionResult evictBefore(int oldestGeneration) {
// Remove those entries that have a generation below the oldest permissible one.
long sizeRemoved = 0;
ArrayList<Short> removedGroups = new ArrayList<>();
for (val e : this.cacheEntries.entrySet()) {
CacheEntry entry = e.getValue();
if (entry.getGeneration() < oldestGeneration
&& entry.getHighestOffset() < this.lastIndexedOffset) {
removedGroups.add(e.getKey());
sizeRemoved += entry.getSize();
}
}
// Clear the expired cache entries.
removedGroups.forEach(this.cacheEntries::remove);
// Remove from the Cache. It's ok to do this outside of the lock as the cache is thread safe.
return new EvictionResult(sizeRemoved, removedGroups.stream().map(CacheKey::new).collect(Collectors.toList()));
} | java | synchronized EvictionResult evictBefore(int oldestGeneration) {
// Remove those entries that have a generation below the oldest permissible one.
long sizeRemoved = 0;
ArrayList<Short> removedGroups = new ArrayList<>();
for (val e : this.cacheEntries.entrySet()) {
CacheEntry entry = e.getValue();
if (entry.getGeneration() < oldestGeneration
&& entry.getHighestOffset() < this.lastIndexedOffset) {
removedGroups.add(e.getKey());
sizeRemoved += entry.getSize();
}
}
// Clear the expired cache entries.
removedGroups.forEach(this.cacheEntries::remove);
// Remove from the Cache. It's ok to do this outside of the lock as the cache is thread safe.
return new EvictionResult(sizeRemoved, removedGroups.stream().map(CacheKey::new).collect(Collectors.toList()));
} | [
"synchronized",
"EvictionResult",
"evictBefore",
"(",
"int",
"oldestGeneration",
")",
"{",
"// Remove those entries that have a generation below the oldest permissible one.",
"long",
"sizeRemoved",
"=",
"0",
";",
"ArrayList",
"<",
"Short",
">",
"removedGroups",
"=",
"new",
... | Collects and unregisters all Cache Entries with a generation smaller than the given one. This method does not
actually execute the eviction since it is invoked while a lock is held in {@link ContainerKeyCache}. The caller
({@link ContainerKeyCache}) needs to execute the actual cache eviction.
@param oldestGeneration The oldest permissible generation.
@return An {@link EvictionResult} instance containing the number of bytes evicted and the {@link Cache.Key} for
each Cache Entry that needs eviction. | [
"Collects",
"and",
"unregisters",
"all",
"Cache",
"Entries",
"with",
"a",
"generation",
"smaller",
"than",
"the",
"given",
"one",
".",
"This",
"method",
"does",
"not",
"actually",
"execute",
"the",
"eviction",
"since",
"it",
"is",
"invoked",
"while",
"a",
"l... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/SegmentKeyCache.java#L102-L120 |
hawtio/hawtio | hawtio-util/src/main/java/io/hawt/util/introspect/support/ClassScanner.java | ClassScanner.setClassLoaderProvider | public void setClassLoaderProvider(String id, ClassLoaderProvider classLoaderProvider) {
if (classLoaderProvider != null) {
classLoaderProviderMap.put(id, classLoaderProvider);
} else {
classLoaderProviderMap.remove(id);
}
} | java | public void setClassLoaderProvider(String id, ClassLoaderProvider classLoaderProvider) {
if (classLoaderProvider != null) {
classLoaderProviderMap.put(id, classLoaderProvider);
} else {
classLoaderProviderMap.remove(id);
}
} | [
"public",
"void",
"setClassLoaderProvider",
"(",
"String",
"id",
",",
"ClassLoaderProvider",
"classLoaderProvider",
")",
"{",
"if",
"(",
"classLoaderProvider",
"!=",
"null",
")",
"{",
"classLoaderProviderMap",
".",
"put",
"(",
"id",
",",
"classLoaderProvider",
")",
... | Registers a named class loader provider or removes it if the classLoaderProvider is null | [
"Registers",
"a",
"named",
"class",
"loader",
"provider",
"or",
"removes",
"it",
"if",
"the",
"classLoaderProvider",
"is",
"null"
] | train | https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/hawtio-util/src/main/java/io/hawt/util/introspect/support/ClassScanner.java#L82-L88 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java | IOGroovyMethods.withWriter | public static <T> T withWriter(Writer writer, @ClosureParams(FirstParam.class) Closure<T> closure) throws IOException {
try {
T result = closure.call(writer);
try {
writer.flush();
} catch (IOException e) {
// try to continue even in case of error
}
Writer temp = writer;
writer = null;
temp.close();
return result;
} finally {
closeWithWarning(writer);
}
} | java | public static <T> T withWriter(Writer writer, @ClosureParams(FirstParam.class) Closure<T> closure) throws IOException {
try {
T result = closure.call(writer);
try {
writer.flush();
} catch (IOException e) {
// try to continue even in case of error
}
Writer temp = writer;
writer = null;
temp.close();
return result;
} finally {
closeWithWarning(writer);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"withWriter",
"(",
"Writer",
"writer",
",",
"@",
"ClosureParams",
"(",
"FirstParam",
".",
"class",
")",
"Closure",
"<",
"T",
">",
"closure",
")",
"throws",
"IOException",
"{",
"try",
"{",
"T",
"result",
"=",
"clo... | Allows this writer to be used within the closure, ensuring that it
is flushed and closed before this method returns.
@param writer the writer which is used and then closed
@param closure the closure that the writer is passed into
@return the value returned by the closure
@throws IOException if an IOException occurs.
@since 1.5.2 | [
"Allows",
"this",
"writer",
"to",
"be",
"used",
"within",
"the",
"closure",
"ensuring",
"that",
"it",
"is",
"flushed",
"and",
"closed",
"before",
"this",
"method",
"returns",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/IOGroovyMethods.java#L1131-L1147 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/dispatcher/DataContextUtils.java | DataContextUtils.replaceDataReferences | public static Map<String, Object> replaceDataReferences(
final Map<String, Object> input,
final Map<String, Map<String, String>> data
)
{
return replaceDataReferences(input, data, null, false, false);
} | java | public static Map<String, Object> replaceDataReferences(
final Map<String, Object> input,
final Map<String, Map<String, String>> data
)
{
return replaceDataReferences(input, data, null, false, false);
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"replaceDataReferences",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"input",
",",
"final",
"Map",
"<",
"String",
",",
"Map",
"<",
"String",
",",
"String",
">",
">",
"data",
")",... | Recursively replace data references in the values in a map which contains either string, collection or Map
values.
@param input input map
@param data context data
@return Map with all string values having references replaced | [
"Recursively",
"replace",
"data",
"references",
"in",
"the",
"values",
"in",
"a",
"map",
"which",
"contains",
"either",
"string",
"collection",
"or",
"Map",
"values",
"."
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/dispatcher/DataContextUtils.java#L183-L189 |
jcuda/jnvgraph | JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java | JNvgraph.nvgraphSssp | public static int nvgraphSssp(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
long weight_index,
Pointer source_vert,
long sssp_index)
{
return checkResult(nvgraphSsspNative(handle, descrG, weight_index, source_vert, sssp_index));
} | java | public static int nvgraphSssp(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
long weight_index,
Pointer source_vert,
long sssp_index)
{
return checkResult(nvgraphSsspNative(handle, descrG, weight_index, source_vert, sssp_index));
} | [
"public",
"static",
"int",
"nvgraphSssp",
"(",
"nvgraphHandle",
"handle",
",",
"nvgraphGraphDescr",
"descrG",
",",
"long",
"weight_index",
",",
"Pointer",
"source_vert",
",",
"long",
"sssp_index",
")",
"{",
"return",
"checkResult",
"(",
"nvgraphSsspNative",
"(",
"... | nvGRAPH Single Source Shortest Path (SSSP)
Calculate the shortest path distance from a single vertex in the graph to all other vertices. | [
"nvGRAPH",
"Single",
"Source",
"Shortest",
"Path",
"(",
"SSSP",
")",
"Calculate",
"the",
"shortest",
"path",
"distance",
"from",
"a",
"single",
"vertex",
"in",
"the",
"graph",
"to",
"all",
"other",
"vertices",
"."
] | train | https://github.com/jcuda/jnvgraph/blob/2c6bd7c58edac181753bacf30af2cceeb1989a78/JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java#L605-L613 |
twitter/cloudhopper-commons | ch-commons-gsm/src/main/java/com/cloudhopper/commons/gsm/DataCoding.java | DataCoding.createReservedGroup | static public DataCoding createReservedGroup(byte dcs) {
return new DataCoding(dcs, Group.RESERVED, CHAR_ENC_DEFAULT, MESSAGE_CLASS_0, false);
} | java | static public DataCoding createReservedGroup(byte dcs) {
return new DataCoding(dcs, Group.RESERVED, CHAR_ENC_DEFAULT, MESSAGE_CLASS_0, false);
} | [
"static",
"public",
"DataCoding",
"createReservedGroup",
"(",
"byte",
"dcs",
")",
"{",
"return",
"new",
"DataCoding",
"(",
"dcs",
",",
"Group",
".",
"RESERVED",
",",
"CHAR_ENC_DEFAULT",
",",
"MESSAGE_CLASS_0",
",",
"false",
")",
";",
"}"
] | Creates a "Reserved" group data coding scheme. NOTE: this method does
not actually check if the byte value is reserved, its assumed the caller
just wants to store the byte value.
@param dcs The data coding scheme byte value
@return A new immutable DataCoding instance representing this data coding scheme | [
"Creates",
"a",
"Reserved",
"group",
"data",
"coding",
"scheme",
".",
"NOTE",
":",
"this",
"method",
"does",
"not",
"actually",
"check",
"if",
"the",
"byte",
"value",
"is",
"reserved",
"its",
"assumed",
"the",
"caller",
"just",
"wants",
"to",
"store",
"the... | train | https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-gsm/src/main/java/com/cloudhopper/commons/gsm/DataCoding.java#L332-L334 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/GPXRead.java | GPXRead.readGPX | public static void readGPX(Connection connection, String fileName, String tableReference) throws IOException, SQLException {
readGPX(connection, fileName, tableReference, false);
} | java | public static void readGPX(Connection connection, String fileName, String tableReference) throws IOException, SQLException {
readGPX(connection, fileName, tableReference, false);
} | [
"public",
"static",
"void",
"readGPX",
"(",
"Connection",
"connection",
",",
"String",
"fileName",
",",
"String",
"tableReference",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"readGPX",
"(",
"connection",
",",
"fileName",
",",
"tableReference",
",",
... | Copy data from GPX File into a new table in specified connection.
@param connection Active connection
@param tableReference [[catalog.]schema.]table reference
@param fileName File path of the SHP file
@throws java.io.IOException
@throws java.sql.SQLException | [
"Copy",
"data",
"from",
"GPX",
"File",
"into",
"a",
"new",
"table",
"in",
"specified",
"connection",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/GPXRead.java#L81-L83 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsVfsDriver.java | CmsVfsDriver.internalRemoveFolder | protected void internalRemoveFolder(CmsDbContext dbc, CmsProject currentProject, CmsResource resource)
throws CmsDataAccessException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(dbc);
// delete the structure record
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_STRUCTURE_DELETE_BY_STRUCTUREID");
stmt.setString(1, resource.getStructureId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(dbc, null, stmt, null);
// delete the resource record
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCES_DELETE_BY_RESOURCEID");
stmt.setString(1, resource.getResourceId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw new CmsDbSqlException(
Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)),
e);
} finally {
m_sqlManager.closeAll(dbc, conn, stmt, null);
}
} | java | protected void internalRemoveFolder(CmsDbContext dbc, CmsProject currentProject, CmsResource resource)
throws CmsDataAccessException {
PreparedStatement stmt = null;
Connection conn = null;
try {
conn = m_sqlManager.getConnection(dbc);
// delete the structure record
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_STRUCTURE_DELETE_BY_STRUCTUREID");
stmt.setString(1, resource.getStructureId().toString());
stmt.executeUpdate();
m_sqlManager.closeAll(dbc, null, stmt, null);
// delete the resource record
stmt = m_sqlManager.getPreparedStatement(conn, currentProject, "C_RESOURCES_DELETE_BY_RESOURCEID");
stmt.setString(1, resource.getResourceId().toString());
stmt.executeUpdate();
} catch (SQLException e) {
throw new CmsDbSqlException(
Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)),
e);
} finally {
m_sqlManager.closeAll(dbc, conn, stmt, null);
}
} | [
"protected",
"void",
"internalRemoveFolder",
"(",
"CmsDbContext",
"dbc",
",",
"CmsProject",
"currentProject",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsDataAccessException",
"{",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"Connection",
"conn",
"=",
"null"... | Removes a resource physically in the database.<p>
@param dbc the current database context
@param currentProject the current project
@param resource the folder to remove
@throws CmsDataAccessException if something goes wrong | [
"Removes",
"a",
"resource",
"physically",
"in",
"the",
"database",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsVfsDriver.java#L3987-L4014 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addErrorsCrudInvalidMode | public FessMessages addErrorsCrudInvalidMode(String property, String arg0, String arg1) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_crud_invalid_mode, arg0, arg1));
return this;
} | java | public FessMessages addErrorsCrudInvalidMode(String property, String arg0, String arg1) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_crud_invalid_mode, arg0, arg1));
return this;
} | [
"public",
"FessMessages",
"addErrorsCrudInvalidMode",
"(",
"String",
"property",
",",
"String",
"arg0",
",",
"String",
"arg1",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"ERRORS_crud_invali... | Add the created action message for the key 'errors.crud_invalid_mode' with parameters.
<pre>
message: Invalid mode(expected value is {0}, but it's {1}).
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@param arg1 The parameter arg1 for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"errors",
".",
"crud_invalid_mode",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"Invalid",
"mode",
"(",
"expected",
"value",
"is",
"{",
"0",
"}",
"but",
"it",
"s",
"{",
"1",
... | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L2096-L2100 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java | CommonOps_DDF2.subtractEquals | public static void subtractEquals( DMatrix2 a , DMatrix2 b ) {
a.a1 -= b.a1;
a.a2 -= b.a2;
} | java | public static void subtractEquals( DMatrix2 a , DMatrix2 b ) {
a.a1 -= b.a1;
a.a2 -= b.a2;
} | [
"public",
"static",
"void",
"subtractEquals",
"(",
"DMatrix2",
"a",
",",
"DMatrix2",
"b",
")",
"{",
"a",
".",
"a1",
"-=",
"b",
".",
"a1",
";",
"a",
".",
"a2",
"-=",
"b",
".",
"a2",
";",
"}"
] | <p>Performs the following operation:<br>
<br>
a = a - b <br>
a<sub>i</sub> = a<sub>i</sub> - b<sub>i</sub> <br>
</p>
@param a A Vector. Modified.
@param b A Vector. Not modified. | [
"<p",
">",
"Performs",
"the",
"following",
"operation",
":",
"<br",
">",
"<br",
">",
"a",
"=",
"a",
"-",
"b",
"<br",
">",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"-",
"b<sub",
">",
"i<",
"/",
"sub",
">",... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L175-L178 |
javalite/activeweb | javalite-async/src/main/java/org/javalite/async/Async.java | Async.receiveCommand | @SuppressWarnings("unchecked")
public <T extends Command> T receiveCommand(String queueName, int timeout, Class<T> type) {
return (T) receiveCommand(queueName, timeout);
} | java | @SuppressWarnings("unchecked")
public <T extends Command> T receiveCommand(String queueName, int timeout, Class<T> type) {
return (T) receiveCommand(queueName, timeout);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"Command",
">",
"T",
"receiveCommand",
"(",
"String",
"queueName",
",",
"int",
"timeout",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"(",
"T",
")",
"receiveC... | Receives a command from a queue synchronously. If this queue also has listeners, then commands will be distributed across
all consumers.
@param queueName name of queue
@param timeout timeout in milliseconds. If a command is not received during a timeout, this methods returns null.
@param type expected class of a command
@return command if found. If command not found, this method will block till a command is present in queue.
@see {@link #receiveCommand(String, long)} | [
"Receives",
"a",
"command",
"from",
"a",
"queue",
"synchronously",
".",
"If",
"this",
"queue",
"also",
"has",
"listeners",
"then",
"commands",
"will",
"be",
"distributed",
"across",
"all",
"consumers",
"."
] | train | https://github.com/javalite/activeweb/blob/f25f589da94852b6f5625182360732e0861794a6/javalite-async/src/main/java/org/javalite/async/Async.java#L418-L421 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/SloppyBugComparator.java | SloppyBugComparator.compareClassesAllowingNull | private int compareClassesAllowingNull(ClassAnnotation lhs, ClassAnnotation rhs) {
if (lhs == null || rhs == null) {
return compareNullElements(lhs, rhs);
}
String lhsClassName = classNameRewriter.rewriteClassName(lhs.getClassName());
String rhsClassName = classNameRewriter.rewriteClassName(rhs.getClassName());
if (DEBUG) {
System.err.println("Comparing " + lhsClassName + " and " + rhsClassName);
}
int cmp = lhsClassName.compareTo(rhsClassName);
if (DEBUG) {
System.err.println("\t==> " + cmp);
}
return cmp;
} | java | private int compareClassesAllowingNull(ClassAnnotation lhs, ClassAnnotation rhs) {
if (lhs == null || rhs == null) {
return compareNullElements(lhs, rhs);
}
String lhsClassName = classNameRewriter.rewriteClassName(lhs.getClassName());
String rhsClassName = classNameRewriter.rewriteClassName(rhs.getClassName());
if (DEBUG) {
System.err.println("Comparing " + lhsClassName + " and " + rhsClassName);
}
int cmp = lhsClassName.compareTo(rhsClassName);
if (DEBUG) {
System.err.println("\t==> " + cmp);
}
return cmp;
} | [
"private",
"int",
"compareClassesAllowingNull",
"(",
"ClassAnnotation",
"lhs",
",",
"ClassAnnotation",
"rhs",
")",
"{",
"if",
"(",
"lhs",
"==",
"null",
"||",
"rhs",
"==",
"null",
")",
"{",
"return",
"compareNullElements",
"(",
"lhs",
",",
"rhs",
")",
";",
... | Compare class annotations.
@param lhs
left hand class annotation
@param rhs
right hand class annotation
@return comparison of the class annotations | [
"Compare",
"class",
"annotations",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SloppyBugComparator.java#L63-L80 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.mixin | public static void mixin(MetaClass self, List<Class> categoryClasses) {
MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses);
} | java | public static void mixin(MetaClass self, List<Class> categoryClasses) {
MixinInMetaClass.mixinClassesToMetaClass(self, categoryClasses);
} | [
"public",
"static",
"void",
"mixin",
"(",
"MetaClass",
"self",
",",
"List",
"<",
"Class",
">",
"categoryClasses",
")",
"{",
"MixinInMetaClass",
".",
"mixinClassesToMetaClass",
"(",
"self",
",",
"categoryClasses",
")",
";",
"}"
] | Extend object with category methods.
All methods for given class and all super classes will be added to the object.
@param self any Class
@param categoryClasses a category classes to use
@since 1.6.0 | [
"Extend",
"object",
"with",
"category",
"methods",
".",
"All",
"methods",
"for",
"given",
"class",
"and",
"all",
"super",
"classes",
"will",
"be",
"added",
"to",
"the",
"object",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L566-L568 |
antopen/alipay-sdk-java | src/main/java/com/alipay/api/internal/util/XmlUtils.java | XmlUtils.getDocument | public static Document getDocument(InputStream in) throws AlipayApiException {
Document doc = null;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
doc = builder.parse(in);
} catch (ParserConfigurationException e) {
throw new AlipayApiException(e);
} catch (SAXException e) {
throw new AlipayApiException("XML_PARSE_ERROR", e);
} catch (IOException e) {
throw new AlipayApiException("XML_READ_ERROR", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// nothing to do
}
}
}
return doc;
} | java | public static Document getDocument(InputStream in) throws AlipayApiException {
Document doc = null;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
doc = builder.parse(in);
} catch (ParserConfigurationException e) {
throw new AlipayApiException(e);
} catch (SAXException e) {
throw new AlipayApiException("XML_PARSE_ERROR", e);
} catch (IOException e) {
throw new AlipayApiException("XML_READ_ERROR", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// nothing to do
}
}
}
return doc;
} | [
"public",
"static",
"Document",
"getDocument",
"(",
"InputStream",
"in",
")",
"throws",
"AlipayApiException",
"{",
"Document",
"doc",
"=",
"null",
";",
"try",
"{",
"DocumentBuilder",
"builder",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
".",
"n... | Parses the content of the given stream as an XML document.
@param in the XML file input stream
@return the document instance representing the entire XML document
@throws ApiException problem parsing the XML input stream | [
"Parses",
"the",
"content",
"of",
"the",
"given",
"stream",
"as",
"an",
"XML",
"document",
"."
] | train | https://github.com/antopen/alipay-sdk-java/blob/e82aeac7d0239330ee173c7e393596e51e41c1cd/src/main/java/com/alipay/api/internal/util/XmlUtils.java#L96-L120 |
aws/aws-sdk-java | aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/model/PlatformApplication.java | PlatformApplication.withAttributes | public PlatformApplication withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} | java | public PlatformApplication withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} | [
"public",
"PlatformApplication",
"withAttributes",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"setAttributes",
"(",
"attributes",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Attributes for platform application object.
</p>
@param attributes
Attributes for platform application object.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Attributes",
"for",
"platform",
"application",
"object",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/model/PlatformApplication.java#L120-L123 |
m-m-m/util | xml/src/main/java/net/sf/mmm/util/xml/base/DomUtilImpl.java | DomUtilImpl.createTransformer | private Transformer createTransformer(boolean indent) {
try {
Transformer result = this.transformerFactory.newTransformer();
if (indent) {
result.setOutputProperty(OutputKeys.INDENT, "yes");
}
return result;
} catch (TransformerConfigurationException e) {
throw new IllegalStateException("XML Transformer misconfigured!" + " Probably your JVM does not support the required JAXP version!", e);
}
} | java | private Transformer createTransformer(boolean indent) {
try {
Transformer result = this.transformerFactory.newTransformer();
if (indent) {
result.setOutputProperty(OutputKeys.INDENT, "yes");
}
return result;
} catch (TransformerConfigurationException e) {
throw new IllegalStateException("XML Transformer misconfigured!" + " Probably your JVM does not support the required JAXP version!", e);
}
} | [
"private",
"Transformer",
"createTransformer",
"(",
"boolean",
"indent",
")",
"{",
"try",
"{",
"Transformer",
"result",
"=",
"this",
".",
"transformerFactory",
".",
"newTransformer",
"(",
")",
";",
"if",
"(",
"indent",
")",
"{",
"result",
".",
"setOutputProper... | This method creates a new transformer.
@param indent - {@code true} if the XML should be indented (automatically add linebreaks before opening
tags), {@code false} otherwise.
@return the new transformer. | [
"This",
"method",
"creates",
"a",
"new",
"transformer",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/xml/src/main/java/net/sf/mmm/util/xml/base/DomUtilImpl.java#L176-L187 |
osglworks/java-tool | src/main/java/org/osgl/OsglConfig.java | OsglConfig.addGlobalMappingFilters | public static void addGlobalMappingFilters(String filterSpec, String ... filterSpecs) {
addGlobalMappingFilter(filterSpec);
for (String s : filterSpecs) {
addGlobalMappingFilter(s);
}
} | java | public static void addGlobalMappingFilters(String filterSpec, String ... filterSpecs) {
addGlobalMappingFilter(filterSpec);
for (String s : filterSpecs) {
addGlobalMappingFilter(s);
}
} | [
"public",
"static",
"void",
"addGlobalMappingFilters",
"(",
"String",
"filterSpec",
",",
"String",
"...",
"filterSpecs",
")",
"{",
"addGlobalMappingFilter",
"(",
"filterSpec",
")",
";",
"for",
"(",
"String",
"s",
":",
"filterSpecs",
")",
"{",
"addGlobalMappingFilt... | Register global mapping filters.
@param filterSpec
the first filter spec
@param filterSpecs
other filter specs
@see #addGlobalMappingFilter(String) | [
"Register",
"global",
"mapping",
"filters",
"."
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/OsglConfig.java#L158-L163 |
Red5/red5-websocket | src/main/java/org/red5/net/websocket/WebSocketConnection.java | WebSocketConnection.sendPong | public void sendPong(byte[] buf) {
if (log.isTraceEnabled()) {
log.trace("send pong: {}", buf);
}
// send pong
send(Packet.build(buf, MessageType.PONG));
} | java | public void sendPong(byte[] buf) {
if (log.isTraceEnabled()) {
log.trace("send pong: {}", buf);
}
// send pong
send(Packet.build(buf, MessageType.PONG));
} | [
"public",
"void",
"sendPong",
"(",
"byte",
"[",
"]",
"buf",
")",
"{",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"trace",
"(",
"\"send pong: {}\"",
",",
"buf",
")",
";",
"}",
"// send pong",
"send",
"(",
"Packet",
".",
... | Sends a pong back to the client; normally in response to a ping.
@param buf | [
"Sends",
"a",
"pong",
"back",
"to",
"the",
"client",
";",
"normally",
"in",
"response",
"to",
"a",
"ping",
"."
] | train | https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L284-L290 |
leancloud/java-sdk-all | core/src/main/java/cn/leancloud/codec/Base64.java | Base64.encodeToString | public static String encodeToString(byte[] input, int flags) {
try {
return new String(encode(input, flags), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
} | java | public static String encodeToString(byte[] input, int flags) {
try {
return new String(encode(input, flags), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
} | [
"public",
"static",
"String",
"encodeToString",
"(",
"byte",
"[",
"]",
"input",
",",
"int",
"flags",
")",
"{",
"try",
"{",
"return",
"new",
"String",
"(",
"encode",
"(",
"input",
",",
"flags",
")",
",",
"\"US-ASCII\"",
")",
";",
"}",
"catch",
"(",
"U... | Base64-encode the given data and return a newly allocated
String with the result.
@param input the data to encode
@param flags controls certain features of the encoded output.
Passing {@code DEFAULT} results in output that
adheres to RFC 2045. | [
"Base64",
"-",
"encode",
"the",
"given",
"data",
"and",
"return",
"a",
"newly",
"allocated",
"String",
"with",
"the",
"result",
"."
] | train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/core/src/main/java/cn/leancloud/codec/Base64.java#L433-L440 |
threerings/nenya | core/src/main/java/com/threerings/media/AbstractMediaManager.java | AbstractMediaManager.paint | public void paint (Graphics2D gfx, int layer, Shape clip)
{
for (int ii = 0, nn = _media.size(); ii < nn; ii++) {
AbstractMedia media = _media.get(ii);
int order = media.getRenderOrder();
try {
if (((layer == ALL) || (layer == FRONT && order >= 0) ||
(layer == BACK && order < 0)) && clip.intersects(media.getBounds())) {
media.paint(gfx);
}
} catch (Exception e) {
log.warning("Failed to render media", "media", media, e);
}
}
} | java | public void paint (Graphics2D gfx, int layer, Shape clip)
{
for (int ii = 0, nn = _media.size(); ii < nn; ii++) {
AbstractMedia media = _media.get(ii);
int order = media.getRenderOrder();
try {
if (((layer == ALL) || (layer == FRONT && order >= 0) ||
(layer == BACK && order < 0)) && clip.intersects(media.getBounds())) {
media.paint(gfx);
}
} catch (Exception e) {
log.warning("Failed to render media", "media", media, e);
}
}
} | [
"public",
"void",
"paint",
"(",
"Graphics2D",
"gfx",
",",
"int",
"layer",
",",
"Shape",
"clip",
")",
"{",
"for",
"(",
"int",
"ii",
"=",
"0",
",",
"nn",
"=",
"_media",
".",
"size",
"(",
")",
";",
"ii",
"<",
"nn",
";",
"ii",
"++",
")",
"{",
"Ab... | Renders all registered media in the given layer that intersect the supplied clipping
rectangle to the given graphics context.
@param layer the layer to render; one of {@link #FRONT}, {@link #BACK}, or {@link #ALL}.
The front layer contains all animations with a positive render order; the back layer
contains all animations with a negative render order; all, both. | [
"Renders",
"all",
"registered",
"media",
"in",
"the",
"given",
"layer",
"that",
"intersect",
"the",
"supplied",
"clipping",
"rectangle",
"to",
"the",
"given",
"graphics",
"context",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/AbstractMediaManager.java#L103-L118 |
tvesalainen/util | util/src/main/java/org/vesalainen/util/CmdArgs.java | CmdArgs.addOption | public final <T> void addOption(String name, String description, String exclusiveGroup, T defValue)
{
Option opt = new Option(name, description, exclusiveGroup, defValue);
Option old = map.put(name, opt);
if (old != null)
{
throw new IllegalArgumentException(name+" was already added");
}
if (exclusiveGroup != null)
{
groups.add(exclusiveGroup, opt);
}
} | java | public final <T> void addOption(String name, String description, String exclusiveGroup, T defValue)
{
Option opt = new Option(name, description, exclusiveGroup, defValue);
Option old = map.put(name, opt);
if (old != null)
{
throw new IllegalArgumentException(name+" was already added");
}
if (exclusiveGroup != null)
{
groups.add(exclusiveGroup, opt);
}
} | [
"public",
"final",
"<",
"T",
">",
"void",
"addOption",
"(",
"String",
"name",
",",
"String",
"description",
",",
"String",
"exclusiveGroup",
",",
"T",
"defValue",
")",
"{",
"Option",
"opt",
"=",
"new",
"Option",
"(",
"name",
",",
"description",
",",
"exc... | Add an option
@param <T>
@param name Option name Option name without
@param description Option description
@param exclusiveGroup A group of options. Only options of a single group
are accepted.
@param defValue Option default value | [
"Add",
"an",
"option"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/CmdArgs.java#L384-L396 |
deeplearning4j/deeplearning4j | datavec/datavec-api/src/main/java/org/datavec/api/split/TransformSplit.java | TransformSplit.ofSearchReplace | public static TransformSplit ofSearchReplace(@NonNull BaseInputSplit sourceSplit, @NonNull final String search,
@NonNull final String replace) throws URISyntaxException {
return new TransformSplit(sourceSplit, new URITransform() {
@Override
public URI apply(URI uri) throws URISyntaxException {
return new URI(uri.toString().replace(search, replace));
}
});
} | java | public static TransformSplit ofSearchReplace(@NonNull BaseInputSplit sourceSplit, @NonNull final String search,
@NonNull final String replace) throws URISyntaxException {
return new TransformSplit(sourceSplit, new URITransform() {
@Override
public URI apply(URI uri) throws URISyntaxException {
return new URI(uri.toString().replace(search, replace));
}
});
} | [
"public",
"static",
"TransformSplit",
"ofSearchReplace",
"(",
"@",
"NonNull",
"BaseInputSplit",
"sourceSplit",
",",
"@",
"NonNull",
"final",
"String",
"search",
",",
"@",
"NonNull",
"final",
"String",
"replace",
")",
"throws",
"URISyntaxException",
"{",
"return",
... | Static factory method, replace the string version of the URI with a simple search-replace pair
@param sourceSplit the split with URIs to transform
@param search the string to search
@param replace the string to replace with
@throws URISyntaxException thrown if the transformed URI is malformed | [
"Static",
"factory",
"method",
"replace",
"the",
"string",
"version",
"of",
"the",
"URI",
"with",
"a",
"simple",
"search",
"-",
"replace",
"pair"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/split/TransformSplit.java#L60-L68 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java | PoolOperations.evaluateAutoScale | public AutoScaleRun evaluateAutoScale(String poolId, String autoScaleFormula)
throws BatchErrorException, IOException {
return evaluateAutoScale(poolId, autoScaleFormula, null);
} | java | public AutoScaleRun evaluateAutoScale(String poolId, String autoScaleFormula)
throws BatchErrorException, IOException {
return evaluateAutoScale(poolId, autoScaleFormula, null);
} | [
"public",
"AutoScaleRun",
"evaluateAutoScale",
"(",
"String",
"poolId",
",",
"String",
"autoScaleFormula",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"return",
"evaluateAutoScale",
"(",
"poolId",
",",
"autoScaleFormula",
",",
"null",
")",
";",
"}... | Gets the result of evaluating an automatic scaling formula on the specified
pool. This is primarily for validating an autoscale formula, as it simply
returns the result without applying the formula to the pool.
@param poolId
The ID of the pool.
@param autoScaleFormula
The formula to be evaluated on the pool.
@return The result of evaluating the formula on the specified pool.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service. | [
"Gets",
"the",
"result",
"of",
"evaluating",
"an",
"automatic",
"scaling",
"formula",
"on",
"the",
"specified",
"pool",
".",
"This",
"is",
"primarily",
"for",
"validating",
"an",
"autoscale",
"formula",
"as",
"it",
"simply",
"returns",
"the",
"result",
"withou... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L808-L811 |
motown-io/motown | operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/persistence/repositories/ReservationRepository.java | ReservationRepository.findByChargingStationIdEvseIdUserId | public Reservation findByChargingStationIdEvseIdUserId(ChargingStationId chargingStationId, EvseId evseid, UserIdentity UserId) throws NoResultException {
EntityManager entityManager = getEntityManager();
try {
return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Reservation AS t WHERE t.chargingStationId = :chargingStationId AND evseId = :evseId AND userId = :userId", Reservation.class)
.setParameter("chargingStationId", chargingStationId.getId())
.setParameter("evseId", evseid)
.setParameter("userId", UserId.getId())
.getSingleResult();
} finally {
entityManager.close();
}
} | java | public Reservation findByChargingStationIdEvseIdUserId(ChargingStationId chargingStationId, EvseId evseid, UserIdentity UserId) throws NoResultException {
EntityManager entityManager = getEntityManager();
try {
return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Reservation AS t WHERE t.chargingStationId = :chargingStationId AND evseId = :evseId AND userId = :userId", Reservation.class)
.setParameter("chargingStationId", chargingStationId.getId())
.setParameter("evseId", evseid)
.setParameter("userId", UserId.getId())
.getSingleResult();
} finally {
entityManager.close();
}
} | [
"public",
"Reservation",
"findByChargingStationIdEvseIdUserId",
"(",
"ChargingStationId",
"chargingStationId",
",",
"EvseId",
"evseid",
",",
"UserIdentity",
"UserId",
")",
"throws",
"NoResultException",
"{",
"EntityManager",
"entityManager",
"=",
"getEntityManager",
"(",
")... | find reservations by chargingstationid, evseid and userId
@param chargingStationId
@param evseid
@param UserId
@return
@throws NoResultException | [
"find",
"reservations",
"by",
"chargingstationid",
"evseid",
"and",
"userId"
] | train | https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/persistence/repositories/ReservationRepository.java#L86-L97 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_ipLoadbalancing_POST | public OvhIPLoadbalancing project_serviceName_ipLoadbalancing_POST(String serviceName, String ipLoadbalancingServiceName, String redirection) throws IOException {
String qPath = "/cloud/project/{serviceName}/ipLoadbalancing";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "ipLoadbalancingServiceName", ipLoadbalancingServiceName);
addBody(o, "redirection", redirection);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhIPLoadbalancing.class);
} | java | public OvhIPLoadbalancing project_serviceName_ipLoadbalancing_POST(String serviceName, String ipLoadbalancingServiceName, String redirection) throws IOException {
String qPath = "/cloud/project/{serviceName}/ipLoadbalancing";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "ipLoadbalancingServiceName", ipLoadbalancingServiceName);
addBody(o, "redirection", redirection);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhIPLoadbalancing.class);
} | [
"public",
"OvhIPLoadbalancing",
"project_serviceName_ipLoadbalancing_POST",
"(",
"String",
"serviceName",
",",
"String",
"ipLoadbalancingServiceName",
",",
"String",
"redirection",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/ipLoad... | Import an existing IP LB into OpenStack
REST: POST /cloud/project/{serviceName}/ipLoadbalancing
@param ipLoadbalancingServiceName [required] Service name of the IP LB to import
@param redirection [required] Where you want to redirect the user after sucessfull authentication. Useful variables admitted: %project <=> project ID, %id <=> ID of load balancing ip, %iplb <=> IPLB service name
@param serviceName [required] The project id
API beta | [
"Import",
"an",
"existing",
"IP",
"LB",
"into",
"OpenStack"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1673-L1681 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/TopScreen.java | TopScreen.getDefaultJava | public char getDefaultJava(String strBrowser, String strOS)
{
char chJavaLaunch = 'A'; // Applet = default
if ("safari".equalsIgnoreCase(strBrowser))
chJavaLaunch = 'W'; // Web start
// if ("linux".equalsIgnoreCase(strOS))
// chJavaLaunch = 'W'; // Web start
return chJavaLaunch;
} | java | public char getDefaultJava(String strBrowser, String strOS)
{
char chJavaLaunch = 'A'; // Applet = default
if ("safari".equalsIgnoreCase(strBrowser))
chJavaLaunch = 'W'; // Web start
// if ("linux".equalsIgnoreCase(strOS))
// chJavaLaunch = 'W'; // Web start
return chJavaLaunch;
} | [
"public",
"char",
"getDefaultJava",
"(",
"String",
"strBrowser",
",",
"String",
"strOS",
")",
"{",
"char",
"chJavaLaunch",
"=",
"'",
"'",
";",
"// Applet = default",
"if",
"(",
"\"safari\"",
".",
"equalsIgnoreCase",
"(",
"strBrowser",
")",
")",
"chJavaLaunch",
... | Get best way to launch java
@param strBrowser
@param strOS
@return | [
"Get",
"best",
"way",
"to",
"launch",
"java"
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/TopScreen.java#L356-L364 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/utils/URI.java | URI.setHost | public void setHost(String p_host) throws MalformedURIException
{
if (p_host == null || p_host.trim().length() == 0)
{
m_host = p_host;
m_userinfo = null;
m_port = -1;
}
else if (!isWellFormedAddress(p_host))
{
throw new MalformedURIException(Utils.messages.createMessage(MsgKey.ER_HOST_ADDRESS_NOT_WELLFORMED, null)); //"Host is not a well formed address!");
}
m_host = p_host;
} | java | public void setHost(String p_host) throws MalformedURIException
{
if (p_host == null || p_host.trim().length() == 0)
{
m_host = p_host;
m_userinfo = null;
m_port = -1;
}
else if (!isWellFormedAddress(p_host))
{
throw new MalformedURIException(Utils.messages.createMessage(MsgKey.ER_HOST_ADDRESS_NOT_WELLFORMED, null)); //"Host is not a well formed address!");
}
m_host = p_host;
} | [
"public",
"void",
"setHost",
"(",
"String",
"p_host",
")",
"throws",
"MalformedURIException",
"{",
"if",
"(",
"p_host",
"==",
"null",
"||",
"p_host",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"m_host",
"=",
"p_host",
";",
"... | Set the host for this URI. If null is passed in, the userinfo
field is also set to null and the port is set to -1.
@param p_host the host for this URI
@throws MalformedURIException if p_host is not a valid IP
address or DNS hostname. | [
"Set",
"the",
"host",
"for",
"this",
"URI",
".",
"If",
"null",
"is",
"passed",
"in",
"the",
"userinfo",
"field",
"is",
"also",
"set",
"to",
"null",
"and",
"the",
"port",
"is",
"set",
"to",
"-",
"1",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/utils/URI.java#L1098-L1113 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WMessageBox.java | WMessageBox.addMessage | public void addMessage(final boolean encode, final String msg, final Serializable... args) {
MessageModel model = getOrCreateComponentModel();
model.messages.add(new Duplet<>(I18nUtilities.asMessage(msg, args), encode));
// Potential for leaking memory here
MemoryUtil.checkSize(model.messages.size(), this.getClass().getSimpleName());
} | java | public void addMessage(final boolean encode, final String msg, final Serializable... args) {
MessageModel model = getOrCreateComponentModel();
model.messages.add(new Duplet<>(I18nUtilities.asMessage(msg, args), encode));
// Potential for leaking memory here
MemoryUtil.checkSize(model.messages.size(), this.getClass().getSimpleName());
} | [
"public",
"void",
"addMessage",
"(",
"final",
"boolean",
"encode",
",",
"final",
"String",
"msg",
",",
"final",
"Serializable",
"...",
"args",
")",
"{",
"MessageModel",
"model",
"=",
"getOrCreateComponentModel",
"(",
")",
";",
"model",
".",
"messages",
".",
... | Adds a message to the message box.
@param encode true to encode the message text, false to leave it unencoded.
@param msg the text of the message to add, using {@link MessageFormat} syntax.
@param args optional arguments for the message format string. | [
"Adds",
"a",
"message",
"to",
"the",
"message",
"box",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WMessageBox.java#L203-L208 |
Quickhull3d/quickhull3d | src/main/java/com/github/quickhull3d/Face.java | Face.areaSquared | public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) {
Point3d p0 = hedge0.tail().pnt;
Point3d p1 = hedge0.head().pnt;
Point3d p2 = hedge1.head().pnt;
double dx1 = p1.x - p0.x;
double dy1 = p1.y - p0.y;
double dz1 = p1.z - p0.z;
double dx2 = p2.x - p0.x;
double dy2 = p2.y - p0.y;
double dz2 = p2.z - p0.z;
double x = dy1 * dz2 - dz1 * dy2;
double y = dz1 * dx2 - dx1 * dz2;
double z = dx1 * dy2 - dy1 * dx2;
return x * x + y * y + z * z;
} | java | public double areaSquared(HalfEdge hedge0, HalfEdge hedge1) {
Point3d p0 = hedge0.tail().pnt;
Point3d p1 = hedge0.head().pnt;
Point3d p2 = hedge1.head().pnt;
double dx1 = p1.x - p0.x;
double dy1 = p1.y - p0.y;
double dz1 = p1.z - p0.z;
double dx2 = p2.x - p0.x;
double dy2 = p2.y - p0.y;
double dz2 = p2.z - p0.z;
double x = dy1 * dz2 - dz1 * dy2;
double y = dz1 * dx2 - dx1 * dz2;
double z = dx1 * dy2 - dy1 * dx2;
return x * x + y * y + z * z;
} | [
"public",
"double",
"areaSquared",
"(",
"HalfEdge",
"hedge0",
",",
"HalfEdge",
"hedge1",
")",
"{",
"Point3d",
"p0",
"=",
"hedge0",
".",
"tail",
"(",
")",
".",
"pnt",
";",
"Point3d",
"p1",
"=",
"hedge0",
".",
"head",
"(",
")",
".",
"pnt",
";",
"Point3... | return the squared area of the triangle defined by the half edge hedge0
and the point at the head of hedge1.
@param hedge0
@param hedge1
@return | [
"return",
"the",
"squared",
"area",
"of",
"the",
"triangle",
"defined",
"by",
"the",
"half",
"edge",
"hedge0",
"and",
"the",
"point",
"at",
"the",
"head",
"of",
"hedge1",
"."
] | train | https://github.com/Quickhull3d/quickhull3d/blob/3f80953b86c46385e84730e5d2a1745cbfa12703/src/main/java/com/github/quickhull3d/Face.java#L408-L426 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRouteGatewaysInner.java | ExpressRouteGatewaysInner.getByResourceGroupAsync | public Observable<ExpressRouteGatewayInner> getByResourceGroupAsync(String resourceGroupName, String expressRouteGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, expressRouteGatewayName).map(new Func1<ServiceResponse<ExpressRouteGatewayInner>, ExpressRouteGatewayInner>() {
@Override
public ExpressRouteGatewayInner call(ServiceResponse<ExpressRouteGatewayInner> response) {
return response.body();
}
});
} | java | public Observable<ExpressRouteGatewayInner> getByResourceGroupAsync(String resourceGroupName, String expressRouteGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, expressRouteGatewayName).map(new Func1<ServiceResponse<ExpressRouteGatewayInner>, ExpressRouteGatewayInner>() {
@Override
public ExpressRouteGatewayInner call(ServiceResponse<ExpressRouteGatewayInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ExpressRouteGatewayInner",
">",
"getByResourceGroupAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"expressRouteGatewayName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"expressRouteG... | Fetches the details of a ExpressRoute gateway in a resource group.
@param resourceGroupName The name of the resource group.
@param expressRouteGatewayName The name of the ExpressRoute gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ExpressRouteGatewayInner object | [
"Fetches",
"the",
"details",
"of",
"a",
"ExpressRoute",
"gateway",
"in",
"a",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRouteGatewaysInner.java#L462-L469 |
zaproxy/zaproxy | src/org/parosproxy/paros/view/WorkbenchPanel.java | WorkbenchPanel.getTabbedWork | public TabbedPanel2 getTabbedWork() {
if (tabbedWork == null) {
tabbedWork = new TabbedPanel2();
tabbedWork.setPreferredSize(new Dimension(600, 400));
tabbedWork.setName("tabbedWork");
tabbedWork.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
return tabbedWork;
} | java | public TabbedPanel2 getTabbedWork() {
if (tabbedWork == null) {
tabbedWork = new TabbedPanel2();
tabbedWork.setPreferredSize(new Dimension(600, 400));
tabbedWork.setName("tabbedWork");
tabbedWork.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
return tabbedWork;
} | [
"public",
"TabbedPanel2",
"getTabbedWork",
"(",
")",
"{",
"if",
"(",
"tabbedWork",
"==",
"null",
")",
"{",
"tabbedWork",
"=",
"new",
"TabbedPanel2",
"(",
")",
";",
"tabbedWork",
".",
"setPreferredSize",
"(",
"new",
"Dimension",
"(",
"600",
",",
"400",
")",... | Gets the tabbed panel that has the {@link PanelType#WORK WORK} panels.
<p>
Direct access/manipulation of the tabbed panel is discouraged, the changes done to it might be lost while changing
layouts.
@return the tabbed panel of the {@code work} panels, never {@code null}
@see #addPanel(AbstractPanel, PanelType) | [
"Gets",
"the",
"tabbed",
"panel",
"that",
"has",
"the",
"{",
"@link",
"PanelType#WORK",
"WORK",
"}",
"panels",
".",
"<p",
">",
"Direct",
"access",
"/",
"manipulation",
"of",
"the",
"tabbed",
"panel",
"is",
"discouraged",
"the",
"changes",
"done",
"to",
"it... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/WorkbenchPanel.java#L738-L746 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java | CommercePriceEntryPersistenceImpl.removeByUuid_C | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommercePriceEntry commercePriceEntry : findByUuid_C(uuid,
companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commercePriceEntry);
}
} | java | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommercePriceEntry commercePriceEntry : findByUuid_C(uuid,
companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commercePriceEntry);
}
} | [
"@",
"Override",
"public",
"void",
"removeByUuid_C",
"(",
"String",
"uuid",
",",
"long",
"companyId",
")",
"{",
"for",
"(",
"CommercePriceEntry",
"commercePriceEntry",
":",
"findByUuid_C",
"(",
"uuid",
",",
"companyId",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"... | Removes all the commerce price entries where uuid = ? and companyId = ? from the database.
@param uuid the uuid
@param companyId the company ID | [
"Removes",
"all",
"the",
"commerce",
"price",
"entries",
"where",
"uuid",
"=",
"?",
";",
"and",
"companyId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java#L1407-L1413 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java | TmdbTV.getTVChanges | public ResultList<ChangeKeyItem> getTVChanges(int tvID, String startDate, String endDate) throws MovieDbException {
return getMediaChanges(tvID, startDate, endDate);
} | java | public ResultList<ChangeKeyItem> getTVChanges(int tvID, String startDate, String endDate) throws MovieDbException {
return getMediaChanges(tvID, startDate, endDate);
} | [
"public",
"ResultList",
"<",
"ChangeKeyItem",
">",
"getTVChanges",
"(",
"int",
"tvID",
",",
"String",
"startDate",
",",
"String",
"endDate",
")",
"throws",
"MovieDbException",
"{",
"return",
"getMediaChanges",
"(",
"tvID",
",",
"startDate",
",",
"endDate",
")",
... | Get the changes for a specific TV show id.
@param tvID
@param startDate
@param endDate
@return
@throws com.omertron.themoviedbapi.MovieDbException | [
"Get",
"the",
"changes",
"for",
"a",
"specific",
"TV",
"show",
"id",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java#L148-L150 |
Alluxio/alluxio | core/server/master/src/main/java/alluxio/master/file/meta/InodeLockList.java | InodeLockList.lockRootEdge | public void lockRootEdge(LockMode mode) {
Preconditions.checkState(mEntries.isEmpty());
mEntries.add(new EdgeEntry(mInodeLockManager.lockEdge(ROOT_EDGE, mode), ROOT_EDGE));
mLockMode = mode;
} | java | public void lockRootEdge(LockMode mode) {
Preconditions.checkState(mEntries.isEmpty());
mEntries.add(new EdgeEntry(mInodeLockManager.lockEdge(ROOT_EDGE, mode), ROOT_EDGE));
mLockMode = mode;
} | [
"public",
"void",
"lockRootEdge",
"(",
"LockMode",
"mode",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"mEntries",
".",
"isEmpty",
"(",
")",
")",
";",
"mEntries",
".",
"add",
"(",
"new",
"EdgeEntry",
"(",
"mInodeLockManager",
".",
"lockEdge",
"(",
"... | Locks the root edge in the specified mode.
@param mode the mode to lock in | [
"Locks",
"the",
"root",
"edge",
"in",
"the",
"specified",
"mode",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeLockList.java#L137-L142 |
opensourceBIM/BIMserver | PluginBase/src/org/bimserver/shared/GuidCompressor.java | GuidCompressor.getGuidFromCompressedString | public static boolean getGuidFromCompressedString(String string, Guid guid) throws InvalidGuidException
{
char[][] str = new char[6][5];
int len, i, j, m;
long[][] num = new long[6][1];
len = string.length();
if (len != 22)
throw new InvalidGuidException(string, "Length must be 22 (is: " + string.length() + ")");
j = 0;
m = 2;
for (i = 0; i < 6; i++) {
for(int k = 0; k<m; k++){
str[i][k] = string.charAt(j+k);
}
str[i][m]= '\0';
j = j + m;
m = 4;
}
for (i = 0; i < 6; i++) {
if (!cv_from_64 (num[i], str[i])) {
throw new InvalidGuidException(string);
}
}
guid.Data1= (long) (num[0][0] * 16777216 + num[1][0]); // 16-13. bytes
guid.Data2= (int) (num[2][0] / 256); // 12-11. bytes
guid.Data3= (int) ((num[2][0] % 256) * 256 + num[3][0] / 65536); // 10-09. bytes
guid.Data4[0] = (char) ((num[3][0] / 256) % 256); // 08. byte
guid.Data4[1] = (char) (num[3][0] % 256); // 07. byte
guid.Data4[2] = (char) (num[4][0] / 65536); // 06. byte
guid.Data4[3] = (char) ((num[4][0] / 256) % 256); // 05. byte
guid.Data4[4] = (char) (num[4][0] % 256); // 04. byte
guid.Data4[5] = (char) (num[5][0] / 65536); // 03. byte
guid.Data4[6] = (char) ((num[5][0] / 256) % 256); // 02. byte
guid.Data4[7] = (char) (num[5][0] % 256); // 01. byte
return true;
} | java | public static boolean getGuidFromCompressedString(String string, Guid guid) throws InvalidGuidException
{
char[][] str = new char[6][5];
int len, i, j, m;
long[][] num = new long[6][1];
len = string.length();
if (len != 22)
throw new InvalidGuidException(string, "Length must be 22 (is: " + string.length() + ")");
j = 0;
m = 2;
for (i = 0; i < 6; i++) {
for(int k = 0; k<m; k++){
str[i][k] = string.charAt(j+k);
}
str[i][m]= '\0';
j = j + m;
m = 4;
}
for (i = 0; i < 6; i++) {
if (!cv_from_64 (num[i], str[i])) {
throw new InvalidGuidException(string);
}
}
guid.Data1= (long) (num[0][0] * 16777216 + num[1][0]); // 16-13. bytes
guid.Data2= (int) (num[2][0] / 256); // 12-11. bytes
guid.Data3= (int) ((num[2][0] % 256) * 256 + num[3][0] / 65536); // 10-09. bytes
guid.Data4[0] = (char) ((num[3][0] / 256) % 256); // 08. byte
guid.Data4[1] = (char) (num[3][0] % 256); // 07. byte
guid.Data4[2] = (char) (num[4][0] / 65536); // 06. byte
guid.Data4[3] = (char) ((num[4][0] / 256) % 256); // 05. byte
guid.Data4[4] = (char) (num[4][0] % 256); // 04. byte
guid.Data4[5] = (char) (num[5][0] / 65536); // 03. byte
guid.Data4[6] = (char) ((num[5][0] / 256) % 256); // 02. byte
guid.Data4[7] = (char) (num[5][0] % 256); // 01. byte
return true;
} | [
"public",
"static",
"boolean",
"getGuidFromCompressedString",
"(",
"String",
"string",
",",
"Guid",
"guid",
")",
"throws",
"InvalidGuidException",
"{",
"char",
"[",
"]",
"[",
"]",
"str",
"=",
"new",
"char",
"[",
"6",
"]",
"[",
"5",
"]",
";",
"int",
"len"... | Reconstructs a Guid-object form an compressed String representation of a GUID
@param string compressed String representation of a GUID, 22 character long
@param guid contains the reconstructed Guid as a result of this method
@return true if no error occurred | [
"Reconstructs",
"a",
"Guid",
"-",
"object",
"form",
"an",
"compressed",
"String",
"representation",
"of",
"a",
"GUID"
] | train | https://github.com/opensourceBIM/BIMserver/blob/116803c3047d1b32217366757cee1bb3880fda63/PluginBase/src/org/bimserver/shared/GuidCompressor.java#L203-L244 |
kiegroup/drools | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java | CompiledFEELSemanticMappings.add | public static Object add(Object left, Object right) {
return InfixOpNode.add(left, right, null);
} | java | public static Object add(Object left, Object right) {
return InfixOpNode.add(left, right, null);
} | [
"public",
"static",
"Object",
"add",
"(",
"Object",
"left",
",",
"Object",
"right",
")",
"{",
"return",
"InfixOpNode",
".",
"add",
"(",
"left",
",",
"right",
",",
"null",
")",
";",
"}"
] | FEEL spec Table 45
Delegates to {@link InfixOpNode} except evaluationcontext | [
"FEEL",
"spec",
"Table",
"45",
"Delegates",
"to",
"{"
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/CompiledFEELSemanticMappings.java#L298-L300 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/log/LogImpl.java | LogImpl.setDebugPatterns | public void setDebugPatterns(String patterns)
{
_patterns=patterns;
if (patterns!=null && patterns.length()>0)
{
_debugPatterns = new ArrayList();
StringTokenizer tok = new StringTokenizer(patterns,", \t");
while (tok.hasMoreTokens())
{
String pattern = tok.nextToken();
_debugPatterns.add(pattern);
}
}
else
_debugPatterns = null;
} | java | public void setDebugPatterns(String patterns)
{
_patterns=patterns;
if (patterns!=null && patterns.length()>0)
{
_debugPatterns = new ArrayList();
StringTokenizer tok = new StringTokenizer(patterns,", \t");
while (tok.hasMoreTokens())
{
String pattern = tok.nextToken();
_debugPatterns.add(pattern);
}
}
else
_debugPatterns = null;
} | [
"public",
"void",
"setDebugPatterns",
"(",
"String",
"patterns",
")",
"{",
"_patterns",
"=",
"patterns",
";",
"if",
"(",
"patterns",
"!=",
"null",
"&&",
"patterns",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"_debugPatterns",
"=",
"new",
"ArrayList",
"... | Set debug patterns.
@param patterns comma separated string of patterns | [
"Set",
"debug",
"patterns",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/log/LogImpl.java#L479-L495 |
zaproxy/zaproxy | src/org/parosproxy/paros/core/scanner/AbstractPlugin.java | AbstractPlugin.stripOff | protected String stripOff(String body, String pattern) {
String urlEncodePattern = getURLEncode(pattern);
String urlDecodePattern = getURLDecode(pattern);
String htmlEncodePattern1 = getHTMLEncode(pattern);
String htmlEncodePattern2 = getHTMLEncode(urlEncodePattern);
String htmlEncodePattern3 = getHTMLEncode(urlDecodePattern);
String result = body.replaceAll("\\Q" + pattern + "\\E", "").replaceAll("\\Q" + urlEncodePattern + "\\E", "").replaceAll("\\Q" + urlDecodePattern + "\\E", "");
result = result.replaceAll("\\Q" + htmlEncodePattern1 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern2 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern3 + "\\E", "");
return result;
} | java | protected String stripOff(String body, String pattern) {
String urlEncodePattern = getURLEncode(pattern);
String urlDecodePattern = getURLDecode(pattern);
String htmlEncodePattern1 = getHTMLEncode(pattern);
String htmlEncodePattern2 = getHTMLEncode(urlEncodePattern);
String htmlEncodePattern3 = getHTMLEncode(urlDecodePattern);
String result = body.replaceAll("\\Q" + pattern + "\\E", "").replaceAll("\\Q" + urlEncodePattern + "\\E", "").replaceAll("\\Q" + urlDecodePattern + "\\E", "");
result = result.replaceAll("\\Q" + htmlEncodePattern1 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern2 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern3 + "\\E", "");
return result;
} | [
"protected",
"String",
"stripOff",
"(",
"String",
"body",
",",
"String",
"pattern",
")",
"{",
"String",
"urlEncodePattern",
"=",
"getURLEncode",
"(",
"pattern",
")",
";",
"String",
"urlDecodePattern",
"=",
"getURLDecode",
"(",
"pattern",
")",
";",
"String",
"h... | Replace body by stripping of pattern string. The URLencoded and
URLdecoded pattern will also be stripped off. This is mainly used for
stripping off a testing string in HTTP response for comparison against
the original response. Reference: TestInjectionSQL
@param body the body that will be used
@param pattern the pattern used for the removals
@return the body without the pattern | [
"Replace",
"body",
"by",
"stripping",
"of",
"pattern",
"string",
".",
"The",
"URLencoded",
"and",
"URLdecoded",
"pattern",
"will",
"also",
"be",
"stripped",
"off",
".",
"This",
"is",
"mainly",
"used",
"for",
"stripping",
"off",
"a",
"testing",
"string",
"in"... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/AbstractPlugin.java#L771-L780 |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/RippleDrawableICS.java | RippleDrawableICS.tryRippleEnter | private void tryRippleEnter() {
if (mExitingRipplesCount >= MAX_RIPPLES) {
// This should never happen unless the user is tapping like a maniac
// or there is a bug that's preventing ripples from being removed.
return;
}
if (mRipple == null) {
final float x;
final float y;
if (mHasPending) {
mHasPending = false;
x = mPendingX;
y = mPendingY;
} else {
x = mHotspotBounds.exactCenterX();
y = mHotspotBounds.exactCenterY();
}
final boolean isBounded = isBounded();
mRipple = new RippleForeground(this, mHotspotBounds, x, y, isBounded);
}
mRipple.setup(mState.mMaxRadius, mDensity);
mRipple.enter(false);
} | java | private void tryRippleEnter() {
if (mExitingRipplesCount >= MAX_RIPPLES) {
// This should never happen unless the user is tapping like a maniac
// or there is a bug that's preventing ripples from being removed.
return;
}
if (mRipple == null) {
final float x;
final float y;
if (mHasPending) {
mHasPending = false;
x = mPendingX;
y = mPendingY;
} else {
x = mHotspotBounds.exactCenterX();
y = mHotspotBounds.exactCenterY();
}
final boolean isBounded = isBounded();
mRipple = new RippleForeground(this, mHotspotBounds, x, y, isBounded);
}
mRipple.setup(mState.mMaxRadius, mDensity);
mRipple.enter(false);
} | [
"private",
"void",
"tryRippleEnter",
"(",
")",
"{",
"if",
"(",
"mExitingRipplesCount",
">=",
"MAX_RIPPLES",
")",
"{",
"// This should never happen unless the user is tapping like a maniac",
"// or there is a bug that's preventing ripples from being removed.",
"return",
";",
"}",
... | Attempts to start an enter animation for the active hotspot. Fails if there are too many
animating ripples. | [
"Attempts",
"to",
"start",
"an",
"enter",
"animation",
"for",
"the",
"active",
"hotspot",
".",
"Fails",
"if",
"there",
"are",
"too",
"many",
"animating",
"ripples",
"."
] | train | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/RippleDrawableICS.java#L567-L592 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Getter.java | Getter.getView | public <T extends View> T getView(Class<T> classToFilterBy, int index) {
return waiter.waitForAndGetView(index, classToFilterBy);
} | java | public <T extends View> T getView(Class<T> classToFilterBy, int index) {
return waiter.waitForAndGetView(index, classToFilterBy);
} | [
"public",
"<",
"T",
"extends",
"View",
">",
"T",
"getView",
"(",
"Class",
"<",
"T",
">",
"classToFilterBy",
",",
"int",
"index",
")",
"{",
"return",
"waiter",
".",
"waitForAndGetView",
"(",
"index",
",",
"classToFilterBy",
")",
";",
"}"
] | Returns a {@code View} with a certain index, from the list of current {@code View}s of the specified type.
@param classToFilterBy which {@code View}s to choose from
@param index choose among all instances of this type, e.g. {@code Button.class} or {@code EditText.class}
@return a {@code View} with a certain index, from the list of current {@code View}s of the specified type | [
"Returns",
"a",
"{",
"@code",
"View",
"}",
"with",
"a",
"certain",
"index",
"from",
"the",
"list",
"of",
"current",
"{",
"@code",
"View",
"}",
"s",
"of",
"the",
"specified",
"type",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Getter.java#L50-L52 |
aws/aws-cloudtrail-processing-library | src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/CloudTrailSourceSerializer.java | CloudTrailSourceSerializer.addCloudTrailLogsAndMessageAttributes | private void addCloudTrailLogsAndMessageAttributes(Message sqsMessage, List<CloudTrailLog> cloudTrailLogs, JsonNode messageNode) throws IOException {
SourceType sourceType = SourceType.Other;
String bucketName = messageNode.get(S3_BUCKET_NAME).textValue();
List<String> objectKeys = mapper.readValue(messageNode.get(S3_OBJECT_KEY).traverse(), new TypeReference<List<String>>() {});
for (String objectKey: objectKeys) {
SourceType currSourceType = sourceIdentifier.identify(objectKey);
if (currSourceType == SourceType.CloudTrailLog) {
cloudTrailLogs.add(new CloudTrailLog(bucketName, objectKey));
sourceType = currSourceType;
LibraryUtils.setMessageAccountId(sqsMessage, objectKey);
}
}
sqsMessage.addAttributesEntry(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey(), sourceType.name());
} | java | private void addCloudTrailLogsAndMessageAttributes(Message sqsMessage, List<CloudTrailLog> cloudTrailLogs, JsonNode messageNode) throws IOException {
SourceType sourceType = SourceType.Other;
String bucketName = messageNode.get(S3_BUCKET_NAME).textValue();
List<String> objectKeys = mapper.readValue(messageNode.get(S3_OBJECT_KEY).traverse(), new TypeReference<List<String>>() {});
for (String objectKey: objectKeys) {
SourceType currSourceType = sourceIdentifier.identify(objectKey);
if (currSourceType == SourceType.CloudTrailLog) {
cloudTrailLogs.add(new CloudTrailLog(bucketName, objectKey));
sourceType = currSourceType;
LibraryUtils.setMessageAccountId(sqsMessage, objectKey);
}
}
sqsMessage.addAttributesEntry(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey(), sourceType.name());
} | [
"private",
"void",
"addCloudTrailLogsAndMessageAttributes",
"(",
"Message",
"sqsMessage",
",",
"List",
"<",
"CloudTrailLog",
">",
"cloudTrailLogs",
",",
"JsonNode",
"messageNode",
")",
"throws",
"IOException",
"{",
"SourceType",
"sourceType",
"=",
"SourceType",
".",
"... | As long as there is at least one CloudTrail log object:
<p>
<li>Add the CloudTrail log object key to the list.</li>
<li>Add <code>accountId</code> extracted from log object key to <code>sqsMessage</code>.</li>
<li>Add {@link SourceType#CloudTrailLog} to the <code>sqsMessage</code>.</li>
</p>
If there is no CloudTrail log object and it is a valid CloudTrail message, CPL adds only {@link SourceType#Other}
to the <code>sqsMessage</code>. | [
"As",
"long",
"as",
"there",
"is",
"at",
"least",
"one",
"CloudTrail",
"log",
"object",
":",
"<p",
">",
"<li",
">",
"Add",
"the",
"CloudTrail",
"log",
"object",
"key",
"to",
"the",
"list",
".",
"<",
"/",
"li",
">",
"<li",
">",
"Add",
"<code",
">",
... | train | https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/CloudTrailSourceSerializer.java#L79-L95 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.deleteBuildVariable | public void deleteBuildVariable(Integer projectId, String key)
throws IOException {
String tailUrl = GitlabProject.URL + "/" +
projectId +
GitlabBuildVariable.URL + "/" +
key;
retrieve().method(DELETE).to(tailUrl, Void.class);
} | java | public void deleteBuildVariable(Integer projectId, String key)
throws IOException {
String tailUrl = GitlabProject.URL + "/" +
projectId +
GitlabBuildVariable.URL + "/" +
key;
retrieve().method(DELETE).to(tailUrl, Void.class);
} | [
"public",
"void",
"deleteBuildVariable",
"(",
"Integer",
"projectId",
",",
"String",
"key",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"\"/\"",
"+",
"projectId",
"+",
"GitlabBuildVariable",
".",
"URL",
"+",
"... | Deletes an existing variable.
@param projectId The ID of the project containing the variable.
@param key The key of the variable to delete.
@throws IOException on gitlab api call error | [
"Deletes",
"an",
"existing",
"variable",
"."
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3706-L3713 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/InternalDocumentRevision.java | InternalDocumentRevision.setAttachmentsInternal | protected void setAttachmentsInternal(Map<String, ? extends Attachment> attachments) {
if (attachments != null) {
// this awkward looking way of doing things is to avoid marking the map as being
// modified
HashMap<String, Attachment> m = new HashMap<String, Attachment>();
for (Map.Entry<String, ? extends Attachment> att : attachments.entrySet()) {
m.put(att.getKey(), att.getValue());
}
this.attachments = SimpleChangeNotifyingMap.wrap(m);
}
} | java | protected void setAttachmentsInternal(Map<String, ? extends Attachment> attachments) {
if (attachments != null) {
// this awkward looking way of doing things is to avoid marking the map as being
// modified
HashMap<String, Attachment> m = new HashMap<String, Attachment>();
for (Map.Entry<String, ? extends Attachment> att : attachments.entrySet()) {
m.put(att.getKey(), att.getValue());
}
this.attachments = SimpleChangeNotifyingMap.wrap(m);
}
} | [
"protected",
"void",
"setAttachmentsInternal",
"(",
"Map",
"<",
"String",
",",
"?",
"extends",
"Attachment",
">",
"attachments",
")",
"{",
"if",
"(",
"attachments",
"!=",
"null",
")",
"{",
"// this awkward looking way of doing things is to avoid marking the map as being",... | /*
Helper used by sub-classes to convert between list and map representation of attachments | [
"/",
"*",
"Helper",
"used",
"by",
"sub",
"-",
"classes",
"to",
"convert",
"between",
"list",
"and",
"map",
"representation",
"of",
"attachments"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/InternalDocumentRevision.java#L127-L137 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/MediaApi.java | MediaApi.createOpenMedia | public ApiSuccessResponse createOpenMedia(String mediatype, CreateData1 createData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = createOpenMediaWithHttpInfo(mediatype, createData);
return resp.getData();
} | java | public ApiSuccessResponse createOpenMedia(String mediatype, CreateData1 createData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = createOpenMediaWithHttpInfo(mediatype, createData);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"createOpenMedia",
"(",
"String",
"mediatype",
",",
"CreateData1",
"createData",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"createOpenMediaWithHttpInfo",
"(",
"mediatype",
",",
"create... | Create open media interaction
Create a new open media interaction
@param mediatype The media channel. (required)
@param createData Request parameters. (required)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Create",
"open",
"media",
"interaction",
"Create",
"a",
"new",
"open",
"media",
"interaction"
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L1429-L1432 |
cojen/Cojen | src/main/java/org/cojen/util/ClassInjector.java | ClassInjector.createExplicit | public static ClassInjector createExplicit(String name, ClassLoader parent) {
if (name == null) {
throw new IllegalArgumentException("Explicit class name not provided");
}
return create(name, parent, true);
} | java | public static ClassInjector createExplicit(String name, ClassLoader parent) {
if (name == null) {
throw new IllegalArgumentException("Explicit class name not provided");
}
return create(name, parent, true);
} | [
"public",
"static",
"ClassInjector",
"createExplicit",
"(",
"String",
"name",
",",
"ClassLoader",
"parent",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Explicit class name not provided\"",
")",
";",
"}",... | Create a ClassInjector for defining one class with an explicit name. If
the parent ClassLoader is not specified, it will default to the
ClassLoader of the ClassInjector class.
<p>
If the parent loader was used for loading injected classes, the new
class will be loaded by it. This allows auto-generated classes access to
package accessible members, as long as they are defined in the same
package.
@param name required class name
@param parent optional parent ClassLoader
@throws IllegalArgumentException if name is null | [
"Create",
"a",
"ClassInjector",
"for",
"defining",
"one",
"class",
"with",
"an",
"explicit",
"name",
".",
"If",
"the",
"parent",
"ClassLoader",
"is",
"not",
"specified",
"it",
"will",
"default",
"to",
"the",
"ClassLoader",
"of",
"the",
"ClassInjector",
"class"... | train | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ClassInjector.java#L107-L112 |
xiancloud/xian | xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/pool/PoolFactory.java | PoolFactory.getPool | public static IPool getPool(String host, Integer port, String database, String... userPwd) {
//暂未启用
throw new RuntimeException("未找到指定的数据库连接池");
} | java | public static IPool getPool(String host, Integer port, String database, String... userPwd) {
//暂未启用
throw new RuntimeException("未找到指定的数据库连接池");
} | [
"public",
"static",
"IPool",
"getPool",
"(",
"String",
"host",
",",
"Integer",
"port",
",",
"String",
"database",
",",
"String",
"...",
"userPwd",
")",
"{",
"//暂未启用",
"throw",
"new",
"RuntimeException",
"(",
"\"未找到指定的数据库连接池\");",
"",
"",
"}"
] | 根据指定的域名端口和数据库名获取连接池,如果之前已经初始化过该连接池那么直接返回已存在的那个连接池
@param host MySQL主机ip或域名
@param port MySQL端口
@param database 数据库名
@return 数据库连接池 | [
"根据指定的域名端口和数据库名获取连接池",
"如果之前已经初始化过该连接池那么直接返回已存在的那个连接池"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/pool/PoolFactory.java#L44-L47 |
apiman/apiman | gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java | ConnectorFactory.createConnector | @Override
public IApiConnector createConnector(ApiRequest req, Api api, RequiredAuthType authType, boolean hasDataPolicy, IConnectorConfig connectorConfig) {
return (request, resultHandler) -> {
// Apply options from config as our base case
ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions(config)
.setHasDataPolicy(hasDataPolicy)
.setRequiredAuthType(authType)
.setTlsOptions(tlsOptions)
.setUri(parseApiEndpoint(api))
.setSsl(api.getEndpoint().toLowerCase().startsWith("https")); //$NON-NLS-1$
// If API has endpoint properties indicating timeouts, then override config.
setAttributesFromApiEndpointProperties(api, httpOptions);
// Get from cache
HttpClient client = clientFromCache(httpOptions);
return new HttpConnector(vertx, client, request, api, httpOptions, connectorConfig, resultHandler).connect();
};
} | java | @Override
public IApiConnector createConnector(ApiRequest req, Api api, RequiredAuthType authType, boolean hasDataPolicy, IConnectorConfig connectorConfig) {
return (request, resultHandler) -> {
// Apply options from config as our base case
ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions(config)
.setHasDataPolicy(hasDataPolicy)
.setRequiredAuthType(authType)
.setTlsOptions(tlsOptions)
.setUri(parseApiEndpoint(api))
.setSsl(api.getEndpoint().toLowerCase().startsWith("https")); //$NON-NLS-1$
// If API has endpoint properties indicating timeouts, then override config.
setAttributesFromApiEndpointProperties(api, httpOptions);
// Get from cache
HttpClient client = clientFromCache(httpOptions);
return new HttpConnector(vertx, client, request, api, httpOptions, connectorConfig, resultHandler).connect();
};
} | [
"@",
"Override",
"public",
"IApiConnector",
"createConnector",
"(",
"ApiRequest",
"req",
",",
"Api",
"api",
",",
"RequiredAuthType",
"authType",
",",
"boolean",
"hasDataPolicy",
",",
"IConnectorConfig",
"connectorConfig",
")",
"{",
"return",
"(",
"request",
",",
"... | In the future we can switch to different back-end implementations here! | [
"In",
"the",
"future",
"we",
"can",
"switch",
"to",
"different",
"back",
"-",
"end",
"implementations",
"here!"
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java#L87-L103 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-securitycenter/src/main/java/com/google/cloud/securitycenter/v1/SecurityCenterClient.java | SecurityCenterClient.createFinding | public final Finding createFinding(SourceName parent, String findingId, Finding finding) {
CreateFindingRequest request =
CreateFindingRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setFindingId(findingId)
.setFinding(finding)
.build();
return createFinding(request);
} | java | public final Finding createFinding(SourceName parent, String findingId, Finding finding) {
CreateFindingRequest request =
CreateFindingRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setFindingId(findingId)
.setFinding(finding)
.build();
return createFinding(request);
} | [
"public",
"final",
"Finding",
"createFinding",
"(",
"SourceName",
"parent",
",",
"String",
"findingId",
",",
"Finding",
"finding",
")",
"{",
"CreateFindingRequest",
"request",
"=",
"CreateFindingRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent... | Creates a finding. The corresponding source must exist for finding creation to succeed.
<p>Sample code:
<pre><code>
try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) {
SourceName parent = SourceName.of("[ORGANIZATION]", "[SOURCE]");
String findingId = "";
Finding finding = Finding.newBuilder().build();
Finding response = securityCenterClient.createFinding(parent, findingId, finding);
}
</code></pre>
@param parent Resource name of the new finding's parent. Its format should be
"organizations/[organization_id]/sources/[source_id]".
@param findingId Unique identifier provided by the client within the parent scope. It must be
alphanumeric and less than or equal to 32 characters and greater than 0 characters in
length.
@param finding The Finding being created. The name and security_marks will be ignored as they
are both output only fields on this resource.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"finding",
".",
"The",
"corresponding",
"source",
"must",
"exist",
"for",
"finding",
"creation",
"to",
"succeed",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-securitycenter/src/main/java/com/google/cloud/securitycenter/v1/SecurityCenterClient.java#L311-L320 |
SeaCloudsEU/SeaCloudsPlatform | discoverer/src/main/java/eu/seaclouds/platform/discoverer/core/OfferingManager.java | OfferingManager.getOffering | public Offering getOffering(String offeringName) {
BasicDBObject query = new BasicDBObject("offering_name", offeringName);
FindIterable<Document> cursor = this.offeringsCollection.find(query);
return Offering.fromDB(cursor.first());
} | java | public Offering getOffering(String offeringName) {
BasicDBObject query = new BasicDBObject("offering_name", offeringName);
FindIterable<Document> cursor = this.offeringsCollection.find(query);
return Offering.fromDB(cursor.first());
} | [
"public",
"Offering",
"getOffering",
"(",
"String",
"offeringName",
")",
"{",
"BasicDBObject",
"query",
"=",
"new",
"BasicDBObject",
"(",
"\"offering_name\"",
",",
"offeringName",
")",
";",
"FindIterable",
"<",
"Document",
">",
"cursor",
"=",
"this",
".",
"offer... | Get an offering
@param offeringName the name of the offering
@return the offering identified by offeringId | [
"Get",
"an",
"offering"
] | train | https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/discoverer/src/main/java/eu/seaclouds/platform/discoverer/core/OfferingManager.java#L53-L58 |
knowm/XChange | xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java | CexIOAdapters.adaptTrades | public static Trades adaptTrades(CexIOTrade[] cexioTrades, CurrencyPair currencyPair) {
List<Trade> tradesList = new ArrayList<>();
long lastTradeId = 0;
for (CexIOTrade trade : cexioTrades) {
long tradeId = trade.getTid();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
// Date is reversed order. Insert at index 0 instead of appending
tradesList.add(0, adaptTrade(trade, currencyPair));
}
return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
} | java | public static Trades adaptTrades(CexIOTrade[] cexioTrades, CurrencyPair currencyPair) {
List<Trade> tradesList = new ArrayList<>();
long lastTradeId = 0;
for (CexIOTrade trade : cexioTrades) {
long tradeId = trade.getTid();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
// Date is reversed order. Insert at index 0 instead of appending
tradesList.add(0, adaptTrade(trade, currencyPair));
}
return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
} | [
"public",
"static",
"Trades",
"adaptTrades",
"(",
"CexIOTrade",
"[",
"]",
"cexioTrades",
",",
"CurrencyPair",
"currencyPair",
")",
"{",
"List",
"<",
"Trade",
">",
"tradesList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"long",
"lastTradeId",
"=",
"0",
... | Adapts a CexIOTrade[] to a Trades Object
@param cexioTrades The CexIO trade data returned by API
@param currencyPair trade currencies
@return The trades | [
"Adapts",
"a",
"CexIOTrade",
"[]",
"to",
"a",
"Trades",
"Object"
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java#L62-L75 |
apache/flink | flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/PojoSerializerSnapshot.java | PojoSerializerSnapshot.newPojoSerializerIsCompatibleWithReconfiguredSerializer | private static <T> boolean newPojoSerializerIsCompatibleWithReconfiguredSerializer(
PojoSerializer<T> newPojoSerializer,
IntermediateCompatibilityResult<T> fieldSerializerCompatibility,
IntermediateCompatibilityResult<T> preExistingRegistrationsCompatibility,
LinkedOptionalMap<Class<?>, TypeSerializerSnapshot<?>> registeredSubclassSerializerSnapshots,
LinkedOptionalMap<Class<?>, TypeSerializerSnapshot<?>> nonRegisteredSubclassSerializerSnapshots) {
return newPojoHasDifferentSubclassRegistrationOrder(registeredSubclassSerializerSnapshots, newPojoSerializer)
|| previousSerializerHasNonRegisteredSubclasses(nonRegisteredSubclassSerializerSnapshots)
|| fieldSerializerCompatibility.isCompatibleWithReconfiguredSerializer()
|| preExistingRegistrationsCompatibility.isCompatibleWithReconfiguredSerializer();
} | java | private static <T> boolean newPojoSerializerIsCompatibleWithReconfiguredSerializer(
PojoSerializer<T> newPojoSerializer,
IntermediateCompatibilityResult<T> fieldSerializerCompatibility,
IntermediateCompatibilityResult<T> preExistingRegistrationsCompatibility,
LinkedOptionalMap<Class<?>, TypeSerializerSnapshot<?>> registeredSubclassSerializerSnapshots,
LinkedOptionalMap<Class<?>, TypeSerializerSnapshot<?>> nonRegisteredSubclassSerializerSnapshots) {
return newPojoHasDifferentSubclassRegistrationOrder(registeredSubclassSerializerSnapshots, newPojoSerializer)
|| previousSerializerHasNonRegisteredSubclasses(nonRegisteredSubclassSerializerSnapshots)
|| fieldSerializerCompatibility.isCompatibleWithReconfiguredSerializer()
|| preExistingRegistrationsCompatibility.isCompatibleWithReconfiguredSerializer();
} | [
"private",
"static",
"<",
"T",
">",
"boolean",
"newPojoSerializerIsCompatibleWithReconfiguredSerializer",
"(",
"PojoSerializer",
"<",
"T",
">",
"newPojoSerializer",
",",
"IntermediateCompatibilityResult",
"<",
"T",
">",
"fieldSerializerCompatibility",
",",
"IntermediateCompat... | Checks if the new {@link PojoSerializer} is compatible with a reconfigured instance. | [
"Checks",
"if",
"the",
"new",
"{"
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/PojoSerializerSnapshot.java#L358-L368 |
OpenTSDB/opentsdb | src/uid/UniqueId.java | UniqueId.getUsedUIDs | public static Deferred<Map<String, Long>> getUsedUIDs(final TSDB tsdb,
final byte[][] kinds) {
/**
* Returns a map with 0 if the max ID row hasn't been initialized yet,
* otherwise the map has actual data
*/
final class GetCB implements Callback<Map<String, Long>,
ArrayList<KeyValue>> {
@Override
public Map<String, Long> call(final ArrayList<KeyValue> row)
throws Exception {
final Map<String, Long> results = new HashMap<String, Long>(3);
if (row == null || row.isEmpty()) {
// it could be the case that this is the first time the TSD has run
// and the user hasn't put any metrics in, so log and return 0s
LOG.info("Could not find the UID assignment row");
for (final byte[] kind : kinds) {
results.put(new String(kind, CHARSET), 0L);
}
return results;
}
for (final KeyValue column : row) {
results.put(new String(column.qualifier(), CHARSET),
Bytes.getLong(column.value()));
}
// if the user is starting with a fresh UID table, we need to account
// for missing columns
for (final byte[] kind : kinds) {
if (results.get(new String(kind, CHARSET)) == null) {
results.put(new String(kind, CHARSET), 0L);
}
}
return results;
}
}
final GetRequest get = new GetRequest(tsdb.uidTable(), MAXID_ROW);
get.family(ID_FAMILY);
get.qualifiers(kinds);
return tsdb.getClient().get(get).addCallback(new GetCB());
} | java | public static Deferred<Map<String, Long>> getUsedUIDs(final TSDB tsdb,
final byte[][] kinds) {
/**
* Returns a map with 0 if the max ID row hasn't been initialized yet,
* otherwise the map has actual data
*/
final class GetCB implements Callback<Map<String, Long>,
ArrayList<KeyValue>> {
@Override
public Map<String, Long> call(final ArrayList<KeyValue> row)
throws Exception {
final Map<String, Long> results = new HashMap<String, Long>(3);
if (row == null || row.isEmpty()) {
// it could be the case that this is the first time the TSD has run
// and the user hasn't put any metrics in, so log and return 0s
LOG.info("Could not find the UID assignment row");
for (final byte[] kind : kinds) {
results.put(new String(kind, CHARSET), 0L);
}
return results;
}
for (final KeyValue column : row) {
results.put(new String(column.qualifier(), CHARSET),
Bytes.getLong(column.value()));
}
// if the user is starting with a fresh UID table, we need to account
// for missing columns
for (final byte[] kind : kinds) {
if (results.get(new String(kind, CHARSET)) == null) {
results.put(new String(kind, CHARSET), 0L);
}
}
return results;
}
}
final GetRequest get = new GetRequest(tsdb.uidTable(), MAXID_ROW);
get.family(ID_FAMILY);
get.qualifiers(kinds);
return tsdb.getClient().get(get).addCallback(new GetCB());
} | [
"public",
"static",
"Deferred",
"<",
"Map",
"<",
"String",
",",
"Long",
">",
">",
"getUsedUIDs",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"byte",
"[",
"]",
"[",
"]",
"kinds",
")",
"{",
"/**\n * Returns a map with 0 if the max ID row hasn't been initialized ... | Returns a map of max UIDs from storage for the given list of UID types
@param tsdb The TSDB to which we belong
@param kinds A list of qualifiers to fetch
@return A map with the "kind" as the key and the maximum assigned UID as
the value
@since 2.0 | [
"Returns",
"a",
"map",
"of",
"max",
"UIDs",
"from",
"storage",
"for",
"the",
"given",
"list",
"of",
"UID",
"types"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/uid/UniqueId.java#L1700-L1746 |
stephenc/redmine-java-api | src/main/java/org/redmine/ta/internal/Transport.java | Transport.getChildEntries | public <T> List<T> getChildEntries(Class<?> parentClass, String parentId,
Class<T> classs) throws RedmineException {
final EntityConfig<T> config = getConfig(classs);
final URI uri = getURIConfigurator().getChildObjectsURI(parentClass,
parentId, classs);
HttpGet http = new HttpGet(uri);
String response = getCommunicator().sendRequest(http);
final JSONObject responseObject;
try {
responseObject = RedmineJSONParser.getResponse(response);
return JsonInput.getListNotNull(responseObject,
config.multiObjectName, config.parser);
} catch (JSONException e) {
throw new RedmineFormatException("Bad categories response " + response, e);
}
} | java | public <T> List<T> getChildEntries(Class<?> parentClass, String parentId,
Class<T> classs) throws RedmineException {
final EntityConfig<T> config = getConfig(classs);
final URI uri = getURIConfigurator().getChildObjectsURI(parentClass,
parentId, classs);
HttpGet http = new HttpGet(uri);
String response = getCommunicator().sendRequest(http);
final JSONObject responseObject;
try {
responseObject = RedmineJSONParser.getResponse(response);
return JsonInput.getListNotNull(responseObject,
config.multiObjectName, config.parser);
} catch (JSONException e) {
throw new RedmineFormatException("Bad categories response " + response, e);
}
} | [
"public",
"<",
"T",
">",
"List",
"<",
"T",
">",
"getChildEntries",
"(",
"Class",
"<",
"?",
">",
"parentClass",
",",
"String",
"parentId",
",",
"Class",
"<",
"T",
">",
"classs",
")",
"throws",
"RedmineException",
"{",
"final",
"EntityConfig",
"<",
"T",
... | Delivers a list of a child entries.
@param classs
target class. | [
"Delivers",
"a",
"list",
"of",
"a",
"child",
"entries",
"."
] | train | https://github.com/stephenc/redmine-java-api/blob/7e5270c84aba32d74a506260ec47ff86ab6c9d84/src/main/java/org/redmine/ta/internal/Transport.java#L416-L432 |
mozilla/rhino | src/org/mozilla/javascript/ScriptableObject.java | ScriptableObject.putConstProperty | public static void putConstProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
if (base instanceof ConstProperties)
((ConstProperties)base).putConst(name, obj, value);
} | java | public static void putConstProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
if (base instanceof ConstProperties)
((ConstProperties)base).putConst(name, obj, value);
} | [
"public",
"static",
"void",
"putConstProperty",
"(",
"Scriptable",
"obj",
",",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"Scriptable",
"base",
"=",
"getBase",
"(",
"obj",
",",
"name",
")",
";",
"if",
"(",
"base",
"==",
"null",
")",
"base",
"=... | Puts a named property in an object or in an object in its prototype chain.
<p>
Searches for the named property in the prototype chain. If it is found,
the value of the property in <code>obj</code> is changed through a call
to {@link Scriptable#put(String, Scriptable, Object)} on the
prototype passing <code>obj</code> as the <code>start</code> argument.
This allows the prototype to veto the property setting in case the
prototype defines the property with [[ReadOnly]] attribute. If the
property is not found, it is added in <code>obj</code>.
@param obj a JavaScript object
@param name a property name
@param value any JavaScript value accepted by Scriptable.put
@since 1.5R2 | [
"Puts",
"a",
"named",
"property",
"in",
"an",
"object",
"or",
"in",
"an",
"object",
"in",
"its",
"prototype",
"chain",
".",
"<p",
">",
"Searches",
"for",
"the",
"named",
"property",
"in",
"the",
"prototype",
"chain",
".",
"If",
"it",
"is",
"found",
"th... | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptableObject.java#L2536-L2543 |
vanilladb/vanillacore | src/main/java/org/vanilladb/core/storage/index/btree/BTreeDir.java | BTreeDir.makeNewRoot | public void makeNewRoot(DirEntry e) {
// makes sure it is opening the root block
if (currentPage.currentBlk().number() != 0) {
currentPage.close();
currentPage = new BTreePage(new BlockId(currentPage.currentBlk().fileName(), 0),
NUM_FLAGS, schema, tx);
}
SearchKey firstKey = getKey(currentPage, 0, keyType.length());
long level = getLevelFlag(currentPage);
// transfer all records to the new block
long newBlkNum = currentPage.split(0, new long[] { level });
DirEntry oldRootEntry = new DirEntry(firstKey, newBlkNum);
insert(oldRootEntry);
insert(e);
setLevelFlag(currentPage, level + 1);
} | java | public void makeNewRoot(DirEntry e) {
// makes sure it is opening the root block
if (currentPage.currentBlk().number() != 0) {
currentPage.close();
currentPage = new BTreePage(new BlockId(currentPage.currentBlk().fileName(), 0),
NUM_FLAGS, schema, tx);
}
SearchKey firstKey = getKey(currentPage, 0, keyType.length());
long level = getLevelFlag(currentPage);
// transfer all records to the new block
long newBlkNum = currentPage.split(0, new long[] { level });
DirEntry oldRootEntry = new DirEntry(firstKey, newBlkNum);
insert(oldRootEntry);
insert(e);
setLevelFlag(currentPage, level + 1);
} | [
"public",
"void",
"makeNewRoot",
"(",
"DirEntry",
"e",
")",
"{",
"// makes sure it is opening the root block\r",
"if",
"(",
"currentPage",
".",
"currentBlk",
"(",
")",
".",
"number",
"(",
")",
"!=",
"0",
")",
"{",
"currentPage",
".",
"close",
"(",
")",
";",
... | Creates a new root block for the B-tree. The new root will have two
children: the old root, and the specified block. Since the root must
always be in block 0 of the file, the contents of block 0 will get
transferred to a new block (serving as the old root).
@param e
the directory entry to be added as a child of the new root | [
"Creates",
"a",
"new",
"root",
"block",
"for",
"the",
"B",
"-",
"tree",
".",
"The",
"new",
"root",
"will",
"have",
"two",
"children",
":",
"the",
"old",
"root",
"and",
"the",
"specified",
"block",
".",
"Since",
"the",
"root",
"must",
"always",
"be",
... | train | https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/index/btree/BTreeDir.java#L186-L202 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV1ServerState.java | PaymentChannelV1ServerState.provideRefundTransaction | public synchronized byte[] provideRefundTransaction(Transaction refundTx, byte[] clientMultiSigPubKey) throws VerificationException {
checkNotNull(refundTx);
checkNotNull(clientMultiSigPubKey);
stateMachine.checkState(State.WAITING_FOR_REFUND_TRANSACTION);
log.info("Provided with refund transaction: {}", refundTx);
// Do a few very basic syntax sanity checks.
refundTx.verify();
// Verify that the refund transaction has a single input (that we can fill to sign the multisig output).
if (refundTx.getInputs().size() != 1)
throw new VerificationException("Refund transaction does not have exactly one input");
// Verify that the refund transaction has a time lock on it and a sequence number that does not disable lock time.
if (refundTx.getInput(0).getSequenceNumber() == TransactionInput.NO_SEQUENCE)
throw new VerificationException("Refund transaction's input's sequence number disables lock time");
if (refundTx.getLockTime() < minExpireTime)
throw new VerificationException("Refund transaction has a lock time too soon");
// Verify the transaction has one output (we don't care about its contents, its up to the client)
// Note that because we sign with SIGHASH_NONE|SIGHASH_ANYOENCANPAY the client can later add more outputs and
// inputs, but we will need only one output later to create the paying transactions
if (refundTx.getOutputs().size() != 1)
throw new VerificationException("Refund transaction does not have exactly one output");
refundTransactionUnlockTimeSecs = refundTx.getLockTime();
// Sign the refund tx with the scriptPubKey and return the signature. We don't have the spending transaction
// so do the steps individually.
clientKey = ECKey.fromPublicOnly(clientMultiSigPubKey);
Script multisigPubKey = ScriptBuilder.createMultiSigOutputScript(2, ImmutableList.of(clientKey, serverKey));
// We are really only signing the fact that the transaction has a proper lock time and don't care about anything
// else, so we sign SIGHASH_NONE and SIGHASH_ANYONECANPAY.
TransactionSignature sig = refundTx.calculateSignature(0, serverKey, multisigPubKey, Transaction.SigHash.NONE, true);
log.info("Signed refund transaction.");
this.clientOutput = refundTx.getOutput(0);
stateMachine.transition(State.WAITING_FOR_MULTISIG_CONTRACT);
return sig.encodeToBitcoin();
} | java | public synchronized byte[] provideRefundTransaction(Transaction refundTx, byte[] clientMultiSigPubKey) throws VerificationException {
checkNotNull(refundTx);
checkNotNull(clientMultiSigPubKey);
stateMachine.checkState(State.WAITING_FOR_REFUND_TRANSACTION);
log.info("Provided with refund transaction: {}", refundTx);
// Do a few very basic syntax sanity checks.
refundTx.verify();
// Verify that the refund transaction has a single input (that we can fill to sign the multisig output).
if (refundTx.getInputs().size() != 1)
throw new VerificationException("Refund transaction does not have exactly one input");
// Verify that the refund transaction has a time lock on it and a sequence number that does not disable lock time.
if (refundTx.getInput(0).getSequenceNumber() == TransactionInput.NO_SEQUENCE)
throw new VerificationException("Refund transaction's input's sequence number disables lock time");
if (refundTx.getLockTime() < minExpireTime)
throw new VerificationException("Refund transaction has a lock time too soon");
// Verify the transaction has one output (we don't care about its contents, its up to the client)
// Note that because we sign with SIGHASH_NONE|SIGHASH_ANYOENCANPAY the client can later add more outputs and
// inputs, but we will need only one output later to create the paying transactions
if (refundTx.getOutputs().size() != 1)
throw new VerificationException("Refund transaction does not have exactly one output");
refundTransactionUnlockTimeSecs = refundTx.getLockTime();
// Sign the refund tx with the scriptPubKey and return the signature. We don't have the spending transaction
// so do the steps individually.
clientKey = ECKey.fromPublicOnly(clientMultiSigPubKey);
Script multisigPubKey = ScriptBuilder.createMultiSigOutputScript(2, ImmutableList.of(clientKey, serverKey));
// We are really only signing the fact that the transaction has a proper lock time and don't care about anything
// else, so we sign SIGHASH_NONE and SIGHASH_ANYONECANPAY.
TransactionSignature sig = refundTx.calculateSignature(0, serverKey, multisigPubKey, Transaction.SigHash.NONE, true);
log.info("Signed refund transaction.");
this.clientOutput = refundTx.getOutput(0);
stateMachine.transition(State.WAITING_FOR_MULTISIG_CONTRACT);
return sig.encodeToBitcoin();
} | [
"public",
"synchronized",
"byte",
"[",
"]",
"provideRefundTransaction",
"(",
"Transaction",
"refundTx",
",",
"byte",
"[",
"]",
"clientMultiSigPubKey",
")",
"throws",
"VerificationException",
"{",
"checkNotNull",
"(",
"refundTx",
")",
";",
"checkNotNull",
"(",
"clien... | Called when the client provides the refund transaction.
The refund transaction must have one input from the multisig contract (that we don't have yet) and one output
that the client creates to themselves. This object will later be modified when we start getting paid.
@param refundTx The refund transaction, this object will be mutated when payment is incremented.
@param clientMultiSigPubKey The client's pubkey which is required for the multisig output
@return Our signature that makes the refund transaction valid
@throws VerificationException If the transaction isnt valid or did not meet the requirements of a refund transaction. | [
"Called",
"when",
"the",
"client",
"provides",
"the",
"refund",
"transaction",
".",
"The",
"refund",
"transaction",
"must",
"have",
"one",
"input",
"from",
"the",
"multisig",
"contract",
"(",
"that",
"we",
"don",
"t",
"have",
"yet",
")",
"and",
"one",
"out... | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV1ServerState.java#L124-L158 |
jpelzer/pelzer-util | src/main/java/com/pelzer/util/StringMan.java | StringMan.detokenize | public static String detokenize(String[] values, String delimiter) {
return concat(values, delimiter, 0, values.length - 1);
} | java | public static String detokenize(String[] values, String delimiter) {
return concat(values, delimiter, 0, values.length - 1);
} | [
"public",
"static",
"String",
"detokenize",
"(",
"String",
"[",
"]",
"values",
",",
"String",
"delimiter",
")",
"{",
"return",
"concat",
"(",
"values",
",",
"delimiter",
",",
"0",
",",
"values",
".",
"length",
"-",
"1",
")",
";",
"}"
] | Converts a string array into a single string with values delimited by the specified delimiter. | [
"Converts",
"a",
"string",
"array",
"into",
"a",
"single",
"string",
"with",
"values",
"delimited",
"by",
"the",
"specified",
"delimiter",
"."
] | train | https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/StringMan.java#L466-L468 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/error/impl/DefaultSystemFailureMapper.java | DefaultSystemFailureMapper.toMessage | @Override
public Message toMessage(final Throwable throwable) {
LOG.error("The system is currently unavailable", throwable);
return new Message(Message.ERROR_MESSAGE, InternalMessages.DEFAULT_SYSTEM_ERROR);
} | java | @Override
public Message toMessage(final Throwable throwable) {
LOG.error("The system is currently unavailable", throwable);
return new Message(Message.ERROR_MESSAGE, InternalMessages.DEFAULT_SYSTEM_ERROR);
} | [
"@",
"Override",
"public",
"Message",
"toMessage",
"(",
"final",
"Throwable",
"throwable",
")",
"{",
"LOG",
".",
"error",
"(",
"\"The system is currently unavailable\"",
",",
"throwable",
")",
";",
"return",
"new",
"Message",
"(",
"Message",
".",
"ERROR_MESSAGE",
... | This method converts a java Throwable into a "user friendly" error message.
@param throwable the Throwable to convert
@return A {@link Message} containing the hard coded description "The system is currently unavailable." | [
"This",
"method",
"converts",
"a",
"java",
"Throwable",
"into",
"a",
"user",
"friendly",
"error",
"message",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/error/impl/DefaultSystemFailureMapper.java#L27-L31 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/config/Config.java | Config.getCacheEventJournalConfig | public EventJournalConfig getCacheEventJournalConfig(String name) {
return ConfigUtils.getConfig(configPatternMatcher, cacheEventJournalConfigs, name, EventJournalConfig.class,
new BiConsumer<EventJournalConfig, String>() {
@Override
public void accept(EventJournalConfig eventJournalConfig, String name) {
eventJournalConfig.setCacheName(name);
if ("default".equals(name)) {
eventJournalConfig.setEnabled(false);
}
}
});
} | java | public EventJournalConfig getCacheEventJournalConfig(String name) {
return ConfigUtils.getConfig(configPatternMatcher, cacheEventJournalConfigs, name, EventJournalConfig.class,
new BiConsumer<EventJournalConfig, String>() {
@Override
public void accept(EventJournalConfig eventJournalConfig, String name) {
eventJournalConfig.setCacheName(name);
if ("default".equals(name)) {
eventJournalConfig.setEnabled(false);
}
}
});
} | [
"public",
"EventJournalConfig",
"getCacheEventJournalConfig",
"(",
"String",
"name",
")",
"{",
"return",
"ConfigUtils",
".",
"getConfig",
"(",
"configPatternMatcher",
",",
"cacheEventJournalConfigs",
",",
"name",
",",
"EventJournalConfig",
".",
"class",
",",
"new",
"B... | Returns the cache event journal config for the given name, creating one
if necessary and adding it to the collection of known configurations.
<p>
The configuration is found by matching the configuration name
pattern to the provided {@code name} without the partition qualifier
(the part of the name after {@code '@'}).
If no configuration matches, it will create one by cloning the
{@code "default"} configuration and add it to the configuration
collection.
<p>
If there is no default config as well, it will create one and disable
the event journal by default.
This method is intended to easily and fluently create and add
configurations more specific than the default configuration without
explicitly adding it by invoking
{@link #addEventJournalConfig(EventJournalConfig)}.
<p>
Because it adds new configurations if they are not already present,
this method is intended to be used before this config is used to
create a hazelcast instance. Afterwards, newly added configurations
may be ignored.
@param name name of the cache event journal config
@return the cache event journal configuration
@throws ConfigurationException if ambiguous configurations are found
@see StringPartitioningStrategy#getBaseName(java.lang.String)
@see #setConfigPatternMatcher(ConfigPatternMatcher)
@see #getConfigPatternMatcher() | [
"Returns",
"the",
"cache",
"event",
"journal",
"config",
"for",
"the",
"given",
"name",
"creating",
"one",
"if",
"necessary",
"and",
"adding",
"it",
"to",
"the",
"collection",
"of",
"known",
"configurations",
".",
"<p",
">",
"The",
"configuration",
"is",
"fo... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L2860-L2871 |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java | ClusterComputeResourceService.updateOrAddVmOverride | public Map<String, String> updateOrAddVmOverride(final HttpInputs httpInputs, final VmInputs vmInputs, final String restartPriority) throws Exception {
final ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
final ManagedObjectReference vmMor = getVirtualMachineReference(vmInputs, connectionResources);
final ManagedObjectReference clusterMor = new MorObjectHandler().getSpecificMor(connectionResources, connectionResources.getMorRootFolder(),
ClusterParameter.CLUSTER_COMPUTE_RESOURCE.getValue(), vmInputs.getClusterName());
final ClusterConfigInfoEx clusterConfigInfoEx = getClusterConfiguration(connectionResources, clusterMor, vmInputs.getClusterName());
final ClusterDasVmConfigSpec clusterDasVmConfigSpec = getClusterVmConfiguration(clusterConfigInfoEx, vmMor, restartPriority);
final ManagedObjectReference task = connectionResources.getVimPortType()
.reconfigureComputeResourceTask(clusterMor, createClusterConfigSpecEx(clusterConfigInfoEx, clusterDasVmConfigSpec), true);
return new ResponseHelper(connectionResources, task)
.getResultsMap(String.format(SUCCESS_MSG, vmInputs.getClusterName(), task.getValue()),
String.format(FAILURE_MSG, vmInputs.getClusterName()));
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> updateOrAddVmOverride(final HttpInputs httpInputs, final VmInputs vmInputs, final String restartPriority) throws Exception {
final ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
final ManagedObjectReference vmMor = getVirtualMachineReference(vmInputs, connectionResources);
final ManagedObjectReference clusterMor = new MorObjectHandler().getSpecificMor(connectionResources, connectionResources.getMorRootFolder(),
ClusterParameter.CLUSTER_COMPUTE_RESOURCE.getValue(), vmInputs.getClusterName());
final ClusterConfigInfoEx clusterConfigInfoEx = getClusterConfiguration(connectionResources, clusterMor, vmInputs.getClusterName());
final ClusterDasVmConfigSpec clusterDasVmConfigSpec = getClusterVmConfiguration(clusterConfigInfoEx, vmMor, restartPriority);
final ManagedObjectReference task = connectionResources.getVimPortType()
.reconfigureComputeResourceTask(clusterMor, createClusterConfigSpecEx(clusterConfigInfoEx, clusterDasVmConfigSpec), true);
return new ResponseHelper(connectionResources, task)
.getResultsMap(String.format(SUCCESS_MSG, vmInputs.getClusterName(), task.getValue()),
String.format(FAILURE_MSG, vmInputs.getClusterName()));
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"updateOrAddVmOverride",
"(",
"final",
"HttpInputs",
"httpInputs",
",",
"final",
"VmInputs",
"vmInputs",
",",
"final",
"String",
"restartPriority",
")",
"throws",
"Exception",
"{",
"final",
"ConnectionResources",
... | Das method looks into das Cluster’s list of VM overrides to update das VM’s restartPriority value.
If a VM override is found, das value will be updated, otherwise a new “override” will be created and added to das list.
@param httpInputs
@param vmInputs
@param restartPriority
@return
@throws Exception | [
"Das",
"method",
"looks",
"into",
"das",
"Cluster’s",
"list",
"of",
"VM",
"overrides",
"to",
"update",
"das",
"VM’s",
"restartPriority",
"value",
".",
"If",
"a",
"VM",
"override",
"is",
"found",
"das",
"value",
"will",
"be",
"updated",
"otherwise",
"a",
"n... | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/ClusterComputeResourceService.java#L44-L67 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.feed_publishActionOfUser | public boolean feed_publishActionOfUser(CharSequence title, CharSequence body)
throws FacebookException, IOException {
return feed_publishActionOfUser(title, body, null);
} | java | public boolean feed_publishActionOfUser(CharSequence title, CharSequence body)
throws FacebookException, IOException {
return feed_publishActionOfUser(title, body, null);
} | [
"public",
"boolean",
"feed_publishActionOfUser",
"(",
"CharSequence",
"title",
",",
"CharSequence",
"body",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"return",
"feed_publishActionOfUser",
"(",
"title",
",",
"body",
",",
"null",
")",
";",
"}"
] | Publish the notification of an action taken by a user to newsfeed.
@param title the title of the feed story (up to 60 characters, excluding tags)
@param body (optional) the body of the feed story (up to 200 characters, excluding tags)
@return whether the story was successfully published; false in case of permission error
@see <a href="http://wiki.developers.facebook.com/index.php/Feed.publishActionOfUser">
Developers Wiki: Feed.publishActionOfUser</a> | [
"Publish",
"the",
"notification",
"of",
"an",
"action",
"taken",
"by",
"a",
"user",
"to",
"newsfeed",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L300-L303 |
vladmihalcea/db-util | src/main/java/com/vladmihalcea/sql/SQLStatementCountValidator.java | SQLStatementCountValidator.assertSelectCount | public static void assertSelectCount(long expectedSelectCount) {
QueryCount queryCount = QueryCountHolder.getGrandTotal();
long recordedSelectCount = queryCount.getSelect();
if (expectedSelectCount != recordedSelectCount) {
throw new SQLSelectCountMismatchException(expectedSelectCount, recordedSelectCount);
}
} | java | public static void assertSelectCount(long expectedSelectCount) {
QueryCount queryCount = QueryCountHolder.getGrandTotal();
long recordedSelectCount = queryCount.getSelect();
if (expectedSelectCount != recordedSelectCount) {
throw new SQLSelectCountMismatchException(expectedSelectCount, recordedSelectCount);
}
} | [
"public",
"static",
"void",
"assertSelectCount",
"(",
"long",
"expectedSelectCount",
")",
"{",
"QueryCount",
"queryCount",
"=",
"QueryCountHolder",
".",
"getGrandTotal",
"(",
")",
";",
"long",
"recordedSelectCount",
"=",
"queryCount",
".",
"getSelect",
"(",
")",
"... | Assert select statement count
@param expectedSelectCount expected select statement count | [
"Assert",
"select",
"statement",
"count"
] | train | https://github.com/vladmihalcea/db-util/blob/81c8c8421253c9869db1d4e221668d7afbd69fd0/src/main/java/com/vladmihalcea/sql/SQLStatementCountValidator.java#L51-L57 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/code/Types.java | Types.isConvertible | public boolean isConvertible(Type t, Type s, Warner warn) {
if (t.hasTag(ERROR)) {
return true;
}
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (tPrimitive == sPrimitive) {
return isSubtypeUnchecked(t, s, warn);
}
if (!allowBoxing) return false;
return tPrimitive
? isSubtype(boxedClass(t).type, s)
: isSubtype(unboxedType(t), s);
} | java | public boolean isConvertible(Type t, Type s, Warner warn) {
if (t.hasTag(ERROR)) {
return true;
}
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (tPrimitive == sPrimitive) {
return isSubtypeUnchecked(t, s, warn);
}
if (!allowBoxing) return false;
return tPrimitive
? isSubtype(boxedClass(t).type, s)
: isSubtype(unboxedType(t), s);
} | [
"public",
"boolean",
"isConvertible",
"(",
"Type",
"t",
",",
"Type",
"s",
",",
"Warner",
"warn",
")",
"{",
"if",
"(",
"t",
".",
"hasTag",
"(",
"ERROR",
")",
")",
"{",
"return",
"true",
";",
"}",
"boolean",
"tPrimitive",
"=",
"t",
".",
"isPrimitive",
... | Is t a subtype of or convertible via boxing/unboxing
conversion to s? | [
"Is",
"t",
"a",
"subtype",
"of",
"or",
"convertible",
"via",
"boxing",
"/",
"unboxing",
"conversion",
"to",
"s?"
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/code/Types.java#L292-L305 |
super-csv/super-csv | super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireHashCode.java | RequireHashCode.execute | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
int hash = value.hashCode();
if( !requiredHashCodes.contains(hash) ) {
throw new SuperCsvConstraintViolationException(String.format(
"the hashcode of %d for value '%s' does not match any of the required hashcodes", hash, value),
context, this);
}
return next.execute(value, context);
} | java | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
int hash = value.hashCode();
if( !requiredHashCodes.contains(hash) ) {
throw new SuperCsvConstraintViolationException(String.format(
"the hashcode of %d for value '%s' does not match any of the required hashcodes", hash, value),
context, this);
}
return next.execute(value, context);
} | [
"public",
"Object",
"execute",
"(",
"final",
"Object",
"value",
",",
"final",
"CsvContext",
"context",
")",
"{",
"validateInputNotNull",
"(",
"value",
",",
"context",
")",
";",
"int",
"hash",
"=",
"value",
".",
"hashCode",
"(",
")",
";",
"if",
"(",
"!",
... | {@inheritDoc}
@throws SuperCsvCellProcessorException
if value is null
@throws SuperCsvConstraintViolationException
if value isn't one of the required hash codes | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/RequireHashCode.java#L131-L142 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/SliderArea.java | SliderArea.drawMapRectangle | public void drawMapRectangle() {
mapWidget.getVectorContext().drawRectangle(group, MAP_AREA,
new Bbox(0, 0, mapWidget.getWidth(), mapWidget.getHeight()),
// IE9 does not draw an empty shapestyle (new ShapeStyle()), but it does draw one with opacity = 0...
new ShapeStyle("#00FF00", 0, "#00FF00", 0, 1));
// new ShapeStyle("#00FF00", 0.1f, "#00FF00", 0.5f, 1));
} | java | public void drawMapRectangle() {
mapWidget.getVectorContext().drawRectangle(group, MAP_AREA,
new Bbox(0, 0, mapWidget.getWidth(), mapWidget.getHeight()),
// IE9 does not draw an empty shapestyle (new ShapeStyle()), but it does draw one with opacity = 0...
new ShapeStyle("#00FF00", 0, "#00FF00", 0, 1));
// new ShapeStyle("#00FF00", 0.1f, "#00FF00", 0.5f, 1));
} | [
"public",
"void",
"drawMapRectangle",
"(",
")",
"{",
"mapWidget",
".",
"getVectorContext",
"(",
")",
".",
"drawRectangle",
"(",
"group",
",",
"MAP_AREA",
",",
"new",
"Bbox",
"(",
"0",
",",
"0",
",",
"mapWidget",
".",
"getWidth",
"(",
")",
",",
"mapWidget... | Provides a rectangle over the map, on which the onDrag event of {@link ZoomSliderController} is listening.
An onUp event redraws this rectangle into the start rectangle with {@link SliderArea#drawStartRectangle()}. | [
"Provides",
"a",
"rectangle",
"over",
"the",
"map",
"on",
"which",
"the",
"onDrag",
"event",
"of",
"{"
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/SliderArea.java#L86-L92 |
menacher/java-game-server | jetserver/src/main/java/org/menacheri/jetserver/concurrent/DataFlowVariable.java | DataFlowVariable.getVal | public Object getVal(long waitTime, TimeUnit timeUnit)
throws InterruptedException
{
if(latch.await(waitTime, timeUnit)){
return val;
}
else
{
return null;
}
} | java | public Object getVal(long waitTime, TimeUnit timeUnit)
throws InterruptedException
{
if(latch.await(waitTime, timeUnit)){
return val;
}
else
{
return null;
}
} | [
"public",
"Object",
"getVal",
"(",
"long",
"waitTime",
",",
"TimeUnit",
"timeUnit",
")",
"throws",
"InterruptedException",
"{",
"if",
"(",
"latch",
".",
"await",
"(",
"waitTime",
",",
"timeUnit",
")",
")",
"{",
"return",
"val",
";",
"}",
"else",
"{",
"re... | This method blocks for a specified amount of time to retrieve the value
bound in bind method.
@param waitTime
the amount of time to wait
@param timeUnit
the unit, milliseconds, seconds etc.
@return Returns the bound value or null if the time out has exceeded.
@throws InterruptedException | [
"This",
"method",
"blocks",
"for",
"a",
"specified",
"amount",
"of",
"time",
"to",
"retrieve",
"the",
"value",
"bound",
"in",
"bind",
"method",
"."
] | train | https://github.com/menacher/java-game-server/blob/668ca49e8bd1dac43add62378cf6c22a93125d48/jetserver/src/main/java/org/menacheri/jetserver/concurrent/DataFlowVariable.java#L65-L75 |
gwtbootstrap3/gwtbootstrap3 | gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/ScrollSpy.java | ScrollSpy.scrollSpy | public static ScrollSpy scrollSpy(final UIObject spyOn, final HasId target) {
return new ScrollSpy(spyOn.getElement(), target);
} | java | public static ScrollSpy scrollSpy(final UIObject spyOn, final HasId target) {
return new ScrollSpy(spyOn.getElement(), target);
} | [
"public",
"static",
"ScrollSpy",
"scrollSpy",
"(",
"final",
"UIObject",
"spyOn",
",",
"final",
"HasId",
"target",
")",
"{",
"return",
"new",
"ScrollSpy",
"(",
"spyOn",
".",
"getElement",
"(",
")",
",",
"target",
")",
";",
"}"
] | Attaches ScrollSpy to specified object with specified target element.
@param spyOn Spy on this object
@param target Target element having an ID
@return ScrollSpy | [
"Attaches",
"ScrollSpy",
"to",
"specified",
"object",
"with",
"specified",
"target",
"element",
"."
] | train | https://github.com/gwtbootstrap3/gwtbootstrap3/blob/54bdbd0b12ba7a436b278c007df960d1adf2e641/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/ScrollSpy.java#L97-L99 |
googleads/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java | ProductPartitionTreeImpl.createAdGroupTree | static ProductPartitionTreeImpl createAdGroupTree(Long adGroupId,
BiddingStrategyConfiguration biddingStrategyConfig, List<AdGroupCriterion> adGroupCriteria) {
Preconditions.checkNotNull(adGroupId, "Null ad group ID");
Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration");
Preconditions.checkNotNull(adGroupCriteria, "Null criteria list");
if (adGroupCriteria.isEmpty()) {
return createEmptyAdGroupTree(adGroupId, biddingStrategyConfig);
}
ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
for (AdGroupCriterion adGroupCriterion : adGroupCriteria) {
Preconditions.checkNotNull(adGroupCriterion.getCriterion(),
"AdGroupCriterion has a null criterion");
if (adGroupCriterion instanceof BiddableAdGroupCriterion) {
BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion) adGroupCriterion;
Preconditions.checkNotNull(biddableCriterion.getUserStatus(),
"User status is null for criterion ID %s", biddableCriterion.getCriterion().getId());
if (UserStatus.REMOVED.equals(biddableCriterion.getUserStatus())) {
// Skip REMOVED criteria.
continue;
}
}
if (adGroupCriterion.getCriterion() instanceof ProductPartition) {
ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
}
}
return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
} | java | static ProductPartitionTreeImpl createAdGroupTree(Long adGroupId,
BiddingStrategyConfiguration biddingStrategyConfig, List<AdGroupCriterion> adGroupCriteria) {
Preconditions.checkNotNull(adGroupId, "Null ad group ID");
Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration");
Preconditions.checkNotNull(adGroupCriteria, "Null criteria list");
if (adGroupCriteria.isEmpty()) {
return createEmptyAdGroupTree(adGroupId, biddingStrategyConfig);
}
ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
for (AdGroupCriterion adGroupCriterion : adGroupCriteria) {
Preconditions.checkNotNull(adGroupCriterion.getCriterion(),
"AdGroupCriterion has a null criterion");
if (adGroupCriterion instanceof BiddableAdGroupCriterion) {
BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion) adGroupCriterion;
Preconditions.checkNotNull(biddableCriterion.getUserStatus(),
"User status is null for criterion ID %s", biddableCriterion.getCriterion().getId());
if (UserStatus.REMOVED.equals(biddableCriterion.getUserStatus())) {
// Skip REMOVED criteria.
continue;
}
}
if (adGroupCriterion.getCriterion() instanceof ProductPartition) {
ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
}
}
return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
} | [
"static",
"ProductPartitionTreeImpl",
"createAdGroupTree",
"(",
"Long",
"adGroupId",
",",
"BiddingStrategyConfiguration",
"biddingStrategyConfig",
",",
"List",
"<",
"AdGroupCriterion",
">",
"adGroupCriteria",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"adGroupId",... | Returns a new instance of this class based on the collection of ad group criteria provided.
<p>NOTE: If retrieving existing criteria for use with this method, you must include all of the
fields in {@link #REQUIRED_SELECTOR_FIELD_ENUMS} in your {@link Selector}.
@param adGroupId the ID of the ad group
@param biddingStrategyConfig the {@link BiddingStrategyConfiguration} for the ad group
@param adGroupCriteria the non-null (but possibly empty) list of ad group criteria
@throws NullPointerException if any argument is null, any element in {@code adGroupCriteria} is
null, or any required field from {@link #REQUIRED_SELECTOR_FIELD_ENUMS} is missing from
an element in {@code adGroupCriteria}
@throws IllegalArgumentException if {@code adGroupCriteria} does not include the root criterion
of the product partition tree | [
"Returns",
"a",
"new",
"instance",
"of",
"this",
"class",
"based",
"on",
"the",
"collection",
"of",
"ad",
"group",
"criteria",
"provided",
".",
"<p",
">",
"NOTE",
":",
"If",
"retrieving",
"existing",
"criteria",
"for",
"use",
"with",
"this",
"method",
"you... | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java#L247-L276 |
UrielCh/ovh-java-sdk | ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java | ApiOvhHostingweb.serviceName_email_bounces_GET | public ArrayList<OvhBounce> serviceName_email_bounces_GET(String serviceName, Long limit) throws IOException {
String qPath = "/hosting/web/{serviceName}/email/bounces";
StringBuilder sb = path(qPath, serviceName);
query(sb, "limit", limit);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t11);
} | java | public ArrayList<OvhBounce> serviceName_email_bounces_GET(String serviceName, Long limit) throws IOException {
String qPath = "/hosting/web/{serviceName}/email/bounces";
StringBuilder sb = path(qPath, serviceName);
query(sb, "limit", limit);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t11);
} | [
"public",
"ArrayList",
"<",
"OvhBounce",
">",
"serviceName_email_bounces_GET",
"(",
"String",
"serviceName",
",",
"Long",
"limit",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/hosting/web/{serviceName}/email/bounces\"",
";",
"StringBuilder",
"sb",
"=",... | Request the last bounces
REST: GET /hosting/web/{serviceName}/email/bounces
@param limit [required] Maximum bounces limit ( default : 20 / max : 100 )
@param serviceName [required] The internal name of your hosting | [
"Request",
"the",
"last",
"bounces"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L1905-L1911 |
cdk/cdk | base/valencycheck/src/main/java/org/openscience/cdk/tools/AtomTypeAwareSaturationChecker.java | AtomTypeAwareSaturationChecker.checkBond | private void checkBond(IAtomContainer atomContainer, int index) throws CDKException {
IBond bond = atomContainer.getBond(index);
if (bond != null && bond.getFlag(CDKConstants.SINGLE_OR_DOUBLE)) {
try {
oldBondOrder = bond.getOrder();
bond.setOrder(IBond.Order.SINGLE);
setMaxBondOrder(bond, atomContainer);
} catch (CDKException e) {
bond.setOrder(oldBondOrder);
logger.debug(e);
}
}
} | java | private void checkBond(IAtomContainer atomContainer, int index) throws CDKException {
IBond bond = atomContainer.getBond(index);
if (bond != null && bond.getFlag(CDKConstants.SINGLE_OR_DOUBLE)) {
try {
oldBondOrder = bond.getOrder();
bond.setOrder(IBond.Order.SINGLE);
setMaxBondOrder(bond, atomContainer);
} catch (CDKException e) {
bond.setOrder(oldBondOrder);
logger.debug(e);
}
}
} | [
"private",
"void",
"checkBond",
"(",
"IAtomContainer",
"atomContainer",
",",
"int",
"index",
")",
"throws",
"CDKException",
"{",
"IBond",
"bond",
"=",
"atomContainer",
".",
"getBond",
"(",
"index",
")",
";",
"if",
"(",
"bond",
"!=",
"null",
"&&",
"bond",
"... | This method tries to set the bond order on the current bond.
@param atomContainer The molecule
@param index The index of the current bond
@throws CDKException when no suitable solution can be found | [
"This",
"method",
"tries",
"to",
"set",
"the",
"bond",
"order",
"on",
"the",
"current",
"bond",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/valencycheck/src/main/java/org/openscience/cdk/tools/AtomTypeAwareSaturationChecker.java#L164-L177 |
CloudSlang/cs-actions | cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java | DateTimeUtils.formatWithDefault | public static DateTimeFormatter formatWithDefault(String lang, String country) {
return (StringUtils.isNotBlank(lang)) ? DateTimeFormat.longDateTime().withLocale(DateTimeUtils.getLocaleByCountry(lang, country)) :
DateTimeFormat.longDateTime().withLocale(Locale.getDefault());
} | java | public static DateTimeFormatter formatWithDefault(String lang, String country) {
return (StringUtils.isNotBlank(lang)) ? DateTimeFormat.longDateTime().withLocale(DateTimeUtils.getLocaleByCountry(lang, country)) :
DateTimeFormat.longDateTime().withLocale(Locale.getDefault());
} | [
"public",
"static",
"DateTimeFormatter",
"formatWithDefault",
"(",
"String",
"lang",
",",
"String",
"country",
")",
"{",
"return",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"lang",
")",
")",
"?",
"DateTimeFormat",
".",
"longDateTime",
"(",
")",
".",
"withLoc... | Generates a DateTimeFormatter using full date pattern with the default locale or a new one
according to what language and country are provided as params.
@param lang the language
@param country the country
@return the DateTimeFormatter generated | [
"Generates",
"a",
"DateTimeFormatter",
"using",
"full",
"date",
"pattern",
"with",
"the",
"default",
"locale",
"or",
"a",
"new",
"one",
"according",
"to",
"what",
"language",
"and",
"country",
"are",
"provided",
"as",
"params",
"."
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L120-L123 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java | ArrayUtil.append | @SafeVarargs
public static <T> T[] append(T[] buffer, T... newElements) {
if(isEmpty(buffer)) {
return newElements;
}
return insert(buffer, buffer.length, newElements);
} | java | @SafeVarargs
public static <T> T[] append(T[] buffer, T... newElements) {
if(isEmpty(buffer)) {
return newElements;
}
return insert(buffer, buffer.length, newElements);
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"T",
"[",
"]",
"append",
"(",
"T",
"[",
"]",
"buffer",
",",
"T",
"...",
"newElements",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"buffer",
")",
")",
"{",
"return",
"newElements",
";",
"}",
"return",... | 将新元素添加到已有数组中<br>
添加新元素会生成一个新的数组,不影响原数组
@param <T> 数组元素类型
@param buffer 已有数组
@param newElements 新元素
@return 新数组 | [
"将新元素添加到已有数组中<br",
">",
"添加新元素会生成一个新的数组,不影响原数组"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L382-L388 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/disktree/DiskTreeReader.java | DiskTreeReader.pickGeometry | public Geometry pickGeometry( long position, long size ) throws Exception {
byte[] geomBytes = new byte[(int) size];
raf.seek(position);
raf.read(geomBytes);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(geomBytes));
return (Geometry) in.readObject();
} | java | public Geometry pickGeometry( long position, long size ) throws Exception {
byte[] geomBytes = new byte[(int) size];
raf.seek(position);
raf.read(geomBytes);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(geomBytes));
return (Geometry) in.readObject();
} | [
"public",
"Geometry",
"pickGeometry",
"(",
"long",
"position",
",",
"long",
"size",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"geomBytes",
"=",
"new",
"byte",
"[",
"(",
"int",
")",
"size",
"]",
";",
"raf",
".",
"seek",
"(",
"position",
")",
... | Reads a single geomtry, using the info from the quadtree read in {@link #readIndex()}.
@param position the position of the geom to read.
@param size the size of the geom to read.
@return the read geometry.
@throws Exception | [
"Reads",
"a",
"single",
"geomtry",
"using",
"the",
"info",
"from",
"the",
"quadtree",
"read",
"in",
"{",
"@link",
"#readIndex",
"()",
"}",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/disktree/DiskTreeReader.java#L107-L114 |
JakeWharton/ActionBarSherlock | actionbarsherlock/src/com/actionbarsherlock/widget/SearchView.java | SearchView.onKeyDown | @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mSearchable == null) {
return false;
}
// if it's an action specified by the searchable activity, launch the
// entered query with the action key
// TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
// TODO if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
// TODO launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText()
// TODO .toString());
// TODO return true;
// TODO }
return super.onKeyDown(keyCode, event);
} | java | @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mSearchable == null) {
return false;
}
// if it's an action specified by the searchable activity, launch the
// entered query with the action key
// TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
// TODO if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
// TODO launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView.getText()
// TODO .toString());
// TODO return true;
// TODO }
return super.onKeyDown(keyCode, event);
} | [
"@",
"Override",
"public",
"boolean",
"onKeyDown",
"(",
"int",
"keyCode",
",",
"KeyEvent",
"event",
")",
"{",
"if",
"(",
"mSearchable",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"// if it's an action specified by the searchable activity, launch the",
"// ... | Handles the key down event for dealing with action keys.
@param keyCode This is the keycode of the typed key, and is the same value as
found in the KeyEvent parameter.
@param event The complete event record for the typed key
@return true if the event was handled here, or false if not. | [
"Handles",
"the",
"key",
"down",
"event",
"for",
"dealing",
"with",
"action",
"keys",
"."
] | train | https://github.com/JakeWharton/ActionBarSherlock/blob/2c71339e756bcc0b1424c4525680549ba3a2dc97/actionbarsherlock/src/com/actionbarsherlock/widget/SearchView.java#L901-L917 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/NetworkClient.java | NetworkClient.insertNetwork | @BetaApi
public final Operation insertNetwork(String project, Network networkResource) {
InsertNetworkHttpRequest request =
InsertNetworkHttpRequest.newBuilder()
.setProject(project)
.setNetworkResource(networkResource)
.build();
return insertNetwork(request);
} | java | @BetaApi
public final Operation insertNetwork(String project, Network networkResource) {
InsertNetworkHttpRequest request =
InsertNetworkHttpRequest.newBuilder()
.setProject(project)
.setNetworkResource(networkResource)
.build();
return insertNetwork(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertNetwork",
"(",
"String",
"project",
",",
"Network",
"networkResource",
")",
"{",
"InsertNetworkHttpRequest",
"request",
"=",
"InsertNetworkHttpRequest",
".",
"newBuilder",
"(",
")",
".",
"setProject",
"(",
"proj... | Creates a network in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (NetworkClient networkClient = NetworkClient.create()) {
ProjectName project = ProjectName.of("[PROJECT]");
Network networkResource = Network.newBuilder().build();
Operation response = networkClient.insertNetwork(project.toString(), networkResource);
}
</code></pre>
@param project Project ID for this request.
@param networkResource Represents a Network resource. Read Virtual Private Cloud (VPC) Network
Overview for more information. (== resource_for v1.networks ==) (== resource_for
beta.networks ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"network",
"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/NetworkClient.java#L511-L520 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/time/DateUtils.java | DateUtils.truncatedCompareTo | public static int truncatedCompareTo(final Date date1, final Date date2, final int field) {
final Date truncatedDate1 = truncate(date1, field);
final Date truncatedDate2 = truncate(date2, field);
return truncatedDate1.compareTo(truncatedDate2);
} | java | public static int truncatedCompareTo(final Date date1, final Date date2, final int field) {
final Date truncatedDate1 = truncate(date1, field);
final Date truncatedDate2 = truncate(date2, field);
return truncatedDate1.compareTo(truncatedDate2);
} | [
"public",
"static",
"int",
"truncatedCompareTo",
"(",
"final",
"Date",
"date1",
",",
"final",
"Date",
"date2",
",",
"final",
"int",
"field",
")",
"{",
"final",
"Date",
"truncatedDate1",
"=",
"truncate",
"(",
"date1",
",",
"field",
")",
";",
"final",
"Date"... | Determines how two dates compare up to no more than the specified
most significant field.
@param date1 the first date, not <code>null</code>
@param date2 the second date, not <code>null</code>
@param field the field from <code>Calendar</code>
@return a negative integer, zero, or a positive integer as the first
date is less than, equal to, or greater than the second.
@throws IllegalArgumentException if any argument is <code>null</code>
@see #truncate(Calendar, int)
@see #truncatedCompareTo(Date, Date, int)
@since 3.0 | [
"Determines",
"how",
"two",
"dates",
"compare",
"up",
"to",
"no",
"more",
"than",
"the",
"specified",
"most",
"significant",
"field",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1798-L1802 |
anotheria/moskito | moskito-web/src/main/java/net/anotheria/moskito/web/filters/JSTalkBackFilter.java | JSTalkBackFilter.getProducer | @SuppressWarnings("unchecked")
private OnDemandStatsProducer<PageInBrowserStats> getProducer(final String producerId, final String category, final String subsystem) {
final IStatsProducer statsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
// create new
if (statsProducer == null)
return createProducer(producerId, category, subsystem);
// use existing
if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats)
return (OnDemandStatsProducer<PageInBrowserStats>) statsProducer;
final IStatsProducer defaultStatsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(getDefaultProducerId());
// create default
if (defaultStatsProducer == null)
return createProducer(getDefaultProducerId(), category, subsystem);
// use existing default
if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats)
return (OnDemandStatsProducer<PageInBrowserStats>) defaultStatsProducer;
log.warn("Can't create OnDemandStatsProducer<BrowserStats> producer with passed id: [" + producerId + "] and default id: [" + getDefaultProducerId() + "].");
return null;
} | java | @SuppressWarnings("unchecked")
private OnDemandStatsProducer<PageInBrowserStats> getProducer(final String producerId, final String category, final String subsystem) {
final IStatsProducer statsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
// create new
if (statsProducer == null)
return createProducer(producerId, category, subsystem);
// use existing
if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats)
return (OnDemandStatsProducer<PageInBrowserStats>) statsProducer;
final IStatsProducer defaultStatsProducer = ProducerRegistryFactory.getProducerRegistryInstance().getProducer(getDefaultProducerId());
// create default
if (defaultStatsProducer == null)
return createProducer(getDefaultProducerId(), category, subsystem);
// use existing default
if (statsProducer instanceof OnDemandStatsProducer && OnDemandStatsProducer.class.cast(statsProducer).getDefaultStats() instanceof PageInBrowserStats)
return (OnDemandStatsProducer<PageInBrowserStats>) defaultStatsProducer;
log.warn("Can't create OnDemandStatsProducer<BrowserStats> producer with passed id: [" + producerId + "] and default id: [" + getDefaultProducerId() + "].");
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"OnDemandStatsProducer",
"<",
"PageInBrowserStats",
">",
"getProducer",
"(",
"final",
"String",
"producerId",
",",
"final",
"String",
"category",
",",
"final",
"String",
"subsystem",
")",
"{",
"final",
... | Returns producer by given producer id.
If it was not found then new producer will be created.
If existing producer is not supported then producer with default producer id will be returned.
If producer with default producer id is not supported then will be returned {@code null}.
@param producerId id of the producer
@param category name of the category
@param subsystem name of the subsystem
@return PageInBrowserStats producer | [
"Returns",
"producer",
"by",
"given",
"producer",
"id",
".",
"If",
"it",
"was",
"not",
"found",
"then",
"new",
"producer",
"will",
"be",
"created",
".",
"If",
"existing",
"producer",
"is",
"not",
"supported",
"then",
"producer",
"with",
"default",
"producer"... | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-web/src/main/java/net/anotheria/moskito/web/filters/JSTalkBackFilter.java#L165-L186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.