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
recommenders/rival
rival-split/src/main/java/net/recommenders/rival/split/parser/AbstractLastfmCelmaParser.java
AbstractLastfmCelmaParser.getIndexMap
public static long getIndexMap(final File in, final Map<String, Long> map) throws IOException { """ Read a user/item mapping (user/item original value, user/item internal id) from a file and return the maximum index number in that file. @param in The file with id mapping. @param map The user/item mapping @return The largest id number. @throws IOException if file does not exist. """ long id = 0; if (in.exists()) { BufferedReader br = SimpleParser.getBufferedReader(in); String line; while ((line = br.readLine()) != null) { String[] toks = line.split("\t"); long i = Long.parseLong(toks[1]); map.put(toks[0], i); id = Math.max(i, id); } br.close(); } return id + 1; }
java
public static long getIndexMap(final File in, final Map<String, Long> map) throws IOException { long id = 0; if (in.exists()) { BufferedReader br = SimpleParser.getBufferedReader(in); String line; while ((line = br.readLine()) != null) { String[] toks = line.split("\t"); long i = Long.parseLong(toks[1]); map.put(toks[0], i); id = Math.max(i, id); } br.close(); } return id + 1; }
[ "public", "static", "long", "getIndexMap", "(", "final", "File", "in", ",", "final", "Map", "<", "String", ",", "Long", ">", "map", ")", "throws", "IOException", "{", "long", "id", "=", "0", ";", "if", "(", "in", ".", "exists", "(", ")", ")", "{", "BufferedReader", "br", "=", "SimpleParser", ".", "getBufferedReader", "(", "in", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "String", "[", "]", "toks", "=", "line", ".", "split", "(", "\"\\t\"", ")", ";", "long", "i", "=", "Long", ".", "parseLong", "(", "toks", "[", "1", "]", ")", ";", "map", ".", "put", "(", "toks", "[", "0", "]", ",", "i", ")", ";", "id", "=", "Math", ".", "max", "(", "i", ",", "id", ")", ";", "}", "br", ".", "close", "(", ")", ";", "}", "return", "id", "+", "1", ";", "}" ]
Read a user/item mapping (user/item original value, user/item internal id) from a file and return the maximum index number in that file. @param in The file with id mapping. @param map The user/item mapping @return The largest id number. @throws IOException if file does not exist.
[ "Read", "a", "user", "/", "item", "mapping", "(", "user", "/", "item", "original", "value", "user", "/", "item", "internal", "id", ")", "from", "a", "file", "and", "return", "the", "maximum", "index", "number", "in", "that", "file", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-split/src/main/java/net/recommenders/rival/split/parser/AbstractLastfmCelmaParser.java#L56-L70
opendatatrentino/s-match
src/main/java/it/unitn/disi/smatch/filters/SPSMMappingFilter.java
SPSMMappingFilter.existsStrongerInColumn
private boolean existsStrongerInColumn(INode source, INode target) { """ Checks if there is no other stronger relation in the same column. @param source source node @param target target node @return true if exists stronger relation in the same column, false otherwise. """ boolean result = false; char current = defautlMappings.getRelation(source, target); //compare with the other relations in the column for (INode i : defautlMappings.getSourceContext().getNodesList()) { if (i != source && defautlMappings.getRelation(i, target) != IMappingElement.IDK && isPrecedent(defautlMappings.getRelation(i, target), current)) { result = true; break; } } return result; }
java
private boolean existsStrongerInColumn(INode source, INode target) { boolean result = false; char current = defautlMappings.getRelation(source, target); //compare with the other relations in the column for (INode i : defautlMappings.getSourceContext().getNodesList()) { if (i != source && defautlMappings.getRelation(i, target) != IMappingElement.IDK && isPrecedent(defautlMappings.getRelation(i, target), current)) { result = true; break; } } return result; }
[ "private", "boolean", "existsStrongerInColumn", "(", "INode", "source", ",", "INode", "target", ")", "{", "boolean", "result", "=", "false", ";", "char", "current", "=", "defautlMappings", ".", "getRelation", "(", "source", ",", "target", ")", ";", "//compare with the other relations in the column\r", "for", "(", "INode", "i", ":", "defautlMappings", ".", "getSourceContext", "(", ")", ".", "getNodesList", "(", ")", ")", "{", "if", "(", "i", "!=", "source", "&&", "defautlMappings", ".", "getRelation", "(", "i", ",", "target", ")", "!=", "IMappingElement", ".", "IDK", "&&", "isPrecedent", "(", "defautlMappings", ".", "getRelation", "(", "i", ",", "target", ")", ",", "current", ")", ")", "{", "result", "=", "true", ";", "break", ";", "}", "}", "return", "result", ";", "}" ]
Checks if there is no other stronger relation in the same column. @param source source node @param target target node @return true if exists stronger relation in the same column, false otherwise.
[ "Checks", "if", "there", "is", "no", "other", "stronger", "relation", "in", "the", "same", "column", "." ]
train
https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/smatch/filters/SPSMMappingFilter.java#L469-L484
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addErrorsFailedToReindex
public FessMessages addErrorsFailedToReindex(String property, String arg0, String arg1) { """ Add the created action message for the key 'errors.failed_to_reindex' with parameters. <pre> message: Failed to start reindexing from {0} to {1} </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @param arg1 The parameter arg1 for message. (NotNull) @return this. (NotNull) """ assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_failed_to_reindex, arg0, arg1)); return this; }
java
public FessMessages addErrorsFailedToReindex(String property, String arg0, String arg1) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_failed_to_reindex, arg0, arg1)); return this; }
[ "public", "FessMessages", "addErrorsFailedToReindex", "(", "String", "property", ",", "String", "arg0", ",", "String", "arg1", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "ERRORS_failed_to_reindex", ",", "arg0", ",", "arg1", ")", ")", ";", "return", "this", ";", "}" ]
Add the created action message for the key 'errors.failed_to_reindex' with parameters. <pre> message: Failed to start reindexing from {0} to {1} </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @param arg1 The parameter arg1 for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "errors", ".", "failed_to_reindex", "with", "parameters", ".", "<pre", ">", "message", ":", "Failed", "to", "start", "reindexing", "from", "{", "0", "}", "to", "{", "1", "}", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L1935-L1939
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java
Subtypes2.addSupertypeEdges
private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) { """ Add supertype edges to the InheritanceGraph for given ClassVertex. If any direct supertypes have not been processed, add them to the worklist. @param vertex a ClassVertex whose supertype edges need to be added @param workList work list of ClassVertexes that need to have their supertype edges added """ XClass xclass = vertex.getXClass(); // Direct superclass ClassDescriptor superclassDescriptor = xclass.getSuperclassDescriptor(); if (superclassDescriptor != null) { addInheritanceEdge(vertex, superclassDescriptor, false, workList); } // Directly implemented interfaces for (ClassDescriptor ifaceDesc : xclass.getInterfaceDescriptorList()) { addInheritanceEdge(vertex, ifaceDesc, true, workList); } }
java
private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) { XClass xclass = vertex.getXClass(); // Direct superclass ClassDescriptor superclassDescriptor = xclass.getSuperclassDescriptor(); if (superclassDescriptor != null) { addInheritanceEdge(vertex, superclassDescriptor, false, workList); } // Directly implemented interfaces for (ClassDescriptor ifaceDesc : xclass.getInterfaceDescriptorList()) { addInheritanceEdge(vertex, ifaceDesc, true, workList); } }
[ "private", "void", "addSupertypeEdges", "(", "ClassVertex", "vertex", ",", "LinkedList", "<", "XClass", ">", "workList", ")", "{", "XClass", "xclass", "=", "vertex", ".", "getXClass", "(", ")", ";", "// Direct superclass", "ClassDescriptor", "superclassDescriptor", "=", "xclass", ".", "getSuperclassDescriptor", "(", ")", ";", "if", "(", "superclassDescriptor", "!=", "null", ")", "{", "addInheritanceEdge", "(", "vertex", ",", "superclassDescriptor", ",", "false", ",", "workList", ")", ";", "}", "// Directly implemented interfaces", "for", "(", "ClassDescriptor", "ifaceDesc", ":", "xclass", ".", "getInterfaceDescriptorList", "(", ")", ")", "{", "addInheritanceEdge", "(", "vertex", ",", "ifaceDesc", ",", "true", ",", "workList", ")", ";", "}", "}" ]
Add supertype edges to the InheritanceGraph for given ClassVertex. If any direct supertypes have not been processed, add them to the worklist. @param vertex a ClassVertex whose supertype edges need to be added @param workList work list of ClassVertexes that need to have their supertype edges added
[ "Add", "supertype", "edges", "to", "the", "InheritanceGraph", "for", "given", "ClassVertex", ".", "If", "any", "direct", "supertypes", "have", "not", "been", "processed", "add", "them", "to", "the", "worklist", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/ch/Subtypes2.java#L1307-L1320
haraldk/TwelveMonkeys
common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java
MagickUtil.rgbToBuffered
private static BufferedImage rgbToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException { """ Converts an (A)RGB {@code MagickImage} to a {@code BufferedImage}, of type {@code TYPE_4BYTE_ABGR} or {@code TYPE_3BYTE_BGR}. @param pImage the original {@code MagickImage} @param pAlpha keep alpha channel @return a new {@code BufferedImage} @throws MagickException if an exception occurs during conversion @see BufferedImage """ Dimension size = pImage.getDimension(); int length = size.width * size.height; int bands = pAlpha ? 4 : 3; byte[] pixels = new byte[length * bands]; // TODO: If we do multiple dispatches (one per line, typically), we could provide listener // feedback. But it's currently a lot slower than fetching all the pixels in one go. // Note: The ordering ABGR or BGR corresponds to BufferedImage // TYPE_4BYTE_ABGR and TYPE_3BYTE_BGR respectively pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "ABGR" : "BGR", pixels); // Init databuffer with array, to avoid allocation of empty array DataBuffer buffer = new DataBufferByte(pixels, pixels.length); int[] bandOffsets = pAlpha ? BAND_OFF_TRANS : BAND_OFF_OPAQUE; WritableRaster raster = Raster.createInterleavedRaster(buffer, size.width, size.height, size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT); return new BufferedImage(pAlpha ? CM_COLOR_ALPHA : CM_COLOR_OPAQUE, raster, pAlpha, null); }
java
private static BufferedImage rgbToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException { Dimension size = pImage.getDimension(); int length = size.width * size.height; int bands = pAlpha ? 4 : 3; byte[] pixels = new byte[length * bands]; // TODO: If we do multiple dispatches (one per line, typically), we could provide listener // feedback. But it's currently a lot slower than fetching all the pixels in one go. // Note: The ordering ABGR or BGR corresponds to BufferedImage // TYPE_4BYTE_ABGR and TYPE_3BYTE_BGR respectively pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "ABGR" : "BGR", pixels); // Init databuffer with array, to avoid allocation of empty array DataBuffer buffer = new DataBufferByte(pixels, pixels.length); int[] bandOffsets = pAlpha ? BAND_OFF_TRANS : BAND_OFF_OPAQUE; WritableRaster raster = Raster.createInterleavedRaster(buffer, size.width, size.height, size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT); return new BufferedImage(pAlpha ? CM_COLOR_ALPHA : CM_COLOR_OPAQUE, raster, pAlpha, null); }
[ "private", "static", "BufferedImage", "rgbToBuffered", "(", "MagickImage", "pImage", ",", "boolean", "pAlpha", ")", "throws", "MagickException", "{", "Dimension", "size", "=", "pImage", ".", "getDimension", "(", ")", ";", "int", "length", "=", "size", ".", "width", "*", "size", ".", "height", ";", "int", "bands", "=", "pAlpha", "?", "4", ":", "3", ";", "byte", "[", "]", "pixels", "=", "new", "byte", "[", "length", "*", "bands", "]", ";", "// TODO: If we do multiple dispatches (one per line, typically), we could provide listener\r", "// feedback. But it's currently a lot slower than fetching all the pixels in one go.\r", "// Note: The ordering ABGR or BGR corresponds to BufferedImage\r", "// TYPE_4BYTE_ABGR and TYPE_3BYTE_BGR respectively\r", "pImage", ".", "dispatchImage", "(", "0", ",", "0", ",", "size", ".", "width", ",", "size", ".", "height", ",", "pAlpha", "?", "\"ABGR\"", ":", "\"BGR\"", ",", "pixels", ")", ";", "// Init databuffer with array, to avoid allocation of empty array\r", "DataBuffer", "buffer", "=", "new", "DataBufferByte", "(", "pixels", ",", "pixels", ".", "length", ")", ";", "int", "[", "]", "bandOffsets", "=", "pAlpha", "?", "BAND_OFF_TRANS", ":", "BAND_OFF_OPAQUE", ";", "WritableRaster", "raster", "=", "Raster", ".", "createInterleavedRaster", "(", "buffer", ",", "size", ".", "width", ",", "size", ".", "height", ",", "size", ".", "width", "*", "bands", ",", "bands", ",", "bandOffsets", ",", "LOCATION_UPPER_LEFT", ")", ";", "return", "new", "BufferedImage", "(", "pAlpha", "?", "CM_COLOR_ALPHA", ":", "CM_COLOR_OPAQUE", ",", "raster", ",", "pAlpha", ",", "null", ")", ";", "}" ]
Converts an (A)RGB {@code MagickImage} to a {@code BufferedImage}, of type {@code TYPE_4BYTE_ABGR} or {@code TYPE_3BYTE_BGR}. @param pImage the original {@code MagickImage} @param pAlpha keep alpha channel @return a new {@code BufferedImage} @throws MagickException if an exception occurs during conversion @see BufferedImage
[ "Converts", "an", "(", "A", ")", "RGB", "{", "@code", "MagickImage", "}", "to", "a", "{", "@code", "BufferedImage", "}", "of", "type", "{", "@code", "TYPE_4BYTE_ABGR", "}", "or", "{", "@code", "TYPE_3BYTE_BGR", "}", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java#L536-L559
apereo/cas
core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java
WebUtils.putServiceOriginalUrlIntoRequestScope
public static void putServiceOriginalUrlIntoRequestScope(final RequestContext requestContext, final WebApplicationService service) { """ Put service original url into request scope. @param requestContext the request context @param service the service """ requestContext.getRequestScope().put("originalUrl", service.getOriginalUrl()); }
java
public static void putServiceOriginalUrlIntoRequestScope(final RequestContext requestContext, final WebApplicationService service) { requestContext.getRequestScope().put("originalUrl", service.getOriginalUrl()); }
[ "public", "static", "void", "putServiceOriginalUrlIntoRequestScope", "(", "final", "RequestContext", "requestContext", ",", "final", "WebApplicationService", "service", ")", "{", "requestContext", ".", "getRequestScope", "(", ")", ".", "put", "(", "\"originalUrl\"", ",", "service", ".", "getOriginalUrl", "(", ")", ")", ";", "}" ]
Put service original url into request scope. @param requestContext the request context @param service the service
[ "Put", "service", "original", "url", "into", "request", "scope", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java#L773-L775
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.VarArray
public JBBPDslBuilder VarArray(final String name, final int size) { """ Create named var array with fixed size. @param size size of the array, if negative then read till end of stream. @return the builder instance, must not be null """ return this.VarArray(name, arraySizeToString(size), null); }
java
public JBBPDslBuilder VarArray(final String name, final int size) { return this.VarArray(name, arraySizeToString(size), null); }
[ "public", "JBBPDslBuilder", "VarArray", "(", "final", "String", "name", ",", "final", "int", "size", ")", "{", "return", "this", ".", "VarArray", "(", "name", ",", "arraySizeToString", "(", "size", ")", ",", "null", ")", ";", "}" ]
Create named var array with fixed size. @param size size of the array, if negative then read till end of stream. @return the builder instance, must not be null
[ "Create", "named", "var", "array", "with", "fixed", "size", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L439-L441
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java
SessionUtilExternalBrowser.getServerSocket
protected ServerSocket getServerSocket() throws SFException { """ Gets a free port on localhost @return port number @throws SFException raised if an error occurs. """ try { return new ServerSocket( 0, // free port 0, // default number of connections InetAddress.getByName("localhost")); } catch (IOException ex) { throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage()); } }
java
protected ServerSocket getServerSocket() throws SFException { try { return new ServerSocket( 0, // free port 0, // default number of connections InetAddress.getByName("localhost")); } catch (IOException ex) { throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage()); } }
[ "protected", "ServerSocket", "getServerSocket", "(", ")", "throws", "SFException", "{", "try", "{", "return", "new", "ServerSocket", "(", "0", ",", "// free port", "0", ",", "// default number of connections", "InetAddress", ".", "getByName", "(", "\"localhost\"", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "SFException", "(", "ex", ",", "ErrorCode", ".", "NETWORK_ERROR", ",", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Gets a free port on localhost @return port number @throws SFException raised if an error occurs.
[ "Gets", "a", "free", "port", "on", "localhost" ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java#L155-L168
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java
IntrospectionUtils.findInstanceMethod
public static MethodHandle findInstanceMethod(Class<?> clazz, String methodName, Class<?> expectedReturnType, Class<?>... expectedParameterTypes) { """ Finds and returns a MethodHandle for a public instance method. @param clazz the class to search @param methodName the name of the method @param expectedReturnType the expected return type. If {@code null}, any return type is treated as valid. @param expectedParameterTypes expected parameter types @return a MethodHandle for the specified criteria. Returns {@code null} if no method exists with the specified criteria. """ return findMethod(clazz, methodName, false, expectedReturnType, expectedParameterTypes); }
java
public static MethodHandle findInstanceMethod(Class<?> clazz, String methodName, Class<?> expectedReturnType, Class<?>... expectedParameterTypes) { return findMethod(clazz, methodName, false, expectedReturnType, expectedParameterTypes); }
[ "public", "static", "MethodHandle", "findInstanceMethod", "(", "Class", "<", "?", ">", "clazz", ",", "String", "methodName", ",", "Class", "<", "?", ">", "expectedReturnType", ",", "Class", "<", "?", ">", "...", "expectedParameterTypes", ")", "{", "return", "findMethod", "(", "clazz", ",", "methodName", ",", "false", ",", "expectedReturnType", ",", "expectedParameterTypes", ")", ";", "}" ]
Finds and returns a MethodHandle for a public instance method. @param clazz the class to search @param methodName the name of the method @param expectedReturnType the expected return type. If {@code null}, any return type is treated as valid. @param expectedParameterTypes expected parameter types @return a MethodHandle for the specified criteria. Returns {@code null} if no method exists with the specified criteria.
[ "Finds", "and", "returns", "a", "MethodHandle", "for", "a", "public", "instance", "method", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java#L437-L440
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/Services.java
Services.deploymentUnitName
public static ServiceName deploymentUnitName(String name, Phase phase) { """ Get the service name of a top-level deployment unit. @param name the simple name of the deployment @param phase the deployment phase @return the service name """ return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name()); }
java
public static ServiceName deploymentUnitName(String name, Phase phase) { return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name()); }
[ "public", "static", "ServiceName", "deploymentUnitName", "(", "String", "name", ",", "Phase", "phase", ")", "{", "return", "JBOSS_DEPLOYMENT_UNIT", ".", "append", "(", "name", ",", "phase", ".", "name", "(", ")", ")", ";", "}" ]
Get the service name of a top-level deployment unit. @param name the simple name of the deployment @param phase the deployment phase @return the service name
[ "Get", "the", "service", "name", "of", "a", "top", "-", "level", "deployment", "unit", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/Services.java#L83-L85
pac4j/pac4j
pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPPostSimpleSignEncoder.java
Pac4jHTTPPostSimpleSignEncoder.getEndpointURL
@Override protected URI getEndpointURL(MessageContext<SAMLObject> messageContext) throws MessageEncodingException { """ Gets the response URL from the message context. @param messageContext current message context @return response URL from the message context @throws MessageEncodingException throw if no relying party endpoint is available """ try { return SAMLBindingSupport.getEndpointURL(messageContext); } catch (BindingException e) { throw new MessageEncodingException("Could not obtain message endpoint URL", e); } }
java
@Override protected URI getEndpointURL(MessageContext<SAMLObject> messageContext) throws MessageEncodingException { try { return SAMLBindingSupport.getEndpointURL(messageContext); } catch (BindingException e) { throw new MessageEncodingException("Could not obtain message endpoint URL", e); } }
[ "@", "Override", "protected", "URI", "getEndpointURL", "(", "MessageContext", "<", "SAMLObject", ">", "messageContext", ")", "throws", "MessageEncodingException", "{", "try", "{", "return", "SAMLBindingSupport", ".", "getEndpointURL", "(", "messageContext", ")", ";", "}", "catch", "(", "BindingException", "e", ")", "{", "throw", "new", "MessageEncodingException", "(", "\"Could not obtain message endpoint URL\"", ",", "e", ")", ";", "}", "}" ]
Gets the response URL from the message context. @param messageContext current message context @return response URL from the message context @throws MessageEncodingException throw if no relying party endpoint is available
[ "Gets", "the", "response", "URL", "from", "the", "message", "context", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPPostSimpleSignEncoder.java#L40-L47
Netflix/ndbench
ndbench-dynamodb-plugins/src/main/java/com/netflix/ndbench/plugin/dynamodb/DynamoDBProgrammaticKeyValue.java
DynamoDBProgrammaticKeyValue.createHighResolutionAlarm
private void createHighResolutionAlarm(String alarmName, String metricName, double threshold) { """ A high-resolution alarm is one that is configured to fire on threshold breaches of high-resolution metrics. See this [announcement](https://aws.amazon.com/about-aws/whats-new/2017/07/amazon-cloudwatch-introduces-high-resolution-custom-metrics-and-alarms/). DynamoDB only publishes 1 minute consumed capacity metrics. By publishing high resolution consumed capacity metrics on the client side, you can react and alarm on spikes in load much quicker. @param alarmName name of the high resolution alarm to create @param metricName name of the metric to alarm on @param threshold threshold at which to alarm on after 5 breaches of the threshold """ putMetricAlarm.apply(new PutMetricAlarmRequest() .withNamespace(CUSTOM_TABLE_METRICS_NAMESPACE) .withDimensions(tableDimension) .withMetricName(metricName) .withAlarmName(alarmName) .withStatistic(Statistic.Sum) .withUnit(StandardUnit.Count) .withComparisonOperator(ComparisonOperator.GreaterThanThreshold) .withDatapointsToAlarm(5).withEvaluationPeriods(5) //alarm when 5 out of 5 consecutive measurements are high .withActionsEnabled(false) //TODO add actions in a later PR .withPeriod(10) //high resolution alarm .withThreshold(10 * threshold)); }
java
private void createHighResolutionAlarm(String alarmName, String metricName, double threshold) { putMetricAlarm.apply(new PutMetricAlarmRequest() .withNamespace(CUSTOM_TABLE_METRICS_NAMESPACE) .withDimensions(tableDimension) .withMetricName(metricName) .withAlarmName(alarmName) .withStatistic(Statistic.Sum) .withUnit(StandardUnit.Count) .withComparisonOperator(ComparisonOperator.GreaterThanThreshold) .withDatapointsToAlarm(5).withEvaluationPeriods(5) //alarm when 5 out of 5 consecutive measurements are high .withActionsEnabled(false) //TODO add actions in a later PR .withPeriod(10) //high resolution alarm .withThreshold(10 * threshold)); }
[ "private", "void", "createHighResolutionAlarm", "(", "String", "alarmName", ",", "String", "metricName", ",", "double", "threshold", ")", "{", "putMetricAlarm", ".", "apply", "(", "new", "PutMetricAlarmRequest", "(", ")", ".", "withNamespace", "(", "CUSTOM_TABLE_METRICS_NAMESPACE", ")", ".", "withDimensions", "(", "tableDimension", ")", ".", "withMetricName", "(", "metricName", ")", ".", "withAlarmName", "(", "alarmName", ")", ".", "withStatistic", "(", "Statistic", ".", "Sum", ")", ".", "withUnit", "(", "StandardUnit", ".", "Count", ")", ".", "withComparisonOperator", "(", "ComparisonOperator", ".", "GreaterThanThreshold", ")", ".", "withDatapointsToAlarm", "(", "5", ")", ".", "withEvaluationPeriods", "(", "5", ")", "//alarm when 5 out of 5 consecutive measurements are high", ".", "withActionsEnabled", "(", "false", ")", "//TODO add actions in a later PR", ".", "withPeriod", "(", "10", ")", "//high resolution alarm", ".", "withThreshold", "(", "10", "*", "threshold", ")", ")", ";", "}" ]
A high-resolution alarm is one that is configured to fire on threshold breaches of high-resolution metrics. See this [announcement](https://aws.amazon.com/about-aws/whats-new/2017/07/amazon-cloudwatch-introduces-high-resolution-custom-metrics-and-alarms/). DynamoDB only publishes 1 minute consumed capacity metrics. By publishing high resolution consumed capacity metrics on the client side, you can react and alarm on spikes in load much quicker. @param alarmName name of the high resolution alarm to create @param metricName name of the metric to alarm on @param threshold threshold at which to alarm on after 5 breaches of the threshold
[ "A", "high", "-", "resolution", "alarm", "is", "one", "that", "is", "configured", "to", "fire", "on", "threshold", "breaches", "of", "high", "-", "resolution", "metrics", ".", "See", "this", "[", "announcement", "]", "(", "https", ":", "//", "aws", ".", "amazon", ".", "com", "/", "about", "-", "aws", "/", "whats", "-", "new", "/", "2017", "/", "07", "/", "amazon", "-", "cloudwatch", "-", "introduces", "-", "high", "-", "resolution", "-", "custom", "-", "metrics", "-", "and", "-", "alarms", "/", ")", ".", "DynamoDB", "only", "publishes", "1", "minute", "consumed", "capacity", "metrics", ".", "By", "publishing", "high", "resolution", "consumed", "capacity", "metrics", "on", "the", "client", "side", "you", "can", "react", "and", "alarm", "on", "spikes", "in", "load", "much", "quicker", "." ]
train
https://github.com/Netflix/ndbench/blob/8d664244b5f9d01395248a296b86a3c822e6d764/ndbench-dynamodb-plugins/src/main/java/com/netflix/ndbench/plugin/dynamodb/DynamoDBProgrammaticKeyValue.java#L169-L182
weld/core
impl/src/main/java/org/jboss/weld/annotated/runtime/InvokableAnnotatedMethod.java
InvokableAnnotatedMethod.invokeOnInstance
public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { """ Invokes the method on the class of the passed instance, not the declaring class. Useful with proxies @param instance The instance to invoke @param manager The Bean manager @return A reference to the instance """ final Map<Class<?>, Method> methods = this.methods; Method method = methods.get(instance.getClass()); if (method == null) { // the same method may be written to the map twice, but that is ok // lookupMethod is very slow Method delegate = annotatedMethod.getJavaMember(); method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes()); SecurityActions.ensureAccessible(method); synchronized (this) { final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods); newMethods.put(instance.getClass(), method); this.methods = WeldCollections.immutableMapView(newMethods); } } return cast(method.invoke(instance, parameters)); }
java
public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Map<Class<?>, Method> methods = this.methods; Method method = methods.get(instance.getClass()); if (method == null) { // the same method may be written to the map twice, but that is ok // lookupMethod is very slow Method delegate = annotatedMethod.getJavaMember(); method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes()); SecurityActions.ensureAccessible(method); synchronized (this) { final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods); newMethods.put(instance.getClass(), method); this.methods = WeldCollections.immutableMapView(newMethods); } } return cast(method.invoke(instance, parameters)); }
[ "public", "<", "X", ">", "X", "invokeOnInstance", "(", "Object", "instance", ",", "Object", "...", "parameters", ")", "throws", "IllegalArgumentException", ",", "SecurityException", ",", "IllegalAccessException", ",", "InvocationTargetException", ",", "NoSuchMethodException", "{", "final", "Map", "<", "Class", "<", "?", ">", ",", "Method", ">", "methods", "=", "this", ".", "methods", ";", "Method", "method", "=", "methods", ".", "get", "(", "instance", ".", "getClass", "(", ")", ")", ";", "if", "(", "method", "==", "null", ")", "{", "// the same method may be written to the map twice, but that is ok", "// lookupMethod is very slow", "Method", "delegate", "=", "annotatedMethod", ".", "getJavaMember", "(", ")", ";", "method", "=", "SecurityActions", ".", "lookupMethod", "(", "instance", ".", "getClass", "(", ")", ",", "delegate", ".", "getName", "(", ")", ",", "delegate", ".", "getParameterTypes", "(", ")", ")", ";", "SecurityActions", ".", "ensureAccessible", "(", "method", ")", ";", "synchronized", "(", "this", ")", "{", "final", "Map", "<", "Class", "<", "?", ">", ",", "Method", ">", "newMethods", "=", "new", "HashMap", "<", "Class", "<", "?", ">", ",", "Method", ">", "(", "methods", ")", ";", "newMethods", ".", "put", "(", "instance", ".", "getClass", "(", ")", ",", "method", ")", ";", "this", ".", "methods", "=", "WeldCollections", ".", "immutableMapView", "(", "newMethods", ")", ";", "}", "}", "return", "cast", "(", "method", ".", "invoke", "(", "instance", ",", "parameters", ")", ")", ";", "}" ]
Invokes the method on the class of the passed instance, not the declaring class. Useful with proxies @param instance The instance to invoke @param manager The Bean manager @return A reference to the instance
[ "Invokes", "the", "method", "on", "the", "class", "of", "the", "passed", "instance", "not", "the", "declaring", "class", ".", "Useful", "with", "proxies" ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/annotated/runtime/InvokableAnnotatedMethod.java#L71-L87
Stratio/deep-spark
deep-jdbc/src/main/java/com/stratio/deep/jdbc/extractor/JdbcNativeCellExtractor.java
JdbcNativeCellExtractor.transformElement
@Override protected Cells transformElement(Map<String, Object> entity) { """ Transforms a database row represented as a Map into a Cells object. @param entity Database row represented as a Map of column name:column value. @return Cells object with database row data. """ return UtilJdbc.getCellsFromObject(entity, jdbcDeepJobConfig); }
java
@Override protected Cells transformElement(Map<String, Object> entity) { return UtilJdbc.getCellsFromObject(entity, jdbcDeepJobConfig); }
[ "@", "Override", "protected", "Cells", "transformElement", "(", "Map", "<", "String", ",", "Object", ">", "entity", ")", "{", "return", "UtilJdbc", ".", "getCellsFromObject", "(", "entity", ",", "jdbcDeepJobConfig", ")", ";", "}" ]
Transforms a database row represented as a Map into a Cells object. @param entity Database row represented as a Map of column name:column value. @return Cells object with database row data.
[ "Transforms", "a", "database", "row", "represented", "as", "a", "Map", "into", "a", "Cells", "object", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-jdbc/src/main/java/com/stratio/deep/jdbc/extractor/JdbcNativeCellExtractor.java#L48-L51
SeaCloudsEU/SeaCloudsPlatform
sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRest.java
TemplateRest.createTemplate
@POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createTemplate(@Context HttpHeaders hh,@Context UriInfo uriInfo, String payload) { """ Returns the information of an specific template If the template it is not in the database, it returns 404 with empty payload /** Creates a new agreement <pre> POST /templates Request: POST /templates HTTP/1.1 Accept: application/xml Response: HTTP/1.1 201 Created Content-type: application/xml Location: http://.../templates/$uuid {@code <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message code="201" message= "The template has been stored successfully in the SLA Repository Database"/> } </pre> Example: <li>curl -H "Content-type: application/xml" -X POST -d @template01.xml localhost:8080/sla-service/templates</li> @return XML information that the template has been created successfully """ logger.debug("StartOf createTemplate - Insert /templates"); TemplateHelper templateRestHelper = getTemplateHelper(); try { String location = templateRestHelper.createTemplate(hh, uriInfo.getAbsolutePath().toString(), payload); logger.debug("EndOf createTemplate"); return buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The template has been stored successfully in the SLA Repository Database"), location); } catch (HelperException e) { logger.info("createTemplate exception:"+e.getMessage()); return buildResponse(e); } }
java
@POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createTemplate(@Context HttpHeaders hh,@Context UriInfo uriInfo, String payload) { logger.debug("StartOf createTemplate - Insert /templates"); TemplateHelper templateRestHelper = getTemplateHelper(); try { String location = templateRestHelper.createTemplate(hh, uriInfo.getAbsolutePath().toString(), payload); logger.debug("EndOf createTemplate"); return buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The template has been stored successfully in the SLA Repository Database"), location); } catch (HelperException e) { logger.info("createTemplate exception:"+e.getMessage()); return buildResponse(e); } }
[ "@", "POST", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_XML", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_XML", ")", "public", "Response", "createTemplate", "(", "@", "Context", "HttpHeaders", "hh", ",", "@", "Context", "UriInfo", "uriInfo", ",", "String", "payload", ")", "{", "logger", ".", "debug", "(", "\"StartOf createTemplate - Insert /templates\"", ")", ";", "TemplateHelper", "templateRestHelper", "=", "getTemplateHelper", "(", ")", ";", "try", "{", "String", "location", "=", "templateRestHelper", ".", "createTemplate", "(", "hh", ",", "uriInfo", ".", "getAbsolutePath", "(", ")", ".", "toString", "(", ")", ",", "payload", ")", ";", "logger", ".", "debug", "(", "\"EndOf createTemplate\"", ")", ";", "return", "buildResponsePOST", "(", "HttpStatus", ".", "CREATED", ",", "printMessage", "(", "HttpStatus", ".", "CREATED", ",", "\"The template has been stored successfully in the SLA Repository Database\"", ")", ",", "location", ")", ";", "}", "catch", "(", "HelperException", "e", ")", "{", "logger", ".", "info", "(", "\"createTemplate exception:\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "return", "buildResponse", "(", "e", ")", ";", "}", "}" ]
Returns the information of an specific template If the template it is not in the database, it returns 404 with empty payload /** Creates a new agreement <pre> POST /templates Request: POST /templates HTTP/1.1 Accept: application/xml Response: HTTP/1.1 201 Created Content-type: application/xml Location: http://.../templates/$uuid {@code <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message code="201" message= "The template has been stored successfully in the SLA Repository Database"/> } </pre> Example: <li>curl -H "Content-type: application/xml" -X POST -d @template01.xml localhost:8080/sla-service/templates</li> @return XML information that the template has been created successfully
[ "Returns", "the", "information", "of", "an", "specific", "template", "If", "the", "template", "it", "is", "not", "in", "the", "database", "it", "returns", "404", "with", "empty", "payload", "/", "**", "Creates", "a", "new", "agreement" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRest.java#L302-L323
forge/core
shell/impl/src/main/java/org/jboss/forge/addon/shell/util/ShellUtil.java
ShellUtil.colorizeResource
public static String colorizeResource(FileResource<?> resource) { """ Applies ANSI colors in a specific resource @param resource @return """ String name = resource.getName(); if (resource.isDirectory()) { name = new TerminalString(name, new TerminalColor(Color.BLUE, Color.DEFAULT)).toString(); } else if (resource.isExecutable()) { name = new TerminalString(name, new TerminalColor(Color.GREEN, Color.DEFAULT)).toString(); } return name; }
java
public static String colorizeResource(FileResource<?> resource) { String name = resource.getName(); if (resource.isDirectory()) { name = new TerminalString(name, new TerminalColor(Color.BLUE, Color.DEFAULT)).toString(); } else if (resource.isExecutable()) { name = new TerminalString(name, new TerminalColor(Color.GREEN, Color.DEFAULT)).toString(); } return name; }
[ "public", "static", "String", "colorizeResource", "(", "FileResource", "<", "?", ">", "resource", ")", "{", "String", "name", "=", "resource", ".", "getName", "(", ")", ";", "if", "(", "resource", ".", "isDirectory", "(", ")", ")", "{", "name", "=", "new", "TerminalString", "(", "name", ",", "new", "TerminalColor", "(", "Color", ".", "BLUE", ",", "Color", ".", "DEFAULT", ")", ")", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "resource", ".", "isExecutable", "(", ")", ")", "{", "name", "=", "new", "TerminalString", "(", "name", ",", "new", "TerminalColor", "(", "Color", ".", "GREEN", ",", "Color", ".", "DEFAULT", ")", ")", ".", "toString", "(", ")", ";", "}", "return", "name", ";", "}" ]
Applies ANSI colors in a specific resource @param resource @return
[ "Applies", "ANSI", "colors", "in", "a", "specific", "resource" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/shell/impl/src/main/java/org/jboss/forge/addon/shell/util/ShellUtil.java#L64-L76
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/DiscreteDistributions.java
DiscreteDistributions.hypergeometricCdf
public static double hypergeometricCdf(int k, int n, int Kp, int Np) { """ Returns the cumulative probability of hypergeometric @param k @param n @param Kp @param Np @return """ if(k<0 || n<0 || Kp<0 || Np<0) { throw new IllegalArgumentException("All the parameters must be positive."); } Kp = Math.max(k, Kp); Np = Math.max(n, Np); /* //slow! $probabilitySum=0; for($i=0;$i<=$k;++$i) { $probabilitySum+=self::hypergeometric($i,$n,$Kp,$Np); } */ //fast and can handle large numbers //Cdf(k)-Cdf(k-1) double probabilitySum = approxHypergeometricCdf(k,n,Kp,Np); return probabilitySum; }
java
public static double hypergeometricCdf(int k, int n, int Kp, int Np) { if(k<0 || n<0 || Kp<0 || Np<0) { throw new IllegalArgumentException("All the parameters must be positive."); } Kp = Math.max(k, Kp); Np = Math.max(n, Np); /* //slow! $probabilitySum=0; for($i=0;$i<=$k;++$i) { $probabilitySum+=self::hypergeometric($i,$n,$Kp,$Np); } */ //fast and can handle large numbers //Cdf(k)-Cdf(k-1) double probabilitySum = approxHypergeometricCdf(k,n,Kp,Np); return probabilitySum; }
[ "public", "static", "double", "hypergeometricCdf", "(", "int", "k", ",", "int", "n", ",", "int", "Kp", ",", "int", "Np", ")", "{", "if", "(", "k", "<", "0", "||", "n", "<", "0", "||", "Kp", "<", "0", "||", "Np", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"All the parameters must be positive.\"", ")", ";", "}", "Kp", "=", "Math", ".", "max", "(", "k", ",", "Kp", ")", ";", "Np", "=", "Math", ".", "max", "(", "n", ",", "Np", ")", ";", "/*\n //slow!\n $probabilitySum=0;\n for($i=0;$i<=$k;++$i) {\n $probabilitySum+=self::hypergeometric($i,$n,$Kp,$Np);\n }\n */", "//fast and can handle large numbers", "//Cdf(k)-Cdf(k-1)", "double", "probabilitySum", "=", "approxHypergeometricCdf", "(", "k", ",", "n", ",", "Kp", ",", "Np", ")", ";", "return", "probabilitySum", ";", "}" ]
Returns the cumulative probability of hypergeometric @param k @param n @param Kp @param Np @return
[ "Returns", "the", "cumulative", "probability", "of", "hypergeometric" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/DiscreteDistributions.java#L300-L320
openengsb/openengsb
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/AbstractStandardTransformationOperation.java
AbstractStandardTransformationOperation.generateMatcher
protected Matcher generateMatcher(String regex, String valueString) throws TransformationOperationException { """ Generates a matcher for the given valueString with the given regular expression. """ if (regex == null) { throw new TransformationOperationException("No regex defined. The step will be skipped."); } try { Pattern pattern = Pattern.compile(regex); return pattern.matcher(valueString); } catch (PatternSyntaxException e) { String message = String.format("Given regex string %s can't be compiled. The step will be skipped.", regex); logger.warn(message); throw new TransformationOperationException(message); } }
java
protected Matcher generateMatcher(String regex, String valueString) throws TransformationOperationException { if (regex == null) { throw new TransformationOperationException("No regex defined. The step will be skipped."); } try { Pattern pattern = Pattern.compile(regex); return pattern.matcher(valueString); } catch (PatternSyntaxException e) { String message = String.format("Given regex string %s can't be compiled. The step will be skipped.", regex); logger.warn(message); throw new TransformationOperationException(message); } }
[ "protected", "Matcher", "generateMatcher", "(", "String", "regex", ",", "String", "valueString", ")", "throws", "TransformationOperationException", "{", "if", "(", "regex", "==", "null", ")", "{", "throw", "new", "TransformationOperationException", "(", "\"No regex defined. The step will be skipped.\"", ")", ";", "}", "try", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "regex", ")", ";", "return", "pattern", ".", "matcher", "(", "valueString", ")", ";", "}", "catch", "(", "PatternSyntaxException", "e", ")", "{", "String", "message", "=", "String", ".", "format", "(", "\"Given regex string %s can't be compiled. The step will be skipped.\"", ",", "regex", ")", ";", "logger", ".", "warn", "(", "message", ")", ";", "throw", "new", "TransformationOperationException", "(", "message", ")", ";", "}", "}" ]
Generates a matcher for the given valueString with the given regular expression.
[ "Generates", "a", "matcher", "for", "the", "given", "valueString", "with", "the", "given", "regular", "expression", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/AbstractStandardTransformationOperation.java#L152-L166
ontop/ontop
core/obda/src/main/java/it/unibz/inf/ontop/spec/ontology/impl/OntologyBuilderImpl.java
OntologyBuilderImpl.createClassAssertion
public static ClassAssertion createClassAssertion(OClass ce, ObjectConstant object) throws InconsistentOntologyException { """ Creates a class assertion <p> ClassAssertion := 'ClassAssertion' '(' axiomAnnotations Class Individual ')' <p> Implements rule [C4]: - ignore (return null) if the class is top - inconsistency if the class is bot """ if (ce.isTop()) return null; if (ce.isBottom()) throw new InconsistentOntologyException(); return new ClassAssertionImpl(ce, object); }
java
public static ClassAssertion createClassAssertion(OClass ce, ObjectConstant object) throws InconsistentOntologyException { if (ce.isTop()) return null; if (ce.isBottom()) throw new InconsistentOntologyException(); return new ClassAssertionImpl(ce, object); }
[ "public", "static", "ClassAssertion", "createClassAssertion", "(", "OClass", "ce", ",", "ObjectConstant", "object", ")", "throws", "InconsistentOntologyException", "{", "if", "(", "ce", ".", "isTop", "(", ")", ")", "return", "null", ";", "if", "(", "ce", ".", "isBottom", "(", ")", ")", "throw", "new", "InconsistentOntologyException", "(", ")", ";", "return", "new", "ClassAssertionImpl", "(", "ce", ",", "object", ")", ";", "}" ]
Creates a class assertion <p> ClassAssertion := 'ClassAssertion' '(' axiomAnnotations Class Individual ')' <p> Implements rule [C4]: - ignore (return null) if the class is top - inconsistency if the class is bot
[ "Creates", "a", "class", "assertion", "<p", ">", "ClassAssertion", ":", "=", "ClassAssertion", "(", "axiomAnnotations", "Class", "Individual", ")", "<p", ">", "Implements", "rule", "[", "C4", "]", ":", "-", "ignore", "(", "return", "null", ")", "if", "the", "class", "is", "top", "-", "inconsistency", "if", "the", "class", "is", "bot" ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/core/obda/src/main/java/it/unibz/inf/ontop/spec/ontology/impl/OntologyBuilderImpl.java#L436-L443
OpenBEL/openbel-framework
org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/xgmml/XGMMLUtility.java
XGMMLUtility.writeStart
public static void writeStart(String name, PrintWriter writer) { """ Write the XGMML start using the {@code graphName} as the label. @param name {@link String}, the name of the XGMML graph @param writer {@link PrintWriter}, the writer """ StringBuilder sb = new StringBuilder(); sb.append("<graph xmlns='http://www.cs.rpi.edu/XGMML' ") .append("xmlns:ns2='http://www.w3.org/1999/xlink' ") .append("xmlns:cy='http://www.cytoscape.org' ") .append("Graphic='1' label='").append(name) .append("' directed='1'>\n"); writer.write(sb.toString()); }
java
public static void writeStart(String name, PrintWriter writer) { StringBuilder sb = new StringBuilder(); sb.append("<graph xmlns='http://www.cs.rpi.edu/XGMML' ") .append("xmlns:ns2='http://www.w3.org/1999/xlink' ") .append("xmlns:cy='http://www.cytoscape.org' ") .append("Graphic='1' label='").append(name) .append("' directed='1'>\n"); writer.write(sb.toString()); }
[ "public", "static", "void", "writeStart", "(", "String", "name", ",", "PrintWriter", "writer", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"<graph xmlns='http://www.cs.rpi.edu/XGMML' \"", ")", ".", "append", "(", "\"xmlns:ns2='http://www.w3.org/1999/xlink' \"", ")", ".", "append", "(", "\"xmlns:cy='http://www.cytoscape.org' \"", ")", ".", "append", "(", "\"Graphic='1' label='\"", ")", ".", "append", "(", "name", ")", ".", "append", "(", "\"' directed='1'>\\n\"", ")", ";", "writer", ".", "write", "(", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Write the XGMML start using the {@code graphName} as the label. @param name {@link String}, the name of the XGMML graph @param writer {@link PrintWriter}, the writer
[ "Write", "the", "XGMML", "start", "using", "the", "{", "@code", "graphName", "}", "as", "the", "label", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/xgmml/XGMMLUtility.java#L259-L267
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/ModuleUiExtensions.java
ModuleUiExtensions.fetchAll
public CMAArray<CMAUiExtension> fetchAll(String spaceId, String environmentId) { """ Fetch ui extensions from a given space. {@link CMAClient.Builder#setSpaceId(String)} and will ignore {@link CMAClient.Builder#setEnvironmentId(String)}. @param spaceId the id of the space this is valid on. @param environmentId the id of the environment this is valid on. @return all the ui extensions for a specific space. @throws IllegalArgumentException if spaceId is null. @throws IllegalArgumentException if environmentId is null. """ return fetchAll(spaceId, environmentId, null); }
java
public CMAArray<CMAUiExtension> fetchAll(String spaceId, String environmentId) { return fetchAll(spaceId, environmentId, null); }
[ "public", "CMAArray", "<", "CMAUiExtension", ">", "fetchAll", "(", "String", "spaceId", ",", "String", "environmentId", ")", "{", "return", "fetchAll", "(", "spaceId", ",", "environmentId", ",", "null", ")", ";", "}" ]
Fetch ui extensions from a given space. {@link CMAClient.Builder#setSpaceId(String)} and will ignore {@link CMAClient.Builder#setEnvironmentId(String)}. @param spaceId the id of the space this is valid on. @param environmentId the id of the environment this is valid on. @return all the ui extensions for a specific space. @throws IllegalArgumentException if spaceId is null. @throws IllegalArgumentException if environmentId is null.
[ "Fetch", "ui", "extensions", "from", "a", "given", "space", ".", "{", "@link", "CMAClient", ".", "Builder#setSpaceId", "(", "String", ")", "}", "and", "will", "ignore", "{", "@link", "CMAClient", ".", "Builder#setEnvironmentId", "(", "String", ")", "}", "." ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/ModuleUiExtensions.java#L137-L139
gfk-ba/senbot
SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/ElementService.java
ElementService.findExpectedFirstMatchedElement
public WebElement findExpectedFirstMatchedElement(int timeoutInSeconds, By... bys) { """ From the passed array of {@link By}'s return the first {@link WebElement} found. The {@link By}'s will be processed in the order that they are passed in. If no element matches any of the {@link By}'s an {@link AssertionError} is thrown causing a test method calling this method to fail. @param timeoutInSeconds timeout to wait for elements to be found @param bys - array of {@link By} @return The first {@link WebElement} found @throws AssertionError if no {@link WebElement} is found or the search times out """ waitForLoaders(); StringBuilder potentialMatches = new StringBuilder(); for (By by : bys) { try { if (potentialMatches.length() > 0) { potentialMatches.append(", "); } potentialMatches.append(by.toString()); WebElement found = new WebDriverWait(getWebDriver(), timeoutInSeconds).until(ExpectedConditions .presenceOfElementLocated(by)); if (found != null) { return found; } } catch (WebDriverException nsee) { // keep checking } } fail("No matches found for: " + potentialMatches.toString()); return null; }
java
public WebElement findExpectedFirstMatchedElement(int timeoutInSeconds, By... bys) { waitForLoaders(); StringBuilder potentialMatches = new StringBuilder(); for (By by : bys) { try { if (potentialMatches.length() > 0) { potentialMatches.append(", "); } potentialMatches.append(by.toString()); WebElement found = new WebDriverWait(getWebDriver(), timeoutInSeconds).until(ExpectedConditions .presenceOfElementLocated(by)); if (found != null) { return found; } } catch (WebDriverException nsee) { // keep checking } } fail("No matches found for: " + potentialMatches.toString()); return null; }
[ "public", "WebElement", "findExpectedFirstMatchedElement", "(", "int", "timeoutInSeconds", ",", "By", "...", "bys", ")", "{", "waitForLoaders", "(", ")", ";", "StringBuilder", "potentialMatches", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "By", "by", ":", "bys", ")", "{", "try", "{", "if", "(", "potentialMatches", ".", "length", "(", ")", ">", "0", ")", "{", "potentialMatches", ".", "append", "(", "\", \"", ")", ";", "}", "potentialMatches", ".", "append", "(", "by", ".", "toString", "(", ")", ")", ";", "WebElement", "found", "=", "new", "WebDriverWait", "(", "getWebDriver", "(", ")", ",", "timeoutInSeconds", ")", ".", "until", "(", "ExpectedConditions", ".", "presenceOfElementLocated", "(", "by", ")", ")", ";", "if", "(", "found", "!=", "null", ")", "{", "return", "found", ";", "}", "}", "catch", "(", "WebDriverException", "nsee", ")", "{", "// keep checking", "}", "}", "fail", "(", "\"No matches found for: \"", "+", "potentialMatches", ".", "toString", "(", ")", ")", ";", "return", "null", ";", "}" ]
From the passed array of {@link By}'s return the first {@link WebElement} found. The {@link By}'s will be processed in the order that they are passed in. If no element matches any of the {@link By}'s an {@link AssertionError} is thrown causing a test method calling this method to fail. @param timeoutInSeconds timeout to wait for elements to be found @param bys - array of {@link By} @return The first {@link WebElement} found @throws AssertionError if no {@link WebElement} is found or the search times out
[ "From", "the", "passed", "array", "of", "{", "@link", "By", "}", "s", "return", "the", "first", "{", "@link", "WebElement", "}", "found", ".", "The", "{", "@link", "By", "}", "s", "will", "be", "processed", "in", "the", "order", "that", "they", "are", "passed", "in", ".", "If", "no", "element", "matches", "any", "of", "the", "{", "@link", "By", "}", "s", "an", "{", "@link", "AssertionError", "}", "is", "thrown", "causing", "a", "test", "method", "calling", "this", "method", "to", "fail", "." ]
train
https://github.com/gfk-ba/senbot/blob/e9a152aa67be48b1bb13a4691655caf6d873b553/SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/ElementService.java#L179-L199
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/writer/TiffWriter.java
TiffWriter.classifyTags
private int classifyTags(IFD ifd, ArrayList<TagValue> oversized, ArrayList<TagValue> undersized) { """ Gets the oversized tags. @param ifd the ifd @param oversized the oversized @param undersized the undersized @return the number of tags """ int tagValueSize = 4; int n = 0; for (TagValue tag : ifd.getMetadata().getTags()) { int tagsize = getTagSize(tag); if (tagsize > tagValueSize) { oversized.add(tag); } else { undersized.add(tag); } n++; } return n; }
java
private int classifyTags(IFD ifd, ArrayList<TagValue> oversized, ArrayList<TagValue> undersized) { int tagValueSize = 4; int n = 0; for (TagValue tag : ifd.getMetadata().getTags()) { int tagsize = getTagSize(tag); if (tagsize > tagValueSize) { oversized.add(tag); } else { undersized.add(tag); } n++; } return n; }
[ "private", "int", "classifyTags", "(", "IFD", "ifd", ",", "ArrayList", "<", "TagValue", ">", "oversized", ",", "ArrayList", "<", "TagValue", ">", "undersized", ")", "{", "int", "tagValueSize", "=", "4", ";", "int", "n", "=", "0", ";", "for", "(", "TagValue", "tag", ":", "ifd", ".", "getMetadata", "(", ")", ".", "getTags", "(", ")", ")", "{", "int", "tagsize", "=", "getTagSize", "(", "tag", ")", ";", "if", "(", "tagsize", ">", "tagValueSize", ")", "{", "oversized", ".", "add", "(", "tag", ")", ";", "}", "else", "{", "undersized", ".", "add", "(", "tag", ")", ";", "}", "n", "++", ";", "}", "return", "n", ";", "}" ]
Gets the oversized tags. @param ifd the ifd @param oversized the oversized @param undersized the undersized @return the number of tags
[ "Gets", "the", "oversized", "tags", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/writer/TiffWriter.java#L175-L188
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java
OjbTagsHandler.createTorqueSchema
public String createTorqueSchema(Properties attributes) throws XDocletException { """ Generates a torque schema for the model. @param attributes The attributes of the tag @return The property value @exception XDocletException If an error occurs @doc.tag type="content" """ String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME); _torqueModel = new TorqueModelDef(dbName, _model); return ""; }
java
public String createTorqueSchema(Properties attributes) throws XDocletException { String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME); _torqueModel = new TorqueModelDef(dbName, _model); return ""; }
[ "public", "String", "createTorqueSchema", "(", "Properties", "attributes", ")", "throws", "XDocletException", "{", "String", "dbName", "=", "(", "String", ")", "getDocletContext", "(", ")", ".", "getConfigParam", "(", "CONFIG_PARAM_DATABASENAME", ")", ";", "_torqueModel", "=", "new", "TorqueModelDef", "(", "dbName", ",", "_model", ")", ";", "return", "\"\"", ";", "}" ]
Generates a torque schema for the model. @param attributes The attributes of the tag @return The property value @exception XDocletException If an error occurs @doc.tag type="content"
[ "Generates", "a", "torque", "schema", "for", "the", "model", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1310-L1316
alkacon/opencms-core
src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryField.java
CmsGalleryField.setImagePreview
protected void setImagePreview(String realPath, String imagePath) { """ Sets the image preview.<p> @param realPath the actual image path @param imagePath the image path """ if ((m_croppingParam == null) || !getFormValueAsString().contains(m_croppingParam.toString())) { m_croppingParam = CmsCroppingParamBean.parseImagePath(getFormValueAsString()); } CmsCroppingParamBean restricted; int marginTop = 0; if (m_croppingParam.getScaleParam().isEmpty()) { imagePath += "?__scale=w:165,h:114,t:1,c:white,r:0"; } else { restricted = m_croppingParam.getRestrictedSizeParam(114, 165); imagePath += "?" + restricted.toString(); marginTop = (114 - restricted.getResultingHeight()) / 2; } Element image = DOM.createImg(); image.setAttribute("src", imagePath); image.getStyle().setMarginTop(marginTop, Unit.PX); if (CmsClientStringUtil.checkIsPathOrLinkToSvg(realPath)) { image.getStyle().setWidth(100, Unit.PCT); image.getStyle().setHeight(100, Unit.PCT); } m_imagePreview.setInnerHTML(""); m_imagePreview.appendChild(image); }
java
protected void setImagePreview(String realPath, String imagePath) { if ((m_croppingParam == null) || !getFormValueAsString().contains(m_croppingParam.toString())) { m_croppingParam = CmsCroppingParamBean.parseImagePath(getFormValueAsString()); } CmsCroppingParamBean restricted; int marginTop = 0; if (m_croppingParam.getScaleParam().isEmpty()) { imagePath += "?__scale=w:165,h:114,t:1,c:white,r:0"; } else { restricted = m_croppingParam.getRestrictedSizeParam(114, 165); imagePath += "?" + restricted.toString(); marginTop = (114 - restricted.getResultingHeight()) / 2; } Element image = DOM.createImg(); image.setAttribute("src", imagePath); image.getStyle().setMarginTop(marginTop, Unit.PX); if (CmsClientStringUtil.checkIsPathOrLinkToSvg(realPath)) { image.getStyle().setWidth(100, Unit.PCT); image.getStyle().setHeight(100, Unit.PCT); } m_imagePreview.setInnerHTML(""); m_imagePreview.appendChild(image); }
[ "protected", "void", "setImagePreview", "(", "String", "realPath", ",", "String", "imagePath", ")", "{", "if", "(", "(", "m_croppingParam", "==", "null", ")", "||", "!", "getFormValueAsString", "(", ")", ".", "contains", "(", "m_croppingParam", ".", "toString", "(", ")", ")", ")", "{", "m_croppingParam", "=", "CmsCroppingParamBean", ".", "parseImagePath", "(", "getFormValueAsString", "(", ")", ")", ";", "}", "CmsCroppingParamBean", "restricted", ";", "int", "marginTop", "=", "0", ";", "if", "(", "m_croppingParam", ".", "getScaleParam", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "imagePath", "+=", "\"?__scale=w:165,h:114,t:1,c:white,r:0\"", ";", "}", "else", "{", "restricted", "=", "m_croppingParam", ".", "getRestrictedSizeParam", "(", "114", ",", "165", ")", ";", "imagePath", "+=", "\"?\"", "+", "restricted", ".", "toString", "(", ")", ";", "marginTop", "=", "(", "114", "-", "restricted", ".", "getResultingHeight", "(", ")", ")", "/", "2", ";", "}", "Element", "image", "=", "DOM", ".", "createImg", "(", ")", ";", "image", ".", "setAttribute", "(", "\"src\"", ",", "imagePath", ")", ";", "image", ".", "getStyle", "(", ")", ".", "setMarginTop", "(", "marginTop", ",", "Unit", ".", "PX", ")", ";", "if", "(", "CmsClientStringUtil", ".", "checkIsPathOrLinkToSvg", "(", "realPath", ")", ")", "{", "image", ".", "getStyle", "(", ")", ".", "setWidth", "(", "100", ",", "Unit", ".", "PCT", ")", ";", "image", ".", "getStyle", "(", ")", ".", "setHeight", "(", "100", ",", "Unit", ".", "PCT", ")", ";", "}", "m_imagePreview", ".", "setInnerHTML", "(", "\"\"", ")", ";", "m_imagePreview", ".", "appendChild", "(", "image", ")", ";", "}" ]
Sets the image preview.<p> @param realPath the actual image path @param imagePath the image path
[ "Sets", "the", "image", "preview", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryField.java#L572-L595
spacecowboy/NoNonsense-FilePicker
library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java
AbstractFilePickerFragment.onClickCheckable
public void onClickCheckable(@NonNull View view, @NonNull CheckableViewHolder viewHolder) { """ Called when a selectable item is clicked. This might be either a file or a directory. @param view that was clicked. Not used in default implementation. @param viewHolder for the clicked view """ if (isDir(viewHolder.file)) { goToDir(viewHolder.file); } else { onLongClickCheckable(view, viewHolder); if (singleClick) { onClickOk(view); } } }
java
public void onClickCheckable(@NonNull View view, @NonNull CheckableViewHolder viewHolder) { if (isDir(viewHolder.file)) { goToDir(viewHolder.file); } else { onLongClickCheckable(view, viewHolder); if (singleClick) { onClickOk(view); } } }
[ "public", "void", "onClickCheckable", "(", "@", "NonNull", "View", "view", ",", "@", "NonNull", "CheckableViewHolder", "viewHolder", ")", "{", "if", "(", "isDir", "(", "viewHolder", ".", "file", ")", ")", "{", "goToDir", "(", "viewHolder", ".", "file", ")", ";", "}", "else", "{", "onLongClickCheckable", "(", "view", ",", "viewHolder", ")", ";", "if", "(", "singleClick", ")", "{", "onClickOk", "(", "view", ")", ";", "}", "}", "}" ]
Called when a selectable item is clicked. This might be either a file or a directory. @param view that was clicked. Not used in default implementation. @param viewHolder for the clicked view
[ "Called", "when", "a", "selectable", "item", "is", "clicked", ".", "This", "might", "be", "either", "a", "file", "or", "a", "directory", "." ]
train
https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java#L765-L774
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ZipChemCompProvider.java
ZipChemCompProvider.addToZipFileSystem
private synchronized boolean addToZipFileSystem(Path zipFile, File[] files, Path pathWithinArchive) { """ Add an array of files to a zip archive. Synchronized to prevent simultaneous reading/writing. @param zipFile is a destination zip archive @param files is an array of files to be added @param pathWithinArchive is the path within the archive to add files to @return true if successfully appended these files. """ boolean ret = false; /* URIs in Java 7 cannot have spaces, must use Path instead * and so, cannot use the properties map to describe need to create * a new zip archive. ZipChemCompProvider.initilizeZip to creates the * missing zip file */ /* // convert the filename to a URI String uriString = "jar:file:" + zipFile.toUri().getPath(); final URI uri = URI.create(uriString); // if filesystem doesn't exist, create one. final Map<String, String> env = new HashMap<>(); // Create a new zip if one isn't present. if (!zipFile.toFile().exists()) { System.out.println("Need to create " + zipFile.toString()); } env.put("create", String.valueOf(!zipFile.toFile().exists())); // Specify the encoding as UTF -8 env.put("encoding", "UTF-8"); */ // Copy in each file. try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, null)) { Files.createDirectories(pathWithinArchive); for (File f : files) { if (!f.isDirectory() && f.exists()) { Path externalFile = f.toPath(); Path pathInZipFile = zipfs.getPath(pathWithinArchive.resolve(f.getName()).toString()); Files.copy(externalFile, pathInZipFile, StandardCopyOption.REPLACE_EXISTING); } } ret = true; } catch (IOException ex) { s_logger.error("Unable to add entries to Chemical Component zip archive : " + ex.getMessage()); ret = false; } return ret; }
java
private synchronized boolean addToZipFileSystem(Path zipFile, File[] files, Path pathWithinArchive) { boolean ret = false; /* URIs in Java 7 cannot have spaces, must use Path instead * and so, cannot use the properties map to describe need to create * a new zip archive. ZipChemCompProvider.initilizeZip to creates the * missing zip file */ /* // convert the filename to a URI String uriString = "jar:file:" + zipFile.toUri().getPath(); final URI uri = URI.create(uriString); // if filesystem doesn't exist, create one. final Map<String, String> env = new HashMap<>(); // Create a new zip if one isn't present. if (!zipFile.toFile().exists()) { System.out.println("Need to create " + zipFile.toString()); } env.put("create", String.valueOf(!zipFile.toFile().exists())); // Specify the encoding as UTF -8 env.put("encoding", "UTF-8"); */ // Copy in each file. try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, null)) { Files.createDirectories(pathWithinArchive); for (File f : files) { if (!f.isDirectory() && f.exists()) { Path externalFile = f.toPath(); Path pathInZipFile = zipfs.getPath(pathWithinArchive.resolve(f.getName()).toString()); Files.copy(externalFile, pathInZipFile, StandardCopyOption.REPLACE_EXISTING); } } ret = true; } catch (IOException ex) { s_logger.error("Unable to add entries to Chemical Component zip archive : " + ex.getMessage()); ret = false; } return ret; }
[ "private", "synchronized", "boolean", "addToZipFileSystem", "(", "Path", "zipFile", ",", "File", "[", "]", "files", ",", "Path", "pathWithinArchive", ")", "{", "boolean", "ret", "=", "false", ";", "/* URIs in Java 7 cannot have spaces, must use Path instead\n\t\t * and so, cannot use the properties map to describe need to create\n\t\t * a new zip archive. ZipChemCompProvider.initilizeZip to creates the\n\t\t * missing zip file */", "/*\n\t\t// convert the filename to a URI\n\t\tString uriString = \"jar:file:\" + zipFile.toUri().getPath();\n\t\tfinal URI uri = URI.create(uriString);\n\n\t\t// if filesystem doesn't exist, create one.\n\t\tfinal Map<String, String> env = new HashMap<>();\n\t\t// Create a new zip if one isn't present.\n\t\tif (!zipFile.toFile().exists()) {\n\t\t\tSystem.out.println(\"Need to create \" + zipFile.toString());\n\t\t}\n\t\tenv.put(\"create\", String.valueOf(!zipFile.toFile().exists()));\n\t\t// Specify the encoding as UTF -8\n\t\tenv.put(\"encoding\", \"UTF-8\");\n\t\t*/", "// Copy in each file.", "try", "(", "FileSystem", "zipfs", "=", "FileSystems", ".", "newFileSystem", "(", "zipFile", ",", "null", ")", ")", "{", "Files", ".", "createDirectories", "(", "pathWithinArchive", ")", ";", "for", "(", "File", "f", ":", "files", ")", "{", "if", "(", "!", "f", ".", "isDirectory", "(", ")", "&&", "f", ".", "exists", "(", ")", ")", "{", "Path", "externalFile", "=", "f", ".", "toPath", "(", ")", ";", "Path", "pathInZipFile", "=", "zipfs", ".", "getPath", "(", "pathWithinArchive", ".", "resolve", "(", "f", ".", "getName", "(", ")", ")", ".", "toString", "(", ")", ")", ";", "Files", ".", "copy", "(", "externalFile", ",", "pathInZipFile", ",", "StandardCopyOption", ".", "REPLACE_EXISTING", ")", ";", "}", "}", "ret", "=", "true", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "s_logger", ".", "error", "(", "\"Unable to add entries to Chemical Component zip archive : \"", "+", "ex", ".", "getMessage", "(", ")", ")", ";", "ret", "=", "false", ";", "}", "return", "ret", ";", "}" ]
Add an array of files to a zip archive. Synchronized to prevent simultaneous reading/writing. @param zipFile is a destination zip archive @param files is an array of files to be added @param pathWithinArchive is the path within the archive to add files to @return true if successfully appended these files.
[ "Add", "an", "array", "of", "files", "to", "a", "zip", "archive", ".", "Synchronized", "to", "prevent", "simultaneous", "reading", "/", "writing", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ZipChemCompProvider.java#L271-L312
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.fill
public static void fill(DMatrixSparseCSC A , double value ) { """ <p> Sets every element in the matrix to the specified value. This can require a very large amount of memory and might exceed the maximum array size<br> <br> A<sub>ij</sub> = value <p> @param A A matrix whose elements are about to be set. Modified. @param value The value each element will have. """ int N = A.numCols*A.numRows; A.growMaxLength(N,false); A.col_idx[0] = 0; for (int col = 0; col < A.numCols; col++) { int idx0 = A.col_idx[col]; int idx1 = A.col_idx[col+1] = idx0 + A.numRows; for (int i = idx0; i < idx1; i++) { A.nz_rows[i] = i-idx0; A.nz_values[i] = value; } } A.nz_length = N; A.indicesSorted = true; }
java
public static void fill(DMatrixSparseCSC A , double value ) { int N = A.numCols*A.numRows; A.growMaxLength(N,false); A.col_idx[0] = 0; for (int col = 0; col < A.numCols; col++) { int idx0 = A.col_idx[col]; int idx1 = A.col_idx[col+1] = idx0 + A.numRows; for (int i = idx0; i < idx1; i++) { A.nz_rows[i] = i-idx0; A.nz_values[i] = value; } } A.nz_length = N; A.indicesSorted = true; }
[ "public", "static", "void", "fill", "(", "DMatrixSparseCSC", "A", ",", "double", "value", ")", "{", "int", "N", "=", "A", ".", "numCols", "*", "A", ".", "numRows", ";", "A", ".", "growMaxLength", "(", "N", ",", "false", ")", ";", "A", ".", "col_idx", "[", "0", "]", "=", "0", ";", "for", "(", "int", "col", "=", "0", ";", "col", "<", "A", ".", "numCols", ";", "col", "++", ")", "{", "int", "idx0", "=", "A", ".", "col_idx", "[", "col", "]", ";", "int", "idx1", "=", "A", ".", "col_idx", "[", "col", "+", "1", "]", "=", "idx0", "+", "A", ".", "numRows", ";", "for", "(", "int", "i", "=", "idx0", ";", "i", "<", "idx1", ";", "i", "++", ")", "{", "A", ".", "nz_rows", "[", "i", "]", "=", "i", "-", "idx0", ";", "A", ".", "nz_values", "[", "i", "]", "=", "value", ";", "}", "}", "A", ".", "nz_length", "=", "N", ";", "A", ".", "indicesSorted", "=", "true", ";", "}" ]
<p> Sets every element in the matrix to the specified value. This can require a very large amount of memory and might exceed the maximum array size<br> <br> A<sub>ij</sub> = value <p> @param A A matrix whose elements are about to be set. Modified. @param value The value each element will have.
[ "<p", ">", "Sets", "every", "element", "in", "the", "matrix", "to", "the", "specified", "value", ".", "This", "can", "require", "a", "very", "large", "amount", "of", "memory", "and", "might", "exceed", "the", "maximum", "array", "size<br", ">", "<br", ">", "A<sub", ">", "ij<", "/", "sub", ">", "=", "value", "<p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L1260-L1275
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bcc/BccClient.java
BccClient.createRequest
private InternalRequest createRequest(AbstractBceRequest bceRequest, HttpMethodName httpMethod, String... pathVariables) { """ Creates and initializes a new request object for the specified bcc resource. This method is responsible for determining the right way to address resources. @param bceRequest The original request, as created by the user. @param httpMethod The HTTP method to use when sending the request. @param pathVariables The optional variables used in the URI path. @return A new request object, populated with endpoint, resource path, ready for callers to populate any additional headers or parameters, and execute. """ List<String> path = new ArrayList<String>(); path.add(VERSION); if (pathVariables != null) { for (String pathVariable : pathVariables) { path.add(pathVariable); } } URI uri = HttpUtils.appendUri(this.getEndpoint(), path.toArray(new String[path.size()])); InternalRequest request = new InternalRequest(httpMethod, uri); request.setCredentials(bceRequest.getRequestCredentials()); return request; }
java
private InternalRequest createRequest(AbstractBceRequest bceRequest, HttpMethodName httpMethod, String... pathVariables) { List<String> path = new ArrayList<String>(); path.add(VERSION); if (pathVariables != null) { for (String pathVariable : pathVariables) { path.add(pathVariable); } } URI uri = HttpUtils.appendUri(this.getEndpoint(), path.toArray(new String[path.size()])); InternalRequest request = new InternalRequest(httpMethod, uri); request.setCredentials(bceRequest.getRequestCredentials()); return request; }
[ "private", "InternalRequest", "createRequest", "(", "AbstractBceRequest", "bceRequest", ",", "HttpMethodName", "httpMethod", ",", "String", "...", "pathVariables", ")", "{", "List", "<", "String", ">", "path", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "path", ".", "add", "(", "VERSION", ")", ";", "if", "(", "pathVariables", "!=", "null", ")", "{", "for", "(", "String", "pathVariable", ":", "pathVariables", ")", "{", "path", ".", "add", "(", "pathVariable", ")", ";", "}", "}", "URI", "uri", "=", "HttpUtils", ".", "appendUri", "(", "this", ".", "getEndpoint", "(", ")", ",", "path", ".", "toArray", "(", "new", "String", "[", "path", ".", "size", "(", ")", "]", ")", ")", ";", "InternalRequest", "request", "=", "new", "InternalRequest", "(", "httpMethod", ",", "uri", ")", ";", "request", ".", "setCredentials", "(", "bceRequest", ".", "getRequestCredentials", "(", ")", ")", ";", "return", "request", ";", "}" ]
Creates and initializes a new request object for the specified bcc resource. This method is responsible for determining the right way to address resources. @param bceRequest The original request, as created by the user. @param httpMethod The HTTP method to use when sending the request. @param pathVariables The optional variables used in the URI path. @return A new request object, populated with endpoint, resource path, ready for callers to populate any additional headers or parameters, and execute.
[ "Creates", "and", "initializes", "a", "new", "request", "object", "for", "the", "specified", "bcc", "resource", ".", "This", "method", "is", "responsible", "for", "determining", "the", "right", "way", "to", "address", "resources", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L163-L178
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/handlers/RequestHandler.java
RequestHandler.invokeController
protected Response invokeController(HttpServerExchange exchange, Response response) throws IllegalAccessException, InvocationTargetException, MangooTemplateEngineException, IOException { """ Invokes the controller methods and retrieves the response which is later send to the client @param exchange The Undertow HttpServerExchange @return A response object @throws IllegalAccessException @throws InvocationTargetException @throws IOException @throws TemplateException @throws MangooTemplateEngineException """ Response invokedResponse; if (this.attachment.getMethodParameters().isEmpty()) { invokedResponse = (Response) this.attachment.getMethod().invoke(this.attachment.getControllerInstance()); } else { final Object [] convertedParameters = getConvertedParameters(exchange); invokedResponse = (Response) this.attachment.getMethod().invoke(this.attachment.getControllerInstance(), convertedParameters); } invokedResponse.andContent(response.getContent()); invokedResponse.andHeaders(response.getHeaders()); if (invokedResponse.isRendered()) { TemplateContext templateContext = new TemplateContext(invokedResponse.getContent()) .withFlash(this.attachment.getFlash()) .withSession(this.attachment.getSession()) .withForm(this.attachment.getForm()) .withMessages(this.attachment.getMessages()) .withController(this.attachment.getControllerAndMethod()) .withPrettyTime(this.attachment.getLocale()) .withAuthenticity(this.attachment.getSession()) .withAuthenticityForm(this.attachment.getSession()) .withTemplatePath(getTemplatePath(invokedResponse)); invokedResponse.andBody(this.attachment.getTemplateEngine().renderTemplate(templateContext)); } else if (invokedResponse.isUnrendered()) { Cache cache = Application.getInstance(CacheProvider.class).getCache(CacheName.RESPONSE); String path = "templates/" + this.attachment.getControllerClassName() + '/' + this.attachment.getControllerMethodName() + ".body"; String body = ""; if (cache.get(path) == null) { body = Resources.toString(Resources.getResource(path), StandardCharsets.UTF_8); cache.put(path, body); } else { body = cache.get(path); } invokedResponse.andBody(body); } else { //ignore anything else } return invokedResponse; }
java
protected Response invokeController(HttpServerExchange exchange, Response response) throws IllegalAccessException, InvocationTargetException, MangooTemplateEngineException, IOException { Response invokedResponse; if (this.attachment.getMethodParameters().isEmpty()) { invokedResponse = (Response) this.attachment.getMethod().invoke(this.attachment.getControllerInstance()); } else { final Object [] convertedParameters = getConvertedParameters(exchange); invokedResponse = (Response) this.attachment.getMethod().invoke(this.attachment.getControllerInstance(), convertedParameters); } invokedResponse.andContent(response.getContent()); invokedResponse.andHeaders(response.getHeaders()); if (invokedResponse.isRendered()) { TemplateContext templateContext = new TemplateContext(invokedResponse.getContent()) .withFlash(this.attachment.getFlash()) .withSession(this.attachment.getSession()) .withForm(this.attachment.getForm()) .withMessages(this.attachment.getMessages()) .withController(this.attachment.getControllerAndMethod()) .withPrettyTime(this.attachment.getLocale()) .withAuthenticity(this.attachment.getSession()) .withAuthenticityForm(this.attachment.getSession()) .withTemplatePath(getTemplatePath(invokedResponse)); invokedResponse.andBody(this.attachment.getTemplateEngine().renderTemplate(templateContext)); } else if (invokedResponse.isUnrendered()) { Cache cache = Application.getInstance(CacheProvider.class).getCache(CacheName.RESPONSE); String path = "templates/" + this.attachment.getControllerClassName() + '/' + this.attachment.getControllerMethodName() + ".body"; String body = ""; if (cache.get(path) == null) { body = Resources.toString(Resources.getResource(path), StandardCharsets.UTF_8); cache.put(path, body); } else { body = cache.get(path); } invokedResponse.andBody(body); } else { //ignore anything else } return invokedResponse; }
[ "protected", "Response", "invokeController", "(", "HttpServerExchange", "exchange", ",", "Response", "response", ")", "throws", "IllegalAccessException", ",", "InvocationTargetException", ",", "MangooTemplateEngineException", ",", "IOException", "{", "Response", "invokedResponse", ";", "if", "(", "this", ".", "attachment", ".", "getMethodParameters", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "invokedResponse", "=", "(", "Response", ")", "this", ".", "attachment", ".", "getMethod", "(", ")", ".", "invoke", "(", "this", ".", "attachment", ".", "getControllerInstance", "(", ")", ")", ";", "}", "else", "{", "final", "Object", "[", "]", "convertedParameters", "=", "getConvertedParameters", "(", "exchange", ")", ";", "invokedResponse", "=", "(", "Response", ")", "this", ".", "attachment", ".", "getMethod", "(", ")", ".", "invoke", "(", "this", ".", "attachment", ".", "getControllerInstance", "(", ")", ",", "convertedParameters", ")", ";", "}", "invokedResponse", ".", "andContent", "(", "response", ".", "getContent", "(", ")", ")", ";", "invokedResponse", ".", "andHeaders", "(", "response", ".", "getHeaders", "(", ")", ")", ";", "if", "(", "invokedResponse", ".", "isRendered", "(", ")", ")", "{", "TemplateContext", "templateContext", "=", "new", "TemplateContext", "(", "invokedResponse", ".", "getContent", "(", ")", ")", ".", "withFlash", "(", "this", ".", "attachment", ".", "getFlash", "(", ")", ")", ".", "withSession", "(", "this", ".", "attachment", ".", "getSession", "(", ")", ")", ".", "withForm", "(", "this", ".", "attachment", ".", "getForm", "(", ")", ")", ".", "withMessages", "(", "this", ".", "attachment", ".", "getMessages", "(", ")", ")", ".", "withController", "(", "this", ".", "attachment", ".", "getControllerAndMethod", "(", ")", ")", ".", "withPrettyTime", "(", "this", ".", "attachment", ".", "getLocale", "(", ")", ")", ".", "withAuthenticity", "(", "this", ".", "attachment", ".", "getSession", "(", ")", ")", ".", "withAuthenticityForm", "(", "this", ".", "attachment", ".", "getSession", "(", ")", ")", ".", "withTemplatePath", "(", "getTemplatePath", "(", "invokedResponse", ")", ")", ";", "invokedResponse", ".", "andBody", "(", "this", ".", "attachment", ".", "getTemplateEngine", "(", ")", ".", "renderTemplate", "(", "templateContext", ")", ")", ";", "}", "else", "if", "(", "invokedResponse", ".", "isUnrendered", "(", ")", ")", "{", "Cache", "cache", "=", "Application", ".", "getInstance", "(", "CacheProvider", ".", "class", ")", ".", "getCache", "(", "CacheName", ".", "RESPONSE", ")", ";", "String", "path", "=", "\"templates/\"", "+", "this", ".", "attachment", ".", "getControllerClassName", "(", ")", "+", "'", "'", "+", "this", ".", "attachment", ".", "getControllerMethodName", "(", ")", "+", "\".body\"", ";", "String", "body", "=", "\"\"", ";", "if", "(", "cache", ".", "get", "(", "path", ")", "==", "null", ")", "{", "body", "=", "Resources", ".", "toString", "(", "Resources", ".", "getResource", "(", "path", ")", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "cache", ".", "put", "(", "path", ",", "body", ")", ";", "}", "else", "{", "body", "=", "cache", ".", "get", "(", "path", ")", ";", "}", "invokedResponse", ".", "andBody", "(", "body", ")", ";", "}", "else", "{", "//ignore anything else", "}", "return", "invokedResponse", ";", "}" ]
Invokes the controller methods and retrieves the response which is later send to the client @param exchange The Undertow HttpServerExchange @return A response object @throws IllegalAccessException @throws InvocationTargetException @throws IOException @throws TemplateException @throws MangooTemplateEngineException
[ "Invokes", "the", "controller", "methods", "and", "retrieves", "the", "response", "which", "is", "later", "send", "to", "the", "client" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/handlers/RequestHandler.java#L135-L179
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/consumer/DataPipe.java
DataPipe.getDelimited
public String getDelimited(String[] outTemplate, String separator) { """ Given an array of variable names, returns a delimited {@link String} of values. @param outTemplate an array of {@link String}s containing the variable names. @param separator the delimiter to use @return a pipe delimited {@link String} of values """ StringBuilder b = new StringBuilder(1024); for (String var : outTemplate) { if (b.length() > 0) { b.append(separator); } b.append(getDataMap().get(var)); } return b.toString(); }
java
public String getDelimited(String[] outTemplate, String separator) { StringBuilder b = new StringBuilder(1024); for (String var : outTemplate) { if (b.length() > 0) { b.append(separator); } b.append(getDataMap().get(var)); } return b.toString(); }
[ "public", "String", "getDelimited", "(", "String", "[", "]", "outTemplate", ",", "String", "separator", ")", "{", "StringBuilder", "b", "=", "new", "StringBuilder", "(", "1024", ")", ";", "for", "(", "String", "var", ":", "outTemplate", ")", "{", "if", "(", "b", ".", "length", "(", ")", ">", "0", ")", "{", "b", ".", "append", "(", "separator", ")", ";", "}", "b", ".", "append", "(", "getDataMap", "(", ")", ".", "get", "(", "var", ")", ")", ";", "}", "return", "b", ".", "toString", "(", ")", ";", "}" ]
Given an array of variable names, returns a delimited {@link String} of values. @param outTemplate an array of {@link String}s containing the variable names. @param separator the delimiter to use @return a pipe delimited {@link String} of values
[ "Given", "an", "array", "of", "variable", "names", "returns", "a", "delimited", "{", "@link", "String", "}", "of", "values", "." ]
train
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/consumer/DataPipe.java#L88-L99
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java
DBObjectBatch.addObject
public DBObject addObject(String objID, String tableName) { """ Create a new DBObject with the given object ID and table name, add it to this DBObjectBatch, and return it. @param objID New DBObject's object ID, if any. @param tableName New DBObject's table name, if any. @return New DBObject. """ DBObject dbObj = new DBObject(objID, tableName); m_dbObjList.add(dbObj); return dbObj; }
java
public DBObject addObject(String objID, String tableName) { DBObject dbObj = new DBObject(objID, tableName); m_dbObjList.add(dbObj); return dbObj; }
[ "public", "DBObject", "addObject", "(", "String", "objID", ",", "String", "tableName", ")", "{", "DBObject", "dbObj", "=", "new", "DBObject", "(", "objID", ",", "tableName", ")", ";", "m_dbObjList", ".", "add", "(", "dbObj", ")", ";", "return", "dbObj", ";", "}" ]
Create a new DBObject with the given object ID and table name, add it to this DBObjectBatch, and return it. @param objID New DBObject's object ID, if any. @param tableName New DBObject's table name, if any. @return New DBObject.
[ "Create", "a", "new", "DBObject", "with", "the", "given", "object", "ID", "and", "table", "name", "add", "it", "to", "this", "DBObjectBatch", "and", "return", "it", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java#L303-L307
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataXceiver.java
DataXceiver.getBlockCrc
void getBlockCrc(DataInputStream in, VersionAndOpcode versionAndOpcode) throws IOException { """ Get block data's CRC32 checksum. @param in @param versionAndOpcode """ // header BlockChecksumHeader blockChecksumHeader = new BlockChecksumHeader(versionAndOpcode); blockChecksumHeader.readFields(in); final int namespaceId = blockChecksumHeader.getNamespaceId(); final Block block = new Block(blockChecksumHeader.getBlockId(), 0, blockChecksumHeader.getGenStamp()); DataOutputStream out = null; ReplicaToRead ri = datanode.data.getReplicaToRead(namespaceId, block); if (ri == null) { throw new IOException("Unknown block"); } updateCurrentThreadName("getting CRC checksum for block " + block); try { //write reply out = new DataOutputStream( NetUtils.getOutputStream(s, datanode.socketWriteTimeout)); int blockCrc; if (ri.hasBlockCrcInfo()) { // There is actually a short window that the block is reopened // and we got exception when call getBlockCrc but it's OK. It's // only happens for append(). So far we don't optimize for this // use case. We can do it later when necessary. // blockCrc = ri.getBlockCrc(); } else { try { if (ri.isInlineChecksum()) { blockCrc = BlockInlineChecksumReader.getBlockCrc(datanode, ri, namespaceId, block); } else { blockCrc = BlockWithChecksumFileReader.getBlockCrc(datanode, ri, namespaceId, block); } } catch (IOException ioe) { LOG.warn("Exception when getting Block CRC", ioe); out.writeShort(DataTransferProtocol.OP_STATUS_ERROR); out.flush(); throw ioe; } } out.writeShort(DataTransferProtocol.OP_STATUS_SUCCESS); out.writeLong(blockCrc); out.flush(); } finally { IOUtils.closeStream(out); } }
java
void getBlockCrc(DataInputStream in, VersionAndOpcode versionAndOpcode) throws IOException { // header BlockChecksumHeader blockChecksumHeader = new BlockChecksumHeader(versionAndOpcode); blockChecksumHeader.readFields(in); final int namespaceId = blockChecksumHeader.getNamespaceId(); final Block block = new Block(blockChecksumHeader.getBlockId(), 0, blockChecksumHeader.getGenStamp()); DataOutputStream out = null; ReplicaToRead ri = datanode.data.getReplicaToRead(namespaceId, block); if (ri == null) { throw new IOException("Unknown block"); } updateCurrentThreadName("getting CRC checksum for block " + block); try { //write reply out = new DataOutputStream( NetUtils.getOutputStream(s, datanode.socketWriteTimeout)); int blockCrc; if (ri.hasBlockCrcInfo()) { // There is actually a short window that the block is reopened // and we got exception when call getBlockCrc but it's OK. It's // only happens for append(). So far we don't optimize for this // use case. We can do it later when necessary. // blockCrc = ri.getBlockCrc(); } else { try { if (ri.isInlineChecksum()) { blockCrc = BlockInlineChecksumReader.getBlockCrc(datanode, ri, namespaceId, block); } else { blockCrc = BlockWithChecksumFileReader.getBlockCrc(datanode, ri, namespaceId, block); } } catch (IOException ioe) { LOG.warn("Exception when getting Block CRC", ioe); out.writeShort(DataTransferProtocol.OP_STATUS_ERROR); out.flush(); throw ioe; } } out.writeShort(DataTransferProtocol.OP_STATUS_SUCCESS); out.writeLong(blockCrc); out.flush(); } finally { IOUtils.closeStream(out); } }
[ "void", "getBlockCrc", "(", "DataInputStream", "in", ",", "VersionAndOpcode", "versionAndOpcode", ")", "throws", "IOException", "{", "// header", "BlockChecksumHeader", "blockChecksumHeader", "=", "new", "BlockChecksumHeader", "(", "versionAndOpcode", ")", ";", "blockChecksumHeader", ".", "readFields", "(", "in", ")", ";", "final", "int", "namespaceId", "=", "blockChecksumHeader", ".", "getNamespaceId", "(", ")", ";", "final", "Block", "block", "=", "new", "Block", "(", "blockChecksumHeader", ".", "getBlockId", "(", ")", ",", "0", ",", "blockChecksumHeader", ".", "getGenStamp", "(", ")", ")", ";", "DataOutputStream", "out", "=", "null", ";", "ReplicaToRead", "ri", "=", "datanode", ".", "data", ".", "getReplicaToRead", "(", "namespaceId", ",", "block", ")", ";", "if", "(", "ri", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Unknown block\"", ")", ";", "}", "updateCurrentThreadName", "(", "\"getting CRC checksum for block \"", "+", "block", ")", ";", "try", "{", "//write reply", "out", "=", "new", "DataOutputStream", "(", "NetUtils", ".", "getOutputStream", "(", "s", ",", "datanode", ".", "socketWriteTimeout", ")", ")", ";", "int", "blockCrc", ";", "if", "(", "ri", ".", "hasBlockCrcInfo", "(", ")", ")", "{", "// There is actually a short window that the block is reopened", "// and we got exception when call getBlockCrc but it's OK. It's", "// only happens for append(). So far we don't optimize for this", "// use case. We can do it later when necessary.", "//", "blockCrc", "=", "ri", ".", "getBlockCrc", "(", ")", ";", "}", "else", "{", "try", "{", "if", "(", "ri", ".", "isInlineChecksum", "(", ")", ")", "{", "blockCrc", "=", "BlockInlineChecksumReader", ".", "getBlockCrc", "(", "datanode", ",", "ri", ",", "namespaceId", ",", "block", ")", ";", "}", "else", "{", "blockCrc", "=", "BlockWithChecksumFileReader", ".", "getBlockCrc", "(", "datanode", ",", "ri", ",", "namespaceId", ",", "block", ")", ";", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "warn", "(", "\"Exception when getting Block CRC\"", ",", "ioe", ")", ";", "out", ".", "writeShort", "(", "DataTransferProtocol", ".", "OP_STATUS_ERROR", ")", ";", "out", ".", "flush", "(", ")", ";", "throw", "ioe", ";", "}", "}", "out", ".", "writeShort", "(", "DataTransferProtocol", ".", "OP_STATUS_SUCCESS", ")", ";", "out", ".", "writeLong", "(", "blockCrc", ")", ";", "out", ".", "flush", "(", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeStream", "(", "out", ")", ";", "}", "}" ]
Get block data's CRC32 checksum. @param in @param versionAndOpcode
[ "Get", "block", "data", "s", "CRC32", "checksum", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataXceiver.java#L931-L985
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscConfigurationsInner.java
DscConfigurationsInner.getContent
public String getContent(String resourceGroupName, String automationAccountName, String configurationName) { """ Retrieve the configuration script identified by configuration name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param configurationName The configuration name. @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 String object if successful. """ return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, configurationName).toBlocking().single().body(); }
java
public String getContent(String resourceGroupName, String automationAccountName, String configurationName) { return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, configurationName).toBlocking().single().body(); }
[ "public", "String", "getContent", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "configurationName", ")", "{", "return", "getContentWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "configurationName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Retrieve the configuration script identified by configuration name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param configurationName The configuration name. @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 String object if successful.
[ "Retrieve", "the", "configuration", "script", "identified", "by", "configuration", "name", "." ]
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/DscConfigurationsInner.java#L571-L573
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java
ParameterEditManager.getParmEditSet
private static Element getParmEditSet(Document plf, IPerson person, boolean create) throws PortalException { """ Get the parameter edits set if any stored in the root of the document or create it if passed-in create flag is true. """ Node root = plf.getDocumentElement(); Node child = root.getFirstChild(); while (child != null) { if (child.getNodeName().equals(Constants.ELM_PARM_SET)) return (Element) child; child = child.getNextSibling(); } if (create == false) return null; String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person.getID(), e); } Element parmSet = plf.createElement(Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_ID, ID); parmSet.setIdAttribute(Constants.ATT_ID, true); root.appendChild(parmSet); return parmSet; }
java
private static Element getParmEditSet(Document plf, IPerson person, boolean create) throws PortalException { Node root = plf.getDocumentElement(); Node child = root.getFirstChild(); while (child != null) { if (child.getNodeName().equals(Constants.ELM_PARM_SET)) return (Element) child; child = child.getNextSibling(); } if (create == false) return null; String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person.getID(), e); } Element parmSet = plf.createElement(Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_ID, ID); parmSet.setIdAttribute(Constants.ATT_ID, true); root.appendChild(parmSet); return parmSet; }
[ "private", "static", "Element", "getParmEditSet", "(", "Document", "plf", ",", "IPerson", "person", ",", "boolean", "create", ")", "throws", "PortalException", "{", "Node", "root", "=", "plf", ".", "getDocumentElement", "(", ")", ";", "Node", "child", "=", "root", ".", "getFirstChild", "(", ")", ";", "while", "(", "child", "!=", "null", ")", "{", "if", "(", "child", ".", "getNodeName", "(", ")", ".", "equals", "(", "Constants", ".", "ELM_PARM_SET", ")", ")", "return", "(", "Element", ")", "child", ";", "child", "=", "child", ".", "getNextSibling", "(", ")", ";", "}", "if", "(", "create", "==", "false", ")", "return", "null", ";", "String", "ID", "=", "null", ";", "try", "{", "ID", "=", "getDLS", "(", ")", ".", "getNextStructDirectiveId", "(", "person", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "PortalException", "(", "\"Exception encountered while \"", "+", "\"generating new parameter edit set node \"", "+", "\"Id for userId=\"", "+", "person", ".", "getID", "(", ")", ",", "e", ")", ";", "}", "Element", "parmSet", "=", "plf", ".", "createElement", "(", "Constants", ".", "ELM_PARM_SET", ")", ";", "parmSet", ".", "setAttribute", "(", "Constants", ".", "ATT_TYPE", ",", "Constants", ".", "ELM_PARM_SET", ")", ";", "parmSet", ".", "setAttribute", "(", "Constants", ".", "ATT_ID", ",", "ID", ")", ";", "parmSet", ".", "setIdAttribute", "(", "Constants", ".", "ATT_ID", ",", "true", ")", ";", "root", ".", "appendChild", "(", "parmSet", ")", ";", "return", "parmSet", ";", "}" ]
Get the parameter edits set if any stored in the root of the document or create it if passed-in create flag is true.
[ "Get", "the", "parameter", "edits", "set", "if", "any", "stored", "in", "the", "root", "of", "the", "document", "or", "create", "it", "if", "passed", "-", "in", "create", "flag", "is", "true", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L174-L204
GumTreeDiff/gumtree
core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java
SequenceAlgorithms.longestCommonSubsequence
public static List<int[]> longestCommonSubsequence(String s0, String s1) { """ Returns the longest common subsequence between two strings. @return a list of size 2 int arrays that corresponds to match of index in sequence 1 to index in sequence 2. """ int[][] lengths = new int[s0.length() + 1][s1.length() + 1]; for (int i = 0; i < s0.length(); i++) for (int j = 0; j < s1.length(); j++) if (s0.charAt(i) == (s1.charAt(j))) lengths[i + 1][j + 1] = lengths[i][j] + 1; else lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]); return extractIndexes(lengths, s0.length(), s1.length()); }
java
public static List<int[]> longestCommonSubsequence(String s0, String s1) { int[][] lengths = new int[s0.length() + 1][s1.length() + 1]; for (int i = 0; i < s0.length(); i++) for (int j = 0; j < s1.length(); j++) if (s0.charAt(i) == (s1.charAt(j))) lengths[i + 1][j + 1] = lengths[i][j] + 1; else lengths[i + 1][j + 1] = Math.max(lengths[i + 1][j], lengths[i][j + 1]); return extractIndexes(lengths, s0.length(), s1.length()); }
[ "public", "static", "List", "<", "int", "[", "]", ">", "longestCommonSubsequence", "(", "String", "s0", ",", "String", "s1", ")", "{", "int", "[", "]", "[", "]", "lengths", "=", "new", "int", "[", "s0", ".", "length", "(", ")", "+", "1", "]", "[", "s1", ".", "length", "(", ")", "+", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s0", ".", "length", "(", ")", ";", "i", "++", ")", "for", "(", "int", "j", "=", "0", ";", "j", "<", "s1", ".", "length", "(", ")", ";", "j", "++", ")", "if", "(", "s0", ".", "charAt", "(", "i", ")", "==", "(", "s1", ".", "charAt", "(", "j", ")", ")", ")", "lengths", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", "=", "lengths", "[", "i", "]", "[", "j", "]", "+", "1", ";", "else", "lengths", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", "=", "Math", ".", "max", "(", "lengths", "[", "i", "+", "1", "]", "[", "j", "]", ",", "lengths", "[", "i", "]", "[", "j", "+", "1", "]", ")", ";", "return", "extractIndexes", "(", "lengths", ",", "s0", ".", "length", "(", ")", ",", "s1", ".", "length", "(", ")", ")", ";", "}" ]
Returns the longest common subsequence between two strings. @return a list of size 2 int arrays that corresponds to match of index in sequence 1 to index in sequence 2.
[ "Returns", "the", "longest", "common", "subsequence", "between", "two", "strings", "." ]
train
https://github.com/GumTreeDiff/gumtree/blob/a772d4d652af44bff22c38a234ddffbfbd365a37/core/src/main/java/com/github/gumtreediff/utils/SequenceAlgorithms.java#L38-L48
RestComm/sip-servlets
sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletMessageImpl.java
SipServletMessageImpl.isSystemHeaderAndNotGruu
public static boolean isSystemHeaderAndNotGruu(ModifiableRule modifiableRule, Parameterable parameterable) { """ Support for GRUU https://github.com/Mobicents/sip-servlets/issues/51 if the header contains one of the gruu, gr, temp-gruu or pub-gruu, it is allowed to set the Contact Header as per RFC 5627 """ boolean isSettingGruu = false; if(modifiableRule == ModifiableRule.ContactSystem && (parameterable.getParameter("gruu") != null || parameterable.getParameter("gr") != null)) { isSettingGruu = true; if (logger.isDebugEnabled()) logger.debug("Setting gruu so modifying contact header address is allowed"); } return !isSettingGruu && isSystemHeader(modifiableRule); }
java
public static boolean isSystemHeaderAndNotGruu(ModifiableRule modifiableRule, Parameterable parameterable) { boolean isSettingGruu = false; if(modifiableRule == ModifiableRule.ContactSystem && (parameterable.getParameter("gruu") != null || parameterable.getParameter("gr") != null)) { isSettingGruu = true; if (logger.isDebugEnabled()) logger.debug("Setting gruu so modifying contact header address is allowed"); } return !isSettingGruu && isSystemHeader(modifiableRule); }
[ "public", "static", "boolean", "isSystemHeaderAndNotGruu", "(", "ModifiableRule", "modifiableRule", ",", "Parameterable", "parameterable", ")", "{", "boolean", "isSettingGruu", "=", "false", ";", "if", "(", "modifiableRule", "==", "ModifiableRule", ".", "ContactSystem", "&&", "(", "parameterable", ".", "getParameter", "(", "\"gruu\"", ")", "!=", "null", "||", "parameterable", ".", "getParameter", "(", "\"gr\"", ")", "!=", "null", ")", ")", "{", "isSettingGruu", "=", "true", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "logger", ".", "debug", "(", "\"Setting gruu so modifying contact header address is allowed\"", ")", ";", "}", "return", "!", "isSettingGruu", "&&", "isSystemHeader", "(", "modifiableRule", ")", ";", "}" ]
Support for GRUU https://github.com/Mobicents/sip-servlets/issues/51 if the header contains one of the gruu, gr, temp-gruu or pub-gruu, it is allowed to set the Contact Header as per RFC 5627
[ "Support", "for", "GRUU", "https", ":", "//", "github", ".", "com", "/", "Mobicents", "/", "sip", "-", "servlets", "/", "issues", "/", "51", "if", "the", "header", "contains", "one", "of", "the", "gruu", "gr", "temp", "-", "gruu", "or", "pub", "-", "gruu", "it", "is", "allowed", "to", "set", "the", "Contact", "Header", "as", "per", "RFC", "5627" ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletMessageImpl.java#L1800-L1810
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java
SpiderSession.aggregateQuery
public AggregateResult aggregateQuery(String tableName, String metric, String queryText, String groupingFields, boolean bComposite) { """ Perform an aggregate query with the given parameters. This is a convenience method that packages parameters into a Map<String,String> and calls {@link #aggregateQuery(String, Map)}. Optional parameters can be null or empty. @param tableName Name of table to query. It must belong to this session's application. @param metric Required metric expression (e.g., "COUNT(*)"). @param queryText Optional query expression. @param groupingFields Optional list of grouping field expressions. @param bComposite True if multi-level composite grouping is desired. @return Query result as an {@link AggregateResult}. """ Map<String, String> params = new HashMap<>(); if (!Utils.isEmpty(metric)) { params.put("m", metric); } if (!Utils.isEmpty(queryText)) { params.put("q", queryText); } if (!Utils.isEmpty(groupingFields)) { // Apply URL encoding in case of Unicode characters. if (bComposite) { params.put("cf", groupingFields); } else { params.put("f", groupingFields); } } return aggregateQuery(tableName, params); }
java
public AggregateResult aggregateQuery(String tableName, String metric, String queryText, String groupingFields, boolean bComposite) { Map<String, String> params = new HashMap<>(); if (!Utils.isEmpty(metric)) { params.put("m", metric); } if (!Utils.isEmpty(queryText)) { params.put("q", queryText); } if (!Utils.isEmpty(groupingFields)) { // Apply URL encoding in case of Unicode characters. if (bComposite) { params.put("cf", groupingFields); } else { params.put("f", groupingFields); } } return aggregateQuery(tableName, params); }
[ "public", "AggregateResult", "aggregateQuery", "(", "String", "tableName", ",", "String", "metric", ",", "String", "queryText", ",", "String", "groupingFields", ",", "boolean", "bComposite", ")", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "!", "Utils", ".", "isEmpty", "(", "metric", ")", ")", "{", "params", ".", "put", "(", "\"m\"", ",", "metric", ")", ";", "}", "if", "(", "!", "Utils", ".", "isEmpty", "(", "queryText", ")", ")", "{", "params", ".", "put", "(", "\"q\"", ",", "queryText", ")", ";", "}", "if", "(", "!", "Utils", ".", "isEmpty", "(", "groupingFields", ")", ")", "{", "// Apply URL encoding in case of Unicode characters.\r", "if", "(", "bComposite", ")", "{", "params", ".", "put", "(", "\"cf\"", ",", "groupingFields", ")", ";", "}", "else", "{", "params", ".", "put", "(", "\"f\"", ",", "groupingFields", ")", ";", "}", "}", "return", "aggregateQuery", "(", "tableName", ",", "params", ")", ";", "}" ]
Perform an aggregate query with the given parameters. This is a convenience method that packages parameters into a Map<String,String> and calls {@link #aggregateQuery(String, Map)}. Optional parameters can be null or empty. @param tableName Name of table to query. It must belong to this session's application. @param metric Required metric expression (e.g., "COUNT(*)"). @param queryText Optional query expression. @param groupingFields Optional list of grouping field expressions. @param bComposite True if multi-level composite grouping is desired. @return Query result as an {@link AggregateResult}.
[ "Perform", "an", "aggregate", "query", "with", "the", "given", "parameters", ".", "This", "is", "a", "convenience", "method", "that", "packages", "parameters", "into", "a", "Map<String", "String", ">", "and", "calls", "{", "@link", "#aggregateQuery", "(", "String", "Map", ")", "}", ".", "Optional", "parameters", "can", "be", "null", "or", "empty", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java#L218-L239
SvenEwald/xmlbeam
src/main/java/org/xmlbeam/evaluation/DefaultXPathEvaluator.java
DefaultXPathEvaluator.asDate
@Override public Date asDate() { """ Evaluates the XPath as a Date value. This method is just a shortcut for as(Date.class); You probably want to specify ' using ' followed by some formatting pattern consecutive to the XPAth. @return Date value of evaluation result. """ final Class<?> callerClass = ReflectionHelper.getDirectCallerClass(); return evaluateSingeValue(Date.class, callerClass); }
java
@Override public Date asDate() { final Class<?> callerClass = ReflectionHelper.getDirectCallerClass(); return evaluateSingeValue(Date.class, callerClass); }
[ "@", "Override", "public", "Date", "asDate", "(", ")", "{", "final", "Class", "<", "?", ">", "callerClass", "=", "ReflectionHelper", ".", "getDirectCallerClass", "(", ")", ";", "return", "evaluateSingeValue", "(", "Date", ".", "class", ",", "callerClass", ")", ";", "}" ]
Evaluates the XPath as a Date value. This method is just a shortcut for as(Date.class); You probably want to specify ' using ' followed by some formatting pattern consecutive to the XPAth. @return Date value of evaluation result.
[ "Evaluates", "the", "XPath", "as", "a", "Date", "value", ".", "This", "method", "is", "just", "a", "shortcut", "for", "as", "(", "Date", ".", "class", ")", ";", "You", "probably", "want", "to", "specify", "using", "followed", "by", "some", "formatting", "pattern", "consecutive", "to", "the", "XPAth", "." ]
train
https://github.com/SvenEwald/xmlbeam/blob/acaac1b8fa28d246f17187f5e3c6696458a0b447/src/main/java/org/xmlbeam/evaluation/DefaultXPathEvaluator.java#L115-L119
Stratio/stratio-connector-commons
connector-commons/src/main/java/com/stratio/connector/commons/metadata/IndexMetadataBuilder.java
IndexMetadataBuilder.addColumn
@TimerJ public IndexMetadataBuilder addColumn(String columnName, ColumnType colType) { """ Add column. Parameters in columnMetadata will be null. @param columnName the column name @param colType the col type @return the index metadata builder """ ColumnName colName = new ColumnName(tableName, columnName); ColumnMetadata colMetadata = new ColumnMetadata(colName, null, colType); columns.put(colName, colMetadata); return this; }
java
@TimerJ public IndexMetadataBuilder addColumn(String columnName, ColumnType colType) { ColumnName colName = new ColumnName(tableName, columnName); ColumnMetadata colMetadata = new ColumnMetadata(colName, null, colType); columns.put(colName, colMetadata); return this; }
[ "@", "TimerJ", "public", "IndexMetadataBuilder", "addColumn", "(", "String", "columnName", ",", "ColumnType", "colType", ")", "{", "ColumnName", "colName", "=", "new", "ColumnName", "(", "tableName", ",", "columnName", ")", ";", "ColumnMetadata", "colMetadata", "=", "new", "ColumnMetadata", "(", "colName", ",", "null", ",", "colType", ")", ";", "columns", ".", "put", "(", "colName", ",", "colMetadata", ")", ";", "return", "this", ";", "}" ]
Add column. Parameters in columnMetadata will be null. @param columnName the column name @param colType the col type @return the index metadata builder
[ "Add", "column", ".", "Parameters", "in", "columnMetadata", "will", "be", "null", "." ]
train
https://github.com/Stratio/stratio-connector-commons/blob/d7cc66cb9591344a13055962e87a91f01c3707d1/connector-commons/src/main/java/com/stratio/connector/commons/metadata/IndexMetadataBuilder.java#L119-L125
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java
PatternsImpl.addPatternAsync
public Observable<PatternRuleInfo> addPatternAsync(UUID appId, String versionId, PatternRuleCreateObject pattern) { """ Adds one pattern to the specified application. @param appId The application ID. @param versionId The version ID. @param pattern The input pattern. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PatternRuleInfo object """ return addPatternWithServiceResponseAsync(appId, versionId, pattern).map(new Func1<ServiceResponse<PatternRuleInfo>, PatternRuleInfo>() { @Override public PatternRuleInfo call(ServiceResponse<PatternRuleInfo> response) { return response.body(); } }); }
java
public Observable<PatternRuleInfo> addPatternAsync(UUID appId, String versionId, PatternRuleCreateObject pattern) { return addPatternWithServiceResponseAsync(appId, versionId, pattern).map(new Func1<ServiceResponse<PatternRuleInfo>, PatternRuleInfo>() { @Override public PatternRuleInfo call(ServiceResponse<PatternRuleInfo> response) { return response.body(); } }); }
[ "public", "Observable", "<", "PatternRuleInfo", ">", "addPatternAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "PatternRuleCreateObject", "pattern", ")", "{", "return", "addPatternWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "pattern", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "PatternRuleInfo", ">", ",", "PatternRuleInfo", ">", "(", ")", "{", "@", "Override", "public", "PatternRuleInfo", "call", "(", "ServiceResponse", "<", "PatternRuleInfo", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Adds one pattern to the specified application. @param appId The application ID. @param versionId The version ID. @param pattern The input pattern. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PatternRuleInfo object
[ "Adds", "one", "pattern", "to", "the", "specified", "application", "." ]
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/PatternsImpl.java#L141-L148
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsCopyToProject.java
CmsCopyToProject.actionCopyToProject
public void actionCopyToProject() throws JspException { """ Performs the copy to project action, will be called by the JSP page.<p> @throws JspException if problems including sub-elements occur """ // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); try { // copy the resource to the current project getCms().copyResourceToProject(getParamResource()); // close the dialog actionCloseDialog(); } catch (Throwable e) { // error copying resource to project, include error page includeErrorpage(this, e); } }
java
public void actionCopyToProject() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); try { // copy the resource to the current project getCms().copyResourceToProject(getParamResource()); // close the dialog actionCloseDialog(); } catch (Throwable e) { // error copying resource to project, include error page includeErrorpage(this, e); } }
[ "public", "void", "actionCopyToProject", "(", ")", "throws", "JspException", "{", "// save initialized instance of this class in request attribute for included sub-elements", "getJsp", "(", ")", ".", "getRequest", "(", ")", ".", "setAttribute", "(", "SESSION_WORKPLACE_CLASS", ",", "this", ")", ";", "try", "{", "// copy the resource to the current project", "getCms", "(", ")", ".", "copyResourceToProject", "(", "getParamResource", "(", ")", ")", ";", "// close the dialog", "actionCloseDialog", "(", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "// error copying resource to project, include error page", "includeErrorpage", "(", "this", ",", "e", ")", ";", "}", "}" ]
Performs the copy to project action, will be called by the JSP page.<p> @throws JspException if problems including sub-elements occur
[ "Performs", "the", "copy", "to", "project", "action", "will", "be", "called", "by", "the", "JSP", "page", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsCopyToProject.java#L97-L110
sarl/sarl
main/coreplugins/io.sarl.lang/src-gen/io/sarl/lang/codebuilder/builders/SarlEnumLiteralBuilderImpl.java
SarlEnumLiteralBuilderImpl.eInit
public void eInit(XtendTypeDeclaration container, String name, IJvmTypeProvider context) { """ Initialize the Ecore element. @param container the container of the SarlEnumLiteral. @param name the name of the SarlEnumLiteral. """ setTypeResolutionContext(context); if (this.sarlEnumLiteral == null) { this.container = container; this.sarlEnumLiteral = SarlFactory.eINSTANCE.createSarlEnumLiteral(); this.sarlEnumLiteral.setName(name); container.getMembers().add(this.sarlEnumLiteral); } }
java
public void eInit(XtendTypeDeclaration container, String name, IJvmTypeProvider context) { setTypeResolutionContext(context); if (this.sarlEnumLiteral == null) { this.container = container; this.sarlEnumLiteral = SarlFactory.eINSTANCE.createSarlEnumLiteral(); this.sarlEnumLiteral.setName(name); container.getMembers().add(this.sarlEnumLiteral); } }
[ "public", "void", "eInit", "(", "XtendTypeDeclaration", "container", ",", "String", "name", ",", "IJvmTypeProvider", "context", ")", "{", "setTypeResolutionContext", "(", "context", ")", ";", "if", "(", "this", ".", "sarlEnumLiteral", "==", "null", ")", "{", "this", ".", "container", "=", "container", ";", "this", ".", "sarlEnumLiteral", "=", "SarlFactory", ".", "eINSTANCE", ".", "createSarlEnumLiteral", "(", ")", ";", "this", ".", "sarlEnumLiteral", ".", "setName", "(", "name", ")", ";", "container", ".", "getMembers", "(", ")", ".", "add", "(", "this", ".", "sarlEnumLiteral", ")", ";", "}", "}" ]
Initialize the Ecore element. @param container the container of the SarlEnumLiteral. @param name the name of the SarlEnumLiteral.
[ "Initialize", "the", "Ecore", "element", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src-gen/io/sarl/lang/codebuilder/builders/SarlEnumLiteralBuilderImpl.java#L61-L69
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTileTransitionModel.java
MapTileTransitionModel.updateTransitive
private void updateTransitive(Collection<Tile> resolved, Tile tile, Tile neighbor, GroupTransition transitive) { """ Update the transitive between tile and its neighbor. @param resolved The resolved tiles. @param tile The tile reference. @param neighbor The neighbor reference. @param transitive The transitive involved. """ final String transitiveOut = transitive.getOut(); final Transition transition = new Transition(TransitionType.CENTER, transitiveOut, transitiveOut); final Collection<TileRef> refs = getTiles(transition); if (!refs.isEmpty()) { final TileRef ref = refs.iterator().next(); // Replace user tile with the needed tile to solve transition (restored later) final Tile newTile = map.createTile(ref.getSheet(), ref.getNumber(), tile.getX(), tile.getY()); map.setTile(newTile); // Replace neighbor with the needed tile to solve transition final Tile newTile2 = map.createTile(ref.getSheet(), ref.getNumber(), neighbor.getX(), neighbor.getY()); map.setTile(newTile2); resolved.addAll(resolve(newTile2)); } }
java
private void updateTransitive(Collection<Tile> resolved, Tile tile, Tile neighbor, GroupTransition transitive) { final String transitiveOut = transitive.getOut(); final Transition transition = new Transition(TransitionType.CENTER, transitiveOut, transitiveOut); final Collection<TileRef> refs = getTiles(transition); if (!refs.isEmpty()) { final TileRef ref = refs.iterator().next(); // Replace user tile with the needed tile to solve transition (restored later) final Tile newTile = map.createTile(ref.getSheet(), ref.getNumber(), tile.getX(), tile.getY()); map.setTile(newTile); // Replace neighbor with the needed tile to solve transition final Tile newTile2 = map.createTile(ref.getSheet(), ref.getNumber(), neighbor.getX(), neighbor.getY()); map.setTile(newTile2); resolved.addAll(resolve(newTile2)); } }
[ "private", "void", "updateTransitive", "(", "Collection", "<", "Tile", ">", "resolved", ",", "Tile", "tile", ",", "Tile", "neighbor", ",", "GroupTransition", "transitive", ")", "{", "final", "String", "transitiveOut", "=", "transitive", ".", "getOut", "(", ")", ";", "final", "Transition", "transition", "=", "new", "Transition", "(", "TransitionType", ".", "CENTER", ",", "transitiveOut", ",", "transitiveOut", ")", ";", "final", "Collection", "<", "TileRef", ">", "refs", "=", "getTiles", "(", "transition", ")", ";", "if", "(", "!", "refs", ".", "isEmpty", "(", ")", ")", "{", "final", "TileRef", "ref", "=", "refs", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "// Replace user tile with the needed tile to solve transition (restored later)\r", "final", "Tile", "newTile", "=", "map", ".", "createTile", "(", "ref", ".", "getSheet", "(", ")", ",", "ref", ".", "getNumber", "(", ")", ",", "tile", ".", "getX", "(", ")", ",", "tile", ".", "getY", "(", ")", ")", ";", "map", ".", "setTile", "(", "newTile", ")", ";", "// Replace neighbor with the needed tile to solve transition\r", "final", "Tile", "newTile2", "=", "map", ".", "createTile", "(", "ref", ".", "getSheet", "(", ")", ",", "ref", ".", "getNumber", "(", ")", ",", "neighbor", ".", "getX", "(", ")", ",", "neighbor", ".", "getY", "(", ")", ")", ";", "map", ".", "setTile", "(", "newTile2", ")", ";", "resolved", ".", "addAll", "(", "resolve", "(", "newTile2", ")", ")", ";", "}", "}" ]
Update the transitive between tile and its neighbor. @param resolved The resolved tiles. @param tile The tile reference. @param neighbor The neighbor reference. @param transitive The transitive involved.
[ "Update", "the", "transitive", "between", "tile", "and", "its", "neighbor", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTileTransitionModel.java#L358-L376
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Ellipse.java
Ellipse.prepare
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { """ Draws this ellipse. @param context the {@link Context2D} used to draw this ellipse. """ final double w = attr.getWidth(); final double h = attr.getHeight(); if ((w > 0) && (h > 0)) { context.beginPath(); context.ellipse(0, 0, w / 2, h / 2, 0, 0, Math.PI * 2, true); context.closePath(); return true; } return false; }
java
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { final double w = attr.getWidth(); final double h = attr.getHeight(); if ((w > 0) && (h > 0)) { context.beginPath(); context.ellipse(0, 0, w / 2, h / 2, 0, 0, Math.PI * 2, true); context.closePath(); return true; } return false; }
[ "@", "Override", "protected", "boolean", "prepare", "(", "final", "Context2D", "context", ",", "final", "Attributes", "attr", ",", "final", "double", "alpha", ")", "{", "final", "double", "w", "=", "attr", ".", "getWidth", "(", ")", ";", "final", "double", "h", "=", "attr", ".", "getHeight", "(", ")", ";", "if", "(", "(", "w", ">", "0", ")", "&&", "(", "h", ">", "0", ")", ")", "{", "context", ".", "beginPath", "(", ")", ";", "context", ".", "ellipse", "(", "0", ",", "0", ",", "w", "/", "2", ",", "h", "/", "2", ",", "0", ",", "0", ",", "Math", ".", "PI", "*", "2", ",", "true", ")", ";", "context", ".", "closePath", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Draws this ellipse. @param context the {@link Context2D} used to draw this ellipse.
[ "Draws", "this", "ellipse", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Ellipse.java#L77-L95
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/GuildWars2.java
GuildWars2.setInstance
public static void setInstance(Cache cache) throws GuildWars2Exception { """ Use this to initialize instance with custom cache @param cache {@link Cache} @throws GuildWars2Exception instance already exist """ if (instance != null) throw new GuildWars2Exception(ErrorCode.Other, "Instance already initialized"); instance = new GuildWars2(cache); }
java
public static void setInstance(Cache cache) throws GuildWars2Exception { if (instance != null) throw new GuildWars2Exception(ErrorCode.Other, "Instance already initialized"); instance = new GuildWars2(cache); }
[ "public", "static", "void", "setInstance", "(", "Cache", "cache", ")", "throws", "GuildWars2Exception", "{", "if", "(", "instance", "!=", "null", ")", "throw", "new", "GuildWars2Exception", "(", "ErrorCode", ".", "Other", ",", "\"Instance already initialized\"", ")", ";", "instance", "=", "new", "GuildWars2", "(", "cache", ")", ";", "}" ]
Use this to initialize instance with custom cache @param cache {@link Cache} @throws GuildWars2Exception instance already exist
[ "Use", "this", "to", "initialize", "instance", "with", "custom", "cache" ]
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/GuildWars2.java#L74-L78
icode/ameba-utils
src/main/java/ameba/captcha/audio/Sample.java
Sample.getStereoSamples
public void getStereoSamples(double[] leftSamples, double[] rightSamples) throws IOException { """ Convenience method. Extract left and right channels for common stereo files. leftSamples and rightSamples must be of size getSampleCount() @param leftSamples leftSamples @param rightSamples rightSamples @throws java.io.IOException java.io.IOException """ long sampleCount = getSampleCount(); double[] interleavedSamples = new double[(int) sampleCount * 2]; getInterleavedSamples(0, sampleCount, interleavedSamples); for (int i = 0; i < leftSamples.length; i++) { leftSamples[i] = interleavedSamples[2 * i]; rightSamples[i] = interleavedSamples[2 * i + 1]; } }
java
public void getStereoSamples(double[] leftSamples, double[] rightSamples) throws IOException { long sampleCount = getSampleCount(); double[] interleavedSamples = new double[(int) sampleCount * 2]; getInterleavedSamples(0, sampleCount, interleavedSamples); for (int i = 0; i < leftSamples.length; i++) { leftSamples[i] = interleavedSamples[2 * i]; rightSamples[i] = interleavedSamples[2 * i + 1]; } }
[ "public", "void", "getStereoSamples", "(", "double", "[", "]", "leftSamples", ",", "double", "[", "]", "rightSamples", ")", "throws", "IOException", "{", "long", "sampleCount", "=", "getSampleCount", "(", ")", ";", "double", "[", "]", "interleavedSamples", "=", "new", "double", "[", "(", "int", ")", "sampleCount", "*", "2", "]", ";", "getInterleavedSamples", "(", "0", ",", "sampleCount", ",", "interleavedSamples", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "leftSamples", ".", "length", ";", "i", "++", ")", "{", "leftSamples", "[", "i", "]", "=", "interleavedSamples", "[", "2", "*", "i", "]", ";", "rightSamples", "[", "i", "]", "=", "interleavedSamples", "[", "2", "*", "i", "+", "1", "]", ";", "}", "}" ]
Convenience method. Extract left and right channels for common stereo files. leftSamples and rightSamples must be of size getSampleCount() @param leftSamples leftSamples @param rightSamples rightSamples @throws java.io.IOException java.io.IOException
[ "Convenience", "method", ".", "Extract", "left", "and", "right", "channels", "for", "common", "stereo", "files", ".", "leftSamples", "and", "rightSamples", "must", "be", "of", "size", "getSampleCount", "()" ]
train
https://github.com/icode/ameba-utils/blob/1aad5317a22e546c83dfe2dc0c80a1dc1fa0ea35/src/main/java/ameba/captcha/audio/Sample.java#L204-L213
kkopacz/agiso-core
bundles/agiso-core-logging/src/main/java/org/agiso/core/logging/log4j/appender/DatabaseLoggerAppender.java
DatabaseLoggerAppender.fillStatement
protected void fillStatement(PreparedStatement stmt, LoggingEvent event) throws SQLException { """ CREATE TABLE `logs` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `level` varchar(7) NOT NULL, `logTime` datetime NOT NULL, `message` varchar(511) DEFAULT NULL, `thread` varchar(63) DEFAULT NULL, `logger` varchar(127) DEFAULT NULL, `location` varchar(255) DEFAULT NULL, `exception` longtext, PRIMARY KEY (`id`) ) ENGINE=InnoDB CHARSET=utf8; INSERT INTO logs (level, logTime, message, thread, logger, location, exception) VALUES(?, ?, ?,, ?, ?, ?, ?); @param stmt @param event @throws SQLException """ Object value; stmt.setString(1, event.getLevel().toString()); // level stmt.setTimestamp(2, new Timestamp(event.getTimeStamp())); // timestamp value = event.getMessage(); // message stmt.setString(3, value == null? null : value.toString()); stmt.setString(4, event.getThreadName()); // thread stmt.setString(5, event.getLoggerName()); // logger stmt.setString(6, event.getLocationInformation().fullInfo); // location if(null == event.getThrowableStrRep()) { // exception stmt.setString(7, null); } else { value = new StringBuffer(); for(String string : event.getThrowableStrRep()) { ((StringBuffer)value).append(string).append("\n"); } stmt.setString(7, value.toString()); } }
java
protected void fillStatement(PreparedStatement stmt, LoggingEvent event) throws SQLException { Object value; stmt.setString(1, event.getLevel().toString()); // level stmt.setTimestamp(2, new Timestamp(event.getTimeStamp())); // timestamp value = event.getMessage(); // message stmt.setString(3, value == null? null : value.toString()); stmt.setString(4, event.getThreadName()); // thread stmt.setString(5, event.getLoggerName()); // logger stmt.setString(6, event.getLocationInformation().fullInfo); // location if(null == event.getThrowableStrRep()) { // exception stmt.setString(7, null); } else { value = new StringBuffer(); for(String string : event.getThrowableStrRep()) { ((StringBuffer)value).append(string).append("\n"); } stmt.setString(7, value.toString()); } }
[ "protected", "void", "fillStatement", "(", "PreparedStatement", "stmt", ",", "LoggingEvent", "event", ")", "throws", "SQLException", "{", "Object", "value", ";", "stmt", ".", "setString", "(", "1", ",", "event", ".", "getLevel", "(", ")", ".", "toString", "(", ")", ")", ";", "// level", "stmt", ".", "setTimestamp", "(", "2", ",", "new", "Timestamp", "(", "event", ".", "getTimeStamp", "(", ")", ")", ")", ";", "// timestamp", "value", "=", "event", ".", "getMessage", "(", ")", ";", "// message", "stmt", ".", "setString", "(", "3", ",", "value", "==", "null", "?", "null", ":", "value", ".", "toString", "(", ")", ")", ";", "stmt", ".", "setString", "(", "4", ",", "event", ".", "getThreadName", "(", ")", ")", ";", "// thread", "stmt", ".", "setString", "(", "5", ",", "event", ".", "getLoggerName", "(", ")", ")", ";", "// logger", "stmt", ".", "setString", "(", "6", ",", "event", ".", "getLocationInformation", "(", ")", ".", "fullInfo", ")", ";", "// location", "if", "(", "null", "==", "event", ".", "getThrowableStrRep", "(", ")", ")", "{", "// exception", "stmt", ".", "setString", "(", "7", ",", "null", ")", ";", "}", "else", "{", "value", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "String", "string", ":", "event", ".", "getThrowableStrRep", "(", ")", ")", "{", "(", "(", "StringBuffer", ")", "value", ")", ".", "append", "(", "string", ")", ".", "append", "(", "\"\\n\"", ")", ";", "}", "stmt", ".", "setString", "(", "7", ",", "value", ".", "toString", "(", ")", ")", ";", "}", "}" ]
CREATE TABLE `logs` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `level` varchar(7) NOT NULL, `logTime` datetime NOT NULL, `message` varchar(511) DEFAULT NULL, `thread` varchar(63) DEFAULT NULL, `logger` varchar(127) DEFAULT NULL, `location` varchar(255) DEFAULT NULL, `exception` longtext, PRIMARY KEY (`id`) ) ENGINE=InnoDB CHARSET=utf8; INSERT INTO logs (level, logTime, message, thread, logger, location, exception) VALUES(?, ?, ?,, ?, ?, ?, ?); @param stmt @param event @throws SQLException
[ "CREATE", "TABLE", "logs", "(", "id", "bigint", "(", "20", ")", "NOT", "NULL", "AUTO_INCREMENT", "level", "varchar", "(", "7", ")", "NOT", "NULL", "logTime", "datetime", "NOT", "NULL", "message", "varchar", "(", "511", ")", "DEFAULT", "NULL", "thread", "varchar", "(", "63", ")", "DEFAULT", "NULL", "logger", "varchar", "(", "127", ")", "DEFAULT", "NULL", "location", "varchar", "(", "255", ")", "DEFAULT", "NULL", "exception", "longtext", "PRIMARY", "KEY", "(", "id", ")", ")", "ENGINE", "=", "InnoDB", "CHARSET", "=", "utf8", ";" ]
train
https://github.com/kkopacz/agiso-core/blob/b994ec0146be1fe3f10829d69cd719bdbdebe1c5/bundles/agiso-core-logging/src/main/java/org/agiso/core/logging/log4j/appender/DatabaseLoggerAppender.java#L283-L301
google/closure-compiler
src/com/google/javascript/jscomp/ModuleIdentifier.java
ModuleIdentifier.forFile
public static ModuleIdentifier forFile(String filepath) { """ Returns an identifier for an ES or CommonJS module. @param filepath Path to the ES or CommonJS module. """ String normalizedName = ModuleNames.fileToModuleName(filepath); return new AutoValue_ModuleIdentifier(filepath, normalizedName, normalizedName); }
java
public static ModuleIdentifier forFile(String filepath) { String normalizedName = ModuleNames.fileToModuleName(filepath); return new AutoValue_ModuleIdentifier(filepath, normalizedName, normalizedName); }
[ "public", "static", "ModuleIdentifier", "forFile", "(", "String", "filepath", ")", "{", "String", "normalizedName", "=", "ModuleNames", ".", "fileToModuleName", "(", "filepath", ")", ";", "return", "new", "AutoValue_ModuleIdentifier", "(", "filepath", ",", "normalizedName", ",", "normalizedName", ")", ";", "}" ]
Returns an identifier for an ES or CommonJS module. @param filepath Path to the ES or CommonJS module.
[ "Returns", "an", "identifier", "for", "an", "ES", "or", "CommonJS", "module", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ModuleIdentifier.java#L81-L84
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.fatalf
public void fatalf(Throwable t, String format, Object... params) { """ Issue a formatted log message with a level of FATAL. @param t the throwable @param format the format string, as per {@link String#format(String, Object...)} @param params the parameters """ doLogf(Level.FATAL, FQCN, format, params, t); }
java
public void fatalf(Throwable t, String format, Object... params) { doLogf(Level.FATAL, FQCN, format, params, t); }
[ "public", "void", "fatalf", "(", "Throwable", "t", ",", "String", "format", ",", "Object", "...", "params", ")", "{", "doLogf", "(", "Level", ".", "FATAL", ",", "FQCN", ",", "format", ",", "params", ",", "t", ")", ";", "}" ]
Issue a formatted log message with a level of FATAL. @param t the throwable @param format the format string, as per {@link String#format(String, Object...)} @param params the parameters
[ "Issue", "a", "formatted", "log", "message", "with", "a", "level", "of", "FATAL", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L1987-L1989
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/util/xml/ObjectTreeParser.java
ObjectTreeParser.setField
private void setField(Field field, Object instance, Object value) throws SlickXMLException { """ Set a field value on a object instance @param field The field to be set @param instance The instance of the object to set it on @param value The value to set @throws SlickXMLException Indicates a failure to set or access the field """ try { field.setAccessible(true); field.set(instance, value); } catch (IllegalArgumentException e) { throw new SlickXMLException("Failed to set: "+field+" for an XML attribute, is it valid?", e); } catch (IllegalAccessException e) { throw new SlickXMLException("Failed to set: "+field+" for an XML attribute, is it valid?", e); } finally { field.setAccessible(false); } }
java
private void setField(Field field, Object instance, Object value) throws SlickXMLException { try { field.setAccessible(true); field.set(instance, value); } catch (IllegalArgumentException e) { throw new SlickXMLException("Failed to set: "+field+" for an XML attribute, is it valid?", e); } catch (IllegalAccessException e) { throw new SlickXMLException("Failed to set: "+field+" for an XML attribute, is it valid?", e); } finally { field.setAccessible(false); } }
[ "private", "void", "setField", "(", "Field", "field", ",", "Object", "instance", ",", "Object", "value", ")", "throws", "SlickXMLException", "{", "try", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "field", ".", "set", "(", "instance", ",", "value", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "SlickXMLException", "(", "\"Failed to set: \"", "+", "field", "+", "\" for an XML attribute, is it valid?\"", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "SlickXMLException", "(", "\"Failed to set: \"", "+", "field", "+", "\" for an XML attribute, is it valid?\"", ",", "e", ")", ";", "}", "finally", "{", "field", ".", "setAccessible", "(", "false", ")", ";", "}", "}" ]
Set a field value on a object instance @param field The field to be set @param instance The instance of the object to set it on @param value The value to set @throws SlickXMLException Indicates a failure to set or access the field
[ "Set", "a", "field", "value", "on", "a", "object", "instance" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/util/xml/ObjectTreeParser.java#L429-L440
brettwooldridge/SansOrm
src/main/java/com/zaxxer/sansorm/SqlClosureElf.java
SqlClosureElf.executeQuery
public static ResultSet executeQuery(Connection connection, String sql, Object... args) throws SQLException { """ Execute the specified SQL as a PreparedStatement with the specified arguments. @param connection a Connection @param sql the SQL statement to prepare and execute @param args the optional arguments to execute with the query @return a ResultSet object @throws SQLException if a {@link SQLException} occurs """ return OrmReader.statementToResultSet(connection.prepareStatement(sql), args); }
java
public static ResultSet executeQuery(Connection connection, String sql, Object... args) throws SQLException { return OrmReader.statementToResultSet(connection.prepareStatement(sql), args); }
[ "public", "static", "ResultSet", "executeQuery", "(", "Connection", "connection", ",", "String", "sql", ",", "Object", "...", "args", ")", "throws", "SQLException", "{", "return", "OrmReader", ".", "statementToResultSet", "(", "connection", ".", "prepareStatement", "(", "sql", ")", ",", "args", ")", ";", "}" ]
Execute the specified SQL as a PreparedStatement with the specified arguments. @param connection a Connection @param sql the SQL statement to prepare and execute @param args the optional arguments to execute with the query @return a ResultSet object @throws SQLException if a {@link SQLException} occurs
[ "Execute", "the", "specified", "SQL", "as", "a", "PreparedStatement", "with", "the", "specified", "arguments", "." ]
train
https://github.com/brettwooldridge/SansOrm/blob/ab22721db79c5f20c0e8483f09eda2844d596557/src/main/java/com/zaxxer/sansorm/SqlClosureElf.java#L226-L229
casmi/casmi
src/main/java/casmi/graphics/element/Arc.java
Arc.setEdgeColor
public void setEdgeColor(ColorSet colorSet) { """ Sets the colorSet of the edge of this Arc. @param colorSet The colorSet of the edge of the Arc. """ if (edgeColor == null) edgeColor = new RGBColor(0.0, 0.0, 0.0); setGradation(true); this.edgeColor = RGBColor.color(colorSet); }
java
public void setEdgeColor(ColorSet colorSet) { if (edgeColor == null) edgeColor = new RGBColor(0.0, 0.0, 0.0); setGradation(true); this.edgeColor = RGBColor.color(colorSet); }
[ "public", "void", "setEdgeColor", "(", "ColorSet", "colorSet", ")", "{", "if", "(", "edgeColor", "==", "null", ")", "edgeColor", "=", "new", "RGBColor", "(", "0.0", ",", "0.0", ",", "0.0", ")", ";", "setGradation", "(", "true", ")", ";", "this", ".", "edgeColor", "=", "RGBColor", ".", "color", "(", "colorSet", ")", ";", "}" ]
Sets the colorSet of the edge of this Arc. @param colorSet The colorSet of the edge of the Arc.
[ "Sets", "the", "colorSet", "of", "the", "edge", "of", "this", "Arc", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Arc.java#L447-L451
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/util/Utils.java
Utils.normalize
public static String normalize(final String text, final Configuration config) { """ システム設定に従いラベルを正規化する。 @since 1.1 @param text セルのラベル @param config システム設定 @return true:ラベルが一致する。 """ if(text != null && config.isNormalizeLabelText()){ return text.trim().replaceAll("[\n\r]", "").replaceAll("[\t  ]+", " "); } return text; }
java
public static String normalize(final String text, final Configuration config){ if(text != null && config.isNormalizeLabelText()){ return text.trim().replaceAll("[\n\r]", "").replaceAll("[\t  ]+", " "); } return text; }
[ "public", "static", "String", "normalize", "(", "final", "String", "text", ",", "final", "Configuration", "config", ")", "{", "if", "(", "text", "!=", "null", "&&", "config", ".", "isNormalizeLabelText", "(", ")", ")", "{", "return", "text", ".", "trim", "(", ")", ".", "replaceAll", "(", "\"[\\n\\r]\"", ",", "\"\"", ")", ".", "replaceAll", "(", "\"[\\t  ]+\", ", "\"", "\");", "\r", "", "}", "return", "text", ";", "}" ]
システム設定に従いラベルを正規化する。 @since 1.1 @param text セルのラベル @param config システム設定 @return true:ラベルが一致する。
[ "システム設定に従いラベルを正規化する。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/Utils.java#L256-L261
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java
ThriftUtils.toBytes
public static byte[] toBytes(TBase<?, ?> record) throws TException { """ Serializes a thrift object to byte array. @param record @return @throws TException """ if (record == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport transport = new TIOStreamTransport(null, baos); TProtocol oProtocol = protocolFactory.getProtocol(transport); record.write(oProtocol); // baos.close(); return baos.toByteArray(); }
java
public static byte[] toBytes(TBase<?, ?> record) throws TException { if (record == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport transport = new TIOStreamTransport(null, baos); TProtocol oProtocol = protocolFactory.getProtocol(transport); record.write(oProtocol); // baos.close(); return baos.toByteArray(); }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "TBase", "<", "?", ",", "?", ">", "record", ")", "throws", "TException", "{", "if", "(", "record", "==", "null", ")", "{", "return", "null", ";", "}", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "TTransport", "transport", "=", "new", "TIOStreamTransport", "(", "null", ",", "baos", ")", ";", "TProtocol", "oProtocol", "=", "protocolFactory", ".", "getProtocol", "(", "transport", ")", ";", "record", ".", "write", "(", "oProtocol", ")", ";", "// baos.close();", "return", "baos", ".", "toByteArray", "(", ")", ";", "}" ]
Serializes a thrift object to byte array. @param record @return @throws TException
[ "Serializes", "a", "thrift", "object", "to", "byte", "array", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java#L45-L55
DDTH/ddth-zookeeper
src/main/java/com/github/ddth/zookeeper/ZooKeeperClient.java
ZooKeeperClient.removeNode
public boolean removeNode(String path, boolean removeChildren) throws ZooKeeperException { """ Removes an existing node. @param path @param removeChildren {@code true} to indicate that child nodes should be removed too @return {@code true} if node has been removed successfully, {@code false} otherwise (maybe node is not empty) @since 0.4.1 @throws ZooKeeperException """ try { if (removeChildren) { curatorFramework.delete().deletingChildrenIfNeeded().forPath(path); } else { curatorFramework.delete().forPath(path); } } catch (KeeperException.NotEmptyException e) { return false; } catch (KeeperException.NoNodeException e) { return true; } catch (Exception e) { if (e instanceof ZooKeeperException) { throw (ZooKeeperException) e; } else { throw new ZooKeeperException(e); } } _invalidateCache(path); return true; }
java
public boolean removeNode(String path, boolean removeChildren) throws ZooKeeperException { try { if (removeChildren) { curatorFramework.delete().deletingChildrenIfNeeded().forPath(path); } else { curatorFramework.delete().forPath(path); } } catch (KeeperException.NotEmptyException e) { return false; } catch (KeeperException.NoNodeException e) { return true; } catch (Exception e) { if (e instanceof ZooKeeperException) { throw (ZooKeeperException) e; } else { throw new ZooKeeperException(e); } } _invalidateCache(path); return true; }
[ "public", "boolean", "removeNode", "(", "String", "path", ",", "boolean", "removeChildren", ")", "throws", "ZooKeeperException", "{", "try", "{", "if", "(", "removeChildren", ")", "{", "curatorFramework", ".", "delete", "(", ")", ".", "deletingChildrenIfNeeded", "(", ")", ".", "forPath", "(", "path", ")", ";", "}", "else", "{", "curatorFramework", ".", "delete", "(", ")", ".", "forPath", "(", "path", ")", ";", "}", "}", "catch", "(", "KeeperException", ".", "NotEmptyException", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "KeeperException", ".", "NoNodeException", "e", ")", "{", "return", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "e", "instanceof", "ZooKeeperException", ")", "{", "throw", "(", "ZooKeeperException", ")", "e", ";", "}", "else", "{", "throw", "new", "ZooKeeperException", "(", "e", ")", ";", "}", "}", "_invalidateCache", "(", "path", ")", ";", "return", "true", ";", "}" ]
Removes an existing node. @param path @param removeChildren {@code true} to indicate that child nodes should be removed too @return {@code true} if node has been removed successfully, {@code false} otherwise (maybe node is not empty) @since 0.4.1 @throws ZooKeeperException
[ "Removes", "an", "existing", "node", "." ]
train
https://github.com/DDTH/ddth-zookeeper/blob/0994eea8b25fa3d885f3da4579768b7d08c1c32b/src/main/java/com/github/ddth/zookeeper/ZooKeeperClient.java#L610-L630
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitSync
public EventBus emitSync(EventObject event, Object... args) { """ Emit a event object with parameters and force all listeners to be called synchronously. @param event the target event @param args the arguments passed in @see #emit(EventObject, Object...) """ return _emitWithOnceBus(eventContextSync(event, args)); }
java
public EventBus emitSync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
[ "public", "EventBus", "emitSync", "(", "EventObject", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextSync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit a event object with parameters and force all listeners to be called synchronously. @param event the target event @param args the arguments passed in @see #emit(EventObject, Object...)
[ "Emit", "a", "event", "object", "with", "parameters", "and", "force", "all", "listeners", "to", "be", "called", "synchronously", "." ]
train
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1105-L1107
craftercms/commons
utilities/src/main/java/org/craftercms/commons/lang/RegexUtils.java
RegexUtils.matchesAny
public static boolean matchesAny(String str, List<String> regexes, boolean fullMatch) { """ Returns true if the string matches any of the specified regexes. @param str the string to match @param regexes the regexes used for matching @param fullMatch if the entire string should be matched @return true if the string matches one or more of the regexes """ if (CollectionUtils.isNotEmpty(regexes)) { for (String regex : regexes) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); if (fullMatch) { if (matcher.matches()) { return true; } } else { if (matcher.find()) { return true; } } } } return false; }
java
public static boolean matchesAny(String str, List<String> regexes, boolean fullMatch) { if (CollectionUtils.isNotEmpty(regexes)) { for (String regex : regexes) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); if (fullMatch) { if (matcher.matches()) { return true; } } else { if (matcher.find()) { return true; } } } } return false; }
[ "public", "static", "boolean", "matchesAny", "(", "String", "str", ",", "List", "<", "String", ">", "regexes", ",", "boolean", "fullMatch", ")", "{", "if", "(", "CollectionUtils", ".", "isNotEmpty", "(", "regexes", ")", ")", "{", "for", "(", "String", "regex", ":", "regexes", ")", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "regex", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "str", ")", ";", "if", "(", "fullMatch", ")", "{", "if", "(", "matcher", ".", "matches", "(", ")", ")", "{", "return", "true", ";", "}", "}", "else", "{", "if", "(", "matcher", ".", "find", "(", ")", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
Returns true if the string matches any of the specified regexes. @param str the string to match @param regexes the regexes used for matching @param fullMatch if the entire string should be matched @return true if the string matches one or more of the regexes
[ "Returns", "true", "if", "the", "string", "matches", "any", "of", "the", "specified", "regexes", "." ]
train
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/lang/RegexUtils.java#L74-L93
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java
MercatorProjection.latitudeToPixelY
public static double latitudeToPixelY(double latitude, long mapSize) { """ Converts a latitude coordinate (in degrees) to a pixel Y coordinate at a certain map size. @param latitude the latitude coordinate that should be converted. @param mapSize precomputed size of map. @return the pixel Y coordinate of the latitude value. """ double sinLatitude = Math.sin(latitude * (Math.PI / 180)); // FIXME improve this formula so that it works correctly without the clipping double pixelY = (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) * mapSize; return Math.min(Math.max(0, pixelY), mapSize); }
java
public static double latitudeToPixelY(double latitude, long mapSize) { double sinLatitude = Math.sin(latitude * (Math.PI / 180)); // FIXME improve this formula so that it works correctly without the clipping double pixelY = (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) * mapSize; return Math.min(Math.max(0, pixelY), mapSize); }
[ "public", "static", "double", "latitudeToPixelY", "(", "double", "latitude", ",", "long", "mapSize", ")", "{", "double", "sinLatitude", "=", "Math", ".", "sin", "(", "latitude", "*", "(", "Math", ".", "PI", "/", "180", ")", ")", ";", "// FIXME improve this formula so that it works correctly without the clipping", "double", "pixelY", "=", "(", "0.5", "-", "Math", ".", "log", "(", "(", "1", "+", "sinLatitude", ")", "/", "(", "1", "-", "sinLatitude", ")", ")", "/", "(", "4", "*", "Math", ".", "PI", ")", ")", "*", "mapSize", ";", "return", "Math", ".", "min", "(", "Math", ".", "max", "(", "0", ",", "pixelY", ")", ",", "mapSize", ")", ";", "}" ]
Converts a latitude coordinate (in degrees) to a pixel Y coordinate at a certain map size. @param latitude the latitude coordinate that should be converted. @param mapSize precomputed size of map. @return the pixel Y coordinate of the latitude value.
[ "Converts", "a", "latitude", "coordinate", "(", "in", "degrees", ")", "to", "a", "pixel", "Y", "coordinate", "at", "a", "certain", "map", "size", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java#L216-L221
UrielCh/ovh-java-sdk
ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java
ApiOvhIpLoadbalancing.serviceName_vrack_network_vrackNetworkId_GET
public OvhVrackNetwork serviceName_vrack_network_vrackNetworkId_GET(String serviceName, Long vrackNetworkId) throws IOException { """ Get this object properties REST: GET /ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId} @param serviceName [required] The internal name of your IP load balancing @param vrackNetworkId [required] Internal Load Balancer identifier of the vRack private network description API beta """ String qPath = "/ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}"; StringBuilder sb = path(qPath, serviceName, vrackNetworkId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhVrackNetwork.class); }
java
public OvhVrackNetwork serviceName_vrack_network_vrackNetworkId_GET(String serviceName, Long vrackNetworkId) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}"; StringBuilder sb = path(qPath, serviceName, vrackNetworkId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhVrackNetwork.class); }
[ "public", "OvhVrackNetwork", "serviceName_vrack_network_vrackNetworkId_GET", "(", "String", "serviceName", ",", "Long", "vrackNetworkId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "vrackNetworkId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhVrackNetwork", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId} @param serviceName [required] The internal name of your IP load balancing @param vrackNetworkId [required] Internal Load Balancer identifier of the vRack private network description API beta
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1109-L1114
aws/aws-sdk-java
aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/GetResourceDefinitionResult.java
GetResourceDefinitionResult.withTags
public GetResourceDefinitionResult withTags(java.util.Map<String, String> tags) { """ The tags for the definition. @param tags The tags for the definition. @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public GetResourceDefinitionResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "GetResourceDefinitionResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
The tags for the definition. @param tags The tags for the definition. @return Returns a reference to this object so that method calls can be chained together.
[ "The", "tags", "for", "the", "definition", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/GetResourceDefinitionResult.java#L310-L313
zerodhatech/javakiteconnect
kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java
KiteRequestHandler.getRequest
public JSONObject getRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException { """ Makes a GET request. @return JSONObject which is received by Kite Trade. @param url is the endpoint to which request has to be sent. @param apiKey is the api key of the Kite Connect app. @param accessToken is the access token obtained after successful login process. @throws IOException is thrown when there is a connection related error. @throws KiteException is thrown for all Kite Trade related errors. @throws JSONException is thrown for parsing errors. """ Request request = createGetRequest(url, apiKey, accessToken); Response response = client.newCall(request).execute(); String body = response.body().string(); return new KiteResponseHandler().handle(response, body); }
java
public JSONObject getRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException { Request request = createGetRequest(url, apiKey, accessToken); Response response = client.newCall(request).execute(); String body = response.body().string(); return new KiteResponseHandler().handle(response, body); }
[ "public", "JSONObject", "getRequest", "(", "String", "url", ",", "String", "apiKey", ",", "String", "accessToken", ")", "throws", "IOException", ",", "KiteException", ",", "JSONException", "{", "Request", "request", "=", "createGetRequest", "(", "url", ",", "apiKey", ",", "accessToken", ")", ";", "Response", "response", "=", "client", ".", "newCall", "(", "request", ")", ".", "execute", "(", ")", ";", "String", "body", "=", "response", ".", "body", "(", ")", ".", "string", "(", ")", ";", "return", "new", "KiteResponseHandler", "(", ")", ".", "handle", "(", "response", ",", "body", ")", ";", "}" ]
Makes a GET request. @return JSONObject which is received by Kite Trade. @param url is the endpoint to which request has to be sent. @param apiKey is the api key of the Kite Connect app. @param accessToken is the access token obtained after successful login process. @throws IOException is thrown when there is a connection related error. @throws KiteException is thrown for all Kite Trade related errors. @throws JSONException is thrown for parsing errors.
[ "Makes", "a", "GET", "request", "." ]
train
https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java#L49-L54
IBM/ibm-cos-sdk-java
ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/s3/internal/crypto/ContentCryptoMaterial.java
ContentCryptoMaterial.doCreate
private static ContentCryptoMaterial doCreate(SecretKey cek, byte[] iv, EncryptionMaterials kekMaterials, ContentCryptoScheme contentCryptoScheme, S3CryptoScheme targetS3CryptoScheme, Provider provider, AWSKMS kms, AmazonWebServiceRequest req) { """ Returns a new instance of <code>ContentCryptoMaterial</code> for the given input parameters by using the specified content crypto scheme, and S3 crypto scheme. Note network calls are involved if the CEK is to be protected by KMS. @param cek content encrypting key @param iv initialization vector @param kekMaterials kek encryption material used to secure the CEK; can be KMS enabled. @param contentCryptoScheme content crypto scheme to be used, which can differ from the one of <code>targetS3CryptoScheme</code> @param targetS3CryptoScheme the target s3 crypto scheme to be used for providing the key wrapping scheme and mechanism for secure randomness @param provider security provider @param kms reference to the KMS client @param req the originating AWS service request """ // Secure the envelope symmetric key either by encryption, key wrapping // or KMS. SecuredCEK cekSecured = secureCEK(cek, kekMaterials, targetS3CryptoScheme.getKeyWrapScheme(), targetS3CryptoScheme.getSecureRandom(), provider, kms, req); return wrap(cek, iv, contentCryptoScheme, provider, cekSecured); }
java
private static ContentCryptoMaterial doCreate(SecretKey cek, byte[] iv, EncryptionMaterials kekMaterials, ContentCryptoScheme contentCryptoScheme, S3CryptoScheme targetS3CryptoScheme, Provider provider, AWSKMS kms, AmazonWebServiceRequest req) { // Secure the envelope symmetric key either by encryption, key wrapping // or KMS. SecuredCEK cekSecured = secureCEK(cek, kekMaterials, targetS3CryptoScheme.getKeyWrapScheme(), targetS3CryptoScheme.getSecureRandom(), provider, kms, req); return wrap(cek, iv, contentCryptoScheme, provider, cekSecured); }
[ "private", "static", "ContentCryptoMaterial", "doCreate", "(", "SecretKey", "cek", ",", "byte", "[", "]", "iv", ",", "EncryptionMaterials", "kekMaterials", ",", "ContentCryptoScheme", "contentCryptoScheme", ",", "S3CryptoScheme", "targetS3CryptoScheme", ",", "Provider", "provider", ",", "AWSKMS", "kms", ",", "AmazonWebServiceRequest", "req", ")", "{", "// Secure the envelope symmetric key either by encryption, key wrapping", "// or KMS.", "SecuredCEK", "cekSecured", "=", "secureCEK", "(", "cek", ",", "kekMaterials", ",", "targetS3CryptoScheme", ".", "getKeyWrapScheme", "(", ")", ",", "targetS3CryptoScheme", ".", "getSecureRandom", "(", ")", ",", "provider", ",", "kms", ",", "req", ")", ";", "return", "wrap", "(", "cek", ",", "iv", ",", "contentCryptoScheme", ",", "provider", ",", "cekSecured", ")", ";", "}" ]
Returns a new instance of <code>ContentCryptoMaterial</code> for the given input parameters by using the specified content crypto scheme, and S3 crypto scheme. Note network calls are involved if the CEK is to be protected by KMS. @param cek content encrypting key @param iv initialization vector @param kekMaterials kek encryption material used to secure the CEK; can be KMS enabled. @param contentCryptoScheme content crypto scheme to be used, which can differ from the one of <code>targetS3CryptoScheme</code> @param targetS3CryptoScheme the target s3 crypto scheme to be used for providing the key wrapping scheme and mechanism for secure randomness @param provider security provider @param kms reference to the KMS client @param req the originating AWS service request
[ "Returns", "a", "new", "instance", "of", "<code", ">", "ContentCryptoMaterial<", "/", "code", ">", "for", "the", "given", "input", "parameters", "by", "using", "the", "specified", "content", "crypto", "scheme", "and", "S3", "crypto", "scheme", "." ]
train
https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/s3/internal/crypto/ContentCryptoMaterial.java#L798-L812
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDMAuditor.java
XDMAuditor.auditPortableMediaImport
public void auditPortableMediaImport( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { """ Audits a PHI Import event for the IHE XDM Portable Media Importer actor and ITI-32 Distribute Document Set on Media Transaction. @param eventOutcome The event outcome indicator @param submissionSetUniqueId The Unique ID of the Submission Set imported @param patientId The ID of the Patient to which the Submission Set pertains """ if (!isAuditorEnabled()) { return; } ImportEvent importEvent = new ImportEvent(false, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse); importEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); importEvent.addDestinationActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), false); if (!EventUtils.isEmptyOrNull(patientId)) { importEvent.addPatientParticipantObject(patientId); } importEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(importEvent); }
java
public void auditPortableMediaImport( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { if (!isAuditorEnabled()) { return; } ImportEvent importEvent = new ImportEvent(false, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse); importEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId()); importEvent.addDestinationActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), false); if (!EventUtils.isEmptyOrNull(patientId)) { importEvent.addPatientParticipantObject(patientId); } importEvent.addSubmissionSetParticipantObject(submissionSetUniqueId); audit(importEvent); }
[ "public", "void", "auditPortableMediaImport", "(", "RFC3881EventOutcomeCodes", "eventOutcome", ",", "String", "submissionSetUniqueId", ",", "String", "patientId", ",", "List", "<", "CodedValueType", ">", "purposesOfUse", ")", "{", "if", "(", "!", "isAuditorEnabled", "(", ")", ")", "{", "return", ";", "}", "ImportEvent", "importEvent", "=", "new", "ImportEvent", "(", "false", ",", "eventOutcome", ",", "new", "IHETransactionEventTypeCodes", ".", "DistributeDocumentSetOnMedia", "(", ")", ",", "purposesOfUse", ")", ";", "importEvent", ".", "setAuditSourceId", "(", "getAuditSourceId", "(", ")", ",", "getAuditEnterpriseSiteId", "(", ")", ")", ";", "importEvent", ".", "addDestinationActiveParticipant", "(", "getSystemUserId", "(", ")", ",", "getSystemAltUserId", "(", ")", ",", "getSystemUserName", "(", ")", ",", "getSystemNetworkId", "(", ")", ",", "false", ")", ";", "if", "(", "!", "EventUtils", ".", "isEmptyOrNull", "(", "patientId", ")", ")", "{", "importEvent", ".", "addPatientParticipantObject", "(", "patientId", ")", ";", "}", "importEvent", ".", "addSubmissionSetParticipantObject", "(", "submissionSetUniqueId", ")", ";", "audit", "(", "importEvent", ")", ";", "}" ]
Audits a PHI Import event for the IHE XDM Portable Media Importer actor and ITI-32 Distribute Document Set on Media Transaction. @param eventOutcome The event outcome indicator @param submissionSetUniqueId The Unique ID of the Submission Set imported @param patientId The ID of the Patient to which the Submission Set pertains
[ "Audits", "a", "PHI", "Import", "event", "for", "the", "IHE", "XDM", "Portable", "Media", "Importer", "actor", "and", "ITI", "-", "32", "Distribute", "Document", "Set", "on", "Media", "Transaction", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDMAuditor.java#L53-L71
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/typeconvert/TypeConverter.java
TypeConverter.convertToChar
public static char convertToChar (@Nonnull final Object aSrcValue) { """ Convert the passed source value to char @param aSrcValue The source value. May not be <code>null</code>. @return The converted value. @throws TypeConverterException if the source value is <code>null</code> or if no converter was found or if the converter returned a <code>null</code> object. @throws RuntimeException If the converter itself throws an exception @see TypeConverterProviderBestMatch """ if (aSrcValue == null) throw new TypeConverterException (char.class, EReason.NULL_SOURCE_NOT_ALLOWED); final Character aValue = convert (aSrcValue, Character.class); return aValue.charValue (); }
java
public static char convertToChar (@Nonnull final Object aSrcValue) { if (aSrcValue == null) throw new TypeConverterException (char.class, EReason.NULL_SOURCE_NOT_ALLOWED); final Character aValue = convert (aSrcValue, Character.class); return aValue.charValue (); }
[ "public", "static", "char", "convertToChar", "(", "@", "Nonnull", "final", "Object", "aSrcValue", ")", "{", "if", "(", "aSrcValue", "==", "null", ")", "throw", "new", "TypeConverterException", "(", "char", ".", "class", ",", "EReason", ".", "NULL_SOURCE_NOT_ALLOWED", ")", ";", "final", "Character", "aValue", "=", "convert", "(", "aSrcValue", ",", "Character", ".", "class", ")", ";", "return", "aValue", ".", "charValue", "(", ")", ";", "}" ]
Convert the passed source value to char @param aSrcValue The source value. May not be <code>null</code>. @return The converted value. @throws TypeConverterException if the source value is <code>null</code> or if no converter was found or if the converter returned a <code>null</code> object. @throws RuntimeException If the converter itself throws an exception @see TypeConverterProviderBestMatch
[ "Convert", "the", "passed", "source", "value", "to", "char" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/typeconvert/TypeConverter.java#L194-L200
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/edge/GradientToEdgeFeatures.java
GradientToEdgeFeatures.nonMaxSuppression8
static public GrayF32 nonMaxSuppression8(GrayF32 intensity , GrayS8 direction , GrayF32 output ) { """ <p> Sets edge intensities to zero if the pixel has an intensity which is less than either of the two adjacent pixels. Pixel adjacency is determined by the gradients discretized direction. </p> @param intensity Edge intensities. Not modified. @param direction 8-Discretized direction. See {@link #discretizeDirection8(GrayF32, GrayS8)}. Not modified. @param output Filtered intensity. If null a new image will be declared and returned. Modified. @return Filtered edge intensity. """ InputSanityCheck.checkSameShape(intensity,direction); output = InputSanityCheck.checkDeclare(intensity,output); if( BoofConcurrency.USE_CONCURRENT ) { ImplEdgeNonMaxSuppression_MT.inner8(intensity, direction, output); ImplEdgeNonMaxSuppression_MT.border8(intensity, direction, output); } else { ImplEdgeNonMaxSuppression.inner8(intensity, direction, output); ImplEdgeNonMaxSuppression.border8(intensity, direction, output); } return output; }
java
static public GrayF32 nonMaxSuppression8(GrayF32 intensity , GrayS8 direction , GrayF32 output ) { InputSanityCheck.checkSameShape(intensity,direction); output = InputSanityCheck.checkDeclare(intensity,output); if( BoofConcurrency.USE_CONCURRENT ) { ImplEdgeNonMaxSuppression_MT.inner8(intensity, direction, output); ImplEdgeNonMaxSuppression_MT.border8(intensity, direction, output); } else { ImplEdgeNonMaxSuppression.inner8(intensity, direction, output); ImplEdgeNonMaxSuppression.border8(intensity, direction, output); } return output; }
[ "static", "public", "GrayF32", "nonMaxSuppression8", "(", "GrayF32", "intensity", ",", "GrayS8", "direction", ",", "GrayF32", "output", ")", "{", "InputSanityCheck", ".", "checkSameShape", "(", "intensity", ",", "direction", ")", ";", "output", "=", "InputSanityCheck", ".", "checkDeclare", "(", "intensity", ",", "output", ")", ";", "if", "(", "BoofConcurrency", ".", "USE_CONCURRENT", ")", "{", "ImplEdgeNonMaxSuppression_MT", ".", "inner8", "(", "intensity", ",", "direction", ",", "output", ")", ";", "ImplEdgeNonMaxSuppression_MT", ".", "border8", "(", "intensity", ",", "direction", ",", "output", ")", ";", "}", "else", "{", "ImplEdgeNonMaxSuppression", ".", "inner8", "(", "intensity", ",", "direction", ",", "output", ")", ";", "ImplEdgeNonMaxSuppression", ".", "border8", "(", "intensity", ",", "direction", ",", "output", ")", ";", "}", "return", "output", ";", "}" ]
<p> Sets edge intensities to zero if the pixel has an intensity which is less than either of the two adjacent pixels. Pixel adjacency is determined by the gradients discretized direction. </p> @param intensity Edge intensities. Not modified. @param direction 8-Discretized direction. See {@link #discretizeDirection8(GrayF32, GrayS8)}. Not modified. @param output Filtered intensity. If null a new image will be declared and returned. Modified. @return Filtered edge intensity.
[ "<p", ">", "Sets", "edge", "intensities", "to", "zero", "if", "the", "pixel", "has", "an", "intensity", "which", "is", "less", "than", "either", "of", "the", "two", "adjacent", "pixels", ".", "Pixel", "adjacency", "is", "determined", "by", "the", "gradients", "discretized", "direction", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/edge/GradientToEdgeFeatures.java#L494-L508
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Searcher.java
Searcher.addViewsToList
private void addViewsToList(List<WebElement> allWebElements, List<WebElement> webElementsOnScreen) { """ Adds views to a given list. @param allWebElements the list of all views @param webTextViewsOnScreen the list of views shown on screen """ int[] xyViewFromSet = new int[2]; int[] xyViewFromScreen = new int[2]; for(WebElement textFromScreen : webElementsOnScreen){ boolean foundView = false; textFromScreen.getLocationOnScreen(xyViewFromScreen); for(WebElement textFromList : allWebElements){ textFromList.getLocationOnScreen(xyViewFromSet); if(textFromScreen.getText().equals(textFromList.getText()) && xyViewFromScreen[0] == xyViewFromSet[0] && xyViewFromScreen[1] == xyViewFromSet[1]) { foundView = true; } } if(!foundView){ allWebElements.add(textFromScreen); } } }
java
private void addViewsToList(List<WebElement> allWebElements, List<WebElement> webElementsOnScreen){ int[] xyViewFromSet = new int[2]; int[] xyViewFromScreen = new int[2]; for(WebElement textFromScreen : webElementsOnScreen){ boolean foundView = false; textFromScreen.getLocationOnScreen(xyViewFromScreen); for(WebElement textFromList : allWebElements){ textFromList.getLocationOnScreen(xyViewFromSet); if(textFromScreen.getText().equals(textFromList.getText()) && xyViewFromScreen[0] == xyViewFromSet[0] && xyViewFromScreen[1] == xyViewFromSet[1]) { foundView = true; } } if(!foundView){ allWebElements.add(textFromScreen); } } }
[ "private", "void", "addViewsToList", "(", "List", "<", "WebElement", ">", "allWebElements", ",", "List", "<", "WebElement", ">", "webElementsOnScreen", ")", "{", "int", "[", "]", "xyViewFromSet", "=", "new", "int", "[", "2", "]", ";", "int", "[", "]", "xyViewFromScreen", "=", "new", "int", "[", "2", "]", ";", "for", "(", "WebElement", "textFromScreen", ":", "webElementsOnScreen", ")", "{", "boolean", "foundView", "=", "false", ";", "textFromScreen", ".", "getLocationOnScreen", "(", "xyViewFromScreen", ")", ";", "for", "(", "WebElement", "textFromList", ":", "allWebElements", ")", "{", "textFromList", ".", "getLocationOnScreen", "(", "xyViewFromSet", ")", ";", "if", "(", "textFromScreen", ".", "getText", "(", ")", ".", "equals", "(", "textFromList", ".", "getText", "(", ")", ")", "&&", "xyViewFromScreen", "[", "0", "]", "==", "xyViewFromSet", "[", "0", "]", "&&", "xyViewFromScreen", "[", "1", "]", "==", "xyViewFromSet", "[", "1", "]", ")", "{", "foundView", "=", "true", ";", "}", "}", "if", "(", "!", "foundView", ")", "{", "allWebElements", ".", "add", "(", "textFromScreen", ")", ";", "}", "}", "}" ]
Adds views to a given list. @param allWebElements the list of all views @param webTextViewsOnScreen the list of views shown on screen
[ "Adds", "views", "to", "a", "given", "list", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Searcher.java#L250-L272
alkacon/opencms-core
src/org/opencms/ui/login/CmsForgotPasswordDialog.java
CmsForgotPasswordDialog.sendPasswordResetLink
public static boolean sendPasswordResetLink(CmsObject cms, String fullUserName, String email) { """ Tries to find a user with the given email address, and if one is found, sends a mail with the password reset link to them.<p> @param cms the CMS Context @param fullUserName the full user name including OU @param email the email address entered by the user @return true if the mail could be sent """ LOG.info("Trying to find user for email " + email); email = email.trim(); try { CmsUser foundUser = null; try { foundUser = cms.readUser(fullUserName); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } if ((foundUser == null) || CmsStringUtil.isEmptyOrWhitespaceOnly(email) || !email.equals(foundUser.getEmail()) || foundUser.isManaged() || foundUser.isWebuser()) { Notification.show( CmsVaadinUtils.getMessageText(Messages.GUI_PWCHANGE_EMAIL_MISMATCH_0), Type.ERROR_MESSAGE); return false; } long now = System.currentTimeMillis(); long expiration = OpenCms.getLoginManager().getTokenLifetime() + now; String expirationStr = CmsVfsService.formatDateTime(cms, expiration); String token = CmsTokenValidator.createToken(cms, foundUser, now); String link = OpenCms.getLinkManager().getWorkplaceLink(cms, CmsWorkplaceLoginHandler.LOGIN_HANDLER, false) + "?at=" + token; LOG.info("Sending password reset link to user " + foundUser.getName() + ": " + link); CmsPasswordChangeNotification notification = new CmsPasswordChangeNotification( cms, foundUser, link, expirationStr); try { notification.send(); } catch (EmailException e) { Notification.show( Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_PWCHANGE_MAIL_SEND_ERROR_0), Type.ERROR_MESSAGE); LOG.error(e.getLocalizedMessage(), e); return false; } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); Notification.show(e.getLocalizedMessage(), Type.ERROR_MESSAGE); return false; } return true; }
java
public static boolean sendPasswordResetLink(CmsObject cms, String fullUserName, String email) { LOG.info("Trying to find user for email " + email); email = email.trim(); try { CmsUser foundUser = null; try { foundUser = cms.readUser(fullUserName); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } if ((foundUser == null) || CmsStringUtil.isEmptyOrWhitespaceOnly(email) || !email.equals(foundUser.getEmail()) || foundUser.isManaged() || foundUser.isWebuser()) { Notification.show( CmsVaadinUtils.getMessageText(Messages.GUI_PWCHANGE_EMAIL_MISMATCH_0), Type.ERROR_MESSAGE); return false; } long now = System.currentTimeMillis(); long expiration = OpenCms.getLoginManager().getTokenLifetime() + now; String expirationStr = CmsVfsService.formatDateTime(cms, expiration); String token = CmsTokenValidator.createToken(cms, foundUser, now); String link = OpenCms.getLinkManager().getWorkplaceLink(cms, CmsWorkplaceLoginHandler.LOGIN_HANDLER, false) + "?at=" + token; LOG.info("Sending password reset link to user " + foundUser.getName() + ": " + link); CmsPasswordChangeNotification notification = new CmsPasswordChangeNotification( cms, foundUser, link, expirationStr); try { notification.send(); } catch (EmailException e) { Notification.show( Messages.get().getBundle(A_CmsUI.get().getLocale()).key(Messages.GUI_PWCHANGE_MAIL_SEND_ERROR_0), Type.ERROR_MESSAGE); LOG.error(e.getLocalizedMessage(), e); return false; } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); Notification.show(e.getLocalizedMessage(), Type.ERROR_MESSAGE); return false; } return true; }
[ "public", "static", "boolean", "sendPasswordResetLink", "(", "CmsObject", "cms", ",", "String", "fullUserName", ",", "String", "email", ")", "{", "LOG", ".", "info", "(", "\"Trying to find user for email \"", "+", "email", ")", ";", "email", "=", "email", ".", "trim", "(", ")", ";", "try", "{", "CmsUser", "foundUser", "=", "null", ";", "try", "{", "foundUser", "=", "cms", ".", "readUser", "(", "fullUserName", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "}", "if", "(", "(", "foundUser", "==", "null", ")", "||", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "email", ")", "||", "!", "email", ".", "equals", "(", "foundUser", ".", "getEmail", "(", ")", ")", "||", "foundUser", ".", "isManaged", "(", ")", "||", "foundUser", ".", "isWebuser", "(", ")", ")", "{", "Notification", ".", "show", "(", "CmsVaadinUtils", ".", "getMessageText", "(", "Messages", ".", "GUI_PWCHANGE_EMAIL_MISMATCH_0", ")", ",", "Type", ".", "ERROR_MESSAGE", ")", ";", "return", "false", ";", "}", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "expiration", "=", "OpenCms", ".", "getLoginManager", "(", ")", ".", "getTokenLifetime", "(", ")", "+", "now", ";", "String", "expirationStr", "=", "CmsVfsService", ".", "formatDateTime", "(", "cms", ",", "expiration", ")", ";", "String", "token", "=", "CmsTokenValidator", ".", "createToken", "(", "cms", ",", "foundUser", ",", "now", ")", ";", "String", "link", "=", "OpenCms", ".", "getLinkManager", "(", ")", ".", "getWorkplaceLink", "(", "cms", ",", "CmsWorkplaceLoginHandler", ".", "LOGIN_HANDLER", ",", "false", ")", "+", "\"?at=\"", "+", "token", ";", "LOG", ".", "info", "(", "\"Sending password reset link to user \"", "+", "foundUser", ".", "getName", "(", ")", "+", "\": \"", "+", "link", ")", ";", "CmsPasswordChangeNotification", "notification", "=", "new", "CmsPasswordChangeNotification", "(", "cms", ",", "foundUser", ",", "link", ",", "expirationStr", ")", ";", "try", "{", "notification", ".", "send", "(", ")", ";", "}", "catch", "(", "EmailException", "e", ")", "{", "Notification", ".", "show", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", "A_CmsUI", ".", "get", "(", ")", ".", "getLocale", "(", ")", ")", ".", "key", "(", "Messages", ".", "GUI_PWCHANGE_MAIL_SEND_ERROR_0", ")", ",", "Type", ".", "ERROR_MESSAGE", ")", ";", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "return", "false", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "Notification", ".", "show", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "Type", ".", "ERROR_MESSAGE", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Tries to find a user with the given email address, and if one is found, sends a mail with the password reset link to them.<p> @param cms the CMS Context @param fullUserName the full user name including OU @param email the email address entered by the user @return true if the mail could be sent
[ "Tries", "to", "find", "a", "user", "with", "the", "given", "email", "address", "and", "if", "one", "is", "found", "sends", "a", "mail", "with", "the", "password", "reset", "link", "to", "them", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/login/CmsForgotPasswordDialog.java#L171-L222
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java
RepositoryApplicationConfiguration.autoCleanupScheduler
@Bean @ConditionalOnMissingBean @Profile("!test") @ConditionalOnProperty(prefix = "hawkbit.autocleanup.scheduler", name = "enabled", matchIfMissing = true) AutoCleanupScheduler autoCleanupScheduler(final SystemManagement systemManagement, final SystemSecurityContext systemSecurityContext, final LockRegistry lockRegistry, final List<CleanupTask> cleanupTasks) { """ {@link AutoCleanupScheduler} bean. @param systemManagement to find all tenants @param systemSecurityContext to run as system @param lockRegistry to lock the tenant for auto assignment @param cleanupTasks a list of cleanup tasks @return a new {@link AutoCleanupScheduler} bean """ return new AutoCleanupScheduler(systemManagement, systemSecurityContext, lockRegistry, cleanupTasks); }
java
@Bean @ConditionalOnMissingBean @Profile("!test") @ConditionalOnProperty(prefix = "hawkbit.autocleanup.scheduler", name = "enabled", matchIfMissing = true) AutoCleanupScheduler autoCleanupScheduler(final SystemManagement systemManagement, final SystemSecurityContext systemSecurityContext, final LockRegistry lockRegistry, final List<CleanupTask> cleanupTasks) { return new AutoCleanupScheduler(systemManagement, systemSecurityContext, lockRegistry, cleanupTasks); }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "@", "Profile", "(", "\"!test\"", ")", "@", "ConditionalOnProperty", "(", "prefix", "=", "\"hawkbit.autocleanup.scheduler\"", ",", "name", "=", "\"enabled\"", ",", "matchIfMissing", "=", "true", ")", "AutoCleanupScheduler", "autoCleanupScheduler", "(", "final", "SystemManagement", "systemManagement", ",", "final", "SystemSecurityContext", "systemSecurityContext", ",", "final", "LockRegistry", "lockRegistry", ",", "final", "List", "<", "CleanupTask", ">", "cleanupTasks", ")", "{", "return", "new", "AutoCleanupScheduler", "(", "systemManagement", ",", "systemSecurityContext", ",", "lockRegistry", ",", "cleanupTasks", ")", ";", "}" ]
{@link AutoCleanupScheduler} bean. @param systemManagement to find all tenants @param systemSecurityContext to run as system @param lockRegistry to lock the tenant for auto assignment @param cleanupTasks a list of cleanup tasks @return a new {@link AutoCleanupScheduler} bean
[ "{", "@link", "AutoCleanupScheduler", "}", "bean", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java#L825-L833
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateDevEndpointResult.java
CreateDevEndpointResult.withArguments
public CreateDevEndpointResult withArguments(java.util.Map<String, String> arguments) { """ <p> The map of arguments used to configure this DevEndpoint. </p> @param arguments The map of arguments used to configure this DevEndpoint. @return Returns a reference to this object so that method calls can be chained together. """ setArguments(arguments); return this; }
java
public CreateDevEndpointResult withArguments(java.util.Map<String, String> arguments) { setArguments(arguments); return this; }
[ "public", "CreateDevEndpointResult", "withArguments", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "arguments", ")", "{", "setArguments", "(", "arguments", ")", ";", "return", "this", ";", "}" ]
<p> The map of arguments used to configure this DevEndpoint. </p> @param arguments The map of arguments used to configure this DevEndpoint. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "map", "of", "arguments", "used", "to", "configure", "this", "DevEndpoint", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateDevEndpointResult.java#L788-L791
eobermuhlner/big-math
ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java
BigDecimalMath.roundWithTrailingZeroes
public static BigDecimal roundWithTrailingZeroes(BigDecimal value, MathContext mathContext) { """ Rounds the specified {@link BigDecimal} to the precision of the specified {@link MathContext} including trailing zeroes. <p>This method is similar to {@link BigDecimal#round(MathContext)} but does <strong>not</strong> remove the trailing zeroes.</p> <p>Example:</p> <pre> MathContext mc = new MathContext(5); System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.234567"), mc)); // 1.2346 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("123.4567"), mc)); // 123.46 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.001234567"), mc)); // 0.0012346 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.23"), mc)); // 1.2300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.230000"), mc)); // 1.2300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00123"), mc)); // 0.0012300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0"), mc)); // 0.0000 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00000000"), mc)); // 0.0000 </pre> @param value the {@link BigDecimal} to round @param mathContext the {@link MathContext} used for the result @return the rounded {@link BigDecimal} value including trailing zeroes @see BigDecimal#round(MathContext) @see BigDecimalMath#round(BigDecimal, MathContext) """ if (value.precision() == mathContext.getPrecision()) { return value; } if (value.signum() == 0) { return BigDecimal.ZERO.setScale(mathContext.getPrecision() - 1); } try { BigDecimal stripped = value.stripTrailingZeros(); int exponentStripped = exponent(stripped); // value.precision() - value.scale() - 1; BigDecimal zero; if (exponentStripped < -1) { zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() - exponentStripped); } else { zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() + exponentStripped + 1); } return stripped.add(zero, mathContext); } catch (ArithmeticException ex) { return value.round(mathContext); } }
java
public static BigDecimal roundWithTrailingZeroes(BigDecimal value, MathContext mathContext) { if (value.precision() == mathContext.getPrecision()) { return value; } if (value.signum() == 0) { return BigDecimal.ZERO.setScale(mathContext.getPrecision() - 1); } try { BigDecimal stripped = value.stripTrailingZeros(); int exponentStripped = exponent(stripped); // value.precision() - value.scale() - 1; BigDecimal zero; if (exponentStripped < -1) { zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() - exponentStripped); } else { zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() + exponentStripped + 1); } return stripped.add(zero, mathContext); } catch (ArithmeticException ex) { return value.round(mathContext); } }
[ "public", "static", "BigDecimal", "roundWithTrailingZeroes", "(", "BigDecimal", "value", ",", "MathContext", "mathContext", ")", "{", "if", "(", "value", ".", "precision", "(", ")", "==", "mathContext", ".", "getPrecision", "(", ")", ")", "{", "return", "value", ";", "}", "if", "(", "value", ".", "signum", "(", ")", "==", "0", ")", "{", "return", "BigDecimal", ".", "ZERO", ".", "setScale", "(", "mathContext", ".", "getPrecision", "(", ")", "-", "1", ")", ";", "}", "try", "{", "BigDecimal", "stripped", "=", "value", ".", "stripTrailingZeros", "(", ")", ";", "int", "exponentStripped", "=", "exponent", "(", "stripped", ")", ";", "// value.precision() - value.scale() - 1;", "BigDecimal", "zero", ";", "if", "(", "exponentStripped", "<", "-", "1", ")", "{", "zero", "=", "BigDecimal", ".", "ZERO", ".", "setScale", "(", "mathContext", ".", "getPrecision", "(", ")", "-", "exponentStripped", ")", ";", "}", "else", "{", "zero", "=", "BigDecimal", ".", "ZERO", ".", "setScale", "(", "mathContext", ".", "getPrecision", "(", ")", "+", "exponentStripped", "+", "1", ")", ";", "}", "return", "stripped", ".", "add", "(", "zero", ",", "mathContext", ")", ";", "}", "catch", "(", "ArithmeticException", "ex", ")", "{", "return", "value", ".", "round", "(", "mathContext", ")", ";", "}", "}" ]
Rounds the specified {@link BigDecimal} to the precision of the specified {@link MathContext} including trailing zeroes. <p>This method is similar to {@link BigDecimal#round(MathContext)} but does <strong>not</strong> remove the trailing zeroes.</p> <p>Example:</p> <pre> MathContext mc = new MathContext(5); System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.234567"), mc)); // 1.2346 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("123.4567"), mc)); // 123.46 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.001234567"), mc)); // 0.0012346 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.23"), mc)); // 1.2300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.230000"), mc)); // 1.2300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00123"), mc)); // 0.0012300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0"), mc)); // 0.0000 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00000000"), mc)); // 0.0000 </pre> @param value the {@link BigDecimal} to round @param mathContext the {@link MathContext} used for the result @return the rounded {@link BigDecimal} value including trailing zeroes @see BigDecimal#round(MathContext) @see BigDecimalMath#round(BigDecimal, MathContext)
[ "Rounds", "the", "specified", "{", "@link", "BigDecimal", "}", "to", "the", "precision", "of", "the", "specified", "{", "@link", "MathContext", "}", "including", "trailing", "zeroes", "." ]
train
https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java#L428-L450
citrusframework/citrus
modules/citrus-websocket/src/main/java/com/consol/citrus/websocket/handler/WebSocketUrlHandlerMapping.java
WebSocketUrlHandlerMapping.postRegisterUrlHandlers
public void postRegisterUrlHandlers(Map<String, Object> wsHandlers) { """ Workaround for registering the WebSocket request handlers, after the spring context has been initialised. @param wsHandlers """ registerHandlers(wsHandlers); for (Object handler : wsHandlers.values()) { if (handler instanceof Lifecycle) { ((Lifecycle) handler).start(); } } }
java
public void postRegisterUrlHandlers(Map<String, Object> wsHandlers) { registerHandlers(wsHandlers); for (Object handler : wsHandlers.values()) { if (handler instanceof Lifecycle) { ((Lifecycle) handler).start(); } } }
[ "public", "void", "postRegisterUrlHandlers", "(", "Map", "<", "String", ",", "Object", ">", "wsHandlers", ")", "{", "registerHandlers", "(", "wsHandlers", ")", ";", "for", "(", "Object", "handler", ":", "wsHandlers", ".", "values", "(", ")", ")", "{", "if", "(", "handler", "instanceof", "Lifecycle", ")", "{", "(", "(", "Lifecycle", ")", "handler", ")", ".", "start", "(", ")", ";", "}", "}", "}" ]
Workaround for registering the WebSocket request handlers, after the spring context has been initialised. @param wsHandlers
[ "Workaround", "for", "registering", "the", "WebSocket", "request", "handlers", "after", "the", "spring", "context", "has", "been", "initialised", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-websocket/src/main/java/com/consol/citrus/websocket/handler/WebSocketUrlHandlerMapping.java#L36-L44
iig-uni-freiburg/SEWOL
ext/org/deckfour/xes/info/XGlobalAttributeNameMap.java
XGlobalAttributeNameMap.mapSafely
public String mapSafely(XAttribute attribute, String mappingName) { """ Maps an attribute safely, using the given attribute mapping. Safe mapping attempts to map the attribute using the given mapping first. If this does not succeed, the standard mapping (EN) will be used for mapping. If no mapping is available in the standard mapping, the original attribute key is returned unchanged. This way, it is always ensured that this method returns a valid string for naming attributes. @param attribute Attribute to map. @param mappingName Name of the mapping to be used preferably. @return The safe mapping for the given attribute. """ return mapSafely(attribute, mappings.get(mappingName)); }
java
public String mapSafely(XAttribute attribute, String mappingName) { return mapSafely(attribute, mappings.get(mappingName)); }
[ "public", "String", "mapSafely", "(", "XAttribute", "attribute", ",", "String", "mappingName", ")", "{", "return", "mapSafely", "(", "attribute", ",", "mappings", ".", "get", "(", "mappingName", ")", ")", ";", "}" ]
Maps an attribute safely, using the given attribute mapping. Safe mapping attempts to map the attribute using the given mapping first. If this does not succeed, the standard mapping (EN) will be used for mapping. If no mapping is available in the standard mapping, the original attribute key is returned unchanged. This way, it is always ensured that this method returns a valid string for naming attributes. @param attribute Attribute to map. @param mappingName Name of the mapping to be used preferably. @return The safe mapping for the given attribute.
[ "Maps", "an", "attribute", "safely", "using", "the", "given", "attribute", "mapping", ".", "Safe", "mapping", "attempts", "to", "map", "the", "attribute", "using", "the", "given", "mapping", "first", ".", "If", "this", "does", "not", "succeed", "the", "standard", "mapping", "(", "EN", ")", "will", "be", "used", "for", "mapping", ".", "If", "no", "mapping", "is", "available", "in", "the", "standard", "mapping", "the", "original", "attribute", "key", "is", "returned", "unchanged", ".", "This", "way", "it", "is", "always", "ensured", "that", "this", "method", "returns", "a", "valid", "string", "for", "naming", "attributes", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/info/XGlobalAttributeNameMap.java#L242-L244
jenkinsci/jenkins
core/src/main/java/jenkins/model/Jenkins.java
Jenkins.doQuietDown
@RequirePOST public HttpRedirect doQuietDown(@QueryParameter boolean block, @QueryParameter int timeout) throws InterruptedException, IOException { """ Quiet down Jenkins - preparation for a restart @param block Block until the system really quiets down and no builds are running @param timeout If non-zero, only block up to the specified number of milliseconds """ synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { long waitUntil = timeout; if (timeout > 0) waitUntil += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < waitUntil) && !RestartListener.isAllReady()) { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } } return new HttpRedirect("."); }
java
@RequirePOST public HttpRedirect doQuietDown(@QueryParameter boolean block, @QueryParameter int timeout) throws InterruptedException, IOException { synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { long waitUntil = timeout; if (timeout > 0) waitUntil += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < waitUntil) && !RestartListener.isAllReady()) { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } } return new HttpRedirect("."); }
[ "@", "RequirePOST", "public", "HttpRedirect", "doQuietDown", "(", "@", "QueryParameter", "boolean", "block", ",", "@", "QueryParameter", "int", "timeout", ")", "throws", "InterruptedException", ",", "IOException", "{", "synchronized", "(", "this", ")", "{", "checkPermission", "(", "ADMINISTER", ")", ";", "isQuietingDown", "=", "true", ";", "}", "if", "(", "block", ")", "{", "long", "waitUntil", "=", "timeout", ";", "if", "(", "timeout", ">", "0", ")", "waitUntil", "+=", "System", ".", "currentTimeMillis", "(", ")", ";", "while", "(", "isQuietingDown", "&&", "(", "timeout", "<=", "0", "||", "System", ".", "currentTimeMillis", "(", ")", "<", "waitUntil", ")", "&&", "!", "RestartListener", ".", "isAllReady", "(", ")", ")", "{", "Thread", ".", "sleep", "(", "TimeUnit", ".", "SECONDS", ".", "toMillis", "(", "1", ")", ")", ";", "}", "}", "return", "new", "HttpRedirect", "(", "\".\"", ")", ";", "}" ]
Quiet down Jenkins - preparation for a restart @param block Block until the system really quiets down and no builds are running @param timeout If non-zero, only block up to the specified number of milliseconds
[ "Quiet", "down", "Jenkins", "-", "preparation", "for", "a", "restart" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/Jenkins.java#L3818-L3834
calimero-project/calimero-core
src/tuwien/auto/calimero/mgmt/LocalDeviceManagementUsb.java
LocalDeviceManagementUsb.getProperty
public byte[] getProperty(final int objectType, final int objectInstance, final int propertyId, final int start, final int elements) throws KNXTimeoutException, KNXRemoteException, KNXPortClosedException, InterruptedException { """ Gets property value elements of an interface object property. @param objectType the interface object type @param objectInstance the interface object instance (usually 1) @param propertyId the property identifier (PID) @param start start index in the property value to start writing to @param elements number of elements to set @return byte array containing the property element data @throws KNXTimeoutException on timeout setting the property elements @throws KNXRemoteException on remote error or invalid response @throws KNXPortClosedException if adapter is closed @throws InterruptedException on interrupt """ final CEMIDevMgmt req = new CEMIDevMgmt(CEMIDevMgmt.MC_PROPREAD_REQ, objectType, objectInstance, propertyId, start, elements); send(req, null); return findFrame(CEMIDevMgmt.MC_PROPREAD_CON, req); }
java
public byte[] getProperty(final int objectType, final int objectInstance, final int propertyId, final int start, final int elements) throws KNXTimeoutException, KNXRemoteException, KNXPortClosedException, InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt(CEMIDevMgmt.MC_PROPREAD_REQ, objectType, objectInstance, propertyId, start, elements); send(req, null); return findFrame(CEMIDevMgmt.MC_PROPREAD_CON, req); }
[ "public", "byte", "[", "]", "getProperty", "(", "final", "int", "objectType", ",", "final", "int", "objectInstance", ",", "final", "int", "propertyId", ",", "final", "int", "start", ",", "final", "int", "elements", ")", "throws", "KNXTimeoutException", ",", "KNXRemoteException", ",", "KNXPortClosedException", ",", "InterruptedException", "{", "final", "CEMIDevMgmt", "req", "=", "new", "CEMIDevMgmt", "(", "CEMIDevMgmt", ".", "MC_PROPREAD_REQ", ",", "objectType", ",", "objectInstance", ",", "propertyId", ",", "start", ",", "elements", ")", ";", "send", "(", "req", ",", "null", ")", ";", "return", "findFrame", "(", "CEMIDevMgmt", ".", "MC_PROPREAD_CON", ",", "req", ")", ";", "}" ]
Gets property value elements of an interface object property. @param objectType the interface object type @param objectInstance the interface object instance (usually 1) @param propertyId the property identifier (PID) @param start start index in the property value to start writing to @param elements number of elements to set @return byte array containing the property element data @throws KNXTimeoutException on timeout setting the property elements @throws KNXRemoteException on remote error or invalid response @throws KNXPortClosedException if adapter is closed @throws InterruptedException on interrupt
[ "Gets", "property", "value", "elements", "of", "an", "interface", "object", "property", "." ]
train
https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/mgmt/LocalDeviceManagementUsb.java#L146-L154
buschmais/jqa-maven3-plugin
src/main/java/com/buschmais/jqassistant/plugin/maven3/api/artifact/MavenArtifactHelper.java
MavenArtifactHelper.setCoordinates
public static void setCoordinates(MavenArtifactDescriptor artifactDescriptor, Coordinates coordinates) { """ Apply the given coordinates to an artifact descriptor. @param artifactDescriptor The artifact descriptor. @param coordinates The coordinates. """ artifactDescriptor.setGroup(coordinates.getGroup()); artifactDescriptor.setName(coordinates.getName()); artifactDescriptor.setVersion(coordinates.getVersion()); artifactDescriptor.setClassifier(coordinates.getClassifier()); artifactDescriptor.setType(coordinates.getType()); }
java
public static void setCoordinates(MavenArtifactDescriptor artifactDescriptor, Coordinates coordinates) { artifactDescriptor.setGroup(coordinates.getGroup()); artifactDescriptor.setName(coordinates.getName()); artifactDescriptor.setVersion(coordinates.getVersion()); artifactDescriptor.setClassifier(coordinates.getClassifier()); artifactDescriptor.setType(coordinates.getType()); }
[ "public", "static", "void", "setCoordinates", "(", "MavenArtifactDescriptor", "artifactDescriptor", ",", "Coordinates", "coordinates", ")", "{", "artifactDescriptor", ".", "setGroup", "(", "coordinates", ".", "getGroup", "(", ")", ")", ";", "artifactDescriptor", ".", "setName", "(", "coordinates", ".", "getName", "(", ")", ")", ";", "artifactDescriptor", ".", "setVersion", "(", "coordinates", ".", "getVersion", "(", ")", ")", ";", "artifactDescriptor", ".", "setClassifier", "(", "coordinates", ".", "getClassifier", "(", ")", ")", ";", "artifactDescriptor", ".", "setType", "(", "coordinates", ".", "getType", "(", ")", ")", ";", "}" ]
Apply the given coordinates to an artifact descriptor. @param artifactDescriptor The artifact descriptor. @param coordinates The coordinates.
[ "Apply", "the", "given", "coordinates", "to", "an", "artifact", "descriptor", "." ]
train
https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/api/artifact/MavenArtifactHelper.java#L29-L35
sniffy/sniffy
sniffy-core/src/main/java/io/sniffy/LegacySpy.java
LegacySpy.expectAtMostOnce
@Deprecated public C expectAtMostOnce(Threads threadMatcher, Query query) { """ Alias for {@link #expectBetween(int, int, Threads, Query)} with arguments 0, 1, {@code threads}, {@code queryType} @since 2.2 """ return expect(SqlQueries.atMostOneQuery().threads(threadMatcher).type(adapter(query))); }
java
@Deprecated public C expectAtMostOnce(Threads threadMatcher, Query query) { return expect(SqlQueries.atMostOneQuery().threads(threadMatcher).type(adapter(query))); }
[ "@", "Deprecated", "public", "C", "expectAtMostOnce", "(", "Threads", "threadMatcher", ",", "Query", "query", ")", "{", "return", "expect", "(", "SqlQueries", ".", "atMostOneQuery", "(", ")", ".", "threads", "(", "threadMatcher", ")", ".", "type", "(", "adapter", "(", "query", ")", ")", ")", ";", "}" ]
Alias for {@link #expectBetween(int, int, Threads, Query)} with arguments 0, 1, {@code threads}, {@code queryType} @since 2.2
[ "Alias", "for", "{" ]
train
https://github.com/sniffy/sniffy/blob/7bdddb9593e6b6e9fe5c7c87519f864acbc3a5c0/sniffy-core/src/main/java/io/sniffy/LegacySpy.java#L244-L247
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/ArtFinder.java
ArtFinder.requestArtworkFrom
public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) { """ Ask the specified player for the specified artwork from the specified media slot, first checking if we have a cached copy. @param artReference uniquely identifies the desired artwork @param trackType the kind of track that owns the artwork @return the artwork, if it was found, or {@code null} @throws IllegalStateException if the ArtFinder is not running """ ensureRunning(); AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches. if (artwork == null) { artwork = requestArtworkInternal(artReference, trackType, false); } return artwork; }
java
public AlbumArt requestArtworkFrom(final DataReference artReference, final CdjStatus.TrackType trackType) { ensureRunning(); AlbumArt artwork = findArtInMemoryCaches(artReference); // First check the in-memory artwork caches. if (artwork == null) { artwork = requestArtworkInternal(artReference, trackType, false); } return artwork; }
[ "public", "AlbumArt", "requestArtworkFrom", "(", "final", "DataReference", "artReference", ",", "final", "CdjStatus", ".", "TrackType", "trackType", ")", "{", "ensureRunning", "(", ")", ";", "AlbumArt", "artwork", "=", "findArtInMemoryCaches", "(", "artReference", ")", ";", "// First check the in-memory artwork caches.", "if", "(", "artwork", "==", "null", ")", "{", "artwork", "=", "requestArtworkInternal", "(", "artReference", ",", "trackType", ",", "false", ")", ";", "}", "return", "artwork", ";", "}" ]
Ask the specified player for the specified artwork from the specified media slot, first checking if we have a cached copy. @param artReference uniquely identifies the desired artwork @param trackType the kind of track that owns the artwork @return the artwork, if it was found, or {@code null} @throws IllegalStateException if the ArtFinder is not running
[ "Ask", "the", "specified", "player", "for", "the", "specified", "artwork", "from", "the", "specified", "media", "slot", "first", "checking", "if", "we", "have", "a", "cached", "copy", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/ArtFinder.java#L339-L346
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/responder/responderpolicylabel_binding.java
responderpolicylabel_binding.get
public static responderpolicylabel_binding get(nitro_service service, String labelname) throws Exception { """ Use this API to fetch responderpolicylabel_binding resource of given name . """ responderpolicylabel_binding obj = new responderpolicylabel_binding(); obj.set_labelname(labelname); responderpolicylabel_binding response = (responderpolicylabel_binding) obj.get_resource(service); return response; }
java
public static responderpolicylabel_binding get(nitro_service service, String labelname) throws Exception{ responderpolicylabel_binding obj = new responderpolicylabel_binding(); obj.set_labelname(labelname); responderpolicylabel_binding response = (responderpolicylabel_binding) obj.get_resource(service); return response; }
[ "public", "static", "responderpolicylabel_binding", "get", "(", "nitro_service", "service", ",", "String", "labelname", ")", "throws", "Exception", "{", "responderpolicylabel_binding", "obj", "=", "new", "responderpolicylabel_binding", "(", ")", ";", "obj", ".", "set_labelname", "(", "labelname", ")", ";", "responderpolicylabel_binding", "response", "=", "(", "responderpolicylabel_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch responderpolicylabel_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "responderpolicylabel_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/responder/responderpolicylabel_binding.java#L114-L119
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/ReflectApiUtil.java
ReflectApiUtil.newInstance
public static <T> T newInstance(final Class<T> klazz) { """ Create class instance through default constructor call @param klazz class to be instantiated, must not be null @param <T> type of the class @return instance of class, must not be null """ try { return klazz.getConstructor().newInstance(); } catch (Exception ex) { throw new Error(String.format("Can't create instance of %s for error %s", klazz.getCanonicalName(), ex.getMessage()), ex); } }
java
public static <T> T newInstance(final Class<T> klazz) { try { return klazz.getConstructor().newInstance(); } catch (Exception ex) { throw new Error(String.format("Can't create instance of %s for error %s", klazz.getCanonicalName(), ex.getMessage()), ex); } }
[ "public", "static", "<", "T", ">", "T", "newInstance", "(", "final", "Class", "<", "T", ">", "klazz", ")", "{", "try", "{", "return", "klazz", ".", "getConstructor", "(", ")", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "Error", "(", "String", ".", "format", "(", "\"Can't create instance of %s for error %s\"", ",", "klazz", ".", "getCanonicalName", "(", ")", ",", "ex", ".", "getMessage", "(", ")", ")", ",", "ex", ")", ";", "}", "}" ]
Create class instance through default constructor call @param klazz class to be instantiated, must not be null @param <T> type of the class @return instance of class, must not be null
[ "Create", "class", "instance", "through", "default", "constructor", "call" ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/ReflectApiUtil.java#L53-L59
groupon/odo
browsermob-proxy/src/main/java/com/groupon/odo/bmp/KeyStoreManager.java
KeyStoreManager.addCertAndPrivateKey
public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey) throws KeyStoreException, CertificateException, NoSuchAlgorithmException { """ Stores a new certificate and its associated private key in the keystore. @param hostname @param cert @param privKey @throws KeyStoreException @throws CertificateException @throws NoSuchAlgorithmException """ // String alias = ThumbprintUtil.getThumbprint(cert); _ks.deleteEntry(hostname); _ks.setCertificateEntry(hostname, cert); _ks.setKeyEntry(hostname, privKey, _keypassword, new java.security.cert.Certificate[] {cert}); if(persistImmediately) { persist(); } }
java
public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey) throws KeyStoreException, CertificateException, NoSuchAlgorithmException { // String alias = ThumbprintUtil.getThumbprint(cert); _ks.deleteEntry(hostname); _ks.setCertificateEntry(hostname, cert); _ks.setKeyEntry(hostname, privKey, _keypassword, new java.security.cert.Certificate[] {cert}); if(persistImmediately) { persist(); } }
[ "public", "synchronized", "void", "addCertAndPrivateKey", "(", "String", "hostname", ",", "final", "X509Certificate", "cert", ",", "final", "PrivateKey", "privKey", ")", "throws", "KeyStoreException", ",", "CertificateException", ",", "NoSuchAlgorithmException", "{", "//\t\tString alias = ThumbprintUtil.getThumbprint(cert);", "_ks", ".", "deleteEntry", "(", "hostname", ")", ";", "_ks", ".", "setCertificateEntry", "(", "hostname", ",", "cert", ")", ";", "_ks", ".", "setKeyEntry", "(", "hostname", ",", "privKey", ",", "_keypassword", ",", "new", "java", ".", "security", ".", "cert", ".", "Certificate", "[", "]", "{", "cert", "}", ")", ";", "if", "(", "persistImmediately", ")", "{", "persist", "(", ")", ";", "}", "}" ]
Stores a new certificate and its associated private key in the keystore. @param hostname @param cert @param privKey @throws KeyStoreException @throws CertificateException @throws NoSuchAlgorithmException
[ "Stores", "a", "new", "certificate", "and", "its", "associated", "private", "key", "in", "the", "keystore", "." ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/browsermob-proxy/src/main/java/com/groupon/odo/bmp/KeyStoreManager.java#L547-L562
apache/flink
flink-core/src/main/java/org/apache/flink/types/Record.java
Record.getFieldsIntoCheckingNull
public void getFieldsIntoCheckingNull(int[] positions, Value[] targets) { """ Gets the fields at the given positions into an array. If at any position a field is null, then this method throws a @link NullKeyFieldException. All fields that have been successfully read until the failing read are correctly contained in the record. All other fields are not set. @param positions The positions of the fields to get. @param targets The values into which the content of the fields is put. @throws NullKeyFieldException in case of a failing field read. """ for (int i = 0; i < positions.length; i++) { if (!getFieldInto(positions[i], targets[i])) { throw new NullKeyFieldException(i); } } }
java
public void getFieldsIntoCheckingNull(int[] positions, Value[] targets) { for (int i = 0; i < positions.length; i++) { if (!getFieldInto(positions[i], targets[i])) { throw new NullKeyFieldException(i); } } }
[ "public", "void", "getFieldsIntoCheckingNull", "(", "int", "[", "]", "positions", ",", "Value", "[", "]", "targets", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "positions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "getFieldInto", "(", "positions", "[", "i", "]", ",", "targets", "[", "i", "]", ")", ")", "{", "throw", "new", "NullKeyFieldException", "(", "i", ")", ";", "}", "}", "}" ]
Gets the fields at the given positions into an array. If at any position a field is null, then this method throws a @link NullKeyFieldException. All fields that have been successfully read until the failing read are correctly contained in the record. All other fields are not set. @param positions The positions of the fields to get. @param targets The values into which the content of the fields is put. @throws NullKeyFieldException in case of a failing field read.
[ "Gets", "the", "fields", "at", "the", "given", "positions", "into", "an", "array", ".", "If", "at", "any", "position", "a", "field", "is", "null", "then", "this", "method", "throws", "a", "@link", "NullKeyFieldException", ".", "All", "fields", "that", "have", "been", "successfully", "read", "until", "the", "failing", "read", "are", "correctly", "contained", "in", "the", "record", ".", "All", "other", "fields", "are", "not", "set", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/Record.java#L357-L363
itfsw/QueryBuilder
src/main/java/com/itfsw/query/builder/support/utils/spring/NumberUtils.java
NumberUtils.checkedLongValue
private static long checkedLongValue(Number number, Class<? extends Number> targetClass) { """ Check for a {@code BigInteger}/{@code BigDecimal} long overflow before returning the given number as a long value. @param number the number to convert @param targetClass the target class to convert to @return the long value, if convertible without overflow @throws IllegalArgumentException if there is an overflow @see #raiseOverflowException """ BigInteger bigInt = null; if (number instanceof BigInteger) { bigInt = (BigInteger) number; } else if (number instanceof BigDecimal) { bigInt = ((BigDecimal) number).toBigInteger(); } // Effectively analogous to JDK 8's BigInteger.longValueExact() if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) { raiseOverflowException(number, targetClass); } return number.longValue(); }
java
private static long checkedLongValue(Number number, Class<? extends Number> targetClass) { BigInteger bigInt = null; if (number instanceof BigInteger) { bigInt = (BigInteger) number; } else if (number instanceof BigDecimal) { bigInt = ((BigDecimal) number).toBigInteger(); } // Effectively analogous to JDK 8's BigInteger.longValueExact() if (bigInt != null && (bigInt.compareTo(LONG_MIN) < 0 || bigInt.compareTo(LONG_MAX) > 0)) { raiseOverflowException(number, targetClass); } return number.longValue(); }
[ "private", "static", "long", "checkedLongValue", "(", "Number", "number", ",", "Class", "<", "?", "extends", "Number", ">", "targetClass", ")", "{", "BigInteger", "bigInt", "=", "null", ";", "if", "(", "number", "instanceof", "BigInteger", ")", "{", "bigInt", "=", "(", "BigInteger", ")", "number", ";", "}", "else", "if", "(", "number", "instanceof", "BigDecimal", ")", "{", "bigInt", "=", "(", "(", "BigDecimal", ")", "number", ")", ".", "toBigInteger", "(", ")", ";", "}", "// Effectively analogous to JDK 8's BigInteger.longValueExact()", "if", "(", "bigInt", "!=", "null", "&&", "(", "bigInt", ".", "compareTo", "(", "LONG_MIN", ")", "<", "0", "||", "bigInt", ".", "compareTo", "(", "LONG_MAX", ")", ">", "0", ")", ")", "{", "raiseOverflowException", "(", "number", ",", "targetClass", ")", ";", "}", "return", "number", ".", "longValue", "(", ")", ";", "}" ]
Check for a {@code BigInteger}/{@code BigDecimal} long overflow before returning the given number as a long value. @param number the number to convert @param targetClass the target class to convert to @return the long value, if convertible without overflow @throws IllegalArgumentException if there is an overflow @see #raiseOverflowException
[ "Check", "for", "a", "{" ]
train
https://github.com/itfsw/QueryBuilder/blob/231dc9a334d54cf98755cfcb236202201ddee162/src/main/java/com/itfsw/query/builder/support/utils/spring/NumberUtils.java#L139-L151
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/HTODDynacache.java
HTODDynacache.delCacheEntry
public void delCacheEntry(CacheEntry ce, int cause, int source, boolean fromDepIdTemplateInvalidation) { """ *********************************************************************** delCacheEntry() Delete cacheEntry from the disk. This also remove dependencies for all dataIds and templates to the cacheEntry *********************************************************************** """ this.invalidationBuffer.add(ce.id, HTODInvalidationBuffer.EXPLICIT_BUFFER, cause, source, fromDepIdTemplateInvalidation, !HTODInvalidationBuffer.FIRE_EVENT, !HTODInvalidationBuffer.ALIAS_ID); for (int i = 0; i < ce.aliasList.length; i++) { this.invalidationBuffer.add(ce.aliasList[i], HTODInvalidationBuffer.EXPLICIT_BUFFER, cause, source, fromDepIdTemplateInvalidation, !HTODInvalidationBuffer.FIRE_EVENT, HTODInvalidationBuffer.ALIAS_ID);; } }
java
public void delCacheEntry(CacheEntry ce, int cause, int source, boolean fromDepIdTemplateInvalidation) { this.invalidationBuffer.add(ce.id, HTODInvalidationBuffer.EXPLICIT_BUFFER, cause, source, fromDepIdTemplateInvalidation, !HTODInvalidationBuffer.FIRE_EVENT, !HTODInvalidationBuffer.ALIAS_ID); for (int i = 0; i < ce.aliasList.length; i++) { this.invalidationBuffer.add(ce.aliasList[i], HTODInvalidationBuffer.EXPLICIT_BUFFER, cause, source, fromDepIdTemplateInvalidation, !HTODInvalidationBuffer.FIRE_EVENT, HTODInvalidationBuffer.ALIAS_ID);; } }
[ "public", "void", "delCacheEntry", "(", "CacheEntry", "ce", ",", "int", "cause", ",", "int", "source", ",", "boolean", "fromDepIdTemplateInvalidation", ")", "{", "this", ".", "invalidationBuffer", ".", "add", "(", "ce", ".", "id", ",", "HTODInvalidationBuffer", ".", "EXPLICIT_BUFFER", ",", "cause", ",", "source", ",", "fromDepIdTemplateInvalidation", ",", "!", "HTODInvalidationBuffer", ".", "FIRE_EVENT", ",", "!", "HTODInvalidationBuffer", ".", "ALIAS_ID", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ce", ".", "aliasList", ".", "length", ";", "i", "++", ")", "{", "this", ".", "invalidationBuffer", ".", "add", "(", "ce", ".", "aliasList", "[", "i", "]", ",", "HTODInvalidationBuffer", ".", "EXPLICIT_BUFFER", ",", "cause", ",", "source", ",", "fromDepIdTemplateInvalidation", ",", "!", "HTODInvalidationBuffer", ".", "FIRE_EVENT", ",", "HTODInvalidationBuffer", ".", "ALIAS_ID", ")", ";", ";", "}", "}" ]
*********************************************************************** delCacheEntry() Delete cacheEntry from the disk. This also remove dependencies for all dataIds and templates to the cacheEntry ***********************************************************************
[ "***********************************************************************", "delCacheEntry", "()", "Delete", "cacheEntry", "from", "the", "disk", ".", "This", "also", "remove", "dependencies", "for", "all", "dataIds", "and", "templates", "to", "the", "cacheEntry", "***********************************************************************" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/HTODDynacache.java#L664-L671
sporniket/core
sporniket-core-io/src/main/java/com/sporniket/libre/io/FileTools.java
FileTools.loadResourceBundle
public static Map<String, String> loadResourceBundle(String bundleName, Encoding encoding, String newline) throws IOException, SyntaxErrorException, MissingResourceException { """ Load a properties file looking for localized versions like ResourceBundle, using the default Locale, supporting multiple line values. @param bundleName the bundle name, like <code>com.foo.MyBundle</code>. @param encoding the encoding of the bundle files. @param newline the sequence to use as a line separator for multiple line values. @return the properties, merged like a Java ResourceBundle. @throws IOException if there is a problem to deal with. @throws SyntaxErrorException if there is a problem to deal with. @throws MissingResourceException if no file at all is found. @see LineByLinePropertyParser @since 16.08.02 """ return loadResourceBundle(bundleName, encoding, newline, Locale.getDefault()); }
java
public static Map<String, String> loadResourceBundle(String bundleName, Encoding encoding, String newline) throws IOException, SyntaxErrorException, MissingResourceException { return loadResourceBundle(bundleName, encoding, newline, Locale.getDefault()); }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "loadResourceBundle", "(", "String", "bundleName", ",", "Encoding", "encoding", ",", "String", "newline", ")", "throws", "IOException", ",", "SyntaxErrorException", ",", "MissingResourceException", "{", "return", "loadResourceBundle", "(", "bundleName", ",", "encoding", ",", "newline", ",", "Locale", ".", "getDefault", "(", ")", ")", ";", "}" ]
Load a properties file looking for localized versions like ResourceBundle, using the default Locale, supporting multiple line values. @param bundleName the bundle name, like <code>com.foo.MyBundle</code>. @param encoding the encoding of the bundle files. @param newline the sequence to use as a line separator for multiple line values. @return the properties, merged like a Java ResourceBundle. @throws IOException if there is a problem to deal with. @throws SyntaxErrorException if there is a problem to deal with. @throws MissingResourceException if no file at all is found. @see LineByLinePropertyParser @since 16.08.02
[ "Load", "a", "properties", "file", "looking", "for", "localized", "versions", "like", "ResourceBundle", "using", "the", "default", "Locale", "supporting", "multiple", "line", "values", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/FileTools.java#L288-L292
fcrepo3/fcrepo
fcrepo-common/src/main/java/org/fcrepo/common/rdf/JRDF.java
JRDF.sameSubject
public static boolean sameSubject(SubjectNode s1, String s2) { """ Tells whether the given subjects are equivalent, with one given as a URI string. @param s1 first subject. @param s2 second subject, given as a URI string. @return true if equivalent, false otherwise. """ if (s1 instanceof URIReference) { return sameResource((URIReference) s1, s2); } else { return false; } }
java
public static boolean sameSubject(SubjectNode s1, String s2) { if (s1 instanceof URIReference) { return sameResource((URIReference) s1, s2); } else { return false; } }
[ "public", "static", "boolean", "sameSubject", "(", "SubjectNode", "s1", ",", "String", "s2", ")", "{", "if", "(", "s1", "instanceof", "URIReference", ")", "{", "return", "sameResource", "(", "(", "URIReference", ")", "s1", ",", "s2", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Tells whether the given subjects are equivalent, with one given as a URI string. @param s1 first subject. @param s2 second subject, given as a URI string. @return true if equivalent, false otherwise.
[ "Tells", "whether", "the", "given", "subjects", "are", "equivalent", "with", "one", "given", "as", "a", "URI", "string", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/common/rdf/JRDF.java#L151-L157
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MatchAllScorer.java
MatchAllScorer.calculateDocFilter
private void calculateDocFilter() throws IOException { """ Calculates a BitSet filter that includes all the nodes that have content in properties according to the field name passed in the constructor of this MatchAllScorer. @throws IOException if an error occurs while reading from the search index. """ PerQueryCache cache = PerQueryCache.getInstance(); @SuppressWarnings("unchecked") Map<String, BitSet> readerCache = (Map<String, BitSet>)cache.get(MatchAllScorer.class, reader); if (readerCache == null) { readerCache = new HashMap<String, BitSet>(); cache.put(MatchAllScorer.class, reader, readerCache); } // get BitSet for field docFilter = (BitSet)readerCache.get(field); if (docFilter != null) { // use cached BitSet; return; } // otherwise calculate new docFilter = new BitSet(reader.maxDoc()); // we match all terms String namedValue = FieldNames.createNamedValue(field, ""); TermEnum terms = reader.terms(new Term(FieldNames.PROPERTIES, namedValue)); try { TermDocs docs = reader.termDocs(); try { while (terms.term() != null && terms.term().field() == FieldNames.PROPERTIES && terms.term().text().startsWith(namedValue)) { docs.seek(terms); while (docs.next()) { docFilter.set(docs.doc()); } terms.next(); } } finally { docs.close(); } } finally { terms.close(); } // put BitSet into cache readerCache.put(field, docFilter); }
java
private void calculateDocFilter() throws IOException { PerQueryCache cache = PerQueryCache.getInstance(); @SuppressWarnings("unchecked") Map<String, BitSet> readerCache = (Map<String, BitSet>)cache.get(MatchAllScorer.class, reader); if (readerCache == null) { readerCache = new HashMap<String, BitSet>(); cache.put(MatchAllScorer.class, reader, readerCache); } // get BitSet for field docFilter = (BitSet)readerCache.get(field); if (docFilter != null) { // use cached BitSet; return; } // otherwise calculate new docFilter = new BitSet(reader.maxDoc()); // we match all terms String namedValue = FieldNames.createNamedValue(field, ""); TermEnum terms = reader.terms(new Term(FieldNames.PROPERTIES, namedValue)); try { TermDocs docs = reader.termDocs(); try { while (terms.term() != null && terms.term().field() == FieldNames.PROPERTIES && terms.term().text().startsWith(namedValue)) { docs.seek(terms); while (docs.next()) { docFilter.set(docs.doc()); } terms.next(); } } finally { docs.close(); } } finally { terms.close(); } // put BitSet into cache readerCache.put(field, docFilter); }
[ "private", "void", "calculateDocFilter", "(", ")", "throws", "IOException", "{", "PerQueryCache", "cache", "=", "PerQueryCache", ".", "getInstance", "(", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Map", "<", "String", ",", "BitSet", ">", "readerCache", "=", "(", "Map", "<", "String", ",", "BitSet", ">", ")", "cache", ".", "get", "(", "MatchAllScorer", ".", "class", ",", "reader", ")", ";", "if", "(", "readerCache", "==", "null", ")", "{", "readerCache", "=", "new", "HashMap", "<", "String", ",", "BitSet", ">", "(", ")", ";", "cache", ".", "put", "(", "MatchAllScorer", ".", "class", ",", "reader", ",", "readerCache", ")", ";", "}", "// get BitSet for field", "docFilter", "=", "(", "BitSet", ")", "readerCache", ".", "get", "(", "field", ")", ";", "if", "(", "docFilter", "!=", "null", ")", "{", "// use cached BitSet;", "return", ";", "}", "// otherwise calculate new", "docFilter", "=", "new", "BitSet", "(", "reader", ".", "maxDoc", "(", ")", ")", ";", "// we match all terms", "String", "namedValue", "=", "FieldNames", ".", "createNamedValue", "(", "field", ",", "\"\"", ")", ";", "TermEnum", "terms", "=", "reader", ".", "terms", "(", "new", "Term", "(", "FieldNames", ".", "PROPERTIES", ",", "namedValue", ")", ")", ";", "try", "{", "TermDocs", "docs", "=", "reader", ".", "termDocs", "(", ")", ";", "try", "{", "while", "(", "terms", ".", "term", "(", ")", "!=", "null", "&&", "terms", ".", "term", "(", ")", ".", "field", "(", ")", "==", "FieldNames", ".", "PROPERTIES", "&&", "terms", ".", "term", "(", ")", ".", "text", "(", ")", ".", "startsWith", "(", "namedValue", ")", ")", "{", "docs", ".", "seek", "(", "terms", ")", ";", "while", "(", "docs", ".", "next", "(", ")", ")", "{", "docFilter", ".", "set", "(", "docs", ".", "doc", "(", ")", ")", ";", "}", "terms", ".", "next", "(", ")", ";", "}", "}", "finally", "{", "docs", ".", "close", "(", ")", ";", "}", "}", "finally", "{", "terms", ".", "close", "(", ")", ";", "}", "// put BitSet into cache", "readerCache", ".", "put", "(", "field", ",", "docFilter", ")", ";", "}" ]
Calculates a BitSet filter that includes all the nodes that have content in properties according to the field name passed in the constructor of this MatchAllScorer. @throws IOException if an error occurs while reading from the search index.
[ "Calculates", "a", "BitSet", "filter", "that", "includes", "all", "the", "nodes", "that", "have", "content", "in", "properties", "according", "to", "the", "field", "name", "passed", "in", "the", "constructor", "of", "this", "MatchAllScorer", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MatchAllScorer.java#L148-L201
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobAgentsInner.java
JobAgentsInner.beginCreateOrUpdate
public JobAgentInner beginCreateOrUpdate(String resourceGroupName, String serverName, String jobAgentName, JobAgentInner parameters) { """ Creates or updates a job agent. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent to be created or updated. @param parameters The requested job agent resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the JobAgentInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, parameters).toBlocking().single().body(); }
java
public JobAgentInner beginCreateOrUpdate(String resourceGroupName, String serverName, String jobAgentName, JobAgentInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, parameters).toBlocking().single().body(); }
[ "public", "JobAgentInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "jobAgentName", ",", "JobAgentInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "jobAgentName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a job agent. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent to be created or updated. @param parameters The requested job agent resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the JobAgentInner object if successful.
[ "Creates", "or", "updates", "a", "job", "agent", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobAgentsInner.java#L417-L419
reinert/requestor
requestor/core/requestor-api/src/main/java/io/reinert/requestor/uri/MultivaluedParamComposition.java
MultivaluedParamComposition.assertNotNullOrEmpty
protected void assertNotNullOrEmpty(String value, String message) throws IllegalArgumentException { """ Assert that the value is not null or empty. @param value the value @param message the message to include with any exceptions @throws IllegalArgumentException if value is null """ if (value == null || value.length() == 0) { throw new IllegalArgumentException(message); } }
java
protected void assertNotNullOrEmpty(String value, String message) throws IllegalArgumentException { if (value == null || value.length() == 0) { throw new IllegalArgumentException(message); } }
[ "protected", "void", "assertNotNullOrEmpty", "(", "String", "value", ",", "String", "message", ")", "throws", "IllegalArgumentException", "{", "if", "(", "value", "==", "null", "||", "value", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "}", "}" ]
Assert that the value is not null or empty. @param value the value @param message the message to include with any exceptions @throws IllegalArgumentException if value is null
[ "Assert", "that", "the", "value", "is", "not", "null", "or", "empty", "." ]
train
https://github.com/reinert/requestor/blob/40163a75cd17815d5089935d0dd97b8d652ad6d4/requestor/core/requestor-api/src/main/java/io/reinert/requestor/uri/MultivaluedParamComposition.java#L50-L54
alipay/sofa-rpc
extension-impl/registry-sofa/src/main/java/com/alipay/sofa/rpc/registry/sofa/SofaRegistryHelper.java
SofaRegistryHelper.getValue
static String getValue(Map<String, String> map, String... keys) { """ 根据多个获取属性值,知道获取到为止 @param map 原始map @param keys 多个key @return 属性值 """ if (CommonUtils.isEmpty(map)) { return null; } for (String key : keys) { String val = map.get(key); if (val != null) { return val; } } return null; }
java
static String getValue(Map<String, String> map, String... keys) { if (CommonUtils.isEmpty(map)) { return null; } for (String key : keys) { String val = map.get(key); if (val != null) { return val; } } return null; }
[ "static", "String", "getValue", "(", "Map", "<", "String", ",", "String", ">", "map", ",", "String", "...", "keys", ")", "{", "if", "(", "CommonUtils", ".", "isEmpty", "(", "map", ")", ")", "{", "return", "null", ";", "}", "for", "(", "String", "key", ":", "keys", ")", "{", "String", "val", "=", "map", ".", "get", "(", "key", ")", ";", "if", "(", "val", "!=", "null", ")", "{", "return", "val", ";", "}", "}", "return", "null", ";", "}" ]
根据多个获取属性值,知道获取到为止 @param map 原始map @param keys 多个key @return 属性值
[ "根据多个获取属性值,知道获取到为止" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/registry-sofa/src/main/java/com/alipay/sofa/rpc/registry/sofa/SofaRegistryHelper.java#L537-L548
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/well/WellRenderer.java
WellRenderer.encodeBegin
@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { """ This methods generates the HTML code of the current b:well. <code>encodeBegin</code> generates the start of the component. After the, the JSF framework calls <code>encodeChildren()</code> to generate the HTML code between the beginning and the end of the component. For instance, in the case of a panel component the content of the panel is generated by <code>encodeChildren()</code>. After that, <code>encodeEnd()</code> is called to generate the rest of the HTML code. @param context the FacesContext. @param component the current b:well. @throws IOException thrown if something goes wrong when writing the HTML code. """ if (!component.isRendered()) { return; } Well well = (Well) component; ResponseWriter rw = context.getResponseWriter(); String clientId = well.getClientId(); String sz = well.getSize(); rw.startElement("div", well); rw.writeAttribute("id", clientId, "id"); String style = well.getStyle(); if (null != style) { rw.writeAttribute("style", style, null); } String styleClass = well.getStyleClass(); if (null == styleClass) styleClass = ""; else styleClass = " " + styleClass; styleClass += Responsive.getResponsiveStyleClass(well, false); Tooltip.generateTooltip(context, well, rw); if (sz != null) { rw.writeAttribute("class", "well well-" + sz + styleClass, "class"); } else { rw.writeAttribute("class", "well" + styleClass, "class"); } beginDisabledFieldset(well, rw); Object value = well.getValue(); if (null != value) { rw.writeText(String.valueOf(value), null); } }
java
@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) { return; } Well well = (Well) component; ResponseWriter rw = context.getResponseWriter(); String clientId = well.getClientId(); String sz = well.getSize(); rw.startElement("div", well); rw.writeAttribute("id", clientId, "id"); String style = well.getStyle(); if (null != style) { rw.writeAttribute("style", style, null); } String styleClass = well.getStyleClass(); if (null == styleClass) styleClass = ""; else styleClass = " " + styleClass; styleClass += Responsive.getResponsiveStyleClass(well, false); Tooltip.generateTooltip(context, well, rw); if (sz != null) { rw.writeAttribute("class", "well well-" + sz + styleClass, "class"); } else { rw.writeAttribute("class", "well" + styleClass, "class"); } beginDisabledFieldset(well, rw); Object value = well.getValue(); if (null != value) { rw.writeText(String.valueOf(value), null); } }
[ "@", "Override", "public", "void", "encodeBegin", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "throws", "IOException", "{", "if", "(", "!", "component", ".", "isRendered", "(", ")", ")", "{", "return", ";", "}", "Well", "well", "=", "(", "Well", ")", "component", ";", "ResponseWriter", "rw", "=", "context", ".", "getResponseWriter", "(", ")", ";", "String", "clientId", "=", "well", ".", "getClientId", "(", ")", ";", "String", "sz", "=", "well", ".", "getSize", "(", ")", ";", "rw", ".", "startElement", "(", "\"div\"", ",", "well", ")", ";", "rw", ".", "writeAttribute", "(", "\"id\"", ",", "clientId", ",", "\"id\"", ")", ";", "String", "style", "=", "well", ".", "getStyle", "(", ")", ";", "if", "(", "null", "!=", "style", ")", "{", "rw", ".", "writeAttribute", "(", "\"style\"", ",", "style", ",", "null", ")", ";", "}", "String", "styleClass", "=", "well", ".", "getStyleClass", "(", ")", ";", "if", "(", "null", "==", "styleClass", ")", "styleClass", "=", "\"\"", ";", "else", "styleClass", "=", "\" \"", "+", "styleClass", ";", "styleClass", "+=", "Responsive", ".", "getResponsiveStyleClass", "(", "well", ",", "false", ")", ";", "Tooltip", ".", "generateTooltip", "(", "context", ",", "well", ",", "rw", ")", ";", "if", "(", "sz", "!=", "null", ")", "{", "rw", ".", "writeAttribute", "(", "\"class\"", ",", "\"well well-\"", "+", "sz", "+", "styleClass", ",", "\"class\"", ")", ";", "}", "else", "{", "rw", ".", "writeAttribute", "(", "\"class\"", ",", "\"well\"", "+", "styleClass", ",", "\"class\"", ")", ";", "}", "beginDisabledFieldset", "(", "well", ",", "rw", ")", ";", "Object", "value", "=", "well", ".", "getValue", "(", ")", ";", "if", "(", "null", "!=", "value", ")", "{", "rw", ".", "writeText", "(", "String", ".", "valueOf", "(", "value", ")", ",", "null", ")", ";", "}", "}" ]
This methods generates the HTML code of the current b:well. <code>encodeBegin</code> generates the start of the component. After the, the JSF framework calls <code>encodeChildren()</code> to generate the HTML code between the beginning and the end of the component. For instance, in the case of a panel component the content of the panel is generated by <code>encodeChildren()</code>. After that, <code>encodeEnd()</code> is called to generate the rest of the HTML code. @param context the FacesContext. @param component the current b:well. @throws IOException thrown if something goes wrong when writing the HTML code.
[ "This", "methods", "generates", "the", "HTML", "code", "of", "the", "current", "b", ":", "well", ".", "<code", ">", "encodeBegin<", "/", "code", ">", "generates", "the", "start", "of", "the", "component", ".", "After", "the", "the", "JSF", "framework", "calls", "<code", ">", "encodeChildren", "()", "<", "/", "code", ">", "to", "generate", "the", "HTML", "code", "between", "the", "beginning", "and", "the", "end", "of", "the", "component", ".", "For", "instance", "in", "the", "case", "of", "a", "panel", "component", "the", "content", "of", "the", "panel", "is", "generated", "by", "<code", ">", "encodeChildren", "()", "<", "/", "code", ">", ".", "After", "that", "<code", ">", "encodeEnd", "()", "<", "/", "code", ">", "is", "called", "to", "generate", "the", "rest", "of", "the", "HTML", "code", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/well/WellRenderer.java#L52-L88
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/validation/DefaultMessageHeaderValidator.java
DefaultMessageHeaderValidator.getHeaderName
private String getHeaderName(String name, Map<String, Object> receivedHeaders, TestContext context, HeaderValidationContext validationContext) { """ Get header name from control message but also check if header expression is a variable or function. In addition to that find case insensitive header name in received message when feature is activated. @param name @param receivedHeaders @param context @param validationContext @return """ String headerName = context.resolveDynamicValue(name); if (!receivedHeaders.containsKey(headerName) && validationContext.isHeaderNameIgnoreCase()) { String key = headerName; log.debug(String.format("Finding case insensitive header for key '%s'", key)); headerName = receivedHeaders .entrySet() .parallelStream() .filter(item -> item.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getKey) .findFirst() .orElseThrow(() -> new ValidationException("Validation failed: No matching header for key '" + key + "'")); log.info(String.format("Found matching case insensitive header name: %s", headerName)); } return headerName; }
java
private String getHeaderName(String name, Map<String, Object> receivedHeaders, TestContext context, HeaderValidationContext validationContext) { String headerName = context.resolveDynamicValue(name); if (!receivedHeaders.containsKey(headerName) && validationContext.isHeaderNameIgnoreCase()) { String key = headerName; log.debug(String.format("Finding case insensitive header for key '%s'", key)); headerName = receivedHeaders .entrySet() .parallelStream() .filter(item -> item.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getKey) .findFirst() .orElseThrow(() -> new ValidationException("Validation failed: No matching header for key '" + key + "'")); log.info(String.format("Found matching case insensitive header name: %s", headerName)); } return headerName; }
[ "private", "String", "getHeaderName", "(", "String", "name", ",", "Map", "<", "String", ",", "Object", ">", "receivedHeaders", ",", "TestContext", "context", ",", "HeaderValidationContext", "validationContext", ")", "{", "String", "headerName", "=", "context", ".", "resolveDynamicValue", "(", "name", ")", ";", "if", "(", "!", "receivedHeaders", ".", "containsKey", "(", "headerName", ")", "&&", "validationContext", ".", "isHeaderNameIgnoreCase", "(", ")", ")", "{", "String", "key", "=", "headerName", ";", "log", ".", "debug", "(", "String", ".", "format", "(", "\"Finding case insensitive header for key '%s'\"", ",", "key", ")", ")", ";", "headerName", "=", "receivedHeaders", ".", "entrySet", "(", ")", ".", "parallelStream", "(", ")", ".", "filter", "(", "item", "->", "item", ".", "getKey", "(", ")", ".", "equalsIgnoreCase", "(", "key", ")", ")", ".", "map", "(", "Map", ".", "Entry", "::", "getKey", ")", ".", "findFirst", "(", ")", ".", "orElseThrow", "(", "(", ")", "->", "new", "ValidationException", "(", "\"Validation failed: No matching header for key '\"", "+", "key", "+", "\"'\"", ")", ")", ";", "log", ".", "info", "(", "String", ".", "format", "(", "\"Found matching case insensitive header name: %s\"", ",", "headerName", ")", ")", ";", "}", "return", "headerName", ";", "}" ]
Get header name from control message but also check if header expression is a variable or function. In addition to that find case insensitive header name in received message when feature is activated. @param name @param receivedHeaders @param context @param validationContext @return
[ "Get", "header", "name", "from", "control", "message", "but", "also", "check", "if", "header", "expression", "is", "a", "variable", "or", "function", ".", "In", "addition", "to", "that", "find", "case", "insensitive", "header", "name", "in", "received", "message", "when", "feature", "is", "activated", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/DefaultMessageHeaderValidator.java#L106-L127
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java
SnapshotFile.createSnapshotFile
@VisibleForTesting static File createSnapshotFile(File directory, String serverName, long index) { """ Creates a snapshot file for the given directory, log name, and snapshot index. """ return new File(directory, createSnapshotFileName(serverName, index)); }
java
@VisibleForTesting static File createSnapshotFile(File directory, String serverName, long index) { return new File(directory, createSnapshotFileName(serverName, index)); }
[ "@", "VisibleForTesting", "static", "File", "createSnapshotFile", "(", "File", "directory", ",", "String", "serverName", ",", "long", "index", ")", "{", "return", "new", "File", "(", "directory", ",", "createSnapshotFileName", "(", "serverName", ",", "index", ")", ")", ";", "}" ]
Creates a snapshot file for the given directory, log name, and snapshot index.
[ "Creates", "a", "snapshot", "file", "for", "the", "given", "directory", "log", "name", "and", "snapshot", "index", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/storage/snapshot/SnapshotFile.java#L88-L91
jenetics/jenetics
jenetics/src/main/java/io/jenetics/engine/Codecs.java
Codecs.ofScalar
public static <A> Codec<A, AnyGene<A>> ofScalar( final Supplier<? extends A> supplier, final Predicate<? super A> validator ) { """ Return a scala {@code Codec} with the given allele {@link Supplier} and allele {@code validator}. The {@code supplier} is responsible for creating new random alleles, and the {@code validator} can verify it. <p> The following example shows a codec which creates and verifies {@code BigInteger} objects. <pre>{@code final Codec<BigInteger, AnyGene<BigInteger>> codec = Codecs.of( // Create new random 'BigInteger' object. () -> { final byte[] data = new byte[100]; RandomRegistry.getRandom().nextBytes(data); return new BigInteger(data); }, // Verify that bit 7 is set. (For illustration purpose.) bi -> bi.testBit(7) ); }</pre> @see AnyGene#of(Supplier, Predicate) @see AnyChromosome#of(Supplier, Predicate) @param <A> the allele type @param supplier the allele-supplier which is used for creating new, random alleles @param validator the validator used for validating the created gene. This predicate is used in the {@link AnyGene#isValid()} method. @return a new {@code Codec} with the given parameters @throws NullPointerException if one of the parameters is {@code null} """ return Codec.of( Genotype.of(AnyChromosome.of(supplier, validator)), gt -> gt.getGene().getAllele() ); }
java
public static <A> Codec<A, AnyGene<A>> ofScalar( final Supplier<? extends A> supplier, final Predicate<? super A> validator ) { return Codec.of( Genotype.of(AnyChromosome.of(supplier, validator)), gt -> gt.getGene().getAllele() ); }
[ "public", "static", "<", "A", ">", "Codec", "<", "A", ",", "AnyGene", "<", "A", ">", ">", "ofScalar", "(", "final", "Supplier", "<", "?", "extends", "A", ">", "supplier", ",", "final", "Predicate", "<", "?", "super", "A", ">", "validator", ")", "{", "return", "Codec", ".", "of", "(", "Genotype", ".", "of", "(", "AnyChromosome", ".", "of", "(", "supplier", ",", "validator", ")", ")", ",", "gt", "->", "gt", ".", "getGene", "(", ")", ".", "getAllele", "(", ")", ")", ";", "}" ]
Return a scala {@code Codec} with the given allele {@link Supplier} and allele {@code validator}. The {@code supplier} is responsible for creating new random alleles, and the {@code validator} can verify it. <p> The following example shows a codec which creates and verifies {@code BigInteger} objects. <pre>{@code final Codec<BigInteger, AnyGene<BigInteger>> codec = Codecs.of( // Create new random 'BigInteger' object. () -> { final byte[] data = new byte[100]; RandomRegistry.getRandom().nextBytes(data); return new BigInteger(data); }, // Verify that bit 7 is set. (For illustration purpose.) bi -> bi.testBit(7) ); }</pre> @see AnyGene#of(Supplier, Predicate) @see AnyChromosome#of(Supplier, Predicate) @param <A> the allele type @param supplier the allele-supplier which is used for creating new, random alleles @param validator the validator used for validating the created gene. This predicate is used in the {@link AnyGene#isValid()} method. @return a new {@code Codec} with the given parameters @throws NullPointerException if one of the parameters is {@code null}
[ "Return", "a", "scala", "{", "@code", "Codec", "}", "with", "the", "given", "allele", "{", "@link", "Supplier", "}", "and", "allele", "{", "@code", "validator", "}", ".", "The", "{", "@code", "supplier", "}", "is", "responsible", "for", "creating", "new", "random", "alleles", "and", "the", "{", "@code", "validator", "}", "can", "verify", "it", ".", "<p", ">", "The", "following", "example", "shows", "a", "codec", "which", "creates", "and", "verifies", "{", "@code", "BigInteger", "}", "objects", ".", "<pre", ">", "{", "@code", "final", "Codec<BigInteger", "AnyGene<BigInteger", ">>", "codec", "=", "Codecs", ".", "of", "(", "//", "Create", "new", "random", "BigInteger", "object", ".", "()", "-", ">", "{", "final", "byte", "[]", "data", "=", "new", "byte", "[", "100", "]", ";", "RandomRegistry", ".", "getRandom", "()", ".", "nextBytes", "(", "data", ")", ";", "return", "new", "BigInteger", "(", "data", ")", ";", "}", "//", "Verify", "that", "bit", "7", "is", "set", ".", "(", "For", "illustration", "purpose", ".", ")", "bi", "-", ">", "bi", ".", "testBit", "(", "7", ")", ")", ";", "}", "<", "/", "pre", ">" ]
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/engine/Codecs.java#L148-L156
magro/memcached-session-manager
core/src/main/java/de/javakaffee/web/msm/NodeIdService.java
NodeIdService.getRandomNextNodeId
protected String getRandomNextNodeId( final String nodeId, final Collection<String> nodeIds ) { """ Determines (randomly) an available node id from the provided node ids. The returned node id will be different from the provided nodeId and will be available according to the local {@link NodeAvailabilityCache}. @param nodeId the original id @param nodeIds the node ids to choose from @return an available node or null """ /* create a list of nodeIds to check randomly */ final List<String> otherNodeIds = new ArrayList<String>( nodeIds ); otherNodeIds.remove( nodeId ); while ( !otherNodeIds.isEmpty() ) { final String nodeIdToCheck = otherNodeIds.get( _random.nextInt( otherNodeIds.size() ) ); if ( isNodeAvailable( nodeIdToCheck ) ) { return nodeIdToCheck; } otherNodeIds.remove( nodeIdToCheck ); } return null; }
java
protected String getRandomNextNodeId( final String nodeId, final Collection<String> nodeIds ) { /* create a list of nodeIds to check randomly */ final List<String> otherNodeIds = new ArrayList<String>( nodeIds ); otherNodeIds.remove( nodeId ); while ( !otherNodeIds.isEmpty() ) { final String nodeIdToCheck = otherNodeIds.get( _random.nextInt( otherNodeIds.size() ) ); if ( isNodeAvailable( nodeIdToCheck ) ) { return nodeIdToCheck; } otherNodeIds.remove( nodeIdToCheck ); } return null; }
[ "protected", "String", "getRandomNextNodeId", "(", "final", "String", "nodeId", ",", "final", "Collection", "<", "String", ">", "nodeIds", ")", "{", "/* create a list of nodeIds to check randomly\n */", "final", "List", "<", "String", ">", "otherNodeIds", "=", "new", "ArrayList", "<", "String", ">", "(", "nodeIds", ")", ";", "otherNodeIds", ".", "remove", "(", "nodeId", ")", ";", "while", "(", "!", "otherNodeIds", ".", "isEmpty", "(", ")", ")", "{", "final", "String", "nodeIdToCheck", "=", "otherNodeIds", ".", "get", "(", "_random", ".", "nextInt", "(", "otherNodeIds", ".", "size", "(", ")", ")", ")", ";", "if", "(", "isNodeAvailable", "(", "nodeIdToCheck", ")", ")", "{", "return", "nodeIdToCheck", ";", "}", "otherNodeIds", ".", "remove", "(", "nodeIdToCheck", ")", ";", "}", "return", "null", ";", "}" ]
Determines (randomly) an available node id from the provided node ids. The returned node id will be different from the provided nodeId and will be available according to the local {@link NodeAvailabilityCache}. @param nodeId the original id @param nodeIds the node ids to choose from @return an available node or null
[ "Determines", "(", "randomly", ")", "an", "available", "node", "id", "from", "the", "provided", "node", "ids", ".", "The", "returned", "node", "id", "will", "be", "different", "from", "the", "provided", "nodeId", "and", "will", "be", "available", "according", "to", "the", "local", "{", "@link", "NodeAvailabilityCache", "}", "." ]
train
https://github.com/magro/memcached-session-manager/blob/716e147c9840ab10298c4d2b9edd0662058331e6/core/src/main/java/de/javakaffee/web/msm/NodeIdService.java#L159-L175
wcm-io/wcm-io-sling
commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java
RequestParam.getDouble
public static double getDouble(@NotNull ServletRequest request, @NotNull String param, double defaultValue) { """ Returns a request parameter as double. @param request Request. @param param Parameter name. @param defaultValue Default value. @return Parameter value or default value if it does not exist or is not a number. """ String value = request.getParameter(param); return NumberUtils.toDouble(value, defaultValue); }
java
public static double getDouble(@NotNull ServletRequest request, @NotNull String param, double defaultValue) { String value = request.getParameter(param); return NumberUtils.toDouble(value, defaultValue); }
[ "public", "static", "double", "getDouble", "(", "@", "NotNull", "ServletRequest", "request", ",", "@", "NotNull", "String", "param", ",", "double", "defaultValue", ")", "{", "String", "value", "=", "request", ".", "getParameter", "(", "param", ")", ";", "return", "NumberUtils", ".", "toDouble", "(", "value", ",", "defaultValue", ")", ";", "}" ]
Returns a request parameter as double. @param request Request. @param param Parameter name. @param defaultValue Default value. @return Parameter value or default value if it does not exist or is not a number.
[ "Returns", "a", "request", "parameter", "as", "double", "." ]
train
https://github.com/wcm-io/wcm-io-sling/blob/90adbe432469378794b5695c72e9cdfa2b7d36f1/commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java#L222-L225
JM-Lab/utils-java8
src/main/java/kr/jm/utils/JMProgressiveManager.java
JMProgressiveManager.registerCountChangeListener
public JMProgressiveManager<T, R> registerCountChangeListener(Consumer<Number> countChangeListener) { """ Register count change listener jm progressive manager. @param countChangeListener the count change listener @return the jm progressive manager """ return registerListener(progressiveCount, countChangeListener); }
java
public JMProgressiveManager<T, R> registerCountChangeListener(Consumer<Number> countChangeListener) { return registerListener(progressiveCount, countChangeListener); }
[ "public", "JMProgressiveManager", "<", "T", ",", "R", ">", "registerCountChangeListener", "(", "Consumer", "<", "Number", ">", "countChangeListener", ")", "{", "return", "registerListener", "(", "progressiveCount", ",", "countChangeListener", ")", ";", "}" ]
Register count change listener jm progressive manager. @param countChangeListener the count change listener @return the jm progressive manager
[ "Register", "count", "change", "listener", "jm", "progressive", "manager", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/JMProgressiveManager.java#L248-L251
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java
PhotosApi.getInfo
public PhotoInfo getInfo(String photoId, String secret) throws JinxException { """ Get information about a photo. The calling user must have permission to view the photo. <br> This method does not require authentication. @param photoId Required. The id of the photo to get information for. @param secret Optional. The secret for the photo. If the correct secret is passed then permissions checking is skipped. This enables the 'sharing' of individual photos by passing around the id and secret. @return object with available information for the photo. @throws JinxException if required parameters are null or empty, or if there are errors. @see <a href="https://www.flickr.com/services/api/flickr.photos.getInfo.html">flickr.photos.getInfo</a> """ JinxUtils.validateParams(photoId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.getInfo"); params.put("photo_id", photoId); if (!JinxUtils.isNullOrEmpty(secret)) { params.put("secret", secret); } return jinx.flickrGet(params, PhotoInfo.class); // sometimes Flickr sends back responses with "machine_tag":false rather than "machine_tag":0 // so we need to work around this by fixing up the response // if the response is not fixed up, Gson cannot parse it // String json = jinx.callFlickr(params, JinxConstants.Method.GET, true); // json = json.replace(":false", ":0"); // return jinx.jsonToClass(json, PhotoInfo.class); }
java
public PhotoInfo getInfo(String photoId, String secret) throws JinxException { JinxUtils.validateParams(photoId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.getInfo"); params.put("photo_id", photoId); if (!JinxUtils.isNullOrEmpty(secret)) { params.put("secret", secret); } return jinx.flickrGet(params, PhotoInfo.class); // sometimes Flickr sends back responses with "machine_tag":false rather than "machine_tag":0 // so we need to work around this by fixing up the response // if the response is not fixed up, Gson cannot parse it // String json = jinx.callFlickr(params, JinxConstants.Method.GET, true); // json = json.replace(":false", ":0"); // return jinx.jsonToClass(json, PhotoInfo.class); }
[ "public", "PhotoInfo", "getInfo", "(", "String", "photoId", ",", "String", "secret", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "photoId", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "TreeMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"method\"", ",", "\"flickr.photos.getInfo\"", ")", ";", "params", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "if", "(", "!", "JinxUtils", ".", "isNullOrEmpty", "(", "secret", ")", ")", "{", "params", ".", "put", "(", "\"secret\"", ",", "secret", ")", ";", "}", "return", "jinx", ".", "flickrGet", "(", "params", ",", "PhotoInfo", ".", "class", ")", ";", "// sometimes Flickr sends back responses with \"machine_tag\":false rather than \"machine_tag\":0", "// so we need to work around this by fixing up the response", "// if the response is not fixed up, Gson cannot parse it", "// String json = jinx.callFlickr(params, JinxConstants.Method.GET, true);", "// json = json.replace(\":false\", \":0\");", "// return jinx.jsonToClass(json, PhotoInfo.class);", "}" ]
Get information about a photo. The calling user must have permission to view the photo. <br> This method does not require authentication. @param photoId Required. The id of the photo to get information for. @param secret Optional. The secret for the photo. If the correct secret is passed then permissions checking is skipped. This enables the 'sharing' of individual photos by passing around the id and secret. @return object with available information for the photo. @throws JinxException if required parameters are null or empty, or if there are errors. @see <a href="https://www.flickr.com/services/api/flickr.photos.getInfo.html">flickr.photos.getInfo</a>
[ "Get", "information", "about", "a", "photo", ".", "The", "calling", "user", "must", "have", "permission", "to", "view", "the", "photo", ".", "<br", ">", "This", "method", "does", "not", "require", "authentication", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java#L332-L347
before/uadetector
modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/AbstractUpdateOperation.java
AbstractUpdateOperation.hasUpdate
static boolean hasUpdate(final String newer, final String older) { """ Checks a given newer version against an older one. @param newer possible newer version @param older possible older version @return {@code true} if the first argument is newer than the second argument, otherwise {@code false} """ return VERSION_PATTERN.matcher(newer).matches() && VERSION_PATTERN.matcher(older).matches() ? newer.compareTo(older) > 0 : false; }
java
static boolean hasUpdate(final String newer, final String older) { return VERSION_PATTERN.matcher(newer).matches() && VERSION_PATTERN.matcher(older).matches() ? newer.compareTo(older) > 0 : false; }
[ "static", "boolean", "hasUpdate", "(", "final", "String", "newer", ",", "final", "String", "older", ")", "{", "return", "VERSION_PATTERN", ".", "matcher", "(", "newer", ")", ".", "matches", "(", ")", "&&", "VERSION_PATTERN", ".", "matcher", "(", "older", ")", ".", "matches", "(", ")", "?", "newer", ".", "compareTo", "(", "older", ")", ">", "0", ":", "false", ";", "}" ]
Checks a given newer version against an older one. @param newer possible newer version @param older possible older version @return {@code true} if the first argument is newer than the second argument, otherwise {@code false}
[ "Checks", "a", "given", "newer", "version", "against", "an", "older", "one", "." ]
train
https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/AbstractUpdateOperation.java#L103-L105
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java
ZipEntryUtil.setZTFilePermissions
static boolean setZTFilePermissions(ZipEntry zipEntry, ZTFilePermissions permissions) { """ Add file permissions info to ZIP entry. Current implementation adds "ASi Unix" (tag 0x756e) extra block to entry. @param zipEntry ZIP entry @param permissions permissions to assign """ try { List<ZipExtraField> fields = ExtraFieldUtils.parse(zipEntry.getExtra()); AsiExtraField asiExtraField = getFirstAsiExtraField(fields); if (asiExtraField == null) { asiExtraField = new AsiExtraField(); fields.add(asiExtraField); } asiExtraField.setDirectory(zipEntry.isDirectory()); asiExtraField.setMode(ZTFilePermissionsUtil.toPosixFileMode(permissions)); zipEntry.setExtra(ExtraFieldUtils.mergeLocalFileDataData(fields)); return true; } catch (java.util.zip.ZipException ze) { return false; } }
java
static boolean setZTFilePermissions(ZipEntry zipEntry, ZTFilePermissions permissions) { try { List<ZipExtraField> fields = ExtraFieldUtils.parse(zipEntry.getExtra()); AsiExtraField asiExtraField = getFirstAsiExtraField(fields); if (asiExtraField == null) { asiExtraField = new AsiExtraField(); fields.add(asiExtraField); } asiExtraField.setDirectory(zipEntry.isDirectory()); asiExtraField.setMode(ZTFilePermissionsUtil.toPosixFileMode(permissions)); zipEntry.setExtra(ExtraFieldUtils.mergeLocalFileDataData(fields)); return true; } catch (java.util.zip.ZipException ze) { return false; } }
[ "static", "boolean", "setZTFilePermissions", "(", "ZipEntry", "zipEntry", ",", "ZTFilePermissions", "permissions", ")", "{", "try", "{", "List", "<", "ZipExtraField", ">", "fields", "=", "ExtraFieldUtils", ".", "parse", "(", "zipEntry", ".", "getExtra", "(", ")", ")", ";", "AsiExtraField", "asiExtraField", "=", "getFirstAsiExtraField", "(", "fields", ")", ";", "if", "(", "asiExtraField", "==", "null", ")", "{", "asiExtraField", "=", "new", "AsiExtraField", "(", ")", ";", "fields", ".", "add", "(", "asiExtraField", ")", ";", "}", "asiExtraField", ".", "setDirectory", "(", "zipEntry", ".", "isDirectory", "(", ")", ")", ";", "asiExtraField", ".", "setMode", "(", "ZTFilePermissionsUtil", ".", "toPosixFileMode", "(", "permissions", ")", ")", ";", "zipEntry", ".", "setExtra", "(", "ExtraFieldUtils", ".", "mergeLocalFileDataData", "(", "fields", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "java", ".", "util", ".", "zip", ".", "ZipException", "ze", ")", "{", "return", "false", ";", "}", "}" ]
Add file permissions info to ZIP entry. Current implementation adds "ASi Unix" (tag 0x756e) extra block to entry. @param zipEntry ZIP entry @param permissions permissions to assign
[ "Add", "file", "permissions", "info", "to", "ZIP", "entry", ".", "Current", "implementation", "adds", "ASi", "Unix", "(", "tag", "0x756e", ")", "extra", "block", "to", "entry", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java#L164-L181