repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/JsMainImpl.java | JsMainImpl.createMessageEngine | private MessagingEngine createMessageEngine(JsMEConfig me) throws Exception {
"""
Create a single Message Engine admin object using suppled config object.
"""
String thisMethodName = CLASS_NAME + ".createMessageEngine(JsMEConfig)";
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, thisMethodName, "replace ME name here");
}
JsMessagingEngine engineImpl = null;
bus = new JsBusImpl(me, this, (me.getSIBus().getName()));// getBusProxy(me);
engineImpl = new JsMessagingEngineImpl(this, bus, me);
MessagingEngine engine = new MessagingEngine(me, engineImpl);
_messagingEngines.put(defaultMEUUID, engine);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.exit(tc, thisMethodName, engine.toString());
}
return engine;
} | java | private MessagingEngine createMessageEngine(JsMEConfig me) throws Exception {
String thisMethodName = CLASS_NAME + ".createMessageEngine(JsMEConfig)";
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, thisMethodName, "replace ME name here");
}
JsMessagingEngine engineImpl = null;
bus = new JsBusImpl(me, this, (me.getSIBus().getName()));// getBusProxy(me);
engineImpl = new JsMessagingEngineImpl(this, bus, me);
MessagingEngine engine = new MessagingEngine(me, engineImpl);
_messagingEngines.put(defaultMEUUID, engine);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.exit(tc, thisMethodName, engine.toString());
}
return engine;
} | [
"private",
"MessagingEngine",
"createMessageEngine",
"(",
"JsMEConfig",
"me",
")",
"throws",
"Exception",
"{",
"String",
"thisMethodName",
"=",
"CLASS_NAME",
"+",
"\".createMessageEngine(JsMEConfig)\"",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"{",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"thisMethodName",
",",
"\"replace ME name here\"",
")",
";",
"}",
"JsMessagingEngine",
"engineImpl",
"=",
"null",
";",
"bus",
"=",
"new",
"JsBusImpl",
"(",
"me",
",",
"this",
",",
"(",
"me",
".",
"getSIBus",
"(",
")",
".",
"getName",
"(",
")",
")",
")",
";",
"// getBusProxy(me);",
"engineImpl",
"=",
"new",
"JsMessagingEngineImpl",
"(",
"this",
",",
"bus",
",",
"me",
")",
";",
"MessagingEngine",
"engine",
"=",
"new",
"MessagingEngine",
"(",
"me",
",",
"engineImpl",
")",
";",
"_messagingEngines",
".",
"put",
"(",
"defaultMEUUID",
",",
"engine",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"{",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"thisMethodName",
",",
"engine",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"engine",
";",
"}"
] | Create a single Message Engine admin object using suppled config object. | [
"Create",
"a",
"single",
"Message",
"Engine",
"admin",
"object",
"using",
"suppled",
"config",
"object",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/JsMainImpl.java#L472-L493 |
sniggle/simple-pgp | simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java | BasePGPCommon.retrievePublicKey | protected PGPPublicKey retrievePublicKey(PGPPublicKeyRing publicKeyRing, KeyFilter<PGPPublicKey> keyFilter) {
"""
reads the PGP public key from a PublicKeyRing
@param publicKeyRing
the source public key ring
@param keyFilter
the filter to apply
@return the matching PGP public or null if none matches
"""
LOGGER.trace("retrievePublicKey(PGPPublicKeyRing, KeyFilter<PGPPublicKey>)");
PGPPublicKey result = null;
Iterator<PGPPublicKey> publicKeyIterator = publicKeyRing.getPublicKeys();
LOGGER.debug("Iterating through public keys in public key ring");
while( result == null && publicKeyIterator.hasNext() ) {
PGPPublicKey key = publicKeyIterator.next();
LOGGER.info("Found secret key: {}", key.getKeyID());
LOGGER.debug("Checking public key with filter");
if( keyFilter.accept(key) ) {
LOGGER.info("Public key {} selected from key ring", key.getKeyID());
result = key;
}
}
return result;
} | java | protected PGPPublicKey retrievePublicKey(PGPPublicKeyRing publicKeyRing, KeyFilter<PGPPublicKey> keyFilter) {
LOGGER.trace("retrievePublicKey(PGPPublicKeyRing, KeyFilter<PGPPublicKey>)");
PGPPublicKey result = null;
Iterator<PGPPublicKey> publicKeyIterator = publicKeyRing.getPublicKeys();
LOGGER.debug("Iterating through public keys in public key ring");
while( result == null && publicKeyIterator.hasNext() ) {
PGPPublicKey key = publicKeyIterator.next();
LOGGER.info("Found secret key: {}", key.getKeyID());
LOGGER.debug("Checking public key with filter");
if( keyFilter.accept(key) ) {
LOGGER.info("Public key {} selected from key ring", key.getKeyID());
result = key;
}
}
return result;
} | [
"protected",
"PGPPublicKey",
"retrievePublicKey",
"(",
"PGPPublicKeyRing",
"publicKeyRing",
",",
"KeyFilter",
"<",
"PGPPublicKey",
">",
"keyFilter",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"retrievePublicKey(PGPPublicKeyRing, KeyFilter<PGPPublicKey>)\"",
")",
";",
"PGPPublicKey",
"result",
"=",
"null",
";",
"Iterator",
"<",
"PGPPublicKey",
">",
"publicKeyIterator",
"=",
"publicKeyRing",
".",
"getPublicKeys",
"(",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Iterating through public keys in public key ring\"",
")",
";",
"while",
"(",
"result",
"==",
"null",
"&&",
"publicKeyIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"PGPPublicKey",
"key",
"=",
"publicKeyIterator",
".",
"next",
"(",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Found secret key: {}\"",
",",
"key",
".",
"getKeyID",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Checking public key with filter\"",
")",
";",
"if",
"(",
"keyFilter",
".",
"accept",
"(",
"key",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Public key {} selected from key ring\"",
",",
"key",
".",
"getKeyID",
"(",
")",
")",
";",
"result",
"=",
"key",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | reads the PGP public key from a PublicKeyRing
@param publicKeyRing
the source public key ring
@param keyFilter
the filter to apply
@return the matching PGP public or null if none matches | [
"reads",
"the",
"PGP",
"public",
"key",
"from",
"a",
"PublicKeyRing"
] | train | https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java#L298-L313 |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java | KnowledgeOperations.setFaults | public static void setFaults(Message message, KnowledgeOperation operation, Map<String, Object> contextOverrides) {
"""
Sets the faults.
@param message the message
@param operation the operation
@param contextOverrides the context overrides
"""
setOutputsOrFaults(message, operation.getFaultExpressionMappings(), contextOverrides, FAULT, false);
} | java | public static void setFaults(Message message, KnowledgeOperation operation, Map<String, Object> contextOverrides) {
setOutputsOrFaults(message, operation.getFaultExpressionMappings(), contextOverrides, FAULT, false);
} | [
"public",
"static",
"void",
"setFaults",
"(",
"Message",
"message",
",",
"KnowledgeOperation",
"operation",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"contextOverrides",
")",
"{",
"setOutputsOrFaults",
"(",
"message",
",",
"operation",
".",
"getFaultExpressionMappings",
"(",
")",
",",
"contextOverrides",
",",
"FAULT",
",",
"false",
")",
";",
"}"
] | Sets the faults.
@param message the message
@param operation the operation
@param contextOverrides the context overrides | [
"Sets",
"the",
"faults",
"."
] | train | https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java#L286-L288 |
brunocvcunha/inutils4j | src/main/java/org/brunocvcunha/inutils4j/MyImageUtils.java | MyImageUtils.resizeToHeight | public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {
"""
Resizes an image to the specified height, changing width in the same proportion
@param originalImage Image in memory
@param heightOut The height to resize
@return New Image in memory
"""
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int heightPercent = (heightOut * 100) / height;
int newWidth = (width * heightPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);
g.dispose();
return resizedImage;
} | java | public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int heightPercent = (heightOut * 100) / height;
int newWidth = (width * heightPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);
g.dispose();
return resizedImage;
} | [
"public",
"static",
"BufferedImage",
"resizeToHeight",
"(",
"BufferedImage",
"originalImage",
",",
"int",
"heightOut",
")",
"{",
"int",
"width",
"=",
"originalImage",
".",
"getWidth",
"(",
")",
";",
"int",
"height",
"=",
"originalImage",
".",
"getHeight",
"(",
")",
";",
"int",
"heightPercent",
"=",
"(",
"heightOut",
"*",
"100",
")",
"/",
"height",
";",
"int",
"newWidth",
"=",
"(",
"width",
"*",
"heightPercent",
")",
"/",
"100",
";",
"BufferedImage",
"resizedImage",
"=",
"new",
"BufferedImage",
"(",
"newWidth",
",",
"heightOut",
",",
"BufferedImage",
".",
"TYPE_INT_ARGB",
")",
";",
"Graphics2D",
"g",
"=",
"resizedImage",
".",
"createGraphics",
"(",
")",
";",
"g",
".",
"drawImage",
"(",
"originalImage",
",",
"0",
",",
"0",
",",
"newWidth",
",",
"heightOut",
",",
"null",
")",
";",
"g",
".",
"dispose",
"(",
")",
";",
"return",
"resizedImage",
";",
"}"
] | Resizes an image to the specified height, changing width in the same proportion
@param originalImage Image in memory
@param heightOut The height to resize
@return New Image in memory | [
"Resizes",
"an",
"image",
"to",
"the",
"specified",
"height",
"changing",
"width",
"in",
"the",
"same",
"proportion"
] | train | https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/MyImageUtils.java#L165-L182 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java | SynchronousRequest.getPvPGameInfo | public List<PvPGame> getPvPGameInfo(String api, String[] ids) throws GuildWars2Exception {
"""
For more info on pvp games API go <a href="https://wiki.guildwars2.com/wiki/API:2/pvp/games">here</a><br/>
Get pvp game info for the given pvp game id(s)
@param api Guild Wars 2 API key
@param ids list of pvp game id(s)
@return list of pvp game info
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see PvPGame pvp game info
"""
isParamValid(new ParamChecker(ParamType.API, api), new ParamChecker(ids));
try {
Response<List<PvPGame>> response = gw2API.getPvPGameInfo(api, processIds(ids)).execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | java | public List<PvPGame> getPvPGameInfo(String api, String[] ids) throws GuildWars2Exception {
isParamValid(new ParamChecker(ParamType.API, api), new ParamChecker(ids));
try {
Response<List<PvPGame>> response = gw2API.getPvPGameInfo(api, processIds(ids)).execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | [
"public",
"List",
"<",
"PvPGame",
">",
"getPvPGameInfo",
"(",
"String",
"api",
",",
"String",
"[",
"]",
"ids",
")",
"throws",
"GuildWars2Exception",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ParamType",
".",
"API",
",",
"api",
")",
",",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"try",
"{",
"Response",
"<",
"List",
"<",
"PvPGame",
">>",
"response",
"=",
"gw2API",
".",
"getPvPGameInfo",
"(",
"api",
",",
"processIds",
"(",
"ids",
")",
")",
".",
"execute",
"(",
")",
";",
"if",
"(",
"!",
"response",
".",
"isSuccessful",
"(",
")",
")",
"throwError",
"(",
"response",
".",
"code",
"(",
")",
",",
"response",
".",
"errorBody",
"(",
")",
")",
";",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"GuildWars2Exception",
"(",
"ErrorCode",
".",
"Network",
",",
"\"Network Error: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | For more info on pvp games API go <a href="https://wiki.guildwars2.com/wiki/API:2/pvp/games">here</a><br/>
Get pvp game info for the given pvp game id(s)
@param api Guild Wars 2 API key
@param ids list of pvp game id(s)
@return list of pvp game info
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see PvPGame pvp game info | [
"For",
"more",
"info",
"on",
"pvp",
"games",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"pvp",
"/",
"games",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Get",
"pvp",
"game",
"info",
"for",
"the",
"given",
"pvp",
"game",
"id",
"(",
"s",
")"
] | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L2772-L2781 |
phoenixnap/springmvc-raml-plugin | src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/data/ApiBodyMetadata.java | ApiBodyMetadata.getCodeModel | public JCodeModel getCodeModel(String basePackage, String schemaLocation, Annotator annotator) {
"""
Builds a JCodeModel for this body
@param basePackage
The package we will be using for the domain objects
@param schemaLocation
The location of this schema, will be used to create absolute
URIs for $ref tags eg "classpath:/"
@param annotator
JsonSchema2Pojo annotator. if null a default annotator will be
used
@return built JCodeModel
"""
if (type != null) {
return codeModel;
} else {
return SchemaHelper.buildBodyJCodeModel(schemaLocation, basePackage, name, schema, annotator);
}
} | java | public JCodeModel getCodeModel(String basePackage, String schemaLocation, Annotator annotator) {
if (type != null) {
return codeModel;
} else {
return SchemaHelper.buildBodyJCodeModel(schemaLocation, basePackage, name, schema, annotator);
}
} | [
"public",
"JCodeModel",
"getCodeModel",
"(",
"String",
"basePackage",
",",
"String",
"schemaLocation",
",",
"Annotator",
"annotator",
")",
"{",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"return",
"codeModel",
";",
"}",
"else",
"{",
"return",
"SchemaHelper",
".",
"buildBodyJCodeModel",
"(",
"schemaLocation",
",",
"basePackage",
",",
"name",
",",
"schema",
",",
"annotator",
")",
";",
"}",
"}"
] | Builds a JCodeModel for this body
@param basePackage
The package we will be using for the domain objects
@param schemaLocation
The location of this schema, will be used to create absolute
URIs for $ref tags eg "classpath:/"
@param annotator
JsonSchema2Pojo annotator. if null a default annotator will be
used
@return built JCodeModel | [
"Builds",
"a",
"JCodeModel",
"for",
"this",
"body"
] | train | https://github.com/phoenixnap/springmvc-raml-plugin/blob/6387072317cd771eb7d6f30943f556ac20dd3c84/src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/data/ApiBodyMetadata.java#L151-L157 |
VoltDB/voltdb | src/frontend/org/voltdb/compiler/VoltCompiler.java | VoltCompiler.getKeyPrefix | String getKeyPrefix(StatementPartitioning partitioning, DeterminismMode detMode, String joinOrder) {
"""
Key prefix includes attributes that make a cached statement usable if they match
For example, if the SQL is the same, but the partitioning isn't, then the statements
aren't actually interchangeable.
"""
// no caching for inferred yet
if (partitioning.isInferred()) {
return null;
}
String joinOrderPrefix = "#";
if (joinOrder != null) {
joinOrderPrefix += joinOrder;
}
boolean partitioned = partitioning.wasSpecifiedAsSingle();
return joinOrderPrefix + String.valueOf(detMode.toChar()) + (partitioned ? "P#" : "R#");
} | java | String getKeyPrefix(StatementPartitioning partitioning, DeterminismMode detMode, String joinOrder) {
// no caching for inferred yet
if (partitioning.isInferred()) {
return null;
}
String joinOrderPrefix = "#";
if (joinOrder != null) {
joinOrderPrefix += joinOrder;
}
boolean partitioned = partitioning.wasSpecifiedAsSingle();
return joinOrderPrefix + String.valueOf(detMode.toChar()) + (partitioned ? "P#" : "R#");
} | [
"String",
"getKeyPrefix",
"(",
"StatementPartitioning",
"partitioning",
",",
"DeterminismMode",
"detMode",
",",
"String",
"joinOrder",
")",
"{",
"// no caching for inferred yet",
"if",
"(",
"partitioning",
".",
"isInferred",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"String",
"joinOrderPrefix",
"=",
"\"#\"",
";",
"if",
"(",
"joinOrder",
"!=",
"null",
")",
"{",
"joinOrderPrefix",
"+=",
"joinOrder",
";",
"}",
"boolean",
"partitioned",
"=",
"partitioning",
".",
"wasSpecifiedAsSingle",
"(",
")",
";",
"return",
"joinOrderPrefix",
"+",
"String",
".",
"valueOf",
"(",
"detMode",
".",
"toChar",
"(",
")",
")",
"+",
"(",
"partitioned",
"?",
"\"P#\"",
":",
"\"R#\"",
")",
";",
"}"
] | Key prefix includes attributes that make a cached statement usable if they match
For example, if the SQL is the same, but the partitioning isn't, then the statements
aren't actually interchangeable. | [
"Key",
"prefix",
"includes",
"attributes",
"that",
"make",
"a",
"cached",
"statement",
"usable",
"if",
"they",
"match"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/VoltCompiler.java#L2266-L2280 |
youngmonkeys/ezyfox-sfs2x | src/main/java/com/tvd12/ezyfox/sfs2x/serializer/ParameterSerializer.java | ParameterSerializer.parseMethod | @SuppressWarnings("rawtypes")
protected void parseMethod(Object value, GetterMethodCover method,
ISFSObject sfsObject) {
"""
Serialize a java object to a SFSObject
@param value value to parse
@param method structure of getter method
@param sfsObject the SFSObject
"""
Object answer = value;
if(method.isColection()) {
answer = parseCollection(method, (Collection)value);
}
else if(method.isTwoDimensionsArray()) {
answer = parseTwoDimensionsArray(method, value);
}
else if(method.isArray()) {
answer = parseArray(method, value);
}
else if(method.isObject()) {
answer = parseObject(method, value);
}
else if(method.isChar()) {
answer = (byte)(((Character)value).charValue());
}
SFSDataType type = getSFSDataType(method);
sfsObject.put(method.getKey(), new SFSDataWrapper(type, answer));
} | java | @SuppressWarnings("rawtypes")
protected void parseMethod(Object value, GetterMethodCover method,
ISFSObject sfsObject) {
Object answer = value;
if(method.isColection()) {
answer = parseCollection(method, (Collection)value);
}
else if(method.isTwoDimensionsArray()) {
answer = parseTwoDimensionsArray(method, value);
}
else if(method.isArray()) {
answer = parseArray(method, value);
}
else if(method.isObject()) {
answer = parseObject(method, value);
}
else if(method.isChar()) {
answer = (byte)(((Character)value).charValue());
}
SFSDataType type = getSFSDataType(method);
sfsObject.put(method.getKey(), new SFSDataWrapper(type, answer));
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"protected",
"void",
"parseMethod",
"(",
"Object",
"value",
",",
"GetterMethodCover",
"method",
",",
"ISFSObject",
"sfsObject",
")",
"{",
"Object",
"answer",
"=",
"value",
";",
"if",
"(",
"method",
".",
"isColection",
"(",
")",
")",
"{",
"answer",
"=",
"parseCollection",
"(",
"method",
",",
"(",
"Collection",
")",
"value",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"isTwoDimensionsArray",
"(",
")",
")",
"{",
"answer",
"=",
"parseTwoDimensionsArray",
"(",
"method",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"isArray",
"(",
")",
")",
"{",
"answer",
"=",
"parseArray",
"(",
"method",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"isObject",
"(",
")",
")",
"{",
"answer",
"=",
"parseObject",
"(",
"method",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"isChar",
"(",
")",
")",
"{",
"answer",
"=",
"(",
"byte",
")",
"(",
"(",
"(",
"Character",
")",
"value",
")",
".",
"charValue",
"(",
")",
")",
";",
"}",
"SFSDataType",
"type",
"=",
"getSFSDataType",
"(",
"method",
")",
";",
"sfsObject",
".",
"put",
"(",
"method",
".",
"getKey",
"(",
")",
",",
"new",
"SFSDataWrapper",
"(",
"type",
",",
"answer",
")",
")",
";",
"}"
] | Serialize a java object to a SFSObject
@param value value to parse
@param method structure of getter method
@param sfsObject the SFSObject | [
"Serialize",
"a",
"java",
"object",
"to",
"a",
"SFSObject"
] | train | https://github.com/youngmonkeys/ezyfox-sfs2x/blob/7e004033a3b551c3ae970a0c8f45db7b1ec144de/src/main/java/com/tvd12/ezyfox/sfs2x/serializer/ParameterSerializer.java#L93-L114 |
Talend/tesb-rt-se | sam/sam-agent/src/main/java/org/talend/esb/sam/agent/lifecycle/AbstractListenerImpl.java | AbstractListenerImpl.processStart | protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {
"""
Process start.
@param endpoint the endpoint
@param eventType the event type
"""
if (!sendLifecycleEvent) {
return;
}
Event event = createEvent(endpoint, eventType);
queue.add(event);
} | java | protected void processStart(Endpoint endpoint, EventTypeEnum eventType) {
if (!sendLifecycleEvent) {
return;
}
Event event = createEvent(endpoint, eventType);
queue.add(event);
} | [
"protected",
"void",
"processStart",
"(",
"Endpoint",
"endpoint",
",",
"EventTypeEnum",
"eventType",
")",
"{",
"if",
"(",
"!",
"sendLifecycleEvent",
")",
"{",
"return",
";",
"}",
"Event",
"event",
"=",
"createEvent",
"(",
"endpoint",
",",
"eventType",
")",
";",
"queue",
".",
"add",
"(",
"event",
")",
";",
"}"
] | Process start.
@param endpoint the endpoint
@param eventType the event type | [
"Process",
"start",
"."
] | train | https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/sam/sam-agent/src/main/java/org/talend/esb/sam/agent/lifecycle/AbstractListenerImpl.java#L92-L99 |
datastax/java-driver | query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/QueryBuilder.java | QueryBuilder.typeHint | @NonNull
public static Term typeHint(@NonNull Term term, @NonNull DataType targetType) {
"""
Provides a type hint for an expression, as in {@code WHERE k = (double)1/3}.
<p>To create the data type, use the constants and static methods in {@link DataTypes}, or
{@link #udt(CqlIdentifier)}.
"""
return new TypeHintTerm(term, targetType);
} | java | @NonNull
public static Term typeHint(@NonNull Term term, @NonNull DataType targetType) {
return new TypeHintTerm(term, targetType);
} | [
"@",
"NonNull",
"public",
"static",
"Term",
"typeHint",
"(",
"@",
"NonNull",
"Term",
"term",
",",
"@",
"NonNull",
"DataType",
"targetType",
")",
"{",
"return",
"new",
"TypeHintTerm",
"(",
"term",
",",
"targetType",
")",
";",
"}"
] | Provides a type hint for an expression, as in {@code WHERE k = (double)1/3}.
<p>To create the data type, use the constants and static methods in {@link DataTypes}, or
{@link #udt(CqlIdentifier)}. | [
"Provides",
"a",
"type",
"hint",
"for",
"an",
"expression",
"as",
"in",
"{",
"@code",
"WHERE",
"k",
"=",
"(",
"double",
")",
"1",
"/",
"3",
"}",
"."
] | train | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/QueryBuilder.java#L307-L310 |
GoogleCloudPlatform/appengine-plugins-core | src/main/java/com/google/cloud/tools/managedcloudsdk/install/ExtractorFactory.java | ExtractorFactory.newExtractor | public Extractor newExtractor(Path archive, Path destination, ProgressListener progressListener)
throws UnknownArchiveTypeException {
"""
Creates a new extractor based on filetype. Filetype determination is based on the filename
string, this method makes no attempt to validate the file contents to verify they are the type
defined by the file extension.
@param archive the archive to extract
@param destination the destination folder for extracted files
@param progressListener a listener for progress
@return {@link Extractor} with {@link TarGzExtractorProvider} for ".tar.gz", {@link
ZipExtractorProvider} for ".zip"
@throws UnknownArchiveTypeException if not ".tar.gz" or ".zip"
"""
if (archive.toString().toLowerCase().endsWith(".tar.gz")) {
return new Extractor(archive, destination, new TarGzExtractorProvider(), progressListener);
}
if (archive.toString().toLowerCase().endsWith(".zip")) {
return new Extractor(archive, destination, new ZipExtractorProvider(), progressListener);
}
throw new UnknownArchiveTypeException(archive);
} | java | public Extractor newExtractor(Path archive, Path destination, ProgressListener progressListener)
throws UnknownArchiveTypeException {
if (archive.toString().toLowerCase().endsWith(".tar.gz")) {
return new Extractor(archive, destination, new TarGzExtractorProvider(), progressListener);
}
if (archive.toString().toLowerCase().endsWith(".zip")) {
return new Extractor(archive, destination, new ZipExtractorProvider(), progressListener);
}
throw new UnknownArchiveTypeException(archive);
} | [
"public",
"Extractor",
"newExtractor",
"(",
"Path",
"archive",
",",
"Path",
"destination",
",",
"ProgressListener",
"progressListener",
")",
"throws",
"UnknownArchiveTypeException",
"{",
"if",
"(",
"archive",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"endsWith",
"(",
"\".tar.gz\"",
")",
")",
"{",
"return",
"new",
"Extractor",
"(",
"archive",
",",
"destination",
",",
"new",
"TarGzExtractorProvider",
"(",
")",
",",
"progressListener",
")",
";",
"}",
"if",
"(",
"archive",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"endsWith",
"(",
"\".zip\"",
")",
")",
"{",
"return",
"new",
"Extractor",
"(",
"archive",
",",
"destination",
",",
"new",
"ZipExtractorProvider",
"(",
")",
",",
"progressListener",
")",
";",
"}",
"throw",
"new",
"UnknownArchiveTypeException",
"(",
"archive",
")",
";",
"}"
] | Creates a new extractor based on filetype. Filetype determination is based on the filename
string, this method makes no attempt to validate the file contents to verify they are the type
defined by the file extension.
@param archive the archive to extract
@param destination the destination folder for extracted files
@param progressListener a listener for progress
@return {@link Extractor} with {@link TarGzExtractorProvider} for ".tar.gz", {@link
ZipExtractorProvider} for ".zip"
@throws UnknownArchiveTypeException if not ".tar.gz" or ".zip" | [
"Creates",
"a",
"new",
"extractor",
"based",
"on",
"filetype",
".",
"Filetype",
"determination",
"is",
"based",
"on",
"the",
"filename",
"string",
"this",
"method",
"makes",
"no",
"attempt",
"to",
"validate",
"the",
"file",
"contents",
"to",
"verify",
"they",
"are",
"the",
"type",
"defined",
"by",
"the",
"file",
"extension",
"."
] | train | https://github.com/GoogleCloudPlatform/appengine-plugins-core/blob/d22e9fa1103522409ab6fdfbf68c4a5a0bc5b97d/src/main/java/com/google/cloud/tools/managedcloudsdk/install/ExtractorFactory.java#L37-L47 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/config/ConfigValueHelper.java | ConfigValueHelper.checkPositiveInteger | protected static void checkPositiveInteger(String configKey, int configValue) throws SofaRpcRuntimeException {
"""
检查数字是否为正整数(>0)
@param configKey 配置项
@param configValue 配置值
@throws SofaRpcRuntimeException 非法异常
"""
if (configValue <= 0) {
throw ExceptionUtils.buildRuntime(configKey, configValue + "", "must > 0");
}
} | java | protected static void checkPositiveInteger(String configKey, int configValue) throws SofaRpcRuntimeException {
if (configValue <= 0) {
throw ExceptionUtils.buildRuntime(configKey, configValue + "", "must > 0");
}
} | [
"protected",
"static",
"void",
"checkPositiveInteger",
"(",
"String",
"configKey",
",",
"int",
"configValue",
")",
"throws",
"SofaRpcRuntimeException",
"{",
"if",
"(",
"configValue",
"<=",
"0",
")",
"{",
"throw",
"ExceptionUtils",
".",
"buildRuntime",
"(",
"configKey",
",",
"configValue",
"+",
"\"\"",
",",
"\"must > 0\"",
")",
";",
"}",
"}"
] | 检查数字是否为正整数(>0)
@param configKey 配置项
@param configValue 配置值
@throws SofaRpcRuntimeException 非法异常 | [
"检查数字是否为正整数(",
">",
"0",
")"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/config/ConfigValueHelper.java#L158-L162 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfSignatureAppearance.java | PdfSignatureAppearance.setCrypto | public void setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) {
"""
Sets the cryptographic parameters.
@param privKey the private key
@param certChain the certificate chain
@param crlList the certificate revocation list. It may be <CODE>null</CODE>
@param filter the crytographic filter type. It can be SELF_SIGNED, VERISIGN_SIGNED or WINCER_SIGNED
"""
this.privKey = privKey;
this.certChain = certChain;
this.crlList = crlList;
this.filter = filter;
} | java | public void setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) {
this.privKey = privKey;
this.certChain = certChain;
this.crlList = crlList;
this.filter = filter;
} | [
"public",
"void",
"setCrypto",
"(",
"PrivateKey",
"privKey",
",",
"Certificate",
"[",
"]",
"certChain",
",",
"CRL",
"[",
"]",
"crlList",
",",
"PdfName",
"filter",
")",
"{",
"this",
".",
"privKey",
"=",
"privKey",
";",
"this",
".",
"certChain",
"=",
"certChain",
";",
"this",
".",
"crlList",
"=",
"crlList",
";",
"this",
".",
"filter",
"=",
"filter",
";",
"}"
] | Sets the cryptographic parameters.
@param privKey the private key
@param certChain the certificate chain
@param crlList the certificate revocation list. It may be <CODE>null</CODE>
@param filter the crytographic filter type. It can be SELF_SIGNED, VERISIGN_SIGNED or WINCER_SIGNED | [
"Sets",
"the",
"cryptographic",
"parameters",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfSignatureAppearance.java#L254-L259 |
jblas-project/jblas | src/main/java/org/jblas/Singular.java | Singular.SVDValues | public static FloatMatrix SVDValues(FloatMatrix A) {
"""
Compute the singular values of a matrix.
@param A FloatMatrix of dimension m * n
@return A min(m, n) vector of singular values.
"""
int m = A.rows;
int n = A.columns;
FloatMatrix S = new FloatMatrix(min(m, n));
int info = NativeBlas.sgesvd('N', 'N', m, n, A.dup().data, 0, m, S.data, 0, null, 0, 1, null, 0, 1);
if (info > 0) {
throw new LapackConvergenceException("GESVD", info + " superdiagonals of an intermediate bidiagonal form failed to converge.");
}
return S;
} | java | public static FloatMatrix SVDValues(FloatMatrix A) {
int m = A.rows;
int n = A.columns;
FloatMatrix S = new FloatMatrix(min(m, n));
int info = NativeBlas.sgesvd('N', 'N', m, n, A.dup().data, 0, m, S.data, 0, null, 0, 1, null, 0, 1);
if (info > 0) {
throw new LapackConvergenceException("GESVD", info + " superdiagonals of an intermediate bidiagonal form failed to converge.");
}
return S;
} | [
"public",
"static",
"FloatMatrix",
"SVDValues",
"(",
"FloatMatrix",
"A",
")",
"{",
"int",
"m",
"=",
"A",
".",
"rows",
";",
"int",
"n",
"=",
"A",
".",
"columns",
";",
"FloatMatrix",
"S",
"=",
"new",
"FloatMatrix",
"(",
"min",
"(",
"m",
",",
"n",
")",
")",
";",
"int",
"info",
"=",
"NativeBlas",
".",
"sgesvd",
"(",
"'",
"'",
",",
"'",
"'",
",",
"m",
",",
"n",
",",
"A",
".",
"dup",
"(",
")",
".",
"data",
",",
"0",
",",
"m",
",",
"S",
".",
"data",
",",
"0",
",",
"null",
",",
"0",
",",
"1",
",",
"null",
",",
"0",
",",
"1",
")",
";",
"if",
"(",
"info",
">",
"0",
")",
"{",
"throw",
"new",
"LapackConvergenceException",
"(",
"\"GESVD\"",
",",
"info",
"+",
"\" superdiagonals of an intermediate bidiagonal form failed to converge.\"",
")",
";",
"}",
"return",
"S",
";",
"}"
] | Compute the singular values of a matrix.
@param A FloatMatrix of dimension m * n
@return A min(m, n) vector of singular values. | [
"Compute",
"the",
"singular",
"values",
"of",
"a",
"matrix",
"."
] | train | https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Singular.java#L263-L275 |
EdwardRaff/JSAT | JSAT/src/jsat/io/JSATData.java | JSATData.writeData | public static <Type extends DataSet<Type>> void writeData(DataSet<Type> dataset, OutputStream outRaw, FloatStorageMethod fpStore) throws IOException {
"""
This method writes out a JSAT dataset to a binary format that can be read
in again later, and could be read in other languages.<br>
<br>
The format that is used will understand both
{@link ClassificationDataSet} and {@link RegressionDataSet} datasets as
special cases, and will store the target values in the binary file. When
read back in, they can be returned as their original dataset type, or
treated as normal fields as a {@link SimpleDataSet}.
@param <Type>
@param dataset the dataset to write out to a binary file
@param outRaw the raw output stream, the caller should provide a buffered
stream.
@param fpStore the storage method of storing floating point values, which
may result in a loss of precision depending on the method chosen.
@throws IOException
"""
fpStore = FloatStorageMethod.getMethod(dataset, fpStore);
DataWriter.DataSetType type;
CategoricalData predicting;
if(dataset instanceof ClassificationDataSet)
{
type = DataWriter.DataSetType.CLASSIFICATION;
predicting = ((ClassificationDataSet)dataset).getPredicting();
}
else if(dataset instanceof RegressionDataSet)
{
type = DataWriter.DataSetType.REGRESSION;
predicting = null;
}
else
{
type = DataWriter.DataSetType.SIMPLE;
predicting = null;
}
DataWriter dw = getWriter(outRaw, dataset.getCategories(), dataset.getNumNumericalVars(), predicting, fpStore, type);
//write out all the datapoints
for(int i = 0; i < dataset.size(); i++)
{
double label = 0;
if (dataset instanceof ClassificationDataSet)
label = ((ClassificationDataSet) dataset).getDataPointCategory(i);
else if (dataset instanceof RegressionDataSet)
label = ((RegressionDataSet) dataset).getTargetValue(i);
dw.writePoint(dataset.getWeight(i), dataset.getDataPoint(i), label);
}
dw.finish();
outRaw.flush();
} | java | public static <Type extends DataSet<Type>> void writeData(DataSet<Type> dataset, OutputStream outRaw, FloatStorageMethod fpStore) throws IOException
{
fpStore = FloatStorageMethod.getMethod(dataset, fpStore);
DataWriter.DataSetType type;
CategoricalData predicting;
if(dataset instanceof ClassificationDataSet)
{
type = DataWriter.DataSetType.CLASSIFICATION;
predicting = ((ClassificationDataSet)dataset).getPredicting();
}
else if(dataset instanceof RegressionDataSet)
{
type = DataWriter.DataSetType.REGRESSION;
predicting = null;
}
else
{
type = DataWriter.DataSetType.SIMPLE;
predicting = null;
}
DataWriter dw = getWriter(outRaw, dataset.getCategories(), dataset.getNumNumericalVars(), predicting, fpStore, type);
//write out all the datapoints
for(int i = 0; i < dataset.size(); i++)
{
double label = 0;
if (dataset instanceof ClassificationDataSet)
label = ((ClassificationDataSet) dataset).getDataPointCategory(i);
else if (dataset instanceof RegressionDataSet)
label = ((RegressionDataSet) dataset).getTargetValue(i);
dw.writePoint(dataset.getWeight(i), dataset.getDataPoint(i), label);
}
dw.finish();
outRaw.flush();
} | [
"public",
"static",
"<",
"Type",
"extends",
"DataSet",
"<",
"Type",
">",
">",
"void",
"writeData",
"(",
"DataSet",
"<",
"Type",
">",
"dataset",
",",
"OutputStream",
"outRaw",
",",
"FloatStorageMethod",
"fpStore",
")",
"throws",
"IOException",
"{",
"fpStore",
"=",
"FloatStorageMethod",
".",
"getMethod",
"(",
"dataset",
",",
"fpStore",
")",
";",
"DataWriter",
".",
"DataSetType",
"type",
";",
"CategoricalData",
"predicting",
";",
"if",
"(",
"dataset",
"instanceof",
"ClassificationDataSet",
")",
"{",
"type",
"=",
"DataWriter",
".",
"DataSetType",
".",
"CLASSIFICATION",
";",
"predicting",
"=",
"(",
"(",
"ClassificationDataSet",
")",
"dataset",
")",
".",
"getPredicting",
"(",
")",
";",
"}",
"else",
"if",
"(",
"dataset",
"instanceof",
"RegressionDataSet",
")",
"{",
"type",
"=",
"DataWriter",
".",
"DataSetType",
".",
"REGRESSION",
";",
"predicting",
"=",
"null",
";",
"}",
"else",
"{",
"type",
"=",
"DataWriter",
".",
"DataSetType",
".",
"SIMPLE",
";",
"predicting",
"=",
"null",
";",
"}",
"DataWriter",
"dw",
"=",
"getWriter",
"(",
"outRaw",
",",
"dataset",
".",
"getCategories",
"(",
")",
",",
"dataset",
".",
"getNumNumericalVars",
"(",
")",
",",
"predicting",
",",
"fpStore",
",",
"type",
")",
";",
"//write out all the datapoints",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"dataset",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"double",
"label",
"=",
"0",
";",
"if",
"(",
"dataset",
"instanceof",
"ClassificationDataSet",
")",
"label",
"=",
"(",
"(",
"ClassificationDataSet",
")",
"dataset",
")",
".",
"getDataPointCategory",
"(",
"i",
")",
";",
"else",
"if",
"(",
"dataset",
"instanceof",
"RegressionDataSet",
")",
"label",
"=",
"(",
"(",
"RegressionDataSet",
")",
"dataset",
")",
".",
"getTargetValue",
"(",
"i",
")",
";",
"dw",
".",
"writePoint",
"(",
"dataset",
".",
"getWeight",
"(",
"i",
")",
",",
"dataset",
".",
"getDataPoint",
"(",
"i",
")",
",",
"label",
")",
";",
"}",
"dw",
".",
"finish",
"(",
")",
";",
"outRaw",
".",
"flush",
"(",
")",
";",
"}"
] | This method writes out a JSAT dataset to a binary format that can be read
in again later, and could be read in other languages.<br>
<br>
The format that is used will understand both
{@link ClassificationDataSet} and {@link RegressionDataSet} datasets as
special cases, and will store the target values in the binary file. When
read back in, they can be returned as their original dataset type, or
treated as normal fields as a {@link SimpleDataSet}.
@param <Type>
@param dataset the dataset to write out to a binary file
@param outRaw the raw output stream, the caller should provide a buffered
stream.
@param fpStore the storage method of storing floating point values, which
may result in a loss of precision depending on the method chosen.
@throws IOException | [
"This",
"method",
"writes",
"out",
"a",
"JSAT",
"dataset",
"to",
"a",
"binary",
"format",
"that",
"can",
"be",
"read",
"in",
"again",
"later",
"and",
"could",
"be",
"read",
"in",
"other",
"languages",
".",
"<br",
">",
"<br",
">",
"The",
"format",
"that",
"is",
"used",
"will",
"understand",
"both",
"{",
"@link",
"ClassificationDataSet",
"}",
"and",
"{",
"@link",
"RegressionDataSet",
"}",
"datasets",
"as",
"special",
"cases",
"and",
"will",
"store",
"the",
"target",
"values",
"in",
"the",
"binary",
"file",
".",
"When",
"read",
"back",
"in",
"they",
"can",
"be",
"returned",
"as",
"their",
"original",
"dataset",
"type",
"or",
"treated",
"as",
"normal",
"fields",
"as",
"a",
"{",
"@link",
"SimpleDataSet",
"}",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/io/JSATData.java#L320-L357 |
uber/NullAway | nullaway/src/main/java/com/uber/nullaway/dataflow/DataFlow.java | DataFlow.expressionDataflow | @Nullable
public <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
A expressionDataflow(TreePath exprPath, Context context, T transfer) {
"""
Run the {@code transfer} dataflow analysis to compute the abstract value of the expression
which is the leaf of {@code exprPath}.
@param exprPath expression
@param context Javac context
@param transfer transfer functions
@param <A> values in abstraction
@param <S> store type
@param <T> transfer function type
@return dataflow value for expression
"""
AnalysisResult<A, S> analysisResult = resultForExpr(exprPath, context, transfer);
return analysisResult == null ? null : analysisResult.getValue(exprPath.getLeaf());
} | java | @Nullable
public <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
A expressionDataflow(TreePath exprPath, Context context, T transfer) {
AnalysisResult<A, S> analysisResult = resultForExpr(exprPath, context, transfer);
return analysisResult == null ? null : analysisResult.getValue(exprPath.getLeaf());
} | [
"@",
"Nullable",
"public",
"<",
"A",
"extends",
"AbstractValue",
"<",
"A",
">",
",",
"S",
"extends",
"Store",
"<",
"S",
">",
",",
"T",
"extends",
"TransferFunction",
"<",
"A",
",",
"S",
">",
">",
"A",
"expressionDataflow",
"(",
"TreePath",
"exprPath",
",",
"Context",
"context",
",",
"T",
"transfer",
")",
"{",
"AnalysisResult",
"<",
"A",
",",
"S",
">",
"analysisResult",
"=",
"resultForExpr",
"(",
"exprPath",
",",
"context",
",",
"transfer",
")",
";",
"return",
"analysisResult",
"==",
"null",
"?",
"null",
":",
"analysisResult",
".",
"getValue",
"(",
"exprPath",
".",
"getLeaf",
"(",
")",
")",
";",
"}"
] | Run the {@code transfer} dataflow analysis to compute the abstract value of the expression
which is the leaf of {@code exprPath}.
@param exprPath expression
@param context Javac context
@param transfer transfer functions
@param <A> values in abstraction
@param <S> store type
@param <T> transfer function type
@return dataflow value for expression | [
"Run",
"the",
"{",
"@code",
"transfer",
"}",
"dataflow",
"analysis",
"to",
"compute",
"the",
"abstract",
"value",
"of",
"the",
"expression",
"which",
"is",
"the",
"leaf",
"of",
"{",
"@code",
"exprPath",
"}",
"."
] | train | https://github.com/uber/NullAway/blob/c3979b4241f80411dbba6aac3ff653acbb88d00b/nullaway/src/main/java/com/uber/nullaway/dataflow/DataFlow.java#L170-L175 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.cut | public static void cut(ImageInputStream srcStream, ImageOutputStream destStream, Rectangle rectangle) {
"""
图像切割(按指定起点坐标和宽高切割),此方法并不关闭流
@param srcStream 源图像流
@param destStream 切片后的图像输出流
@param rectangle 矩形对象,表示矩形区域的x,y,width,height
@since 3.1.0
"""
cut(read(srcStream), destStream, rectangle);
} | java | public static void cut(ImageInputStream srcStream, ImageOutputStream destStream, Rectangle rectangle) {
cut(read(srcStream), destStream, rectangle);
} | [
"public",
"static",
"void",
"cut",
"(",
"ImageInputStream",
"srcStream",
",",
"ImageOutputStream",
"destStream",
",",
"Rectangle",
"rectangle",
")",
"{",
"cut",
"(",
"read",
"(",
"srcStream",
")",
",",
"destStream",
",",
"rectangle",
")",
";",
"}"
] | 图像切割(按指定起点坐标和宽高切割),此方法并不关闭流
@param srcStream 源图像流
@param destStream 切片后的图像输出流
@param rectangle 矩形对象,表示矩形区域的x,y,width,height
@since 3.1.0 | [
"图像切割",
"(",
"按指定起点坐标和宽高切割",
")",
",此方法并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L280-L282 |
LAW-Unimi/BUbiNG | src/it/unimi/di/law/bubing/frontier/WorkbenchVirtualizer.java | WorkbenchVirtualizer.dequeuePathQueries | public int dequeuePathQueries(final VisitState visitState, final int maxUrls) throws IOException {
"""
Dequeues at most the given number of path+queries into the given visit state.
<p>Note that the path+queries are directly enqueued into the visit state using
{@link VisitState#enqueuePathQuery(byte[])}.
@param visitState the visitState in which path+queries will be moved.
@param maxUrls the maximum number of path+queries to move.
@return the number of actually dequeued path+queries.
@throws IOException
"""
if (maxUrls == 0) return 0;
final int dequeued = (int)Math.min(maxUrls, byteArrayDiskQueues.count(visitState));
for(int i = dequeued; i-- != 0;) visitState.enqueuePathQuery(byteArrayDiskQueues.dequeue(visitState));
return dequeued;
} | java | public int dequeuePathQueries(final VisitState visitState, final int maxUrls) throws IOException {
if (maxUrls == 0) return 0;
final int dequeued = (int)Math.min(maxUrls, byteArrayDiskQueues.count(visitState));
for(int i = dequeued; i-- != 0;) visitState.enqueuePathQuery(byteArrayDiskQueues.dequeue(visitState));
return dequeued;
} | [
"public",
"int",
"dequeuePathQueries",
"(",
"final",
"VisitState",
"visitState",
",",
"final",
"int",
"maxUrls",
")",
"throws",
"IOException",
"{",
"if",
"(",
"maxUrls",
"==",
"0",
")",
"return",
"0",
";",
"final",
"int",
"dequeued",
"=",
"(",
"int",
")",
"Math",
".",
"min",
"(",
"maxUrls",
",",
"byteArrayDiskQueues",
".",
"count",
"(",
"visitState",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"dequeued",
";",
"i",
"--",
"!=",
"0",
";",
")",
"visitState",
".",
"enqueuePathQuery",
"(",
"byteArrayDiskQueues",
".",
"dequeue",
"(",
"visitState",
")",
")",
";",
"return",
"dequeued",
";",
"}"
] | Dequeues at most the given number of path+queries into the given visit state.
<p>Note that the path+queries are directly enqueued into the visit state using
{@link VisitState#enqueuePathQuery(byte[])}.
@param visitState the visitState in which path+queries will be moved.
@param maxUrls the maximum number of path+queries to move.
@return the number of actually dequeued path+queries.
@throws IOException | [
"Dequeues",
"at",
"most",
"the",
"given",
"number",
"of",
"path",
"+",
"queries",
"into",
"the",
"given",
"visit",
"state",
"."
] | train | https://github.com/LAW-Unimi/BUbiNG/blob/e148acc90031a4f3967422705a9fb07ddaf155e4/src/it/unimi/di/law/bubing/frontier/WorkbenchVirtualizer.java#L87-L92 |
gosu-lang/gosu-lang | gosu-core-api/src/main/java/gw/lang/parser/PostCompilationAnalysis.java | PostCompilationAnalysis.maybeAnalyze | public static void maybeAnalyze( IParsedElement pe, IParsedElement... other ) {
"""
Perform post compilation analysis on the given ParsedElement. The other ParsedElements are supporting ones,
e.g. ClassStatements for inner classes
"""
if( !shouldAnalyze() )
{
return;
}
if( !(pe instanceof IProgram) &&
(!(pe instanceof IClassFileStatement) ||
classFileIsNotAnInterface( (IClassFileStatement)pe )) )
{
// pe.performUnusedElementAnalysis( other );
}
} | java | public static void maybeAnalyze( IParsedElement pe, IParsedElement... other )
{
if( !shouldAnalyze() )
{
return;
}
if( !(pe instanceof IProgram) &&
(!(pe instanceof IClassFileStatement) ||
classFileIsNotAnInterface( (IClassFileStatement)pe )) )
{
// pe.performUnusedElementAnalysis( other );
}
} | [
"public",
"static",
"void",
"maybeAnalyze",
"(",
"IParsedElement",
"pe",
",",
"IParsedElement",
"...",
"other",
")",
"{",
"if",
"(",
"!",
"shouldAnalyze",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"pe",
"instanceof",
"IProgram",
")",
"&&",
"(",
"!",
"(",
"pe",
"instanceof",
"IClassFileStatement",
")",
"||",
"classFileIsNotAnInterface",
"(",
"(",
"IClassFileStatement",
")",
"pe",
")",
")",
")",
"{",
"// pe.performUnusedElementAnalysis( other );",
"}",
"}"
] | Perform post compilation analysis on the given ParsedElement. The other ParsedElements are supporting ones,
e.g. ClassStatements for inner classes | [
"Perform",
"post",
"compilation",
"analysis",
"on",
"the",
"given",
"ParsedElement",
".",
"The",
"other",
"ParsedElements",
"are",
"supporting",
"ones",
"e",
".",
"g",
".",
"ClassStatements",
"for",
"inner",
"classes"
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/lang/parser/PostCompilationAnalysis.java#L34-L47 |
netty/netty | example/src/main/java/io/netty/example/http2/helloworld/client/Http2SettingsHandler.java | Http2SettingsHandler.awaitSettings | public void awaitSettings(long timeout, TimeUnit unit) throws Exception {
"""
Wait for this handler to be added after the upgrade to HTTP/2, and for initial preface
handshake to complete.
@param timeout Time to wait
@param unit {@link java.util.concurrent.TimeUnit} for {@code timeout}
@throws Exception if timeout or other failure occurs
"""
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for settings");
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
} | java | public void awaitSettings(long timeout, TimeUnit unit) throws Exception {
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for settings");
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
} | [
"public",
"void",
"awaitSettings",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"promise",
".",
"awaitUninterruptibly",
"(",
"timeout",
",",
"unit",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Timed out waiting for settings\"",
")",
";",
"}",
"if",
"(",
"!",
"promise",
".",
"isSuccess",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"promise",
".",
"cause",
"(",
")",
")",
";",
"}",
"}"
] | Wait for this handler to be added after the upgrade to HTTP/2, and for initial preface
handshake to complete.
@param timeout Time to wait
@param unit {@link java.util.concurrent.TimeUnit} for {@code timeout}
@throws Exception if timeout or other failure occurs | [
"Wait",
"for",
"this",
"handler",
"to",
"be",
"added",
"after",
"the",
"upgrade",
"to",
"HTTP",
"/",
"2",
"and",
"for",
"initial",
"preface",
"handshake",
"to",
"complete",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http2/helloworld/client/Http2SettingsHandler.java#L47-L54 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/ZealotKhala.java | ZealotKhala.doIn | private ZealotKhala doIn(String prefix, String field, Object[] values, boolean match, boolean positive) {
"""
执行生成in范围查询SQL片段的方法.
@param prefix 前缀
@param field 数据库字段
@param values 数组的值
@param match 是否匹配
@param positive true则表示是in,否则是not in
@return ZealotKhala实例的当前实例
"""
return this.doInByType(prefix, field, values, match, ZealotConst.OBJTYPE_ARRAY, positive);
} | java | private ZealotKhala doIn(String prefix, String field, Object[] values, boolean match, boolean positive) {
return this.doInByType(prefix, field, values, match, ZealotConst.OBJTYPE_ARRAY, positive);
} | [
"private",
"ZealotKhala",
"doIn",
"(",
"String",
"prefix",
",",
"String",
"field",
",",
"Object",
"[",
"]",
"values",
",",
"boolean",
"match",
",",
"boolean",
"positive",
")",
"{",
"return",
"this",
".",
"doInByType",
"(",
"prefix",
",",
"field",
",",
"values",
",",
"match",
",",
"ZealotConst",
".",
"OBJTYPE_ARRAY",
",",
"positive",
")",
";",
"}"
] | 执行生成in范围查询SQL片段的方法.
@param prefix 前缀
@param field 数据库字段
@param values 数组的值
@param match 是否匹配
@param positive true则表示是in,否则是not in
@return ZealotKhala实例的当前实例 | [
"执行生成in范围查询SQL片段的方法",
"."
] | train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L480-L482 |
huahin/huahin-core | src/main/java/org/huahinframework/core/Runner.java | Runner.addJob | public void addJob(String name, Class<? extends SimpleJobTool> clazz) {
"""
Add job sequence.
@param name job sequence name
@param clazz SimpleJobTool class
"""
jobMap.put(name, clazz);
} | java | public void addJob(String name, Class<? extends SimpleJobTool> clazz) {
jobMap.put(name, clazz);
} | [
"public",
"void",
"addJob",
"(",
"String",
"name",
",",
"Class",
"<",
"?",
"extends",
"SimpleJobTool",
">",
"clazz",
")",
"{",
"jobMap",
".",
"put",
"(",
"name",
",",
"clazz",
")",
";",
"}"
] | Add job sequence.
@param name job sequence name
@param clazz SimpleJobTool class | [
"Add",
"job",
"sequence",
"."
] | train | https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/Runner.java#L86-L88 |
VoltDB/voltdb | src/frontend/org/voltdb/iv2/Site.java | Site.handleUndoLog | private static void handleUndoLog(List<UndoAction> undoLog, boolean undo) {
"""
Java level related stuffs that are also needed to roll back
@param undoLog
@param undo
"""
if (undoLog == null) {
return;
}
if (undo) {
undoLog = Lists.reverse(undoLog);
}
for (UndoAction action : undoLog) {
if (undo) {
action.undo();
} else {
action.release();
}
}
if (undo) {
undoLog.clear();
}
} | java | private static void handleUndoLog(List<UndoAction> undoLog, boolean undo) {
if (undoLog == null) {
return;
}
if (undo) {
undoLog = Lists.reverse(undoLog);
}
for (UndoAction action : undoLog) {
if (undo) {
action.undo();
} else {
action.release();
}
}
if (undo) {
undoLog.clear();
}
} | [
"private",
"static",
"void",
"handleUndoLog",
"(",
"List",
"<",
"UndoAction",
">",
"undoLog",
",",
"boolean",
"undo",
")",
"{",
"if",
"(",
"undoLog",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"undo",
")",
"{",
"undoLog",
"=",
"Lists",
".",
"reverse",
"(",
"undoLog",
")",
";",
"}",
"for",
"(",
"UndoAction",
"action",
":",
"undoLog",
")",
"{",
"if",
"(",
"undo",
")",
"{",
"action",
".",
"undo",
"(",
")",
";",
"}",
"else",
"{",
"action",
".",
"release",
"(",
")",
";",
"}",
"}",
"if",
"(",
"undo",
")",
"{",
"undoLog",
".",
"clear",
"(",
")",
";",
"}",
"}"
] | Java level related stuffs that are also needed to roll back
@param undoLog
@param undo | [
"Java",
"level",
"related",
"stuffs",
"that",
"are",
"also",
"needed",
"to",
"roll",
"back"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/iv2/Site.java#L1167-L1185 |
apache/flink | flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/state/serialization/KvStateSerializer.java | KvStateSerializer.deserializeValue | public static <T> T deserializeValue(byte[] serializedValue, TypeSerializer<T> serializer) throws IOException {
"""
Deserializes the value with the given serializer.
@param serializedValue Serialized value of type T
@param serializer Serializer for T
@param <T> Type of the value
@return Deserialized value or <code>null</code> if the serialized value
is <code>null</code>
@throws IOException On failure during deserialization
"""
if (serializedValue == null) {
return null;
} else {
final DataInputDeserializer deser = new DataInputDeserializer(
serializedValue, 0, serializedValue.length);
final T value = serializer.deserialize(deser);
if (deser.available() > 0) {
throw new IOException(
"Unconsumed bytes in the deserialized value. " +
"This indicates a mismatch in the value serializers " +
"used by the KvState instance and this access.");
}
return value;
}
} | java | public static <T> T deserializeValue(byte[] serializedValue, TypeSerializer<T> serializer) throws IOException {
if (serializedValue == null) {
return null;
} else {
final DataInputDeserializer deser = new DataInputDeserializer(
serializedValue, 0, serializedValue.length);
final T value = serializer.deserialize(deser);
if (deser.available() > 0) {
throw new IOException(
"Unconsumed bytes in the deserialized value. " +
"This indicates a mismatch in the value serializers " +
"used by the KvState instance and this access.");
}
return value;
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"deserializeValue",
"(",
"byte",
"[",
"]",
"serializedValue",
",",
"TypeSerializer",
"<",
"T",
">",
"serializer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"serializedValue",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"final",
"DataInputDeserializer",
"deser",
"=",
"new",
"DataInputDeserializer",
"(",
"serializedValue",
",",
"0",
",",
"serializedValue",
".",
"length",
")",
";",
"final",
"T",
"value",
"=",
"serializer",
".",
"deserialize",
"(",
"deser",
")",
";",
"if",
"(",
"deser",
".",
"available",
"(",
")",
">",
"0",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unconsumed bytes in the deserialized value. \"",
"+",
"\"This indicates a mismatch in the value serializers \"",
"+",
"\"used by the KvState instance and this access.\"",
")",
";",
"}",
"return",
"value",
";",
"}",
"}"
] | Deserializes the value with the given serializer.
@param serializedValue Serialized value of type T
@param serializer Serializer for T
@param <T> Type of the value
@return Deserialized value or <code>null</code> if the serialized value
is <code>null</code>
@throws IOException On failure during deserialization | [
"Deserializes",
"the",
"value",
"with",
"the",
"given",
"serializer",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/client/state/serialization/KvStateSerializer.java#L145-L160 |
gwtplus/google-gin | src/main/java/com/google/gwt/inject/rebind/util/NameGenerator.java | NameGenerator.getFragmentClassName | public String getFragmentClassName(String injectorClassName,
FragmentPackageName fragmentPackageName) {
"""
Computes the name of a single fragment of a Ginjector.
@param injectorClassName the simple name of the injector's class (not
including its package)
"""
// Sanity check.
Preconditions.checkArgument(!injectorClassName.contains("."),
"The injector class must be a simple name, but it was \"%s\"", injectorClassName);
// Note that the fragment package name is not actually included in the
// fragment. This reduces the length of the fragment's class name, which is
// important because some systems have small limits on the maximum length of
// a file (e.g., ~256 characters). However, it means that other parts of
// Gin must reference the fragment using its canonical class name, to avoid
// ambiguity.
return injectorClassName + "_fragment";
} | java | public String getFragmentClassName(String injectorClassName,
FragmentPackageName fragmentPackageName) {
// Sanity check.
Preconditions.checkArgument(!injectorClassName.contains("."),
"The injector class must be a simple name, but it was \"%s\"", injectorClassName);
// Note that the fragment package name is not actually included in the
// fragment. This reduces the length of the fragment's class name, which is
// important because some systems have small limits on the maximum length of
// a file (e.g., ~256 characters). However, it means that other parts of
// Gin must reference the fragment using its canonical class name, to avoid
// ambiguity.
return injectorClassName + "_fragment";
} | [
"public",
"String",
"getFragmentClassName",
"(",
"String",
"injectorClassName",
",",
"FragmentPackageName",
"fragmentPackageName",
")",
"{",
"// Sanity check.",
"Preconditions",
".",
"checkArgument",
"(",
"!",
"injectorClassName",
".",
"contains",
"(",
"\".\"",
")",
",",
"\"The injector class must be a simple name, but it was \\\"%s\\\"\"",
",",
"injectorClassName",
")",
";",
"// Note that the fragment package name is not actually included in the",
"// fragment. This reduces the length of the fragment's class name, which is",
"// important because some systems have small limits on the maximum length of",
"// a file (e.g., ~256 characters). However, it means that other parts of",
"// Gin must reference the fragment using its canonical class name, to avoid",
"// ambiguity.",
"return",
"injectorClassName",
"+",
"\"_fragment\"",
";",
"}"
] | Computes the name of a single fragment of a Ginjector.
@param injectorClassName the simple name of the injector's class (not
including its package) | [
"Computes",
"the",
"name",
"of",
"a",
"single",
"fragment",
"of",
"a",
"Ginjector",
"."
] | train | https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/NameGenerator.java#L104-L117 |
santhosh-tekuri/jlibs | core/src/main/java/jlibs/core/lang/Ansi.java | Ansi.errFormat | public void errFormat(String format, Object... args) {
"""
Prints formatted and colorized {@code format} to {@link System#err}
@param format A format string whose output to be colorized
@param args Arguments referenced by the format specifiers in the format
"""
format(System.err, format, args);
} | java | public void errFormat(String format, Object... args){
format(System.err, format, args);
} | [
"public",
"void",
"errFormat",
"(",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"format",
"(",
"System",
".",
"err",
",",
"format",
",",
"args",
")",
";",
"}"
] | Prints formatted and colorized {@code format} to {@link System#err}
@param format A format string whose output to be colorized
@param args Arguments referenced by the format specifiers in the format | [
"Prints",
"formatted",
"and",
"colorized",
"{",
"@code",
"format",
"}",
"to",
"{",
"@link",
"System#err",
"}"
] | train | https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/lang/Ansi.java#L336-L338 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscNodesInner.java | DscNodesInner.get | public DscNodeInner get(String resourceGroupName, String automationAccountName, String nodeId) {
"""
Retrieve the dsc node identified by node id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param nodeId The node id.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DscNodeInner object if successful.
"""
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeId).toBlocking().single().body();
} | java | public DscNodeInner get(String resourceGroupName, String automationAccountName, String nodeId) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeId).toBlocking().single().body();
} | [
"public",
"DscNodeInner",
"get",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"nodeId",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"nodeId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Retrieve the dsc node identified by node id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param nodeId The node id.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DscNodeInner object if successful. | [
"Retrieve",
"the",
"dsc",
"node",
"identified",
"by",
"node",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscNodesInner.java#L189-L191 |
Whiley/WhileyCompiler | src/main/java/wyil/check/DefiniteAssignmentCheck.java | DefiniteAssignmentCheck.visitFunctionOrMethod | @Override
public ControlFlow visitFunctionOrMethod(Decl.FunctionOrMethod declaration, DefinitelyAssignedSet dummy) {
"""
Check a function or method declaration for definite assignment.
@param declaration
@return
"""
DefinitelyAssignedSet environment = new DefinitelyAssignedSet();
// Definitely assigned variables includes all parameters.
environment = environment.addAll(declaration.getParameters());
// Preconditions can only refer to parameters
visitExpressions(declaration.getRequires(),environment);
// Postconditions can refer to parameterts and returns
{
DefinitelyAssignedSet postEnvironment = environment.addAll(declaration.getReturns());
visitExpressions(declaration.getEnsures(),postEnvironment);
}
// Iterate through each statement in the body of the function or method,
// updating the set of definitely assigned variables as appropriate.
visitStatement(declaration.getBody(),environment);
//
return null;
} | java | @Override
public ControlFlow visitFunctionOrMethod(Decl.FunctionOrMethod declaration, DefinitelyAssignedSet dummy) {
DefinitelyAssignedSet environment = new DefinitelyAssignedSet();
// Definitely assigned variables includes all parameters.
environment = environment.addAll(declaration.getParameters());
// Preconditions can only refer to parameters
visitExpressions(declaration.getRequires(),environment);
// Postconditions can refer to parameterts and returns
{
DefinitelyAssignedSet postEnvironment = environment.addAll(declaration.getReturns());
visitExpressions(declaration.getEnsures(),postEnvironment);
}
// Iterate through each statement in the body of the function or method,
// updating the set of definitely assigned variables as appropriate.
visitStatement(declaration.getBody(),environment);
//
return null;
} | [
"@",
"Override",
"public",
"ControlFlow",
"visitFunctionOrMethod",
"(",
"Decl",
".",
"FunctionOrMethod",
"declaration",
",",
"DefinitelyAssignedSet",
"dummy",
")",
"{",
"DefinitelyAssignedSet",
"environment",
"=",
"new",
"DefinitelyAssignedSet",
"(",
")",
";",
"// Definitely assigned variables includes all parameters.",
"environment",
"=",
"environment",
".",
"addAll",
"(",
"declaration",
".",
"getParameters",
"(",
")",
")",
";",
"// Preconditions can only refer to parameters",
"visitExpressions",
"(",
"declaration",
".",
"getRequires",
"(",
")",
",",
"environment",
")",
";",
"// Postconditions can refer to parameterts and returns",
"{",
"DefinitelyAssignedSet",
"postEnvironment",
"=",
"environment",
".",
"addAll",
"(",
"declaration",
".",
"getReturns",
"(",
")",
")",
";",
"visitExpressions",
"(",
"declaration",
".",
"getEnsures",
"(",
")",
",",
"postEnvironment",
")",
";",
"}",
"// Iterate through each statement in the body of the function or method,",
"// updating the set of definitely assigned variables as appropriate.",
"visitStatement",
"(",
"declaration",
".",
"getBody",
"(",
")",
",",
"environment",
")",
";",
"//",
"return",
"null",
";",
"}"
] | Check a function or method declaration for definite assignment.
@param declaration
@return | [
"Check",
"a",
"function",
"or",
"method",
"declaration",
"for",
"definite",
"assignment",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/DefiniteAssignmentCheck.java#L69-L86 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/request/JmxRequestFactory.java | JmxRequestFactory.extractPathInfo | private static String extractPathInfo(String pPathInfo, ProcessingParameters pProcessingParams) {
"""
Extract path info either from the 'real' URL path, or from an request parameter
"""
String pathInfo = pPathInfo;
// If no pathinfo is given directly, we look for a query parameter named 'p'.
// This variant is helpful, if there are problems with the server mangling
// up the pathinfo (e.g. for security concerns, often '/','\',';' and other are not
// allowed in encoded form within the pathinfo)
if (pProcessingParams != null && (pPathInfo == null || pPathInfo.length() == 0 || pathInfo.matches("^/+$"))) {
pathInfo = pProcessingParams.getPathInfo();
}
return normalizePathInfo(pathInfo);
} | java | private static String extractPathInfo(String pPathInfo, ProcessingParameters pProcessingParams) {
String pathInfo = pPathInfo;
// If no pathinfo is given directly, we look for a query parameter named 'p'.
// This variant is helpful, if there are problems with the server mangling
// up the pathinfo (e.g. for security concerns, often '/','\',';' and other are not
// allowed in encoded form within the pathinfo)
if (pProcessingParams != null && (pPathInfo == null || pPathInfo.length() == 0 || pathInfo.matches("^/+$"))) {
pathInfo = pProcessingParams.getPathInfo();
}
return normalizePathInfo(pathInfo);
} | [
"private",
"static",
"String",
"extractPathInfo",
"(",
"String",
"pPathInfo",
",",
"ProcessingParameters",
"pProcessingParams",
")",
"{",
"String",
"pathInfo",
"=",
"pPathInfo",
";",
"// If no pathinfo is given directly, we look for a query parameter named 'p'.",
"// This variant is helpful, if there are problems with the server mangling",
"// up the pathinfo (e.g. for security concerns, often '/','\\',';' and other are not",
"// allowed in encoded form within the pathinfo)",
"if",
"(",
"pProcessingParams",
"!=",
"null",
"&&",
"(",
"pPathInfo",
"==",
"null",
"||",
"pPathInfo",
".",
"length",
"(",
")",
"==",
"0",
"||",
"pathInfo",
".",
"matches",
"(",
"\"^/+$\"",
")",
")",
")",
"{",
"pathInfo",
"=",
"pProcessingParams",
".",
"getPathInfo",
"(",
")",
";",
"}",
"return",
"normalizePathInfo",
"(",
"pathInfo",
")",
";",
"}"
] | Extract path info either from the 'real' URL path, or from an request parameter | [
"Extract",
"path",
"info",
"either",
"from",
"the",
"real",
"URL",
"path",
"or",
"from",
"an",
"request",
"parameter"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/request/JmxRequestFactory.java#L145-L156 |
ops4j/org.ops4j.pax.web | pax-web-extender-war/src/main/java/org/ops4j/pax/web/extender/war/internal/parser/WebAppParser.java | WebAppParser.parseContextParams | private static void parseContextParams(final ParamValueType contextParam, final WebApp webApp) {
"""
Parses context params out of web.xml.
@param contextParam contextParam element from web.xml
@param webApp model for web.xml
"""
final WebAppInitParam initParam = new WebAppInitParam();
initParam.setParamName(contextParam.getParamName().getValue());
initParam.setParamValue(contextParam.getParamValue().getValue());
webApp.addContextParam(initParam);
} | java | private static void parseContextParams(final ParamValueType contextParam, final WebApp webApp) {
final WebAppInitParam initParam = new WebAppInitParam();
initParam.setParamName(contextParam.getParamName().getValue());
initParam.setParamValue(contextParam.getParamValue().getValue());
webApp.addContextParam(initParam);
} | [
"private",
"static",
"void",
"parseContextParams",
"(",
"final",
"ParamValueType",
"contextParam",
",",
"final",
"WebApp",
"webApp",
")",
"{",
"final",
"WebAppInitParam",
"initParam",
"=",
"new",
"WebAppInitParam",
"(",
")",
";",
"initParam",
".",
"setParamName",
"(",
"contextParam",
".",
"getParamName",
"(",
")",
".",
"getValue",
"(",
")",
")",
";",
"initParam",
".",
"setParamValue",
"(",
"contextParam",
".",
"getParamValue",
"(",
")",
".",
"getValue",
"(",
")",
")",
";",
"webApp",
".",
"addContextParam",
"(",
"initParam",
")",
";",
"}"
] | Parses context params out of web.xml.
@param contextParam contextParam element from web.xml
@param webApp model for web.xml | [
"Parses",
"context",
"params",
"out",
"of",
"web",
".",
"xml",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.web/blob/9ecf3676c1d316be0d43ea7fcfdc8f0defffc2a2/pax-web-extender-war/src/main/java/org/ops4j/pax/web/extender/war/internal/parser/WebAppParser.java#L526-L531 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ProjectsInner.java | ProjectsInner.updateAsync | public Observable<ProjectInner> updateAsync(String groupName, String serviceName, String projectName, ProjectInner parameters) {
"""
Update project.
The project resource is a nested resource representing a stored migration project. The PATCH method updates an existing project.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@param parameters Information about the project
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProjectInner object
"""
return updateWithServiceResponseAsync(groupName, serviceName, projectName, parameters).map(new Func1<ServiceResponse<ProjectInner>, ProjectInner>() {
@Override
public ProjectInner call(ServiceResponse<ProjectInner> response) {
return response.body();
}
});
} | java | public Observable<ProjectInner> updateAsync(String groupName, String serviceName, String projectName, ProjectInner parameters) {
return updateWithServiceResponseAsync(groupName, serviceName, projectName, parameters).map(new Func1<ServiceResponse<ProjectInner>, ProjectInner>() {
@Override
public ProjectInner call(ServiceResponse<ProjectInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ProjectInner",
">",
"updateAsync",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
",",
"String",
"projectName",
",",
"ProjectInner",
"parameters",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
",",
"projectName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ProjectInner",
">",
",",
"ProjectInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ProjectInner",
"call",
"(",
"ServiceResponse",
"<",
"ProjectInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Update project.
The project resource is a nested resource representing a stored migration project. The PATCH method updates an existing project.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@param parameters Information about the project
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProjectInner object | [
"Update",
"project",
".",
"The",
"project",
"resource",
"is",
"a",
"nested",
"resource",
"representing",
"a",
"stored",
"migration",
"project",
".",
"The",
"PATCH",
"method",
"updates",
"an",
"existing",
"project",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ProjectsInner.java#L657-L664 |
ReactiveX/RxJavaComputationExpressions | src/main/java/rx/Statement.java | Statement.ifThen | public static <R> Observable<R> ifThen(Func0<Boolean> condition, Observable<? extends R> then,
Observable<? extends R> orElse) {
"""
Return an Observable that emits the emissions from one specified
Observable if a condition evaluates to true, or from another specified
Observable otherwise.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ifThen.e.png" alt="">
@param <R>
the result value type
@param condition
the condition that decides which Observable to emit the
emissions from
@param then
the Observable sequence to emit to if {@code condition} is {@code true}
@param orElse
the Observable sequence to emit to if {@code condition} is {@code false}
@return an Observable that mimics either the {@code then} or {@code orElse} Observables depending on a condition function
"""
return Observable.create(new OperatorIfThen<R>(condition, then, orElse));
} | java | public static <R> Observable<R> ifThen(Func0<Boolean> condition, Observable<? extends R> then,
Observable<? extends R> orElse) {
return Observable.create(new OperatorIfThen<R>(condition, then, orElse));
} | [
"public",
"static",
"<",
"R",
">",
"Observable",
"<",
"R",
">",
"ifThen",
"(",
"Func0",
"<",
"Boolean",
">",
"condition",
",",
"Observable",
"<",
"?",
"extends",
"R",
">",
"then",
",",
"Observable",
"<",
"?",
"extends",
"R",
">",
"orElse",
")",
"{",
"return",
"Observable",
".",
"create",
"(",
"new",
"OperatorIfThen",
"<",
"R",
">",
"(",
"condition",
",",
"then",
",",
"orElse",
")",
")",
";",
"}"
] | Return an Observable that emits the emissions from one specified
Observable if a condition evaluates to true, or from another specified
Observable otherwise.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ifThen.e.png" alt="">
@param <R>
the result value type
@param condition
the condition that decides which Observable to emit the
emissions from
@param then
the Observable sequence to emit to if {@code condition} is {@code true}
@param orElse
the Observable sequence to emit to if {@code condition} is {@code false}
@return an Observable that mimics either the {@code then} or {@code orElse} Observables depending on a condition function | [
"Return",
"an",
"Observable",
"that",
"emits",
"the",
"emissions",
"from",
"one",
"specified",
"Observable",
"if",
"a",
"condition",
"evaluates",
"to",
"true",
"or",
"from",
"another",
"specified",
"Observable",
"otherwise",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"ReactiveX",
"/",
"RxJava",
"/",
"images",
"/",
"rx",
"-",
"operators",
"/",
"ifThen",
".",
"e",
".",
"png",
"alt",
"=",
">"
] | train | https://github.com/ReactiveX/RxJavaComputationExpressions/blob/f9d04ab762223b36fad47402ac36ce7969320d69/src/main/java/rx/Statement.java#L203-L206 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/ColorNames.java | ColorNames.getColorFromName | @Pure
public static int getColorFromName(String colorName, int defaultValue) {
"""
Replies the color value for the given color name.
<p>See the documentation of the {@link #ColorNames} type for obtaining a list of the colors.
@param colorName the color name.
@param defaultValue if the given name does not corresponds to a known color, this value is replied.
@return the color value.
"""
final Integer value = COLOR_MATCHES.get(Strings.nullToEmpty(colorName).toLowerCase());
if (value != null) {
return value.intValue();
}
return defaultValue;
} | java | @Pure
public static int getColorFromName(String colorName, int defaultValue) {
final Integer value = COLOR_MATCHES.get(Strings.nullToEmpty(colorName).toLowerCase());
if (value != null) {
return value.intValue();
}
return defaultValue;
} | [
"@",
"Pure",
"public",
"static",
"int",
"getColorFromName",
"(",
"String",
"colorName",
",",
"int",
"defaultValue",
")",
"{",
"final",
"Integer",
"value",
"=",
"COLOR_MATCHES",
".",
"get",
"(",
"Strings",
".",
"nullToEmpty",
"(",
"colorName",
")",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"return",
"value",
".",
"intValue",
"(",
")",
";",
"}",
"return",
"defaultValue",
";",
"}"
] | Replies the color value for the given color name.
<p>See the documentation of the {@link #ColorNames} type for obtaining a list of the colors.
@param colorName the color name.
@param defaultValue if the given name does not corresponds to a known color, this value is replied.
@return the color value. | [
"Replies",
"the",
"color",
"value",
"for",
"the",
"given",
"color",
"name",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/ColorNames.java#L541-L548 |
iipc/webarchive-commons | src/main/java/org/archive/util/TextUtils.java | TextUtils.writeEscapedForHTML | public static void writeEscapedForHTML(String s, Writer w)
throws IOException {
"""
Utility method for writing a (potentially large) String to a JspWriter,
escaping it for HTML display, without constructing another large String
of the whole content.
@param s String to write
@param out destination JspWriter
@throws IOException
"""
PrintWriter out = new PrintWriter(w);
BufferedReader reader = new BufferedReader(new StringReader(s));
String line;
while((line=reader.readLine()) != null){
out.println(StringEscapeUtils.escapeHtml(line));
}
} | java | public static void writeEscapedForHTML(String s, Writer w)
throws IOException {
PrintWriter out = new PrintWriter(w);
BufferedReader reader = new BufferedReader(new StringReader(s));
String line;
while((line=reader.readLine()) != null){
out.println(StringEscapeUtils.escapeHtml(line));
}
} | [
"public",
"static",
"void",
"writeEscapedForHTML",
"(",
"String",
"s",
",",
"Writer",
"w",
")",
"throws",
"IOException",
"{",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"w",
")",
";",
"BufferedReader",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"StringReader",
"(",
"s",
")",
")",
";",
"String",
"line",
";",
"while",
"(",
"(",
"line",
"=",
"reader",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"out",
".",
"println",
"(",
"StringEscapeUtils",
".",
"escapeHtml",
"(",
"line",
")",
")",
";",
"}",
"}"
] | Utility method for writing a (potentially large) String to a JspWriter,
escaping it for HTML display, without constructing another large String
of the whole content.
@param s String to write
@param out destination JspWriter
@throws IOException | [
"Utility",
"method",
"for",
"writing",
"a",
"(",
"potentially",
"large",
")",
"String",
"to",
"a",
"JspWriter",
"escaping",
"it",
"for",
"HTML",
"display",
"without",
"constructing",
"another",
"large",
"String",
"of",
"the",
"whole",
"content",
"."
] | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/TextUtils.java#L236-L244 |
datumbox/datumbox-framework | datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/KolmogorovSmirnovOneSample.java | KolmogorovSmirnovOneSample.checkCriticalValue | private static boolean checkCriticalValue(double score, boolean is_twoTailed, int n, double aLevel) {
"""
Checks the Critical Value to determine if the Hypothesis should be rejected
@param score
@param is_twoTailed
@param n
@param aLevel
@return
"""
boolean rejected=false;
double criticalValue;
if(CRITICAL_VALUES.containsKey(aLevel)) { //the aLevel is one of the standards, we can use the tables
if(CRITICAL_VALUES.get(aLevel).containsKey(n)) { //if the n value exists within the table use the exact percentage
criticalValue = CRITICAL_VALUES.get(aLevel).getDouble(n);
}
else {
//the n is too large, use the approximation
criticalValue=CRITICAL_VALUES.get(aLevel).getDouble(0);
criticalValue/=Math.sqrt(n+Math.sqrt(n/10.0));
}
}
else {
//estimate dynamically the critical value from the kolmogorov distribution
criticalValue=calculateCriticalValue(is_twoTailed,n,aLevel);
}
if(score>criticalValue) {
rejected=true;
}
return rejected;
} | java | private static boolean checkCriticalValue(double score, boolean is_twoTailed, int n, double aLevel) {
boolean rejected=false;
double criticalValue;
if(CRITICAL_VALUES.containsKey(aLevel)) { //the aLevel is one of the standards, we can use the tables
if(CRITICAL_VALUES.get(aLevel).containsKey(n)) { //if the n value exists within the table use the exact percentage
criticalValue = CRITICAL_VALUES.get(aLevel).getDouble(n);
}
else {
//the n is too large, use the approximation
criticalValue=CRITICAL_VALUES.get(aLevel).getDouble(0);
criticalValue/=Math.sqrt(n+Math.sqrt(n/10.0));
}
}
else {
//estimate dynamically the critical value from the kolmogorov distribution
criticalValue=calculateCriticalValue(is_twoTailed,n,aLevel);
}
if(score>criticalValue) {
rejected=true;
}
return rejected;
} | [
"private",
"static",
"boolean",
"checkCriticalValue",
"(",
"double",
"score",
",",
"boolean",
"is_twoTailed",
",",
"int",
"n",
",",
"double",
"aLevel",
")",
"{",
"boolean",
"rejected",
"=",
"false",
";",
"double",
"criticalValue",
";",
"if",
"(",
"CRITICAL_VALUES",
".",
"containsKey",
"(",
"aLevel",
")",
")",
"{",
"//the aLevel is one of the standards, we can use the tables",
"if",
"(",
"CRITICAL_VALUES",
".",
"get",
"(",
"aLevel",
")",
".",
"containsKey",
"(",
"n",
")",
")",
"{",
"//if the n value exists within the table use the exact percentage",
"criticalValue",
"=",
"CRITICAL_VALUES",
".",
"get",
"(",
"aLevel",
")",
".",
"getDouble",
"(",
"n",
")",
";",
"}",
"else",
"{",
"//the n is too large, use the approximation",
"criticalValue",
"=",
"CRITICAL_VALUES",
".",
"get",
"(",
"aLevel",
")",
".",
"getDouble",
"(",
"0",
")",
";",
"criticalValue",
"/=",
"Math",
".",
"sqrt",
"(",
"n",
"+",
"Math",
".",
"sqrt",
"(",
"n",
"/",
"10.0",
")",
")",
";",
"}",
"}",
"else",
"{",
"//estimate dynamically the critical value from the kolmogorov distribution",
"criticalValue",
"=",
"calculateCriticalValue",
"(",
"is_twoTailed",
",",
"n",
",",
"aLevel",
")",
";",
"}",
"if",
"(",
"score",
">",
"criticalValue",
")",
"{",
"rejected",
"=",
"true",
";",
"}",
"return",
"rejected",
";",
"}"
] | Checks the Critical Value to determine if the Hypothesis should be rejected
@param score
@param is_twoTailed
@param n
@param aLevel
@return | [
"Checks",
"the",
"Critical",
"Value",
"to",
"determine",
"if",
"the",
"Hypothesis",
"should",
"be",
"rejected"
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/onesample/KolmogorovSmirnovOneSample.java#L125-L151 |
javers/javers | javers-core/src/main/java/org/javers/core/metamodel/type/TypeMapper.java | TypeMapper.getJaversManagedType | public <T extends ManagedType> T getJaversManagedType(Class javaClass, Class<T> expectedType) {
"""
If given javaClass is mapped to expected ManagedType, returns its JaversType
@throws JaversException MANAGED_CLASS_MAPPING_ERROR
"""
JaversType mType = getJaversType(javaClass);
if (expectedType.isAssignableFrom(mType.getClass())) {
return (T) mType;
} else {
throw new JaversException(JaversExceptionCode.MANAGED_CLASS_MAPPING_ERROR,
javaClass,
mType.getClass().getSimpleName(),
expectedType.getSimpleName());
}
} | java | public <T extends ManagedType> T getJaversManagedType(Class javaClass, Class<T> expectedType) {
JaversType mType = getJaversType(javaClass);
if (expectedType.isAssignableFrom(mType.getClass())) {
return (T) mType;
} else {
throw new JaversException(JaversExceptionCode.MANAGED_CLASS_MAPPING_ERROR,
javaClass,
mType.getClass().getSimpleName(),
expectedType.getSimpleName());
}
} | [
"public",
"<",
"T",
"extends",
"ManagedType",
">",
"T",
"getJaversManagedType",
"(",
"Class",
"javaClass",
",",
"Class",
"<",
"T",
">",
"expectedType",
")",
"{",
"JaversType",
"mType",
"=",
"getJaversType",
"(",
"javaClass",
")",
";",
"if",
"(",
"expectedType",
".",
"isAssignableFrom",
"(",
"mType",
".",
"getClass",
"(",
")",
")",
")",
"{",
"return",
"(",
"T",
")",
"mType",
";",
"}",
"else",
"{",
"throw",
"new",
"JaversException",
"(",
"JaversExceptionCode",
".",
"MANAGED_CLASS_MAPPING_ERROR",
",",
"javaClass",
",",
"mType",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
",",
"expectedType",
".",
"getSimpleName",
"(",
")",
")",
";",
"}",
"}"
] | If given javaClass is mapped to expected ManagedType, returns its JaversType
@throws JaversException MANAGED_CLASS_MAPPING_ERROR | [
"If",
"given",
"javaClass",
"is",
"mapped",
"to",
"expected",
"ManagedType",
"returns",
"its",
"JaversType"
] | train | https://github.com/javers/javers/blob/a51511be7d8bcee3e1812db8b7e69a45330b4e14/javers-core/src/main/java/org/javers/core/metamodel/type/TypeMapper.java#L179-L190 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/MPXReader.java | MPXReader.populateCalendarHours | private void populateCalendarHours(Record record, ProjectCalendarHours hours) throws MPXJException {
"""
Populates a calendar hours instance.
@param record MPX record
@param hours calendar hours instance
@throws MPXJException
"""
hours.setDay(Day.getInstance(NumberHelper.getInt(record.getInteger(0))));
addDateRange(hours, record.getTime(1), record.getTime(2));
addDateRange(hours, record.getTime(3), record.getTime(4));
addDateRange(hours, record.getTime(5), record.getTime(6));
} | java | private void populateCalendarHours(Record record, ProjectCalendarHours hours) throws MPXJException
{
hours.setDay(Day.getInstance(NumberHelper.getInt(record.getInteger(0))));
addDateRange(hours, record.getTime(1), record.getTime(2));
addDateRange(hours, record.getTime(3), record.getTime(4));
addDateRange(hours, record.getTime(5), record.getTime(6));
} | [
"private",
"void",
"populateCalendarHours",
"(",
"Record",
"record",
",",
"ProjectCalendarHours",
"hours",
")",
"throws",
"MPXJException",
"{",
"hours",
".",
"setDay",
"(",
"Day",
".",
"getInstance",
"(",
"NumberHelper",
".",
"getInt",
"(",
"record",
".",
"getInteger",
"(",
"0",
")",
")",
")",
")",
";",
"addDateRange",
"(",
"hours",
",",
"record",
".",
"getTime",
"(",
"1",
")",
",",
"record",
".",
"getTime",
"(",
"2",
")",
")",
";",
"addDateRange",
"(",
"hours",
",",
"record",
".",
"getTime",
"(",
"3",
")",
",",
"record",
".",
"getTime",
"(",
"4",
")",
")",
";",
"addDateRange",
"(",
"hours",
",",
"record",
".",
"getTime",
"(",
"5",
")",
",",
"record",
".",
"getTime",
"(",
"6",
")",
")",
";",
"}"
] | Populates a calendar hours instance.
@param record MPX record
@param hours calendar hours instance
@throws MPXJException | [
"Populates",
"a",
"calendar",
"hours",
"instance",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXReader.java#L632-L638 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/Centroid.java | Centroid.put | public void put(double[] val, double weight) {
"""
Add data with a given weight.
@param val data
@param weight weight
"""
assert (val.length == elements.length);
if(weight == 0) {
return; // Skip zero weights.
}
final double nwsum = weight + wsum;
for(int i = 0; i < elements.length; i++) {
final double delta = val[i] - elements[i];
final double rval = delta * weight / nwsum;
elements[i] += rval;
}
wsum = nwsum;
} | java | public void put(double[] val, double weight) {
assert (val.length == elements.length);
if(weight == 0) {
return; // Skip zero weights.
}
final double nwsum = weight + wsum;
for(int i = 0; i < elements.length; i++) {
final double delta = val[i] - elements[i];
final double rval = delta * weight / nwsum;
elements[i] += rval;
}
wsum = nwsum;
} | [
"public",
"void",
"put",
"(",
"double",
"[",
"]",
"val",
",",
"double",
"weight",
")",
"{",
"assert",
"(",
"val",
".",
"length",
"==",
"elements",
".",
"length",
")",
";",
"if",
"(",
"weight",
"==",
"0",
")",
"{",
"return",
";",
"// Skip zero weights.",
"}",
"final",
"double",
"nwsum",
"=",
"weight",
"+",
"wsum",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"elements",
".",
"length",
";",
"i",
"++",
")",
"{",
"final",
"double",
"delta",
"=",
"val",
"[",
"i",
"]",
"-",
"elements",
"[",
"i",
"]",
";",
"final",
"double",
"rval",
"=",
"delta",
"*",
"weight",
"/",
"nwsum",
";",
"elements",
"[",
"i",
"]",
"+=",
"rval",
";",
"}",
"wsum",
"=",
"nwsum",
";",
"}"
] | Add data with a given weight.
@param val data
@param weight weight | [
"Add",
"data",
"with",
"a",
"given",
"weight",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/Centroid.java#L80-L92 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java | GeometryTools.calculatePerpendicularUnitVector | public static Vector2d calculatePerpendicularUnitVector(Point2d point1, Point2d point2) {
"""
Determines the normalized vector orthogonal on the vector p1->p2.
@param point1 Description of the Parameter
@param point2 Description of the Parameter
@return Description of the Return Value
"""
Vector2d vector = new Vector2d();
vector.sub(point2, point1);
vector.normalize();
// Return the perpendicular vector
return new Vector2d(-1.0 * vector.y, vector.x);
} | java | public static Vector2d calculatePerpendicularUnitVector(Point2d point1, Point2d point2) {
Vector2d vector = new Vector2d();
vector.sub(point2, point1);
vector.normalize();
// Return the perpendicular vector
return new Vector2d(-1.0 * vector.y, vector.x);
} | [
"public",
"static",
"Vector2d",
"calculatePerpendicularUnitVector",
"(",
"Point2d",
"point1",
",",
"Point2d",
"point2",
")",
"{",
"Vector2d",
"vector",
"=",
"new",
"Vector2d",
"(",
")",
";",
"vector",
".",
"sub",
"(",
"point2",
",",
"point1",
")",
";",
"vector",
".",
"normalize",
"(",
")",
";",
"// Return the perpendicular vector",
"return",
"new",
"Vector2d",
"(",
"-",
"1.0",
"*",
"vector",
".",
"y",
",",
"vector",
".",
"x",
")",
";",
"}"
] | Determines the normalized vector orthogonal on the vector p1->p2.
@param point1 Description of the Parameter
@param point2 Description of the Parameter
@return Description of the Return Value | [
"Determines",
"the",
"normalized",
"vector",
"orthogonal",
"on",
"the",
"vector",
"p1",
"-",
">",
";",
"p2",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L1145-L1152 |
blinkfox/zealot | src/main/java/com/blinkfox/zealot/core/ZealotKhala.java | ZealotKhala.notLikePattern | public ZealotKhala notLikePattern(String field, String pattern) {
"""
根据指定的模式字符串生成" NOT LIKE "模糊查询的SQL片段.
<p>示例:传入 {"b.title", "Java%"} 两个参数,生成的SQL片段为:" b.title NOT LIKE 'Java%' "</p>
@param field 数据库字段
@param pattern 模式字符串
@return ZealotKhala实例
"""
return this.doLikePattern(ZealotConst.ONE_SPACE, field, pattern, true, false);
} | java | public ZealotKhala notLikePattern(String field, String pattern) {
return this.doLikePattern(ZealotConst.ONE_SPACE, field, pattern, true, false);
} | [
"public",
"ZealotKhala",
"notLikePattern",
"(",
"String",
"field",
",",
"String",
"pattern",
")",
"{",
"return",
"this",
".",
"doLikePattern",
"(",
"ZealotConst",
".",
"ONE_SPACE",
",",
"field",
",",
"pattern",
",",
"true",
",",
"false",
")",
";",
"}"
] | 根据指定的模式字符串生成" NOT LIKE "模糊查询的SQL片段.
<p>示例:传入 {"b.title", "Java%"} 两个参数,生成的SQL片段为:" b.title NOT LIKE 'Java%' "</p>
@param field 数据库字段
@param pattern 模式字符串
@return ZealotKhala实例 | [
"根据指定的模式字符串生成",
"NOT",
"LIKE",
"模糊查询的SQL片段",
".",
"<p",
">",
"示例:传入",
"{",
"b",
".",
"title",
"Java%",
"}",
"两个参数,生成的SQL片段为:",
"b",
".",
"title",
"NOT",
"LIKE",
"Java%",
"<",
"/",
"p",
">"
] | train | https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L1118-L1120 |
molgenis/molgenis | molgenis-r/src/main/java/org/molgenis/r/RScriptExecutor.java | RScriptExecutor.executeScriptExecuteRequest | private String executeScriptExecuteRequest(String rScript) throws IOException {
"""
Execute R script using OpenCPU
@param rScript R script
@return OpenCPU session key
@throws IOException if error occured during script execution request
"""
URI uri = getScriptExecutionUri();
HttpPost httpPost = new HttpPost(uri);
NameValuePair nameValuePair = new BasicNameValuePair("x", rScript);
httpPost.setEntity(new UrlEncodedFormEntity(singletonList(nameValuePair)));
String openCpuSessionKey;
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
Header openCpuSessionKeyHeader = response.getFirstHeader("X-ocpu-session");
if (openCpuSessionKeyHeader == null) {
throw new IOException("Missing 'X-ocpu-session' header");
}
openCpuSessionKey = openCpuSessionKeyHeader.getValue();
EntityUtils.consume(response.getEntity());
} else if (statusCode == 400) {
HttpEntity entity = response.getEntity();
String rErrorMessage = EntityUtils.toString(entity);
EntityUtils.consume(entity);
throw new ScriptException(rErrorMessage);
} else {
throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode));
}
}
return openCpuSessionKey;
} | java | private String executeScriptExecuteRequest(String rScript) throws IOException {
URI uri = getScriptExecutionUri();
HttpPost httpPost = new HttpPost(uri);
NameValuePair nameValuePair = new BasicNameValuePair("x", rScript);
httpPost.setEntity(new UrlEncodedFormEntity(singletonList(nameValuePair)));
String openCpuSessionKey;
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
Header openCpuSessionKeyHeader = response.getFirstHeader("X-ocpu-session");
if (openCpuSessionKeyHeader == null) {
throw new IOException("Missing 'X-ocpu-session' header");
}
openCpuSessionKey = openCpuSessionKeyHeader.getValue();
EntityUtils.consume(response.getEntity());
} else if (statusCode == 400) {
HttpEntity entity = response.getEntity();
String rErrorMessage = EntityUtils.toString(entity);
EntityUtils.consume(entity);
throw new ScriptException(rErrorMessage);
} else {
throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode));
}
}
return openCpuSessionKey;
} | [
"private",
"String",
"executeScriptExecuteRequest",
"(",
"String",
"rScript",
")",
"throws",
"IOException",
"{",
"URI",
"uri",
"=",
"getScriptExecutionUri",
"(",
")",
";",
"HttpPost",
"httpPost",
"=",
"new",
"HttpPost",
"(",
"uri",
")",
";",
"NameValuePair",
"nameValuePair",
"=",
"new",
"BasicNameValuePair",
"(",
"\"x\"",
",",
"rScript",
")",
";",
"httpPost",
".",
"setEntity",
"(",
"new",
"UrlEncodedFormEntity",
"(",
"singletonList",
"(",
"nameValuePair",
")",
")",
")",
";",
"String",
"openCpuSessionKey",
";",
"try",
"(",
"CloseableHttpResponse",
"response",
"=",
"httpClient",
".",
"execute",
"(",
"httpPost",
")",
")",
"{",
"int",
"statusCode",
"=",
"response",
".",
"getStatusLine",
"(",
")",
".",
"getStatusCode",
"(",
")",
";",
"if",
"(",
"statusCode",
">=",
"200",
"&&",
"statusCode",
"<",
"300",
")",
"{",
"Header",
"openCpuSessionKeyHeader",
"=",
"response",
".",
"getFirstHeader",
"(",
"\"X-ocpu-session\"",
")",
";",
"if",
"(",
"openCpuSessionKeyHeader",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Missing 'X-ocpu-session' header\"",
")",
";",
"}",
"openCpuSessionKey",
"=",
"openCpuSessionKeyHeader",
".",
"getValue",
"(",
")",
";",
"EntityUtils",
".",
"consume",
"(",
"response",
".",
"getEntity",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"statusCode",
"==",
"400",
")",
"{",
"HttpEntity",
"entity",
"=",
"response",
".",
"getEntity",
"(",
")",
";",
"String",
"rErrorMessage",
"=",
"EntityUtils",
".",
"toString",
"(",
"entity",
")",
";",
"EntityUtils",
".",
"consume",
"(",
"entity",
")",
";",
"throw",
"new",
"ScriptException",
"(",
"rErrorMessage",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ClientProtocolException",
"(",
"format",
"(",
"FORMAT_UNEXPECTED_RESPONSE_STATUS",
",",
"statusCode",
")",
")",
";",
"}",
"}",
"return",
"openCpuSessionKey",
";",
"}"
] | Execute R script using OpenCPU
@param rScript R script
@return OpenCPU session key
@throws IOException if error occured during script execution request | [
"Execute",
"R",
"script",
"using",
"OpenCPU"
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-r/src/main/java/org/molgenis/r/RScriptExecutor.java#L79-L105 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java | BpmnParse.parseSequenceFlowConditionExpression | public void parseSequenceFlowConditionExpression(Element seqFlowElement, TransitionImpl seqFlow) {
"""
Parses a condition expression on a sequence flow.
@param seqFlowElement
The 'sequenceFlow' element that can contain a condition.
@param seqFlow
The sequenceFlow object representation to which the condition must
be added.
"""
Element conditionExprElement = seqFlowElement.element(CONDITION_EXPRESSION);
if (conditionExprElement != null) {
Condition condition = parseConditionExpression(conditionExprElement);
seqFlow.setProperty(PROPERTYNAME_CONDITION_TEXT, conditionExprElement.getText().trim());
seqFlow.setProperty(PROPERTYNAME_CONDITION, condition);
}
} | java | public void parseSequenceFlowConditionExpression(Element seqFlowElement, TransitionImpl seqFlow) {
Element conditionExprElement = seqFlowElement.element(CONDITION_EXPRESSION);
if (conditionExprElement != null) {
Condition condition = parseConditionExpression(conditionExprElement);
seqFlow.setProperty(PROPERTYNAME_CONDITION_TEXT, conditionExprElement.getText().trim());
seqFlow.setProperty(PROPERTYNAME_CONDITION, condition);
}
} | [
"public",
"void",
"parseSequenceFlowConditionExpression",
"(",
"Element",
"seqFlowElement",
",",
"TransitionImpl",
"seqFlow",
")",
"{",
"Element",
"conditionExprElement",
"=",
"seqFlowElement",
".",
"element",
"(",
"CONDITION_EXPRESSION",
")",
";",
"if",
"(",
"conditionExprElement",
"!=",
"null",
")",
"{",
"Condition",
"condition",
"=",
"parseConditionExpression",
"(",
"conditionExprElement",
")",
";",
"seqFlow",
".",
"setProperty",
"(",
"PROPERTYNAME_CONDITION_TEXT",
",",
"conditionExprElement",
".",
"getText",
"(",
")",
".",
"trim",
"(",
")",
")",
";",
"seqFlow",
".",
"setProperty",
"(",
"PROPERTYNAME_CONDITION",
",",
"condition",
")",
";",
"}",
"}"
] | Parses a condition expression on a sequence flow.
@param seqFlowElement
The 'sequenceFlow' element that can contain a condition.
@param seqFlow
The sequenceFlow object representation to which the condition must
be added. | [
"Parses",
"a",
"condition",
"expression",
"on",
"a",
"sequence",
"flow",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java#L4070-L4077 |
Coveros/selenified | src/main/java/com/coveros/selenified/application/App.java | App.newElement | public Element newElement(Locator type, String locator) {
"""
setups a new element which is located on the page
@param type - the locator type e.g. Locator.id, Locator.xpath
@param locator - the locator string e.g. login, //input[@id='login']
@return Element: a page element to interact with
"""
return new Element(driver, reporter, type, locator);
} | java | public Element newElement(Locator type, String locator) {
return new Element(driver, reporter, type, locator);
} | [
"public",
"Element",
"newElement",
"(",
"Locator",
"type",
",",
"String",
"locator",
")",
"{",
"return",
"new",
"Element",
"(",
"driver",
",",
"reporter",
",",
"type",
",",
"locator",
")",
";",
"}"
] | setups a new element which is located on the page
@param type - the locator type e.g. Locator.id, Locator.xpath
@param locator - the locator string e.g. login, //input[@id='login']
@return Element: a page element to interact with | [
"setups",
"a",
"new",
"element",
"which",
"is",
"located",
"on",
"the",
"page"
] | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/App.java#L135-L137 |
agapsys/embedded-servlet-container | src/main/java/com/agapsys/jee/AbstractFileServlet.java | AbstractFileServlet.onUncaughtException | protected void onUncaughtException(HttpServletRequest request, HttpServletResponse response, RuntimeException error) throws IOException {
"""
Called if an uncaught error was detected while processing given request.
Default implementation just sends a
{@linkplain HttpServletResponse#SC_INTERNAL_SERVER_ERROR} status and the
error stack trace embedded in response body.
@param request HTTP request.
@param response HTTP response.
@param error uncaught error.
@throws IOException
"""
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().print(__getStackTrace(error));
} | java | protected void onUncaughtException(HttpServletRequest request, HttpServletResponse response, RuntimeException error) throws IOException {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().print(__getStackTrace(error));
} | [
"protected",
"void",
"onUncaughtException",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"RuntimeException",
"error",
")",
"throws",
"IOException",
"{",
"response",
".",
"setStatus",
"(",
"HttpServletResponse",
".",
"SC_INTERNAL_SERVER_ERROR",
")",
";",
"response",
".",
"getWriter",
"(",
")",
".",
"print",
"(",
"__getStackTrace",
"(",
"error",
")",
")",
";",
"}"
] | Called if an uncaught error was detected while processing given request.
Default implementation just sends a
{@linkplain HttpServletResponse#SC_INTERNAL_SERVER_ERROR} status and the
error stack trace embedded in response body.
@param request HTTP request.
@param response HTTP response.
@param error uncaught error.
@throws IOException | [
"Called",
"if",
"an",
"uncaught",
"error",
"was",
"detected",
"while",
"processing",
"given",
"request",
".",
"Default",
"implementation",
"just",
"sends",
"a",
"{",
"@linkplain",
"HttpServletResponse#SC_INTERNAL_SERVER_ERROR",
"}",
"status",
"and",
"the",
"error",
"stack",
"trace",
"embedded",
"in",
"response",
"body",
"."
] | train | https://github.com/agapsys/embedded-servlet-container/blob/28314a2600ad8550ed2c901d8e35d86583c26bb0/src/main/java/com/agapsys/jee/AbstractFileServlet.java#L1331-L1334 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java | Convolution.conv2d | public static INDArray conv2d(INDArray input, INDArray kernel, Type type) {
"""
2d convolution (aka the last 2 dimensions
@param input the input to op
@param kernel the kernel to convolve with
@param type
@return
"""
return Nd4j.getConvolution().conv2d(input, kernel, type);
} | java | public static INDArray conv2d(INDArray input, INDArray kernel, Type type) {
return Nd4j.getConvolution().conv2d(input, kernel, type);
} | [
"public",
"static",
"INDArray",
"conv2d",
"(",
"INDArray",
"input",
",",
"INDArray",
"kernel",
",",
"Type",
"type",
")",
"{",
"return",
"Nd4j",
".",
"getConvolution",
"(",
")",
".",
"conv2d",
"(",
"input",
",",
"kernel",
",",
"type",
")",
";",
"}"
] | 2d convolution (aka the last 2 dimensions
@param input the input to op
@param kernel the kernel to convolve with
@param type
@return | [
"2d",
"convolution",
"(",
"aka",
"the",
"last",
"2",
"dimensions"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java#L355-L357 |
jhunters/jprotobuf | src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java | MiniTemplator.setVariableEsc | public void setVariableEsc(String variableName, String variableValue, boolean isOptional)
throws VariableNotDefinedException {
"""
Sets a template variable to an escaped value.
<p>
Convenience method for:
<code>setVariable (variableName, MiniTemplator.escapeHtml(variableValue), isOptional)</code>
@param variableName the name of the variable to be set.
@param variableValue the new value of the variable. May be <code>null</code>. Special HTML/XML characters are
escaped.
@param isOptional specifies whether an exception should be thrown when the variable does not exist in the
template. If <code>isOptional</code> is <code>false</code> and the variable does not exist, an
exception is thrown.
@throws VariableNotDefinedException when no variable with the specified name exists in the template and
<code>isOptional</code> is <code>false</code>.
@see #setVariable(String, String, boolean)
@see #escapeHtml(String)
"""
setVariable(variableName, escapeHtml(variableValue), isOptional);
} | java | public void setVariableEsc(String variableName, String variableValue, boolean isOptional)
throws VariableNotDefinedException {
setVariable(variableName, escapeHtml(variableValue), isOptional);
} | [
"public",
"void",
"setVariableEsc",
"(",
"String",
"variableName",
",",
"String",
"variableValue",
",",
"boolean",
"isOptional",
")",
"throws",
"VariableNotDefinedException",
"{",
"setVariable",
"(",
"variableName",
",",
"escapeHtml",
"(",
"variableValue",
")",
",",
"isOptional",
")",
";",
"}"
] | Sets a template variable to an escaped value.
<p>
Convenience method for:
<code>setVariable (variableName, MiniTemplator.escapeHtml(variableValue), isOptional)</code>
@param variableName the name of the variable to be set.
@param variableValue the new value of the variable. May be <code>null</code>. Special HTML/XML characters are
escaped.
@param isOptional specifies whether an exception should be thrown when the variable does not exist in the
template. If <code>isOptional</code> is <code>false</code> and the variable does not exist, an
exception is thrown.
@throws VariableNotDefinedException when no variable with the specified name exists in the template and
<code>isOptional</code> is <code>false</code>.
@see #setVariable(String, String, boolean)
@see #escapeHtml(String) | [
"Sets",
"a",
"template",
"variable",
"to",
"an",
"escaped",
"value",
".",
"<p",
">",
"Convenience",
"method",
"for",
":",
"<code",
">",
"setVariable",
"(",
"variableName",
"MiniTemplator",
".",
"escapeHtml",
"(",
"variableValue",
")",
"isOptional",
")",
"<",
"/",
"code",
">"
] | train | https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java#L451-L454 |
apache/predictionio-sdk-java | client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java | EventClient.deleteUser | public String deleteUser(String uid)
throws ExecutionException, InterruptedException, IOException {
"""
Deletes a user. Event time is recorded as the time when the function is called.
@param uid ID of the user
@return ID of this event
"""
return deleteUser(uid, new DateTime());
} | java | public String deleteUser(String uid)
throws ExecutionException, InterruptedException, IOException {
return deleteUser(uid, new DateTime());
} | [
"public",
"String",
"deleteUser",
"(",
"String",
"uid",
")",
"throws",
"ExecutionException",
",",
"InterruptedException",
",",
"IOException",
"{",
"return",
"deleteUser",
"(",
"uid",
",",
"new",
"DateTime",
"(",
")",
")",
";",
"}"
] | Deletes a user. Event time is recorded as the time when the function is called.
@param uid ID of the user
@return ID of this event | [
"Deletes",
"a",
"user",
".",
"Event",
"time",
"is",
"recorded",
"as",
"the",
"time",
"when",
"the",
"function",
"is",
"called",
"."
] | train | https://github.com/apache/predictionio-sdk-java/blob/16052c96b136340c175c3f9c2692e720850df219/client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java#L439-L442 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509Key.java | X509Key.encode | static void encode(DerOutputStream out, AlgorithmId algid, BitArray key)
throws IOException {
"""
/*
Produce SubjectPublicKey encoding from algorithm id and key material.
"""
DerOutputStream tmp = new DerOutputStream();
algid.encode(tmp);
tmp.putUnalignedBitString(key);
out.write(DerValue.tag_Sequence, tmp);
} | java | static void encode(DerOutputStream out, AlgorithmId algid, BitArray key)
throws IOException {
DerOutputStream tmp = new DerOutputStream();
algid.encode(tmp);
tmp.putUnalignedBitString(key);
out.write(DerValue.tag_Sequence, tmp);
} | [
"static",
"void",
"encode",
"(",
"DerOutputStream",
"out",
",",
"AlgorithmId",
"algid",
",",
"BitArray",
"key",
")",
"throws",
"IOException",
"{",
"DerOutputStream",
"tmp",
"=",
"new",
"DerOutputStream",
"(",
")",
";",
"algid",
".",
"encode",
"(",
"tmp",
")",
";",
"tmp",
".",
"putUnalignedBitString",
"(",
"key",
")",
";",
"out",
".",
"write",
"(",
"DerValue",
".",
"tag_Sequence",
",",
"tmp",
")",
";",
"}"
] | /*
Produce SubjectPublicKey encoding from algorithm id and key material. | [
"/",
"*",
"Produce",
"SubjectPublicKey",
"encoding",
"from",
"algorithm",
"id",
"and",
"key",
"material",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509Key.java#L470-L476 |
apigee/usergrid-java-sdk | src/main/java/org/usergrid/java/client/Client.java | Client.queryEntitiesRequest | public Query queryEntitiesRequest(HttpMethod method,
Map<String, Object> params, Object data, String... segments) {
"""
Perform a query request and return a query object. The Query object
provides a simple way of dealing with result sets that need to be
iterated or paged through.
@param method
@param params
@param data
@param segments
@return
"""
ApiResponse response = apiRequest(method, params, data, segments);
return new EntityQuery(response, method, params, data, segments);
} | java | public Query queryEntitiesRequest(HttpMethod method,
Map<String, Object> params, Object data, String... segments) {
ApiResponse response = apiRequest(method, params, data, segments);
return new EntityQuery(response, method, params, data, segments);
} | [
"public",
"Query",
"queryEntitiesRequest",
"(",
"HttpMethod",
"method",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"params",
",",
"Object",
"data",
",",
"String",
"...",
"segments",
")",
"{",
"ApiResponse",
"response",
"=",
"apiRequest",
"(",
"method",
",",
"params",
",",
"data",
",",
"segments",
")",
";",
"return",
"new",
"EntityQuery",
"(",
"response",
",",
"method",
",",
"params",
",",
"data",
",",
"segments",
")",
";",
"}"
] | Perform a query request and return a query object. The Query object
provides a simple way of dealing with result sets that need to be
iterated or paged through.
@param method
@param params
@param data
@param segments
@return | [
"Perform",
"a",
"query",
"request",
"and",
"return",
"a",
"query",
"object",
".",
"The",
"Query",
"object",
"provides",
"a",
"simple",
"way",
"of",
"dealing",
"with",
"result",
"sets",
"that",
"need",
"to",
"be",
"iterated",
"or",
"paged",
"through",
"."
] | train | https://github.com/apigee/usergrid-java-sdk/blob/6202745f184754defff13962dfc3d830bc7d8c63/src/main/java/org/usergrid/java/client/Client.java#L805-L809 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java | EJSContainer.getEJBLocalHome | public EJBLocalHome getEJBLocalHome(J2EEName name) throws ContainerEJBException {
"""
Returns a reference to the EJBLocalHome associated with a specified J2EEName.
@param name is the J2EEName of the EJB's local home object.
@return reference to EJBLocalHome for J2EEName specified by name parameter.
@exception ContainerEJBException if any Throwable occurs that
prevented this method from return EJBLocalHome. Use the getCause
method to recover the Throwable that occured.
"""
try {
EJSWrapperCommon wrapperCommon = getHomeWrapperCommon(name);
return (EJBLocalHome) wrapperCommon.getLocalObject(); // d188404
} catch (Throwable t) {
FFDCFilter.processException(t, CLASS_NAME + ".getEJBLocalHome", "2993", this);
throw new ContainerEJBException("Could not get EJBLocalHome", t);
}
} | java | public EJBLocalHome getEJBLocalHome(J2EEName name) throws ContainerEJBException {
try {
EJSWrapperCommon wrapperCommon = getHomeWrapperCommon(name);
return (EJBLocalHome) wrapperCommon.getLocalObject(); // d188404
} catch (Throwable t) {
FFDCFilter.processException(t, CLASS_NAME + ".getEJBLocalHome", "2993", this);
throw new ContainerEJBException("Could not get EJBLocalHome", t);
}
} | [
"public",
"EJBLocalHome",
"getEJBLocalHome",
"(",
"J2EEName",
"name",
")",
"throws",
"ContainerEJBException",
"{",
"try",
"{",
"EJSWrapperCommon",
"wrapperCommon",
"=",
"getHomeWrapperCommon",
"(",
"name",
")",
";",
"return",
"(",
"EJBLocalHome",
")",
"wrapperCommon",
".",
"getLocalObject",
"(",
")",
";",
"// d188404",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"FFDCFilter",
".",
"processException",
"(",
"t",
",",
"CLASS_NAME",
"+",
"\".getEJBLocalHome\"",
",",
"\"2993\"",
",",
"this",
")",
";",
"throw",
"new",
"ContainerEJBException",
"(",
"\"Could not get EJBLocalHome\"",
",",
"t",
")",
";",
"}",
"}"
] | Returns a reference to the EJBLocalHome associated with a specified J2EEName.
@param name is the J2EEName of the EJB's local home object.
@return reference to EJBLocalHome for J2EEName specified by name parameter.
@exception ContainerEJBException if any Throwable occurs that
prevented this method from return EJBLocalHome. Use the getCause
method to recover the Throwable that occured. | [
"Returns",
"a",
"reference",
"to",
"the",
"EJBLocalHome",
"associated",
"with",
"a",
"specified",
"J2EEName",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java#L4546-L4555 |
OpenCompare/OpenCompare | org.opencompare/pcmdata-importers/src/main/java/data_omdb/OMDBCSVProductFactory.java | OMDBCSVProductFactory.mkCSVProduct | public String mkCSVProduct(OMDBProduct p, OMDBMediaType t) {
"""
A CSV representation of "Product" (in fact a CSV line)
the CSV representation depends on OMDB type
@param p
@param t
@return
"""
if (t.equals(OMDBMediaType.MOVIE))
return mkCSVProductMovie(p) ;
if (t.equals(OMDBMediaType.SERIES))
return mkCSVProductSerie(p) ;
if (t.equals(OMDBMediaType.EPISODE))
return mkCSVProductEpisode(p);
return null;
} | java | public String mkCSVProduct(OMDBProduct p, OMDBMediaType t) {
if (t.equals(OMDBMediaType.MOVIE))
return mkCSVProductMovie(p) ;
if (t.equals(OMDBMediaType.SERIES))
return mkCSVProductSerie(p) ;
if (t.equals(OMDBMediaType.EPISODE))
return mkCSVProductEpisode(p);
return null;
} | [
"public",
"String",
"mkCSVProduct",
"(",
"OMDBProduct",
"p",
",",
"OMDBMediaType",
"t",
")",
"{",
"if",
"(",
"t",
".",
"equals",
"(",
"OMDBMediaType",
".",
"MOVIE",
")",
")",
"return",
"mkCSVProductMovie",
"(",
"p",
")",
";",
"if",
"(",
"t",
".",
"equals",
"(",
"OMDBMediaType",
".",
"SERIES",
")",
")",
"return",
"mkCSVProductSerie",
"(",
"p",
")",
";",
"if",
"(",
"t",
".",
"equals",
"(",
"OMDBMediaType",
".",
"EPISODE",
")",
")",
"return",
"mkCSVProductEpisode",
"(",
"p",
")",
";",
"return",
"null",
";",
"}"
] | A CSV representation of "Product" (in fact a CSV line)
the CSV representation depends on OMDB type
@param p
@param t
@return | [
"A",
"CSV",
"representation",
"of",
"Product",
"(",
"in",
"fact",
"a",
"CSV",
"line",
")",
"the",
"CSV",
"representation",
"depends",
"on",
"OMDB",
"type"
] | train | https://github.com/OpenCompare/OpenCompare/blob/6cd776466b375cb8ecca08fcd94e573d65e20b14/org.opencompare/pcmdata-importers/src/main/java/data_omdb/OMDBCSVProductFactory.java#L33-L45 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/distance/Distance.java | Distance.Chessboard | public static double Chessboard(double[] x, double[] y) {
"""
Gets the Chessboard distance between two points.
@param x A point in space.
@param y A point in space.
@return The Chessboard distance between x and y.
"""
double d = 0;
for (int i = 0; i < x.length; i++) {
d = Math.max(d, x[i] - y[i]);
}
return d;
} | java | public static double Chessboard(double[] x, double[] y) {
double d = 0;
for (int i = 0; i < x.length; i++) {
d = Math.max(d, x[i] - y[i]);
}
return d;
} | [
"public",
"static",
"double",
"Chessboard",
"(",
"double",
"[",
"]",
"x",
",",
"double",
"[",
"]",
"y",
")",
"{",
"double",
"d",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"i",
"++",
")",
"{",
"d",
"=",
"Math",
".",
"max",
"(",
"d",
",",
"x",
"[",
"i",
"]",
"-",
"y",
"[",
"i",
"]",
")",
";",
"}",
"return",
"d",
";",
"}"
] | Gets the Chessboard distance between two points.
@param x A point in space.
@param y A point in space.
@return The Chessboard distance between x and y. | [
"Gets",
"the",
"Chessboard",
"distance",
"between",
"two",
"points",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L221-L229 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java | ComputeNodeOperations.deleteComputeNodeUser | public void deleteComputeNodeUser(String poolId, String nodeId, String userName) throws BatchErrorException, IOException {
"""
Deletes the specified user account from the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node where the user account will be deleted.
@param userName The name of the user account to be deleted.
@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.
"""
deleteComputeNodeUser(poolId, nodeId, userName, null);
} | java | public void deleteComputeNodeUser(String poolId, String nodeId, String userName) throws BatchErrorException, IOException {
deleteComputeNodeUser(poolId, nodeId, userName, null);
} | [
"public",
"void",
"deleteComputeNodeUser",
"(",
"String",
"poolId",
",",
"String",
"nodeId",
",",
"String",
"userName",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"deleteComputeNodeUser",
"(",
"poolId",
",",
"nodeId",
",",
"userName",
",",
"null",
")",
";",
"}"
] | Deletes the specified user account from the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node where the user account will be deleted.
@param userName The name of the user account to be deleted.
@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. | [
"Deletes",
"the",
"specified",
"user",
"account",
"from",
"the",
"specified",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L113-L115 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/csv/internal/CsvParser.java | CsvParser.isNextCharacterEscapable | protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i) {
"""
precondition: the current character is an escape
@param nextLine the current line
@param inQuotes true if the current context is quoted
@param i current index in line
@return true if the following character is a quote
"""
return inQuotes // we are in quotes, therefore there can be escaped
// quotes in here.
&& nextLine.length() > (i + 1) // there is indeed another
// character to check.
&& (format.isDelimiter(nextLine.charAt(i + 1)) || format.isEscape(nextLine.charAt(i + 1)));
} | java | protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i) {
return inQuotes // we are in quotes, therefore there can be escaped
// quotes in here.
&& nextLine.length() > (i + 1) // there is indeed another
// character to check.
&& (format.isDelimiter(nextLine.charAt(i + 1)) || format.isEscape(nextLine.charAt(i + 1)));
} | [
"protected",
"boolean",
"isNextCharacterEscapable",
"(",
"String",
"nextLine",
",",
"boolean",
"inQuotes",
",",
"int",
"i",
")",
"{",
"return",
"inQuotes",
"// we are in quotes, therefore there can be escaped",
"// quotes in here.",
"&&",
"nextLine",
".",
"length",
"(",
")",
">",
"(",
"i",
"+",
"1",
")",
"// there is indeed another",
"// character to check.",
"&&",
"(",
"format",
".",
"isDelimiter",
"(",
"nextLine",
".",
"charAt",
"(",
"i",
"+",
"1",
")",
")",
"||",
"format",
".",
"isEscape",
"(",
"nextLine",
".",
"charAt",
"(",
"i",
"+",
"1",
")",
")",
")",
";",
"}"
] | precondition: the current character is an escape
@param nextLine the current line
@param inQuotes true if the current context is quoted
@param i current index in line
@return true if the following character is a quote | [
"precondition",
":",
"the",
"current",
"character",
"is",
"an",
"escape"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/csv/internal/CsvParser.java#L218-L224 |
ironjacamar/ironjacamar | web/src/main/java/org/ironjacamar/web/console/HtmlAdaptorServlet.java | HtmlAdaptorServlet.inspectMBean | private void inspectMBean(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
"""
Display a MBeans attributes and operations
@param request The HTTP request
@param response The HTTP response
@exception ServletException Thrown if an error occurs
@exception IOException Thrown if an I/O error occurs
"""
String name = request.getParameter("name");
if (trace)
log.trace("inspectMBean, name=" + name);
try
{
MBeanData data = getMBeanData(name);
request.setAttribute("mbeanData", data);
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/inspectmbean.jsp");
rd.forward(request, response);
}
catch (Exception e)
{
throw new ServletException("Failed to get MBean data", e);
}
} | java | private void inspectMBean(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("name");
if (trace)
log.trace("inspectMBean, name=" + name);
try
{
MBeanData data = getMBeanData(name);
request.setAttribute("mbeanData", data);
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/inspectmbean.jsp");
rd.forward(request, response);
}
catch (Exception e)
{
throw new ServletException("Failed to get MBean data", e);
}
} | [
"private",
"void",
"inspectMBean",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"String",
"name",
"=",
"request",
".",
"getParameter",
"(",
"\"name\"",
")",
";",
"if",
"(",
"trace",
")",
"log",
".",
"trace",
"(",
"\"inspectMBean, name=\"",
"+",
"name",
")",
";",
"try",
"{",
"MBeanData",
"data",
"=",
"getMBeanData",
"(",
"name",
")",
";",
"request",
".",
"setAttribute",
"(",
"\"mbeanData\"",
",",
"data",
")",
";",
"RequestDispatcher",
"rd",
"=",
"this",
".",
"getServletContext",
"(",
")",
".",
"getRequestDispatcher",
"(",
"\"/inspectmbean.jsp\"",
")",
";",
"rd",
".",
"forward",
"(",
"request",
",",
"response",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"ServletException",
"(",
"\"Failed to get MBean data\"",
",",
"e",
")",
";",
"}",
"}"
] | Display a MBeans attributes and operations
@param request The HTTP request
@param response The HTTP response
@exception ServletException Thrown if an error occurs
@exception IOException Thrown if an I/O error occurs | [
"Display",
"a",
"MBeans",
"attributes",
"and",
"operations"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/web/src/main/java/org/ironjacamar/web/console/HtmlAdaptorServlet.java#L174-L194 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/WhitelistingApi.java | WhitelistingApi.deleteWhitelistCertificate | public WhitelistEnvelope deleteWhitelistCertificate(String dtid, String cid) throws ApiException {
"""
Delete a whitelist certificate associated with a devicetype.
Delete a whitelist certificate associated with a devicetype.
@param dtid Device Type ID. (required)
@param cid Certificate ID. (required)
@return WhitelistEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<WhitelistEnvelope> resp = deleteWhitelistCertificateWithHttpInfo(dtid, cid);
return resp.getData();
} | java | public WhitelistEnvelope deleteWhitelistCertificate(String dtid, String cid) throws ApiException {
ApiResponse<WhitelistEnvelope> resp = deleteWhitelistCertificateWithHttpInfo(dtid, cid);
return resp.getData();
} | [
"public",
"WhitelistEnvelope",
"deleteWhitelistCertificate",
"(",
"String",
"dtid",
",",
"String",
"cid",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"WhitelistEnvelope",
">",
"resp",
"=",
"deleteWhitelistCertificateWithHttpInfo",
"(",
"dtid",
",",
"cid",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Delete a whitelist certificate associated with a devicetype.
Delete a whitelist certificate associated with a devicetype.
@param dtid Device Type ID. (required)
@param cid Certificate ID. (required)
@return WhitelistEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Delete",
"a",
"whitelist",
"certificate",
"associated",
"with",
"a",
"devicetype",
".",
"Delete",
"a",
"whitelist",
"certificate",
"associated",
"with",
"a",
"devicetype",
"."
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/WhitelistingApi.java#L265-L268 |
headius/invokebinder | src/main/java/com/headius/invokebinder/SmartBinder.java | SmartBinder.castVirtual | public SmartBinder castVirtual(Class<?> returnType, Class<?> firstArg, Class<?>... restArgs) {
"""
Cast the incoming arguments to the return, first argument type, and
remaining argument types. Provide for convenience when dealing with
virtual method argument lists, which frequently omit the target
object.
@param returnType the return type for the casted signature
@param firstArg the type of the first argument for the casted signature
@param restArgs the types of the remaining arguments for the casted signature
@return a new SmartBinder with the cast applied.
"""
return new SmartBinder(this, new Signature(returnType, firstArg, restArgs, signature().argNames()), binder.castVirtual(returnType, firstArg, restArgs));
} | java | public SmartBinder castVirtual(Class<?> returnType, Class<?> firstArg, Class<?>... restArgs) {
return new SmartBinder(this, new Signature(returnType, firstArg, restArgs, signature().argNames()), binder.castVirtual(returnType, firstArg, restArgs));
} | [
"public",
"SmartBinder",
"castVirtual",
"(",
"Class",
"<",
"?",
">",
"returnType",
",",
"Class",
"<",
"?",
">",
"firstArg",
",",
"Class",
"<",
"?",
">",
"...",
"restArgs",
")",
"{",
"return",
"new",
"SmartBinder",
"(",
"this",
",",
"new",
"Signature",
"(",
"returnType",
",",
"firstArg",
",",
"restArgs",
",",
"signature",
"(",
")",
".",
"argNames",
"(",
")",
")",
",",
"binder",
".",
"castVirtual",
"(",
"returnType",
",",
"firstArg",
",",
"restArgs",
")",
")",
";",
"}"
] | Cast the incoming arguments to the return, first argument type, and
remaining argument types. Provide for convenience when dealing with
virtual method argument lists, which frequently omit the target
object.
@param returnType the return type for the casted signature
@param firstArg the type of the first argument for the casted signature
@param restArgs the types of the remaining arguments for the casted signature
@return a new SmartBinder with the cast applied. | [
"Cast",
"the",
"incoming",
"arguments",
"to",
"the",
"return",
"first",
"argument",
"type",
"and",
"remaining",
"argument",
"types",
".",
"Provide",
"for",
"convenience",
"when",
"dealing",
"with",
"virtual",
"method",
"argument",
"lists",
"which",
"frequently",
"omit",
"the",
"target",
"object",
"."
] | train | https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/SmartBinder.java#L895-L897 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.setProgressBar | public void setProgressBar(ProgressBar progressBar, int progress) {
"""
Sets the progress of the specified ProgressBar. Examples of ProgressBars are: {@link android.widget.SeekBar} and {@link android.widget.RatingBar}.
@param progressBar the {@link ProgressBar}
@param progress the progress to set the {@link ProgressBar}
"""
if(config.commandLogging){
Log.d(config.commandLoggingTag, "setProgressBar("+progressBar+", "+progress+")");
}
progressBar = (ProgressBar) waiter.waitForView(progressBar, Timeout.getSmallTimeout());
setter.setProgressBar(progressBar, progress);
} | java | public void setProgressBar(ProgressBar progressBar, int progress){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "setProgressBar("+progressBar+", "+progress+")");
}
progressBar = (ProgressBar) waiter.waitForView(progressBar, Timeout.getSmallTimeout());
setter.setProgressBar(progressBar, progress);
} | [
"public",
"void",
"setProgressBar",
"(",
"ProgressBar",
"progressBar",
",",
"int",
"progress",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"setProgressBar(\"",
"+",
"progressBar",
"+",
"\", \"",
"+",
"progress",
"+",
"\")\"",
")",
";",
"}",
"progressBar",
"=",
"(",
"ProgressBar",
")",
"waiter",
".",
"waitForView",
"(",
"progressBar",
",",
"Timeout",
".",
"getSmallTimeout",
"(",
")",
")",
";",
"setter",
".",
"setProgressBar",
"(",
"progressBar",
",",
"progress",
")",
";",
"}"
] | Sets the progress of the specified ProgressBar. Examples of ProgressBars are: {@link android.widget.SeekBar} and {@link android.widget.RatingBar}.
@param progressBar the {@link ProgressBar}
@param progress the progress to set the {@link ProgressBar} | [
"Sets",
"the",
"progress",
"of",
"the",
"specified",
"ProgressBar",
".",
"Examples",
"of",
"ProgressBars",
"are",
":",
"{",
"@link",
"android",
".",
"widget",
".",
"SeekBar",
"}",
"and",
"{",
"@link",
"android",
".",
"widget",
".",
"RatingBar",
"}",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L2602-L2609 |
martinwithaar/Encryptor4j | src/main/java/org/encryptor4j/util/FileEncryptor.java | FileEncryptor.copy | private void copy(InputStream is, OutputStream os) throws IOException {
"""
<p>Reads data from the <code>InputStream</code> and writes it to the <code>OutputStream</code>.</p>
@param is the input stream
@param os the output stream
@throws IOException
"""
byte[] buffer = new byte[bufferSize];
int nRead;
while((nRead = is.read(buffer)) != -1) {
os.write(buffer, 0, nRead);
}
os.flush();
} | java | private void copy(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[bufferSize];
int nRead;
while((nRead = is.read(buffer)) != -1) {
os.write(buffer, 0, nRead);
}
os.flush();
} | [
"private",
"void",
"copy",
"(",
"InputStream",
"is",
",",
"OutputStream",
"os",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"bufferSize",
"]",
";",
"int",
"nRead",
";",
"while",
"(",
"(",
"nRead",
"=",
"is",
".",
"read",
"(",
"buffer",
")",
")",
"!=",
"-",
"1",
")",
"{",
"os",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"nRead",
")",
";",
"}",
"os",
".",
"flush",
"(",
")",
";",
"}"
] | <p>Reads data from the <code>InputStream</code> and writes it to the <code>OutputStream</code>.</p>
@param is the input stream
@param os the output stream
@throws IOException | [
"<p",
">",
"Reads",
"data",
"from",
"the",
"<code",
">",
"InputStream<",
"/",
"code",
">",
"and",
"writes",
"it",
"to",
"the",
"<code",
">",
"OutputStream<",
"/",
"code",
">",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/martinwithaar/Encryptor4j/blob/8c31d84d9136309f59d810323ed68d902b9bac55/src/main/java/org/encryptor4j/util/FileEncryptor.java#L140-L147 |
zxing/zxing | core/src/main/java/com/google/zxing/common/BitArray.java | BitArray.setRange | public void setRange(int start, int end) {
"""
Sets a range of bits.
@param start start of range, inclusive.
@param end end of range, exclusive
"""
if (end < start || start < 0 || end > size) {
throw new IllegalArgumentException();
}
if (end == start) {
return;
}
end--; // will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start / 32;
int lastInt = end / 32;
for (int i = firstInt; i <= lastInt; i++) {
int firstBit = i > firstInt ? 0 : start & 0x1F;
int lastBit = i < lastInt ? 31 : end & 0x1F;
// Ones from firstBit to lastBit, inclusive
int mask = (2 << lastBit) - (1 << firstBit);
bits[i] |= mask;
}
} | java | public void setRange(int start, int end) {
if (end < start || start < 0 || end > size) {
throw new IllegalArgumentException();
}
if (end == start) {
return;
}
end--; // will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start / 32;
int lastInt = end / 32;
for (int i = firstInt; i <= lastInt; i++) {
int firstBit = i > firstInt ? 0 : start & 0x1F;
int lastBit = i < lastInt ? 31 : end & 0x1F;
// Ones from firstBit to lastBit, inclusive
int mask = (2 << lastBit) - (1 << firstBit);
bits[i] |= mask;
}
} | [
"public",
"void",
"setRange",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"end",
"<",
"start",
"||",
"start",
"<",
"0",
"||",
"end",
">",
"size",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"if",
"(",
"end",
"==",
"start",
")",
"{",
"return",
";",
"}",
"end",
"--",
";",
"// will be easier to treat this as the last actually set bit -- inclusive",
"int",
"firstInt",
"=",
"start",
"/",
"32",
";",
"int",
"lastInt",
"=",
"end",
"/",
"32",
";",
"for",
"(",
"int",
"i",
"=",
"firstInt",
";",
"i",
"<=",
"lastInt",
";",
"i",
"++",
")",
"{",
"int",
"firstBit",
"=",
"i",
">",
"firstInt",
"?",
"0",
":",
"start",
"&",
"0x1F",
";",
"int",
"lastBit",
"=",
"i",
"<",
"lastInt",
"?",
"31",
":",
"end",
"&",
"0x1F",
";",
"// Ones from firstBit to lastBit, inclusive",
"int",
"mask",
"=",
"(",
"2",
"<<",
"lastBit",
")",
"-",
"(",
"1",
"<<",
"firstBit",
")",
";",
"bits",
"[",
"i",
"]",
"|=",
"mask",
";",
"}",
"}"
] | Sets a range of bits.
@param start start of range, inclusive.
@param end end of range, exclusive | [
"Sets",
"a",
"range",
"of",
"bits",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/common/BitArray.java#L153-L170 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-core/src/main/java/org/deeplearning4j/evaluation/EvaluationTools.java | EvaluationTools.exportRocChartsToHtmlFile | public static void exportRocChartsToHtmlFile(ROCMultiClass roc, File file) throws Exception {
"""
Given a {@link ROCMultiClass} chart, export the ROC chart and precision vs. recall charts to a stand-alone HTML file
@param roc ROC to export
@param file File to export to
"""
String rocAsHtml = rocChartToHtml(roc);
FileUtils.writeStringToFile(file, rocAsHtml, StandardCharsets.UTF_8);
} | java | public static void exportRocChartsToHtmlFile(ROCMultiClass roc, File file) throws Exception {
String rocAsHtml = rocChartToHtml(roc);
FileUtils.writeStringToFile(file, rocAsHtml, StandardCharsets.UTF_8);
} | [
"public",
"static",
"void",
"exportRocChartsToHtmlFile",
"(",
"ROCMultiClass",
"roc",
",",
"File",
"file",
")",
"throws",
"Exception",
"{",
"String",
"rocAsHtml",
"=",
"rocChartToHtml",
"(",
"roc",
")",
";",
"FileUtils",
".",
"writeStringToFile",
"(",
"file",
",",
"rocAsHtml",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"}"
] | Given a {@link ROCMultiClass} chart, export the ROC chart and precision vs. recall charts to a stand-alone HTML file
@param roc ROC to export
@param file File to export to | [
"Given",
"a",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-core/src/main/java/org/deeplearning4j/evaluation/EvaluationTools.java#L133-L136 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/ServerBuilder.java | ServerBuilder.gracefulShutdownTimeout | public ServerBuilder gracefulShutdownTimeout(long quietPeriodMillis, long timeoutMillis) {
"""
Sets the amount of time to wait after calling {@link Server#stop()} for
requests to go away before actually shutting down.
@param quietPeriodMillis the number of milliseconds to wait for active
requests to go end before shutting down. 0 means the server will
stop right away without waiting.
@param timeoutMillis the number of milliseconds to wait before shutting
down the server regardless of active requests. This should be set to
a time greater than {@code quietPeriodMillis} to ensure the server
shuts down even if there is a stuck request.
"""
return gracefulShutdownTimeout(
Duration.ofMillis(quietPeriodMillis), Duration.ofMillis(timeoutMillis));
} | java | public ServerBuilder gracefulShutdownTimeout(long quietPeriodMillis, long timeoutMillis) {
return gracefulShutdownTimeout(
Duration.ofMillis(quietPeriodMillis), Duration.ofMillis(timeoutMillis));
} | [
"public",
"ServerBuilder",
"gracefulShutdownTimeout",
"(",
"long",
"quietPeriodMillis",
",",
"long",
"timeoutMillis",
")",
"{",
"return",
"gracefulShutdownTimeout",
"(",
"Duration",
".",
"ofMillis",
"(",
"quietPeriodMillis",
")",
",",
"Duration",
".",
"ofMillis",
"(",
"timeoutMillis",
")",
")",
";",
"}"
] | Sets the amount of time to wait after calling {@link Server#stop()} for
requests to go away before actually shutting down.
@param quietPeriodMillis the number of milliseconds to wait for active
requests to go end before shutting down. 0 means the server will
stop right away without waiting.
@param timeoutMillis the number of milliseconds to wait before shutting
down the server regardless of active requests. This should be set to
a time greater than {@code quietPeriodMillis} to ensure the server
shuts down even if there is a stuck request. | [
"Sets",
"the",
"amount",
"of",
"time",
"to",
"wait",
"after",
"calling",
"{",
"@link",
"Server#stop",
"()",
"}",
"for",
"requests",
"to",
"go",
"away",
"before",
"actually",
"shutting",
"down",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/ServerBuilder.java#L622-L625 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/VoiceApi.java | VoiceApi.resumeRecording | public ApiSuccessResponse resumeRecording(String id, ResumeRecordingBody resumeRecordingBody) throws ApiException {
"""
Resume recording a call
Resume recording the specified call.
@param id The connection ID of the call. (required)
@param resumeRecordingBody Request parameters. (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<ApiSuccessResponse> resp = resumeRecordingWithHttpInfo(id, resumeRecordingBody);
return resp.getData();
} | java | public ApiSuccessResponse resumeRecording(String id, ResumeRecordingBody resumeRecordingBody) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = resumeRecordingWithHttpInfo(id, resumeRecordingBody);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"resumeRecording",
"(",
"String",
"id",
",",
"ResumeRecordingBody",
"resumeRecordingBody",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"resumeRecordingWithHttpInfo",
"(",
"id",
",",
"resumeRecordingBody",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Resume recording a call
Resume recording the specified call.
@param id The connection ID of the call. (required)
@param resumeRecordingBody Request parameters. (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Resume",
"recording",
"a",
"call",
"Resume",
"recording",
"the",
"specified",
"call",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L3102-L3105 |
vdmeer/skb-java-base | src/main/java/de/vandermeer/skb/base/shell/SkbShellFactory.java | SkbShellFactory.newShell | public static SkbShell newShell(String id, boolean useConsole) {
"""
Returns a new shell with given identifier and console flag with standard STGroup.
@param id new shell with identifier, uses default if given STG is not valid
@param useConsole flag to use (true) or not to use (false) console, of false then no output will happen
@return new shell
"""
return SkbShellFactory.newShell(id, null, useConsole);
} | java | public static SkbShell newShell(String id, boolean useConsole){
return SkbShellFactory.newShell(id, null, useConsole);
} | [
"public",
"static",
"SkbShell",
"newShell",
"(",
"String",
"id",
",",
"boolean",
"useConsole",
")",
"{",
"return",
"SkbShellFactory",
".",
"newShell",
"(",
"id",
",",
"null",
",",
"useConsole",
")",
";",
"}"
] | Returns a new shell with given identifier and console flag with standard STGroup.
@param id new shell with identifier, uses default if given STG is not valid
@param useConsole flag to use (true) or not to use (false) console, of false then no output will happen
@return new shell | [
"Returns",
"a",
"new",
"shell",
"with",
"given",
"identifier",
"and",
"console",
"flag",
"with",
"standard",
"STGroup",
"."
] | train | https://github.com/vdmeer/skb-java-base/blob/6d845bcc482aa9344d016e80c0c3455aeae13a13/src/main/java/de/vandermeer/skb/base/shell/SkbShellFactory.java#L75-L77 |
foundation-runtime/logging | logging-api/src/main/java/com/cisco/oss/foundation/logging/transactions/TransactionLogger.java | TransactionLogger.getMapAsString | protected static String getMapAsString(Map<String, String> map, String separator) {
"""
Get string representation of the given map:
key:value separator key:value separator ...
@param map
@param separator
@return string representation of the given map
"""
if (map != null && !map.isEmpty()) {
StringBuilder str = new StringBuilder();
boolean isFirst = true;
for (Entry<String, String> entry : map.entrySet() ) {
if (!isFirst) {
str.append(separator);
} else {
isFirst = false;
}
str.append(entry.getKey()).append(":").append(entry.getValue());
}
return str.toString();
}
return null;
} | java | protected static String getMapAsString(Map<String, String> map, String separator) {
if (map != null && !map.isEmpty()) {
StringBuilder str = new StringBuilder();
boolean isFirst = true;
for (Entry<String, String> entry : map.entrySet() ) {
if (!isFirst) {
str.append(separator);
} else {
isFirst = false;
}
str.append(entry.getKey()).append(":").append(entry.getValue());
}
return str.toString();
}
return null;
} | [
"protected",
"static",
"String",
"getMapAsString",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"map",
",",
"String",
"separator",
")",
"{",
"if",
"(",
"map",
"!=",
"null",
"&&",
"!",
"map",
".",
"isEmpty",
"(",
")",
")",
"{",
"StringBuilder",
"str",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"boolean",
"isFirst",
"=",
"true",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"!",
"isFirst",
")",
"{",
"str",
".",
"append",
"(",
"separator",
")",
";",
"}",
"else",
"{",
"isFirst",
"=",
"false",
";",
"}",
"str",
".",
"append",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
".",
"append",
"(",
"\":\"",
")",
".",
"append",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"str",
".",
"toString",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Get string representation of the given map:
key:value separator key:value separator ...
@param map
@param separator
@return string representation of the given map | [
"Get",
"string",
"representation",
"of",
"the",
"given",
"map",
":",
"key",
":",
"value",
"separator",
"key",
":",
"value",
"separator",
"..."
] | train | https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-api/src/main/java/com/cisco/oss/foundation/logging/transactions/TransactionLogger.java#L378-L393 |
jhalterman/concurrentunit | src/main/java/net/jodah/concurrentunit/Waiter.java | Waiter.assertEquals | public void assertEquals(Object expected, Object actual) {
"""
Asserts that the {@code expected} values equals the {@code actual} value
@throws AssertionError when the assertion fails
"""
if (expected == null && actual == null)
return;
if (expected != null && expected.equals(actual))
return;
fail(format(expected, actual));
} | java | public void assertEquals(Object expected, Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && expected.equals(actual))
return;
fail(format(expected, actual));
} | [
"public",
"void",
"assertEquals",
"(",
"Object",
"expected",
",",
"Object",
"actual",
")",
"{",
"if",
"(",
"expected",
"==",
"null",
"&&",
"actual",
"==",
"null",
")",
"return",
";",
"if",
"(",
"expected",
"!=",
"null",
"&&",
"expected",
".",
"equals",
"(",
"actual",
")",
")",
"return",
";",
"fail",
"(",
"format",
"(",
"expected",
",",
"actual",
")",
")",
";",
"}"
] | Asserts that the {@code expected} values equals the {@code actual} value
@throws AssertionError when the assertion fails | [
"Asserts",
"that",
"the",
"{",
"@code",
"expected",
"}",
"values",
"equals",
"the",
"{",
"@code",
"actual",
"}",
"value"
] | train | https://github.com/jhalterman/concurrentunit/blob/403b82537866e5ba598017d874753e12fa7aab10/src/main/java/net/jodah/concurrentunit/Waiter.java#L47-L53 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/event/AbstractEventListener.java | AbstractEventListener.performAction | final void performAction(final AbstractEventQueue eventQueue, final Event<?> event) {
"""
Performs the listener {@code action} method with the specified event
queue and event.
@param eventQueue the specified event
@param event the specified event
@see #action(org.b3log.latke.event.Event)
"""
final Event<T> eventObject = (Event<T>) event;
try {
action(eventObject);
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Event perform failed", e);
} finally { // remove event from event queue
if (eventQueue instanceof SynchronizedEventQueue) {
final SynchronizedEventQueue synchronizedEventQueue = (SynchronizedEventQueue) eventQueue;
synchronizedEventQueue.removeEvent(eventObject);
}
}
} | java | final void performAction(final AbstractEventQueue eventQueue, final Event<?> event) {
final Event<T> eventObject = (Event<T>) event;
try {
action(eventObject);
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Event perform failed", e);
} finally { // remove event from event queue
if (eventQueue instanceof SynchronizedEventQueue) {
final SynchronizedEventQueue synchronizedEventQueue = (SynchronizedEventQueue) eventQueue;
synchronizedEventQueue.removeEvent(eventObject);
}
}
} | [
"final",
"void",
"performAction",
"(",
"final",
"AbstractEventQueue",
"eventQueue",
",",
"final",
"Event",
"<",
"?",
">",
"event",
")",
"{",
"final",
"Event",
"<",
"T",
">",
"eventObject",
"=",
"(",
"Event",
"<",
"T",
">",
")",
"event",
";",
"try",
"{",
"action",
"(",
"eventObject",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARN",
",",
"\"Event perform failed\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"// remove event from event queue",
"if",
"(",
"eventQueue",
"instanceof",
"SynchronizedEventQueue",
")",
"{",
"final",
"SynchronizedEventQueue",
"synchronizedEventQueue",
"=",
"(",
"SynchronizedEventQueue",
")",
"eventQueue",
";",
"synchronizedEventQueue",
".",
"removeEvent",
"(",
"eventObject",
")",
";",
"}",
"}",
"}"
] | Performs the listener {@code action} method with the specified event
queue and event.
@param eventQueue the specified event
@param event the specified event
@see #action(org.b3log.latke.event.Event) | [
"Performs",
"the",
"listener",
"{",
"@code",
"action",
"}",
"method",
"with",
"the",
"specified",
"event",
"queue",
"and",
"event",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/event/AbstractEventListener.java#L50-L64 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/RepositoryFileApi.java | RepositoryFileApi.getFile | public RepositoryFile getFile(Object projectIdOrPath, String filePath, String ref, boolean includeContent) throws GitLabApiException {
"""
Get file from repository. Allows you to receive information about file in repository like name, size, and optionally content.
Note that file content is Base64 encoded.
<pre><code>GitLab Endpoint: GET /projects/:id/repository/files</code></pre>
@param projectIdOrPath the id, path of the project, or a Project instance holding the project ID or path
@param filePath (required) - Full path to the file. Ex. lib/class.rb
@param ref (required) - The name of branch, tag or commit
@param includeContent if true will also fetch file content
@return a RepositoryFile instance with the file info and optionally file content
@throws GitLabApiException if any exception occurs
"""
if (!includeContent) {
return (getFileInfo(projectIdOrPath, filePath, ref));
}
Form form = new Form();
addFormParam(form, "ref", ref, true);
Response response = get(Response.Status.OK, form.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(filePath));
return (response.readEntity(RepositoryFile.class));
} | java | public RepositoryFile getFile(Object projectIdOrPath, String filePath, String ref, boolean includeContent) throws GitLabApiException {
if (!includeContent) {
return (getFileInfo(projectIdOrPath, filePath, ref));
}
Form form = new Form();
addFormParam(form, "ref", ref, true);
Response response = get(Response.Status.OK, form.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(filePath));
return (response.readEntity(RepositoryFile.class));
} | [
"public",
"RepositoryFile",
"getFile",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"filePath",
",",
"String",
"ref",
",",
"boolean",
"includeContent",
")",
"throws",
"GitLabApiException",
"{",
"if",
"(",
"!",
"includeContent",
")",
"{",
"return",
"(",
"getFileInfo",
"(",
"projectIdOrPath",
",",
"filePath",
",",
"ref",
")",
")",
";",
"}",
"Form",
"form",
"=",
"new",
"Form",
"(",
")",
";",
"addFormParam",
"(",
"form",
",",
"\"ref\"",
",",
"ref",
",",
"true",
")",
";",
"Response",
"response",
"=",
"get",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"form",
".",
"asMap",
"(",
")",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"repository\"",
",",
"\"files\"",
",",
"urlEncode",
"(",
"filePath",
")",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"RepositoryFile",
".",
"class",
")",
")",
";",
"}"
] | Get file from repository. Allows you to receive information about file in repository like name, size, and optionally content.
Note that file content is Base64 encoded.
<pre><code>GitLab Endpoint: GET /projects/:id/repository/files</code></pre>
@param projectIdOrPath the id, path of the project, or a Project instance holding the project ID or path
@param filePath (required) - Full path to the file. Ex. lib/class.rb
@param ref (required) - The name of branch, tag or commit
@param includeContent if true will also fetch file content
@return a RepositoryFile instance with the file info and optionally file content
@throws GitLabApiException if any exception occurs | [
"Get",
"file",
"from",
"repository",
".",
"Allows",
"you",
"to",
"receive",
"information",
"about",
"file",
"in",
"repository",
"like",
"name",
"size",
"and",
"optionally",
"content",
".",
"Note",
"that",
"file",
"content",
"is",
"Base64",
"encoded",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryFileApi.java#L154-L164 |
infinispan/infinispan | lock/src/main/java/org/infinispan/lock/impl/lock/RequestExpirationScheduler.java | RequestExpirationScheduler.abortScheduling | public void abortScheduling(String requestId, boolean force) {
"""
Aborts the scheduled request. If force is true, it will abort even if the request is not completed
@param requestId, unique identifier of the request
@param force, force abort
"""
if (trace) {
log.tracef("Request[%s] abort scheduling", requestId);
}
ScheduledRequest scheduledRequest = scheduledRequests.get(requestId);
if (scheduledRequest != null && (scheduledRequest.request.isDone() || force)) {
scheduledRequest.scheduledFuture.cancel(false);
scheduledRequests.remove(requestId);
}
} | java | public void abortScheduling(String requestId, boolean force) {
if (trace) {
log.tracef("Request[%s] abort scheduling", requestId);
}
ScheduledRequest scheduledRequest = scheduledRequests.get(requestId);
if (scheduledRequest != null && (scheduledRequest.request.isDone() || force)) {
scheduledRequest.scheduledFuture.cancel(false);
scheduledRequests.remove(requestId);
}
} | [
"public",
"void",
"abortScheduling",
"(",
"String",
"requestId",
",",
"boolean",
"force",
")",
"{",
"if",
"(",
"trace",
")",
"{",
"log",
".",
"tracef",
"(",
"\"Request[%s] abort scheduling\"",
",",
"requestId",
")",
";",
"}",
"ScheduledRequest",
"scheduledRequest",
"=",
"scheduledRequests",
".",
"get",
"(",
"requestId",
")",
";",
"if",
"(",
"scheduledRequest",
"!=",
"null",
"&&",
"(",
"scheduledRequest",
".",
"request",
".",
"isDone",
"(",
")",
"||",
"force",
")",
")",
"{",
"scheduledRequest",
".",
"scheduledFuture",
".",
"cancel",
"(",
"false",
")",
";",
"scheduledRequests",
".",
"remove",
"(",
"requestId",
")",
";",
"}",
"}"
] | Aborts the scheduled request. If force is true, it will abort even if the request is not completed
@param requestId, unique identifier of the request
@param force, force abort | [
"Aborts",
"the",
"scheduled",
"request",
".",
"If",
"force",
"is",
"true",
"it",
"will",
"abort",
"even",
"if",
"the",
"request",
"is",
"not",
"completed"
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/lock/src/main/java/org/infinispan/lock/impl/lock/RequestExpirationScheduler.java#L99-L108 |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAChangeParameter.java | LPAChangeParameter.changeParameterChild | static void changeParameterChild(Element node, String name, String value) {
"""
Look in the passed-in element for a parameter child element whose value is to be changed to
the passed-in value.
@param node the parent node in which to create the parameter.
@param name the name of the parameter to be created.
@param value the value of the parameter to be created.
"""
if (node != null) {
boolean foundIt = false;
for (Element parm = (Element) node.getFirstChild();
parm != null;
parm = (Element) parm.getNextSibling()) {
Attr att = parm.getAttributeNode(Constants.ATT_NAME);
if (att != null && att.getValue().equals(name)) {
parm.setAttribute(Constants.ATT_VALUE, value);
foundIt = true;
break;
}
}
if (!foundIt) // if didn't find it add a new one
LPAAddParameter.addParameterChild(node, name, value);
}
} | java | static void changeParameterChild(Element node, String name, String value) {
if (node != null) {
boolean foundIt = false;
for (Element parm = (Element) node.getFirstChild();
parm != null;
parm = (Element) parm.getNextSibling()) {
Attr att = parm.getAttributeNode(Constants.ATT_NAME);
if (att != null && att.getValue().equals(name)) {
parm.setAttribute(Constants.ATT_VALUE, value);
foundIt = true;
break;
}
}
if (!foundIt) // if didn't find it add a new one
LPAAddParameter.addParameterChild(node, name, value);
}
} | [
"static",
"void",
"changeParameterChild",
"(",
"Element",
"node",
",",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"node",
"!=",
"null",
")",
"{",
"boolean",
"foundIt",
"=",
"false",
";",
"for",
"(",
"Element",
"parm",
"=",
"(",
"Element",
")",
"node",
".",
"getFirstChild",
"(",
")",
";",
"parm",
"!=",
"null",
";",
"parm",
"=",
"(",
"Element",
")",
"parm",
".",
"getNextSibling",
"(",
")",
")",
"{",
"Attr",
"att",
"=",
"parm",
".",
"getAttributeNode",
"(",
"Constants",
".",
"ATT_NAME",
")",
";",
"if",
"(",
"att",
"!=",
"null",
"&&",
"att",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
"{",
"parm",
".",
"setAttribute",
"(",
"Constants",
".",
"ATT_VALUE",
",",
"value",
")",
";",
"foundIt",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"foundIt",
")",
"// if didn't find it add a new one",
"LPAAddParameter",
".",
"addParameterChild",
"(",
"node",
",",
"name",
",",
"value",
")",
";",
"}",
"}"
] | Look in the passed-in element for a parameter child element whose value is to be changed to
the passed-in value.
@param node the parent node in which to create the parameter.
@param name the name of the parameter to be created.
@param value the value of the parameter to be created. | [
"Look",
"in",
"the",
"passed",
"-",
"in",
"element",
"for",
"a",
"parameter",
"child",
"element",
"whose",
"value",
"is",
"to",
"be",
"changed",
"to",
"the",
"passed",
"-",
"in",
"value",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAChangeParameter.java#L68-L85 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/particles/ParticleIO.java | ParticleIO.loadConfiguredSystem | public static ParticleSystem loadConfiguredSystem(InputStream ref, Color mask)
throws IOException {
"""
Load a set of configured emitters into a single system
@param ref
The stream to read the XML from
@param mask The mask used to make the particle image transparent
@return A configured particle system
@throws IOException
Indicates a failure to find, read or parse the XML file
"""
return loadConfiguredSystem(ref, null, null, mask);
} | java | public static ParticleSystem loadConfiguredSystem(InputStream ref, Color mask)
throws IOException {
return loadConfiguredSystem(ref, null, null, mask);
} | [
"public",
"static",
"ParticleSystem",
"loadConfiguredSystem",
"(",
"InputStream",
"ref",
",",
"Color",
"mask",
")",
"throws",
"IOException",
"{",
"return",
"loadConfiguredSystem",
"(",
"ref",
",",
"null",
",",
"null",
",",
"mask",
")",
";",
"}"
] | Load a set of configured emitters into a single system
@param ref
The stream to read the XML from
@param mask The mask used to make the particle image transparent
@return A configured particle system
@throws IOException
Indicates a failure to find, read or parse the XML file | [
"Load",
"a",
"set",
"of",
"configured",
"emitters",
"into",
"a",
"single",
"system"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/particles/ParticleIO.java#L95-L98 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/CertificatesImpl.java | CertificatesImpl.listNextAsync | public ServiceFuture<List<Certificate>> listNextAsync(final String nextPageLink, final CertificateListNextOptions certificateListNextOptions, final ServiceFuture<List<Certificate>> serviceFuture, final ListOperationCallback<Certificate> serviceCallback) {
"""
Lists all of the certificates that have been added to the specified account.
@param nextPageLink The NextLink from the previous successful call to List operation.
@param certificateListNextOptions Additional parameters for the operation
@param serviceFuture the ServiceFuture object tracking the Retrofit calls
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object
"""
return AzureServiceFuture.fromHeaderPageResponse(
listNextSinglePageAsync(nextPageLink, certificateListNextOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink, certificateListNextOptions);
}
},
serviceCallback);
} | java | public ServiceFuture<List<Certificate>> listNextAsync(final String nextPageLink, final CertificateListNextOptions certificateListNextOptions, final ServiceFuture<List<Certificate>> serviceFuture, final ListOperationCallback<Certificate> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listNextSinglePageAsync(nextPageLink, certificateListNextOptions),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink, certificateListNextOptions);
}
},
serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"Certificate",
">",
">",
"listNextAsync",
"(",
"final",
"String",
"nextPageLink",
",",
"final",
"CertificateListNextOptions",
"certificateListNextOptions",
",",
"final",
"ServiceFuture",
"<",
"List",
"<",
"Certificate",
">",
">",
"serviceFuture",
",",
"final",
"ListOperationCallback",
"<",
"Certificate",
">",
"serviceCallback",
")",
"{",
"return",
"AzureServiceFuture",
".",
"fromHeaderPageResponse",
"(",
"listNextSinglePageAsync",
"(",
"nextPageLink",
",",
"certificateListNextOptions",
")",
",",
"new",
"Func1",
"<",
"String",
",",
"Observable",
"<",
"ServiceResponseWithHeaders",
"<",
"Page",
"<",
"Certificate",
">",
",",
"CertificateListHeaders",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponseWithHeaders",
"<",
"Page",
"<",
"Certificate",
">",
",",
"CertificateListHeaders",
">",
">",
"call",
"(",
"String",
"nextPageLink",
")",
"{",
"return",
"listNextSinglePageAsync",
"(",
"nextPageLink",
",",
"certificateListNextOptions",
")",
";",
"}",
"}",
",",
"serviceCallback",
")",
";",
"}"
] | Lists all of the certificates that have been added to the specified account.
@param nextPageLink The NextLink from the previous successful call to List operation.
@param certificateListNextOptions Additional parameters for the operation
@param serviceFuture the ServiceFuture object tracking the Retrofit calls
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Lists",
"all",
"of",
"the",
"certificates",
"that",
"have",
"been",
"added",
"to",
"the",
"specified",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/CertificatesImpl.java#L1334-L1344 |
wcm-io/wcm-io-handler | media/src/main/java/io/wcm/handler/mediasource/dam/impl/DefaultRenditionHandler.java | DefaultRenditionHandler.addRendition | private void addRendition(Set<RenditionMetadata> candidates, Rendition rendition, MediaArgs mediaArgs) {
"""
adds rendition to the list of candidates, if it should be available for resolving
@param candidates
@param rendition
"""
// ignore AEM-generated thumbnail renditions unless allowed via mediaargs
if (!mediaArgs.isIncludeAssetThumbnails() && AssetRendition.isThumbnailRendition(rendition)) {
return;
}
// ignore AEM-generated web renditions unless allowed via mediaargs
boolean isIncludeAssetWebRenditions = mediaArgs.isIncludeAssetWebRenditions() != null
? mediaArgs.isIncludeAssetWebRenditions()
: true;
if (!isIncludeAssetWebRenditions && AssetRendition.isWebRendition(rendition)) {
return;
}
RenditionMetadata renditionMetadata = createRenditionMetadata(rendition);
candidates.add(renditionMetadata);
} | java | private void addRendition(Set<RenditionMetadata> candidates, Rendition rendition, MediaArgs mediaArgs) {
// ignore AEM-generated thumbnail renditions unless allowed via mediaargs
if (!mediaArgs.isIncludeAssetThumbnails() && AssetRendition.isThumbnailRendition(rendition)) {
return;
}
// ignore AEM-generated web renditions unless allowed via mediaargs
boolean isIncludeAssetWebRenditions = mediaArgs.isIncludeAssetWebRenditions() != null
? mediaArgs.isIncludeAssetWebRenditions()
: true;
if (!isIncludeAssetWebRenditions && AssetRendition.isWebRendition(rendition)) {
return;
}
RenditionMetadata renditionMetadata = createRenditionMetadata(rendition);
candidates.add(renditionMetadata);
} | [
"private",
"void",
"addRendition",
"(",
"Set",
"<",
"RenditionMetadata",
">",
"candidates",
",",
"Rendition",
"rendition",
",",
"MediaArgs",
"mediaArgs",
")",
"{",
"// ignore AEM-generated thumbnail renditions unless allowed via mediaargs",
"if",
"(",
"!",
"mediaArgs",
".",
"isIncludeAssetThumbnails",
"(",
")",
"&&",
"AssetRendition",
".",
"isThumbnailRendition",
"(",
"rendition",
")",
")",
"{",
"return",
";",
"}",
"// ignore AEM-generated web renditions unless allowed via mediaargs",
"boolean",
"isIncludeAssetWebRenditions",
"=",
"mediaArgs",
".",
"isIncludeAssetWebRenditions",
"(",
")",
"!=",
"null",
"?",
"mediaArgs",
".",
"isIncludeAssetWebRenditions",
"(",
")",
":",
"true",
";",
"if",
"(",
"!",
"isIncludeAssetWebRenditions",
"&&",
"AssetRendition",
".",
"isWebRendition",
"(",
"rendition",
")",
")",
"{",
"return",
";",
"}",
"RenditionMetadata",
"renditionMetadata",
"=",
"createRenditionMetadata",
"(",
"rendition",
")",
";",
"candidates",
".",
"add",
"(",
"renditionMetadata",
")",
";",
"}"
] | adds rendition to the list of candidates, if it should be available for resolving
@param candidates
@param rendition | [
"adds",
"rendition",
"to",
"the",
"list",
"of",
"candidates",
"if",
"it",
"should",
"be",
"available",
"for",
"resolving"
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/impl/DefaultRenditionHandler.java#L94-L108 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspDateSeriesBean.java | CmsJspDateSeriesBean.getParentSeries | public CmsJspDateSeriesBean getParentSeries() {
"""
Returns the parent series, if it is present, otherwise <code>null</code>.<p>
@return the parent series, if it is present, otherwise <code>null</code>
"""
if ((m_parentSeries == null) && getIsExtractedDate()) {
CmsObject cms = m_value.getCmsObject();
try {
CmsResource res = cms.readResource(m_seriesDefinition.getParentSeriesId());
CmsJspContentAccessBean content = new CmsJspContentAccessBean(cms, m_value.getLocale(), res);
CmsJspContentAccessValueWrapper value = content.getValue().get(m_value.getPath());
return new CmsJspDateSeriesBean(value, m_locale);
} catch (NullPointerException | CmsException e) {
LOG.warn("Parent series with id " + m_seriesDefinition.getParentSeriesId() + " could not be read.", e);
}
}
return null;
} | java | public CmsJspDateSeriesBean getParentSeries() {
if ((m_parentSeries == null) && getIsExtractedDate()) {
CmsObject cms = m_value.getCmsObject();
try {
CmsResource res = cms.readResource(m_seriesDefinition.getParentSeriesId());
CmsJspContentAccessBean content = new CmsJspContentAccessBean(cms, m_value.getLocale(), res);
CmsJspContentAccessValueWrapper value = content.getValue().get(m_value.getPath());
return new CmsJspDateSeriesBean(value, m_locale);
} catch (NullPointerException | CmsException e) {
LOG.warn("Parent series with id " + m_seriesDefinition.getParentSeriesId() + " could not be read.", e);
}
}
return null;
} | [
"public",
"CmsJspDateSeriesBean",
"getParentSeries",
"(",
")",
"{",
"if",
"(",
"(",
"m_parentSeries",
"==",
"null",
")",
"&&",
"getIsExtractedDate",
"(",
")",
")",
"{",
"CmsObject",
"cms",
"=",
"m_value",
".",
"getCmsObject",
"(",
")",
";",
"try",
"{",
"CmsResource",
"res",
"=",
"cms",
".",
"readResource",
"(",
"m_seriesDefinition",
".",
"getParentSeriesId",
"(",
")",
")",
";",
"CmsJspContentAccessBean",
"content",
"=",
"new",
"CmsJspContentAccessBean",
"(",
"cms",
",",
"m_value",
".",
"getLocale",
"(",
")",
",",
"res",
")",
";",
"CmsJspContentAccessValueWrapper",
"value",
"=",
"content",
".",
"getValue",
"(",
")",
".",
"get",
"(",
"m_value",
".",
"getPath",
"(",
")",
")",
";",
"return",
"new",
"CmsJspDateSeriesBean",
"(",
"value",
",",
"m_locale",
")",
";",
"}",
"catch",
"(",
"NullPointerException",
"|",
"CmsException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Parent series with id \"",
"+",
"m_seriesDefinition",
".",
"getParentSeriesId",
"(",
")",
"+",
"\" could not be read.\"",
",",
"e",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns the parent series, if it is present, otherwise <code>null</code>.<p>
@return the parent series, if it is present, otherwise <code>null</code> | [
"Returns",
"the",
"parent",
"series",
"if",
"it",
"is",
"present",
"otherwise",
"<code",
">",
"null<",
"/",
"code",
">",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspDateSeriesBean.java#L293-L308 |
kaazing/gateway | mina.netty/src/main/java/org/kaazing/mina/netty/util/threadlocal/VicariousThreadLocal.java | VicariousThreadLocal.callWith | public <R> R callWith(T value, java.util.concurrent.Callable<R> doCall) throws Exception {
"""
Executes task with thread-local set to the specified value. The state is restored however the task exits. If
uninitialised before running the task, it will remain so upon exiting. Setting the thread-local within the task
does not affect the state after exitign.
@return value returned by {@code doCall}
"""
WeakReference<Holder> ref = local.get();
Holder holder = ref != null ? ref.get() : createHolder();
Object oldValue = holder.value;
holder.value = value;
try {
return doCall.call();
} finally {
holder.value = oldValue;
}
} | java | public <R> R callWith(T value, java.util.concurrent.Callable<R> doCall) throws Exception {
WeakReference<Holder> ref = local.get();
Holder holder = ref != null ? ref.get() : createHolder();
Object oldValue = holder.value;
holder.value = value;
try {
return doCall.call();
} finally {
holder.value = oldValue;
}
} | [
"public",
"<",
"R",
">",
"R",
"callWith",
"(",
"T",
"value",
",",
"java",
".",
"util",
".",
"concurrent",
".",
"Callable",
"<",
"R",
">",
"doCall",
")",
"throws",
"Exception",
"{",
"WeakReference",
"<",
"Holder",
">",
"ref",
"=",
"local",
".",
"get",
"(",
")",
";",
"Holder",
"holder",
"=",
"ref",
"!=",
"null",
"?",
"ref",
".",
"get",
"(",
")",
":",
"createHolder",
"(",
")",
";",
"Object",
"oldValue",
"=",
"holder",
".",
"value",
";",
"holder",
".",
"value",
"=",
"value",
";",
"try",
"{",
"return",
"doCall",
".",
"call",
"(",
")",
";",
"}",
"finally",
"{",
"holder",
".",
"value",
"=",
"oldValue",
";",
"}",
"}"
] | Executes task with thread-local set to the specified value. The state is restored however the task exits. If
uninitialised before running the task, it will remain so upon exiting. Setting the thread-local within the task
does not affect the state after exitign.
@return value returned by {@code doCall} | [
"Executes",
"task",
"with",
"thread",
"-",
"local",
"set",
"to",
"the",
"specified",
"value",
".",
"The",
"state",
"is",
"restored",
"however",
"the",
"task",
"exits",
".",
"If",
"uninitialised",
"before",
"running",
"the",
"task",
"it",
"will",
"remain",
"so",
"upon",
"exiting",
".",
"Setting",
"the",
"thread",
"-",
"local",
"within",
"the",
"task",
"does",
"not",
"affect",
"the",
"state",
"after",
"exitign",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.netty/src/main/java/org/kaazing/mina/netty/util/threadlocal/VicariousThreadLocal.java#L259-L269 |
Alluxio/alluxio | core/client/fs/src/main/java/alluxio/client/block/stream/BlockInStream.java | BlockInStream.createRemoteBlockInStream | public static BlockInStream createRemoteBlockInStream(FileSystemContext context, long blockId,
WorkerNetAddress address, BlockInStreamSource blockSource, long blockSize,
Protocol.OpenUfsBlockOptions ufsOptions) {
"""
Creates a {@link BlockInStream} to read from a specific remote server. Should only be used
in cases where the data source and method of reading is known, ie. worker - worker
communication.
@param context the file system context
@param blockId the block id
@param address the address of the gRPC data server
@param blockSource the source location of the block
@param blockSize the size of the block
@param ufsOptions the ufs read options
@return the {@link BlockInStream} created
"""
long chunkSize =
context.getClusterConf()
.getBytes(PropertyKey.USER_NETWORK_READER_CHUNK_SIZE_BYTES);
ReadRequest readRequest = ReadRequest.newBuilder().setBlockId(blockId)
.setOpenUfsBlockOptions(ufsOptions).setChunkSize(chunkSize).buildPartial();
DataReader.Factory factory = new GrpcDataReader.Factory(context, address,
readRequest.toBuilder().buildPartial());
return new BlockInStream(factory, address, blockSource, blockId, blockSize);
} | java | public static BlockInStream createRemoteBlockInStream(FileSystemContext context, long blockId,
WorkerNetAddress address, BlockInStreamSource blockSource, long blockSize,
Protocol.OpenUfsBlockOptions ufsOptions) {
long chunkSize =
context.getClusterConf()
.getBytes(PropertyKey.USER_NETWORK_READER_CHUNK_SIZE_BYTES);
ReadRequest readRequest = ReadRequest.newBuilder().setBlockId(blockId)
.setOpenUfsBlockOptions(ufsOptions).setChunkSize(chunkSize).buildPartial();
DataReader.Factory factory = new GrpcDataReader.Factory(context, address,
readRequest.toBuilder().buildPartial());
return new BlockInStream(factory, address, blockSource, blockId, blockSize);
} | [
"public",
"static",
"BlockInStream",
"createRemoteBlockInStream",
"(",
"FileSystemContext",
"context",
",",
"long",
"blockId",
",",
"WorkerNetAddress",
"address",
",",
"BlockInStreamSource",
"blockSource",
",",
"long",
"blockSize",
",",
"Protocol",
".",
"OpenUfsBlockOptions",
"ufsOptions",
")",
"{",
"long",
"chunkSize",
"=",
"context",
".",
"getClusterConf",
"(",
")",
".",
"getBytes",
"(",
"PropertyKey",
".",
"USER_NETWORK_READER_CHUNK_SIZE_BYTES",
")",
";",
"ReadRequest",
"readRequest",
"=",
"ReadRequest",
".",
"newBuilder",
"(",
")",
".",
"setBlockId",
"(",
"blockId",
")",
".",
"setOpenUfsBlockOptions",
"(",
"ufsOptions",
")",
".",
"setChunkSize",
"(",
"chunkSize",
")",
".",
"buildPartial",
"(",
")",
";",
"DataReader",
".",
"Factory",
"factory",
"=",
"new",
"GrpcDataReader",
".",
"Factory",
"(",
"context",
",",
"address",
",",
"readRequest",
".",
"toBuilder",
"(",
")",
".",
"buildPartial",
"(",
")",
")",
";",
"return",
"new",
"BlockInStream",
"(",
"factory",
",",
"address",
",",
"blockSource",
",",
"blockId",
",",
"blockSize",
")",
";",
"}"
] | Creates a {@link BlockInStream} to read from a specific remote server. Should only be used
in cases where the data source and method of reading is known, ie. worker - worker
communication.
@param context the file system context
@param blockId the block id
@param address the address of the gRPC data server
@param blockSource the source location of the block
@param blockSize the size of the block
@param ufsOptions the ufs read options
@return the {@link BlockInStream} created | [
"Creates",
"a",
"{",
"@link",
"BlockInStream",
"}",
"to",
"read",
"from",
"a",
"specific",
"remote",
"server",
".",
"Should",
"only",
"be",
"used",
"in",
"cases",
"where",
"the",
"data",
"source",
"and",
"method",
"of",
"reading",
"is",
"known",
"ie",
".",
"worker",
"-",
"worker",
"communication",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/block/stream/BlockInStream.java#L193-L204 |
lessthanoptimal/ejml | examples/src/org/ejml/example/PolynomialRootFinder.java | PolynomialRootFinder.findRoots | public static Complex_F64[] findRoots(double... coefficients) {
"""
<p>
Given a set of polynomial coefficients, compute the roots of the polynomial. Depending on
the polynomial being considered the roots may contain complex number. When complex numbers are
present they will come in pairs of complex conjugates.
</p>
<p>
Coefficients are ordered from least to most significant, e.g: y = c[0] + x*c[1] + x*x*c[2].
</p>
@param coefficients Coefficients of the polynomial.
@return The roots of the polynomial
"""
int N = coefficients.length-1;
// Construct the companion matrix
DMatrixRMaj c = new DMatrixRMaj(N,N);
double a = coefficients[N];
for( int i = 0; i < N; i++ ) {
c.set(i,N-1,-coefficients[i]/a);
}
for( int i = 1; i < N; i++ ) {
c.set(i,i-1,1);
}
// use generalized eigenvalue decomposition to find the roots
EigenDecomposition_F64<DMatrixRMaj> evd = DecompositionFactory_DDRM.eig(N,false);
evd.decompose(c);
Complex_F64[] roots = new Complex_F64[N];
for( int i = 0; i < N; i++ ) {
roots[i] = evd.getEigenvalue(i);
}
return roots;
} | java | public static Complex_F64[] findRoots(double... coefficients) {
int N = coefficients.length-1;
// Construct the companion matrix
DMatrixRMaj c = new DMatrixRMaj(N,N);
double a = coefficients[N];
for( int i = 0; i < N; i++ ) {
c.set(i,N-1,-coefficients[i]/a);
}
for( int i = 1; i < N; i++ ) {
c.set(i,i-1,1);
}
// use generalized eigenvalue decomposition to find the roots
EigenDecomposition_F64<DMatrixRMaj> evd = DecompositionFactory_DDRM.eig(N,false);
evd.decompose(c);
Complex_F64[] roots = new Complex_F64[N];
for( int i = 0; i < N; i++ ) {
roots[i] = evd.getEigenvalue(i);
}
return roots;
} | [
"public",
"static",
"Complex_F64",
"[",
"]",
"findRoots",
"(",
"double",
"...",
"coefficients",
")",
"{",
"int",
"N",
"=",
"coefficients",
".",
"length",
"-",
"1",
";",
"// Construct the companion matrix",
"DMatrixRMaj",
"c",
"=",
"new",
"DMatrixRMaj",
"(",
"N",
",",
"N",
")",
";",
"double",
"a",
"=",
"coefficients",
"[",
"N",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"c",
".",
"set",
"(",
"i",
",",
"N",
"-",
"1",
",",
"-",
"coefficients",
"[",
"i",
"]",
"/",
"a",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"c",
".",
"set",
"(",
"i",
",",
"i",
"-",
"1",
",",
"1",
")",
";",
"}",
"// use generalized eigenvalue decomposition to find the roots",
"EigenDecomposition_F64",
"<",
"DMatrixRMaj",
">",
"evd",
"=",
"DecompositionFactory_DDRM",
".",
"eig",
"(",
"N",
",",
"false",
")",
";",
"evd",
".",
"decompose",
"(",
"c",
")",
";",
"Complex_F64",
"[",
"]",
"roots",
"=",
"new",
"Complex_F64",
"[",
"N",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"roots",
"[",
"i",
"]",
"=",
"evd",
".",
"getEigenvalue",
"(",
"i",
")",
";",
"}",
"return",
"roots",
";",
"}"
] | <p>
Given a set of polynomial coefficients, compute the roots of the polynomial. Depending on
the polynomial being considered the roots may contain complex number. When complex numbers are
present they will come in pairs of complex conjugates.
</p>
<p>
Coefficients are ordered from least to most significant, e.g: y = c[0] + x*c[1] + x*x*c[2].
</p>
@param coefficients Coefficients of the polynomial.
@return The roots of the polynomial | [
"<p",
">",
"Given",
"a",
"set",
"of",
"polynomial",
"coefficients",
"compute",
"the",
"roots",
"of",
"the",
"polynomial",
".",
"Depending",
"on",
"the",
"polynomial",
"being",
"considered",
"the",
"roots",
"may",
"contain",
"complex",
"number",
".",
"When",
"complex",
"numbers",
"are",
"present",
"they",
"will",
"come",
"in",
"pairs",
"of",
"complex",
"conjugates",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/examples/src/org/ejml/example/PolynomialRootFinder.java#L62-L88 |
voldemort/voldemort | src/java/voldemort/utils/ByteUtils.java | ByteUtils.getBytes | public static byte[] getBytes(String string, String encoding) {
"""
Translate the string to bytes using the given encoding
@param string The string to translate
@param encoding The encoding to use
@return The bytes that make up the string
"""
try {
return string.getBytes(encoding);
} catch(UnsupportedEncodingException e) {
throw new IllegalArgumentException(encoding + " is not a known encoding name.", e);
}
} | java | public static byte[] getBytes(String string, String encoding) {
try {
return string.getBytes(encoding);
} catch(UnsupportedEncodingException e) {
throw new IllegalArgumentException(encoding + " is not a known encoding name.", e);
}
} | [
"public",
"static",
"byte",
"[",
"]",
"getBytes",
"(",
"String",
"string",
",",
"String",
"encoding",
")",
"{",
"try",
"{",
"return",
"string",
".",
"getBytes",
"(",
"encoding",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"encoding",
"+",
"\" is not a known encoding name.\"",
",",
"e",
")",
";",
"}",
"}"
] | Translate the string to bytes using the given encoding
@param string The string to translate
@param encoding The encoding to use
@return The bytes that make up the string | [
"Translate",
"the",
"string",
"to",
"bytes",
"using",
"the",
"given",
"encoding"
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ByteUtils.java#L384-L390 |
alipay/sofa-rpc | core/common/src/main/java/com/alipay/sofa/rpc/common/utils/ReflectUtils.java | ReflectUtils.getMethod | public static Method getMethod(Class clazz, String methodName, Class... argsType) {
"""
加载Method方法
@param clazz 类
@param methodName 方法名
@param argsType 参数列表
@return Method对象
@since 5.4.0
"""
try {
return clazz.getMethod(methodName, argsType);
} catch (NoSuchMethodException e) {
throw new SofaRpcRuntimeException(e.getMessage(), e);
}
} | java | public static Method getMethod(Class clazz, String methodName, Class... argsType) {
try {
return clazz.getMethod(methodName, argsType);
} catch (NoSuchMethodException e) {
throw new SofaRpcRuntimeException(e.getMessage(), e);
}
} | [
"public",
"static",
"Method",
"getMethod",
"(",
"Class",
"clazz",
",",
"String",
"methodName",
",",
"Class",
"...",
"argsType",
")",
"{",
"try",
"{",
"return",
"clazz",
".",
"getMethod",
"(",
"methodName",
",",
"argsType",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"SofaRpcRuntimeException",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | 加载Method方法
@param clazz 类
@param methodName 方法名
@param argsType 参数列表
@return Method对象
@since 5.4.0 | [
"加载Method方法"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/utils/ReflectUtils.java#L110-L116 |
GerdHolz/TOVAL | src/de/invation/code/toval/graphic/util/GraphicUtils.java | GraphicUtils.drawArrow | public static void drawArrow(Graphics g, Point from, Point to, double weight) {
"""
Draws an arrow between two given points using the specified weight.<br>
The arrow is leading from point <code>from</code> to point <code>to</code>.
@param g Graphics context
@param from Arrow starting point
@param to Arrow ending point
@param weight Arrow weight
"""
drawArrow(g, from.getX(), from.getY(), to.getX(), to.getY(), weight);
} | java | public static void drawArrow(Graphics g, Point from, Point to, double weight){
drawArrow(g, from.getX(), from.getY(), to.getX(), to.getY(), weight);
} | [
"public",
"static",
"void",
"drawArrow",
"(",
"Graphics",
"g",
",",
"Point",
"from",
",",
"Point",
"to",
",",
"double",
"weight",
")",
"{",
"drawArrow",
"(",
"g",
",",
"from",
".",
"getX",
"(",
")",
",",
"from",
".",
"getY",
"(",
")",
",",
"to",
".",
"getX",
"(",
")",
",",
"to",
".",
"getY",
"(",
")",
",",
"weight",
")",
";",
"}"
] | Draws an arrow between two given points using the specified weight.<br>
The arrow is leading from point <code>from</code> to point <code>to</code>.
@param g Graphics context
@param from Arrow starting point
@param to Arrow ending point
@param weight Arrow weight | [
"Draws",
"an",
"arrow",
"between",
"two",
"given",
"points",
"using",
"the",
"specified",
"weight",
".",
"<br",
">",
"The",
"arrow",
"is",
"leading",
"from",
"point",
"<code",
">",
"from<",
"/",
"code",
">",
"to",
"point",
"<code",
">",
"to<",
"/",
"code",
">",
"."
] | train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/graphic/util/GraphicUtils.java#L97-L99 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getRegexEntityRoles | public List<EntityRole> getRegexEntityRoles(UUID appId, String versionId, UUID entityId) {
"""
Get All Entity Roles for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId entity Id
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<EntityRole> object if successful.
"""
return getRegexEntityRolesWithServiceResponseAsync(appId, versionId, entityId).toBlocking().single().body();
} | java | public List<EntityRole> getRegexEntityRoles(UUID appId, String versionId, UUID entityId) {
return getRegexEntityRolesWithServiceResponseAsync(appId, versionId, entityId).toBlocking().single().body();
} | [
"public",
"List",
"<",
"EntityRole",
">",
"getRegexEntityRoles",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
")",
"{",
"return",
"getRegexEntityRolesWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Get All Entity Roles for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId entity Id
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<EntityRole> object if successful. | [
"Get",
"All",
"Entity",
"Roles",
"for",
"a",
"given",
"entity",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L8499-L8501 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/spillover/spilloverpolicy.java | spilloverpolicy.get | public static spilloverpolicy get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch spilloverpolicy resource of given name .
"""
spilloverpolicy obj = new spilloverpolicy();
obj.set_name(name);
spilloverpolicy response = (spilloverpolicy) obj.get_resource(service);
return response;
} | java | public static spilloverpolicy get(nitro_service service, String name) throws Exception{
spilloverpolicy obj = new spilloverpolicy();
obj.set_name(name);
spilloverpolicy response = (spilloverpolicy) obj.get_resource(service);
return response;
} | [
"public",
"static",
"spilloverpolicy",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"spilloverpolicy",
"obj",
"=",
"new",
"spilloverpolicy",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"spilloverpolicy",
"response",
"=",
"(",
"spilloverpolicy",
")",
"obj",
".",
"get_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
] | Use this API to fetch spilloverpolicy resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"spilloverpolicy",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/spillover/spilloverpolicy.java#L400-L405 |
wwadge/bonecp | bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java | StatementCache.calculateCacheKey | public String calculateCacheKey(String sql, int[] columnIndexes) {
"""
Calculate a cache key.
@param sql to use
@param columnIndexes to use
@return cache key to use.
"""
StringBuilder tmp = new StringBuilder(sql.length()+4);
tmp.append(sql);
for (int i=0; i < columnIndexes.length; i++){
tmp.append(columnIndexes[i]);
tmp.append("CI,");
}
return tmp.toString();
} | java | public String calculateCacheKey(String sql, int[] columnIndexes) {
StringBuilder tmp = new StringBuilder(sql.length()+4);
tmp.append(sql);
for (int i=0; i < columnIndexes.length; i++){
tmp.append(columnIndexes[i]);
tmp.append("CI,");
}
return tmp.toString();
} | [
"public",
"String",
"calculateCacheKey",
"(",
"String",
"sql",
",",
"int",
"[",
"]",
"columnIndexes",
")",
"{",
"StringBuilder",
"tmp",
"=",
"new",
"StringBuilder",
"(",
"sql",
".",
"length",
"(",
")",
"+",
"4",
")",
";",
"tmp",
".",
"append",
"(",
"sql",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"columnIndexes",
".",
"length",
";",
"i",
"++",
")",
"{",
"tmp",
".",
"append",
"(",
"columnIndexes",
"[",
"i",
"]",
")",
";",
"tmp",
".",
"append",
"(",
"\"CI,\"",
")",
";",
"}",
"return",
"tmp",
".",
"toString",
"(",
")",
";",
"}"
] | Calculate a cache key.
@param sql to use
@param columnIndexes to use
@return cache key to use. | [
"Calculate",
"a",
"cache",
"key",
"."
] | train | https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java#L127-L135 |
landawn/AbacusUtil | src/com/landawn/abacus/util/stream/Stream.java | Stream.parallelConcatt | public static <T> Stream<T> parallelConcatt(final Collection<? extends Iterator<? extends T>> c, final int readThreadNum) {
"""
Put the stream in try-catch to stop the back-end reading thread if error happens
<br />
<code>
try (Stream<Integer> stream = Stream.parallelConcat(a,b, ...)) {
stream.forEach(N::println);
}
</code>
@param c
@param readThreadNum
@return
"""
return parallelConcatt(c, readThreadNum, calculateQueueSize(c.size()));
} | java | public static <T> Stream<T> parallelConcatt(final Collection<? extends Iterator<? extends T>> c, final int readThreadNum) {
return parallelConcatt(c, readThreadNum, calculateQueueSize(c.size()));
} | [
"public",
"static",
"<",
"T",
">",
"Stream",
"<",
"T",
">",
"parallelConcatt",
"(",
"final",
"Collection",
"<",
"?",
"extends",
"Iterator",
"<",
"?",
"extends",
"T",
">",
">",
"c",
",",
"final",
"int",
"readThreadNum",
")",
"{",
"return",
"parallelConcatt",
"(",
"c",
",",
"readThreadNum",
",",
"calculateQueueSize",
"(",
"c",
".",
"size",
"(",
")",
")",
")",
";",
"}"
] | Put the stream in try-catch to stop the back-end reading thread if error happens
<br />
<code>
try (Stream<Integer> stream = Stream.parallelConcat(a,b, ...)) {
stream.forEach(N::println);
}
</code>
@param c
@param readThreadNum
@return | [
"Put",
"the",
"stream",
"in",
"try",
"-",
"catch",
"to",
"stop",
"the",
"back",
"-",
"end",
"reading",
"thread",
"if",
"error",
"happens",
"<br",
"/",
">",
"<code",
">",
"try",
"(",
"Stream<Integer",
">",
"stream",
"=",
"Stream",
".",
"parallelConcat",
"(",
"a",
"b",
"...",
"))",
"{",
"stream",
".",
"forEach",
"(",
"N",
"::",
"println",
")",
";",
"}",
"<",
"/",
"code",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/stream/Stream.java#L4408-L4410 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/message/internal/DiagnosticsReport.java | DiagnosticsReport.exportToJson | public String exportToJson(boolean pretty) {
"""
Exports this report into the standard JSON format which is consistent
across different language SDKs.
@return the encoded JSON string.
"""
Map<String, Object> result = new HashMap<String, Object>();
Map<String, List<Map<String, Object>>> services = new HashMap<String, List<Map<String, Object>>>();
for (EndpointHealth h : endpoints) {
String type = serviceTypeFromEnum(h.type());
if (!services.containsKey(type)) {
services.put(type, new ArrayList<Map<String, Object>>());
}
List<Map<String, Object>> eps = services.get(type);
eps.add(h.toMap());
}
result.put("version", version);
result.put("services", services);
result.put("sdk", sdk);
result.put("id", id);
try {
if (pretty) {
return DefaultObjectMapper.prettyWriter().writeValueAsString(result);
} else {
return DefaultObjectMapper.writeValueAsString(result);
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode as JSON string.", e);
}
} | java | public String exportToJson(boolean pretty) {
Map<String, Object> result = new HashMap<String, Object>();
Map<String, List<Map<String, Object>>> services = new HashMap<String, List<Map<String, Object>>>();
for (EndpointHealth h : endpoints) {
String type = serviceTypeFromEnum(h.type());
if (!services.containsKey(type)) {
services.put(type, new ArrayList<Map<String, Object>>());
}
List<Map<String, Object>> eps = services.get(type);
eps.add(h.toMap());
}
result.put("version", version);
result.put("services", services);
result.put("sdk", sdk);
result.put("id", id);
try {
if (pretty) {
return DefaultObjectMapper.prettyWriter().writeValueAsString(result);
} else {
return DefaultObjectMapper.writeValueAsString(result);
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode as JSON string.", e);
}
} | [
"public",
"String",
"exportToJson",
"(",
"boolean",
"pretty",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"result",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"Map",
"<",
"String",
",",
"List",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
">",
"services",
"=",
"new",
"HashMap",
"<",
"String",
",",
"List",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
">",
"(",
")",
";",
"for",
"(",
"EndpointHealth",
"h",
":",
"endpoints",
")",
"{",
"String",
"type",
"=",
"serviceTypeFromEnum",
"(",
"h",
".",
"type",
"(",
")",
")",
";",
"if",
"(",
"!",
"services",
".",
"containsKey",
"(",
"type",
")",
")",
"{",
"services",
".",
"put",
"(",
"type",
",",
"new",
"ArrayList",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"(",
")",
")",
";",
"}",
"List",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"eps",
"=",
"services",
".",
"get",
"(",
"type",
")",
";",
"eps",
".",
"add",
"(",
"h",
".",
"toMap",
"(",
")",
")",
";",
"}",
"result",
".",
"put",
"(",
"\"version\"",
",",
"version",
")",
";",
"result",
".",
"put",
"(",
"\"services\"",
",",
"services",
")",
";",
"result",
".",
"put",
"(",
"\"sdk\"",
",",
"sdk",
")",
";",
"result",
".",
"put",
"(",
"\"id\"",
",",
"id",
")",
";",
"try",
"{",
"if",
"(",
"pretty",
")",
"{",
"return",
"DefaultObjectMapper",
".",
"prettyWriter",
"(",
")",
".",
"writeValueAsString",
"(",
"result",
")",
";",
"}",
"else",
"{",
"return",
"DefaultObjectMapper",
".",
"writeValueAsString",
"(",
"result",
")",
";",
"}",
"}",
"catch",
"(",
"JsonProcessingException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Could not encode as JSON string.\"",
",",
"e",
")",
";",
"}",
"}"
] | Exports this report into the standard JSON format which is consistent
across different language SDKs.
@return the encoded JSON string. | [
"Exports",
"this",
"report",
"into",
"the",
"standard",
"JSON",
"format",
"which",
"is",
"consistent",
"across",
"different",
"language",
"SDKs",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/message/internal/DiagnosticsReport.java#L103-L130 |
square/dagger | compiler/src/main/java/dagger/internal/codegen/Util.java | Util.rawTypeToString | public static String rawTypeToString(TypeMirror type, char innerClassSeparator) {
"""
Returns a string for the raw type of {@code type}. Primitive types are always boxed.
"""
if (!(type instanceof DeclaredType)) {
throw new IllegalArgumentException("Unexpected type: " + type);
}
StringBuilder result = new StringBuilder();
DeclaredType declaredType = (DeclaredType) type;
rawTypeToString(result, (TypeElement) declaredType.asElement(), innerClassSeparator);
return result.toString();
} | java | public static String rawTypeToString(TypeMirror type, char innerClassSeparator) {
if (!(type instanceof DeclaredType)) {
throw new IllegalArgumentException("Unexpected type: " + type);
}
StringBuilder result = new StringBuilder();
DeclaredType declaredType = (DeclaredType) type;
rawTypeToString(result, (TypeElement) declaredType.asElement(), innerClassSeparator);
return result.toString();
} | [
"public",
"static",
"String",
"rawTypeToString",
"(",
"TypeMirror",
"type",
",",
"char",
"innerClassSeparator",
")",
"{",
"if",
"(",
"!",
"(",
"type",
"instanceof",
"DeclaredType",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unexpected type: \"",
"+",
"type",
")",
";",
"}",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"DeclaredType",
"declaredType",
"=",
"(",
"DeclaredType",
")",
"type",
";",
"rawTypeToString",
"(",
"result",
",",
"(",
"TypeElement",
")",
"declaredType",
".",
"asElement",
"(",
")",
",",
"innerClassSeparator",
")",
";",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}"
] | Returns a string for the raw type of {@code type}. Primitive types are always boxed. | [
"Returns",
"a",
"string",
"for",
"the",
"raw",
"type",
"of",
"{"
] | train | https://github.com/square/dagger/blob/572cdd2fe97fc3c148fb3d8e1b2ce7beb4dcbcde/compiler/src/main/java/dagger/internal/codegen/Util.java#L104-L112 |
cycorp/api-suite | core-api/src/main/java/com/cyc/session/ServerAddress.java | ServerAddress.fromString | public static ServerAddress fromString(String string) {
"""
Creates a new ServerAddress instance from a string matching the format
<code>host:port</code>.
@param string a string matching the format <code>host:port</code>.
@return A new ServerAddress instance based on the string representation.
"""
String tokens[] = string.split(":");
if (tokens.length == 1) {
return new ServerAddress(tokens[0], null);
}
return new ServerAddress(tokens[0], Integer.valueOf(tokens[1]));
} | java | public static ServerAddress fromString(String string) {
String tokens[] = string.split(":");
if (tokens.length == 1) {
return new ServerAddress(tokens[0], null);
}
return new ServerAddress(tokens[0], Integer.valueOf(tokens[1]));
} | [
"public",
"static",
"ServerAddress",
"fromString",
"(",
"String",
"string",
")",
"{",
"String",
"tokens",
"[",
"]",
"=",
"string",
".",
"split",
"(",
"\":\"",
")",
";",
"if",
"(",
"tokens",
".",
"length",
"==",
"1",
")",
"{",
"return",
"new",
"ServerAddress",
"(",
"tokens",
"[",
"0",
"]",
",",
"null",
")",
";",
"}",
"return",
"new",
"ServerAddress",
"(",
"tokens",
"[",
"0",
"]",
",",
"Integer",
".",
"valueOf",
"(",
"tokens",
"[",
"1",
"]",
")",
")",
";",
"}"
] | Creates a new ServerAddress instance from a string matching the format
<code>host:port</code>.
@param string a string matching the format <code>host:port</code>.
@return A new ServerAddress instance based on the string representation. | [
"Creates",
"a",
"new",
"ServerAddress",
"instance",
"from",
"a",
"string",
"matching",
"the",
"format",
"<code",
">",
"host",
":",
"port<",
"/",
"code",
">",
"."
] | train | https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/session/ServerAddress.java#L118-L124 |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java | SecureCredentialsManager.saveCredentials | public void saveCredentials(@NonNull Credentials credentials) throws CredentialsManagerException {
"""
Saves the given credentials in the Storage.
@param credentials the credentials to save.
@throws CredentialsManagerException if the credentials couldn't be encrypted. Some devices are not compatible at all with the cryptographic
implementation and will have {@link CredentialsManagerException#isDeviceIncompatible()} return true.
"""
if ((isEmpty(credentials.getAccessToken()) && isEmpty(credentials.getIdToken())) || credentials.getExpiresAt() == null) {
throw new CredentialsManagerException("Credentials must have a valid date of expiration and a valid access_token or id_token value.");
}
String json = gson.toJson(credentials);
long expiresAt = credentials.getExpiresAt().getTime();
boolean canRefresh = !isEmpty(credentials.getRefreshToken());
Log.d(TAG, "Trying to encrypt the given data using the private key.");
try {
byte[] encrypted = crypto.encrypt(json.getBytes());
String encryptedEncoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
storage.store(KEY_CREDENTIALS, encryptedEncoded);
storage.store(KEY_EXPIRES_AT, expiresAt);
storage.store(KEY_CAN_REFRESH, canRefresh);
} catch (IncompatibleDeviceException e) {
throw new CredentialsManagerException(String.format("This device is not compatible with the %s class.", SecureCredentialsManager.class.getSimpleName()), e);
} catch (CryptoException e) {
/*
* If the keys were invalidated in the call above a good new pair is going to be available
* to use on the next call. We clear any existing credentials so #hasValidCredentials returns
* a true value. Retrying this operation will succeed.
*/
clearCredentials();
throw new CredentialsManagerException("A change on the Lock Screen security settings have deemed the encryption keys invalid and have been recreated. Please, try saving the credentials again.", e);
}
} | java | public void saveCredentials(@NonNull Credentials credentials) throws CredentialsManagerException {
if ((isEmpty(credentials.getAccessToken()) && isEmpty(credentials.getIdToken())) || credentials.getExpiresAt() == null) {
throw new CredentialsManagerException("Credentials must have a valid date of expiration and a valid access_token or id_token value.");
}
String json = gson.toJson(credentials);
long expiresAt = credentials.getExpiresAt().getTime();
boolean canRefresh = !isEmpty(credentials.getRefreshToken());
Log.d(TAG, "Trying to encrypt the given data using the private key.");
try {
byte[] encrypted = crypto.encrypt(json.getBytes());
String encryptedEncoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
storage.store(KEY_CREDENTIALS, encryptedEncoded);
storage.store(KEY_EXPIRES_AT, expiresAt);
storage.store(KEY_CAN_REFRESH, canRefresh);
} catch (IncompatibleDeviceException e) {
throw new CredentialsManagerException(String.format("This device is not compatible with the %s class.", SecureCredentialsManager.class.getSimpleName()), e);
} catch (CryptoException e) {
/*
* If the keys were invalidated in the call above a good new pair is going to be available
* to use on the next call. We clear any existing credentials so #hasValidCredentials returns
* a true value. Retrying this operation will succeed.
*/
clearCredentials();
throw new CredentialsManagerException("A change on the Lock Screen security settings have deemed the encryption keys invalid and have been recreated. Please, try saving the credentials again.", e);
}
} | [
"public",
"void",
"saveCredentials",
"(",
"@",
"NonNull",
"Credentials",
"credentials",
")",
"throws",
"CredentialsManagerException",
"{",
"if",
"(",
"(",
"isEmpty",
"(",
"credentials",
".",
"getAccessToken",
"(",
")",
")",
"&&",
"isEmpty",
"(",
"credentials",
".",
"getIdToken",
"(",
")",
")",
")",
"||",
"credentials",
".",
"getExpiresAt",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CredentialsManagerException",
"(",
"\"Credentials must have a valid date of expiration and a valid access_token or id_token value.\"",
")",
";",
"}",
"String",
"json",
"=",
"gson",
".",
"toJson",
"(",
"credentials",
")",
";",
"long",
"expiresAt",
"=",
"credentials",
".",
"getExpiresAt",
"(",
")",
".",
"getTime",
"(",
")",
";",
"boolean",
"canRefresh",
"=",
"!",
"isEmpty",
"(",
"credentials",
".",
"getRefreshToken",
"(",
")",
")",
";",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"Trying to encrypt the given data using the private key.\"",
")",
";",
"try",
"{",
"byte",
"[",
"]",
"encrypted",
"=",
"crypto",
".",
"encrypt",
"(",
"json",
".",
"getBytes",
"(",
")",
")",
";",
"String",
"encryptedEncoded",
"=",
"Base64",
".",
"encodeToString",
"(",
"encrypted",
",",
"Base64",
".",
"DEFAULT",
")",
";",
"storage",
".",
"store",
"(",
"KEY_CREDENTIALS",
",",
"encryptedEncoded",
")",
";",
"storage",
".",
"store",
"(",
"KEY_EXPIRES_AT",
",",
"expiresAt",
")",
";",
"storage",
".",
"store",
"(",
"KEY_CAN_REFRESH",
",",
"canRefresh",
")",
";",
"}",
"catch",
"(",
"IncompatibleDeviceException",
"e",
")",
"{",
"throw",
"new",
"CredentialsManagerException",
"(",
"String",
".",
"format",
"(",
"\"This device is not compatible with the %s class.\"",
",",
"SecureCredentialsManager",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"CryptoException",
"e",
")",
"{",
"/*\n * If the keys were invalidated in the call above a good new pair is going to be available\n * to use on the next call. We clear any existing credentials so #hasValidCredentials returns\n * a true value. Retrying this operation will succeed.\n */",
"clearCredentials",
"(",
")",
";",
"throw",
"new",
"CredentialsManagerException",
"(",
"\"A change on the Lock Screen security settings have deemed the encryption keys invalid and have been recreated. Please, try saving the credentials again.\"",
",",
"e",
")",
";",
"}",
"}"
] | Saves the given credentials in the Storage.
@param credentials the credentials to save.
@throws CredentialsManagerException if the credentials couldn't be encrypted. Some devices are not compatible at all with the cryptographic
implementation and will have {@link CredentialsManagerException#isDeviceIncompatible()} return true. | [
"Saves",
"the",
"given",
"credentials",
"in",
"the",
"Storage",
"."
] | train | https://github.com/auth0/Auth0.Android/blob/ee37b7f94d989c1fbab2cb1378c87fdcaf7a8156/auth0/src/main/java/com/auth0/android/authentication/storage/SecureCredentialsManager.java#L137-L164 |
liferay/com-liferay-commerce | commerce-product-api/src/main/java/com/liferay/commerce/product/service/persistence/CPOptionCategoryUtil.java | CPOptionCategoryUtil.removeByG_K | public static CPOptionCategory removeByG_K(long groupId, String key)
throws com.liferay.commerce.product.exception.NoSuchCPOptionCategoryException {
"""
Removes the cp option category where groupId = ? and key = ? from the database.
@param groupId the group ID
@param key the key
@return the cp option category that was removed
"""
return getPersistence().removeByG_K(groupId, key);
} | java | public static CPOptionCategory removeByG_K(long groupId, String key)
throws com.liferay.commerce.product.exception.NoSuchCPOptionCategoryException {
return getPersistence().removeByG_K(groupId, key);
} | [
"public",
"static",
"CPOptionCategory",
"removeByG_K",
"(",
"long",
"groupId",
",",
"String",
"key",
")",
"throws",
"com",
".",
"liferay",
".",
"commerce",
".",
"product",
".",
"exception",
".",
"NoSuchCPOptionCategoryException",
"{",
"return",
"getPersistence",
"(",
")",
".",
"removeByG_K",
"(",
"groupId",
",",
"key",
")",
";",
"}"
] | Removes the cp option category where groupId = ? and key = ? from the database.
@param groupId the group ID
@param key the key
@return the cp option category that was removed | [
"Removes",
"the",
"cp",
"option",
"category",
"where",
"groupId",
"=",
"?",
";",
"and",
"key",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/service/persistence/CPOptionCategoryUtil.java#L870-L873 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChainDataImpl.java | ChainDataImpl.chainStartFailed | public final void chainStartFailed(int attemptsMade, int attemptsLeft) {
"""
This method is called when the chain start fails. It informs
each of the chain event listeners.
@param attemptsMade
@param attemptsLeft
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(this, tc, "chainStartFailed, chain: " + this.name);
}
// Clone the list in case one of the event listeners modifies
// the chain during this iteration.
for (ChainEventListener listener : chainEventListeners) {
if (listener instanceof RetryableChainEventListener) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Calling chain retryable chain event listener");
}
((RetryableChainEventListener) listener).chainStartFailed(this, attemptsMade, attemptsLeft);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(this, tc, "chainStartFailed");
}
} | java | public final void chainStartFailed(int attemptsMade, int attemptsLeft) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(this, tc, "chainStartFailed, chain: " + this.name);
}
// Clone the list in case one of the event listeners modifies
// the chain during this iteration.
for (ChainEventListener listener : chainEventListeners) {
if (listener instanceof RetryableChainEventListener) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Calling chain retryable chain event listener");
}
((RetryableChainEventListener) listener).chainStartFailed(this, attemptsMade, attemptsLeft);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(this, tc, "chainStartFailed");
}
} | [
"public",
"final",
"void",
"chainStartFailed",
"(",
"int",
"attemptsMade",
",",
"int",
"attemptsLeft",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"entry",
"(",
"this",
",",
"tc",
",",
"\"chainStartFailed, chain: \"",
"+",
"this",
".",
"name",
")",
";",
"}",
"// Clone the list in case one of the event listeners modifies",
"// the chain during this iteration.",
"for",
"(",
"ChainEventListener",
"listener",
":",
"chainEventListeners",
")",
"{",
"if",
"(",
"listener",
"instanceof",
"RetryableChainEventListener",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"Calling chain retryable chain event listener\"",
")",
";",
"}",
"(",
"(",
"RetryableChainEventListener",
")",
"listener",
")",
".",
"chainStartFailed",
"(",
"this",
",",
"attemptsMade",
",",
"attemptsLeft",
")",
";",
"}",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"exit",
"(",
"this",
",",
"tc",
",",
"\"chainStartFailed\"",
")",
";",
"}",
"}"
] | This method is called when the chain start fails. It informs
each of the chain event listeners.
@param attemptsMade
@param attemptsLeft | [
"This",
"method",
"is",
"called",
"when",
"the",
"chain",
"start",
"fails",
".",
"It",
"informs",
"each",
"of",
"the",
"chain",
"event",
"listeners",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChainDataImpl.java#L401-L418 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java | Resolve.accessMethod | Symbol accessMethod(Symbol sym,
DiagnosticPosition pos,
Symbol location,
Type site,
Name name,
boolean qualified,
List<Type> argtypes,
List<Type> typeargtypes) {
"""
Variant of the generalized access routine, to be used for generating method
resolution diagnostics
"""
return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
} | java | Symbol accessMethod(Symbol sym,
DiagnosticPosition pos,
Symbol location,
Type site,
Name name,
boolean qualified,
List<Type> argtypes,
List<Type> typeargtypes) {
return accessInternal(sym, pos, location, site, name, qualified, argtypes, typeargtypes, methodLogResolveHelper);
} | [
"Symbol",
"accessMethod",
"(",
"Symbol",
"sym",
",",
"DiagnosticPosition",
"pos",
",",
"Symbol",
"location",
",",
"Type",
"site",
",",
"Name",
"name",
",",
"boolean",
"qualified",
",",
"List",
"<",
"Type",
">",
"argtypes",
",",
"List",
"<",
"Type",
">",
"typeargtypes",
")",
"{",
"return",
"accessInternal",
"(",
"sym",
",",
"pos",
",",
"location",
",",
"site",
",",
"name",
",",
"qualified",
",",
"argtypes",
",",
"typeargtypes",
",",
"methodLogResolveHelper",
")",
";",
"}"
] | Variant of the generalized access routine, to be used for generating method
resolution diagnostics | [
"Variant",
"of",
"the",
"generalized",
"access",
"routine",
"to",
"be",
"used",
"for",
"generating",
"method",
"resolution",
"diagnostics"
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L2458-L2467 |
dmurph/jgoogleanalyticstracker | src/main/java/com/dmurph/tracking/JGoogleAnalyticsTracker.java | JGoogleAnalyticsTracker.setProxy | public static void setProxy(String proxyAddr) {
"""
Define the proxy to use for all GA tracking requests.
<p>
Call this static method early (before creating any tracking requests).
@param proxyAddr "addr:port" of the proxy to use; may also be given as URL ("http://addr:port/").
"""
if (proxyAddr != null) {
Scanner s = new Scanner(proxyAddr);
// Split into "proxyAddr:proxyPort".
proxyAddr = null;
int proxyPort = 8080;
try {
s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
MatchResult m = s.match();
if (m.groupCount() >= 2) {
proxyAddr = m.group(2);
}
if ((m.groupCount() >= 4) && (!m.group(4).isEmpty())) {
proxyPort = Integer.parseInt(m.group(4));
}
} finally {
s.close();
}
if (proxyAddr != null) {
SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
setProxy(new Proxy(Type.HTTP, sa));
}
}
} | java | public static void setProxy(String proxyAddr) {
if (proxyAddr != null) {
Scanner s = new Scanner(proxyAddr);
// Split into "proxyAddr:proxyPort".
proxyAddr = null;
int proxyPort = 8080;
try {
s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
MatchResult m = s.match();
if (m.groupCount() >= 2) {
proxyAddr = m.group(2);
}
if ((m.groupCount() >= 4) && (!m.group(4).isEmpty())) {
proxyPort = Integer.parseInt(m.group(4));
}
} finally {
s.close();
}
if (proxyAddr != null) {
SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
setProxy(new Proxy(Type.HTTP, sa));
}
}
} | [
"public",
"static",
"void",
"setProxy",
"(",
"String",
"proxyAddr",
")",
"{",
"if",
"(",
"proxyAddr",
"!=",
"null",
")",
"{",
"Scanner",
"s",
"=",
"new",
"Scanner",
"(",
"proxyAddr",
")",
";",
"// Split into \"proxyAddr:proxyPort\".",
"proxyAddr",
"=",
"null",
";",
"int",
"proxyPort",
"=",
"8080",
";",
"try",
"{",
"s",
".",
"findInLine",
"(",
"\"(http://|)([^:/]+)(:|)([0-9]*)(/|)\"",
")",
";",
"MatchResult",
"m",
"=",
"s",
".",
"match",
"(",
")",
";",
"if",
"(",
"m",
".",
"groupCount",
"(",
")",
">=",
"2",
")",
"{",
"proxyAddr",
"=",
"m",
".",
"group",
"(",
"2",
")",
";",
"}",
"if",
"(",
"(",
"m",
".",
"groupCount",
"(",
")",
">=",
"4",
")",
"&&",
"(",
"!",
"m",
".",
"group",
"(",
"4",
")",
".",
"isEmpty",
"(",
")",
")",
")",
"{",
"proxyPort",
"=",
"Integer",
".",
"parseInt",
"(",
"m",
".",
"group",
"(",
"4",
")",
")",
";",
"}",
"}",
"finally",
"{",
"s",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"proxyAddr",
"!=",
"null",
")",
"{",
"SocketAddress",
"sa",
"=",
"new",
"InetSocketAddress",
"(",
"proxyAddr",
",",
"proxyPort",
")",
";",
"setProxy",
"(",
"new",
"Proxy",
"(",
"Type",
".",
"HTTP",
",",
"sa",
")",
")",
";",
"}",
"}",
"}"
] | Define the proxy to use for all GA tracking requests.
<p>
Call this static method early (before creating any tracking requests).
@param proxyAddr "addr:port" of the proxy to use; may also be given as URL ("http://addr:port/"). | [
"Define",
"the",
"proxy",
"to",
"use",
"for",
"all",
"GA",
"tracking",
"requests",
".",
"<p",
">",
"Call",
"this",
"static",
"method",
"early",
"(",
"before",
"creating",
"any",
"tracking",
"requests",
")",
"."
] | train | https://github.com/dmurph/jgoogleanalyticstracker/blob/69f68caf8e09a53e6f6076477bf05b84bc80e386/src/main/java/com/dmurph/tracking/JGoogleAnalyticsTracker.java#L221-L248 |
UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java | ApiOvhPrice.dedicated_server_antiDDoSPro_commercialRange_GET | public OvhPrice dedicated_server_antiDDoSPro_commercialRange_GET(net.minidev.ovh.api.price.dedicated.server.OvhAntiDDoSProEnum commercialRange) throws IOException {
"""
Get price of anti-DDos Pro option
REST: GET /price/dedicated/server/antiDDoSPro/{commercialRange}
@param commercialRange [required] commercial range of your dedicated server
"""
String qPath = "/price/dedicated/server/antiDDoSPro/{commercialRange}";
StringBuilder sb = path(qPath, commercialRange);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | java | public OvhPrice dedicated_server_antiDDoSPro_commercialRange_GET(net.minidev.ovh.api.price.dedicated.server.OvhAntiDDoSProEnum commercialRange) throws IOException {
String qPath = "/price/dedicated/server/antiDDoSPro/{commercialRange}";
StringBuilder sb = path(qPath, commercialRange);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | [
"public",
"OvhPrice",
"dedicated_server_antiDDoSPro_commercialRange_GET",
"(",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"price",
".",
"dedicated",
".",
"server",
".",
"OvhAntiDDoSProEnum",
"commercialRange",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/price/dedicated/server/antiDDoSPro/{commercialRange}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"commercialRange",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhPrice",
".",
"class",
")",
";",
"}"
] | Get price of anti-DDos Pro option
REST: GET /price/dedicated/server/antiDDoSPro/{commercialRange}
@param commercialRange [required] commercial range of your dedicated server | [
"Get",
"price",
"of",
"anti",
"-",
"DDos",
"Pro",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L102-L107 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/ByteBufferMinMaxOffsetHeap.java | ByteBufferMinMaxOffsetHeap.findMinGrandChild | private int findMinGrandChild(Comparator comparator, int index) {
"""
Returns the minimum grand child or -1 if no grand child exists.
"""
int leftChildIndex = getLeftChildIndex(index);
if (leftChildIndex < 0) {
return -1;
}
return findMin(comparator, getLeftChildIndex(leftChildIndex), 4);
} | java | private int findMinGrandChild(Comparator comparator, int index)
{
int leftChildIndex = getLeftChildIndex(index);
if (leftChildIndex < 0) {
return -1;
}
return findMin(comparator, getLeftChildIndex(leftChildIndex), 4);
} | [
"private",
"int",
"findMinGrandChild",
"(",
"Comparator",
"comparator",
",",
"int",
"index",
")",
"{",
"int",
"leftChildIndex",
"=",
"getLeftChildIndex",
"(",
"index",
")",
";",
"if",
"(",
"leftChildIndex",
"<",
"0",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"findMin",
"(",
"comparator",
",",
"getLeftChildIndex",
"(",
"leftChildIndex",
")",
",",
"4",
")",
";",
"}"
] | Returns the minimum grand child or -1 if no grand child exists. | [
"Returns",
"the",
"minimum",
"grand",
"child",
"or",
"-",
"1",
"if",
"no",
"grand",
"child",
"exists",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/ByteBufferMinMaxOffsetHeap.java#L383-L390 |
hawkular/hawkular-agent | hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/JavaAgentEngine.java | JavaAgentEngine.startHawkularAgent | public void startHawkularAgent(Configuration newConfig) {
"""
This method allows you to start the agent using a Java Agent Engine Configuration ({@link Configuration})
rather than a Agent Core Engine configuration ({@link AgentCoreEngineConfiguration}).
If the original agent configuration indicated the agent should be immutable, this ignores
the given configuration and restarts the agent using the old configuration.
The new configuration will be persisted if the agent was mutable and allowed to change.
@param newConfig the new configuration to use (may be null which means use the previous configuration).
"""
if (newConfig == null) {
super.startHawkularAgent();
} else {
Configuration oldConfig = getConfigurationManager().getConfiguration();
boolean doNotChangeConfig = (oldConfig != null && oldConfig.getSubsystem().getImmutable());
AgentCoreEngineConfiguration agentConfig;
try {
agentConfig = new ConfigConverter(doNotChangeConfig ? oldConfig : newConfig).convert();
} catch (Exception e) {
throw new RuntimeException("Cannot start agent - config is invalid", e);
}
try {
if (!doNotChangeConfig) {
this.configurationManager.updateConfiguration(newConfig, true);
}
super.startHawkularAgent(agentConfig);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | java | public void startHawkularAgent(Configuration newConfig) {
if (newConfig == null) {
super.startHawkularAgent();
} else {
Configuration oldConfig = getConfigurationManager().getConfiguration();
boolean doNotChangeConfig = (oldConfig != null && oldConfig.getSubsystem().getImmutable());
AgentCoreEngineConfiguration agentConfig;
try {
agentConfig = new ConfigConverter(doNotChangeConfig ? oldConfig : newConfig).convert();
} catch (Exception e) {
throw new RuntimeException("Cannot start agent - config is invalid", e);
}
try {
if (!doNotChangeConfig) {
this.configurationManager.updateConfiguration(newConfig, true);
}
super.startHawkularAgent(agentConfig);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | [
"public",
"void",
"startHawkularAgent",
"(",
"Configuration",
"newConfig",
")",
"{",
"if",
"(",
"newConfig",
"==",
"null",
")",
"{",
"super",
".",
"startHawkularAgent",
"(",
")",
";",
"}",
"else",
"{",
"Configuration",
"oldConfig",
"=",
"getConfigurationManager",
"(",
")",
".",
"getConfiguration",
"(",
")",
";",
"boolean",
"doNotChangeConfig",
"=",
"(",
"oldConfig",
"!=",
"null",
"&&",
"oldConfig",
".",
"getSubsystem",
"(",
")",
".",
"getImmutable",
"(",
")",
")",
";",
"AgentCoreEngineConfiguration",
"agentConfig",
";",
"try",
"{",
"agentConfig",
"=",
"new",
"ConfigConverter",
"(",
"doNotChangeConfig",
"?",
"oldConfig",
":",
"newConfig",
")",
".",
"convert",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot start agent - config is invalid\"",
",",
"e",
")",
";",
"}",
"try",
"{",
"if",
"(",
"!",
"doNotChangeConfig",
")",
"{",
"this",
".",
"configurationManager",
".",
"updateConfiguration",
"(",
"newConfig",
",",
"true",
")",
";",
"}",
"super",
".",
"startHawkularAgent",
"(",
"agentConfig",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"re",
")",
"{",
"throw",
"re",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}"
] | This method allows you to start the agent using a Java Agent Engine Configuration ({@link Configuration})
rather than a Agent Core Engine configuration ({@link AgentCoreEngineConfiguration}).
If the original agent configuration indicated the agent should be immutable, this ignores
the given configuration and restarts the agent using the old configuration.
The new configuration will be persisted if the agent was mutable and allowed to change.
@param newConfig the new configuration to use (may be null which means use the previous configuration). | [
"This",
"method",
"allows",
"you",
"to",
"start",
"the",
"agent",
"using",
"a",
"Java",
"Agent",
"Engine",
"Configuration",
"(",
"{",
"@link",
"Configuration",
"}",
")",
"rather",
"than",
"a",
"Agent",
"Core",
"Engine",
"configuration",
"(",
"{",
"@link",
"AgentCoreEngineConfiguration",
"}",
")",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-javaagent/src/main/java/org/hawkular/agent/javaagent/JavaAgentEngine.java#L141-L166 |
qatools/properties | src/main/java/ru/qatools/properties/utils/PropsReplacer.java | PropsReplacer.replaceProps | public PropsReplacer replaceProps(String pattern, Properties properties) {
"""
Fluent-api method. Replace properties in each path from paths field using pattern. Change paths filed value
@param pattern - pattern to replace. First group should contains property name
@param properties - list of properties using to replace
@return PropsReplacer
"""
List<String> replaced = new ArrayList<>();
for (String path : paths) {
replaced.add(replaceProps(pattern, path, properties));
}
setPaths(replaced);
return this;
} | java | public PropsReplacer replaceProps(String pattern, Properties properties) {
List<String> replaced = new ArrayList<>();
for (String path : paths) {
replaced.add(replaceProps(pattern, path, properties));
}
setPaths(replaced);
return this;
} | [
"public",
"PropsReplacer",
"replaceProps",
"(",
"String",
"pattern",
",",
"Properties",
"properties",
")",
"{",
"List",
"<",
"String",
">",
"replaced",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"String",
"path",
":",
"paths",
")",
"{",
"replaced",
".",
"add",
"(",
"replaceProps",
"(",
"pattern",
",",
"path",
",",
"properties",
")",
")",
";",
"}",
"setPaths",
"(",
"replaced",
")",
";",
"return",
"this",
";",
"}"
] | Fluent-api method. Replace properties in each path from paths field using pattern. Change paths filed value
@param pattern - pattern to replace. First group should contains property name
@param properties - list of properties using to replace
@return PropsReplacer | [
"Fluent",
"-",
"api",
"method",
".",
"Replace",
"properties",
"in",
"each",
"path",
"from",
"paths",
"field",
"using",
"pattern",
".",
"Change",
"paths",
"filed",
"value"
] | train | https://github.com/qatools/properties/blob/ae50b460a6bb4fcb21afe888b2e86a7613cd2115/src/main/java/ru/qatools/properties/utils/PropsReplacer.java#L29-L36 |
legsem/legstar-core2 | legstar-cob2xsd/src/main/java/com/legstar/cob2xsd/Cob2Xsd.java | Cob2Xsd.emitXsd | public XmlSchema emitXsd(final List < CobolDataItem > cobolDataItems, final String targetNamespace) {
"""
Generate an XML Schema using a model of COBOL data items. The model is a
list of root level items. From these, we only process group items
(structures) with children.
@param cobolDataItems a list of COBOL data items
@param targetNamespace the target namespace to use (null for no namespace)
@return the XML schema
"""
if (_log.isDebugEnabled()) {
_log.debug("5. Emitting XML Schema from model: {}",
cobolDataItems.toString());
}
XmlSchema xsd = createXmlSchema(getConfig().getXsdEncoding(), targetNamespace);
List < String > nonUniqueCobolNames = getNonUniqueCobolNames(cobolDataItems);
XsdEmitter emitter = new XsdEmitter(xsd, getConfig());
for (CobolDataItem cobolDataItem : cobolDataItems) {
if (getConfig().ignoreOrphanPrimitiveElements()
&& cobolDataItem.getChildren().size() == 0) {
continue;
}
XsdDataItem xsdDataItem = new XsdDataItem(cobolDataItem,
getConfig(), null, 0, nonUniqueCobolNames, _errorHandler);
// Create and add a root element
xsd.getItems().add(emitter.createXmlSchemaElement(xsdDataItem));
}
return xsd;
} | java | public XmlSchema emitXsd(final List < CobolDataItem > cobolDataItems, final String targetNamespace) {
if (_log.isDebugEnabled()) {
_log.debug("5. Emitting XML Schema from model: {}",
cobolDataItems.toString());
}
XmlSchema xsd = createXmlSchema(getConfig().getXsdEncoding(), targetNamespace);
List < String > nonUniqueCobolNames = getNonUniqueCobolNames(cobolDataItems);
XsdEmitter emitter = new XsdEmitter(xsd, getConfig());
for (CobolDataItem cobolDataItem : cobolDataItems) {
if (getConfig().ignoreOrphanPrimitiveElements()
&& cobolDataItem.getChildren().size() == 0) {
continue;
}
XsdDataItem xsdDataItem = new XsdDataItem(cobolDataItem,
getConfig(), null, 0, nonUniqueCobolNames, _errorHandler);
// Create and add a root element
xsd.getItems().add(emitter.createXmlSchemaElement(xsdDataItem));
}
return xsd;
} | [
"public",
"XmlSchema",
"emitXsd",
"(",
"final",
"List",
"<",
"CobolDataItem",
">",
"cobolDataItems",
",",
"final",
"String",
"targetNamespace",
")",
"{",
"if",
"(",
"_log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"_log",
".",
"debug",
"(",
"\"5. Emitting XML Schema from model: {}\"",
",",
"cobolDataItems",
".",
"toString",
"(",
")",
")",
";",
"}",
"XmlSchema",
"xsd",
"=",
"createXmlSchema",
"(",
"getConfig",
"(",
")",
".",
"getXsdEncoding",
"(",
")",
",",
"targetNamespace",
")",
";",
"List",
"<",
"String",
">",
"nonUniqueCobolNames",
"=",
"getNonUniqueCobolNames",
"(",
"cobolDataItems",
")",
";",
"XsdEmitter",
"emitter",
"=",
"new",
"XsdEmitter",
"(",
"xsd",
",",
"getConfig",
"(",
")",
")",
";",
"for",
"(",
"CobolDataItem",
"cobolDataItem",
":",
"cobolDataItems",
")",
"{",
"if",
"(",
"getConfig",
"(",
")",
".",
"ignoreOrphanPrimitiveElements",
"(",
")",
"&&",
"cobolDataItem",
".",
"getChildren",
"(",
")",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"continue",
";",
"}",
"XsdDataItem",
"xsdDataItem",
"=",
"new",
"XsdDataItem",
"(",
"cobolDataItem",
",",
"getConfig",
"(",
")",
",",
"null",
",",
"0",
",",
"nonUniqueCobolNames",
",",
"_errorHandler",
")",
";",
"// Create and add a root element",
"xsd",
".",
"getItems",
"(",
")",
".",
"add",
"(",
"emitter",
".",
"createXmlSchemaElement",
"(",
"xsdDataItem",
")",
")",
";",
"}",
"return",
"xsd",
";",
"}"
] | Generate an XML Schema using a model of COBOL data items. The model is a
list of root level items. From these, we only process group items
(structures) with children.
@param cobolDataItems a list of COBOL data items
@param targetNamespace the target namespace to use (null for no namespace)
@return the XML schema | [
"Generate",
"an",
"XML",
"Schema",
"using",
"a",
"model",
"of",
"COBOL",
"data",
"items",
".",
"The",
"model",
"is",
"a",
"list",
"of",
"root",
"level",
"items",
".",
"From",
"these",
"we",
"only",
"process",
"group",
"items",
"(",
"structures",
")",
"with",
"children",
"."
] | train | https://github.com/legsem/legstar-core2/blob/f74d25d5b2b21a2ebaaaf2162b3fb7138dca40c6/legstar-cob2xsd/src/main/java/com/legstar/cob2xsd/Cob2Xsd.java#L264-L283 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.denominateAndRound | private BigDecimal denominateAndRound(BigInteger satoshis, int minDecimals, List<Integer> fractionGroups) {
"""
Takes a bitcoin monetary value that the client wants to format and returns the number of
denominational units having the equal value, rounded to the appropriate number of
decimal places. Calls the scale() method of the subclass, which may have the
side-effect of changing the currency symbol and code of the underlying `NumberFormat`
object, therefore only invoke this from a synchronized method that resets the NumberFormat.
"""
int scale = scale(satoshis, minDecimals);
BigDecimal denominatedUnitCount = new BigDecimal(satoshis).movePointLeft(offSatoshis(scale));
int places = calculateFractionPlaces(denominatedUnitCount, scale, minDecimals, fractionGroups);
return denominatedUnitCount.setScale(places, HALF_UP);
} | java | private BigDecimal denominateAndRound(BigInteger satoshis, int minDecimals, List<Integer> fractionGroups) {
int scale = scale(satoshis, minDecimals);
BigDecimal denominatedUnitCount = new BigDecimal(satoshis).movePointLeft(offSatoshis(scale));
int places = calculateFractionPlaces(denominatedUnitCount, scale, minDecimals, fractionGroups);
return denominatedUnitCount.setScale(places, HALF_UP);
} | [
"private",
"BigDecimal",
"denominateAndRound",
"(",
"BigInteger",
"satoshis",
",",
"int",
"minDecimals",
",",
"List",
"<",
"Integer",
">",
"fractionGroups",
")",
"{",
"int",
"scale",
"=",
"scale",
"(",
"satoshis",
",",
"minDecimals",
")",
";",
"BigDecimal",
"denominatedUnitCount",
"=",
"new",
"BigDecimal",
"(",
"satoshis",
")",
".",
"movePointLeft",
"(",
"offSatoshis",
"(",
"scale",
")",
")",
";",
"int",
"places",
"=",
"calculateFractionPlaces",
"(",
"denominatedUnitCount",
",",
"scale",
",",
"minDecimals",
",",
"fractionGroups",
")",
";",
"return",
"denominatedUnitCount",
".",
"setScale",
"(",
"places",
",",
"HALF_UP",
")",
";",
"}"
] | Takes a bitcoin monetary value that the client wants to format and returns the number of
denominational units having the equal value, rounded to the appropriate number of
decimal places. Calls the scale() method of the subclass, which may have the
side-effect of changing the currency symbol and code of the underlying `NumberFormat`
object, therefore only invoke this from a synchronized method that resets the NumberFormat. | [
"Takes",
"a",
"bitcoin",
"monetary",
"value",
"that",
"the",
"client",
"wants",
"to",
"format",
"and",
"returns",
"the",
"number",
"of",
"denominational",
"units",
"having",
"the",
"equal",
"value",
"rounded",
"to",
"the",
"appropriate",
"number",
"of",
"decimal",
"places",
".",
"Calls",
"the",
"scale",
"()",
"method",
"of",
"the",
"subclass",
"which",
"may",
"have",
"the",
"side",
"-",
"effect",
"of",
"changing",
"the",
"currency",
"symbol",
"and",
"code",
"of",
"the",
"underlying",
"NumberFormat",
"object",
"therefore",
"only",
"invoke",
"this",
"from",
"a",
"synchronized",
"method",
"that",
"resets",
"the",
"NumberFormat",
"."
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1228-L1233 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newResourceNotFoundException | public static ResourceNotFoundException newResourceNotFoundException(String message, Object... args) {
"""
Constructs and initializes a new {@link ResourceNotFoundException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link ResourceNotFoundException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ResourceNotFoundException} with the given {@link String message}.
@see #newResourceNotFoundException(Throwable, String, Object...)
@see org.cp.elements.lang.ResourceNotFoundException
"""
return newResourceNotFoundException(null, message, args);
} | java | public static ResourceNotFoundException newResourceNotFoundException(String message, Object... args) {
return newResourceNotFoundException(null, message, args);
} | [
"public",
"static",
"ResourceNotFoundException",
"newResourceNotFoundException",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"newResourceNotFoundException",
"(",
"null",
",",
"message",
",",
"args",
")",
";",
"}"
] | Constructs and initializes a new {@link ResourceNotFoundException} with the given {@link String message}
formatted with the given {@link Object[] arguments}.
@param message {@link String} describing the {@link ResourceNotFoundException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link ResourceNotFoundException} with the given {@link String message}.
@see #newResourceNotFoundException(Throwable, String, Object...)
@see org.cp.elements.lang.ResourceNotFoundException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"ResourceNotFoundException",
"}",
"with",
"the",
"given",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object",
"[]",
"arguments",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L495-L497 |
apache/incubator-druid | extensions-core/orc-extensions/src/main/java/org/apache/druid/data/input/orc/OrcStructConverter.java | OrcStructConverter.convertField | @Nullable
Object convertField(OrcStruct struct, int fieldIndex) {
"""
Convert a orc struct field as though it were a map, by fieldIndex. Complex types will be transformed
into java lists and maps when possible ({@link OrcStructConverter#convertList} and
{@link OrcStructConverter#convertMap}), and
primitive types will be extracted into an ingestion friendly state (e.g. 'int' and 'long'). Finally,
if a field is not present, this method will return null.
Note: "Union" types are not currently supported and will be returned as null
"""
if (fieldIndex < 0) {
return null;
}
TypeDescription schema = struct.getSchema();
TypeDescription fieldDescription = schema.getChildren().get(fieldIndex);
WritableComparable fieldValue = struct.getFieldValue(fieldIndex);
if (fieldValue == null) {
return null;
}
if (fieldDescription.getCategory().isPrimitive()) {
return convertPrimitive(fieldDescription, fieldValue, binaryAsString);
} else {
// handle complex column types
/*
ORC TYPE WRITABLE TYPE
array org.apache.orc.mapred.OrcList
map org.apache.orc.mapred.OrcMap
struct org.apache.orc.mapred.OrcStruct
uniontype org.apache.orc.mapred.OrcUnion
*/
switch (fieldDescription.getCategory()) {
case LIST:
OrcList orcList = (OrcList) fieldValue;
return convertList(fieldDescription, orcList, binaryAsString);
case MAP:
OrcMap map = (OrcMap) fieldValue;
return convertMap(fieldDescription, map, binaryAsString);
case STRUCT:
OrcStruct structMap = (OrcStruct) fieldValue;
return convertStructToMap(structMap);
case UNION:
// sorry union types :(
default:
return null;
}
}
} | java | @Nullable
Object convertField(OrcStruct struct, int fieldIndex)
{
if (fieldIndex < 0) {
return null;
}
TypeDescription schema = struct.getSchema();
TypeDescription fieldDescription = schema.getChildren().get(fieldIndex);
WritableComparable fieldValue = struct.getFieldValue(fieldIndex);
if (fieldValue == null) {
return null;
}
if (fieldDescription.getCategory().isPrimitive()) {
return convertPrimitive(fieldDescription, fieldValue, binaryAsString);
} else {
// handle complex column types
/*
ORC TYPE WRITABLE TYPE
array org.apache.orc.mapred.OrcList
map org.apache.orc.mapred.OrcMap
struct org.apache.orc.mapred.OrcStruct
uniontype org.apache.orc.mapred.OrcUnion
*/
switch (fieldDescription.getCategory()) {
case LIST:
OrcList orcList = (OrcList) fieldValue;
return convertList(fieldDescription, orcList, binaryAsString);
case MAP:
OrcMap map = (OrcMap) fieldValue;
return convertMap(fieldDescription, map, binaryAsString);
case STRUCT:
OrcStruct structMap = (OrcStruct) fieldValue;
return convertStructToMap(structMap);
case UNION:
// sorry union types :(
default:
return null;
}
}
} | [
"@",
"Nullable",
"Object",
"convertField",
"(",
"OrcStruct",
"struct",
",",
"int",
"fieldIndex",
")",
"{",
"if",
"(",
"fieldIndex",
"<",
"0",
")",
"{",
"return",
"null",
";",
"}",
"TypeDescription",
"schema",
"=",
"struct",
".",
"getSchema",
"(",
")",
";",
"TypeDescription",
"fieldDescription",
"=",
"schema",
".",
"getChildren",
"(",
")",
".",
"get",
"(",
"fieldIndex",
")",
";",
"WritableComparable",
"fieldValue",
"=",
"struct",
".",
"getFieldValue",
"(",
"fieldIndex",
")",
";",
"if",
"(",
"fieldValue",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"fieldDescription",
".",
"getCategory",
"(",
")",
".",
"isPrimitive",
"(",
")",
")",
"{",
"return",
"convertPrimitive",
"(",
"fieldDescription",
",",
"fieldValue",
",",
"binaryAsString",
")",
";",
"}",
"else",
"{",
"// handle complex column types",
"/*\n ORC TYPE WRITABLE TYPE\n array org.apache.orc.mapred.OrcList\n map org.apache.orc.mapred.OrcMap\n struct org.apache.orc.mapred.OrcStruct\n uniontype org.apache.orc.mapred.OrcUnion\n */",
"switch",
"(",
"fieldDescription",
".",
"getCategory",
"(",
")",
")",
"{",
"case",
"LIST",
":",
"OrcList",
"orcList",
"=",
"(",
"OrcList",
")",
"fieldValue",
";",
"return",
"convertList",
"(",
"fieldDescription",
",",
"orcList",
",",
"binaryAsString",
")",
";",
"case",
"MAP",
":",
"OrcMap",
"map",
"=",
"(",
"OrcMap",
")",
"fieldValue",
";",
"return",
"convertMap",
"(",
"fieldDescription",
",",
"map",
",",
"binaryAsString",
")",
";",
"case",
"STRUCT",
":",
"OrcStruct",
"structMap",
"=",
"(",
"OrcStruct",
")",
"fieldValue",
";",
"return",
"convertStructToMap",
"(",
"structMap",
")",
";",
"case",
"UNION",
":",
"// sorry union types :(",
"default",
":",
"return",
"null",
";",
"}",
"}",
"}"
] | Convert a orc struct field as though it were a map, by fieldIndex. Complex types will be transformed
into java lists and maps when possible ({@link OrcStructConverter#convertList} and
{@link OrcStructConverter#convertMap}), and
primitive types will be extracted into an ingestion friendly state (e.g. 'int' and 'long'). Finally,
if a field is not present, this method will return null.
Note: "Union" types are not currently supported and will be returned as null | [
"Convert",
"a",
"orc",
"struct",
"field",
"as",
"though",
"it",
"were",
"a",
"map",
"by",
"fieldIndex",
".",
"Complex",
"types",
"will",
"be",
"transformed",
"into",
"java",
"lists",
"and",
"maps",
"when",
"possible",
"(",
"{",
"@link",
"OrcStructConverter#convertList",
"}",
"and",
"{",
"@link",
"OrcStructConverter#convertMap",
"}",
")",
"and",
"primitive",
"types",
"will",
"be",
"extracted",
"into",
"an",
"ingestion",
"friendly",
"state",
"(",
"e",
".",
"g",
".",
"int",
"and",
"long",
")",
".",
"Finally",
"if",
"a",
"field",
"is",
"not",
"present",
"this",
"method",
"will",
"return",
"null",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/orc-extensions/src/main/java/org/apache/druid/data/input/orc/OrcStructConverter.java#L185-L227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.