repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
JM-Lab/utils-java8
src/main/java/kr/jm/utils/datastructure/JMMap.java
JMMap.putGetNew
public static <V, K> V putGetNew(Map<K, V> map, K key, V newValue) { synchronized (map) { map.put(key, newValue); return newValue; } }
java
public static <V, K> V putGetNew(Map<K, V> map, K key, V newValue) { synchronized (map) { map.put(key, newValue); return newValue; } }
[ "public", "static", "<", "V", ",", "K", ">", "V", "putGetNew", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "K", "key", ",", "V", "newValue", ")", "{", "synchronized", "(", "map", ")", "{", "map", ".", "put", "(", "key", ",", "newValue", ...
Put get new v. @param <V> the type parameter @param <K> the type parameter @param map the map @param key the key @param newValue the new value @return the v
[ "Put", "get", "new", "v", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/datastructure/JMMap.java#L122-L127
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/model/Interval.java
Interval.withEndDate
public Interval withEndDate(LocalDate date) { requireNonNull(date); return new Interval(startDate, startTime, date, endTime, zoneId); }
java
public Interval withEndDate(LocalDate date) { requireNonNull(date); return new Interval(startDate, startTime, date, endTime, zoneId); }
[ "public", "Interval", "withEndDate", "(", "LocalDate", "date", ")", "{", "requireNonNull", "(", "date", ")", ";", "return", "new", "Interval", "(", "startDate", ",", "startTime", ",", "date", ",", "endTime", ",", "zoneId", ")", ";", "}" ]
Returns a new interval based on this interval but with a different end date. @param date the new end date @return a new interval
[ "Returns", "a", "new", "interval", "based", "on", "this", "interval", "but", "with", "a", "different", "end", "date", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/model/Interval.java#L331-L334
liferay/com-liferay-commerce
commerce-payment-service/src/main/java/com/liferay/commerce/payment/service/persistence/impl/CommercePaymentMethodGroupRelPersistenceImpl.java
CommercePaymentMethodGroupRelPersistenceImpl.findByGroupId
@Override public List<CommercePaymentMethodGroupRel> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommercePaymentMethodGroupRel> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommercePaymentMethodGroupRel", ">", "findByGroupId", "(", "long", "groupId", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";...
Returns all the commerce payment method group rels where groupId = &#63;. @param groupId the group ID @return the matching commerce payment method group rels
[ "Returns", "all", "the", "commerce", "payment", "method", "group", "rels", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-payment-service/src/main/java/com/liferay/commerce/payment/service/persistence/impl/CommercePaymentMethodGroupRelPersistenceImpl.java#L127-L130
AKSW/RDFUnit
rdfunit-core/src/main/java/org/aksw/rdfunit/prefix/TrustingUrlConnection.java
TrustingUrlConnection.executeHeadRequest
static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException { HttpHead headMethod = new HttpHead(uri); MyRedirectHandler redirectHandler = new MyRedirectHandler(uri); String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty() ? format.getMimeType() : "*/*"; CloseableHttpClient httpClient = HttpClientBuilder .create() .setDefaultRequestConfig(requestConfig) .setConnectionManager(poolingConnManager) .setSSLContext(ssl) .setRedirectStrategy(redirectHandler) .setDefaultHeaders(Arrays.asList( new BasicHeader("Accept", acceptHeader), //if default request we try to pretend to be a browser, else we accept everything new BasicHeader("User-Agent", "Mozilla/5.0"), new BasicHeader("Upgrade-Insecure-Requests", "1") // we are an all trusting client... )) .build(); HttpResponse httpResponse = httpClient.execute(headMethod); redirectHandler.lastRedirectedUri.forEach(x -> httpResponse.setHeader(HEADERKEY, String.valueOf(x))); return httpResponse; }
java
static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException { HttpHead headMethod = new HttpHead(uri); MyRedirectHandler redirectHandler = new MyRedirectHandler(uri); String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty() ? format.getMimeType() : "*/*"; CloseableHttpClient httpClient = HttpClientBuilder .create() .setDefaultRequestConfig(requestConfig) .setConnectionManager(poolingConnManager) .setSSLContext(ssl) .setRedirectStrategy(redirectHandler) .setDefaultHeaders(Arrays.asList( new BasicHeader("Accept", acceptHeader), //if default request we try to pretend to be a browser, else we accept everything new BasicHeader("User-Agent", "Mozilla/5.0"), new BasicHeader("Upgrade-Insecure-Requests", "1") // we are an all trusting client... )) .build(); HttpResponse httpResponse = httpClient.execute(headMethod); redirectHandler.lastRedirectedUri.forEach(x -> httpResponse.setHeader(HEADERKEY, String.valueOf(x))); return httpResponse; }
[ "static", "HttpResponse", "executeHeadRequest", "(", "URI", "uri", ",", "SerializationFormat", "format", ")", "throws", "IOException", "{", "HttpHead", "headMethod", "=", "new", "HttpHead", "(", "uri", ")", ";", "MyRedirectHandler", "redirectHandler", "=", "new", ...
Will execute a HEAD only request, following redirects, trying to locate an rdf document. @param uri - the initial uri @param format - the expected mime type @return - the final http response @throws IOException
[ "Will", "execute", "a", "HEAD", "only", "request", "following", "redirects", "trying", "to", "locate", "an", "rdf", "document", "." ]
train
https://github.com/AKSW/RDFUnit/blob/083f18ebda4ad790b1fbb4cfe1c9dd1762d51384/rdfunit-core/src/main/java/org/aksw/rdfunit/prefix/TrustingUrlConnection.java#L101-L123
graknlabs/grakn
server/src/server/kb/concept/SchemaConceptImpl.java
SchemaConceptImpl.changingSuperAllowed
boolean changingSuperAllowed(T oldSuperType, T newSuperType) { checkSchemaMutationAllowed(); return oldSuperType == null || !oldSuperType.equals(newSuperType); }
java
boolean changingSuperAllowed(T oldSuperType, T newSuperType) { checkSchemaMutationAllowed(); return oldSuperType == null || !oldSuperType.equals(newSuperType); }
[ "boolean", "changingSuperAllowed", "(", "T", "oldSuperType", ",", "T", "newSuperType", ")", "{", "checkSchemaMutationAllowed", "(", ")", ";", "return", "oldSuperType", "==", "null", "||", "!", "oldSuperType", ".", "equals", "(", "newSuperType", ")", ";", "}" ]
Checks if changing the super is allowed. This passed if: The <code>newSuperType</code> is different from the old. @param oldSuperType the old super @param newSuperType the new super @return true if we can set the new super
[ "Checks", "if", "changing", "the", "super", "is", "allowed", ".", "This", "passed", "if", ":", "The", "<code", ">", "newSuperType<", "/", "code", ">", "is", "different", "from", "the", "old", "." ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/SchemaConceptImpl.java#L244-L247
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/core/image/ConvertImage.java
ConvertImage.convertU8F32
public static InterleavedF32 convertU8F32( Planar<GrayU8> input , InterleavedF32 output ) { if (output == null) { output = new InterleavedF32(input.width, input.height,input.getNumBands()); } else { output.reshape(input.width,input.height,input.getNumBands()); } if( BoofConcurrency.USE_CONCURRENT ) { ImplConvertImage_MT.convertU8F32(input,output); } else { ImplConvertImage.convertU8F32(input,output); } return output; }
java
public static InterleavedF32 convertU8F32( Planar<GrayU8> input , InterleavedF32 output ) { if (output == null) { output = new InterleavedF32(input.width, input.height,input.getNumBands()); } else { output.reshape(input.width,input.height,input.getNumBands()); } if( BoofConcurrency.USE_CONCURRENT ) { ImplConvertImage_MT.convertU8F32(input,output); } else { ImplConvertImage.convertU8F32(input,output); } return output; }
[ "public", "static", "InterleavedF32", "convertU8F32", "(", "Planar", "<", "GrayU8", ">", "input", ",", "InterleavedF32", "output", ")", "{", "if", "(", "output", "==", "null", ")", "{", "output", "=", "new", "InterleavedF32", "(", "input", ".", "width", ",...
Converts a {@link Planar} into the equivalent {@link InterleavedF32} @param input (Input) Planar image that is being converted. Not modified. @param output (Optional) The output image. If null a new image is created. Modified. @return Converted image.
[ "Converts", "a", "{", "@link", "Planar", "}", "into", "the", "equivalent", "{", "@link", "InterleavedF32", "}" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/core/image/ConvertImage.java#L3581-L3595
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java
SpiderService.aggregateQuery
public AggregateResult aggregateQuery(TableDefinition tableDef, Aggregate aggParams) { checkServiceState(); aggParams.execute(); return aggParams.getResult(); }
java
public AggregateResult aggregateQuery(TableDefinition tableDef, Aggregate aggParams) { checkServiceState(); aggParams.execute(); return aggParams.getResult(); }
[ "public", "AggregateResult", "aggregateQuery", "(", "TableDefinition", "tableDef", ",", "Aggregate", "aggParams", ")", "{", "checkServiceState", "(", ")", ";", "aggParams", ".", "execute", "(", ")", ";", "return", "aggParams", ".", "getResult", "(", ")", ";", ...
Perform an aggregate query on the given table using the given query parameters. @param tableDef {@link TableDefinition} of table to query. @param aggParams {@link Aggregate} containing query parameters. @return {@link AggregateResult} containing search results.
[ "Perform", "an", "aggregate", "query", "on", "the", "given", "table", "using", "the", "given", "query", "parameters", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderService.java#L209-L213
elki-project/elki
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/minkowski/LPIntegerNormDistanceFunction.java
LPIntegerNormDistanceFunction.preNormMBR
private double preNormMBR(SpatialComparable mbr, final int start, final int end) { double agg = 0.; for(int d = start; d < end; d++) { double delta = mbr.getMin(d); delta = delta >= 0 ? delta : -mbr.getMax(d); if(delta > 0.) { agg += MathUtil.powi(delta, intp); } } return agg; }
java
private double preNormMBR(SpatialComparable mbr, final int start, final int end) { double agg = 0.; for(int d = start; d < end; d++) { double delta = mbr.getMin(d); delta = delta >= 0 ? delta : -mbr.getMax(d); if(delta > 0.) { agg += MathUtil.powi(delta, intp); } } return agg; }
[ "private", "double", "preNormMBR", "(", "SpatialComparable", "mbr", ",", "final", "int", "start", ",", "final", "int", "end", ")", "{", "double", "agg", "=", "0.", ";", "for", "(", "int", "d", "=", "start", ";", "d", "<", "end", ";", "d", "++", ")"...
Compute unscaled norm in a range of dimensions. @param mbr Data object @param start First dimension @param end Exclusive last dimension @return Aggregated values.
[ "Compute", "unscaled", "norm", "in", "a", "range", "of", "dimensions", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/minkowski/LPIntegerNormDistanceFunction.java#L153-L163
spotbugs/spotbugs
spotbugs/src/gui/main/edu/umd/cs/findbugs/gui/AnnotatedString.java
AnnotatedString.localiseButton
public static void localiseButton(AbstractButton button, String key, String defaultString, boolean setMnemonic) { AnnotatedString as = new AnnotatedString(L10N.getLocalString(key, defaultString)); button.setText(as.toString()); int mnemonic; if (setMnemonic && (mnemonic = as.getMnemonic()) != KeyEvent.VK_UNDEFINED) { button.setMnemonic(mnemonic); button.setDisplayedMnemonicIndex(as.getMnemonicIndex()); } }
java
public static void localiseButton(AbstractButton button, String key, String defaultString, boolean setMnemonic) { AnnotatedString as = new AnnotatedString(L10N.getLocalString(key, defaultString)); button.setText(as.toString()); int mnemonic; if (setMnemonic && (mnemonic = as.getMnemonic()) != KeyEvent.VK_UNDEFINED) { button.setMnemonic(mnemonic); button.setDisplayedMnemonicIndex(as.getMnemonicIndex()); } }
[ "public", "static", "void", "localiseButton", "(", "AbstractButton", "button", ",", "String", "key", ",", "String", "defaultString", ",", "boolean", "setMnemonic", ")", "{", "AnnotatedString", "as", "=", "new", "AnnotatedString", "(", "L10N", ".", "getLocalString"...
Localise the given AbstractButton, setting the text and optionally mnemonic Note that AbstractButton includes menus and menu items. @param button The button to localise @param key The key to look up in resource bundle @param defaultString default String to use if key not found @param setMnemonic whether or not to set the mnemonic. According to Sun's guidelines, default/cancel buttons should not have mnemonics but instead should use Return/Escape
[ "Localise", "the", "given", "AbstractButton", "setting", "the", "text", "and", "optionally", "mnemonic", "Note", "that", "AbstractButton", "includes", "menus", "and", "menu", "items", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/gui/main/edu/umd/cs/findbugs/gui/AnnotatedString.java#L168-L176
oehf/ipf-oht-atna
nodeauth/src/main/java/org/openhealthtools/ihe/atna/nodeauth/handlers/AbstractSecureSocketHandler.java
AbstractSecureSocketHandler.createSocketFromFactory
protected Socket createSocketFromFactory(SocketFactory factory, String host, int port) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + host +" on port " + port + " (timeout: " + CONTEXT.getConfig().getConnectTimeout() + " ms) using factory "+ factory.getClass().getName()); } SocketAddress address = new InetSocketAddress(host,port); Socket socket = factory.createSocket(); socket.connect(address, CONTEXT.getConfig().getConnectTimeout()); // Set amount of time to wait on socket read before timing out socket.setSoTimeout(CONTEXT.getConfig().getSocketTimeout()); socket.setKeepAlive(true); return socket; }
java
protected Socket createSocketFromFactory(SocketFactory factory, String host, int port) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + host +" on port " + port + " (timeout: " + CONTEXT.getConfig().getConnectTimeout() + " ms) using factory "+ factory.getClass().getName()); } SocketAddress address = new InetSocketAddress(host,port); Socket socket = factory.createSocket(); socket.connect(address, CONTEXT.getConfig().getConnectTimeout()); // Set amount of time to wait on socket read before timing out socket.setSoTimeout(CONTEXT.getConfig().getSocketTimeout()); socket.setKeepAlive(true); return socket; }
[ "protected", "Socket", "createSocketFromFactory", "(", "SocketFactory", "factory", ",", "String", "host", ",", "int", "port", ")", "throws", "IOException", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"C...
Creates a new connected socket to a given host and port from a provided Socket Factory. @param factory Java Socket Factory to use in the connection @param host Hostname to connect to @param port Port to connect to @return Connected socket instance from the given factory @throws IOException
[ "Creates", "a", "new", "connected", "socket", "to", "a", "given", "host", "and", "port", "from", "a", "provided", "Socket", "Factory", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/nodeauth/src/main/java/org/openhealthtools/ihe/atna/nodeauth/handlers/AbstractSecureSocketHandler.java#L224-L238
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRSkeleton.java
GVRSkeleton.setBoneName
public void setBoneName(int boneindex, String bonename) { mBoneNames[boneindex] = bonename; NativeSkeleton.setBoneName(getNative(), boneindex, bonename); }
java
public void setBoneName(int boneindex, String bonename) { mBoneNames[boneindex] = bonename; NativeSkeleton.setBoneName(getNative(), boneindex, bonename); }
[ "public", "void", "setBoneName", "(", "int", "boneindex", ",", "String", "bonename", ")", "{", "mBoneNames", "[", "boneindex", "]", "=", "bonename", ";", "NativeSkeleton", ".", "setBoneName", "(", "getNative", "(", ")", ",", "boneindex", ",", "bonename", ")"...
Sets the name of the designated bone. @param boneindex zero based index of bone to rotate. @param bonename string with name of bone. . * @see #getBoneName
[ "Sets", "the", "name", "of", "the", "designated", "bone", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRSkeleton.java#L776-L780
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/util/FileUtils.java
FileUtils.readToString
public static String readToString(InputStream inputStream, Charset charset) throws IOException { return new String(FileCopyUtils.copyToByteArray(inputStream), charset); }
java
public static String readToString(InputStream inputStream, Charset charset) throws IOException { return new String(FileCopyUtils.copyToByteArray(inputStream), charset); }
[ "public", "static", "String", "readToString", "(", "InputStream", "inputStream", ",", "Charset", "charset", ")", "throws", "IOException", "{", "return", "new", "String", "(", "FileCopyUtils", ".", "copyToByteArray", "(", "inputStream", ")", ",", "charset", ")", ...
Read file input stream to string value. @param inputStream @param charset @return @throws IOException
[ "Read", "file", "input", "stream", "to", "string", "value", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/util/FileUtils.java#L125-L127
paypal/SeLion
common/src/main/java/com/paypal/selion/platform/utilities/FileAssistant.java
FileAssistant.writeStreamToFile
public static void writeStreamToFile(InputStream isr, String fileName, String outputFolder) throws IOException { logger.entering(new Object[] { isr, fileName, outputFolder }); FileUtils.copyInputStreamToFile(isr, new File(outputFolder + "/" + fileName)); logger.exiting(); }
java
public static void writeStreamToFile(InputStream isr, String fileName, String outputFolder) throws IOException { logger.entering(new Object[] { isr, fileName, outputFolder }); FileUtils.copyInputStreamToFile(isr, new File(outputFolder + "/" + fileName)); logger.exiting(); }
[ "public", "static", "void", "writeStreamToFile", "(", "InputStream", "isr", ",", "String", "fileName", ",", "String", "outputFolder", ")", "throws", "IOException", "{", "logger", ".", "entering", "(", "new", "Object", "[", "]", "{", "isr", ",", "fileName", "...
Write an {@link InputStream} to a file @param isr the {@link InputStream} @param fileName The target file name to use. Do not include the path. @param outputFolder The target folder to use. @throws IOException
[ "Write", "an", "{" ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/common/src/main/java/com/paypal/selion/platform/utilities/FileAssistant.java#L114-L118
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MessageFormat.java
MessageFormat.setCustomArgStartFormat
private void setCustomArgStartFormat(int argStart, Format formatter) { setArgStartFormat(argStart, formatter); if (customFormatArgStarts == null) { customFormatArgStarts = new HashSet<Integer>(); } customFormatArgStarts.add(argStart); }
java
private void setCustomArgStartFormat(int argStart, Format formatter) { setArgStartFormat(argStart, formatter); if (customFormatArgStarts == null) { customFormatArgStarts = new HashSet<Integer>(); } customFormatArgStarts.add(argStart); }
[ "private", "void", "setCustomArgStartFormat", "(", "int", "argStart", ",", "Format", "formatter", ")", "{", "setArgStartFormat", "(", "argStart", ",", "formatter", ")", ";", "if", "(", "customFormatArgStarts", "==", "null", ")", "{", "customFormatArgStarts", "=", ...
Sets a custom formatter for a MessagePattern ARG_START part index. "Custom" formatters are provided by the user via setFormat() or similar APIs.
[ "Sets", "a", "custom", "formatter", "for", "a", "MessagePattern", "ARG_START", "part", "index", ".", "Custom", "formatters", "are", "provided", "by", "the", "user", "via", "setFormat", "()", "or", "similar", "APIs", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/MessageFormat.java#L2400-L2406
upwork/java-upwork
src/com/Upwork/api/Routers/Workdiary.java
Workdiary.getByContract
public JSONObject getByContract(String contract, String date, HashMap<String, String> params) throws JSONException { return oClient.get("/team/v3/workdiaries/contracts/" + contract + "/" + date, params); }
java
public JSONObject getByContract(String contract, String date, HashMap<String, String> params) throws JSONException { return oClient.get("/team/v3/workdiaries/contracts/" + contract + "/" + date, params); }
[ "public", "JSONObject", "getByContract", "(", "String", "contract", ",", "String", "date", ",", "HashMap", "<", "String", ",", "String", ">", "params", ")", "throws", "JSONException", "{", "return", "oClient", ".", "get", "(", "\"/team/v3/workdiaries/contracts/\""...
Get Work Diary by Contract @param contract Contract ID @param date Date @param params (Optional) Parameters @throws JSONException If error occurred @return {@link JSONObject}
[ "Get", "Work", "Diary", "by", "Contract" ]
train
https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/Routers/Workdiary.java#L68-L70
rubenlagus/TelegramBots
telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java
CommandRegistry.executeCommand
public final boolean executeCommand(AbsSender absSender, Message message) { if (message.hasText()) { String text = message.getText(); if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { String commandMessage = text.substring(1); String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP); String command = removeUsernameFromCommandIfNeeded(commandSplit[0]); if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); commandRegistryMap.get(command).processMessage(absSender, message, parameters); return true; } else if (defaultConsumer != null) { defaultConsumer.accept(absSender, message); return true; } } } return false; }
java
public final boolean executeCommand(AbsSender absSender, Message message) { if (message.hasText()) { String text = message.getText(); if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) { String commandMessage = text.substring(1); String[] commandSplit = commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR_REGEXP); String command = removeUsernameFromCommandIfNeeded(commandSplit[0]); if (commandRegistryMap.containsKey(command)) { String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length); commandRegistryMap.get(command).processMessage(absSender, message, parameters); return true; } else if (defaultConsumer != null) { defaultConsumer.accept(absSender, message); return true; } } } return false; }
[ "public", "final", "boolean", "executeCommand", "(", "AbsSender", "absSender", ",", "Message", "message", ")", "{", "if", "(", "message", ".", "hasText", "(", ")", ")", "{", "String", "text", "=", "message", ".", "getText", "(", ")", ";", "if", "(", "t...
Executes a command action if the command is registered. @note If the command is not registered and there is a default consumer, that action will be performed @param absSender absSender @param message input message @return True if a command or default action is executed, false otherwise
[ "Executes", "a", "command", "action", "if", "the", "command", "is", "registered", "." ]
train
https://github.com/rubenlagus/TelegramBots/blob/d62354915d7664597a40fd9858f16bce67ef1478/telegrambots-extensions/src/main/java/org/telegram/telegrambots/extensions/bots/commandbot/commands/CommandRegistry.java#L95-L115
cdk/cdk
base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/QueryChemObject.java
QueryChemObject.setProperty
@Override public void setProperty(Object description, Object property) { lazyProperties().put(description, property); notifyChanged(); }
java
@Override public void setProperty(Object description, Object property) { lazyProperties().put(description, property); notifyChanged(); }
[ "@", "Override", "public", "void", "setProperty", "(", "Object", "description", ",", "Object", "property", ")", "{", "lazyProperties", "(", ")", ".", "put", "(", "description", ",", "property", ")", ";", "notifyChanged", "(", ")", ";", "}" ]
Sets a property for a IChemObject. @param description An object description of the property (most likely a unique string) @param property An object with the property itself @see #getProperty @see #removeProperty
[ "Sets", "a", "property", "for", "a", "IChemObject", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/QueryChemObject.java#L191-L195
aspectran/aspectran
core/src/main/java/com/aspectran/core/component/aspect/pointcut/AbstractPointcut.java
AbstractPointcut.matches
protected boolean matches(PointcutPatternRule pointcutPatternRule, String transletName, String beanId, String className, String methodName) { if ((transletName == null && pointcutPatternRule.getTransletNamePattern() != null) || (beanId == null && pointcutPatternRule.getBeanIdPattern() != null) || (className == null && pointcutPatternRule.getClassNamePattern() != null) || (methodName == null && pointcutPatternRule.getMethodNamePattern() != null)) { return false; } else { return exists(pointcutPatternRule, transletName, beanId, className, methodName); } }
java
protected boolean matches(PointcutPatternRule pointcutPatternRule, String transletName, String beanId, String className, String methodName) { if ((transletName == null && pointcutPatternRule.getTransletNamePattern() != null) || (beanId == null && pointcutPatternRule.getBeanIdPattern() != null) || (className == null && pointcutPatternRule.getClassNamePattern() != null) || (methodName == null && pointcutPatternRule.getMethodNamePattern() != null)) { return false; } else { return exists(pointcutPatternRule, transletName, beanId, className, methodName); } }
[ "protected", "boolean", "matches", "(", "PointcutPatternRule", "pointcutPatternRule", ",", "String", "transletName", ",", "String", "beanId", ",", "String", "className", ",", "String", "methodName", ")", "{", "if", "(", "(", "transletName", "==", "null", "&&", "...
Returns whether or not corresponding to the point cut pattern rules. It is recognized to {@code true} if the operands are {@code null}. @param pointcutPatternRule the pointcut pattern @param transletName the translet name @param beanId the bean id @param className the bean class name @param methodName the name of the method that is executed in the bean @return true, if exists matched
[ "Returns", "whether", "or", "not", "corresponding", "to", "the", "point", "cut", "pattern", "rules", ".", "It", "is", "recognized", "to", "{", "@code", "true", "}", "if", "the", "operands", "are", "{", "@code", "null", "}", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/component/aspect/pointcut/AbstractPointcut.java#L100-L110
ManfredTremmel/gwt-bean-validators
mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/MustNotBeEqualValidator.java
MustNotBeEqualValidator.isValid
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { if (pvalue == null) { return true; } try { final Object field1Value = BeanPropertyReaderUtil.getNullSaveProperty(pvalue, field1Name); final Object field2Value = BeanPropertyReaderUtil.getNullSaveProperty(pvalue, field2Name); if ((field1Value == null || field1Value instanceof String && StringUtils.isEmpty((String) field1Value)) && (field2Value == null || field2Value instanceof String && StringUtils.isEmpty((String) field2Value))) { return true; } if (Objects.equals(field1Value, field2Value)) { switchContext(pcontext); return false; } return true; } catch (final Exception ignore) { switchContext(pcontext); return false; } }
java
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { if (pvalue == null) { return true; } try { final Object field1Value = BeanPropertyReaderUtil.getNullSaveProperty(pvalue, field1Name); final Object field2Value = BeanPropertyReaderUtil.getNullSaveProperty(pvalue, field2Name); if ((field1Value == null || field1Value instanceof String && StringUtils.isEmpty((String) field1Value)) && (field2Value == null || field2Value instanceof String && StringUtils.isEmpty((String) field2Value))) { return true; } if (Objects.equals(field1Value, field2Value)) { switchContext(pcontext); return false; } return true; } catch (final Exception ignore) { switchContext(pcontext); return false; } }
[ "@", "Override", "public", "final", "boolean", "isValid", "(", "final", "Object", "pvalue", ",", "final", "ConstraintValidatorContext", "pcontext", ")", "{", "if", "(", "pvalue", "==", "null", ")", "{", "return", "true", ";", "}", "try", "{", "final", "Obj...
{@inheritDoc} check if given object is valid. @see javax.validation.ConstraintValidator#isValid(Object, javax.validation.ConstraintValidatorContext)
[ "{", "@inheritDoc", "}", "check", "if", "given", "object", "is", "valid", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/MustNotBeEqualValidator.java#L79-L102
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ffdc/SibDiagnosticModule.java
SibDiagnosticModule.ffdcDumpDefault
public void ffdcDumpDefault(Throwable t, IncidentStream is, Object callerThis, Object[] objs, String sourceId) { is.writeLine("SIB FFDC dump for:", t); captureDefaultInformation(is,t); if (callerThis != null) { is.writeLine("SibDiagnosticModule :: Dump of callerThis (DiagnosticModule)", toFFDCString(callerThis)); //255802 is.introspectAndWriteLine("Introspection of callerThis:", callerThis); //255802 } if (objs != null) { for (int i = 0; i < objs.length; i++) { is.writeLine("callerArg (DiagnosticModule) [" + i + "]", //255802 toFFDCString(objs[i])); //287897 is.introspectAndWriteLine("callerArg [" + i + "] (Introspection)", objs[i]); //255802 } } }
java
public void ffdcDumpDefault(Throwable t, IncidentStream is, Object callerThis, Object[] objs, String sourceId) { is.writeLine("SIB FFDC dump for:", t); captureDefaultInformation(is,t); if (callerThis != null) { is.writeLine("SibDiagnosticModule :: Dump of callerThis (DiagnosticModule)", toFFDCString(callerThis)); //255802 is.introspectAndWriteLine("Introspection of callerThis:", callerThis); //255802 } if (objs != null) { for (int i = 0; i < objs.length; i++) { is.writeLine("callerArg (DiagnosticModule) [" + i + "]", //255802 toFFDCString(objs[i])); //287897 is.introspectAndWriteLine("callerArg [" + i + "] (Introspection)", objs[i]); //255802 } } }
[ "public", "void", "ffdcDumpDefault", "(", "Throwable", "t", ",", "IncidentStream", "is", ",", "Object", "callerThis", ",", "Object", "[", "]", "objs", ",", "String", "sourceId", ")", "{", "is", ".", "writeLine", "(", "\"SIB FFDC dump for:\"", ",", "t", ")", ...
Capture information about this problem into the incidentStream @param t The exception which triggered the FFDC capture process. @param is The IncidentStream. Data to be captured is written to this stream. @param callerThis The 'this' pointer for the object which invoked the filter. The value will be null if the method which invoked the filter was static, or if the method which invoked the filter does not correspond to the DM being invoked. @param objs The value of the array may be null. If not null, it contains an array of objects which the caller to the filter provided. Since the information in the array may vary depending upon the location in the code, the first index of the array may contain hints as to the content of the rest of the array. @param sourceId The sourceId passed to the filter.
[ "Capture", "information", "about", "this", "problem", "into", "the", "incidentStream" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ffdc/SibDiagnosticModule.java#L255-L277
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/ContainerKeyIndex.java
ContainerKeyIndex.notifyIndexOffsetChanged
void notifyIndexOffsetChanged(long segmentId, long indexOffset) { this.cache.updateSegmentIndexOffset(segmentId, indexOffset); this.recoveryTracker.updateSegmentIndexOffset(segmentId, indexOffset); }
java
void notifyIndexOffsetChanged(long segmentId, long indexOffset) { this.cache.updateSegmentIndexOffset(segmentId, indexOffset); this.recoveryTracker.updateSegmentIndexOffset(segmentId, indexOffset); }
[ "void", "notifyIndexOffsetChanged", "(", "long", "segmentId", ",", "long", "indexOffset", ")", "{", "this", ".", "cache", ".", "updateSegmentIndexOffset", "(", "segmentId", ",", "indexOffset", ")", ";", "this", ".", "recoveryTracker", ".", "updateSegmentIndexOffset"...
Notifies this ContainerKeyIndex instance that the {@link TableAttributes#INDEX_OFFSET} attribute value for the given Segment has been changed. @param segmentId The Id of the Segment whose Index Offset has changed. @param indexOffset The new value for the Index Offset. A negative value indicates this segment has been evicted from memory and relevant resources can be freed.
[ "Notifies", "this", "ContainerKeyIndex", "instance", "that", "the", "{", "@link", "TableAttributes#INDEX_OFFSET", "}", "attribute", "value", "for", "the", "given", "Segment", "has", "been", "changed", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/ContainerKeyIndex.java#L489-L492
beihaifeiwu/dolphin
dolphin-common/src/main/java/com/freetmp/common/asm/ClassReader.java
ClassReader.readConst
public Object readConst(final int item, final char[] buf) { int index = items[item]; switch (b[index - 1]) { case ClassWriter.INT: return readInt(index); case ClassWriter.FLOAT: return Float.intBitsToFloat(readInt(index)); case ClassWriter.LONG: return readLong(index); case ClassWriter.DOUBLE: return Double.longBitsToDouble(readLong(index)); case ClassWriter.CLASS: return Type.getObjectType(readUTF8(index, buf)); case ClassWriter.STR: return readUTF8(index, buf); case ClassWriter.MTYPE: return Type.getMethodType(readUTF8(index, buf)); default: // case ClassWriter.HANDLE_BASE + [1..9]: int tag = readByte(index); int[] items = this.items; int cpIndex = items[readUnsignedShort(index + 1)]; String owner = readClass(cpIndex, buf); cpIndex = items[readUnsignedShort(cpIndex + 2)]; String name = readUTF8(cpIndex, buf); String desc = readUTF8(cpIndex + 2, buf); return new Handle(tag, owner, name, desc); } }
java
public Object readConst(final int item, final char[] buf) { int index = items[item]; switch (b[index - 1]) { case ClassWriter.INT: return readInt(index); case ClassWriter.FLOAT: return Float.intBitsToFloat(readInt(index)); case ClassWriter.LONG: return readLong(index); case ClassWriter.DOUBLE: return Double.longBitsToDouble(readLong(index)); case ClassWriter.CLASS: return Type.getObjectType(readUTF8(index, buf)); case ClassWriter.STR: return readUTF8(index, buf); case ClassWriter.MTYPE: return Type.getMethodType(readUTF8(index, buf)); default: // case ClassWriter.HANDLE_BASE + [1..9]: int tag = readByte(index); int[] items = this.items; int cpIndex = items[readUnsignedShort(index + 1)]; String owner = readClass(cpIndex, buf); cpIndex = items[readUnsignedShort(cpIndex + 2)]; String name = readUTF8(cpIndex, buf); String desc = readUTF8(cpIndex + 2, buf); return new Handle(tag, owner, name, desc); } }
[ "public", "Object", "readConst", "(", "final", "int", "item", ",", "final", "char", "[", "]", "buf", ")", "{", "int", "index", "=", "items", "[", "item", "]", ";", "switch", "(", "b", "[", "index", "-", "1", "]", ")", "{", "case", "ClassWriter", ...
Reads a numeric or string constant pool item in {@link #b b}. <i>This method is intended for {@link Attribute} sub classes, and is normally not needed by class generators or adapters.</i> @param item the index of a constant pool item. @param buf buffer to be used to read the item. This buffer must be sufficiently large. It is not automatically resized. @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, {@link Type} or {@link Handle} corresponding to the given constant pool item.
[ "Reads", "a", "numeric", "or", "string", "constant", "pool", "item", "in", "{", "@link", "#b", "b", "}", ".", "<i", ">", "This", "method", "is", "intended", "for", "{", "@link", "Attribute", "}", "sub", "classes", "and", "is", "normally", "not", "neede...
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/asm/ClassReader.java#L2479-L2506
dmak/jaxb-xew-plugin
src/main/java/com/sun/tools/xjc/addon/xew/CommonUtils.java
CommonUtils.isListedAsParametrisation
public static boolean isListedAsParametrisation(JClass classToCheck, JType type) { return type instanceof JClass && ((JClass) type).getTypeParameters().contains(classToCheck); }
java
public static boolean isListedAsParametrisation(JClass classToCheck, JType type) { return type instanceof JClass && ((JClass) type).getTypeParameters().contains(classToCheck); }
[ "public", "static", "boolean", "isListedAsParametrisation", "(", "JClass", "classToCheck", ",", "JType", "type", ")", "{", "return", "type", "instanceof", "JClass", "&&", "(", "(", "JClass", ")", "type", ")", ".", "getTypeParameters", "(", ")", ".", "contains"...
Returns <code>true</code> of the given <code>type</code> is {@link JClass} and contains <code>classToCheck</code> in the list of parametrisations.
[ "Returns", "<code", ">", "true<", "/", "code", ">", "of", "the", "given", "<code", ">", "type<", "/", "code", ">", "is", "{" ]
train
https://github.com/dmak/jaxb-xew-plugin/blob/d564d6bf8e50c46b056cdb4b46d1d4bee4adfbe3/src/main/java/com/sun/tools/xjc/addon/xew/CommonUtils.java#L49-L51
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/MasterSlaveUtils.java
MasterSlaveUtils.findNodeByUri
static RedisNodeDescription findNodeByUri(Collection<RedisNodeDescription> nodes, RedisURI lookupUri) { return findNodeByHostAndPort(nodes, lookupUri.getHost(), lookupUri.getPort()); }
java
static RedisNodeDescription findNodeByUri(Collection<RedisNodeDescription> nodes, RedisURI lookupUri) { return findNodeByHostAndPort(nodes, lookupUri.getHost(), lookupUri.getPort()); }
[ "static", "RedisNodeDescription", "findNodeByUri", "(", "Collection", "<", "RedisNodeDescription", ">", "nodes", ",", "RedisURI", "lookupUri", ")", "{", "return", "findNodeByHostAndPort", "(", "nodes", ",", "lookupUri", ".", "getHost", "(", ")", ",", "lookupUri", ...
Lookup a {@link RedisNodeDescription} by {@link RedisURI}. @param nodes @param lookupUri @return the {@link RedisNodeDescription} or {@literal null}
[ "Lookup", "a", "{", "@link", "RedisNodeDescription", "}", "by", "{", "@link", "RedisURI", "}", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/MasterSlaveUtils.java#L60-L62
lucee/Lucee
core/src/main/java/lucee/runtime/op/date/DateCaster.java
DateCaster.toDateTime
public static DateTime toDateTime(Locale locale, String str, TimeZone tz, boolean useCommomDateParserAsWell) throws PageException { DateTime dt = toDateTime(locale, str, tz, null, useCommomDateParserAsWell); if (dt == null) { String prefix = locale.getLanguage() + "-" + locale.getCountry() + "-"; throw new ExpressionException("can't cast [" + str + "] to date value", "to add custom formats for " + LocaleFactory.toString(locale) + ", create/extend on of the following files [" + prefix + "datetime.df (for date time formats), " + prefix + "date.df (for date formats) or " + prefix + "time.df (for time formats)] in the following directory [<context>/lucee/locales]." + ""); // throw new ExpressionException("can't cast ["+str+"] to date value"); } return dt; }
java
public static DateTime toDateTime(Locale locale, String str, TimeZone tz, boolean useCommomDateParserAsWell) throws PageException { DateTime dt = toDateTime(locale, str, tz, null, useCommomDateParserAsWell); if (dt == null) { String prefix = locale.getLanguage() + "-" + locale.getCountry() + "-"; throw new ExpressionException("can't cast [" + str + "] to date value", "to add custom formats for " + LocaleFactory.toString(locale) + ", create/extend on of the following files [" + prefix + "datetime.df (for date time formats), " + prefix + "date.df (for date formats) or " + prefix + "time.df (for time formats)] in the following directory [<context>/lucee/locales]." + ""); // throw new ExpressionException("can't cast ["+str+"] to date value"); } return dt; }
[ "public", "static", "DateTime", "toDateTime", "(", "Locale", "locale", ",", "String", "str", ",", "TimeZone", "tz", ",", "boolean", "useCommomDateParserAsWell", ")", "throws", "PageException", "{", "DateTime", "dt", "=", "toDateTime", "(", "locale", ",", "str", ...
parse a string to a Datetime Object @param locale @param str String representation of a locale Date @param tz @return DateTime Object @throws PageException
[ "parse", "a", "string", "to", "a", "Datetime", "Object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/date/DateCaster.java#L186-L198
paoding-code/paoding-rose
paoding-rose-jade/src/main/java/net/paoding/rose/jade/statement/expression/impl/ExqlCompiler.java
ExqlCompiler.findRightBrace
private int findRightBrace(char chLeft, char chRight, int fromIndex) { int level = 0; // 记录括号重叠级别。 // 查找匹配的右括号。 for (int index = fromIndex; index < length; index++) { char ch = pattern.charAt(index); // 如果出现左括号,重叠级别增加。 if (ch == chLeft) { level++; } // 如果出现右括号,重叠级别降低。 else if (ch == chRight) { if (level == 0) { // 找到右括号。 return index; } level--; } } // 没有找到匹配的括号。 return -1; }
java
private int findRightBrace(char chLeft, char chRight, int fromIndex) { int level = 0; // 记录括号重叠级别。 // 查找匹配的右括号。 for (int index = fromIndex; index < length; index++) { char ch = pattern.charAt(index); // 如果出现左括号,重叠级别增加。 if (ch == chLeft) { level++; } // 如果出现右括号,重叠级别降低。 else if (ch == chRight) { if (level == 0) { // 找到右括号。 return index; } level--; } } // 没有找到匹配的括号。 return -1; }
[ "private", "int", "findRightBrace", "(", "char", "chLeft", ",", "char", "chRight", ",", "int", "fromIndex", ")", "{", "int", "level", "=", "0", ";", "// 记录括号重叠级别。", "// 查找匹配的右括号。", "for", "(", "int", "index", "=", "fromIndex", ";", "index", "<", "length", ...
查找匹配的右括号, 可以用于匹配 '{}', '[]', '()' 括号对。 如果未找到匹配的右括号,函数返回 -1. @param string - 查找的字符串 @param chLeft - 匹配的左括号 @param chRight - 匹配的右括号 @param fromIndex - 查找的起始位置 @return 右括号的位置, 如果未找到匹配的右括号,函数返回 -1.
[ "查找匹配的右括号", "可以用于匹配", "{}", "[]", "()", "括号对。" ]
train
https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-jade/src/main/java/net/paoding/rose/jade/statement/expression/impl/ExqlCompiler.java#L319-L346
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.security/src/com/ibm/ws/messaging/security/internal/MessagingSecurityServiceImpl.java
MessagingSecurityServiceImpl.printDestinationPermissions
private void printDestinationPermissions(Map<String, ?> destinationPermissions) { Set<String> destinations = destinationPermissions.keySet(); for (String destination : destinations) { SibTr.debug(tc, CLASS_NAME + " Destination: " + destination); Permission permission = (Permission) destinationPermissions.get(destination); SibTr.debug(tc, " Users having permissions!!!"); Map<String, Set<String>> userRoles = permission.getRoleToUserMap(); Set<String> uRoles = userRoles.keySet(); for (String role : uRoles) { SibTr.debug(tc, " " + role + ": " + userRoles.get(role)); } SibTr.debug(tc, " Groups having permissions!!!"); Map<String, Set<String>> groupRoles = permission .getRoleToGroupMap(); Set<String> gRoles = groupRoles.keySet(); for (String role : gRoles) { SibTr.debug(tc, " " + role + ": " + groupRoles.get(role)); } } }
java
private void printDestinationPermissions(Map<String, ?> destinationPermissions) { Set<String> destinations = destinationPermissions.keySet(); for (String destination : destinations) { SibTr.debug(tc, CLASS_NAME + " Destination: " + destination); Permission permission = (Permission) destinationPermissions.get(destination); SibTr.debug(tc, " Users having permissions!!!"); Map<String, Set<String>> userRoles = permission.getRoleToUserMap(); Set<String> uRoles = userRoles.keySet(); for (String role : uRoles) { SibTr.debug(tc, " " + role + ": " + userRoles.get(role)); } SibTr.debug(tc, " Groups having permissions!!!"); Map<String, Set<String>> groupRoles = permission .getRoleToGroupMap(); Set<String> gRoles = groupRoles.keySet(); for (String role : gRoles) { SibTr.debug(tc, " " + role + ": " + groupRoles.get(role)); } } }
[ "private", "void", "printDestinationPermissions", "(", "Map", "<", "String", ",", "?", ">", "destinationPermissions", ")", "{", "Set", "<", "String", ">", "destinations", "=", "destinationPermissions", ".", "keySet", "(", ")", ";", "for", "(", "String", "desti...
Print the Destination Permissions, it will be used for debugging purpose
[ "Print", "the", "Destination", "Permissions", "it", "will", "be", "used", "for", "debugging", "purpose" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.security/src/com/ibm/ws/messaging/security/internal/MessagingSecurityServiceImpl.java#L624-L643
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Instant.java
Instant.plus
private Instant plus(long secondsToAdd, long nanosToAdd) { if ((secondsToAdd | nanosToAdd) == 0) { return this; } long epochSec = Math.addExact(seconds, secondsToAdd); epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); nanosToAdd = nanosToAdd % NANOS_PER_SECOND; long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND return ofEpochSecond(epochSec, nanoAdjustment); }
java
private Instant plus(long secondsToAdd, long nanosToAdd) { if ((secondsToAdd | nanosToAdd) == 0) { return this; } long epochSec = Math.addExact(seconds, secondsToAdd); epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); nanosToAdd = nanosToAdd % NANOS_PER_SECOND; long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND return ofEpochSecond(epochSec, nanoAdjustment); }
[ "private", "Instant", "plus", "(", "long", "secondsToAdd", ",", "long", "nanosToAdd", ")", "{", "if", "(", "(", "secondsToAdd", "|", "nanosToAdd", ")", "==", "0", ")", "{", "return", "this", ";", "}", "long", "epochSec", "=", "Math", ".", "addExact", "...
Returns a copy of this instant with the specified duration added. <p> This instance is immutable and unaffected by this method call. @param secondsToAdd the seconds to add, positive or negative @param nanosToAdd the nanos to add, positive or negative @return an {@code Instant} based on this instant with the specified seconds added, not null @throws DateTimeException if the result exceeds the maximum or minimum instant @throws ArithmeticException if numeric overflow occurs
[ "Returns", "a", "copy", "of", "this", "instant", "with", "the", "specified", "duration", "added", ".", "<p", ">", "This", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "call", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Instant.java#L915-L924
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLAnnotationUtil.java
SARLAnnotationUtil.findAnnotation
@SuppressWarnings("static-method") public JvmAnnotationReference findAnnotation(JvmAnnotationTarget annotationTarget, String lookupType) { // avoid creating an empty list for all given targets but check for #eIsSet first if (annotationTarget.eIsSet(TypesPackage.Literals.JVM_ANNOTATION_TARGET__ANNOTATIONS)) { for (final JvmAnnotationReference annotation: annotationTarget.getAnnotations()) { final JvmAnnotationType annotationType = annotation.getAnnotation(); if (annotationType != null && Objects.equals(lookupType, annotationType.getQualifiedName())) { return annotation; } } } return null; }
java
@SuppressWarnings("static-method") public JvmAnnotationReference findAnnotation(JvmAnnotationTarget annotationTarget, String lookupType) { // avoid creating an empty list for all given targets but check for #eIsSet first if (annotationTarget.eIsSet(TypesPackage.Literals.JVM_ANNOTATION_TARGET__ANNOTATIONS)) { for (final JvmAnnotationReference annotation: annotationTarget.getAnnotations()) { final JvmAnnotationType annotationType = annotation.getAnnotation(); if (annotationType != null && Objects.equals(lookupType, annotationType.getQualifiedName())) { return annotation; } } } return null; }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "public", "JvmAnnotationReference", "findAnnotation", "(", "JvmAnnotationTarget", "annotationTarget", ",", "String", "lookupType", ")", "{", "// avoid creating an empty list for all given targets but check for #eIsSet first", ...
Find an annotation. @param annotationTarget the annotation target. @param lookupType the name of the type to look for. @return the annotation or {@code null}. @see AnnotationLookup#findAnnotation(JvmAnnotationTarget, Class)
[ "Find", "an", "annotation", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLAnnotationUtil.java#L251-L263
alkacon/opencms-core
src/org/opencms/security/CmsDefaultAuthorizationHandler.java
CmsDefaultAuthorizationHandler.requestAuthorization
public void requestAuthorization(HttpServletRequest req, HttpServletResponse res, String loginFormURL) throws IOException { CmsHttpAuthenticationSettings httpAuthenticationSettings = OpenCms.getSystemInfo().getHttpAuthenticationSettings(); if (loginFormURL == null) { if (httpAuthenticationSettings.useBrowserBasedHttpAuthentication()) { // HTTP basic authentication is used res.setHeader( CmsRequestUtil.HEADER_WWW_AUTHENTICATE, "BASIC realm=\"" + OpenCms.getSystemInfo().getOpenCmsContext() + "\""); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } else if (httpAuthenticationSettings.getFormBasedHttpAuthenticationUri() != null) { loginFormURL = httpAuthenticationSettings.getFormBasedHttpAuthenticationUri(); } else { LOG.error( Messages.get().getBundle().key( Messages.ERR_UNSUPPORTED_AUTHENTICATION_MECHANISM_1, httpAuthenticationSettings.getBrowserBasedAuthenticationMechanism())); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_AUTHENTICATE_PROPERTY_2, loginFormURL, req.getRequestURI())); } // finally redirect to the login form res.sendRedirect(loginFormURL); }
java
public void requestAuthorization(HttpServletRequest req, HttpServletResponse res, String loginFormURL) throws IOException { CmsHttpAuthenticationSettings httpAuthenticationSettings = OpenCms.getSystemInfo().getHttpAuthenticationSettings(); if (loginFormURL == null) { if (httpAuthenticationSettings.useBrowserBasedHttpAuthentication()) { // HTTP basic authentication is used res.setHeader( CmsRequestUtil.HEADER_WWW_AUTHENTICATE, "BASIC realm=\"" + OpenCms.getSystemInfo().getOpenCmsContext() + "\""); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } else if (httpAuthenticationSettings.getFormBasedHttpAuthenticationUri() != null) { loginFormURL = httpAuthenticationSettings.getFormBasedHttpAuthenticationUri(); } else { LOG.error( Messages.get().getBundle().key( Messages.ERR_UNSUPPORTED_AUTHENTICATION_MECHANISM_1, httpAuthenticationSettings.getBrowserBasedAuthenticationMechanism())); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_AUTHENTICATE_PROPERTY_2, loginFormURL, req.getRequestURI())); } // finally redirect to the login form res.sendRedirect(loginFormURL); }
[ "public", "void", "requestAuthorization", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ",", "String", "loginFormURL", ")", "throws", "IOException", "{", "CmsHttpAuthenticationSettings", "httpAuthenticationSettings", "=", "OpenCms", ".", "getSystemInf...
This method sends a request to the client to display a login form, it is needed for HTTP-Authentication.<p> @param req the client request @param res the response @param loginFormURL the full URL used for form based authentication @throws IOException if something goes wrong
[ "This", "method", "sends", "a", "request", "to", "the", "client", "to", "display", "a", "login", "form", "it", "is", "needed", "for", "HTTP", "-", "Authentication", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsDefaultAuthorizationHandler.java#L144-L179
SonarOpenCommunity/sonar-cxx
cxx-sensors/src/main/java/org/sonar/cxx/sensors/utils/CxxReportSensor.java
CxxReportSensor.resolveFilename
@Nullable public static String resolveFilename(final String baseDir, @Nullable final String filename) { if (filename != null) { // Normalization can return null if path is null, is invalid, // or is a path with back-ticks outside known directory structure String normalizedPath = FilenameUtils.normalize(filename); if ((normalizedPath != null) && (new File(normalizedPath).isAbsolute())) { return normalizedPath; } // Prefix with absolute module base directory, attempt normalization again -- can still get null here normalizedPath = FilenameUtils.normalize(baseDir + File.separator + filename); if (normalizedPath != null) { return normalizedPath; } } return null; }
java
@Nullable public static String resolveFilename(final String baseDir, @Nullable final String filename) { if (filename != null) { // Normalization can return null if path is null, is invalid, // or is a path with back-ticks outside known directory structure String normalizedPath = FilenameUtils.normalize(filename); if ((normalizedPath != null) && (new File(normalizedPath).isAbsolute())) { return normalizedPath; } // Prefix with absolute module base directory, attempt normalization again -- can still get null here normalizedPath = FilenameUtils.normalize(baseDir + File.separator + filename); if (normalizedPath != null) { return normalizedPath; } } return null; }
[ "@", "Nullable", "public", "static", "String", "resolveFilename", "(", "final", "String", "baseDir", ",", "@", "Nullable", "final", "String", "filename", ")", "{", "if", "(", "filename", "!=", "null", ")", "{", "// Normalization can return null if path is null, is i...
resolveFilename normalizes the report full path @param baseDir of the project @param filename of the report @return String
[ "resolveFilename", "normalizes", "the", "report", "full", "path" ]
train
https://github.com/SonarOpenCommunity/sonar-cxx/blob/7e7a3a44d6d86382a0434652a798f8235503c9b8/cxx-sensors/src/main/java/org/sonar/cxx/sensors/utils/CxxReportSensor.java#L86-L104
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfStamper.java
PdfStamper.createSignature
public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion) throws DocumentException, IOException { return createSignature(reader, os, pdfVersion, null, false); }
java
public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion) throws DocumentException, IOException { return createSignature(reader, os, pdfVersion, null, false); }
[ "public", "static", "PdfStamper", "createSignature", "(", "PdfReader", "reader", ",", "OutputStream", "os", ",", "char", "pdfVersion", ")", "throws", "DocumentException", ",", "IOException", "{", "return", "createSignature", "(", "reader", ",", "os", ",", "pdfVers...
Applies a digital signature to a document. The returned PdfStamper can be used normally as the signature is only applied when closing. <p> Note that the pdf is created in memory. <p> A possible use is: <p> <pre> KeyStore ks = KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray()); String alias = (String)ks.aliases().nextElement(); PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); PdfReader reader = new PdfReader("original.pdf"); FileOutputStream fout = new FileOutputStream("signed.pdf"); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("I'm the author"); sap.setLocation("Lisbon"); // comment next line to have an invisible signature sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); stp.close(); </pre> @param reader the original document @param os the output stream @param pdfVersion the new pdf version or '\0' to keep the same version as the original document @throws DocumentException on error @throws IOException on error @return a <CODE>PdfStamper</CODE>
[ "Applies", "a", "digital", "signature", "to", "a", "document", ".", "The", "returned", "PdfStamper", "can", "be", "used", "normally", "as", "the", "signature", "is", "only", "applied", "when", "closing", ".", "<p", ">", "Note", "that", "the", "pdf", "is", ...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfStamper.java#L718-L720
sdl/Testy
src/main/java/com/sdl/selenium/web/XPathBuilder.java
XPathBuilder.setText
@SuppressWarnings("unchecked") public <T extends XPathBuilder> T setText(final String text, final SearchType... searchTypes) { this.text = text; // notSupportedForCss(text, "text"); // if(text == null) { // xpath.remove("text"); // } else { // xpath.add("text"); // } setSearchTextType(searchTypes); return (T) this; }
java
@SuppressWarnings("unchecked") public <T extends XPathBuilder> T setText(final String text, final SearchType... searchTypes) { this.text = text; // notSupportedForCss(text, "text"); // if(text == null) { // xpath.remove("text"); // } else { // xpath.add("text"); // } setSearchTextType(searchTypes); return (T) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "XPathBuilder", ">", "T", "setText", "(", "final", "String", "text", ",", "final", "SearchType", "...", "searchTypes", ")", "{", "this", ".", "text", "=", "text", ";", "// ...
<p><b>Used for finding element process (to generate xpath address)</b></p> @param text with which to identify the item @param searchTypes type search text element: see more details see {@link SearchType} @param <T> the element which calls this method @return this element
[ "<p", ">", "<b", ">", "Used", "for", "finding", "element", "process", "(", "to", "generate", "xpath", "address", ")", "<", "/", "b", ">", "<", "/", "p", ">" ]
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/XPathBuilder.java#L257-L268
geomajas/geomajas-project-server
impl/src/main/java/org/geomajas/internal/rendering/painter/tile/StringContentTilePainter.java
StringContentTilePainter.createFeatureDocument
private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer())); document.registerWriter(InternalTileImpl.class, new SvgTileWriter()); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
java
private GraphicsDocument createFeatureDocument(StringWriter writer) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalFeatureImpl.class, new SvgFeatureWriter(getTransformer())); document.registerWriter(InternalTileImpl.class, new SvgTileWriter()); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlTileWriter(coordWidth, coordHeight)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
[ "private", "GraphicsDocument", "createFeatureDocument", "(", "StringWriter", "writer", ")", "throws", "RenderException", "{", "if", "(", "TileMetadata", ".", "PARAM_SVG_RENDERER", ".", "equalsIgnoreCase", "(", "renderer", ")", ")", "{", "DefaultSvgDocument", "document",...
Create a document that parses the tile's featureFragment, using GraphicsWriter classes. @param writer writer @return document @throws RenderException oops
[ "Create", "a", "document", "that", "parses", "the", "tile", "s", "featureFragment", "using", "GraphicsWriter", "classes", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/internal/rendering/painter/tile/StringContentTilePainter.java#L250-L269
playn/playn
android/src/playn/android/AndroidGraphics.java
AndroidGraphics.registerFont
public void registerFont(Typeface face, String name, Font.Style style, String... ligatureGlyphs) { Pair<String,Font.Style> key = Pair.create(name, style); fonts.put(key, face); ligatureHacks.put(key, ligatureGlyphs); }
java
public void registerFont(Typeface face, String name, Font.Style style, String... ligatureGlyphs) { Pair<String,Font.Style> key = Pair.create(name, style); fonts.put(key, face); ligatureHacks.put(key, ligatureGlyphs); }
[ "public", "void", "registerFont", "(", "Typeface", "face", ",", "String", "name", ",", "Font", ".", "Style", "style", ",", "String", "...", "ligatureGlyphs", ")", "{", "Pair", "<", "String", ",", "Font", ".", "Style", ">", "key", "=", "Pair", ".", "cre...
Registers a font with the graphics system. @param face the typeface to be registered. It can be loaded via {@link AndroidAssets#getTypeface}. @param name the name under which to register the font. @param style the style variant of the specified name provided by the font file. For example one might {@code registerFont("myfont.ttf", "My Font", Font.Style.PLAIN)} and {@code registerFont("myfontb.ttf", "My Font", Font.Style.BOLD)} to provide both the plain and bold variants of a particular font. @param ligatureGlyphs any known text sequences that are converted into a single ligature character in this font. This works around an Android bug where measuring text for wrapping that contains character sequences that are converted into ligatures (e.g. "fi" or "ae") incorrectly reports the number of characters "consumed" from the to-be-wrapped string.
[ "Registers", "a", "font", "with", "the", "graphics", "system", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/android/src/playn/android/AndroidGraphics.java#L86-L90
aws/aws-sdk-java
aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/CreateConfigurationRequest.java
CreateConfigurationRequest.withTags
public CreateConfigurationRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public CreateConfigurationRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "CreateConfigurationRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
Create tags when creating the configuration. @param tags Create tags when creating the configuration. @return Returns a reference to this object so that method calls can be chained together.
[ "Create", "tags", "when", "creating", "the", "configuration", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/CreateConfigurationRequest.java#L205-L208
JodaOrg/joda-time
src/main/java/org/joda/time/YearMonthDay.java
YearMonthDay.withYear
public YearMonthDay withYear(int year) { int[] newValues = getValues(); newValues = getChronology().year().set(this, YEAR, newValues, year); return new YearMonthDay(this, newValues); }
java
public YearMonthDay withYear(int year) { int[] newValues = getValues(); newValues = getChronology().year().set(this, YEAR, newValues, year); return new YearMonthDay(this, newValues); }
[ "public", "YearMonthDay", "withYear", "(", "int", "year", ")", "{", "int", "[", "]", "newValues", "=", "getValues", "(", ")", ";", "newValues", "=", "getChronology", "(", ")", ".", "year", "(", ")", ".", "set", "(", "this", ",", "YEAR", ",", "newValu...
Returns a copy of this date with the year field updated. <p> YearMonthDay is immutable, so there are no set methods. Instead, this method returns a new instance with the value of year changed. @param year the year to set @return a copy of this object with the field set @throws IllegalArgumentException if the value is invalid @since 1.3
[ "Returns", "a", "copy", "of", "this", "date", "with", "the", "year", "field", "updated", ".", "<p", ">", "YearMonthDay", "is", "immutable", "so", "there", "are", "no", "set", "methods", ".", "Instead", "this", "method", "returns", "a", "new", "instance", ...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/YearMonthDay.java#L842-L846
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/dataflow/PlainChangesLogImpl.java
PlainChangesLogImpl.getItemState
public ItemState getItemState(String itemIdentifier, int state) { return index.get(new IDStateBasedKey(itemIdentifier, state)); }
java
public ItemState getItemState(String itemIdentifier, int state) { return index.get(new IDStateBasedKey(itemIdentifier, state)); }
[ "public", "ItemState", "getItemState", "(", "String", "itemIdentifier", ",", "int", "state", ")", "{", "return", "index", ".", "get", "(", "new", "IDStateBasedKey", "(", "itemIdentifier", ",", "state", ")", ")", ";", "}" ]
Get ItemState by identifier and state. NOTE: Uses index HashMap. @param itemIdentifier @param state @return
[ "Get", "ItemState", "by", "identifier", "and", "state", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/dataflow/PlainChangesLogImpl.java#L676-L679
jamesdbloom/mockserver
mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java
HttpResponse.replaceHeader
public HttpResponse replaceHeader(String name, String... values) { this.headers.replaceEntry(name, values); return this; }
java
public HttpResponse replaceHeader(String name, String... values) { this.headers.replaceEntry(name, values); return this; }
[ "public", "HttpResponse", "replaceHeader", "(", "String", "name", ",", "String", "...", "values", ")", "{", "this", ".", "headers", ".", "replaceEntry", "(", "name", ",", "values", ")", ";", "return", "this", ";", "}" ]
Update header to return as a Header object, if a header with the same name already exists it will be modified @param name the header name @param values the header values
[ "Update", "header", "to", "return", "as", "a", "Header", "object", "if", "a", "header", "with", "the", "same", "name", "already", "exists", "it", "will", "be", "modified" ]
train
https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpResponse.java#L258-L261
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/Searcher.java
Searcher.getLeadingZeros
private static String getLeadingZeros(int i, int size) { assert i <= size; int w1 = (int) Math.floor(Math.log10(size)); int w2 = (int) Math.floor(Math.log10(i)); String s = ""; for (int j = w2; j < w1; j++) { s += "0"; } return s; }
java
private static String getLeadingZeros(int i, int size) { assert i <= size; int w1 = (int) Math.floor(Math.log10(size)); int w2 = (int) Math.floor(Math.log10(i)); String s = ""; for (int j = w2; j < w1; j++) { s += "0"; } return s; }
[ "private", "static", "String", "getLeadingZeros", "(", "int", "i", ",", "int", "size", ")", "{", "assert", "i", "<=", "size", ";", "int", "w1", "=", "(", "int", ")", "Math", ".", "floor", "(", "Math", ".", "log10", "(", "size", ")", ")", ";", "in...
Prepares an int for printing with leading zeros for the given size. @param i the int to prepare @param size max value for i @return printable string for i with leading zeros
[ "Prepares", "an", "int", "for", "printing", "with", "leading", "zeros", "for", "the", "given", "size", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/Searcher.java#L417-L430
kaichunlin/android-transition
core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java
TransitionControllerManager.addAnimatorSetAsTransition
public TransitionController addAnimatorSetAsTransition(@Nullable View target, @NonNull AnimatorSet animatorSet) { return addTransitionController(new DefaultTransitionController(target, animatorSet)); }
java
public TransitionController addAnimatorSetAsTransition(@Nullable View target, @NonNull AnimatorSet animatorSet) { return addTransitionController(new DefaultTransitionController(target, animatorSet)); }
[ "public", "TransitionController", "addAnimatorSetAsTransition", "(", "@", "Nullable", "View", "target", ",", "@", "NonNull", "AnimatorSet", "animatorSet", ")", "{", "return", "addTransitionController", "(", "new", "DefaultTransitionController", "(", "target", ",", "anim...
Adds an AnimatorSet as {@link TransitionController} @param target @param animatorSet @return
[ "Adds", "an", "AnimatorSet", "as", "{", "@link", "TransitionController", "}" ]
train
https://github.com/kaichunlin/android-transition/blob/7b53074206622f5cf5d82091d891a7ed8b9f06cd/core/src/main/java/com/kaichunlin/transition/internal/TransitionControllerManager.java#L76-L78
zerodhatech/javakiteconnect
kiteconnect/src/com/zerodhatech/kiteconnect/KiteConnect.java
KiteConnect.cancelOrder
public Order cancelOrder(String orderId, String variety) throws KiteException, JSONException, IOException { String url = routes.get("orders.cancel").replace(":variety", variety).replace(":order_id", orderId); Map<String, Object> params = new HashMap<String, Object>(); JSONObject jsonObject = new KiteRequestHandler(proxy).deleteRequest(url, params, apiKey, accessToken); Order order = new Order(); order.orderId = jsonObject.getJSONObject("data").getString("order_id"); return order; }
java
public Order cancelOrder(String orderId, String variety) throws KiteException, JSONException, IOException { String url = routes.get("orders.cancel").replace(":variety", variety).replace(":order_id", orderId); Map<String, Object> params = new HashMap<String, Object>(); JSONObject jsonObject = new KiteRequestHandler(proxy).deleteRequest(url, params, apiKey, accessToken); Order order = new Order(); order.orderId = jsonObject.getJSONObject("data").getString("order_id"); return order; }
[ "public", "Order", "cancelOrder", "(", "String", "orderId", ",", "String", "variety", ")", "throws", "KiteException", ",", "JSONException", ",", "IOException", "{", "String", "url", "=", "routes", ".", "get", "(", "\"orders.cancel\"", ")", ".", "replace", "(",...
Cancels an order. @param orderId order id of the order to be cancelled. @param variety [variety="regular"]. Order variety can be bo, co, amo, regular. @return Order object contains only orderId. @throws KiteException is thrown for all Kite trade related errors. @throws JSONException is thrown when there is exception while parsing response. @throws IOException is thrown when there is connection error.
[ "Cancels", "an", "order", "." ]
train
https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/kiteconnect/KiteConnect.java#L334-L342
NoraUi/NoraUi
src/main/java/com/github/noraui/cucumber/interceptor/ConditionedInterceptor.java
ConditionedInterceptor.displayMessageAtTheBeginningOfMethod
private void displayMessageAtTheBeginningOfMethod(String methodName, List<GherkinStepCondition> conditions) { logger.debug("{} with {} contition(s)", methodName, conditions.size()); displayConditionsAtTheBeginningOfMethod(conditions); }
java
private void displayMessageAtTheBeginningOfMethod(String methodName, List<GherkinStepCondition> conditions) { logger.debug("{} with {} contition(s)", methodName, conditions.size()); displayConditionsAtTheBeginningOfMethod(conditions); }
[ "private", "void", "displayMessageAtTheBeginningOfMethod", "(", "String", "methodName", ",", "List", "<", "GherkinStepCondition", ">", "conditions", ")", "{", "logger", ".", "debug", "(", "\"{} with {} contition(s)\"", ",", "methodName", ",", "conditions", ".", "size"...
Display a message at the beginning of method. @param methodName is the name of method for logs @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
[ "Display", "a", "message", "at", "the", "beginning", "of", "method", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/cucumber/interceptor/ConditionedInterceptor.java#L63-L66
jbossas/remoting-jmx
src/main/java/org/jboss/remotingjmx/protocol/v1/Common.java
Common.prepareForUnMarshalling
protected Unmarshaller prepareForUnMarshalling(final DataInput dataInput, final ClassResolver classResolver) throws IOException { final Unmarshaller unmarshaller = this.getUnMarshaller(marshallerFactory, classResolver); final InputStream is = new InputStream() { @Override public int read() throws IOException { try { final int b = dataInput.readByte(); return b & 0xff; } catch (EOFException eof) { return -1; } } }; final ByteInput byteInput = Marshalling.createByteInput(is); // start the unmarshaller unmarshaller.start(byteInput); return unmarshaller; }
java
protected Unmarshaller prepareForUnMarshalling(final DataInput dataInput, final ClassResolver classResolver) throws IOException { final Unmarshaller unmarshaller = this.getUnMarshaller(marshallerFactory, classResolver); final InputStream is = new InputStream() { @Override public int read() throws IOException { try { final int b = dataInput.readByte(); return b & 0xff; } catch (EOFException eof) { return -1; } } }; final ByteInput byteInput = Marshalling.createByteInput(is); // start the unmarshaller unmarshaller.start(byteInput); return unmarshaller; }
[ "protected", "Unmarshaller", "prepareForUnMarshalling", "(", "final", "DataInput", "dataInput", ",", "final", "ClassResolver", "classResolver", ")", "throws", "IOException", "{", "final", "Unmarshaller", "unmarshaller", "=", "this", ".", "getUnMarshaller", "(", "marshal...
Creates and returns a {@link org.jboss.marshalling.Unmarshaller} which is ready to be used for unmarshalling. The {@link org.jboss.marshalling.Unmarshaller#start(org.jboss.marshalling.ByteInput)} will be invoked by this method, to use the passed {@link java.io.DataInput dataInput}, before returning the unmarshaller. @param dataInput The data input from which to unmarshall @param classResolver The class resolver to use for unmarshalling @return @throws IOException
[ "Creates", "and", "returns", "a", "{", "@link", "org", ".", "jboss", ".", "marshalling", ".", "Unmarshaller", "}", "which", "is", "ready", "to", "be", "used", "for", "unmarshalling", ".", "The", "{", "@link", "org", ".", "jboss", ".", "marshalling", ".",...
train
https://github.com/jbossas/remoting-jmx/blob/dbc87bfed47e5bb9e37c355a77ca0ae9a6ea1363/src/main/java/org/jboss/remotingjmx/protocol/v1/Common.java#L130-L150
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java
SearchUtils.findField
public static FieldNode findField(ClassNode classNode, String name) { Validate.notNull(classNode); Validate.notNull(name); Validate.notEmpty(name); return classNode.fields.stream() .filter(x -> name.equals(x.name)) .findAny().orElse(null); }
java
public static FieldNode findField(ClassNode classNode, String name) { Validate.notNull(classNode); Validate.notNull(name); Validate.notEmpty(name); return classNode.fields.stream() .filter(x -> name.equals(x.name)) .findAny().orElse(null); }
[ "public", "static", "FieldNode", "findField", "(", "ClassNode", "classNode", ",", "String", "name", ")", "{", "Validate", ".", "notNull", "(", "classNode", ")", ";", "Validate", ".", "notNull", "(", "name", ")", ";", "Validate", ".", "notEmpty", "(", "name...
Find field within a class by its name. @param classNode class to search @param name name to search for @return found field (or {@code null} if not found) @throws NullPointerException if any argument is {@code null} @throws IllegalArgumentException if {@code name} is empty
[ "Find", "field", "within", "a", "class", "by", "its", "name", "." ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/asm/SearchUtils.java#L540-L547
google/closure-templates
java/src/com/google/template/soy/types/SoyTypeRegistry.java
SoyTypeRegistry.getType
@Nullable public SoyType getType(String typeName) { SoyType result = BUILTIN_TYPES.get(typeName); if (result != null) { return result; } synchronized (lock) { result = protoTypeCache.get(typeName); if (result == null) { GenericDescriptor descriptor = descriptors.get(typeName); if (descriptor == null) { return null; } if (descriptor instanceof EnumDescriptor) { result = new SoyProtoEnumType((EnumDescriptor) descriptor); } else { result = new SoyProtoType(this, (Descriptor) descriptor, extensions.get(typeName)); } protoTypeCache.put(typeName, result); } } return result; }
java
@Nullable public SoyType getType(String typeName) { SoyType result = BUILTIN_TYPES.get(typeName); if (result != null) { return result; } synchronized (lock) { result = protoTypeCache.get(typeName); if (result == null) { GenericDescriptor descriptor = descriptors.get(typeName); if (descriptor == null) { return null; } if (descriptor instanceof EnumDescriptor) { result = new SoyProtoEnumType((EnumDescriptor) descriptor); } else { result = new SoyProtoType(this, (Descriptor) descriptor, extensions.get(typeName)); } protoTypeCache.put(typeName, result); } } return result; }
[ "@", "Nullable", "public", "SoyType", "getType", "(", "String", "typeName", ")", "{", "SoyType", "result", "=", "BUILTIN_TYPES", ".", "get", "(", "typeName", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "synchroniz...
Look up a type by name. Returns null if there is no such type. @param typeName The fully-qualified name of the type. @return The type object, or {@code null}.
[ "Look", "up", "a", "type", "by", "name", ".", "Returns", "null", "if", "there", "is", "no", "such", "type", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/types/SoyTypeRegistry.java#L176-L198
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java
SDNN.multiHeadDotProductAttention
public List<SDVariable> multiHeadDotProductAttention(SDVariable queries, SDVariable keys, SDVariable values, SDVariable Wq, SDVariable Wk, SDVariable Wv, SDVariable Wo, SDVariable mask, boolean scaled, boolean withWeights){ return multiHeadDotProductAttention(null, queries, keys, values, Wq, Wk, Wv, Wo, mask, scaled, withWeights); }
java
public List<SDVariable> multiHeadDotProductAttention(SDVariable queries, SDVariable keys, SDVariable values, SDVariable Wq, SDVariable Wk, SDVariable Wv, SDVariable Wo, SDVariable mask, boolean scaled, boolean withWeights){ return multiHeadDotProductAttention(null, queries, keys, values, Wq, Wk, Wv, Wo, mask, scaled, withWeights); }
[ "public", "List", "<", "SDVariable", ">", "multiHeadDotProductAttention", "(", "SDVariable", "queries", ",", "SDVariable", "keys", ",", "SDVariable", "values", ",", "SDVariable", "Wq", ",", "SDVariable", "Wk", ",", "SDVariable", "Wv", ",", "SDVariable", "Wo", ",...
This performs multi-headed dot product attention on the given timeseries input @see #multiHeadDotProductAttention(String, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, SDVariable, boolean, boolean)
[ "This", "performs", "multi", "-", "headed", "dot", "product", "attention", "on", "the", "given", "timeseries", "input" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java#L923-L925
Hygieia/Hygieia
collectors/artifact/artifactory/src/main/java/com/capitalone/dashboard/collector/DefaultArtifactoryClient.java
DefaultArtifactoryClient.createArtifact
private BinaryArtifact createArtifact(String artifactCanonicalName, String artifactPath, long timestamp, JSONObject jsonArtifact) { BinaryArtifact result = null; String fullPath = artifactPath + "/" + artifactCanonicalName; int idx = 0; for (Pattern pattern : artifactPatterns) { result = ArtifactUtil.parse(pattern, fullPath); if (result != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Artifact at " + fullPath + " matched pattern " + idx); } result.setType(getString(jsonArtifact, "type")); result.setCreatedTimeStamp(convertTimestamp(getString(jsonArtifact, "created"))); result.setCreatedBy(getString(jsonArtifact, "created_by")); result.setModifiedTimeStamp(convertTimestamp(getString(jsonArtifact, "modified"))); result.setModifiedBy(getString(jsonArtifact, "modified_by")); result.setActual_md5(getString(jsonArtifact, "actual_md5")); result.setActual_sha1(getString(jsonArtifact, "actual_sha1")); result.setCanonicalName(artifactCanonicalName); result.setTimestamp(timestamp); result.setVirtualRepos(getJsonArray(jsonArtifact, "virtual_repos")); addMetadataToArtifact(result, jsonArtifact); return result; } idx++; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Artifact at " + fullPath + " did not match any patterns."); } return null; }
java
private BinaryArtifact createArtifact(String artifactCanonicalName, String artifactPath, long timestamp, JSONObject jsonArtifact) { BinaryArtifact result = null; String fullPath = artifactPath + "/" + artifactCanonicalName; int idx = 0; for (Pattern pattern : artifactPatterns) { result = ArtifactUtil.parse(pattern, fullPath); if (result != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Artifact at " + fullPath + " matched pattern " + idx); } result.setType(getString(jsonArtifact, "type")); result.setCreatedTimeStamp(convertTimestamp(getString(jsonArtifact, "created"))); result.setCreatedBy(getString(jsonArtifact, "created_by")); result.setModifiedTimeStamp(convertTimestamp(getString(jsonArtifact, "modified"))); result.setModifiedBy(getString(jsonArtifact, "modified_by")); result.setActual_md5(getString(jsonArtifact, "actual_md5")); result.setActual_sha1(getString(jsonArtifact, "actual_sha1")); result.setCanonicalName(artifactCanonicalName); result.setTimestamp(timestamp); result.setVirtualRepos(getJsonArray(jsonArtifact, "virtual_repos")); addMetadataToArtifact(result, jsonArtifact); return result; } idx++; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Artifact at " + fullPath + " did not match any patterns."); } return null; }
[ "private", "BinaryArtifact", "createArtifact", "(", "String", "artifactCanonicalName", ",", "String", "artifactPath", ",", "long", "timestamp", ",", "JSONObject", "jsonArtifact", ")", "{", "BinaryArtifact", "result", "=", "null", ";", "String", "fullPath", "=", "art...
Creates an artifact given its canonical name and path. Artifacts are created by supplied pattern configurations. By default three are supplied: 1. Maven artifacts: [org]/[module]/[version]/[module]-[version]([-classifier])(.[ext]) 2. Ivy artifacts: (a) [org]/[module]/[revision]/[type]/[artifact]-[revision](-[classifier])(.[ext]) (b) [org]/[module]/[revision]/ivy-[revision](-[classifier]).xml Using these patterns, we extract the artifact name, version and group id from the canonical name and path. @param artifactCanonicalName artifact's canonical name in artifactory @param artifactPath artifact's path in artifactory @param timestamp the artifact's timestamp @param jsonArtifact the artifact metadata is extracted from here @return
[ "Creates", "an", "artifact", "given", "its", "canonical", "name", "and", "path", ".", "Artifacts", "are", "created", "by", "supplied", "pattern", "configurations", ".", "By", "default", "three", "are", "supplied", ":", "1", ".", "Maven", "artifacts", ":", "[...
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/artifact/artifactory/src/main/java/com/capitalone/dashboard/collector/DefaultArtifactoryClient.java#L255-L291
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java
EJSContainer.getBean
public EJBObject getBean(ContainerTx tx, BeanId id) throws RemoteException { EJBObject result = null; BeanO beanO = activator.getBean(tx, id); if (beanO != null) { try { // d116480 result = wrapperManager.getWrapper(id).getRemoteWrapper(); // f111627 d156807.1 } catch (IllegalStateException ise) { // d116480 // Result is still null if no defined interface FFDCFilter.processException(ise, CLASS_NAME + ".getBean", "1542", this); } // d116480 } return result; }
java
public EJBObject getBean(ContainerTx tx, BeanId id) throws RemoteException { EJBObject result = null; BeanO beanO = activator.getBean(tx, id); if (beanO != null) { try { // d116480 result = wrapperManager.getWrapper(id).getRemoteWrapper(); // f111627 d156807.1 } catch (IllegalStateException ise) { // d116480 // Result is still null if no defined interface FFDCFilter.processException(ise, CLASS_NAME + ".getBean", "1542", this); } // d116480 } return result; }
[ "public", "EJBObject", "getBean", "(", "ContainerTx", "tx", ",", "BeanId", "id", ")", "throws", "RemoteException", "{", "EJBObject", "result", "=", "null", ";", "BeanO", "beanO", "=", "activator", ".", "getBean", "(", "tx", ",", "id", ")", ";", "if", "("...
Attempt to retrieve from cache bean with given <code>beanId</code> in current transaction context. <p> This method returns null if a bean with given id is not found. <p> @param id the <code>BeanId</code> to retrieve bean for <p>
[ "Attempt", "to", "retrieve", "from", "cache", "bean", "with", "given", "<code", ">", "beanId<", "/", "code", ">", "in", "current", "transaction", "context", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java#L1793-L1806
raphw/byte-buddy
byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/Initialization.java
Initialization.getEntryPoint
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Applies Maven exception wrapper") public EntryPoint getEntryPoint(ClassLoaderResolver classLoaderResolver, String groupId, String artifactId, String version, String packaging) throws MojoExecutionException { if (entryPoint == null || entryPoint.length() == 0) { throw new MojoExecutionException("Entry point name is not defined"); } for (EntryPoint.Default entryPoint : EntryPoint.Default.values()) { if (this.entryPoint.equals(entryPoint.name())) { return entryPoint; } } try { return (EntryPoint) Class.forName(entryPoint, false, classLoaderResolver.resolve(asCoordinate(groupId, artifactId, version, packaging))) .getDeclaredConstructor() .newInstance(); } catch (Exception exception) { throw new MojoExecutionException("Cannot create entry point: " + entryPoint, exception); } }
java
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Applies Maven exception wrapper") public EntryPoint getEntryPoint(ClassLoaderResolver classLoaderResolver, String groupId, String artifactId, String version, String packaging) throws MojoExecutionException { if (entryPoint == null || entryPoint.length() == 0) { throw new MojoExecutionException("Entry point name is not defined"); } for (EntryPoint.Default entryPoint : EntryPoint.Default.values()) { if (this.entryPoint.equals(entryPoint.name())) { return entryPoint; } } try { return (EntryPoint) Class.forName(entryPoint, false, classLoaderResolver.resolve(asCoordinate(groupId, artifactId, version, packaging))) .getDeclaredConstructor() .newInstance(); } catch (Exception exception) { throw new MojoExecutionException("Cannot create entry point: " + entryPoint, exception); } }
[ "@", "SuppressFBWarnings", "(", "value", "=", "\"REC_CATCH_EXCEPTION\"", ",", "justification", "=", "\"Applies Maven exception wrapper\"", ")", "public", "EntryPoint", "getEntryPoint", "(", "ClassLoaderResolver", "classLoaderResolver", ",", "String", "groupId", ",", "String...
Resolves the described entry point. @param classLoaderResolver The class loader resolved to use. @param groupId This project's group id. @param artifactId This project's artifact id. @param version This project's version id. @param packaging This project's packaging @return The resolved entry point. @throws MojoExecutionException If the entry point cannot be created.
[ "Resolves", "the", "described", "entry", "point", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/Initialization.java#L55-L72
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java
PredictionsImpl.predictImageWithNoStore
public ImagePrediction predictImageWithNoStore(UUID projectId, byte[] imageData, PredictImageWithNoStoreOptionalParameter predictImageWithNoStoreOptionalParameter) { return predictImageWithNoStoreWithServiceResponseAsync(projectId, imageData, predictImageWithNoStoreOptionalParameter).toBlocking().single().body(); }
java
public ImagePrediction predictImageWithNoStore(UUID projectId, byte[] imageData, PredictImageWithNoStoreOptionalParameter predictImageWithNoStoreOptionalParameter) { return predictImageWithNoStoreWithServiceResponseAsync(projectId, imageData, predictImageWithNoStoreOptionalParameter).toBlocking().single().body(); }
[ "public", "ImagePrediction", "predictImageWithNoStore", "(", "UUID", "projectId", ",", "byte", "[", "]", "imageData", ",", "PredictImageWithNoStoreOptionalParameter", "predictImageWithNoStoreOptionalParameter", ")", "{", "return", "predictImageWithNoStoreWithServiceResponseAsync", ...
Predict an image without saving the result. @param projectId The project id @param imageData the InputStream value @param predictImageWithNoStoreOptionalParameter the object representing the optional parameters to be set before calling this API @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 ImagePrediction object if successful.
[ "Predict", "an", "image", "without", "saving", "the", "result", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java#L97-L99
couchbase/CouchbaseMock
src/main/java/com/couchbase/mock/memcached/VBucketStore.java
VBucketStore.forceStorageMutation
void forceStorageMutation(Item itm, VBucketCoordinates coords) { forceMutation(itm.getKeySpec().vbId, itm, coords, false); }
java
void forceStorageMutation(Item itm, VBucketCoordinates coords) { forceMutation(itm.getKeySpec().vbId, itm, coords, false); }
[ "void", "forceStorageMutation", "(", "Item", "itm", ",", "VBucketCoordinates", "coords", ")", "{", "forceMutation", "(", "itm", ".", "getKeySpec", "(", ")", ".", "vbId", ",", "itm", ",", "coords", ",", "false", ")", ";", "}" ]
Force a storage of an item to the cache. This assumes the current object belongs to a replica, as it will blindly assume information passed here is authoritative. @param itm The item to mutate (should be a copy of the original) @param coords Coordinate info
[ "Force", "a", "storage", "of", "an", "item", "to", "the", "cache", "." ]
train
https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/VBucketStore.java#L312-L314
redkale/redkale-plugins
src/org/redkalex/source/mysql/CharsetMapping.java
CharsetMapping.getJavaEncodingForMysqlCharset
public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName, String javaEncoding) { String res = javaEncoding; MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(mysqlCharsetName); if (cs != null) { res = cs.getMatchingJavaEncoding(javaEncoding); } return res; }
java
public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName, String javaEncoding) { String res = javaEncoding; MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(mysqlCharsetName); if (cs != null) { res = cs.getMatchingJavaEncoding(javaEncoding); } return res; }
[ "public", "static", "String", "getJavaEncodingForMysqlCharset", "(", "String", "mysqlCharsetName", ",", "String", "javaEncoding", ")", "{", "String", "res", "=", "javaEncoding", ";", "MysqlCharset", "cs", "=", "CHARSET_NAME_TO_CHARSET", ".", "get", "(", "mysqlCharsetN...
MySQL charset could map to several Java encodings. So here we choose the one according to next rules: if there is no static mapping for this charset then return javaEncoding value as is because this could be a custom charset for example if static mapping exists and javaEncoding equals to one of Java encoding canonical names or aliases available for this mapping then javaEncoding value as is; this is required when result should match to connection encoding, for example if connection encoding is Cp943 we must avoid getting SHIFT_JIS for sjis mysql charset if static mapping exists and javaEncoding doesn't match any Java encoding canonical names or aliases available for this mapping then return default Java encoding (the first in mapping list) @param mysqlCharsetName String @param javaEncoding String @return String
[ "MySQL", "charset", "could", "map", "to", "several", "Java", "encodings", ".", "So", "here", "we", "choose", "the", "one", "according", "to", "next", "rules", ":", "if", "there", "is", "no", "static", "mapping", "for", "this", "charset", "then", "return", ...
train
https://github.com/redkale/redkale-plugins/blob/a1edfc906a444ae19fe6aababce2957c9b5ea9d2/src/org/redkalex/source/mysql/CharsetMapping.java#L655-L662
apache/flink
flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraCommitter.java
CassandraCommitter.createResource
@Override public void createResource() throws Exception { cluster = builder.getCluster(); session = cluster.connect(); session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s with replication={'class':'SimpleStrategy', 'replication_factor':1};", keySpace)); session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (sink_id text, sub_id int, checkpoint_id bigint, PRIMARY KEY (sink_id, sub_id));", keySpace, table)); try { session.close(); } catch (Exception e) { LOG.error("Error while closing session.", e); } try { cluster.close(); } catch (Exception e) { LOG.error("Error while closing cluster.", e); } }
java
@Override public void createResource() throws Exception { cluster = builder.getCluster(); session = cluster.connect(); session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s with replication={'class':'SimpleStrategy', 'replication_factor':1};", keySpace)); session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (sink_id text, sub_id int, checkpoint_id bigint, PRIMARY KEY (sink_id, sub_id));", keySpace, table)); try { session.close(); } catch (Exception e) { LOG.error("Error while closing session.", e); } try { cluster.close(); } catch (Exception e) { LOG.error("Error while closing cluster.", e); } }
[ "@", "Override", "public", "void", "createResource", "(", ")", "throws", "Exception", "{", "cluster", "=", "builder", ".", "getCluster", "(", ")", ";", "session", "=", "cluster", ".", "connect", "(", ")", ";", "session", ".", "execute", "(", "String", "....
Generates the necessary tables to store information. @throws Exception
[ "Generates", "the", "necessary", "tables", "to", "store", "information", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraCommitter.java#L78-L96
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsModelPageHelper.java
CmsModelPageHelper.addModelPageToSitemapConfiguration
public void addModelPageToSitemapConfiguration(CmsResource sitemapConfig, CmsResource modelPage, boolean disabled) throws CmsException { CmsFile sitemapConfigFile = m_cms.readFile(sitemapConfig); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, sitemapConfigFile); CmsConfigurationReader reader = new CmsConfigurationReader(m_cms); reader.parseConfiguration(m_adeConfig.getBasePath(), content); List<CmsModelPageConfig> modelPageConfigs = reader.getModelPageConfigs(); int i = 0; boolean isDefault = false; for (CmsModelPageConfig config : modelPageConfigs) { if (config.getResource().getStructureId().equals(modelPage.getStructureId())) { isDefault = config.isDefault(); break; } i += 1; } if (i >= modelPageConfigs.size()) { content.addValue(m_cms, CmsConfigurationReader.N_MODEL_PAGE, Locale.ENGLISH, i); } String prefix = CmsConfigurationReader.N_MODEL_PAGE + "[" + (1 + i) + "]"; content.getValue(prefix + "/" + CmsConfigurationReader.N_PAGE, Locale.ENGLISH).setStringValue( m_cms, modelPage.getRootPath()); content.getValue(prefix + "/" + CmsConfigurationReader.N_DISABLED, Locale.ENGLISH).setStringValue( m_cms, "" + disabled); content.getValue(prefix + "/" + CmsConfigurationReader.N_IS_DEFAULT, Locale.ENGLISH).setStringValue( m_cms, "" + isDefault); writeSitemapConfig(content, sitemapConfigFile); }
java
public void addModelPageToSitemapConfiguration(CmsResource sitemapConfig, CmsResource modelPage, boolean disabled) throws CmsException { CmsFile sitemapConfigFile = m_cms.readFile(sitemapConfig); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, sitemapConfigFile); CmsConfigurationReader reader = new CmsConfigurationReader(m_cms); reader.parseConfiguration(m_adeConfig.getBasePath(), content); List<CmsModelPageConfig> modelPageConfigs = reader.getModelPageConfigs(); int i = 0; boolean isDefault = false; for (CmsModelPageConfig config : modelPageConfigs) { if (config.getResource().getStructureId().equals(modelPage.getStructureId())) { isDefault = config.isDefault(); break; } i += 1; } if (i >= modelPageConfigs.size()) { content.addValue(m_cms, CmsConfigurationReader.N_MODEL_PAGE, Locale.ENGLISH, i); } String prefix = CmsConfigurationReader.N_MODEL_PAGE + "[" + (1 + i) + "]"; content.getValue(prefix + "/" + CmsConfigurationReader.N_PAGE, Locale.ENGLISH).setStringValue( m_cms, modelPage.getRootPath()); content.getValue(prefix + "/" + CmsConfigurationReader.N_DISABLED, Locale.ENGLISH).setStringValue( m_cms, "" + disabled); content.getValue(prefix + "/" + CmsConfigurationReader.N_IS_DEFAULT, Locale.ENGLISH).setStringValue( m_cms, "" + isDefault); writeSitemapConfig(content, sitemapConfigFile); }
[ "public", "void", "addModelPageToSitemapConfiguration", "(", "CmsResource", "sitemapConfig", ",", "CmsResource", "modelPage", ",", "boolean", "disabled", ")", "throws", "CmsException", "{", "CmsFile", "sitemapConfigFile", "=", "m_cms", ".", "readFile", "(", "sitemapConf...
Adds a model page to the sitemap config.<p> @param sitemapConfig the sitemap configuration resource @param modelPage the model page to add @param disabled true if the model page should be added as 'disabled' @throws CmsException if something goes wrong
[ "Adds", "a", "model", "page", "to", "the", "sitemap", "config", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsModelPageHelper.java#L127-L159
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java
LongExtensions.operator_doubleLessThan
@Pure @Inline(value="($1 << $2)", constantExpression=true) public static long operator_doubleLessThan(long a, int distance) { return a << distance; }
java
@Pure @Inline(value="($1 << $2)", constantExpression=true) public static long operator_doubleLessThan(long a, int distance) { return a << distance; }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"($1 << $2)\"", ",", "constantExpression", "=", "true", ")", "public", "static", "long", "operator_doubleLessThan", "(", "long", "a", ",", "int", "distance", ")", "{", "return", "a", "<<", "distance", ";", "...
The binary <code>signed left shift</code> operator. This is the equivalent to the java <code>&lt;&lt;</code> operator. Fills in a zero as the least significant bit. @param a a long. @param distance the number of times to shift. @return <code>a&lt;&lt;distance</code>
[ "The", "binary", "<code", ">", "signed", "left", "shift<", "/", "code", ">", "operator", ".", "This", "is", "the", "equivalent", "to", "the", "java", "<code", ">", "&lt", ";", "&lt", ";", "<", "/", "code", ">", "operator", ".", "Fills", "in", "a", ...
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java#L107-L111
landawn/AbacusUtil
src/com/landawn/abacus/util/N.java
N.removeAll
@SafeVarargs public static char[] removeAll(final char[] a, final char... elements) { if (N.isNullOrEmpty(a)) { return N.EMPTY_CHAR_ARRAY; } else if (N.isNullOrEmpty(elements)) { return a.clone(); } else if (elements.length == 1) { return removeAllOccurrences(a, elements[0]); } final CharList list = CharList.of(a.clone()); list.removeAll(CharList.of(elements)); return list.trimToSize().array(); }
java
@SafeVarargs public static char[] removeAll(final char[] a, final char... elements) { if (N.isNullOrEmpty(a)) { return N.EMPTY_CHAR_ARRAY; } else if (N.isNullOrEmpty(elements)) { return a.clone(); } else if (elements.length == 1) { return removeAllOccurrences(a, elements[0]); } final CharList list = CharList.of(a.clone()); list.removeAll(CharList.of(elements)); return list.trimToSize().array(); }
[ "@", "SafeVarargs", "public", "static", "char", "[", "]", "removeAll", "(", "final", "char", "[", "]", "a", ",", "final", "char", "...", "elements", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "a", ")", ")", "{", "return", "N", ".", "EMPTY...
Returns a new array with removes all the occurrences of specified elements from <code>a</code> @param a @param elements @return @see Collection#removeAll(Collection)
[ "Returns", "a", "new", "array", "with", "removes", "all", "the", "occurrences", "of", "specified", "elements", "from", "<code", ">", "a<", "/", "code", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L23374-L23387
BlueBrain/bluima
modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java
diff_match_patch.diff_toDelta
public String diff_toDelta(LinkedList<Diff> diffs) { StringBuilder text = new StringBuilder(); for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: try { text.append("+") .append(URLEncoder.encode(aDiff.text, "UTF-8") .replace('+', ' ')).append("\t"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } break; case DELETE: text.append("-").append(aDiff.text.length()).append("\t"); break; case EQUAL: text.append("=").append(aDiff.text.length()).append("\t"); break; } } String delta = text.toString(); if (delta.length() != 0) { // Strip off trailing tab character. delta = delta.substring(0, delta.length() - 1); delta = unescapeForEncodeUriCompatability(delta); } return delta; }
java
public String diff_toDelta(LinkedList<Diff> diffs) { StringBuilder text = new StringBuilder(); for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: try { text.append("+") .append(URLEncoder.encode(aDiff.text, "UTF-8") .replace('+', ' ')).append("\t"); } catch (UnsupportedEncodingException e) { // Not likely on modern system. throw new Error("This system does not support UTF-8.", e); } break; case DELETE: text.append("-").append(aDiff.text.length()).append("\t"); break; case EQUAL: text.append("=").append(aDiff.text.length()).append("\t"); break; } } String delta = text.toString(); if (delta.length() != 0) { // Strip off trailing tab character. delta = delta.substring(0, delta.length() - 1); delta = unescapeForEncodeUriCompatability(delta); } return delta; }
[ "public", "String", "diff_toDelta", "(", "LinkedList", "<", "Diff", ">", "diffs", ")", "{", "StringBuilder", "text", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Diff", "aDiff", ":", "diffs", ")", "{", "switch", "(", "aDiff", ".", "operation"...
Crush the diff into an encoded string which describes the operations required to transform text1 into text2. E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. @param diffs Array of Diff objects. @return Delta text.
[ "Crush", "the", "diff", "into", "an", "encoded", "string", "which", "describes", "the", "operations", "required", "to", "transform", "text1", "into", "text2", ".", "E", ".", "g", ".", "=", "3", "\\", "t", "-", "2", "\\", "t", "+", "ing", "-", ">", ...
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java#L1551-L1580
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java
ObjectReader.readObject
public Object readObject(Object pId, Class pObjClass, Hashtable pMapping, Hashtable pWhere) throws SQLException { ObjectMapper om = new ObjectMapper(pObjClass, pMapping); return readObject0(pId, pObjClass, om, pWhere); }
java
public Object readObject(Object pId, Class pObjClass, Hashtable pMapping, Hashtable pWhere) throws SQLException { ObjectMapper om = new ObjectMapper(pObjClass, pMapping); return readObject0(pId, pObjClass, om, pWhere); }
[ "public", "Object", "readObject", "(", "Object", "pId", ",", "Class", "pObjClass", ",", "Hashtable", "pMapping", ",", "Hashtable", "pWhere", ")", "throws", "SQLException", "{", "ObjectMapper", "om", "=", "new", "ObjectMapper", "(", "pObjClass", ",", "pMapping", ...
Reads the object with the given id from the database, using the given mapping. This is the most general form of readObject(). @param id An object uniquely identifying the object to read @param objClass The class of the object to read @param mapping The hashtable containing the object mapping @param where An hashtable containing extra criteria for the read @return An array of Objects, or an zero-length array if none was found
[ "Reads", "the", "object", "with", "the", "given", "id", "from", "the", "database", "using", "the", "given", "mapping", ".", "This", "is", "the", "most", "general", "form", "of", "readObject", "()", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L586-L591
burberius/eve-esi
src/main/java/net/troja/eve/esi/api/MetaApi.java
MetaApi.getHeadersAsync
public com.squareup.okhttp.Call getHeadersAsync(final ApiCallback<Map<String, String>> callback) throws ApiException { com.squareup.okhttp.Call call = getHeadersValidateBeforeCall(callback); Type localVarReturnType = new TypeToken<Map<String, String>>() { }.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call getHeadersAsync(final ApiCallback<Map<String, String>> callback) throws ApiException { com.squareup.okhttp.Call call = getHeadersValidateBeforeCall(callback); Type localVarReturnType = new TypeToken<Map<String, String>>() { }.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "getHeadersAsync", "(", "final", "ApiCallback", "<", "Map", "<", "String", ",", "String", ">", ">", "callback", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", ...
Debug request headers (asynchronously) Echo the request headers for debugging purposes. Note that the &#39;Connection&#39; header and any &#39;X-&#39; headers are not included @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Debug", "request", "headers", "(", "asynchronously", ")", "Echo", "the", "request", "headers", "for", "debugging", "purposes", ".", "Note", "that", "the", "&#39", ";", "Connection&#39", ";", "header", "and", "any", "&#39", ";", "X", "-", "&#39", ";", "hea...
train
https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/MetaApi.java#L143-L151
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java
AbstractMemberWriter.addModifiers
protected void addModifiers(MemberDoc member, Content htmltree) { String mod = modifierString(member); // According to JLS, we should not be showing public modifier for // interface methods. if ((member.isField() || member.isMethod()) && writer instanceof ClassWriterImpl && ((ClassWriterImpl) writer).getClassDoc().isInterface()) { // This check for isDefault() and the default modifier needs to be // added for it to appear on the method details section. Once the // default modifier is added to the Modifier list on DocEnv and once // it is updated to use the javax.lang.model.element.Modifier, we // will need to remove this. mod = (member.isMethod() && ((MethodDoc)member).isDefault()) ? Util.replaceText(mod, "public", "default").trim() : Util.replaceText(mod, "public", "").trim(); } if(mod.length() > 0) { htmltree.addContent(mod); htmltree.addContent(writer.getSpace()); } }
java
protected void addModifiers(MemberDoc member, Content htmltree) { String mod = modifierString(member); // According to JLS, we should not be showing public modifier for // interface methods. if ((member.isField() || member.isMethod()) && writer instanceof ClassWriterImpl && ((ClassWriterImpl) writer).getClassDoc().isInterface()) { // This check for isDefault() and the default modifier needs to be // added for it to appear on the method details section. Once the // default modifier is added to the Modifier list on DocEnv and once // it is updated to use the javax.lang.model.element.Modifier, we // will need to remove this. mod = (member.isMethod() && ((MethodDoc)member).isDefault()) ? Util.replaceText(mod, "public", "default").trim() : Util.replaceText(mod, "public", "").trim(); } if(mod.length() > 0) { htmltree.addContent(mod); htmltree.addContent(writer.getSpace()); } }
[ "protected", "void", "addModifiers", "(", "MemberDoc", "member", ",", "Content", "htmltree", ")", "{", "String", "mod", "=", "modifierString", "(", "member", ")", ";", "// According to JLS, we should not be showing public modifier for", "// interface methods.", "if", "(",...
Add the modifier for the member. @param member the member for which teh modifier will be added. @param htmltree the content tree to which the modifier information will be added.
[ "Add", "the", "modifier", "for", "the", "member", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java#L234-L254
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.simpleFormat
public static String simpleFormat(final String format, final Object... args) { String retVal = format; for (final Object current : args) { String argString = null; try { argString = StringUtils.substring(java.util.Objects.toString(current), 0, 256); retVal = retVal.replaceFirst("[%][sdf]", argString); } catch (final Exception e) { argString = "Ups"; retVal = retVal.replaceFirst("[%][sdf]", argString); } } return retVal; }
java
public static String simpleFormat(final String format, final Object... args) { String retVal = format; for (final Object current : args) { String argString = null; try { argString = StringUtils.substring(java.util.Objects.toString(current), 0, 256); retVal = retVal.replaceFirst("[%][sdf]", argString); } catch (final Exception e) { argString = "Ups"; retVal = retVal.replaceFirst("[%][sdf]", argString); } } return retVal; }
[ "public", "static", "String", "simpleFormat", "(", "final", "String", "format", ",", "final", "Object", "...", "args", ")", "{", "String", "retVal", "=", "format", ";", "for", "(", "final", "Object", "current", ":", "args", ")", "{", "String", "argString",...
Simple replacement for String.format(), works only with %s but it's enough for logging or exceptions. @param format A <a href="../util/Formatter.html#syntax">format string</a> @param args Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by <cite>The Java&trade; Virtual Machine Specification</cite>. The behaviour on a <tt>null</tt> argument depends on the <a href="../util/Formatter.html#syntax">conversion</a>. @return A formatted string
[ "Simple", "replacement", "for", "String", ".", "format", "()", "works", "only", "with", "%s", "but", "it", "s", "enough", "for", "logging", "or", "exceptions", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L9283-L9296
alkacon/opencms-core
src/org/opencms/security/CmsRoleManager.java
CmsRoleManager.hasRole
public boolean hasRole(CmsObject cms, String userName, CmsRole role) { CmsUser user; try { user = cms.readUser(userName); } catch (CmsException e) { // ignore return false; } return m_securityManager.hasRole(cms.getRequestContext(), user, role); }
java
public boolean hasRole(CmsObject cms, String userName, CmsRole role) { CmsUser user; try { user = cms.readUser(userName); } catch (CmsException e) { // ignore return false; } return m_securityManager.hasRole(cms.getRequestContext(), user, role); }
[ "public", "boolean", "hasRole", "(", "CmsObject", "cms", ",", "String", "userName", ",", "CmsRole", "role", ")", "{", "CmsUser", "user", ";", "try", "{", "user", "=", "cms", ".", "readUser", "(", "userName", ")", ";", "}", "catch", "(", "CmsException", ...
Checks if the given user has the given role in the given organizational unit.<p> @param cms the opencms context @param userName the name of the user to check the role for @param role the role to check @return <code>true</code> if the given user has the given role in the given organizational unit
[ "Checks", "if", "the", "given", "user", "has", "the", "given", "role", "in", "the", "given", "organizational", "unit", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsRoleManager.java#L440-L450
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java
ExpressRouteCrossConnectionsInner.beginListRoutesTable
public ExpressRouteCircuitsRoutesTableListResultInner beginListRoutesTable(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return beginListRoutesTableWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).toBlocking().single().body(); }
java
public ExpressRouteCircuitsRoutesTableListResultInner beginListRoutesTable(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return beginListRoutesTableWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).toBlocking().single().body(); }
[ "public", "ExpressRouteCircuitsRoutesTableListResultInner", "beginListRoutesTable", "(", "String", "resourceGroupName", ",", "String", "crossConnectionName", ",", "String", "peeringName", ",", "String", "devicePath", ")", "{", "return", "beginListRoutesTableWithServiceResponseAsy...
Gets the currently advertised routes table associated with the express route cross connection in a resource group. @param resourceGroupName The name of the resource group. @param crossConnectionName The name of the ExpressRouteCrossConnection. @param peeringName The name of the peering. @param devicePath The path of the device. @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 ExpressRouteCircuitsRoutesTableListResultInner object if successful.
[ "Gets", "the", "currently", "advertised", "routes", "table", "associated", "with", "the", "express", "route", "cross", "connection", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L1367-L1369
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/util/ExceptionFactory.java
ExceptionFactory.planVersionAlreadyExistsException
public static final PlanVersionAlreadyExistsException planVersionAlreadyExistsException(String planName, String version) { return new PlanVersionAlreadyExistsException(Messages.i18n.format("PlanVersionAlreadyExists", planName, version)); //$NON-NLS-1$ }
java
public static final PlanVersionAlreadyExistsException planVersionAlreadyExistsException(String planName, String version) { return new PlanVersionAlreadyExistsException(Messages.i18n.format("PlanVersionAlreadyExists", planName, version)); //$NON-NLS-1$ }
[ "public", "static", "final", "PlanVersionAlreadyExistsException", "planVersionAlreadyExistsException", "(", "String", "planName", ",", "String", "version", ")", "{", "return", "new", "PlanVersionAlreadyExistsException", "(", "Messages", ".", "i18n", ".", "format", "(", ...
Creates an exception from an plan name. @param planName the plan name @param version the version @return the exception
[ "Creates", "an", "exception", "from", "an", "plan", "name", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/util/ExceptionFactory.java#L292-L294
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/HeaderElement.java
HeaderElement.setParseInformation
protected void setParseInformation(int index, int start) { this.buffIndex = index; this.offset = start; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Set parse information " + this.buffIndex + " " + this.offset); } }
java
protected void setParseInformation(int index, int start) { this.buffIndex = index; this.offset = start; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Set parse information " + this.buffIndex + " " + this.offset); } }
[ "protected", "void", "setParseInformation", "(", "int", "index", ",", "int", "start", ")", "{", "this", ".", "buffIndex", "=", "index", ";", "this", ".", "offset", "=", "start", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", ...
Set the information about the WsByteBuffer parsing. This is intended to be used during the parsing of the wsbb but prior to actually pulling the value out into the byte[] or String storage. @param index @param start
[ "Set", "the", "information", "about", "the", "WsByteBuffer", "parsing", ".", "This", "is", "intended", "to", "be", "used", "during", "the", "parsing", "of", "the", "wsbb", "but", "prior", "to", "actually", "pulling", "the", "value", "out", "into", "the", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/HeaderElement.java#L110-L117
JoeKerouac/utils
src/main/java/com/joe/utils/secure/impl/AsymmetricCipher.java
AsymmetricCipher.buildInstance
public static CipherUtil buildInstance(PrivateKey privateKey, PublicKey publicKey) { return new AsymmetricCipher(new String(BASE_64.encrypt(privateKey.getEncoded())) + ":" + new String(BASE_64.encrypt(publicKey.getEncoded())), Algorithms.RSA, privateKey, publicKey); }
java
public static CipherUtil buildInstance(PrivateKey privateKey, PublicKey publicKey) { return new AsymmetricCipher(new String(BASE_64.encrypt(privateKey.getEncoded())) + ":" + new String(BASE_64.encrypt(publicKey.getEncoded())), Algorithms.RSA, privateKey, publicKey); }
[ "public", "static", "CipherUtil", "buildInstance", "(", "PrivateKey", "privateKey", ",", "PublicKey", "publicKey", ")", "{", "return", "new", "AsymmetricCipher", "(", "new", "String", "(", "BASE_64", ".", "encrypt", "(", "privateKey", ".", "getEncoded", "(", ")"...
非对称加密构造器 @param privateKey PKCS8格式的私钥 @param publicKey X509格式的公钥 @return AsymmetricCipher
[ "非对称加密构造器" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/secure/impl/AsymmetricCipher.java#L69-L73
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.publishObject
private synchronized String publishObject(KeenProject project, URL url, final Map<String, ?> requestData) throws IOException { if (requestData == null || requestData.size() == 0) { KeenLogging.log("No API calls were made because there were no events to upload"); return null; } // Build an output source which simply writes the serialized JSON to the output. OutputSource source = new OutputSource() { @Override public void writeTo(OutputStream out) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(out, ENCODING); jsonHandler.writeJson(writer, requestData); } }; // If logging is enabled, log the request being sent. if (KeenLogging.isLoggingEnabled()) { try { StringWriter writer = new StringWriter(); jsonHandler.writeJson(writer, requestData); String request = writer.toString(); KeenLogging.log(String.format(Locale.US, "Sent request '%s' to URL '%s'", request, url.toString())); } catch (IOException e) { KeenLogging.log("Couldn't log event written to file: ", e); } } // Send the request. String writeKey = project.getWriteKey(); Request request = new Request(url, HttpMethods.POST, writeKey, source, proxy, connectTimeout, readTimeout); Response response = httpHandler.execute(request); // If logging is enabled, log the response. if (KeenLogging.isLoggingEnabled()) { KeenLogging.log(String.format(Locale.US, "Received response: '%s' (%d)", response.body, response.statusCode)); } // If the request succeeded, return the response body. Otherwise throw an exception. if (response.isSuccess()) { return response.body; } else { throw new ServerException(response.body); } }
java
private synchronized String publishObject(KeenProject project, URL url, final Map<String, ?> requestData) throws IOException { if (requestData == null || requestData.size() == 0) { KeenLogging.log("No API calls were made because there were no events to upload"); return null; } // Build an output source which simply writes the serialized JSON to the output. OutputSource source = new OutputSource() { @Override public void writeTo(OutputStream out) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(out, ENCODING); jsonHandler.writeJson(writer, requestData); } }; // If logging is enabled, log the request being sent. if (KeenLogging.isLoggingEnabled()) { try { StringWriter writer = new StringWriter(); jsonHandler.writeJson(writer, requestData); String request = writer.toString(); KeenLogging.log(String.format(Locale.US, "Sent request '%s' to URL '%s'", request, url.toString())); } catch (IOException e) { KeenLogging.log("Couldn't log event written to file: ", e); } } // Send the request. String writeKey = project.getWriteKey(); Request request = new Request(url, HttpMethods.POST, writeKey, source, proxy, connectTimeout, readTimeout); Response response = httpHandler.execute(request); // If logging is enabled, log the response. if (KeenLogging.isLoggingEnabled()) { KeenLogging.log(String.format(Locale.US, "Received response: '%s' (%d)", response.body, response.statusCode)); } // If the request succeeded, return the response body. Otherwise throw an exception. if (response.isSuccess()) { return response.body; } else { throw new ServerException(response.body); } }
[ "private", "synchronized", "String", "publishObject", "(", "KeenProject", "project", ",", "URL", "url", ",", "final", "Map", "<", "String", ",", "?", ">", "requestData", ")", "throws", "IOException", "{", "if", "(", "requestData", "==", "null", "||", "reques...
Posts a request to the server in the specified project, using the given URL and request data. The request data will be serialized into JSON using the client's {@link io.keen.client.java.KeenJsonHandler}. @param project The project in which the event(s) will be published; this is used to determine the write key to use for authentication. @param url The URL to which the POST should be sent. @param requestData The request data, which will be serialized into JSON and sent in the request body. @return The response from the server. @throws IOException If there was an error communicating with the server.
[ "Posts", "a", "request", "to", "the", "server", "in", "the", "specified", "project", "using", "the", "given", "URL", "and", "request", "data", ".", "The", "request", "data", "will", "be", "serialized", "into", "JSON", "using", "the", "client", "s", "{", ...
train
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1447-L1494
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java
RocksDbWrapper.openReadWrite
public static RocksDbWrapper openReadWrite(File directory, DBOptions dbOptions, ReadOptions readOptions, WriteOptions writeOptions, String... columnFamilies) throws RocksDbException, IOException { RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(directory, false); rocksDbWrapper.setDbOptions(dbOptions).setReadOptions(readOptions) .setWriteOptions(writeOptions); rocksDbWrapper.setColumnFamilies(RocksDbUtils.buildColumnFamilyDescriptors(columnFamilies)); rocksDbWrapper.init(); return rocksDbWrapper; }
java
public static RocksDbWrapper openReadWrite(File directory, DBOptions dbOptions, ReadOptions readOptions, WriteOptions writeOptions, String... columnFamilies) throws RocksDbException, IOException { RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(directory, false); rocksDbWrapper.setDbOptions(dbOptions).setReadOptions(readOptions) .setWriteOptions(writeOptions); rocksDbWrapper.setColumnFamilies(RocksDbUtils.buildColumnFamilyDescriptors(columnFamilies)); rocksDbWrapper.init(); return rocksDbWrapper; }
[ "public", "static", "RocksDbWrapper", "openReadWrite", "(", "File", "directory", ",", "DBOptions", "dbOptions", ",", "ReadOptions", "readOptions", ",", "WriteOptions", "writeOptions", ",", "String", "...", "columnFamilies", ")", "throws", "RocksDbException", ",", "IOE...
Open a {@link RocksDB} with specified options in read/write mode. @param directory directory to store {@link RocksDB} data @param dbOptions @param readOptions @param writeOptions @param columnFamilies list of column families to store key/value (the column family "default" will be automatically added) @return @throws RocksDbException @throws IOException
[ "Open", "a", "{", "@link", "RocksDB", "}", "with", "specified", "options", "in", "read", "/", "write", "mode", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/rocksdb/RocksDbWrapper.java#L167-L176
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
Types.makeIntersectionType
public IntersectionClassType makeIntersectionType(List<Type> bounds) { return makeIntersectionType(bounds, bounds.head.tsym.isInterface()); }
java
public IntersectionClassType makeIntersectionType(List<Type> bounds) { return makeIntersectionType(bounds, bounds.head.tsym.isInterface()); }
[ "public", "IntersectionClassType", "makeIntersectionType", "(", "List", "<", "Type", ">", "bounds", ")", "{", "return", "makeIntersectionType", "(", "bounds", ",", "bounds", ".", "head", ".", "tsym", ".", "isInterface", "(", ")", ")", ";", "}" ]
Make an intersection type from non-empty list of types. The list should be ordered according to {@link TypeSymbol#precedes(TypeSymbol, Types)}. Note that this might cause a symbol completion. Hence, this version of makeIntersectionType may not be called during a classfile read. @param bounds the types from which the intersection type is formed
[ "Make", "an", "intersection", "type", "from", "non", "-", "empty", "list", "of", "types", ".", "The", "list", "should", "be", "ordered", "according", "to", "{", "@link", "TypeSymbol#precedes", "(", "TypeSymbol", "Types", ")", "}", ".", "Note", "that", "thi...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java#L2175-L2177
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/BufferUtil.java
BufferUtil.lineEnd
public static int lineEnd(ByteBuffer buffer, int maxLength) { int primitivePosition = buffer.position(); boolean canEnd = false; int charIndex = primitivePosition; byte b; while (buffer.hasRemaining()) { b = buffer.get(); charIndex++; if (b == StrUtil.C_CR) { canEnd = true; } else if (b == StrUtil.C_LF) { return canEnd ? charIndex - 2 : charIndex - 1; } else { // 只有\r无法确认换行 canEnd = false; } if (charIndex - primitivePosition > maxLength) { // 查找到尽头,未找到,还原位置 buffer.position(primitivePosition); throw new IndexOutOfBoundsException(StrUtil.format("Position is out of maxLength: {}", maxLength)); } } // 查找到buffer尽头,未找到,还原位置 buffer.position(primitivePosition); // 读到结束位置 return -1; }
java
public static int lineEnd(ByteBuffer buffer, int maxLength) { int primitivePosition = buffer.position(); boolean canEnd = false; int charIndex = primitivePosition; byte b; while (buffer.hasRemaining()) { b = buffer.get(); charIndex++; if (b == StrUtil.C_CR) { canEnd = true; } else if (b == StrUtil.C_LF) { return canEnd ? charIndex - 2 : charIndex - 1; } else { // 只有\r无法确认换行 canEnd = false; } if (charIndex - primitivePosition > maxLength) { // 查找到尽头,未找到,还原位置 buffer.position(primitivePosition); throw new IndexOutOfBoundsException(StrUtil.format("Position is out of maxLength: {}", maxLength)); } } // 查找到buffer尽头,未找到,还原位置 buffer.position(primitivePosition); // 读到结束位置 return -1; }
[ "public", "static", "int", "lineEnd", "(", "ByteBuffer", "buffer", ",", "int", "maxLength", ")", "{", "int", "primitivePosition", "=", "buffer", ".", "position", "(", ")", ";", "boolean", "canEnd", "=", "false", ";", "int", "charIndex", "=", "primitivePositi...
一行的末尾位置,查找位置时位移ByteBuffer到结束位置<br> 支持的换行符如下: <pre> 1. \r\n 2. \n </pre> @param buffer {@link ByteBuffer} @param maxLength 读取最大长度 @return 末尾位置,未找到或达到最大长度返回-1
[ "一行的末尾位置,查找位置时位移ByteBuffer到结束位置<br", ">", "支持的换行符如下:" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/BufferUtil.java#L161-L189
BlueBrain/bluima
modules/bluima_protein_concentrations/src/main/java/ch/epfl/bbp/nlp/ie/proteinconc/normalizer/ConcentrationNormalizer.java
ConcentrationNormalizer.normalizeMassUnit
private ValueUnitWrapper normalizeMassUnit(final double value, final String unit) throws UnknownUnitException { Matcher matcher = mMassUnitPatter.matcher(unit); if (matcher.find()) { double normalizationFactor = 1.0; String numeratorSIPrefix = matcher.group(1); Double numeratorFactor = getSIFactor(numeratorSIPrefix); if (numeratorFactor != null) { normalizationFactor *= numeratorFactor; } String denominatorSIPrefix = matcher.group(3); String denominatorUnit = matcher.group(4); Double denominatorFactor = getSIFactor(denominatorSIPrefix); if (denominatorFactor != null) { int power = (denominatorUnit.endsWith("3")) ? 3 : 1; normalizationFactor /= Math.pow(denominatorFactor, power); } if (denominatorUnit.equals("l") || denominatorUnit.equals("L")) { normalizationFactor *= 1000; } assert mSIPrefixes.get("kilo") != null : "kilo seems not to be in the table !"; double normalizedValue = (normalizationFactor * value) / mSIPrefixes.get("kilo"); return new ValueUnitWrapper(normalizedValue, MASS_NORMALIZED_UNIT); } else { throw new UnknownUnitException(unit); } }
java
private ValueUnitWrapper normalizeMassUnit(final double value, final String unit) throws UnknownUnitException { Matcher matcher = mMassUnitPatter.matcher(unit); if (matcher.find()) { double normalizationFactor = 1.0; String numeratorSIPrefix = matcher.group(1); Double numeratorFactor = getSIFactor(numeratorSIPrefix); if (numeratorFactor != null) { normalizationFactor *= numeratorFactor; } String denominatorSIPrefix = matcher.group(3); String denominatorUnit = matcher.group(4); Double denominatorFactor = getSIFactor(denominatorSIPrefix); if (denominatorFactor != null) { int power = (denominatorUnit.endsWith("3")) ? 3 : 1; normalizationFactor /= Math.pow(denominatorFactor, power); } if (denominatorUnit.equals("l") || denominatorUnit.equals("L")) { normalizationFactor *= 1000; } assert mSIPrefixes.get("kilo") != null : "kilo seems not to be in the table !"; double normalizedValue = (normalizationFactor * value) / mSIPrefixes.get("kilo"); return new ValueUnitWrapper(normalizedValue, MASS_NORMALIZED_UNIT); } else { throw new UnknownUnitException(unit); } }
[ "private", "ValueUnitWrapper", "normalizeMassUnit", "(", "final", "double", "value", ",", "final", "String", "unit", ")", "throws", "UnknownUnitException", "{", "Matcher", "matcher", "=", "mMassUnitPatter", ".", "matcher", "(", "unit", ")", ";", "if", "(", "matc...
deals with the normalization of unit confronting weight and volume
[ "deals", "with", "the", "normalization", "of", "unit", "confronting", "weight", "and", "volume" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_protein_concentrations/src/main/java/ch/epfl/bbp/nlp/ie/proteinconc/normalizer/ConcentrationNormalizer.java#L83-L115
Alluxio/alluxio
core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java
UnderFileSystemUtils.touch
public static void touch(UnderFileSystem ufs, String path) throws IOException { OutputStream os = ufs.create(path); os.close(); }
java
public static void touch(UnderFileSystem ufs, String path) throws IOException { OutputStream os = ufs.create(path); os.close(); }
[ "public", "static", "void", "touch", "(", "UnderFileSystem", "ufs", ",", "String", "path", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "ufs", ".", "create", "(", "path", ")", ";", "os", ".", "close", "(", ")", ";", "}" ]
Creates an empty file. @param ufs instance of {@link UnderFileSystem} @param path path to the file
[ "Creates", "an", "empty", "file", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/UnderFileSystemUtils.java#L63-L66
EdwardRaff/JSAT
JSAT/src/jsat/io/LIBSVMLoader.java
LIBSVMLoader.loadC
public static ClassificationDataSet loadC(File file, double sparseRatio) throws FileNotFoundException, IOException { return loadC(file, sparseRatio, -1); }
java
public static ClassificationDataSet loadC(File file, double sparseRatio) throws FileNotFoundException, IOException { return loadC(file, sparseRatio, -1); }
[ "public", "static", "ClassificationDataSet", "loadC", "(", "File", "file", ",", "double", "sparseRatio", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "return", "loadC", "(", "file", ",", "sparseRatio", ",", "-", "1", ")", ";", "}" ]
Loads a new classification data set from a LIBSVM file, assuming the label is a nominal target value @param file the file to load @param sparseRatio the fraction of non zero values to qualify a data point as sparse @return a classification data set @throws FileNotFoundException if the file was not found @throws IOException if an error occurred reading the input stream
[ "Loads", "a", "new", "classification", "data", "set", "from", "a", "LIBSVM", "file", "assuming", "the", "label", "is", "a", "nominal", "target", "value" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/io/LIBSVMLoader.java#L180-L183
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java
IOGroovyMethods.splitEachLine
public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure); }
java
public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options="List<String>") Closure<T> closure) throws IOException { return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure); }
[ "public", "static", "<", "T", ">", "T", "splitEachLine", "(", "InputStream", "stream", ",", "String", "regex", ",", "String", "charset", ",", "@", "ClosureParams", "(", "value", "=", "FromString", ".", "class", ",", "options", "=", "\"List<String>\"", ")", ...
Iterates through the given InputStream line by line using the specified encoding, splitting each line using the given separator. The list of tokens for each line is then passed to the given closure. Finally, the stream is closed. @param stream an InputStream @param regex the delimiting regular expression @param charset opens the stream with a specified charset @param closure a closure @return the last value returned by the closure @throws IOException if an IOException occurs. @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid @see #splitEachLine(java.io.Reader, java.lang.String, groovy.lang.Closure) @since 1.5.5
[ "Iterates", "through", "the", "given", "InputStream", "line", "by", "line", "using", "the", "specified", "encoding", "splitting", "each", "line", "using", "the", "given", "separator", ".", "The", "list", "of", "tokens", "for", "each", "line", "is", "then", "...
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/IOGroovyMethods.java#L603-L605
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java
PrepareRoutingSubnetworks.removeDeadEndUnvisitedNetworks
int removeDeadEndUnvisitedNetworks(final PrepEdgeFilter bothFilter) { StopWatch sw = new StopWatch(bothFilter.getAccessEnc() + " findComponents").start(); final EdgeFilter outFilter = DefaultEdgeFilter.outEdges(bothFilter.getAccessEnc()); // partition graph into strongly connected components using Tarjan's algorithm TarjansSCCAlgorithm tarjan = new TarjansSCCAlgorithm(ghStorage, outFilter, true); List<IntArrayList> components = tarjan.findComponents(); logger.info(sw.stop() + ", size:" + components.size()); return removeEdges(bothFilter, components, minOneWayNetworkSize); }
java
int removeDeadEndUnvisitedNetworks(final PrepEdgeFilter bothFilter) { StopWatch sw = new StopWatch(bothFilter.getAccessEnc() + " findComponents").start(); final EdgeFilter outFilter = DefaultEdgeFilter.outEdges(bothFilter.getAccessEnc()); // partition graph into strongly connected components using Tarjan's algorithm TarjansSCCAlgorithm tarjan = new TarjansSCCAlgorithm(ghStorage, outFilter, true); List<IntArrayList> components = tarjan.findComponents(); logger.info(sw.stop() + ", size:" + components.size()); return removeEdges(bothFilter, components, minOneWayNetworkSize); }
[ "int", "removeDeadEndUnvisitedNetworks", "(", "final", "PrepEdgeFilter", "bothFilter", ")", "{", "StopWatch", "sw", "=", "new", "StopWatch", "(", "bothFilter", ".", "getAccessEnc", "(", ")", "+", "\" findComponents\"", ")", ".", "start", "(", ")", ";", "final", ...
This method removes networks that will be never be visited by this filter. See #235 for example, small areas like parking lots are sometimes connected to the whole network through a one-way road. This is clearly an error - but it causes the routing to fail when a point gets connected to this small area. This routine removes all these networks from the graph. @return number of removed edges
[ "This", "method", "removes", "networks", "that", "will", "be", "never", "be", "visited", "by", "this", "filter", ".", "See", "#235", "for", "example", "small", "areas", "like", "parking", "lots", "are", "sometimes", "connected", "to", "the", "whole", "networ...
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/subnetwork/PrepareRoutingSubnetworks.java#L198-L208
vlingo/vlingo-actors
src/main/java/io/vlingo/actors/Stage.java
Stage.actorFor
public <T> T actorFor(final Class<T> protocol, final Definition definition, final Address address) { final Address actorAddress = this.allocateAddress(definition, address); final Mailbox actorMailbox = this.allocateMailbox(definition, actorAddress, null); final ActorProtocolActor<T> actor = actorProtocolFor( protocol, definition, definition.parentOr(world.defaultParent()), actorAddress, actorMailbox, definition.supervisor(), definition.loggerOr(world.defaultLogger())); return actor.protocolActor(); }
java
public <T> T actorFor(final Class<T> protocol, final Definition definition, final Address address) { final Address actorAddress = this.allocateAddress(definition, address); final Mailbox actorMailbox = this.allocateMailbox(definition, actorAddress, null); final ActorProtocolActor<T> actor = actorProtocolFor( protocol, definition, definition.parentOr(world.defaultParent()), actorAddress, actorMailbox, definition.supervisor(), definition.loggerOr(world.defaultLogger())); return actor.protocolActor(); }
[ "public", "<", "T", ">", "T", "actorFor", "(", "final", "Class", "<", "T", ">", "protocol", ",", "final", "Definition", "definition", ",", "final", "Address", "address", ")", "{", "final", "Address", "actorAddress", "=", "this", ".", "allocateAddress", "("...
Answers the {@code T} protocol of the newly created {@code Actor} that implements the {@code protocol} and that will be assigned the specific {@code address}. @param <T> the protocol type @param protocol the {@code Class<T>} protocol @param definition the {@code Definition} used to initialize the newly created {@code Actor} @param address the {@code Address} to assign to the newly created {@code Actor} @return T
[ "Answers", "the", "{" ]
train
https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/Stage.java#L78-L92
uniform-java/uniform
src/main/java/net/uniform/impl/ElementWithOptions.java
ElementWithOptions.addOption
public ElementWithOptions addOption(Object value, String text) { return addOptionToGroup(value, text, null); }
java
public ElementWithOptions addOption(Object value, String text) { return addOptionToGroup(value, text, null); }
[ "public", "ElementWithOptions", "addOption", "(", "Object", "value", ",", "String", "text", ")", "{", "return", "addOptionToGroup", "(", "value", ",", "text", ",", "null", ")", ";", "}" ]
Adds an option to the default option group of this element. @param value Unique value in this element @param text Option text @return This element
[ "Adds", "an", "option", "to", "the", "default", "option", "group", "of", "this", "element", "." ]
train
https://github.com/uniform-java/uniform/blob/0b84f0db562253165bc06c69f631e464dca0cb48/src/main/java/net/uniform/impl/ElementWithOptions.java#L84-L86
pravega/pravega
controller/src/main/java/io/pravega/controller/server/rpc/auth/RESTAuthHelper.java
RESTAuthHelper.authenticateAuthorize
public void authenticateAuthorize(List<String> authHeader, String resource, AuthHandler.Permissions permission) throws AuthException { if (isAuthEnabled()) { String credentials = parseCredentials(authHeader); if (!pravegaAuthManager.authenticateAndAuthorize(resource, credentials, permission)) { throw new AuthException( String.format("Failed to authenticate or authorize for resource [%s]", resource), Response.Status.FORBIDDEN.getStatusCode()); } } }
java
public void authenticateAuthorize(List<String> authHeader, String resource, AuthHandler.Permissions permission) throws AuthException { if (isAuthEnabled()) { String credentials = parseCredentials(authHeader); if (!pravegaAuthManager.authenticateAndAuthorize(resource, credentials, permission)) { throw new AuthException( String.format("Failed to authenticate or authorize for resource [%s]", resource), Response.Status.FORBIDDEN.getStatusCode()); } } }
[ "public", "void", "authenticateAuthorize", "(", "List", "<", "String", ">", "authHeader", ",", "String", "resource", ",", "AuthHandler", ".", "Permissions", "permission", ")", "throws", "AuthException", "{", "if", "(", "isAuthEnabled", "(", ")", ")", "{", "Str...
Ensures that the subject represented by the given {@code authHeader} is authenticated and that the subject is authorized for the specified {@code permission} on the given {@code resource}. @param authHeader contents of an HTTP Authorization header @param resource representation of the resource being accessed @param permission the permission @throws AuthException if authentication/authorization fails
[ "Ensures", "that", "the", "subject", "represented", "by", "the", "given", "{", "@code", "authHeader", "}", "is", "authenticated", "and", "that", "the", "subject", "is", "authorized", "for", "the", "specified", "{", "@code", "permission", "}", "on", "the", "g...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/server/rpc/auth/RESTAuthHelper.java#L104-L114
joniles/mpxj
src/main/java/net/sf/mpxj/mpx/Record.java
Record.getDate
public Date getDate(int field) throws MPXJException { try { Date result; if ((field < m_fields.length) && (m_fields[field].length() != 0)) { result = m_formats.getDateFormat().parse(m_fields[field]); } else { result = null; } return (result); } catch (ParseException ex) { throw new MPXJException("Failed to parse date", ex); } }
java
public Date getDate(int field) throws MPXJException { try { Date result; if ((field < m_fields.length) && (m_fields[field].length() != 0)) { result = m_formats.getDateFormat().parse(m_fields[field]); } else { result = null; } return (result); } catch (ParseException ex) { throw new MPXJException("Failed to parse date", ex); } }
[ "public", "Date", "getDate", "(", "int", "field", ")", "throws", "MPXJException", "{", "try", "{", "Date", "result", ";", "if", "(", "(", "field", "<", "m_fields", ".", "length", ")", "&&", "(", "m_fields", "[", "field", "]", ".", "length", "(", ")",...
Accessor method used to retrieve an Date instance representing the contents of an individual field. If the field does not exist in the record, null is returned. @param field the index number of the field to be retrieved @return the value of the required field @throws MPXJException normally thrown when parsing fails
[ "Accessor", "method", "used", "to", "retrieve", "an", "Date", "instance", "representing", "the", "contents", "of", "an", "individual", "field", ".", "If", "the", "field", "does", "not", "exist", "in", "the", "record", "null", "is", "returned", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/Record.java#L283-L305
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.notifyChildChanged
@UiThread public void notifyChildChanged(int parentPosition, int childPosition) { P parent = mParentList.get(parentPosition); int flatParentPosition = getFlatParentPosition(parentPosition); ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); parentWrapper.setParent(parent); if (parentWrapper.isExpanded()) { int flatChildPosition = flatParentPosition + childPosition + 1; ExpandableWrapper<P, C> child = parentWrapper.getWrappedChildList().get(childPosition); mFlatItemList.set(flatChildPosition, child); notifyItemChanged(flatChildPosition); } }
java
@UiThread public void notifyChildChanged(int parentPosition, int childPosition) { P parent = mParentList.get(parentPosition); int flatParentPosition = getFlatParentPosition(parentPosition); ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); parentWrapper.setParent(parent); if (parentWrapper.isExpanded()) { int flatChildPosition = flatParentPosition + childPosition + 1; ExpandableWrapper<P, C> child = parentWrapper.getWrappedChildList().get(childPosition); mFlatItemList.set(flatChildPosition, child); notifyItemChanged(flatChildPosition); } }
[ "@", "UiThread", "public", "void", "notifyChildChanged", "(", "int", "parentPosition", ",", "int", "childPosition", ")", "{", "P", "parent", "=", "mParentList", ".", "get", "(", "parentPosition", ")", ";", "int", "flatParentPosition", "=", "getFlatParentPosition",...
Notify any registered observers that the parent at {@code parentPosition} has a child located at {@code childPosition} that has changed. <p> This is an item change event, not a structural change event. It indicates that any reflection of the data at {@code childPosition} is out of date and should be updated. The parent at {@code childPosition} retains the same identity. @param parentPosition Position of the parent which has a child that has changed @param childPosition Position of the child that has changed
[ "Notify", "any", "registered", "observers", "that", "the", "parent", "at", "{", "@code", "parentPosition", "}", "has", "a", "child", "located", "at", "{", "@code", "childPosition", "}", "that", "has", "changed", ".", "<p", ">", "This", "is", "an", "item", ...
train
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L1241-L1253
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/math/ProbabilityUtils.java
ProbabilityUtils.cleanProbability
public static double cleanProbability(double prob, double epsilon, boolean allowOne) { if (prob < -epsilon || prob > (1.0 + epsilon)) { throw new InvalidProbabilityException(prob); } if (prob < epsilon) { prob = epsilon; } else { final double limit = allowOne ? 1.0 : (1.0 - epsilon); if (prob > limit) { prob = limit; } } return prob; }
java
public static double cleanProbability(double prob, double epsilon, boolean allowOne) { if (prob < -epsilon || prob > (1.0 + epsilon)) { throw new InvalidProbabilityException(prob); } if (prob < epsilon) { prob = epsilon; } else { final double limit = allowOne ? 1.0 : (1.0 - epsilon); if (prob > limit) { prob = limit; } } return prob; }
[ "public", "static", "double", "cleanProbability", "(", "double", "prob", ",", "double", "epsilon", ",", "boolean", "allowOne", ")", "{", "if", "(", "prob", "<", "-", "epsilon", "||", "prob", ">", "(", "1.0", "+", "epsilon", ")", ")", "{", "throw", "new...
Cleans up input which should be probabilities. Occasionally due to numerical stability issues you get input which should be a probability but could actually be very slightly less than 0 or more than 1.0. This function will take values within epsilon of being good probabilities and fix them. If the prob is within epsilon of zero, it is changed to +epsilon. One the upper end, if allowOne is true, anything between 1.0 and 1.0 + epsilon is mapped to 1.0. If allowOne is false, anything between 1.0-epsilon and 1.0 + epsilon is mapped to 1.0-epsilon. All other probability values throw an unchecked InvalidProbabilityException.
[ "Cleans", "up", "input", "which", "should", "be", "probabilities", ".", "Occasionally", "due", "to", "numerical", "stability", "issues", "you", "get", "input", "which", "should", "be", "a", "probability", "but", "could", "actually", "be", "very", "slightly", "...
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/math/ProbabilityUtils.java#L35-L50
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java
SDMath.confusionMatrix
public SDVariable confusionMatrix(String name, SDVariable labels, SDVariable pred, Integer numClasses) { validateInteger("confusionMatrix", "labels", labels); validateInteger("confusionMatrix", "prediction", pred); SDVariable result = f().confusionMatrix(labels, pred, numClasses); return updateVariableNameAndReference(result, name); }
java
public SDVariable confusionMatrix(String name, SDVariable labels, SDVariable pred, Integer numClasses) { validateInteger("confusionMatrix", "labels", labels); validateInteger("confusionMatrix", "prediction", pred); SDVariable result = f().confusionMatrix(labels, pred, numClasses); return updateVariableNameAndReference(result, name); }
[ "public", "SDVariable", "confusionMatrix", "(", "String", "name", ",", "SDVariable", "labels", ",", "SDVariable", "pred", ",", "Integer", "numClasses", ")", "{", "validateInteger", "(", "\"confusionMatrix\"", ",", "\"labels\"", ",", "labels", ")", ";", "validateIn...
Compute the 2d confusion matrix of size [numClasses, numClasses] from a pair of labels and predictions, both of which are represented as integer values.<br> For example, if labels = [0, 1, 1], predicted = [0, 2, 1], and numClasses=4 then output is:<br> [1, 0, 0, 0]<br> [0, 1, 1, 0]<br> [0, 0, 0, 0]<br> [0, 0, 0, 0]<br> @param name Name of the output variable @param labels Labels - 1D array of integer values representing label values @param pred Predictions - 1D array of integer values representing predictions. Same length as labels @param numClasses Number of classes @return Output variable (2D, shape [numClasses, numClasses})
[ "Compute", "the", "2d", "confusion", "matrix", "of", "size", "[", "numClasses", "numClasses", "]", "from", "a", "pair", "of", "labels", "and", "predictions", "both", "of", "which", "are", "represented", "as", "integer", "values", ".", "<br", ">", "For", "e...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java#L522-L527
dihedron/dihedron-commons
src/main/java/org/dihedron/patterns/activities/TypedVector.java
TypedVector.lastIndexOf
@Override public int lastIndexOf(Object o, int index) { int idx = getRealIndex(index); return super.lastIndexOf(o, idx); }
java
@Override public int lastIndexOf(Object o, int index) { int idx = getRealIndex(index); return super.lastIndexOf(o, idx); }
[ "@", "Override", "public", "int", "lastIndexOf", "(", "Object", "o", ",", "int", "index", ")", "{", "int", "idx", "=", "getRealIndex", "(", "index", ")", ";", "return", "super", ".", "lastIndexOf", "(", "o", ",", "idx", ")", ";", "}" ]
Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found. @param o the object to look for. @param index the index at which the element lookup should start; it can be a positive number, or a negative number that is smaller than the size of the vector; see {@link #getRealIndex(int)}. @see java.util.Vector#lastIndexOf(java.lang.Object, int)
[ "Returns", "the", "index", "of", "the", "last", "occurrence", "of", "the", "specified", "element", "in", "this", "vector", "searching", "backwards", "from", "index", "or", "returns", "-", "1", "if", "the", "element", "is", "not", "found", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/patterns/activities/TypedVector.java#L186-L190
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/FileUtil.java
FileUtil.addFolderToZip
public static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException { File folder = new File(srcFolder); if (folder.list().length == 0) { addFileToZip(path, srcFolder, zip, true); } else { for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false); } } } }
java
public static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException { File folder = new File(srcFolder); if (folder.list().length == 0) { addFileToZip(path, srcFolder, zip, true); } else { for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false); } } } }
[ "public", "static", "void", "addFolderToZip", "(", "String", "path", ",", "String", "srcFolder", ",", "ZipOutputStream", "zip", ")", "throws", "IOException", "{", "File", "folder", "=", "new", "File", "(", "srcFolder", ")", ";", "if", "(", "folder", ".", "...
Adds folder to the archive. @param path path to the folder @param srcFolder folder name @param zip zip archive @throws IOException
[ "Adds", "folder", "to", "the", "archive", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/FileUtil.java#L266-L279
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.executeUploadPhotoRequestAsync
@Deprecated public static RequestAsyncTask executeUploadPhotoRequestAsync(Session session, Bitmap image, Callback callback) { return newUploadPhotoRequest(session, image, callback).executeAsync(); }
java
@Deprecated public static RequestAsyncTask executeUploadPhotoRequestAsync(Session session, Bitmap image, Callback callback) { return newUploadPhotoRequest(session, image, callback).executeAsync(); }
[ "@", "Deprecated", "public", "static", "RequestAsyncTask", "executeUploadPhotoRequestAsync", "(", "Session", "session", ",", "Bitmap", "image", ",", "Callback", "callback", ")", "{", "return", "newUploadPhotoRequest", "(", "session", ",", "image", ",", "callback", "...
Starts a new Request configured to upload a photo to the user's default photo album. <p/> This should only be called from the UI thread. This method is deprecated. Prefer to call Request.newUploadPhotoRequest(...).executeAsync(); @param session the Session to use, or null; if non-null, the session must be in an opened state @param image the image to upload @param callback a callback that will be called when the request is completed to handle success or error conditions @return a RequestAsyncTask that is executing the request
[ "Starts", "a", "new", "Request", "configured", "to", "upload", "a", "photo", "to", "the", "user", "s", "default", "photo", "album", ".", "<p", "/", ">", "This", "should", "only", "be", "called", "from", "the", "UI", "thread", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1153-L1156
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.addToken
public CompletableFuture<Revision> addToken(Author author, String projectName, String appId, ProjectRole role) { requireNonNull(author, "author"); requireNonNull(projectName, "projectName"); requireNonNull(appId, "appId"); requireNonNull(role, "role"); return getTokens().thenCompose(tokens -> { final Token token = tokens.appIds().get(appId); checkArgument(token != null, "Token not found: " + appId); final TokenRegistration registration = new TokenRegistration(appId, role, UserAndTimestamp.of(author)); final JsonPointer path = JsonPointer.compile("/tokens" + encodeSegment(registration.id())); final Change<JsonNode> change = Change.ofJsonPatch(METADATA_JSON, asJsonArray(new TestAbsenceOperation(path), new AddOperation(path, Jackson.valueToTree(registration)))); final String commitSummary = "Add a token '" + registration.id() + "' to the project " + projectName + " with a role '" + role + '\''; return metadataRepo.push(projectName, Project.REPO_DOGMA, author, commitSummary, change); }); }
java
public CompletableFuture<Revision> addToken(Author author, String projectName, String appId, ProjectRole role) { requireNonNull(author, "author"); requireNonNull(projectName, "projectName"); requireNonNull(appId, "appId"); requireNonNull(role, "role"); return getTokens().thenCompose(tokens -> { final Token token = tokens.appIds().get(appId); checkArgument(token != null, "Token not found: " + appId); final TokenRegistration registration = new TokenRegistration(appId, role, UserAndTimestamp.of(author)); final JsonPointer path = JsonPointer.compile("/tokens" + encodeSegment(registration.id())); final Change<JsonNode> change = Change.ofJsonPatch(METADATA_JSON, asJsonArray(new TestAbsenceOperation(path), new AddOperation(path, Jackson.valueToTree(registration)))); final String commitSummary = "Add a token '" + registration.id() + "' to the project " + projectName + " with a role '" + role + '\''; return metadataRepo.push(projectName, Project.REPO_DOGMA, author, commitSummary, change); }); }
[ "public", "CompletableFuture", "<", "Revision", ">", "addToken", "(", "Author", "author", ",", "String", "projectName", ",", "String", "appId", ",", "ProjectRole", "role", ")", "{", "requireNonNull", "(", "author", ",", "\"author\"", ")", ";", "requireNonNull", ...
Adds a {@link Token} of the specified {@code appId} to the specified {@code projectName}.
[ "Adds", "a", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L334-L356
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/workspace/WorkspaceUtils.java
WorkspaceUtils.assertOpenActiveAndCurrent
public static void assertOpenActiveAndCurrent(@NonNull String ws, @NonNull String errorMsg) throws ND4JWorkspaceException { if (!Nd4j.getWorkspaceManager().checkIfWorkspaceExistsAndActive(ws)) { throw new ND4JWorkspaceException(errorMsg + " - workspace is not open and active"); } MemoryWorkspace currWs = Nd4j.getMemoryManager().getCurrentWorkspace(); if (currWs == null || !ws.equals(currWs.getId())) { throw new ND4JWorkspaceException(errorMsg + " - not the current workspace (current workspace: " + (currWs == null ? null : currWs.getId())); } }
java
public static void assertOpenActiveAndCurrent(@NonNull String ws, @NonNull String errorMsg) throws ND4JWorkspaceException { if (!Nd4j.getWorkspaceManager().checkIfWorkspaceExistsAndActive(ws)) { throw new ND4JWorkspaceException(errorMsg + " - workspace is not open and active"); } MemoryWorkspace currWs = Nd4j.getMemoryManager().getCurrentWorkspace(); if (currWs == null || !ws.equals(currWs.getId())) { throw new ND4JWorkspaceException(errorMsg + " - not the current workspace (current workspace: " + (currWs == null ? null : currWs.getId())); } }
[ "public", "static", "void", "assertOpenActiveAndCurrent", "(", "@", "NonNull", "String", "ws", ",", "@", "NonNull", "String", "errorMsg", ")", "throws", "ND4JWorkspaceException", "{", "if", "(", "!", "Nd4j", ".", "getWorkspaceManager", "(", ")", ".", "checkIfWor...
Assert that the specified workspace is open, active, and is the current workspace @param ws Name of the workspace to assert open/active/current @param errorMsg Message to include in the exception, if required
[ "Assert", "that", "the", "specified", "workspace", "is", "open", "active", "and", "is", "the", "current", "workspace" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/workspace/WorkspaceUtils.java#L92-L101
PistoiaHELM/HELM2NotationToolkit
src/main/java/org/helm/notation2/tools/SiRNANotation.java
SiRNANotation.getSirnaNotation
public static HELM2Notation getSirnaNotation(String senseSeq, String antiSenseSeq, String rnaDesignType) throws NotationException, FastaFormatException, HELM2HandledException, RNAUtilsException, org.helm.notation2.exception.NotationException, ChemistryException, CTKException, NucleotideLoadingException { HELM2Notation helm2notation = null; if (senseSeq != null && senseSeq.length() > 0) { helm2notation = SequenceConverter.readRNA(senseSeq); } if (antiSenseSeq != null && antiSenseSeq.length() > 0) { PolymerNotation antisense = new PolymerNotation("RNA2"); antisense = new PolymerNotation(antisense.getPolymerID(), FastaFormat.generateElementsforRNA(antiSenseSeq, antisense.getPolymerID())); helm2notation.addPolymer(antisense); } validateSiRNADesign(helm2notation.getListOfPolymers().get(0), helm2notation.getListOfPolymers().get(1), rnaDesignType); helm2notation.getListOfConnections().addAll(hybridization(helm2notation.getListOfPolymers().get(0), helm2notation.getListOfPolymers().get(1), rnaDesignType)); ChangeObjects.addAnnotation(new AnnotationNotation("RNA1{ss}|RNA2{as}"), 0, helm2notation); return helm2notation; }
java
public static HELM2Notation getSirnaNotation(String senseSeq, String antiSenseSeq, String rnaDesignType) throws NotationException, FastaFormatException, HELM2HandledException, RNAUtilsException, org.helm.notation2.exception.NotationException, ChemistryException, CTKException, NucleotideLoadingException { HELM2Notation helm2notation = null; if (senseSeq != null && senseSeq.length() > 0) { helm2notation = SequenceConverter.readRNA(senseSeq); } if (antiSenseSeq != null && antiSenseSeq.length() > 0) { PolymerNotation antisense = new PolymerNotation("RNA2"); antisense = new PolymerNotation(antisense.getPolymerID(), FastaFormat.generateElementsforRNA(antiSenseSeq, antisense.getPolymerID())); helm2notation.addPolymer(antisense); } validateSiRNADesign(helm2notation.getListOfPolymers().get(0), helm2notation.getListOfPolymers().get(1), rnaDesignType); helm2notation.getListOfConnections().addAll(hybridization(helm2notation.getListOfPolymers().get(0), helm2notation.getListOfPolymers().get(1), rnaDesignType)); ChangeObjects.addAnnotation(new AnnotationNotation("RNA1{ss}|RNA2{as}"), 0, helm2notation); return helm2notation; }
[ "public", "static", "HELM2Notation", "getSirnaNotation", "(", "String", "senseSeq", ",", "String", "antiSenseSeq", ",", "String", "rnaDesignType", ")", "throws", "NotationException", ",", "FastaFormatException", ",", "HELM2HandledException", ",", "RNAUtilsException", ",",...
this method converts nucleotide sequences into HELM notation based on design pattern @param senseSeq 5-3 nucleotide sequence @param antiSenseSeq 3-5 nucleotide sequence @param rnaDesignType given design pattern @return HELM2Notation for siRNA @throws NotationException if notation is not valid @throws FastaFormatException if the fasta input is not valid @throws HELM2HandledException if it contains HELM2 specific features, so that it can not be casted to HELM1 Format @throws RNAUtilsException if the polymer is not a RNA/DNA @throws org.helm.notation2.exception.NotationException if notation is not valid @throws ChemistryException if the Chemistry Engine can not be initialized @throws CTKException general ChemToolKit exception passed to HELMToolKit @throws NucleotideLoadingException if nucleotides can not be loaded
[ "this", "method", "converts", "nucleotide", "sequences", "into", "HELM", "notation", "based", "on", "design", "pattern" ]
train
https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/SiRNANotation.java#L115-L136
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.fireEvent
private void fireEvent(int type, Object data) { OpenCms.fireCmsEvent(type, Collections.singletonMap("data", data)); }
java
private void fireEvent(int type, Object data) { OpenCms.fireCmsEvent(type, Collections.singletonMap("data", data)); }
[ "private", "void", "fireEvent", "(", "int", "type", ",", "Object", "data", ")", "{", "OpenCms", ".", "fireCmsEvent", "(", "type", ",", "Collections", ".", "singletonMap", "(", "\"data\"", ",", "data", ")", ")", ";", "}" ]
Notify all event listeners that a particular event has occurred.<p> The event will be given to all registered <code>{@link I_CmsEventListener}</code>s.<p> @param type the type of the event @param data a data object that contains data used by the event listeners @see OpenCms#addCmsEventListener(I_CmsEventListener) @see OpenCms#addCmsEventListener(I_CmsEventListener, int[])
[ "Notify", "all", "event", "listeners", "that", "a", "particular", "event", "has", "occurred", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L4258-L4261
menacher/java-game-server
jetclient/src/main/java/org/menacheri/jetclient/util/NettyUtils.java
NettyUtils.writeStrings
public static ChannelBuffer writeStrings(Charset charset, String... msgs) { ChannelBuffer buffer = null; for (String msg : msgs) { if (null == buffer) { buffer = writeString(msg, charset); } else { ChannelBuffer theBuffer = writeString(msg,charset); if(null != theBuffer) { buffer = ChannelBuffers.wrappedBuffer(buffer,theBuffer); } } } return buffer; }
java
public static ChannelBuffer writeStrings(Charset charset, String... msgs) { ChannelBuffer buffer = null; for (String msg : msgs) { if (null == buffer) { buffer = writeString(msg, charset); } else { ChannelBuffer theBuffer = writeString(msg,charset); if(null != theBuffer) { buffer = ChannelBuffers.wrappedBuffer(buffer,theBuffer); } } } return buffer; }
[ "public", "static", "ChannelBuffer", "writeStrings", "(", "Charset", "charset", ",", "String", "...", "msgs", ")", "{", "ChannelBuffer", "buffer", "=", "null", ";", "for", "(", "String", "msg", ":", "msgs", ")", "{", "if", "(", "null", "==", "buffer", ")...
Writes multiple strings to a channelBuffer with the length of the string preceding its content. So if there are two string <code>Hello</code> and <code>World</code> then the channel buffer returned would contain <Length of Hello><Hello as appropriate charset binary><Length of world><World as UTF-8 binary> @param charset The Charset say 'UTF-8' in which the encoding needs to be done. @param msgs The messages to be written. @return {@link ChannelBuffer} with format length-stringbinary-length-stringbinary
[ "Writes", "multiple", "strings", "to", "a", "channelBuffer", "with", "the", "length", "of", "the", "string", "preceding", "its", "content", ".", "So", "if", "there", "are", "two", "string", "<code", ">", "Hello<", "/", "code", ">", "and", "<code", ">", "...
train
https://github.com/menacher/java-game-server/blob/668ca49e8bd1dac43add62378cf6c22a93125d48/jetclient/src/main/java/org/menacheri/jetclient/util/NettyUtils.java#L221-L240
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java
AbstractIndexWriter.addDescription
protected void addDescription(MemberDoc member, Content dlTree) { String name = (member instanceof ExecutableMemberDoc)? member.name() + ((ExecutableMemberDoc)member).flatSignature() : member.name(); Content span = HtmlTree.SPAN(HtmlStyle.memberNameLink, getDocLink(LinkInfoImpl.Kind.INDEX, member, name)); Content dt = HtmlTree.DT(span); dt.addContent(" - "); addMemberDesc(member, dt); dlTree.addContent(dt); Content dd = new HtmlTree(HtmlTag.DD); addComment(member, dd); dlTree.addContent(dd); }
java
protected void addDescription(MemberDoc member, Content dlTree) { String name = (member instanceof ExecutableMemberDoc)? member.name() + ((ExecutableMemberDoc)member).flatSignature() : member.name(); Content span = HtmlTree.SPAN(HtmlStyle.memberNameLink, getDocLink(LinkInfoImpl.Kind.INDEX, member, name)); Content dt = HtmlTree.DT(span); dt.addContent(" - "); addMemberDesc(member, dt); dlTree.addContent(dt); Content dd = new HtmlTree(HtmlTag.DD); addComment(member, dd); dlTree.addContent(dd); }
[ "protected", "void", "addDescription", "(", "MemberDoc", "member", ",", "Content", "dlTree", ")", "{", "String", "name", "=", "(", "member", "instanceof", "ExecutableMemberDoc", ")", "?", "member", ".", "name", "(", ")", "+", "(", "(", "ExecutableMemberDoc", ...
Add description for Class, Field, Method or Constructor. @param member MemberDoc for the member of the Class Kind @param dlTree the content tree to which the description will be added
[ "Add", "description", "for", "Class", "Field", "Method", "or", "Constructor", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java#L175-L188
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/StatementManager.java
StatementManager.bindStatement
private int bindStatement(PreparedStatement stmt, int index, BetweenCriteria crit, ClassDescriptor cld) throws SQLException { index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); return bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue2(), cld); }
java
private int bindStatement(PreparedStatement stmt, int index, BetweenCriteria crit, ClassDescriptor cld) throws SQLException { index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld); return bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue2(), cld); }
[ "private", "int", "bindStatement", "(", "PreparedStatement", "stmt", ",", "int", "index", ",", "BetweenCriteria", "crit", ",", "ClassDescriptor", "cld", ")", "throws", "SQLException", "{", "index", "=", "bindStatementValue", "(", "stmt", ",", "index", ",", "crit...
bind BetweenCriteria @param stmt the PreparedStatement @param index the position of the parameter to bind @param crit the Criteria containing the parameter @param cld the ClassDescriptor @return next index for PreparedStatement
[ "bind", "BetweenCriteria" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/StatementManager.java#L295-L300
apache/incubator-shardingsphere
sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/ShardingExecuteEngine.java
ShardingExecuteEngine.groupExecute
public <I, O> List<O> groupExecute(final Collection<ShardingExecuteGroup<I>> inputGroups, final ShardingGroupExecuteCallback<I, O> callback) throws SQLException { return groupExecute(inputGroups, null, callback, false); }
java
public <I, O> List<O> groupExecute(final Collection<ShardingExecuteGroup<I>> inputGroups, final ShardingGroupExecuteCallback<I, O> callback) throws SQLException { return groupExecute(inputGroups, null, callback, false); }
[ "public", "<", "I", ",", "O", ">", "List", "<", "O", ">", "groupExecute", "(", "final", "Collection", "<", "ShardingExecuteGroup", "<", "I", ">", ">", "inputGroups", ",", "final", "ShardingGroupExecuteCallback", "<", "I", ",", "O", ">", "callback", ")", ...
Execute for group. @param inputGroups input groups @param callback sharding execute callback @param <I> type of input value @param <O> type of return value @return execute result @throws SQLException throw if execute failure
[ "Execute", "for", "group", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/ShardingExecuteEngine.java#L61-L63
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdxtools_image.java
sdxtools_image.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sdxtools_image_responses result = (sdxtools_image_responses) service.get_payload_formatter().string_to_resource(sdxtools_image_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sdxtools_image_response_array); } sdxtools_image[] result_sdxtools_image = new sdxtools_image[result.sdxtools_image_response_array.length]; for(int i = 0; i < result.sdxtools_image_response_array.length; i++) { result_sdxtools_image[i] = result.sdxtools_image_response_array[i].sdxtools_image[0]; } return result_sdxtools_image; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sdxtools_image_responses result = (sdxtools_image_responses) service.get_payload_formatter().string_to_resource(sdxtools_image_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sdxtools_image_response_array); } sdxtools_image[] result_sdxtools_image = new sdxtools_image[result.sdxtools_image_response_array.length]; for(int i = 0; i < result.sdxtools_image_response_array.length; i++) { result_sdxtools_image[i] = result.sdxtools_image_response_array[i].sdxtools_image[0]; } return result_sdxtools_image; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "sdxtools_image_responses", "result", "=", "(", "sdxtools_image_responses", ")", "service", ".", "get_payload_...
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdxtools_image.java#L265-L282
jbundle/jbundle
base/screen/model/src/main/java/org/jbundle/base/screen/model/ToolScreen.java
ToolScreen.printData
public boolean printData(PrintWriter out, int iPrintOptions) { boolean bControls = super.printData(out, iPrintOptions); bControls = this.getScreenFieldView().printToolbarData(bControls, out, iPrintOptions); return bControls; }
java
public boolean printData(PrintWriter out, int iPrintOptions) { boolean bControls = super.printData(out, iPrintOptions); bControls = this.getScreenFieldView().printToolbarData(bControls, out, iPrintOptions); return bControls; }
[ "public", "boolean", "printData", "(", "PrintWriter", "out", ",", "int", "iPrintOptions", ")", "{", "boolean", "bControls", "=", "super", ".", "printData", "(", "out", ",", "iPrintOptions", ")", ";", "bControls", "=", "this", ".", "getScreenFieldView", "(", ...
Display this control's data in print (view) format. @return true if default params were found for this form. @param out The http output stream. @exception DBException File exception.
[ "Display", "this", "control", "s", "data", "in", "print", "(", "view", ")", "format", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/ToolScreen.java#L201-L206
knightliao/apollo
src/main/java/com/github/knightliao/apollo/redis/RedisClient.java
RedisClient.getSet
public Object getSet(String key, Object value, Integer expiration) throws Exception { Jedis jedis = null; try { jedis = this.jedisPool.getResource(); long begin = System.currentTimeMillis(); // 操作expire成功返回1,失败返回0,仅当均返回1时,实际操作成功 byte[] val = jedis.getSet(SafeEncoder.encode(key), serialize(value)); Object result = deserialize(val); boolean success = true; if (expiration > 0) { Long res = jedis.expire(key, expiration); if (res == 0L) { success = false; } } long end = System.currentTimeMillis(); if (success) { logger.info("getset key:" + key + ", spends: " + (end - begin) + "ms"); } else { logger.info("getset key: " + key + " failed, key has already exists! "); } return result; } catch (Exception e) { logger.error(e.getMessage(), e); this.jedisPool.returnBrokenResource(jedis); throw e; } finally { if (jedis != null) { this.jedisPool.returnResource(jedis); } } }
java
public Object getSet(String key, Object value, Integer expiration) throws Exception { Jedis jedis = null; try { jedis = this.jedisPool.getResource(); long begin = System.currentTimeMillis(); // 操作expire成功返回1,失败返回0,仅当均返回1时,实际操作成功 byte[] val = jedis.getSet(SafeEncoder.encode(key), serialize(value)); Object result = deserialize(val); boolean success = true; if (expiration > 0) { Long res = jedis.expire(key, expiration); if (res == 0L) { success = false; } } long end = System.currentTimeMillis(); if (success) { logger.info("getset key:" + key + ", spends: " + (end - begin) + "ms"); } else { logger.info("getset key: " + key + " failed, key has already exists! "); } return result; } catch (Exception e) { logger.error(e.getMessage(), e); this.jedisPool.returnBrokenResource(jedis); throw e; } finally { if (jedis != null) { this.jedisPool.returnResource(jedis); } } }
[ "public", "Object", "getSet", "(", "String", "key", ",", "Object", "value", ",", "Integer", "expiration", ")", "throws", "Exception", "{", "Jedis", "jedis", "=", "null", ";", "try", "{", "jedis", "=", "this", ".", "jedisPool", ".", "getResource", "(", ")...
get old value and set new value @param key @param value @param expiration @return false if redis did not execute the option @throws Exception @author wangchongjie
[ "get", "old", "value", "and", "set", "new", "value" ]
train
https://github.com/knightliao/apollo/blob/d7a283659fa3e67af6375db8969b2d065a8ce6eb/src/main/java/com/github/knightliao/apollo/redis/RedisClient.java#L162-L197
nguillaumin/slick2d-maven
slick2d-peditor/src/main/java/org/newdawn/slick/tools/peditor/GradientEditor.java
GradientEditor.movePoint
private void movePoint(int mx, int my) { if (!isEnabled()) { return; } if (selected == null) { return; } if (list.indexOf(selected) == 0) { return; } if (list.indexOf(selected) == list.size()-1) { return; } float newPos = (mx - 10) / (float) width; newPos = Math.min(1, newPos); newPos = Math.max(0, newPos); selected.pos = newPos; sortPoints(); fireUpdate(); }
java
private void movePoint(int mx, int my) { if (!isEnabled()) { return; } if (selected == null) { return; } if (list.indexOf(selected) == 0) { return; } if (list.indexOf(selected) == list.size()-1) { return; } float newPos = (mx - 10) / (float) width; newPos = Math.min(1, newPos); newPos = Math.max(0, newPos); selected.pos = newPos; sortPoints(); fireUpdate(); }
[ "private", "void", "movePoint", "(", "int", "mx", ",", "int", "my", ")", "{", "if", "(", "!", "isEnabled", "(", ")", ")", "{", "return", ";", "}", "if", "(", "selected", "==", "null", ")", "{", "return", ";", "}", "if", "(", "list", ".", "index...
Move the current point to the specified mouse location @param mx The x coordinate of the mouse @param my The y coordinate of teh mouse
[ "Move", "the", "current", "point", "to", "the", "specified", "mouse", "location" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-peditor/src/main/java/org/newdawn/slick/tools/peditor/GradientEditor.java#L294-L316
LevelFourAB/commons
commons-types/src/main/java/se/l4/commons/types/Types.java
Types.resolveSubtype
@NonNull public static ResolvedType resolveSubtype(@NonNull ResolvedType superType, @NonNull Class<?> subType) { return typeResolver.resolveSubtype(superType, subType); }
java
@NonNull public static ResolvedType resolveSubtype(@NonNull ResolvedType superType, @NonNull Class<?> subType) { return typeResolver.resolveSubtype(superType, subType); }
[ "@", "NonNull", "public", "static", "ResolvedType", "resolveSubtype", "(", "@", "NonNull", "ResolvedType", "superType", ",", "@", "NonNull", "Class", "<", "?", ">", "subType", ")", "{", "return", "typeResolver", ".", "resolveSubtype", "(", "superType", ",", "s...
Resolve a sub type of the given super type. @param superType the super type @param subType the sub type to resolve @return resolved type @see TypeResolver#resolveSubtype(ResolvedType, Class)
[ "Resolve", "a", "sub", "type", "of", "the", "given", "super", "type", "." ]
train
https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-types/src/main/java/se/l4/commons/types/Types.java#L72-L76
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/XmlContentBuilder.java
XmlContentBuilder.buildNtFile
public Document buildNtFile(String mimeType, String encoding) { Document doc = documentBuilder.newDocument(); Element jcrRoot = createJcrRoot(doc, NT_FILE); Element jcrContent = createJcrContent(doc, jcrRoot, NT_RESOURCE); if (StringUtils.isNotEmpty(mimeType)) { setAttributeNamespaceAware(jcrContent, "jcr:mimeType", mimeType); } if (StringUtils.isNotEmpty(encoding)) { setAttributeNamespaceAware(jcrContent, "jcr:encoding", encoding); } return doc; }
java
public Document buildNtFile(String mimeType, String encoding) { Document doc = documentBuilder.newDocument(); Element jcrRoot = createJcrRoot(doc, NT_FILE); Element jcrContent = createJcrContent(doc, jcrRoot, NT_RESOURCE); if (StringUtils.isNotEmpty(mimeType)) { setAttributeNamespaceAware(jcrContent, "jcr:mimeType", mimeType); } if (StringUtils.isNotEmpty(encoding)) { setAttributeNamespaceAware(jcrContent, "jcr:encoding", encoding); } return doc; }
[ "public", "Document", "buildNtFile", "(", "String", "mimeType", ",", "String", "encoding", ")", "{", "Document", "doc", "=", "documentBuilder", ".", "newDocument", "(", ")", ";", "Element", "jcrRoot", "=", "createJcrRoot", "(", "doc", ",", "NT_FILE", ")", ";...
Build XML for nt:file @param mimeType Mime type @param encoding Encoding @return nt:file XML
[ "Build", "XML", "for", "nt", ":", "file" ]
train
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/XmlContentBuilder.java#L136-L149