repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
elki-project/elki
elki-database/src/main/java/de/lmu/ifi/dbs/elki/database/HashmapDatabase.java
HashmapDatabase.alignColumns
protected Relation<?>[] alignColumns(ObjectBundle pack) { """ Find a mapping from package columns to database columns, eventually adding new database columns when needed. @param pack Package to process @return Column mapping """ // align representations. Relation<?>[] targets = new Relation<?>[pack.metaLength()]; long[] used = BitsUtil.zero(relations.size()); for(int i = 0; i < targets.length; i++) { SimpleTypeInformation<?> meta = pack.meta(i); // TODO: aggressively try to match exact metas first? // Try to match unused representations only for(int j = BitsUtil.nextClearBit(used, 0); j >= 0 && j < relations.size(); j = BitsUtil.nextClearBit(used, j + 1)) { Relation<?> relation = relations.get(j); if(relation.getDataTypeInformation().isAssignableFromType(meta)) { targets[i] = relation; BitsUtil.setI(used, j); break; } } if(targets[i] == null) { targets[i] = addNewRelation(meta); BitsUtil.setI(used, relations.size() - 1); } } return targets; }
java
protected Relation<?>[] alignColumns(ObjectBundle pack) { // align representations. Relation<?>[] targets = new Relation<?>[pack.metaLength()]; long[] used = BitsUtil.zero(relations.size()); for(int i = 0; i < targets.length; i++) { SimpleTypeInformation<?> meta = pack.meta(i); // TODO: aggressively try to match exact metas first? // Try to match unused representations only for(int j = BitsUtil.nextClearBit(used, 0); j >= 0 && j < relations.size(); j = BitsUtil.nextClearBit(used, j + 1)) { Relation<?> relation = relations.get(j); if(relation.getDataTypeInformation().isAssignableFromType(meta)) { targets[i] = relation; BitsUtil.setI(used, j); break; } } if(targets[i] == null) { targets[i] = addNewRelation(meta); BitsUtil.setI(used, relations.size() - 1); } } return targets; }
[ "protected", "Relation", "<", "?", ">", "[", "]", "alignColumns", "(", "ObjectBundle", "pack", ")", "{", "// align representations.", "Relation", "<", "?", ">", "[", "]", "targets", "=", "new", "Relation", "<", "?", ">", "[", "pack", ".", "metaLength", "(", ")", "]", ";", "long", "[", "]", "used", "=", "BitsUtil", ".", "zero", "(", "relations", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "targets", ".", "length", ";", "i", "++", ")", "{", "SimpleTypeInformation", "<", "?", ">", "meta", "=", "pack", ".", "meta", "(", "i", ")", ";", "// TODO: aggressively try to match exact metas first?", "// Try to match unused representations only", "for", "(", "int", "j", "=", "BitsUtil", ".", "nextClearBit", "(", "used", ",", "0", ")", ";", "j", ">=", "0", "&&", "j", "<", "relations", ".", "size", "(", ")", ";", "j", "=", "BitsUtil", ".", "nextClearBit", "(", "used", ",", "j", "+", "1", ")", ")", "{", "Relation", "<", "?", ">", "relation", "=", "relations", ".", "get", "(", "j", ")", ";", "if", "(", "relation", ".", "getDataTypeInformation", "(", ")", ".", "isAssignableFromType", "(", "meta", ")", ")", "{", "targets", "[", "i", "]", "=", "relation", ";", "BitsUtil", ".", "setI", "(", "used", ",", "j", ")", ";", "break", ";", "}", "}", "if", "(", "targets", "[", "i", "]", "==", "null", ")", "{", "targets", "[", "i", "]", "=", "addNewRelation", "(", "meta", ")", ";", "BitsUtil", ".", "setI", "(", "used", ",", "relations", ".", "size", "(", ")", "-", "1", ")", ";", "}", "}", "return", "targets", ";", "}" ]
Find a mapping from package columns to database columns, eventually adding new database columns when needed. @param pack Package to process @return Column mapping
[ "Find", "a", "mapping", "from", "package", "columns", "to", "database", "columns", "eventually", "adding", "new", "database", "columns", "when", "needed", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-database/src/main/java/de/lmu/ifi/dbs/elki/database/HashmapDatabase.java#L170-L192
johnkil/Android-AppMsg
library/src/com/devspark/appmsg/AppMsg.java
AppMsg.makeText
public static AppMsg makeText(Activity context, CharSequence text, Style style, int layoutId) { """ Make a {@link AppMsg} with a custom layout. The layout must have a {@link TextView} com id {@link android.R.id.message} @param context The context to use. Usually your {@link android.app.Activity} object. @param text The text to show. Can be formatted text. @param style The style with a background and a duration. """ LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(layoutId, null); return makeText(context, text, style, v, true); }
java
public static AppMsg makeText(Activity context, CharSequence text, Style style, int layoutId) { LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(layoutId, null); return makeText(context, text, style, v, true); }
[ "public", "static", "AppMsg", "makeText", "(", "Activity", "context", ",", "CharSequence", "text", ",", "Style", "style", ",", "int", "layoutId", ")", "{", "LayoutInflater", "inflate", "=", "(", "LayoutInflater", ")", "context", ".", "getSystemService", "(", "Context", ".", "LAYOUT_INFLATER_SERVICE", ")", ";", "View", "v", "=", "inflate", ".", "inflate", "(", "layoutId", ",", "null", ")", ";", "return", "makeText", "(", "context", ",", "text", ",", "style", ",", "v", ",", "true", ")", ";", "}" ]
Make a {@link AppMsg} with a custom layout. The layout must have a {@link TextView} com id {@link android.R.id.message} @param context The context to use. Usually your {@link android.app.Activity} object. @param text The text to show. Can be formatted text. @param style The style with a background and a duration.
[ "Make", "a", "{", "@link", "AppMsg", "}", "with", "a", "custom", "layout", ".", "The", "layout", "must", "have", "a", "{", "@link", "TextView", "}", "com", "id", "{", "@link", "android", ".", "R", ".", "id", ".", "message", "}" ]
train
https://github.com/johnkil/Android-AppMsg/blob/e7fdd7870530a24e6d825278ee0863be0521e8b8/library/src/com/devspark/appmsg/AppMsg.java#L184-L190
square/okhttp
okhttp/src/main/java/okhttp3/internal/ws/WebSocketWriter.java
WebSocketWriter.writeClose
void writeClose(int code, ByteString reason) throws IOException { """ Send a close frame with optional code and reason. @param code Status code as defined by <a href="http://tools.ietf.org/html/rfc6455#section-7.4">Section 7.4 of RFC 6455</a> or {@code 0}. @param reason Reason for shutting down or {@code null}. """ ByteString payload = ByteString.EMPTY; if (code != 0 || reason != null) { if (code != 0) { validateCloseCode(code); } Buffer buffer = new Buffer(); buffer.writeShort(code); if (reason != null) { buffer.write(reason); } payload = buffer.readByteString(); } try { writeControlFrame(OPCODE_CONTROL_CLOSE, payload); } finally { writerClosed = true; } }
java
void writeClose(int code, ByteString reason) throws IOException { ByteString payload = ByteString.EMPTY; if (code != 0 || reason != null) { if (code != 0) { validateCloseCode(code); } Buffer buffer = new Buffer(); buffer.writeShort(code); if (reason != null) { buffer.write(reason); } payload = buffer.readByteString(); } try { writeControlFrame(OPCODE_CONTROL_CLOSE, payload); } finally { writerClosed = true; } }
[ "void", "writeClose", "(", "int", "code", ",", "ByteString", "reason", ")", "throws", "IOException", "{", "ByteString", "payload", "=", "ByteString", ".", "EMPTY", ";", "if", "(", "code", "!=", "0", "||", "reason", "!=", "null", ")", "{", "if", "(", "code", "!=", "0", ")", "{", "validateCloseCode", "(", "code", ")", ";", "}", "Buffer", "buffer", "=", "new", "Buffer", "(", ")", ";", "buffer", ".", "writeShort", "(", "code", ")", ";", "if", "(", "reason", "!=", "null", ")", "{", "buffer", ".", "write", "(", "reason", ")", ";", "}", "payload", "=", "buffer", ".", "readByteString", "(", ")", ";", "}", "try", "{", "writeControlFrame", "(", "OPCODE_CONTROL_CLOSE", ",", "payload", ")", ";", "}", "finally", "{", "writerClosed", "=", "true", ";", "}", "}" ]
Send a close frame with optional code and reason. @param code Status code as defined by <a href="http://tools.ietf.org/html/rfc6455#section-7.4">Section 7.4 of RFC 6455</a> or {@code 0}. @param reason Reason for shutting down or {@code null}.
[ "Send", "a", "close", "frame", "with", "optional", "code", "and", "reason", "." ]
train
https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/ws/WebSocketWriter.java#L91-L110
google/closure-compiler
src/com/google/javascript/refactoring/ApplySuggestedFixes.java
ApplySuggestedFixes.applyCodeReplacements
public static String applyCodeReplacements(Iterable<CodeReplacement> replacements, String code) { """ Applies the provided set of code replacements to the code and returns the transformed code. The code replacements may not have any overlap. """ List<CodeReplacement> sortedReplacements = ORDER_CODE_REPLACEMENTS.sortedCopy(replacements); validateNoOverlaps(sortedReplacements); StringBuilder sb = new StringBuilder(); int lastIndex = 0; for (CodeReplacement replacement : sortedReplacements) { sb.append(code, lastIndex, replacement.getStartPosition()); sb.append(replacement.getNewContent()); lastIndex = replacement.getEndPosition(); } if (lastIndex <= code.length()) { sb.append(code, lastIndex, code.length()); } return sb.toString(); }
java
public static String applyCodeReplacements(Iterable<CodeReplacement> replacements, String code) { List<CodeReplacement> sortedReplacements = ORDER_CODE_REPLACEMENTS.sortedCopy(replacements); validateNoOverlaps(sortedReplacements); StringBuilder sb = new StringBuilder(); int lastIndex = 0; for (CodeReplacement replacement : sortedReplacements) { sb.append(code, lastIndex, replacement.getStartPosition()); sb.append(replacement.getNewContent()); lastIndex = replacement.getEndPosition(); } if (lastIndex <= code.length()) { sb.append(code, lastIndex, code.length()); } return sb.toString(); }
[ "public", "static", "String", "applyCodeReplacements", "(", "Iterable", "<", "CodeReplacement", ">", "replacements", ",", "String", "code", ")", "{", "List", "<", "CodeReplacement", ">", "sortedReplacements", "=", "ORDER_CODE_REPLACEMENTS", ".", "sortedCopy", "(", "replacements", ")", ";", "validateNoOverlaps", "(", "sortedReplacements", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "lastIndex", "=", "0", ";", "for", "(", "CodeReplacement", "replacement", ":", "sortedReplacements", ")", "{", "sb", ".", "append", "(", "code", ",", "lastIndex", ",", "replacement", ".", "getStartPosition", "(", ")", ")", ";", "sb", ".", "append", "(", "replacement", ".", "getNewContent", "(", ")", ")", ";", "lastIndex", "=", "replacement", ".", "getEndPosition", "(", ")", ";", "}", "if", "(", "lastIndex", "<=", "code", ".", "length", "(", ")", ")", "{", "sb", ".", "append", "(", "code", ",", "lastIndex", ",", "code", ".", "length", "(", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Applies the provided set of code replacements to the code and returns the transformed code. The code replacements may not have any overlap.
[ "Applies", "the", "provided", "set", "of", "code", "replacements", "to", "the", "code", "and", "returns", "the", "transformed", "code", ".", "The", "code", "replacements", "may", "not", "have", "any", "overlap", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/refactoring/ApplySuggestedFixes.java#L146-L161
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Bar.java
Bar.setColorGradient
public void setColorGradient(int x1, int y1, ColorRgba color1, int x2, int y2, ColorRgba color2) { """ Set a gradient color from point 1 with color 1 to point2 with color 2. @param x1 The first horizontal location. @param y1 The first vertical location. @param color1 The first color. @param x2 The last horizontal location. @param y2 The last vertical location. @param color2 The last color. """ gradientColor = new ColorGradient(x1, y1, color1, x2, y2, color2); }
java
public void setColorGradient(int x1, int y1, ColorRgba color1, int x2, int y2, ColorRgba color2) { gradientColor = new ColorGradient(x1, y1, color1, x2, y2, color2); }
[ "public", "void", "setColorGradient", "(", "int", "x1", ",", "int", "y1", ",", "ColorRgba", "color1", ",", "int", "x2", ",", "int", "y2", ",", "ColorRgba", "color2", ")", "{", "gradientColor", "=", "new", "ColorGradient", "(", "x1", ",", "y1", ",", "color1", ",", "x2", ",", "y2", ",", "color2", ")", ";", "}" ]
Set a gradient color from point 1 with color 1 to point2 with color 2. @param x1 The first horizontal location. @param y1 The first vertical location. @param color1 The first color. @param x2 The last horizontal location. @param y2 The last vertical location. @param color2 The last color.
[ "Set", "a", "gradient", "color", "from", "point", "1", "with", "color", "1", "to", "point2", "with", "color", "2", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Bar.java#L209-L212
BoltsFramework/Bolts-Android
bolts-applinks/src/main/java/bolts/AppLinkNavigation.java
AppLinkNavigation.navigateInBackground
public static Task<NavigationResult> navigateInBackground(Context context, String destinationUrl, AppLinkResolver resolver) { """ Navigates to an {@link AppLink} for the given destination using the App Link resolution strategy specified. @param context the Context from which the navigation should be performed. @param destinationUrl the destination URL for the App Link. @param resolver the resolver to use for fetching App Link metadata. @return the {@link NavigationResult} performed by navigating. """ return navigateInBackground(context, Uri.parse(destinationUrl), resolver); }
java
public static Task<NavigationResult> navigateInBackground(Context context, String destinationUrl, AppLinkResolver resolver) { return navigateInBackground(context, Uri.parse(destinationUrl), resolver); }
[ "public", "static", "Task", "<", "NavigationResult", ">", "navigateInBackground", "(", "Context", "context", ",", "String", "destinationUrl", ",", "AppLinkResolver", "resolver", ")", "{", "return", "navigateInBackground", "(", "context", ",", "Uri", ".", "parse", "(", "destinationUrl", ")", ",", "resolver", ")", ";", "}" ]
Navigates to an {@link AppLink} for the given destination using the App Link resolution strategy specified. @param context the Context from which the navigation should be performed. @param destinationUrl the destination URL for the App Link. @param resolver the resolver to use for fetching App Link metadata. @return the {@link NavigationResult} performed by navigating.
[ "Navigates", "to", "an", "{", "@link", "AppLink", "}", "for", "the", "given", "destination", "using", "the", "App", "Link", "resolution", "strategy", "specified", "." ]
train
https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-applinks/src/main/java/bolts/AppLinkNavigation.java#L422-L426
FrodeRanders/java-vopn
src/main/java/org/gautelis/vopn/lang/Date.java
Date.convertDate
public static java.sql.Date convertDate(String date, Locale locale) { """ Converts the users input date value to java.sql.Date @param date Date to convert @return The converted date in java.sql.date format """ SimpleDateFormat df; java.util.Date dbDate = null; java.sql.Date sqldate = null; try { if (date == null || date.equals("")) { return null; } df = (SimpleDateFormat) DateFormat.getDateInstance(dateStyle, locale); SimpleDateFormat sdf = new SimpleDateFormat(df.toPattern()); java.text.ParsePosition pos = new java.text.ParsePosition(0); sdf.setLenient(false); dbDate = sdf.parse(date, pos); return new java.sql.Date(dbDate.getTime()); } catch (Exception e) { return null; } }
java
public static java.sql.Date convertDate(String date, Locale locale) { SimpleDateFormat df; java.util.Date dbDate = null; java.sql.Date sqldate = null; try { if (date == null || date.equals("")) { return null; } df = (SimpleDateFormat) DateFormat.getDateInstance(dateStyle, locale); SimpleDateFormat sdf = new SimpleDateFormat(df.toPattern()); java.text.ParsePosition pos = new java.text.ParsePosition(0); sdf.setLenient(false); dbDate = sdf.parse(date, pos); return new java.sql.Date(dbDate.getTime()); } catch (Exception e) { return null; } }
[ "public", "static", "java", ".", "sql", ".", "Date", "convertDate", "(", "String", "date", ",", "Locale", "locale", ")", "{", "SimpleDateFormat", "df", ";", "java", ".", "util", ".", "Date", "dbDate", "=", "null", ";", "java", ".", "sql", ".", "Date", "sqldate", "=", "null", ";", "try", "{", "if", "(", "date", "==", "null", "||", "date", ".", "equals", "(", "\"\"", ")", ")", "{", "return", "null", ";", "}", "df", "=", "(", "SimpleDateFormat", ")", "DateFormat", ".", "getDateInstance", "(", "dateStyle", ",", "locale", ")", ";", "SimpleDateFormat", "sdf", "=", "new", "SimpleDateFormat", "(", "df", ".", "toPattern", "(", ")", ")", ";", "java", ".", "text", ".", "ParsePosition", "pos", "=", "new", "java", ".", "text", ".", "ParsePosition", "(", "0", ")", ";", "sdf", ".", "setLenient", "(", "false", ")", ";", "dbDate", "=", "sdf", ".", "parse", "(", "date", ",", "pos", ")", ";", "return", "new", "java", ".", "sql", ".", "Date", "(", "dbDate", ".", "getTime", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "}" ]
Converts the users input date value to java.sql.Date @param date Date to convert @return The converted date in java.sql.date format
[ "Converts", "the", "users", "input", "date", "value", "to", "java", ".", "sql", ".", "Date" ]
train
https://github.com/FrodeRanders/java-vopn/blob/4c7b2f90201327af4eaa3cd46b3fee68f864e5cc/src/main/java/org/gautelis/vopn/lang/Date.java#L116-L136
doubledutch/LazyJSON
src/main/java/me/doubledutch/lazyjson/LazyObject.java
LazyObject.optString
public String optString(String key,String defaultValue) { """ Returns the string value stored in this object for the given key. Returns the default value if there is no such key. @param key the name of the field on this object @param defaultValue the default value to return @return the requested string value or the default value if there was no such key """ LazyNode token=getOptionalFieldToken(key); if(token==null)return defaultValue; if(token.type==LazyNode.VALUE_NULL)return defaultValue; return token.getStringValue(); }
java
public String optString(String key,String defaultValue){ LazyNode token=getOptionalFieldToken(key); if(token==null)return defaultValue; if(token.type==LazyNode.VALUE_NULL)return defaultValue; return token.getStringValue(); }
[ "public", "String", "optString", "(", "String", "key", ",", "String", "defaultValue", ")", "{", "LazyNode", "token", "=", "getOptionalFieldToken", "(", "key", ")", ";", "if", "(", "token", "==", "null", ")", "return", "defaultValue", ";", "if", "(", "token", ".", "type", "==", "LazyNode", ".", "VALUE_NULL", ")", "return", "defaultValue", ";", "return", "token", ".", "getStringValue", "(", ")", ";", "}" ]
Returns the string value stored in this object for the given key. Returns the default value if there is no such key. @param key the name of the field on this object @param defaultValue the default value to return @return the requested string value or the default value if there was no such key
[ "Returns", "the", "string", "value", "stored", "in", "this", "object", "for", "the", "given", "key", ".", "Returns", "the", "default", "value", "if", "there", "is", "no", "such", "key", "." ]
train
https://github.com/doubledutch/LazyJSON/blob/1a223f57fc0cb9941bc175739697ac95da5618cc/src/main/java/me/doubledutch/lazyjson/LazyObject.java#L363-L368
Azure/azure-sdk-for-java
signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java
SignalRsInner.checkNameAvailability
public NameAvailabilityInner checkNameAvailability(String location, NameAvailabilityParameters parameters) { """ Checks that the SignalR name is valid and is not already in use. @param location the region @param parameters Parameters supplied to the operation. @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 NameAvailabilityInner object if successful. """ return checkNameAvailabilityWithServiceResponseAsync(location, parameters).toBlocking().single().body(); }
java
public NameAvailabilityInner checkNameAvailability(String location, NameAvailabilityParameters parameters) { return checkNameAvailabilityWithServiceResponseAsync(location, parameters).toBlocking().single().body(); }
[ "public", "NameAvailabilityInner", "checkNameAvailability", "(", "String", "location", ",", "NameAvailabilityParameters", "parameters", ")", "{", "return", "checkNameAvailabilityWithServiceResponseAsync", "(", "location", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Checks that the SignalR name is valid and is not already in use. @param location the region @param parameters Parameters supplied to the operation. @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 NameAvailabilityInner object if successful.
[ "Checks", "that", "the", "SignalR", "name", "is", "valid", "and", "is", "not", "already", "in", "use", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java#L216-L218
forge/javaee-descriptors
impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/jsptaglibrary20/WebJsptaglibraryDescriptorImpl.java
WebJsptaglibraryDescriptorImpl.addNamespace
public WebJsptaglibraryDescriptor addNamespace(String name, String value) { """ Adds a new namespace @return the current instance of <code>WebJsptaglibraryDescriptor</code> """ model.attribute(name, value); return this; }
java
public WebJsptaglibraryDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
[ "public", "WebJsptaglibraryDescriptor", "addNamespace", "(", "String", "name", ",", "String", "value", ")", "{", "model", ".", "attribute", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a new namespace @return the current instance of <code>WebJsptaglibraryDescriptor</code>
[ "Adds", "a", "new", "namespace" ]
train
https://github.com/forge/javaee-descriptors/blob/cb914330a1a0b04bfc1d0f199bd9cde3bbf0b3ed/impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/jsptaglibrary20/WebJsptaglibraryDescriptorImpl.java#L91-L95
Netflix/eureka
eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java
DeserializerStringCache.apply
public String apply(CharBuffer charValue, CacheScope cacheScope) { """ returns a object of type T that may be interned at the specified scope to reduce heap consumption @param charValue @param cacheScope @param trabsform @return a possibly interned instance of T """ int keyLength = charValue.length(); if ((lengthLimit < 0 || keyLength <= lengthLimit)) { Map<CharBuffer, String> cache = (cacheScope == CacheScope.GLOBAL_SCOPE) ? globalCache : applicationCache; String value = cache.get(charValue); if (value == null) { value = charValue.consume((k, v) -> { cache.put(k, v); }); } else { // System.out.println("cache hit"); } return value; } return charValue.toString(); }
java
public String apply(CharBuffer charValue, CacheScope cacheScope) { int keyLength = charValue.length(); if ((lengthLimit < 0 || keyLength <= lengthLimit)) { Map<CharBuffer, String> cache = (cacheScope == CacheScope.GLOBAL_SCOPE) ? globalCache : applicationCache; String value = cache.get(charValue); if (value == null) { value = charValue.consume((k, v) -> { cache.put(k, v); }); } else { // System.out.println("cache hit"); } return value; } return charValue.toString(); }
[ "public", "String", "apply", "(", "CharBuffer", "charValue", ",", "CacheScope", "cacheScope", ")", "{", "int", "keyLength", "=", "charValue", ".", "length", "(", ")", ";", "if", "(", "(", "lengthLimit", "<", "0", "||", "keyLength", "<=", "lengthLimit", ")", ")", "{", "Map", "<", "CharBuffer", ",", "String", ">", "cache", "=", "(", "cacheScope", "==", "CacheScope", ".", "GLOBAL_SCOPE", ")", "?", "globalCache", ":", "applicationCache", ";", "String", "value", "=", "cache", ".", "get", "(", "charValue", ")", ";", "if", "(", "value", "==", "null", ")", "{", "value", "=", "charValue", ".", "consume", "(", "(", "k", ",", "v", ")", "->", "{", "cache", ".", "put", "(", "k", ",", "v", ")", ";", "}", ")", ";", "}", "else", "{", "// System.out.println(\"cache hit\");", "}", "return", "value", ";", "}", "return", "charValue", ".", "toString", "(", ")", ";", "}" ]
returns a object of type T that may be interned at the specified scope to reduce heap consumption @param charValue @param cacheScope @param trabsform @return a possibly interned instance of T
[ "returns", "a", "object", "of", "type", "T", "that", "may", "be", "interned", "at", "the", "specified", "scope", "to", "reduce", "heap", "consumption" ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-client/src/main/java/com/netflix/discovery/util/DeserializerStringCache.java#L233-L248
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/factory/transform/wavelet/FactoryWaveletTransform.java
FactoryWaveletTransform.create_F32
public static WaveletTransform<GrayF32, GrayF32,WlCoef_F32> create_F32( WaveletDescription<WlCoef_F32> waveletDesc , int numLevels, float minPixelValue , float maxPixelValue ) { """ Creates a wavelet transform for images that are of type {@link GrayF32}. @param waveletDesc Description of the wavelet. @param numLevels Number of levels in the multi-level transform. @param minPixelValue Minimum pixel intensity value @param maxPixelValue Maximum pixel intensity value @return The transform class. """ return new WaveletTransformFloat32(waveletDesc,numLevels,minPixelValue,maxPixelValue); }
java
public static WaveletTransform<GrayF32, GrayF32,WlCoef_F32> create_F32( WaveletDescription<WlCoef_F32> waveletDesc , int numLevels, float minPixelValue , float maxPixelValue ) { return new WaveletTransformFloat32(waveletDesc,numLevels,minPixelValue,maxPixelValue); }
[ "public", "static", "WaveletTransform", "<", "GrayF32", ",", "GrayF32", ",", "WlCoef_F32", ">", "create_F32", "(", "WaveletDescription", "<", "WlCoef_F32", ">", "waveletDesc", ",", "int", "numLevels", ",", "float", "minPixelValue", ",", "float", "maxPixelValue", ")", "{", "return", "new", "WaveletTransformFloat32", "(", "waveletDesc", ",", "numLevels", ",", "minPixelValue", ",", "maxPixelValue", ")", ";", "}" ]
Creates a wavelet transform for images that are of type {@link GrayF32}. @param waveletDesc Description of the wavelet. @param numLevels Number of levels in the multi-level transform. @param minPixelValue Minimum pixel intensity value @param maxPixelValue Maximum pixel intensity value @return The transform class.
[ "Creates", "a", "wavelet", "transform", "for", "images", "that", "are", "of", "type", "{", "@link", "GrayF32", "}", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/transform/wavelet/FactoryWaveletTransform.java#L86-L92
camunda/camunda-spin
core/src/main/java/org/camunda/spin/impl/util/SpinIoUtil.java
SpinIoUtil.getStringFromReader
public static String getStringFromReader(Reader reader, boolean trim) throws IOException { """ Convert an {@link Reader} to a {@link String} @param reader the {@link Reader} to convert @param trim trigger if whitespaces are trimmed in the output @return the resulting {@link String} @throws IOException """ BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); try { bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { if (trim) { stringBuilder.append(line.trim()); } else { stringBuilder.append(line).append("\n"); } } } finally { closeSilently(bufferedReader); } return stringBuilder.toString(); }
java
public static String getStringFromReader(Reader reader, boolean trim) throws IOException { BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); try { bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { if (trim) { stringBuilder.append(line.trim()); } else { stringBuilder.append(line).append("\n"); } } } finally { closeSilently(bufferedReader); } return stringBuilder.toString(); }
[ "public", "static", "String", "getStringFromReader", "(", "Reader", "reader", ",", "boolean", "trim", ")", "throws", "IOException", "{", "BufferedReader", "bufferedReader", "=", "null", ";", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "bufferedReader", "=", "new", "BufferedReader", "(", "reader", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "trim", ")", "{", "stringBuilder", ".", "append", "(", "line", ".", "trim", "(", ")", ")", ";", "}", "else", "{", "stringBuilder", ".", "append", "(", "line", ")", ".", "append", "(", "\"\\n\"", ")", ";", "}", "}", "}", "finally", "{", "closeSilently", "(", "bufferedReader", ")", ";", "}", "return", "stringBuilder", ".", "toString", "(", ")", ";", "}" ]
Convert an {@link Reader} to a {@link String} @param reader the {@link Reader} to convert @param trim trigger if whitespaces are trimmed in the output @return the resulting {@link String} @throws IOException
[ "Convert", "an", "{", "@link", "Reader", "}", "to", "a", "{", "@link", "String", "}" ]
train
https://github.com/camunda/camunda-spin/blob/cfe65161eb97fd5023a945cb97c47fbfe69e9fdd/core/src/main/java/org/camunda/spin/impl/util/SpinIoUtil.java#L106-L124
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/ByteArrayUtil.java
ByteArrayUtil.putLongBE
public static void putLongBE(final byte[] array, final int offset, final long value) { """ Put the source <i>long</i> into the destination byte array starting at the given offset in big endian order. There is no bounds checking. @param array destination byte array @param offset destination starting point @param value source <i>long</i> """ array[offset + 7] = (byte) (value ); array[offset + 6] = (byte) (value >>> 8); array[offset + 5] = (byte) (value >>> 16); array[offset + 4] = (byte) (value >>> 24); array[offset + 3] = (byte) (value >>> 32); array[offset + 2] = (byte) (value >>> 40); array[offset + 1] = (byte) (value >>> 48); array[offset ] = (byte) (value >>> 56); }
java
public static void putLongBE(final byte[] array, final int offset, final long value) { array[offset + 7] = (byte) (value ); array[offset + 6] = (byte) (value >>> 8); array[offset + 5] = (byte) (value >>> 16); array[offset + 4] = (byte) (value >>> 24); array[offset + 3] = (byte) (value >>> 32); array[offset + 2] = (byte) (value >>> 40); array[offset + 1] = (byte) (value >>> 48); array[offset ] = (byte) (value >>> 56); }
[ "public", "static", "void", "putLongBE", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "long", "value", ")", "{", "array", "[", "offset", "+", "7", "]", "=", "(", "byte", ")", "(", "value", ")", ";", "array", "[", "offset", "+", "6", "]", "=", "(", "byte", ")", "(", "value", ">>>", "8", ")", ";", "array", "[", "offset", "+", "5", "]", "=", "(", "byte", ")", "(", "value", ">>>", "16", ")", ";", "array", "[", "offset", "+", "4", "]", "=", "(", "byte", ")", "(", "value", ">>>", "24", ")", ";", "array", "[", "offset", "+", "3", "]", "=", "(", "byte", ")", "(", "value", ">>>", "32", ")", ";", "array", "[", "offset", "+", "2", "]", "=", "(", "byte", ")", "(", "value", ">>>", "40", ")", ";", "array", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "(", "value", ">>>", "48", ")", ";", "array", "[", "offset", "]", "=", "(", "byte", ")", "(", "value", ">>>", "56", ")", ";", "}" ]
Put the source <i>long</i> into the destination byte array starting at the given offset in big endian order. There is no bounds checking. @param array destination byte array @param offset destination starting point @param value source <i>long</i>
[ "Put", "the", "source", "<i", ">", "long<", "/", "i", ">", "into", "the", "destination", "byte", "array", "starting", "at", "the", "given", "offset", "in", "big", "endian", "order", ".", "There", "is", "no", "bounds", "checking", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/ByteArrayUtil.java#L182-L191
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
DebugUtil.printTimeDifference
public static void printTimeDifference(final long pStartTime, final long pEndTime, final PrintStream pPrintStream) { """ Prints out the difference between two millisecond representations. The start time is subtracted from the end time. <p> @param pStartTime the start time. @param pEndTime the end time. @param pPrintStream the {@code java.io.PrintStream} for flushing the results. """ if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(buildTimeDifference(pStartTime, pEndTime)); }
java
public static void printTimeDifference(final long pStartTime, final long pEndTime, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(buildTimeDifference(pStartTime, pEndTime)); }
[ "public", "static", "void", "printTimeDifference", "(", "final", "long", "pStartTime", ",", "final", "long", "pEndTime", ",", "final", "PrintStream", "pPrintStream", ")", "{", "if", "(", "pPrintStream", "==", "null", ")", "{", "System", ".", "err", ".", "println", "(", "PRINTSTREAM_IS_NULL_ERROR_MESSAGE", ")", ";", "return", ";", "}", "pPrintStream", ".", "println", "(", "buildTimeDifference", "(", "pStartTime", ",", "pEndTime", ")", ")", ";", "}" ]
Prints out the difference between two millisecond representations. The start time is subtracted from the end time. <p> @param pStartTime the start time. @param pEndTime the end time. @param pPrintStream the {@code java.io.PrintStream} for flushing the results.
[ "Prints", "out", "the", "difference", "between", "two", "millisecond", "representations", ".", "The", "start", "time", "is", "subtracted", "from", "the", "end", "time", ".", "<p", ">" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L896-L903
op4j/op4j
src/main/java/org/op4j/Op.java
Op.onArray
public static <T> Level0ArrayOperator<String[],String> onArray(final String[] target) { """ <p> Creates an <i>operation expression</i> on the specified target object. </p> @param target the target object on which the expression will execute @return an operator, ready for chaining """ return onArrayOf(Types.STRING, target); }
java
public static <T> Level0ArrayOperator<String[],String> onArray(final String[] target) { return onArrayOf(Types.STRING, target); }
[ "public", "static", "<", "T", ">", "Level0ArrayOperator", "<", "String", "[", "]", ",", "String", ">", "onArray", "(", "final", "String", "[", "]", "target", ")", "{", "return", "onArrayOf", "(", "Types", ".", "STRING", ",", "target", ")", ";", "}" ]
<p> Creates an <i>operation expression</i> on the specified target object. </p> @param target the target object on which the expression will execute @return an operator, ready for chaining
[ "<p", ">", "Creates", "an", "<i", ">", "operation", "expression<", "/", "i", ">", "on", "the", "specified", "target", "object", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/Op.java#L767-L769
samskivert/samskivert
src/main/java/com/samskivert/swing/util/TaskMaster.java
TaskMaster.invokeTask
public static void invokeTask (String name, Task task, TaskObserver observer) { """ Instructs the task master to run the supplied task. The task is given the supplied name and can be referenced by that name in subsequent dealings with the task master. The supplied observer (if non-null) will be notified when the task has completed. """ // create a task runner and stick it in our task table TaskRunner runner = new TaskRunner(name, task, observer); _tasks.put(name, runner); // then start the runner up runner.start(); }
java
public static void invokeTask (String name, Task task, TaskObserver observer) { // create a task runner and stick it in our task table TaskRunner runner = new TaskRunner(name, task, observer); _tasks.put(name, runner); // then start the runner up runner.start(); }
[ "public", "static", "void", "invokeTask", "(", "String", "name", ",", "Task", "task", ",", "TaskObserver", "observer", ")", "{", "// create a task runner and stick it in our task table", "TaskRunner", "runner", "=", "new", "TaskRunner", "(", "name", ",", "task", ",", "observer", ")", ";", "_tasks", ".", "put", "(", "name", ",", "runner", ")", ";", "// then start the runner up", "runner", ".", "start", "(", ")", ";", "}" ]
Instructs the task master to run the supplied task. The task is given the supplied name and can be referenced by that name in subsequent dealings with the task master. The supplied observer (if non-null) will be notified when the task has completed.
[ "Instructs", "the", "task", "master", "to", "run", "the", "supplied", "task", ".", "The", "task", "is", "given", "the", "supplied", "name", "and", "can", "be", "referenced", "by", "that", "name", "in", "subsequent", "dealings", "with", "the", "task", "master", ".", "The", "supplied", "observer", "(", "if", "non", "-", "null", ")", "will", "be", "notified", "when", "the", "task", "has", "completed", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/util/TaskMaster.java#L35-L42
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/value/basic/ReferenceValueFactory.java
ReferenceValueFactory.newInstance
public static ReferenceValueFactory newInstance( TextDecoder decoder, ValueFactories factories, boolean weak, boolean simple ) { """ Create a new instance. @param decoder the text decoder; may be null if the default decoder should be used @param factories the set of value factories, used to obtain the {@link ValueFactories#getStringFactory() string value factory}; may not be null @param weak true if this factory should create weak references, or false if it should create strong references @param simple true if this factory should create simple references, false otherwise @return the new reference factory; never null """ if (simple) { return new ReferenceValueFactory(PropertyType.SIMPLEREFERENCE, decoder, factories, weak, simple); } return new ReferenceValueFactory(weak ? PropertyType.WEAKREFERENCE : PropertyType.REFERENCE, decoder, factories, weak, simple); }
java
public static ReferenceValueFactory newInstance( TextDecoder decoder, ValueFactories factories, boolean weak, boolean simple ) { if (simple) { return new ReferenceValueFactory(PropertyType.SIMPLEREFERENCE, decoder, factories, weak, simple); } return new ReferenceValueFactory(weak ? PropertyType.WEAKREFERENCE : PropertyType.REFERENCE, decoder, factories, weak, simple); }
[ "public", "static", "ReferenceValueFactory", "newInstance", "(", "TextDecoder", "decoder", ",", "ValueFactories", "factories", ",", "boolean", "weak", ",", "boolean", "simple", ")", "{", "if", "(", "simple", ")", "{", "return", "new", "ReferenceValueFactory", "(", "PropertyType", ".", "SIMPLEREFERENCE", ",", "decoder", ",", "factories", ",", "weak", ",", "simple", ")", ";", "}", "return", "new", "ReferenceValueFactory", "(", "weak", "?", "PropertyType", ".", "WEAKREFERENCE", ":", "PropertyType", ".", "REFERENCE", ",", "decoder", ",", "factories", ",", "weak", ",", "simple", ")", ";", "}" ]
Create a new instance. @param decoder the text decoder; may be null if the default decoder should be used @param factories the set of value factories, used to obtain the {@link ValueFactories#getStringFactory() string value factory}; may not be null @param weak true if this factory should create weak references, or false if it should create strong references @param simple true if this factory should create simple references, false otherwise @return the new reference factory; never null
[ "Create", "a", "new", "instance", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/value/basic/ReferenceValueFactory.java#L59-L68
trellis-ldp/trellis
components/file/src/main/java/org/trellisldp/file/FileUtils.java
FileUtils.parseQuad
public static Stream<Quad> parseQuad(final String line) { """ Parse a string into a stream of Quads. @param line the line of text @return the Quad """ final List<Token> tokens = new ArrayList<>(); makeTokenizerString(line).forEachRemaining(tokens::add); final List<Node> nodes = tokens.stream().filter(Token::isNode).map(Token::asNode).filter(Objects::nonNull) .collect(toList()); if (nodes.size() == 3) { return of(rdf.asQuad(create(defaultGraphIRI, nodes.get(0), nodes.get(1), nodes.get(2)))); } else if (nodes.size() == 4) { return of(rdf.asQuad(create(nodes.get(3), nodes.get(0), nodes.get(1), nodes.get(2)))); } else { LOGGER.warn("Skipping invalid data value: {}", line); return empty(); } }
java
public static Stream<Quad> parseQuad(final String line) { final List<Token> tokens = new ArrayList<>(); makeTokenizerString(line).forEachRemaining(tokens::add); final List<Node> nodes = tokens.stream().filter(Token::isNode).map(Token::asNode).filter(Objects::nonNull) .collect(toList()); if (nodes.size() == 3) { return of(rdf.asQuad(create(defaultGraphIRI, nodes.get(0), nodes.get(1), nodes.get(2)))); } else if (nodes.size() == 4) { return of(rdf.asQuad(create(nodes.get(3), nodes.get(0), nodes.get(1), nodes.get(2)))); } else { LOGGER.warn("Skipping invalid data value: {}", line); return empty(); } }
[ "public", "static", "Stream", "<", "Quad", ">", "parseQuad", "(", "final", "String", "line", ")", "{", "final", "List", "<", "Token", ">", "tokens", "=", "new", "ArrayList", "<>", "(", ")", ";", "makeTokenizerString", "(", "line", ")", ".", "forEachRemaining", "(", "tokens", "::", "add", ")", ";", "final", "List", "<", "Node", ">", "nodes", "=", "tokens", ".", "stream", "(", ")", ".", "filter", "(", "Token", "::", "isNode", ")", ".", "map", "(", "Token", "::", "asNode", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "collect", "(", "toList", "(", ")", ")", ";", "if", "(", "nodes", ".", "size", "(", ")", "==", "3", ")", "{", "return", "of", "(", "rdf", ".", "asQuad", "(", "create", "(", "defaultGraphIRI", ",", "nodes", ".", "get", "(", "0", ")", ",", "nodes", ".", "get", "(", "1", ")", ",", "nodes", ".", "get", "(", "2", ")", ")", ")", ")", ";", "}", "else", "if", "(", "nodes", ".", "size", "(", ")", "==", "4", ")", "{", "return", "of", "(", "rdf", ".", "asQuad", "(", "create", "(", "nodes", ".", "get", "(", "3", ")", ",", "nodes", ".", "get", "(", "0", ")", ",", "nodes", ".", "get", "(", "1", ")", ",", "nodes", ".", "get", "(", "2", ")", ")", ")", ")", ";", "}", "else", "{", "LOGGER", ".", "warn", "(", "\"Skipping invalid data value: {}\"", ",", "line", ")", ";", "return", "empty", "(", ")", ";", "}", "}" ]
Parse a string into a stream of Quads. @param line the line of text @return the Quad
[ "Parse", "a", "string", "into", "a", "stream", "of", "Quads", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/file/src/main/java/org/trellisldp/file/FileUtils.java#L107-L122
elki-project/elki
elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/database/relation/RelationUtil.java
RelationUtil.getColumnLabel
public static <V extends SpatialComparable> String getColumnLabel(Relation<? extends V> rel, int col) { """ Get the column name or produce a generic label "Column XY". @param rel Relation @param col Column @param <V> Vector type @return Label """ SimpleTypeInformation<? extends V> type = rel.getDataTypeInformation(); if(!(type instanceof VectorFieldTypeInformation)) { return "Column " + col; } final VectorFieldTypeInformation<?> vtype = (VectorFieldTypeInformation<?>) type; String lbl = vtype.getLabel(col); return (lbl != null) ? lbl : ("Column " + col); }
java
public static <V extends SpatialComparable> String getColumnLabel(Relation<? extends V> rel, int col) { SimpleTypeInformation<? extends V> type = rel.getDataTypeInformation(); if(!(type instanceof VectorFieldTypeInformation)) { return "Column " + col; } final VectorFieldTypeInformation<?> vtype = (VectorFieldTypeInformation<?>) type; String lbl = vtype.getLabel(col); return (lbl != null) ? lbl : ("Column " + col); }
[ "public", "static", "<", "V", "extends", "SpatialComparable", ">", "String", "getColumnLabel", "(", "Relation", "<", "?", "extends", "V", ">", "rel", ",", "int", "col", ")", "{", "SimpleTypeInformation", "<", "?", "extends", "V", ">", "type", "=", "rel", ".", "getDataTypeInformation", "(", ")", ";", "if", "(", "!", "(", "type", "instanceof", "VectorFieldTypeInformation", ")", ")", "{", "return", "\"Column \"", "+", "col", ";", "}", "final", "VectorFieldTypeInformation", "<", "?", ">", "vtype", "=", "(", "VectorFieldTypeInformation", "<", "?", ">", ")", "type", ";", "String", "lbl", "=", "vtype", ".", "getLabel", "(", "col", ")", ";", "return", "(", "lbl", "!=", "null", ")", "?", "lbl", ":", "(", "\"Column \"", "+", "col", ")", ";", "}" ]
Get the column name or produce a generic label "Column XY". @param rel Relation @param col Column @param <V> Vector type @return Label
[ "Get", "the", "column", "name", "or", "produce", "a", "generic", "label", "Column", "XY", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/database/relation/RelationUtil.java#L162-L170
grails/grails-core
grails-core/src/main/groovy/grails/core/DefaultGrailsApplication.java
DefaultGrailsApplication.addArtefact
public GrailsClass addArtefact(String artefactType, GrailsClass artefactGrailsClass) { """ Adds an artefact of the given type for the given GrailsClass. @param artefactType The type of the artefact as defined by a ArtefactHandler instance @param artefactGrailsClass A GrailsClass instance that matches the type defined by the ArtefactHandler @return The GrailsClass if successful or null if it couldn't be added @throws GrailsConfigurationException If the specified GrailsClass is not the same as the type defined by the ArtefactHandler @see grails.core.ArtefactHandler """ ArtefactHandler handler = artefactHandlersByName.get(artefactType); if (handler.isArtefactGrailsClass(artefactGrailsClass)) { // Store the GrailsClass in cache DefaultArtefactInfo info = getArtefactInfo(artefactType, true); info.addGrailsClass(artefactGrailsClass); info.updateComplete(); initializeArtefacts(artefactType); return artefactGrailsClass; } throw new GrailsConfigurationException("Cannot add " + artefactType + " class [" + artefactGrailsClass + "]. It is not a " + artefactType + "!"); }
java
public GrailsClass addArtefact(String artefactType, GrailsClass artefactGrailsClass) { ArtefactHandler handler = artefactHandlersByName.get(artefactType); if (handler.isArtefactGrailsClass(artefactGrailsClass)) { // Store the GrailsClass in cache DefaultArtefactInfo info = getArtefactInfo(artefactType, true); info.addGrailsClass(artefactGrailsClass); info.updateComplete(); initializeArtefacts(artefactType); return artefactGrailsClass; } throw new GrailsConfigurationException("Cannot add " + artefactType + " class [" + artefactGrailsClass + "]. It is not a " + artefactType + "!"); }
[ "public", "GrailsClass", "addArtefact", "(", "String", "artefactType", ",", "GrailsClass", "artefactGrailsClass", ")", "{", "ArtefactHandler", "handler", "=", "artefactHandlersByName", ".", "get", "(", "artefactType", ")", ";", "if", "(", "handler", ".", "isArtefactGrailsClass", "(", "artefactGrailsClass", ")", ")", "{", "// Store the GrailsClass in cache", "DefaultArtefactInfo", "info", "=", "getArtefactInfo", "(", "artefactType", ",", "true", ")", ";", "info", ".", "addGrailsClass", "(", "artefactGrailsClass", ")", ";", "info", ".", "updateComplete", "(", ")", ";", "initializeArtefacts", "(", "artefactType", ")", ";", "return", "artefactGrailsClass", ";", "}", "throw", "new", "GrailsConfigurationException", "(", "\"Cannot add \"", "+", "artefactType", "+", "\" class [\"", "+", "artefactGrailsClass", "+", "\"]. It is not a \"", "+", "artefactType", "+", "\"!\"", ")", ";", "}" ]
Adds an artefact of the given type for the given GrailsClass. @param artefactType The type of the artefact as defined by a ArtefactHandler instance @param artefactGrailsClass A GrailsClass instance that matches the type defined by the ArtefactHandler @return The GrailsClass if successful or null if it couldn't be added @throws GrailsConfigurationException If the specified GrailsClass is not the same as the type defined by the ArtefactHandler @see grails.core.ArtefactHandler
[ "Adds", "an", "artefact", "of", "the", "given", "type", "for", "the", "given", "GrailsClass", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/core/DefaultGrailsApplication.java#L516-L531
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.offsetOf65KUtf8Bytes
private static int offsetOf65KUtf8Bytes(String str, int startIndex, int endIndex) { """ Returns the largest index between {@code startIndex} and {@code endIdex} such that the UTF8 encoded bytes of {@code str.substring(startIndex, returnValue}} is less than or equal to 65K. """ // This implementation is based off of Utf8.encodedLength int utf8Length = 0; int i = startIndex; for (; i < endIndex; i++) { char c = str.charAt(i); utf8Length++; if (c < 0x800) { utf8Length += (0x7f - c) >>> 31; // branch free! } else { utf8Length += Character.isSurrogate(c) ? 1 : 2; } if (utf8Length == MAX_CONSTANT_STRING_LENGTH) { return i + 1; } else if (utf8Length > MAX_CONSTANT_STRING_LENGTH) { return i; } } return endIndex; }
java
private static int offsetOf65KUtf8Bytes(String str, int startIndex, int endIndex) { // This implementation is based off of Utf8.encodedLength int utf8Length = 0; int i = startIndex; for (; i < endIndex; i++) { char c = str.charAt(i); utf8Length++; if (c < 0x800) { utf8Length += (0x7f - c) >>> 31; // branch free! } else { utf8Length += Character.isSurrogate(c) ? 1 : 2; } if (utf8Length == MAX_CONSTANT_STRING_LENGTH) { return i + 1; } else if (utf8Length > MAX_CONSTANT_STRING_LENGTH) { return i; } } return endIndex; }
[ "private", "static", "int", "offsetOf65KUtf8Bytes", "(", "String", "str", ",", "int", "startIndex", ",", "int", "endIndex", ")", "{", "// This implementation is based off of Utf8.encodedLength", "int", "utf8Length", "=", "0", ";", "int", "i", "=", "startIndex", ";", "for", "(", ";", "i", "<", "endIndex", ";", "i", "++", ")", "{", "char", "c", "=", "str", ".", "charAt", "(", "i", ")", ";", "utf8Length", "++", ";", "if", "(", "c", "<", "0x800", ")", "{", "utf8Length", "+=", "(", "0x7f", "-", "c", ")", ">>>", "31", ";", "// branch free!", "}", "else", "{", "utf8Length", "+=", "Character", ".", "isSurrogate", "(", "c", ")", "?", "1", ":", "2", ";", "}", "if", "(", "utf8Length", "==", "MAX_CONSTANT_STRING_LENGTH", ")", "{", "return", "i", "+", "1", ";", "}", "else", "if", "(", "utf8Length", ">", "MAX_CONSTANT_STRING_LENGTH", ")", "{", "return", "i", ";", "}", "}", "return", "endIndex", ";", "}" ]
Returns the largest index between {@code startIndex} and {@code endIdex} such that the UTF8 encoded bytes of {@code str.substring(startIndex, returnValue}} is less than or equal to 65K.
[ "Returns", "the", "largest", "index", "between", "{" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L333-L352
lastaflute/lastaflute
src/main/java/org/lastaflute/web/LastaAction.java
LastaAction.forwardById
protected HtmlResponse forwardById(Class<?> actionType, Number... ids) { """ Forward to the action (index method) by the IDs on URL. <pre> <span style="color: #3F7E5E">// e.g. /member/edit/3/</span> return forwardById(MemberEditAction.class, 3); <span style="color: #3F7E5E">// e.g. /member/edit/3/197/</span> return forwardById(MemberEditAction.class, 3, 197); <span style="color: #3F7E5E">// e.g. /member/3/</span> return forwardById(MemberAction.class, 3); </pre> @param actionType The class type of action that it forwards to. (NotNull) @param ids The varying array for IDs. (NotNull) @return The HTML response for forward. (NotNull) """ assertArgumentNotNull("actionType", actionType); assertArgumentNotNull("ids", ids); final Object[] objAry = (Object[]) ids; // to suppress warning return forwardWith(actionType, moreUrl(objAry)); }
java
protected HtmlResponse forwardById(Class<?> actionType, Number... ids) { assertArgumentNotNull("actionType", actionType); assertArgumentNotNull("ids", ids); final Object[] objAry = (Object[]) ids; // to suppress warning return forwardWith(actionType, moreUrl(objAry)); }
[ "protected", "HtmlResponse", "forwardById", "(", "Class", "<", "?", ">", "actionType", ",", "Number", "...", "ids", ")", "{", "assertArgumentNotNull", "(", "\"actionType\"", ",", "actionType", ")", ";", "assertArgumentNotNull", "(", "\"ids\"", ",", "ids", ")", ";", "final", "Object", "[", "]", "objAry", "=", "(", "Object", "[", "]", ")", "ids", ";", "// to suppress warning", "return", "forwardWith", "(", "actionType", ",", "moreUrl", "(", "objAry", ")", ")", ";", "}" ]
Forward to the action (index method) by the IDs on URL. <pre> <span style="color: #3F7E5E">// e.g. /member/edit/3/</span> return forwardById(MemberEditAction.class, 3); <span style="color: #3F7E5E">// e.g. /member/edit/3/197/</span> return forwardById(MemberEditAction.class, 3, 197); <span style="color: #3F7E5E">// e.g. /member/3/</span> return forwardById(MemberAction.class, 3); </pre> @param actionType The class type of action that it forwards to. (NotNull) @param ids The varying array for IDs. (NotNull) @return The HTML response for forward. (NotNull)
[ "Forward", "to", "the", "action", "(", "index", "method", ")", "by", "the", "IDs", "on", "URL", ".", "<pre", ">", "<span", "style", "=", "color", ":", "#3F7E5E", ">", "//", "e", ".", "g", ".", "/", "member", "/", "edit", "/", "3", "/", "<", "/", "span", ">", "return", "forwardById", "(", "MemberEditAction", ".", "class", "3", ")", ";" ]
train
https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/web/LastaAction.java#L412-L417
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java
SSLAlpnNegotiator.tryToRegisterAlpnNegotiator
protected ThirdPartyAlpnNegotiator tryToRegisterAlpnNegotiator(SSLEngine engine, SSLConnectionLink link, boolean useAlpn) { """ Check for the Java 9 ALPN API, IBM's ALPNJSSEExt, jetty-alpn, and grizzly-npn; if any are present, set up the connection for ALPN. Order of preference is Java 9 ALPN API, IBM's ALPNJSSEExt, jetty-alpn, then grizzly-npn. @param SSLEngine @param SSLConnectionLink @param useAlpn true if alpn should be used @return ThirdPartyAlpnNegotiator used for this connection, or null if ALPN is not available or the Java 9 / IBM provider was used """ if (isNativeAlpnActive()) { if (useAlpn) { registerNativeAlpn(engine); } } else if (isIbmAlpnActive()) { registerIbmAlpn(engine, useAlpn); } else if (this.isJettyAlpnActive() && useAlpn) { return registerJettyAlpn(engine, link); } else if (this.isGrizzlyAlpnActive() && useAlpn) { return registerGrizzlyAlpn(engine, link); } return null; }
java
protected ThirdPartyAlpnNegotiator tryToRegisterAlpnNegotiator(SSLEngine engine, SSLConnectionLink link, boolean useAlpn) { if (isNativeAlpnActive()) { if (useAlpn) { registerNativeAlpn(engine); } } else if (isIbmAlpnActive()) { registerIbmAlpn(engine, useAlpn); } else if (this.isJettyAlpnActive() && useAlpn) { return registerJettyAlpn(engine, link); } else if (this.isGrizzlyAlpnActive() && useAlpn) { return registerGrizzlyAlpn(engine, link); } return null; }
[ "protected", "ThirdPartyAlpnNegotiator", "tryToRegisterAlpnNegotiator", "(", "SSLEngine", "engine", ",", "SSLConnectionLink", "link", ",", "boolean", "useAlpn", ")", "{", "if", "(", "isNativeAlpnActive", "(", ")", ")", "{", "if", "(", "useAlpn", ")", "{", "registerNativeAlpn", "(", "engine", ")", ";", "}", "}", "else", "if", "(", "isIbmAlpnActive", "(", ")", ")", "{", "registerIbmAlpn", "(", "engine", ",", "useAlpn", ")", ";", "}", "else", "if", "(", "this", ".", "isJettyAlpnActive", "(", ")", "&&", "useAlpn", ")", "{", "return", "registerJettyAlpn", "(", "engine", ",", "link", ")", ";", "}", "else", "if", "(", "this", ".", "isGrizzlyAlpnActive", "(", ")", "&&", "useAlpn", ")", "{", "return", "registerGrizzlyAlpn", "(", "engine", ",", "link", ")", ";", "}", "return", "null", ";", "}" ]
Check for the Java 9 ALPN API, IBM's ALPNJSSEExt, jetty-alpn, and grizzly-npn; if any are present, set up the connection for ALPN. Order of preference is Java 9 ALPN API, IBM's ALPNJSSEExt, jetty-alpn, then grizzly-npn. @param SSLEngine @param SSLConnectionLink @param useAlpn true if alpn should be used @return ThirdPartyAlpnNegotiator used for this connection, or null if ALPN is not available or the Java 9 / IBM provider was used
[ "Check", "for", "the", "Java", "9", "ALPN", "API", "IBM", "s", "ALPNJSSEExt", "jetty", "-", "alpn", "and", "grizzly", "-", "npn", ";", "if", "any", "are", "present", "set", "up", "the", "connection", "for", "ALPN", ".", "Order", "of", "preference", "is", "Java", "9", "ALPN", "API", "IBM", "s", "ALPNJSSEExt", "jetty", "-", "alpn", "then", "grizzly", "-", "npn", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java#L202-L215
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.installUpdatesAsync
public Observable<Void> installUpdatesAsync(String deviceName, String resourceGroupName) { """ Installs the updates on the data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return installUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> installUpdatesAsync(String deviceName, String resourceGroupName) { return installUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "installUpdatesAsync", "(", "String", "deviceName", ",", "String", "resourceGroupName", ")", "{", "return", "installUpdatesWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Installs the updates on the data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Installs", "the", "updates", "on", "the", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1467-L1474
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/UnImplNode.java
UnImplNode.getAttributeNodeNS
public Attr getAttributeNodeNS(String namespaceURI, String localName) { """ Unimplemented. See org.w3c.dom.Element @param namespaceURI Namespace URI of attribute node to get @param localName Local part of qualified name of attribute node to get @return null """ error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getAttributeNodeNS not supported!"); return null; }
java
public Attr getAttributeNodeNS(String namespaceURI, String localName) { error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"getAttributeNodeNS not supported!"); return null; }
[ "public", "Attr", "getAttributeNodeNS", "(", "String", "namespaceURI", ",", "String", "localName", ")", "{", "error", "(", "XMLErrorResources", ".", "ER_FUNCTION_NOT_SUPPORTED", ")", ";", "//\"getAttributeNodeNS not supported!\");", "return", "null", ";", "}" ]
Unimplemented. See org.w3c.dom.Element @param namespaceURI Namespace URI of attribute node to get @param localName Local part of qualified name of attribute node to get @return null
[ "Unimplemented", ".", "See", "org", ".", "w3c", ".", "dom", ".", "Element" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/UnImplNode.java#L459-L465
rometools/rome
rome-modules/src/main/java/com/rometools/modules/mediarss/io/MediaModuleGenerator.java
MediaModuleGenerator.generatePrices
private void generatePrices(final Metadata m, final Element e) { """ Generation of backLinks tag. @param m source @param e element to attach new element to """ for (final Price price : m.getPrices()) { if (price == null) { continue; } final Element priceElement = new Element("price", NS); if (price.getType() != null) { priceElement.setAttribute("type", price.getType().name().toLowerCase()); } addNotNullAttribute(priceElement, "info", price.getInfo()); addNotNullAttribute(priceElement, "price", price.getPrice()); addNotNullAttribute(priceElement, "currency", price.getCurrency()); if (priceElement.hasAttributes()) { e.addContent(priceElement); } } }
java
private void generatePrices(final Metadata m, final Element e) { for (final Price price : m.getPrices()) { if (price == null) { continue; } final Element priceElement = new Element("price", NS); if (price.getType() != null) { priceElement.setAttribute("type", price.getType().name().toLowerCase()); } addNotNullAttribute(priceElement, "info", price.getInfo()); addNotNullAttribute(priceElement, "price", price.getPrice()); addNotNullAttribute(priceElement, "currency", price.getCurrency()); if (priceElement.hasAttributes()) { e.addContent(priceElement); } } }
[ "private", "void", "generatePrices", "(", "final", "Metadata", "m", ",", "final", "Element", "e", ")", "{", "for", "(", "final", "Price", "price", ":", "m", ".", "getPrices", "(", ")", ")", "{", "if", "(", "price", "==", "null", ")", "{", "continue", ";", "}", "final", "Element", "priceElement", "=", "new", "Element", "(", "\"price\"", ",", "NS", ")", ";", "if", "(", "price", ".", "getType", "(", ")", "!=", "null", ")", "{", "priceElement", ".", "setAttribute", "(", "\"type\"", ",", "price", ".", "getType", "(", ")", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ")", ";", "}", "addNotNullAttribute", "(", "priceElement", ",", "\"info\"", ",", "price", ".", "getInfo", "(", ")", ")", ";", "addNotNullAttribute", "(", "priceElement", ",", "\"price\"", ",", "price", ".", "getPrice", "(", ")", ")", ";", "addNotNullAttribute", "(", "priceElement", ",", "\"currency\"", ",", "price", ".", "getCurrency", "(", ")", ")", ";", "if", "(", "priceElement", ".", "hasAttributes", "(", ")", ")", "{", "e", ".", "addContent", "(", "priceElement", ")", ";", "}", "}", "}" ]
Generation of backLinks tag. @param m source @param e element to attach new element to
[ "Generation", "of", "backLinks", "tag", "." ]
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-modules/src/main/java/com/rometools/modules/mediarss/io/MediaModuleGenerator.java#L469-L485
jtrfp/jfdt
src/main/java/org/jtrfp/jfdt/Parser.java
Parser.readToExistingBean
public void readToExistingBean(InputStream is, ThirdPartyParseable target) throws IllegalAccessException, UnrecognizedFormatException { """ Read the specified InputStream, parsing it and writing the property values to the given instantiated bean.<br> When finished, the current position of the stream will be immediately after the data extracted. @param is An InputStream supplying the raw data to be parsed. @param target The bean to which the properties are to be updated. Parser is implicitly specified when passing this bean. @throws IllegalAccessException @throws UnrecognizedFormatException @since Sep 17, 2012 """ readToExistingBean(new EndianAwareDataInputStream(new DataInputStream(is)),target); }
java
public void readToExistingBean(InputStream is, ThirdPartyParseable target) throws IllegalAccessException, UnrecognizedFormatException{ readToExistingBean(new EndianAwareDataInputStream(new DataInputStream(is)),target); }
[ "public", "void", "readToExistingBean", "(", "InputStream", "is", ",", "ThirdPartyParseable", "target", ")", "throws", "IllegalAccessException", ",", "UnrecognizedFormatException", "{", "readToExistingBean", "(", "new", "EndianAwareDataInputStream", "(", "new", "DataInputStream", "(", "is", ")", ")", ",", "target", ")", ";", "}" ]
Read the specified InputStream, parsing it and writing the property values to the given instantiated bean.<br> When finished, the current position of the stream will be immediately after the data extracted. @param is An InputStream supplying the raw data to be parsed. @param target The bean to which the properties are to be updated. Parser is implicitly specified when passing this bean. @throws IllegalAccessException @throws UnrecognizedFormatException @since Sep 17, 2012
[ "Read", "the", "specified", "InputStream", "parsing", "it", "and", "writing", "the", "property", "values", "to", "the", "given", "instantiated", "bean", ".", "<br", ">", "When", "finished", "the", "current", "position", "of", "the", "stream", "will", "be", "immediately", "after", "the", "data", "extracted", "." ]
train
https://github.com/jtrfp/jfdt/blob/64e665669b5fcbfe96736346b4e7893e466dd8a0/src/main/java/org/jtrfp/jfdt/Parser.java#L85-L88
pac4j/pac4j
pac4j-saml/src/main/java/org/pac4j/saml/transport/AbstractPac4jDecoder.java
AbstractPac4jDecoder.unmarshallMessage
protected XMLObject unmarshallMessage(InputStream messageStream) throws MessageDecodingException { """ Helper method that deserializes and unmarshalls the message from the given stream. @param messageStream input stream containing the message @return the inbound message @throws MessageDecodingException thrown if there is a problem deserializing and unmarshalling the message """ try { XMLObject message = XMLObjectSupport.unmarshallFromInputStream(getParserPool(), messageStream); return message; } catch (XMLParserException e) { throw new MessageDecodingException("Error unmarshalling message from input stream", e); } catch (UnmarshallingException e) { throw new MessageDecodingException("Error unmarshalling message from input stream", e); } }
java
protected XMLObject unmarshallMessage(InputStream messageStream) throws MessageDecodingException { try { XMLObject message = XMLObjectSupport.unmarshallFromInputStream(getParserPool(), messageStream); return message; } catch (XMLParserException e) { throw new MessageDecodingException("Error unmarshalling message from input stream", e); } catch (UnmarshallingException e) { throw new MessageDecodingException("Error unmarshalling message from input stream", e); } }
[ "protected", "XMLObject", "unmarshallMessage", "(", "InputStream", "messageStream", ")", "throws", "MessageDecodingException", "{", "try", "{", "XMLObject", "message", "=", "XMLObjectSupport", ".", "unmarshallFromInputStream", "(", "getParserPool", "(", ")", ",", "messageStream", ")", ";", "return", "message", ";", "}", "catch", "(", "XMLParserException", "e", ")", "{", "throw", "new", "MessageDecodingException", "(", "\"Error unmarshalling message from input stream\"", ",", "e", ")", ";", "}", "catch", "(", "UnmarshallingException", "e", ")", "{", "throw", "new", "MessageDecodingException", "(", "\"Error unmarshalling message from input stream\"", ",", "e", ")", ";", "}", "}" ]
Helper method that deserializes and unmarshalls the message from the given stream. @param messageStream input stream containing the message @return the inbound message @throws MessageDecodingException thrown if there is a problem deserializing and unmarshalling the message
[ "Helper", "method", "that", "deserializes", "and", "unmarshalls", "the", "message", "from", "the", "given", "stream", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/transport/AbstractPac4jDecoder.java#L123-L132
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/Branch.java
Branch.initSession
public boolean initSession(BranchReferralInitListener callback, Activity activity) { """ <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p> @param callback A {@link BranchReferralInitListener} instance that will be called following successful (or unsuccessful) initialisation of the session with the Branch API. @param activity The calling {@link Activity} for context. @return A {@link Boolean} value, indicating <i>false</i> if initialisation is unsuccessful. """ if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal(callback, activity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal(callback, activity, isReferrable); } return true; }
java
public boolean initSession(BranchReferralInitListener callback, Activity activity) { if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) { initUserSessionInternal(callback, activity, true); } else { boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE; initUserSessionInternal(callback, activity, isReferrable); } return true; }
[ "public", "boolean", "initSession", "(", "BranchReferralInitListener", "callback", ",", "Activity", "activity", ")", "{", "if", "(", "customReferrableSettings_", "==", "CUSTOM_REFERRABLE_SETTINGS", ".", "USE_DEFAULT", ")", "{", "initUserSessionInternal", "(", "callback", ",", "activity", ",", "true", ")", ";", "}", "else", "{", "boolean", "isReferrable", "=", "customReferrableSettings_", "==", "CUSTOM_REFERRABLE_SETTINGS", ".", "REFERRABLE", ";", "initUserSessionInternal", "(", "callback", ",", "activity", ",", "isReferrable", ")", ";", "}", "return", "true", ";", "}" ]
<p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p> @param callback A {@link BranchReferralInitListener} instance that will be called following successful (or unsuccessful) initialisation of the session with the Branch API. @param activity The calling {@link Activity} for context. @return A {@link Boolean} value, indicating <i>false</i> if initialisation is unsuccessful.
[ "<p", ">", "Initialises", "a", "session", "with", "the", "Branch", "API", "passing", "the", "{", "@link", "Activity", "}", "and", "assigning", "a", "{", "@link", "BranchReferralInitListener", "}", "to", "perform", "an", "action", "upon", "successful", "initialisation", ".", "<", "/", "p", ">" ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/Branch.java#L1018-L1026
Metrink/croquet
croquet-core/src/main/java/com/metrink/croquet/CroquetRestBuilder.java
CroquetRestBuilder.checkLoggingSettings
protected void checkLoggingSettings() { """ Runs some checks over the log settings before building a {@link Corquet} instance. """ final LoggingSettings logSettings = settings.getLoggingSettings(); final LogFile logFileSettings = logSettings.getLogFile(); if(logFileSettings.getCurrentLogFilename() != null && logFileSettings.isEnabled() == false) { LOG.warn("You specified a log file, but have it disabled"); } if(logFileSettings.isEnabled() && logFileSettings.getCurrentLogFilename() == null) { throw new IllegalStateException("You enabled logging to a file, but didn't specify the file name"); } }
java
protected void checkLoggingSettings() { final LoggingSettings logSettings = settings.getLoggingSettings(); final LogFile logFileSettings = logSettings.getLogFile(); if(logFileSettings.getCurrentLogFilename() != null && logFileSettings.isEnabled() == false) { LOG.warn("You specified a log file, but have it disabled"); } if(logFileSettings.isEnabled() && logFileSettings.getCurrentLogFilename() == null) { throw new IllegalStateException("You enabled logging to a file, but didn't specify the file name"); } }
[ "protected", "void", "checkLoggingSettings", "(", ")", "{", "final", "LoggingSettings", "logSettings", "=", "settings", ".", "getLoggingSettings", "(", ")", ";", "final", "LogFile", "logFileSettings", "=", "logSettings", ".", "getLogFile", "(", ")", ";", "if", "(", "logFileSettings", ".", "getCurrentLogFilename", "(", ")", "!=", "null", "&&", "logFileSettings", ".", "isEnabled", "(", ")", "==", "false", ")", "{", "LOG", ".", "warn", "(", "\"You specified a log file, but have it disabled\"", ")", ";", "}", "if", "(", "logFileSettings", ".", "isEnabled", "(", ")", "&&", "logFileSettings", ".", "getCurrentLogFilename", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"You enabled logging to a file, but didn't specify the file name\"", ")", ";", "}", "}" ]
Runs some checks over the log settings before building a {@link Corquet} instance.
[ "Runs", "some", "checks", "over", "the", "log", "settings", "before", "building", "a", "{" ]
train
https://github.com/Metrink/croquet/blob/1b0ed1327a104cf1f809ce4c3c5bf30a3d95384b/croquet-core/src/main/java/com/metrink/croquet/CroquetRestBuilder.java#L138-L151
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/store/ServiceBuilder.java
ServiceBuilder.withContainerManager
public ServiceBuilder withContainerManager(Function<ComponentSetup, SegmentContainerManager> segmentContainerManagerCreator) { """ Attaches the given SegmentContainerManager creator to this ServiceBuilder. The given Function will only not be invoked right away; it will be called when needed. @param segmentContainerManagerCreator The Function to attach. @return This ServiceBuilder. """ Preconditions.checkNotNull(segmentContainerManagerCreator, "segmentContainerManagerCreator"); this.segmentContainerManagerCreator = segmentContainerManagerCreator; return this; }
java
public ServiceBuilder withContainerManager(Function<ComponentSetup, SegmentContainerManager> segmentContainerManagerCreator) { Preconditions.checkNotNull(segmentContainerManagerCreator, "segmentContainerManagerCreator"); this.segmentContainerManagerCreator = segmentContainerManagerCreator; return this; }
[ "public", "ServiceBuilder", "withContainerManager", "(", "Function", "<", "ComponentSetup", ",", "SegmentContainerManager", ">", "segmentContainerManagerCreator", ")", "{", "Preconditions", ".", "checkNotNull", "(", "segmentContainerManagerCreator", ",", "\"segmentContainerManagerCreator\"", ")", ";", "this", ".", "segmentContainerManagerCreator", "=", "segmentContainerManagerCreator", ";", "return", "this", ";", "}" ]
Attaches the given SegmentContainerManager creator to this ServiceBuilder. The given Function will only not be invoked right away; it will be called when needed. @param segmentContainerManagerCreator The Function to attach. @return This ServiceBuilder.
[ "Attaches", "the", "given", "SegmentContainerManager", "creator", "to", "this", "ServiceBuilder", ".", "The", "given", "Function", "will", "only", "not", "be", "invoked", "right", "away", ";", "it", "will", "be", "called", "when", "needed", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/store/ServiceBuilder.java#L196-L200
jenkinsci/jenkins
core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java
HudsonPrivateSecurityRealm.loginAndTakeBack
@SuppressWarnings("ACL.impersonate") private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException { """ Lets the current user silently login as the given user and report back accordingly. """ HttpSession session = req.getSession(false); if (session != null) { // avoid session fixation session.invalidate(); } req.getSession(true); // ... and let him login Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = this.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); SecurityListener.fireLoggedIn(u.getId()); // then back to top req.getView(this,"success.jelly").forward(req,rsp); }
java
@SuppressWarnings("ACL.impersonate") private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException { HttpSession session = req.getSession(false); if (session != null) { // avoid session fixation session.invalidate(); } req.getSession(true); // ... and let him login Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = this.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); SecurityListener.fireLoggedIn(u.getId()); // then back to top req.getView(this,"success.jelly").forward(req,rsp); }
[ "@", "SuppressWarnings", "(", "\"ACL.impersonate\"", ")", "private", "void", "loginAndTakeBack", "(", "StaplerRequest", "req", ",", "StaplerResponse", "rsp", ",", "User", "u", ")", "throws", "ServletException", ",", "IOException", "{", "HttpSession", "session", "=", "req", ".", "getSession", "(", "false", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "// avoid session fixation", "session", ".", "invalidate", "(", ")", ";", "}", "req", ".", "getSession", "(", "true", ")", ";", "// ... and let him login", "Authentication", "a", "=", "new", "UsernamePasswordAuthenticationToken", "(", "u", ".", "getId", "(", ")", ",", "req", ".", "getParameter", "(", "\"password1\"", ")", ")", ";", "a", "=", "this", ".", "getSecurityComponents", "(", ")", ".", "manager", ".", "authenticate", "(", "a", ")", ";", "SecurityContextHolder", ".", "getContext", "(", ")", ".", "setAuthentication", "(", "a", ")", ";", "SecurityListener", ".", "fireLoggedIn", "(", "u", ".", "getId", "(", ")", ")", ";", "// then back to top", "req", ".", "getView", "(", "this", ",", "\"success.jelly\"", ")", ".", "forward", "(", "req", ",", "rsp", ")", ";", "}" ]
Lets the current user silently login as the given user and report back accordingly.
[ "Lets", "the", "current", "user", "silently", "login", "as", "the", "given", "user", "and", "report", "back", "accordingly", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java#L269-L287
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java
DriverChannel.setKeyspace
public Future<Void> setKeyspace(CqlIdentifier newKeyspace) { """ Switches the underlying Cassandra connection to a new keyspace (as if a {@code USE ...} statement was issued). <p>The future will complete once the change is effective. Only one change may run at a given time, concurrent attempts will fail. <p>Changing the keyspace is inherently thread-unsafe: if other queries are running at the same time, the keyspace they will use is unpredictable. """ Promise<Void> promise = channel.eventLoop().newPromise(); channel.pipeline().fireUserEventTriggered(new SetKeyspaceEvent(newKeyspace, promise)); return promise; }
java
public Future<Void> setKeyspace(CqlIdentifier newKeyspace) { Promise<Void> promise = channel.eventLoop().newPromise(); channel.pipeline().fireUserEventTriggered(new SetKeyspaceEvent(newKeyspace, promise)); return promise; }
[ "public", "Future", "<", "Void", ">", "setKeyspace", "(", "CqlIdentifier", "newKeyspace", ")", "{", "Promise", "<", "Void", ">", "promise", "=", "channel", ".", "eventLoop", "(", ")", ".", "newPromise", "(", ")", ";", "channel", ".", "pipeline", "(", ")", ".", "fireUserEventTriggered", "(", "new", "SetKeyspaceEvent", "(", "newKeyspace", ",", "promise", ")", ")", ";", "return", "promise", ";", "}" ]
Switches the underlying Cassandra connection to a new keyspace (as if a {@code USE ...} statement was issued). <p>The future will complete once the change is effective. Only one change may run at a given time, concurrent attempts will fail. <p>Changing the keyspace is inherently thread-unsafe: if other queries are running at the same time, the keyspace they will use is unpredictable.
[ "Switches", "the", "underlying", "Cassandra", "connection", "to", "a", "new", "keyspace", "(", "as", "if", "a", "{", "@code", "USE", "...", "}", "statement", "was", "issued", ")", "." ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java#L109-L113
kopihao/peasy-recyclerview
peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java
PeasyRecyclerView.configureRecyclerViewTouchEvent
private void configureRecyclerViewTouchEvent() { """ * Provide default {@link RecyclerView.OnItemTouchListener} of provided recyclerView """ getRecyclerView().addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { @Override public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { if (isEnhancedFAB() && getFab() != null) { enhanceFAB(getFab(), e); } onViewInterceptTouchEvent(rv, e); return false; } @Override public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }); }
java
private void configureRecyclerViewTouchEvent() { getRecyclerView().addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { @Override public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { if (isEnhancedFAB() && getFab() != null) { enhanceFAB(getFab(), e); } onViewInterceptTouchEvent(rv, e); return false; } @Override public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }); }
[ "private", "void", "configureRecyclerViewTouchEvent", "(", ")", "{", "getRecyclerView", "(", ")", ".", "addOnItemTouchListener", "(", "new", "RecyclerView", ".", "OnItemTouchListener", "(", ")", "{", "@", "Override", "public", "boolean", "onInterceptTouchEvent", "(", "@", "NonNull", "RecyclerView", "rv", ",", "@", "NonNull", "MotionEvent", "e", ")", "{", "if", "(", "isEnhancedFAB", "(", ")", "&&", "getFab", "(", ")", "!=", "null", ")", "{", "enhanceFAB", "(", "getFab", "(", ")", ",", "e", ")", ";", "}", "onViewInterceptTouchEvent", "(", "rv", ",", "e", ")", ";", "return", "false", ";", "}", "@", "Override", "public", "void", "onTouchEvent", "(", "@", "NonNull", "RecyclerView", "rv", ",", "@", "NonNull", "MotionEvent", "e", ")", "{", "}", "@", "Override", "public", "void", "onRequestDisallowInterceptTouchEvent", "(", "boolean", "disallowIntercept", ")", "{", "}", "}", ")", ";", "}" ]
* Provide default {@link RecyclerView.OnItemTouchListener} of provided recyclerView
[ "*", "Provide", "default", "{" ]
train
https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L142-L162
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
CSL.makeBibliography
public Bibliography makeBibliography(SelectionMode mode, CSLItemData... selection) { """ Generates a bibliography for the registered citations. Depending on the selection mode selects, includes, or excludes bibliography items whose fields and field values match the fields and field values from the given example item data objects. @param mode the selection mode @param selection the example item data objects that contain the fields and field values to match @return the bibliography """ return makeBibliography(mode, selection, null); }
java
public Bibliography makeBibliography(SelectionMode mode, CSLItemData... selection) { return makeBibliography(mode, selection, null); }
[ "public", "Bibliography", "makeBibliography", "(", "SelectionMode", "mode", ",", "CSLItemData", "...", "selection", ")", "{", "return", "makeBibliography", "(", "mode", ",", "selection", ",", "null", ")", ";", "}" ]
Generates a bibliography for the registered citations. Depending on the selection mode selects, includes, or excludes bibliography items whose fields and field values match the fields and field values from the given example item data objects. @param mode the selection mode @param selection the example item data objects that contain the fields and field values to match @return the bibliography
[ "Generates", "a", "bibliography", "for", "the", "registered", "citations", ".", "Depending", "on", "the", "selection", "mode", "selects", "includes", "or", "excludes", "bibliography", "items", "whose", "fields", "and", "field", "values", "match", "the", "fields", "and", "field", "values", "from", "the", "given", "example", "item", "data", "objects", "." ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L739-L741
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/widget/FacebookDialog.java
FacebookDialog.canPresentMessageDialog
public static boolean canPresentMessageDialog(Context context, MessageDialogFeature... features) { """ Determines whether the version of the Facebook application installed on the user's device is recent enough to support specific features of the native Message dialog, which in turn may be used to determine which UI, etc., to present to the user. @param context the calling Context @param features zero or more features to check for; {@link com.facebook.widget.FacebookDialog.MessageDialogFeature#MESSAGE_DIALOG} is implicitly checked if not explicitly specified @return true if all of the specified features are supported by the currently installed version of the Facebook application; false if any of the features are not supported """ return handleCanPresent(context, EnumSet.of(MessageDialogFeature.MESSAGE_DIALOG, features)); }
java
public static boolean canPresentMessageDialog(Context context, MessageDialogFeature... features) { return handleCanPresent(context, EnumSet.of(MessageDialogFeature.MESSAGE_DIALOG, features)); }
[ "public", "static", "boolean", "canPresentMessageDialog", "(", "Context", "context", ",", "MessageDialogFeature", "...", "features", ")", "{", "return", "handleCanPresent", "(", "context", ",", "EnumSet", ".", "of", "(", "MessageDialogFeature", ".", "MESSAGE_DIALOG", ",", "features", ")", ")", ";", "}" ]
Determines whether the version of the Facebook application installed on the user's device is recent enough to support specific features of the native Message dialog, which in turn may be used to determine which UI, etc., to present to the user. @param context the calling Context @param features zero or more features to check for; {@link com.facebook.widget.FacebookDialog.MessageDialogFeature#MESSAGE_DIALOG} is implicitly checked if not explicitly specified @return true if all of the specified features are supported by the currently installed version of the Facebook application; false if any of the features are not supported
[ "Determines", "whether", "the", "version", "of", "the", "Facebook", "application", "installed", "on", "the", "user", "s", "device", "is", "recent", "enough", "to", "support", "specific", "features", "of", "the", "native", "Message", "dialog", "which", "in", "turn", "may", "be", "used", "to", "determine", "which", "UI", "etc", ".", "to", "present", "to", "the", "user", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookDialog.java#L384-L386
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/TimeSeriesUtils.java
TimeSeriesUtils.movingAverage
public static INDArray movingAverage(INDArray toAvg, int n) { """ Calculate a moving average given the length @param toAvg the array to average @param n the length of the moving window @return the moving averages for each row """ INDArray ret = Nd4j.cumsum(toAvg); INDArrayIndex[] ends = new INDArrayIndex[] {NDArrayIndex.interval(n, toAvg.columns())}; INDArrayIndex[] begins = new INDArrayIndex[] {NDArrayIndex.interval(0, toAvg.columns() - n, false)}; INDArrayIndex[] nMinusOne = new INDArrayIndex[] {NDArrayIndex.interval(n - 1, toAvg.columns())}; ret.put(ends, ret.get(ends).sub(ret.get(begins))); return ret.get(nMinusOne).divi(n); }
java
public static INDArray movingAverage(INDArray toAvg, int n) { INDArray ret = Nd4j.cumsum(toAvg); INDArrayIndex[] ends = new INDArrayIndex[] {NDArrayIndex.interval(n, toAvg.columns())}; INDArrayIndex[] begins = new INDArrayIndex[] {NDArrayIndex.interval(0, toAvg.columns() - n, false)}; INDArrayIndex[] nMinusOne = new INDArrayIndex[] {NDArrayIndex.interval(n - 1, toAvg.columns())}; ret.put(ends, ret.get(ends).sub(ret.get(begins))); return ret.get(nMinusOne).divi(n); }
[ "public", "static", "INDArray", "movingAverage", "(", "INDArray", "toAvg", ",", "int", "n", ")", "{", "INDArray", "ret", "=", "Nd4j", ".", "cumsum", "(", "toAvg", ")", ";", "INDArrayIndex", "[", "]", "ends", "=", "new", "INDArrayIndex", "[", "]", "{", "NDArrayIndex", ".", "interval", "(", "n", ",", "toAvg", ".", "columns", "(", ")", ")", "}", ";", "INDArrayIndex", "[", "]", "begins", "=", "new", "INDArrayIndex", "[", "]", "{", "NDArrayIndex", ".", "interval", "(", "0", ",", "toAvg", ".", "columns", "(", ")", "-", "n", ",", "false", ")", "}", ";", "INDArrayIndex", "[", "]", "nMinusOne", "=", "new", "INDArrayIndex", "[", "]", "{", "NDArrayIndex", ".", "interval", "(", "n", "-", "1", ",", "toAvg", ".", "columns", "(", ")", ")", "}", ";", "ret", ".", "put", "(", "ends", ",", "ret", ".", "get", "(", "ends", ")", ".", "sub", "(", "ret", ".", "get", "(", "begins", ")", ")", ")", ";", "return", "ret", ".", "get", "(", "nMinusOne", ")", ".", "divi", "(", "n", ")", ";", "}" ]
Calculate a moving average given the length @param toAvg the array to average @param n the length of the moving window @return the moving averages for each row
[ "Calculate", "a", "moving", "average", "given", "the", "length" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/TimeSeriesUtils.java#L49-L56
lamarios/sherdog-parser
src/main/java/com/ftpix/sherdogparser/parsers/ParserUtils.java
ParserUtils.downloadImageToFile
public static void downloadImageToFile(String url, Path file) throws IOException { """ Downloads an image to a file with the adequate headers to the http query @param url the url of the image @param file the file to create @throws IOException if the file download fails """ if (Files.exists(file.getParent())) { URL urlObject = new URL(url); URLConnection connection = urlObject.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); connection.setRequestProperty("Referer", "http://www.google.com"); FileUtils.copyInputStreamToFile(connection.getInputStream(), file.toFile()); } }
java
public static void downloadImageToFile(String url, Path file) throws IOException { if (Files.exists(file.getParent())) { URL urlObject = new URL(url); URLConnection connection = urlObject.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"); connection.setRequestProperty("Referer", "http://www.google.com"); FileUtils.copyInputStreamToFile(connection.getInputStream(), file.toFile()); } }
[ "public", "static", "void", "downloadImageToFile", "(", "String", "url", ",", "Path", "file", ")", "throws", "IOException", "{", "if", "(", "Files", ".", "exists", "(", "file", ".", "getParent", "(", ")", ")", ")", "{", "URL", "urlObject", "=", "new", "URL", "(", "url", ")", ";", "URLConnection", "connection", "=", "urlObject", ".", "openConnection", "(", ")", ";", "connection", ".", "setRequestProperty", "(", "\"User-Agent\"", ",", "\"Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\"", ")", ";", "connection", ".", "setRequestProperty", "(", "\"Referer\"", ",", "\"http://www.google.com\"", ")", ";", "FileUtils", ".", "copyInputStreamToFile", "(", "connection", ".", "getInputStream", "(", ")", ",", "file", ".", "toFile", "(", ")", ")", ";", "}", "}" ]
Downloads an image to a file with the adequate headers to the http query @param url the url of the image @param file the file to create @throws IOException if the file download fails
[ "Downloads", "an", "image", "to", "a", "file", "with", "the", "adequate", "headers", "to", "the", "http", "query" ]
train
https://github.com/lamarios/sherdog-parser/blob/7cdb36280317caeaaa54db77c04dc4b4e1db053e/src/main/java/com/ftpix/sherdogparser/parsers/ParserUtils.java#L115-L127
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/util/HttpUtil.java
HttpUtil.isModifiedSince
public static boolean isModifiedSince(long ifModifiedSince, Calendar lastModified) { """ returns 'true' if 'lastModified' is after 'ifModifiedSince' (and both values are valid) """ return lastModified != null && isModifiedSince(ifModifiedSince, lastModified.getTimeInMillis()); }
java
public static boolean isModifiedSince(long ifModifiedSince, Calendar lastModified) { return lastModified != null && isModifiedSince(ifModifiedSince, lastModified.getTimeInMillis()); }
[ "public", "static", "boolean", "isModifiedSince", "(", "long", "ifModifiedSince", ",", "Calendar", "lastModified", ")", "{", "return", "lastModified", "!=", "null", "&&", "isModifiedSince", "(", "ifModifiedSince", ",", "lastModified", ".", "getTimeInMillis", "(", ")", ")", ";", "}" ]
returns 'true' if 'lastModified' is after 'ifModifiedSince' (and both values are valid)
[ "returns", "true", "if", "lastModified", "is", "after", "ifModifiedSince", "(", "and", "both", "values", "are", "valid", ")" ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/util/HttpUtil.java#L28-L30
apiman/apiman
manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java
EsMarshalling.unmarshallClientVersionSummary
public static ClientVersionSummaryBean unmarshallClientVersionSummary(Map<String, Object> source) { """ Unmarshals the given map source into a bean. @param source the source @return the client version summary """ if (source == null) { return null; } ClientVersionSummaryBean bean = new ClientVersionSummaryBean(); bean.setDescription(asString(source.get("clientDescription"))); bean.setId(asString(source.get("clientId"))); bean.setName(asString(source.get("clientName"))); bean.setOrganizationId(asString(source.get("organizationId"))); bean.setOrganizationName(asString(source.get("organizationName"))); bean.setStatus(asEnum(source.get("status"), ClientStatus.class)); bean.setVersion(asString(source.get("version"))); bean.setApiKey(asString(source.get("apikey"))); postMarshall(bean); return bean; }
java
public static ClientVersionSummaryBean unmarshallClientVersionSummary(Map<String, Object> source) { if (source == null) { return null; } ClientVersionSummaryBean bean = new ClientVersionSummaryBean(); bean.setDescription(asString(source.get("clientDescription"))); bean.setId(asString(source.get("clientId"))); bean.setName(asString(source.get("clientName"))); bean.setOrganizationId(asString(source.get("organizationId"))); bean.setOrganizationName(asString(source.get("organizationName"))); bean.setStatus(asEnum(source.get("status"), ClientStatus.class)); bean.setVersion(asString(source.get("version"))); bean.setApiKey(asString(source.get("apikey"))); postMarshall(bean); return bean; }
[ "public", "static", "ClientVersionSummaryBean", "unmarshallClientVersionSummary", "(", "Map", "<", "String", ",", "Object", ">", "source", ")", "{", "if", "(", "source", "==", "null", ")", "{", "return", "null", ";", "}", "ClientVersionSummaryBean", "bean", "=", "new", "ClientVersionSummaryBean", "(", ")", ";", "bean", ".", "setDescription", "(", "asString", "(", "source", ".", "get", "(", "\"clientDescription\"", ")", ")", ")", ";", "bean", ".", "setId", "(", "asString", "(", "source", ".", "get", "(", "\"clientId\"", ")", ")", ")", ";", "bean", ".", "setName", "(", "asString", "(", "source", ".", "get", "(", "\"clientName\"", ")", ")", ")", ";", "bean", ".", "setOrganizationId", "(", "asString", "(", "source", ".", "get", "(", "\"organizationId\"", ")", ")", ")", ";", "bean", ".", "setOrganizationName", "(", "asString", "(", "source", ".", "get", "(", "\"organizationName\"", ")", ")", ")", ";", "bean", ".", "setStatus", "(", "asEnum", "(", "source", ".", "get", "(", "\"status\"", ")", ",", "ClientStatus", ".", "class", ")", ")", ";", "bean", ".", "setVersion", "(", "asString", "(", "source", ".", "get", "(", "\"version\"", ")", ")", ")", ";", "bean", ".", "setApiKey", "(", "asString", "(", "source", ".", "get", "(", "\"apikey\"", ")", ")", ")", ";", "postMarshall", "(", "bean", ")", ";", "return", "bean", ";", "}" ]
Unmarshals the given map source into a bean. @param source the source @return the client version summary
[ "Unmarshals", "the", "given", "map", "source", "into", "a", "bean", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L1084-L1099
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterJoinManager.java
ClusterJoinManager.executeJoinRequest
private void executeJoinRequest(JoinRequest joinRequest, Connection connection) { """ Executed by a master node to process the {@link JoinRequest} sent by a node attempting to join the cluster. @param joinRequest the join request from a node attempting to join @param connection the connection of this node to the joining node """ clusterServiceLock.lock(); try { if (checkJoinRequest(joinRequest, connection)) { return; } if (!authenticate(joinRequest)) { return; } if (!validateJoinRequest(joinRequest, joinRequest.getAddress())) { return; } startJoinRequest(joinRequest.toMemberInfo()); } finally { clusterServiceLock.unlock(); } }
java
private void executeJoinRequest(JoinRequest joinRequest, Connection connection) { clusterServiceLock.lock(); try { if (checkJoinRequest(joinRequest, connection)) { return; } if (!authenticate(joinRequest)) { return; } if (!validateJoinRequest(joinRequest, joinRequest.getAddress())) { return; } startJoinRequest(joinRequest.toMemberInfo()); } finally { clusterServiceLock.unlock(); } }
[ "private", "void", "executeJoinRequest", "(", "JoinRequest", "joinRequest", ",", "Connection", "connection", ")", "{", "clusterServiceLock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "checkJoinRequest", "(", "joinRequest", ",", "connection", ")", ")", "{", "return", ";", "}", "if", "(", "!", "authenticate", "(", "joinRequest", ")", ")", "{", "return", ";", "}", "if", "(", "!", "validateJoinRequest", "(", "joinRequest", ",", "joinRequest", ".", "getAddress", "(", ")", ")", ")", "{", "return", ";", "}", "startJoinRequest", "(", "joinRequest", ".", "toMemberInfo", "(", ")", ")", ";", "}", "finally", "{", "clusterServiceLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Executed by a master node to process the {@link JoinRequest} sent by a node attempting to join the cluster. @param joinRequest the join request from a node attempting to join @param connection the connection of this node to the joining node
[ "Executed", "by", "a", "master", "node", "to", "process", "the", "{", "@link", "JoinRequest", "}", "sent", "by", "a", "node", "attempting", "to", "join", "the", "cluster", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/ClusterJoinManager.java#L248-L267
centic9/commons-dost
src/main/java/org/dstadler/commons/zip/ZipUtils.java
ZipUtils.findZip
public static void findZip(String zipName, InputStream zipInput, FileFilter searchFilter, List<String> results) throws IOException { """ Looks in the ZIP file available via zipInput for files matching the provided file-filter, recursing into sub-ZIP files. @param zipName Name of the file to read, mainly used for building the resulting pointer into the zip-file @param zipInput An InputStream which is positioned at the beginning of the zip-file contents @param searchFilter A {@link FileFilter} which determines if files in the zip-file are matched @param results A existing list where found matches are added to. @throws IOException If the ZIP file cannot be read, e.g. if it is corrupted. """ ZipInputStream zin = new ZipInputStream(zipInput); while (true) { final ZipEntry en; try { en = zin.getNextEntry(); } catch (IOException | IllegalArgumentException e) { throw new IOException("While handling file " + zipName, e); } if(en == null) { break; } if (searchFilter.accept(new File(en.getName()))) { results.add(zipName + ZIP_DELIMITER + en); } if (ZipUtils.isZip(en.getName())) { findZip(zipName + ZIP_DELIMITER + en, zin, searchFilter, results); } } }
java
public static void findZip(String zipName, InputStream zipInput, FileFilter searchFilter, List<String> results) throws IOException { ZipInputStream zin = new ZipInputStream(zipInput); while (true) { final ZipEntry en; try { en = zin.getNextEntry(); } catch (IOException | IllegalArgumentException e) { throw new IOException("While handling file " + zipName, e); } if(en == null) { break; } if (searchFilter.accept(new File(en.getName()))) { results.add(zipName + ZIP_DELIMITER + en); } if (ZipUtils.isZip(en.getName())) { findZip(zipName + ZIP_DELIMITER + en, zin, searchFilter, results); } } }
[ "public", "static", "void", "findZip", "(", "String", "zipName", ",", "InputStream", "zipInput", ",", "FileFilter", "searchFilter", ",", "List", "<", "String", ">", "results", ")", "throws", "IOException", "{", "ZipInputStream", "zin", "=", "new", "ZipInputStream", "(", "zipInput", ")", ";", "while", "(", "true", ")", "{", "final", "ZipEntry", "en", ";", "try", "{", "en", "=", "zin", ".", "getNextEntry", "(", ")", ";", "}", "catch", "(", "IOException", "|", "IllegalArgumentException", "e", ")", "{", "throw", "new", "IOException", "(", "\"While handling file \"", "+", "zipName", ",", "e", ")", ";", "}", "if", "(", "en", "==", "null", ")", "{", "break", ";", "}", "if", "(", "searchFilter", ".", "accept", "(", "new", "File", "(", "en", ".", "getName", "(", ")", ")", ")", ")", "{", "results", ".", "add", "(", "zipName", "+", "ZIP_DELIMITER", "+", "en", ")", ";", "}", "if", "(", "ZipUtils", ".", "isZip", "(", "en", ".", "getName", "(", ")", ")", ")", "{", "findZip", "(", "zipName", "+", "ZIP_DELIMITER", "+", "en", ",", "zin", ",", "searchFilter", ",", "results", ")", ";", "}", "}", "}" ]
Looks in the ZIP file available via zipInput for files matching the provided file-filter, recursing into sub-ZIP files. @param zipName Name of the file to read, mainly used for building the resulting pointer into the zip-file @param zipInput An InputStream which is positioned at the beginning of the zip-file contents @param searchFilter A {@link FileFilter} which determines if files in the zip-file are matched @param results A existing list where found matches are added to. @throws IOException If the ZIP file cannot be read, e.g. if it is corrupted.
[ "Looks", "in", "the", "ZIP", "file", "available", "via", "zipInput", "for", "files", "matching", "the", "provided", "file", "-", "filter", "recursing", "into", "sub", "-", "ZIP", "files", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/zip/ZipUtils.java#L109-L129
xcesco/kripton
kripton-core/src/main/java/com/abubusoft/kripton/common/DynamicByteBufferHelper.java
DynamicByteBufferHelper.insertDoubleInto
public static byte[] insertDoubleInto(byte[] array, int index, double value) { """ Insert double into. @param array the array @param index the index @param value the value @return the byte[] """ byte[] holder = new byte[4]; doubleTo(holder, 0, value); return insert(array, index, holder); }
java
public static byte[] insertDoubleInto(byte[] array, int index, double value) { byte[] holder = new byte[4]; doubleTo(holder, 0, value); return insert(array, index, holder); }
[ "public", "static", "byte", "[", "]", "insertDoubleInto", "(", "byte", "[", "]", "array", ",", "int", "index", ",", "double", "value", ")", "{", "byte", "[", "]", "holder", "=", "new", "byte", "[", "4", "]", ";", "doubleTo", "(", "holder", ",", "0", ",", "value", ")", ";", "return", "insert", "(", "array", ",", "index", ",", "holder", ")", ";", "}" ]
Insert double into. @param array the array @param index the index @param value the value @return the byte[]
[ "Insert", "double", "into", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-core/src/main/java/com/abubusoft/kripton/common/DynamicByteBufferHelper.java#L927-L932
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/extensions/ChocoUtils.java
ChocoUtils.postIfOnlyIf
public static void postIfOnlyIf(ReconfigurationProblem rp, BoolVar b1, Constraint c2) { """ Make and post a constraint that states and(or(b1, non c2), or(non b1, c2)) @param rp the problem to solve @param b1 the first constraint @param c2 the second constraint """ Model csp = rp.getModel(); BoolVar notBC1 = b1.not(); BoolVar bC2 = csp.boolVar(rp.makeVarLabel(c2.toString(), " satisfied")); c2.reifyWith(bC2); BoolVar notBC2 = bC2.not(); csp.post(rp.getModel().or(rp.getModel().or(b1, bC2), rp.getModel().or(notBC1, notBC2))); }
java
public static void postIfOnlyIf(ReconfigurationProblem rp, BoolVar b1, Constraint c2) { Model csp = rp.getModel(); BoolVar notBC1 = b1.not(); BoolVar bC2 = csp.boolVar(rp.makeVarLabel(c2.toString(), " satisfied")); c2.reifyWith(bC2); BoolVar notBC2 = bC2.not(); csp.post(rp.getModel().or(rp.getModel().or(b1, bC2), rp.getModel().or(notBC1, notBC2))); }
[ "public", "static", "void", "postIfOnlyIf", "(", "ReconfigurationProblem", "rp", ",", "BoolVar", "b1", ",", "Constraint", "c2", ")", "{", "Model", "csp", "=", "rp", ".", "getModel", "(", ")", ";", "BoolVar", "notBC1", "=", "b1", ".", "not", "(", ")", ";", "BoolVar", "bC2", "=", "csp", ".", "boolVar", "(", "rp", ".", "makeVarLabel", "(", "c2", ".", "toString", "(", ")", ",", "\" satisfied\"", ")", ")", ";", "c2", ".", "reifyWith", "(", "bC2", ")", ";", "BoolVar", "notBC2", "=", "bC2", ".", "not", "(", ")", ";", "csp", ".", "post", "(", "rp", ".", "getModel", "(", ")", ".", "or", "(", "rp", ".", "getModel", "(", ")", ".", "or", "(", "b1", ",", "bC2", ")", ",", "rp", ".", "getModel", "(", ")", ".", "or", "(", "notBC1", ",", "notBC2", ")", ")", ")", ";", "}" ]
Make and post a constraint that states and(or(b1, non c2), or(non b1, c2)) @param rp the problem to solve @param b1 the first constraint @param c2 the second constraint
[ "Make", "and", "post", "a", "constraint", "that", "states", "and", "(", "or", "(", "b1", "non", "c2", ")", "or", "(", "non", "b1", "c2", "))" ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/ChocoUtils.java#L63-L70
OpenLiberty/open-liberty
dev/com.ibm.ws.concurrent.persistent/src/com/ibm/ws/concurrent/persistent/internal/TaskInfo.java
TaskInfo.deserializeThreadContext
public ThreadContextDescriptor deserializeThreadContext(Map<String, String> execProps) throws IOException, ClassNotFoundException { """ Returns the thread context that was captured at the point when the task was submitted. @param execProps execution properties for the persistent task. @return the thread context that was captured at the point when the task was submitted. @throws IOException @throws ClassNotFoundException """ return threadContextBytes == null ? null : ThreadContextDeserializer.deserialize(threadContextBytes, execProps); }
java
public ThreadContextDescriptor deserializeThreadContext(Map<String, String> execProps) throws IOException, ClassNotFoundException { return threadContextBytes == null ? null : ThreadContextDeserializer.deserialize(threadContextBytes, execProps); }
[ "public", "ThreadContextDescriptor", "deserializeThreadContext", "(", "Map", "<", "String", ",", "String", ">", "execProps", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "return", "threadContextBytes", "==", "null", "?", "null", ":", "ThreadContextDeserializer", ".", "deserialize", "(", "threadContextBytes", ",", "execProps", ")", ";", "}" ]
Returns the thread context that was captured at the point when the task was submitted. @param execProps execution properties for the persistent task. @return the thread context that was captured at the point when the task was submitted. @throws IOException @throws ClassNotFoundException
[ "Returns", "the", "thread", "context", "that", "was", "captured", "at", "the", "point", "when", "the", "task", "was", "submitted", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.persistent/src/com/ibm/ws/concurrent/persistent/internal/TaskInfo.java#L151-L153
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/AdapterUtil.java
AdapterUtil.translateSQLException
public static ResourceException translateSQLException( SQLException se, Object mapper, boolean sendEvent, Class<?> caller) { """ Translates a SQLException from the database. The exception mapping methods have been rewritten to account for the error detection model and to consolidate the RRA exception mapping routines into a single place. See the AdapterUtil.mapException method. @param SQLException se - the SQLException from the database @param mapper a managed connection or managed connection factory capable of mapping the exception. If NULL is provided, the exception cannot be mapped. If stale statement handling or connection error handling is required then a managed connection must be provided. @param boolean sendEvent - if true, throw an exception if the SQLException is a connectionError event @return ResourceException - the translated SQLException wrapped in a ResourceException """ return (ResourceException) mapException( new DataStoreAdapterException("DSA_ERROR", se, caller, se.getMessage()), null, mapper, sendEvent); }
java
public static ResourceException translateSQLException( SQLException se, Object mapper, boolean sendEvent, Class<?> caller) { return (ResourceException) mapException( new DataStoreAdapterException("DSA_ERROR", se, caller, se.getMessage()), null, mapper, sendEvent); }
[ "public", "static", "ResourceException", "translateSQLException", "(", "SQLException", "se", ",", "Object", "mapper", ",", "boolean", "sendEvent", ",", "Class", "<", "?", ">", "caller", ")", "{", "return", "(", "ResourceException", ")", "mapException", "(", "new", "DataStoreAdapterException", "(", "\"DSA_ERROR\"", ",", "se", ",", "caller", ",", "se", ".", "getMessage", "(", ")", ")", ",", "null", ",", "mapper", ",", "sendEvent", ")", ";", "}" ]
Translates a SQLException from the database. The exception mapping methods have been rewritten to account for the error detection model and to consolidate the RRA exception mapping routines into a single place. See the AdapterUtil.mapException method. @param SQLException se - the SQLException from the database @param mapper a managed connection or managed connection factory capable of mapping the exception. If NULL is provided, the exception cannot be mapped. If stale statement handling or connection error handling is required then a managed connection must be provided. @param boolean sendEvent - if true, throw an exception if the SQLException is a connectionError event @return ResourceException - the translated SQLException wrapped in a ResourceException
[ "Translates", "a", "SQLException", "from", "the", "database", ".", "The", "exception", "mapping", "methods", "have", "been", "rewritten", "to", "account", "for", "the", "error", "detection", "model", "and", "to", "consolidate", "the", "RRA", "exception", "mapping", "routines", "into", "a", "single", "place", ".", "See", "the", "AdapterUtil", ".", "mapException", "method", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/AdapterUtil.java#L768-L778
cdk/cdk
tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
MmffAromaticTypeMapping.getBetaAromaticType
private String getBetaAromaticType(String symb, boolean imidazolium, boolean anion) { """ Convenience method to obtain the aromatic type of a symbolic (SYMB) type in the beta position of a 5-member ring. This method delegates to {@link #getAromaticType(java.util.Map, char, String, boolean, boolean)} setup for beta atoms. @param symb symbolic atom type @param imidazolium imidazolium flag (IM naming from MMFFAROM.PAR) @param anion anion flag (AN naming from MMFFAROM.PAR) @return the aromatic type """ return getAromaticType(betaTypes, 'B', symb, imidazolium, anion); }
java
private String getBetaAromaticType(String symb, boolean imidazolium, boolean anion) { return getAromaticType(betaTypes, 'B', symb, imidazolium, anion); }
[ "private", "String", "getBetaAromaticType", "(", "String", "symb", ",", "boolean", "imidazolium", ",", "boolean", "anion", ")", "{", "return", "getAromaticType", "(", "betaTypes", ",", "'", "'", ",", "symb", ",", "imidazolium", ",", "anion", ")", ";", "}" ]
Convenience method to obtain the aromatic type of a symbolic (SYMB) type in the beta position of a 5-member ring. This method delegates to {@link #getAromaticType(java.util.Map, char, String, boolean, boolean)} setup for beta atoms. @param symb symbolic atom type @param imidazolium imidazolium flag (IM naming from MMFFAROM.PAR) @param anion anion flag (AN naming from MMFFAROM.PAR) @return the aromatic type
[ "Convenience", "method", "to", "obtain", "the", "aromatic", "type", "of", "a", "symbolic", "(", "SYMB", ")", "type", "in", "the", "beta", "position", "of", "a", "5", "-", "member", "ring", ".", "This", "method", "delegates", "to", "{", "@link", "#getAromaticType", "(", "java", ".", "util", ".", "Map", "char", "String", "boolean", "boolean", ")", "}", "setup", "for", "beta", "atoms", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java#L286-L288
MutabilityDetector/MutabilityDetector
src/main/java/org/mutabilitydetector/ConfigurationBuilder.java
ConfigurationBuilder.hardcodeValidCopyMethod
protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) { """ Hardcode a copy method as being valid. This should be used to tell Mutability Detector about a method which copies a collection, and when the copy can be wrapped in an immutable wrapper we can consider the assignment immutable. Useful for allowing Mutability Detector to correctly work with other collections frameworks such as Google Guava. Reflection is used to obtain the method's descriptor and to verify the method's existence. @param fieldType - the type of the field to which the result of the copy is assigned @param fullyQualifiedMethodName - the fully qualified method name @param argType - the type of the argument passed to the copy method @throws MutabilityAnalysisException - if the specified class or method does not exist @throws IllegalArgumentException - if any of the arguments are null """ if (argType==null || fieldType==null || fullyQualifiedMethodName==null) { throw new IllegalArgumentException("All parameters must be supplied - no nulls"); } String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(".")); String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(".")+1); String desc = null; try { if (MethodIs.aConstructor(methodName)) { Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType); desc = Type.getConstructorDescriptor(ctor); } else { Method method = Class.forName(className).getMethod(methodName, argType); desc = Type.getMethodDescriptor(method); } } catch (NoSuchMethodException e) { rethrow("No such method", e); } catch (SecurityException e) { rethrow("Security error", e); } catch (ClassNotFoundException e) { rethrow("Class not found", e); } CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc); hardcodeValidCopyMethod(fieldType, copyMethod); }
java
protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) { if (argType==null || fieldType==null || fullyQualifiedMethodName==null) { throw new IllegalArgumentException("All parameters must be supplied - no nulls"); } String className = fullyQualifiedMethodName.substring(0, fullyQualifiedMethodName.lastIndexOf(".")); String methodName = fullyQualifiedMethodName.substring(fullyQualifiedMethodName.lastIndexOf(".")+1); String desc = null; try { if (MethodIs.aConstructor(methodName)) { Constructor<?> ctor = Class.forName(className).getDeclaredConstructor(argType); desc = Type.getConstructorDescriptor(ctor); } else { Method method = Class.forName(className).getMethod(methodName, argType); desc = Type.getMethodDescriptor(method); } } catch (NoSuchMethodException e) { rethrow("No such method", e); } catch (SecurityException e) { rethrow("Security error", e); } catch (ClassNotFoundException e) { rethrow("Class not found", e); } CopyMethod copyMethod = new CopyMethod(dotted(className), methodName, desc); hardcodeValidCopyMethod(fieldType, copyMethod); }
[ "protected", "final", "void", "hardcodeValidCopyMethod", "(", "Class", "<", "?", ">", "fieldType", ",", "String", "fullyQualifiedMethodName", ",", "Class", "<", "?", ">", "argType", ")", "{", "if", "(", "argType", "==", "null", "||", "fieldType", "==", "null", "||", "fullyQualifiedMethodName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"All parameters must be supplied - no nulls\"", ")", ";", "}", "String", "className", "=", "fullyQualifiedMethodName", ".", "substring", "(", "0", ",", "fullyQualifiedMethodName", ".", "lastIndexOf", "(", "\".\"", ")", ")", ";", "String", "methodName", "=", "fullyQualifiedMethodName", ".", "substring", "(", "fullyQualifiedMethodName", ".", "lastIndexOf", "(", "\".\"", ")", "+", "1", ")", ";", "String", "desc", "=", "null", ";", "try", "{", "if", "(", "MethodIs", ".", "aConstructor", "(", "methodName", ")", ")", "{", "Constructor", "<", "?", ">", "ctor", "=", "Class", ".", "forName", "(", "className", ")", ".", "getDeclaredConstructor", "(", "argType", ")", ";", "desc", "=", "Type", ".", "getConstructorDescriptor", "(", "ctor", ")", ";", "}", "else", "{", "Method", "method", "=", "Class", ".", "forName", "(", "className", ")", ".", "getMethod", "(", "methodName", ",", "argType", ")", ";", "desc", "=", "Type", ".", "getMethodDescriptor", "(", "method", ")", ";", "}", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "rethrow", "(", "\"No such method\"", ",", "e", ")", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "rethrow", "(", "\"Security error\"", ",", "e", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "rethrow", "(", "\"Class not found\"", ",", "e", ")", ";", "}", "CopyMethod", "copyMethod", "=", "new", "CopyMethod", "(", "dotted", "(", "className", ")", ",", "methodName", ",", "desc", ")", ";", "hardcodeValidCopyMethod", "(", "fieldType", ",", "copyMethod", ")", ";", "}" ]
Hardcode a copy method as being valid. This should be used to tell Mutability Detector about a method which copies a collection, and when the copy can be wrapped in an immutable wrapper we can consider the assignment immutable. Useful for allowing Mutability Detector to correctly work with other collections frameworks such as Google Guava. Reflection is used to obtain the method's descriptor and to verify the method's existence. @param fieldType - the type of the field to which the result of the copy is assigned @param fullyQualifiedMethodName - the fully qualified method name @param argType - the type of the argument passed to the copy method @throws MutabilityAnalysisException - if the specified class or method does not exist @throws IllegalArgumentException - if any of the arguments are null
[ "Hardcode", "a", "copy", "method", "as", "being", "valid", ".", "This", "should", "be", "used", "to", "tell", "Mutability", "Detector", "about", "a", "method", "which", "copies", "a", "collection", "and", "when", "the", "copy", "can", "be", "wrapped", "in", "an", "immutable", "wrapper", "we", "can", "consider", "the", "assignment", "immutable", ".", "Useful", "for", "allowing", "Mutability", "Detector", "to", "correctly", "work", "with", "other", "collections", "frameworks", "such", "as", "Google", "Guava", ".", "Reflection", "is", "used", "to", "obtain", "the", "method", "s", "descriptor", "and", "to", "verify", "the", "method", "s", "existence", "." ]
train
https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/ConfigurationBuilder.java#L430-L456
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java
RoutesInner.getAsync
public Observable<RouteInner> getAsync(String resourceGroupName, String routeTableName, String routeName) { """ Gets the specified route from a route table. @param resourceGroupName The name of the resource group. @param routeTableName The name of the route table. @param routeName The name of the route. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RouteInner object """ return getWithServiceResponseAsync(resourceGroupName, routeTableName, routeName).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() { @Override public RouteInner call(ServiceResponse<RouteInner> response) { return response.body(); } }); }
java
public Observable<RouteInner> getAsync(String resourceGroupName, String routeTableName, String routeName) { return getWithServiceResponseAsync(resourceGroupName, routeTableName, routeName).map(new Func1<ServiceResponse<RouteInner>, RouteInner>() { @Override public RouteInner call(ServiceResponse<RouteInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RouteInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "routeTableName", ",", "String", "routeName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "routeTableName", ",", "routeName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RouteInner", ">", ",", "RouteInner", ">", "(", ")", "{", "@", "Override", "public", "RouteInner", "call", "(", "ServiceResponse", "<", "RouteInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the specified route from a route table. @param resourceGroupName The name of the resource group. @param routeTableName The name of the route table. @param routeName The name of the route. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RouteInner object
[ "Gets", "the", "specified", "route", "from", "a", "route", "table", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/RoutesInner.java#L297-L304
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.dedicatedCloud_serviceName_ip_duration_POST
public OvhOrder dedicatedCloud_serviceName_ip_duration_POST(String serviceName, String duration, OvhIpCountriesEnum country, String description, Long estimatedClientsNumber, String networkName, OvhOrderableIpBlockRangeEnum size, String usage) throws IOException { """ Create order REST: POST /order/dedicatedCloud/{serviceName}/ip/{duration} @param size [required] The network ranges orderable @param usage [required] Basic information of how will this bloc be used (as "web","ssl","cloud" or other things) @param description [required] Information visible on whois (minimum 3 and maximum 250 alphanumeric characters) @param country [required] This Ip block country @param estimatedClientsNumber [required] How much clients would be hosted on those ips ? @param networkName [required] Information visible on whois (between 2 and maximum 20 alphanumeric characters) @param serviceName [required] @param duration [required] Duration """ String qPath = "/order/dedicatedCloud/{serviceName}/ip/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "country", country); addBody(o, "description", description); addBody(o, "estimatedClientsNumber", estimatedClientsNumber); addBody(o, "networkName", networkName); addBody(o, "size", size); addBody(o, "usage", usage); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder dedicatedCloud_serviceName_ip_duration_POST(String serviceName, String duration, OvhIpCountriesEnum country, String description, Long estimatedClientsNumber, String networkName, OvhOrderableIpBlockRangeEnum size, String usage) throws IOException { String qPath = "/order/dedicatedCloud/{serviceName}/ip/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "country", country); addBody(o, "description", description); addBody(o, "estimatedClientsNumber", estimatedClientsNumber); addBody(o, "networkName", networkName); addBody(o, "size", size); addBody(o, "usage", usage); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "dedicatedCloud_serviceName_ip_duration_POST", "(", "String", "serviceName", ",", "String", "duration", ",", "OvhIpCountriesEnum", "country", ",", "String", "description", ",", "Long", "estimatedClientsNumber", ",", "String", "networkName", ",", "OvhOrderableIpBlockRangeEnum", "size", ",", "String", "usage", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/dedicatedCloud/{serviceName}/ip/{duration}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "duration", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"country\"", ",", "country", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "addBody", "(", "o", ",", "\"estimatedClientsNumber\"", ",", "estimatedClientsNumber", ")", ";", "addBody", "(", "o", ",", "\"networkName\"", ",", "networkName", ")", ";", "addBody", "(", "o", ",", "\"size\"", ",", "size", ")", ";", "addBody", "(", "o", ",", "\"usage\"", ",", "usage", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrder", ".", "class", ")", ";", "}" ]
Create order REST: POST /order/dedicatedCloud/{serviceName}/ip/{duration} @param size [required] The network ranges orderable @param usage [required] Basic information of how will this bloc be used (as "web","ssl","cloud" or other things) @param description [required] Information visible on whois (minimum 3 and maximum 250 alphanumeric characters) @param country [required] This Ip block country @param estimatedClientsNumber [required] How much clients would be hosted on those ips ? @param networkName [required] Information visible on whois (between 2 and maximum 20 alphanumeric characters) @param serviceName [required] @param duration [required] Duration
[ "Create", "order" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5850-L5862
EXIficient/exificient
src/main/java/com/siemens/ct/exi/main/api/stream/StAXEncoder.java
StAXEncoder.writeCharacters
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { """ /* Write text to the output (non-Javadoc) @see javax.xml.stream.XMLStreamWriter#writeCharacters(char[], int, int) """ this.writeCharacters(new String(text, start, len)); }
java
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { this.writeCharacters(new String(text, start, len)); }
[ "public", "void", "writeCharacters", "(", "char", "[", "]", "text", ",", "int", "start", ",", "int", "len", ")", "throws", "XMLStreamException", "{", "this", ".", "writeCharacters", "(", "new", "String", "(", "text", ",", "start", ",", "len", ")", ")", ";", "}" ]
/* Write text to the output (non-Javadoc) @see javax.xml.stream.XMLStreamWriter#writeCharacters(char[], int, int)
[ "/", "*", "Write", "text", "to", "the", "output" ]
train
https://github.com/EXIficient/exificient/blob/93c7c0d63d74cfccf6ab1d5041b203745ef9ddb8/src/main/java/com/siemens/ct/exi/main/api/stream/StAXEncoder.java#L350-L353
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobSchedulesImpl.java
JobSchedulesImpl.listAsync
public ServiceFuture<List<CloudJobSchedule>> listAsync(final JobScheduleListOptions jobScheduleListOptions, final ListOperationCallback<CloudJobSchedule> serviceCallback) { """ Lists all of the job schedules in the specified account. @param jobScheduleListOptions Additional parameters for the operation @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return AzureServiceFuture.fromHeaderPageResponse( listSinglePageAsync(jobScheduleListOptions), new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudJobSchedule>, JobScheduleListHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<CloudJobSchedule>, JobScheduleListHeaders>> call(String nextPageLink) { JobScheduleListNextOptions jobScheduleListNextOptions = null; if (jobScheduleListOptions != null) { jobScheduleListNextOptions = new JobScheduleListNextOptions(); jobScheduleListNextOptions.withClientRequestId(jobScheduleListOptions.clientRequestId()); jobScheduleListNextOptions.withReturnClientRequestId(jobScheduleListOptions.returnClientRequestId()); jobScheduleListNextOptions.withOcpDate(jobScheduleListOptions.ocpDate()); } return listNextSinglePageAsync(nextPageLink, jobScheduleListNextOptions); } }, serviceCallback); }
java
public ServiceFuture<List<CloudJobSchedule>> listAsync(final JobScheduleListOptions jobScheduleListOptions, final ListOperationCallback<CloudJobSchedule> serviceCallback) { return AzureServiceFuture.fromHeaderPageResponse( listSinglePageAsync(jobScheduleListOptions), new Func1<String, Observable<ServiceResponseWithHeaders<Page<CloudJobSchedule>, JobScheduleListHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Page<CloudJobSchedule>, JobScheduleListHeaders>> call(String nextPageLink) { JobScheduleListNextOptions jobScheduleListNextOptions = null; if (jobScheduleListOptions != null) { jobScheduleListNextOptions = new JobScheduleListNextOptions(); jobScheduleListNextOptions.withClientRequestId(jobScheduleListOptions.clientRequestId()); jobScheduleListNextOptions.withReturnClientRequestId(jobScheduleListOptions.returnClientRequestId()); jobScheduleListNextOptions.withOcpDate(jobScheduleListOptions.ocpDate()); } return listNextSinglePageAsync(nextPageLink, jobScheduleListNextOptions); } }, serviceCallback); }
[ "public", "ServiceFuture", "<", "List", "<", "CloudJobSchedule", ">", ">", "listAsync", "(", "final", "JobScheduleListOptions", "jobScheduleListOptions", ",", "final", "ListOperationCallback", "<", "CloudJobSchedule", ">", "serviceCallback", ")", "{", "return", "AzureServiceFuture", ".", "fromHeaderPageResponse", "(", "listSinglePageAsync", "(", "jobScheduleListOptions", ")", ",", "new", "Func1", "<", "String", ",", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "CloudJobSchedule", ">", ",", "JobScheduleListHeaders", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "CloudJobSchedule", ">", ",", "JobScheduleListHeaders", ">", ">", "call", "(", "String", "nextPageLink", ")", "{", "JobScheduleListNextOptions", "jobScheduleListNextOptions", "=", "null", ";", "if", "(", "jobScheduleListOptions", "!=", "null", ")", "{", "jobScheduleListNextOptions", "=", "new", "JobScheduleListNextOptions", "(", ")", ";", "jobScheduleListNextOptions", ".", "withClientRequestId", "(", "jobScheduleListOptions", ".", "clientRequestId", "(", ")", ")", ";", "jobScheduleListNextOptions", ".", "withReturnClientRequestId", "(", "jobScheduleListOptions", ".", "returnClientRequestId", "(", ")", ")", ";", "jobScheduleListNextOptions", ".", "withOcpDate", "(", "jobScheduleListOptions", ".", "ocpDate", "(", ")", ")", ";", "}", "return", "listNextSinglePageAsync", "(", "nextPageLink", ",", "jobScheduleListNextOptions", ")", ";", "}", "}", ",", "serviceCallback", ")", ";", "}" ]
Lists all of the job schedules in the specified account. @param jobScheduleListOptions Additional parameters for the operation @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "all", "of", "the", "job", "schedules", "in", "the", "specified", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobSchedulesImpl.java#L2322-L2339
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuGraphicsResourceGetMappedPointer
public static int cuGraphicsResourceGetMappedPointer( CUdeviceptr pDevPtr, long pSize[], CUgraphicsResource resource ) { """ Get a device pointer through which to access a mapped graphics resource. <pre> CUresult cuGraphicsResourceGetMappedPointer ( CUdeviceptr* pDevPtr, size_t* pSize, CUgraphicsResource resource ) </pre> <div> <p>Get a device pointer through which to access a mapped graphics resource. Returns in <tt>*pDevPtr</tt> a pointer through which the mapped graphics resource <tt>resource</tt> may be accessed. Returns in <tt>pSize</tt> the size of the memory in bytes which may be accessed from that pointer. The value set in <tt>pPointer</tt> may change every time that <tt>resource</tt> is mapped. </p> <p>If <tt>resource</tt> is not a buffer then it cannot be accessed via a pointer and CUDA_ERROR_NOT_MAPPED_AS_POINTER is returned. If <tt>resource</tt> is not mapped then CUDA_ERROR_NOT_MAPPED is returned. * </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param pDevPtr Returned pointer through which resource may be accessed @param pSize Returned size of the buffer accessible starting at *pPointer @param resource Mapped resource to access @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPEDCUDA_ERROR_NOT_MAPPED_AS_POINTER @see JCudaDriver#cuGraphicsMapResources @see JCudaDriver#cuGraphicsSubResourceGetMappedArray """ return checkResult(cuGraphicsResourceGetMappedPointerNative(pDevPtr, pSize, resource)); }
java
public static int cuGraphicsResourceGetMappedPointer( CUdeviceptr pDevPtr, long pSize[], CUgraphicsResource resource ) { return checkResult(cuGraphicsResourceGetMappedPointerNative(pDevPtr, pSize, resource)); }
[ "public", "static", "int", "cuGraphicsResourceGetMappedPointer", "(", "CUdeviceptr", "pDevPtr", ",", "long", "pSize", "[", "]", ",", "CUgraphicsResource", "resource", ")", "{", "return", "checkResult", "(", "cuGraphicsResourceGetMappedPointerNative", "(", "pDevPtr", ",", "pSize", ",", "resource", ")", ")", ";", "}" ]
Get a device pointer through which to access a mapped graphics resource. <pre> CUresult cuGraphicsResourceGetMappedPointer ( CUdeviceptr* pDevPtr, size_t* pSize, CUgraphicsResource resource ) </pre> <div> <p>Get a device pointer through which to access a mapped graphics resource. Returns in <tt>*pDevPtr</tt> a pointer through which the mapped graphics resource <tt>resource</tt> may be accessed. Returns in <tt>pSize</tt> the size of the memory in bytes which may be accessed from that pointer. The value set in <tt>pPointer</tt> may change every time that <tt>resource</tt> is mapped. </p> <p>If <tt>resource</tt> is not a buffer then it cannot be accessed via a pointer and CUDA_ERROR_NOT_MAPPED_AS_POINTER is returned. If <tt>resource</tt> is not mapped then CUDA_ERROR_NOT_MAPPED is returned. * </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param pDevPtr Returned pointer through which resource may be accessed @param pSize Returned size of the buffer accessible starting at *pPointer @param resource Mapped resource to access @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_HANDLE, CUDA_ERROR_NOT_MAPPEDCUDA_ERROR_NOT_MAPPED_AS_POINTER @see JCudaDriver#cuGraphicsMapResources @see JCudaDriver#cuGraphicsSubResourceGetMappedArray
[ "Get", "a", "device", "pointer", "through", "which", "to", "access", "a", "mapped", "graphics", "resource", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L15961-L15964
lightbend/config
config/src/main/java/com/typesafe/config/impl/AbstractConfigObject.java
AbstractConfigObject.peekAssumingResolved
protected final AbstractConfigValue peekAssumingResolved(String key, Path originalPath) { """ This looks up the key with no transformation or type conversion of any kind, and returns null if the key is not present. The object must be resolved along the nodes needed to get the key or ConfigException.NotResolved will be thrown. @param key @return the unmodified raw value or null """ try { return attemptPeekWithPartialResolve(key); } catch (ConfigException.NotResolved e) { throw ConfigImpl.improveNotResolved(originalPath, e); } }
java
protected final AbstractConfigValue peekAssumingResolved(String key, Path originalPath) { try { return attemptPeekWithPartialResolve(key); } catch (ConfigException.NotResolved e) { throw ConfigImpl.improveNotResolved(originalPath, e); } }
[ "protected", "final", "AbstractConfigValue", "peekAssumingResolved", "(", "String", "key", ",", "Path", "originalPath", ")", "{", "try", "{", "return", "attemptPeekWithPartialResolve", "(", "key", ")", ";", "}", "catch", "(", "ConfigException", ".", "NotResolved", "e", ")", "{", "throw", "ConfigImpl", ".", "improveNotResolved", "(", "originalPath", ",", "e", ")", ";", "}", "}" ]
This looks up the key with no transformation or type conversion of any kind, and returns null if the key is not present. The object must be resolved along the nodes needed to get the key or ConfigException.NotResolved will be thrown. @param key @return the unmodified raw value or null
[ "This", "looks", "up", "the", "key", "with", "no", "transformation", "or", "type", "conversion", "of", "any", "kind", "and", "returns", "null", "if", "the", "key", "is", "not", "present", ".", "The", "object", "must", "be", "resolved", "along", "the", "nodes", "needed", "to", "get", "the", "key", "or", "ConfigException", ".", "NotResolved", "will", "be", "thrown", "." ]
train
https://github.com/lightbend/config/blob/68cebfde5e861e9a5fdc75ceff366ed95e17d475/config/src/main/java/com/typesafe/config/impl/AbstractConfigObject.java#L64-L70
jbossas/jboss-vfs
src/main/java/org/jboss/vfs/VirtualJarFileInputStream.java
VirtualJarFileInputStream.bufferLocalFileHeader
private boolean bufferLocalFileHeader() throws IOException { """ Buffer the content of the local file header for a single entry. @return true if the next local file header was buffered @throws IOException if any problems occur """ buffer.reset(); JarEntry jarEntry = virtualJarInputStream.getNextJarEntry(); if (jarEntry == null) { return false; } currentEntry = new ProcessedEntry(jarEntry, totalRead); processedEntries.add(currentEntry); bufferInt(ZipEntry.LOCSIG); // Local file header signature bufferShort(10); // Extraction version bufferShort(0); // Flags bufferShort(ZipEntry.STORED); // Compression type bufferInt(jarEntry.getTime()); // Entry time bufferInt(0); // CRC bufferInt(0); // Compressed size bufferInt(0); // Uncompressed size byte[] nameBytes = jarEntry.getName().getBytes("UTF8"); bufferShort(nameBytes.length); // Entry name length bufferShort(0); // Extra length buffer(nameBytes); return true; }
java
private boolean bufferLocalFileHeader() throws IOException { buffer.reset(); JarEntry jarEntry = virtualJarInputStream.getNextJarEntry(); if (jarEntry == null) { return false; } currentEntry = new ProcessedEntry(jarEntry, totalRead); processedEntries.add(currentEntry); bufferInt(ZipEntry.LOCSIG); // Local file header signature bufferShort(10); // Extraction version bufferShort(0); // Flags bufferShort(ZipEntry.STORED); // Compression type bufferInt(jarEntry.getTime()); // Entry time bufferInt(0); // CRC bufferInt(0); // Compressed size bufferInt(0); // Uncompressed size byte[] nameBytes = jarEntry.getName().getBytes("UTF8"); bufferShort(nameBytes.length); // Entry name length bufferShort(0); // Extra length buffer(nameBytes); return true; }
[ "private", "boolean", "bufferLocalFileHeader", "(", ")", "throws", "IOException", "{", "buffer", ".", "reset", "(", ")", ";", "JarEntry", "jarEntry", "=", "virtualJarInputStream", ".", "getNextJarEntry", "(", ")", ";", "if", "(", "jarEntry", "==", "null", ")", "{", "return", "false", ";", "}", "currentEntry", "=", "new", "ProcessedEntry", "(", "jarEntry", ",", "totalRead", ")", ";", "processedEntries", ".", "add", "(", "currentEntry", ")", ";", "bufferInt", "(", "ZipEntry", ".", "LOCSIG", ")", ";", "// Local file header signature", "bufferShort", "(", "10", ")", ";", "// Extraction version", "bufferShort", "(", "0", ")", ";", "// Flags", "bufferShort", "(", "ZipEntry", ".", "STORED", ")", ";", "// Compression type", "bufferInt", "(", "jarEntry", ".", "getTime", "(", ")", ")", ";", "// Entry time", "bufferInt", "(", "0", ")", ";", "// CRC", "bufferInt", "(", "0", ")", ";", "// Compressed size", "bufferInt", "(", "0", ")", ";", "// Uncompressed size", "byte", "[", "]", "nameBytes", "=", "jarEntry", ".", "getName", "(", ")", ".", "getBytes", "(", "\"UTF8\"", ")", ";", "bufferShort", "(", "nameBytes", ".", "length", ")", ";", "// Entry name length", "bufferShort", "(", "0", ")", ";", "// Extra length", "buffer", "(", "nameBytes", ")", ";", "return", "true", ";", "}" ]
Buffer the content of the local file header for a single entry. @return true if the next local file header was buffered @throws IOException if any problems occur
[ "Buffer", "the", "content", "of", "the", "local", "file", "header", "for", "a", "single", "entry", "." ]
train
https://github.com/jbossas/jboss-vfs/blob/420f4b896d6178ee5f6758f3421e9f350d2b8ab5/src/main/java/org/jboss/vfs/VirtualJarFileInputStream.java#L120-L143
appium/java-client
src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java
AppiumElementLocator.getBy
private static By getBy(By currentBy, SearchContext currentContent) { """ This methods makes sets some settings of the {@link By} according to the given instance of {@link SearchContext}. If there is some {@link ContentMappedBy} then it is switched to the searching for some html or native mobile element. Otherwise nothing happens there. @param currentBy is some locator strategy @param currentContent is an instance of some subclass of the {@link SearchContext}. @return the corrected {@link By} for the further searching """ if (!ContentMappedBy.class.isAssignableFrom(currentBy.getClass())) { return currentBy; } return ContentMappedBy.class.cast(currentBy) .useContent(getCurrentContentType(currentContent)); }
java
private static By getBy(By currentBy, SearchContext currentContent) { if (!ContentMappedBy.class.isAssignableFrom(currentBy.getClass())) { return currentBy; } return ContentMappedBy.class.cast(currentBy) .useContent(getCurrentContentType(currentContent)); }
[ "private", "static", "By", "getBy", "(", "By", "currentBy", ",", "SearchContext", "currentContent", ")", "{", "if", "(", "!", "ContentMappedBy", ".", "class", ".", "isAssignableFrom", "(", "currentBy", ".", "getClass", "(", ")", ")", ")", "{", "return", "currentBy", ";", "}", "return", "ContentMappedBy", ".", "class", ".", "cast", "(", "currentBy", ")", ".", "useContent", "(", "getCurrentContentType", "(", "currentContent", ")", ")", ";", "}" ]
This methods makes sets some settings of the {@link By} according to the given instance of {@link SearchContext}. If there is some {@link ContentMappedBy} then it is switched to the searching for some html or native mobile element. Otherwise nothing happens there. @param currentBy is some locator strategy @param currentContent is an instance of some subclass of the {@link SearchContext}. @return the corrected {@link By} for the further searching
[ "This", "methods", "makes", "sets", "some", "settings", "of", "the", "{", "@link", "By", "}", "according", "to", "the", "given", "instance", "of", "{", "@link", "SearchContext", "}", ".", "If", "there", "is", "some", "{", "@link", "ContentMappedBy", "}", "then", "it", "is", "switched", "to", "the", "searching", "for", "some", "html", "or", "native", "mobile", "element", ".", "Otherwise", "nothing", "happens", "there", "." ]
train
https://github.com/appium/java-client/blob/5a17759b05d6fda8ef425b3ab6e766c73ed2e8df/src/main/java/io/appium/java_client/pagefactory/AppiumElementLocator.java#L84-L91
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java
DomHelper.drawGroup
public void drawGroup(Object parent, Object object) { """ Creates a group element in the technology (SVG/VML/...) of this context. A group is meant to group other elements together. @param parent parent group object @param object group object """ createOrUpdateGroup(parent, object, null, null); }
java
public void drawGroup(Object parent, Object object) { createOrUpdateGroup(parent, object, null, null); }
[ "public", "void", "drawGroup", "(", "Object", "parent", ",", "Object", "object", ")", "{", "createOrUpdateGroup", "(", "parent", ",", "object", ",", "null", ",", "null", ")", ";", "}" ]
Creates a group element in the technology (SVG/VML/...) of this context. A group is meant to group other elements together. @param parent parent group object @param object group object
[ "Creates", "a", "group", "element", "in", "the", "technology", "(", "SVG", "/", "VML", "/", "...", ")", "of", "this", "context", ".", "A", "group", "is", "meant", "to", "group", "other", "elements", "together", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L197-L199
cdapio/tephra
tephra-core/src/main/java/co/cask/tephra/util/TxUtils.java
TxUtils.getFirstShortInProgress
public static long getFirstShortInProgress(Map<Long, TransactionManager.InProgressTx> inProgress) { """ Returns the write pointer for the first "short" transaction that in the in-progress set, or {@link Transaction#NO_TX_IN_PROGRESS} if none. """ long firstShort = Transaction.NO_TX_IN_PROGRESS; for (Map.Entry<Long, TransactionManager.InProgressTx> entry : inProgress.entrySet()) { if (!entry.getValue().isLongRunning()) { firstShort = entry.getKey(); break; } } return firstShort; }
java
public static long getFirstShortInProgress(Map<Long, TransactionManager.InProgressTx> inProgress) { long firstShort = Transaction.NO_TX_IN_PROGRESS; for (Map.Entry<Long, TransactionManager.InProgressTx> entry : inProgress.entrySet()) { if (!entry.getValue().isLongRunning()) { firstShort = entry.getKey(); break; } } return firstShort; }
[ "public", "static", "long", "getFirstShortInProgress", "(", "Map", "<", "Long", ",", "TransactionManager", ".", "InProgressTx", ">", "inProgress", ")", "{", "long", "firstShort", "=", "Transaction", ".", "NO_TX_IN_PROGRESS", ";", "for", "(", "Map", ".", "Entry", "<", "Long", ",", "TransactionManager", ".", "InProgressTx", ">", "entry", ":", "inProgress", ".", "entrySet", "(", ")", ")", "{", "if", "(", "!", "entry", ".", "getValue", "(", ")", ".", "isLongRunning", "(", ")", ")", "{", "firstShort", "=", "entry", ".", "getKey", "(", ")", ";", "break", ";", "}", "}", "return", "firstShort", ";", "}" ]
Returns the write pointer for the first "short" transaction that in the in-progress set, or {@link Transaction#NO_TX_IN_PROGRESS} if none.
[ "Returns", "the", "write", "pointer", "for", "the", "first", "short", "transaction", "that", "in", "the", "in", "-", "progress", "set", "or", "{" ]
train
https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/util/TxUtils.java#L114-L123
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java
Parameters.getParamForAnnotation
public String getParamForAnnotation(Class<?> clazz) { """ Gets the parameter associated with an annotation. Provided with an annotation class, this will check first if it has a {@code String} field called {@code param}. If it does, its value is returned. If not, it checks for a {@code String} field called {@code params}. If it exists, it is split on ",", the elements are trimmed, and the return value of {@link #getFirstExistingParamName(String[])} on the resulting array is returned. If neither is present, a {@link ParameterException} is thrown. The reason this hack-y thing exists is that it is often convenient for Guice annotations to include on the annotation the parameter typically used to set it when configuring from a param file. However, we cannot specify array valued fields on annotations, so we need to use a comma-separated {@code String}. """ try { return (String) clazz.getField("param").get(""); } catch (NoSuchFieldException e) { try { return getFirstExistingParamName( StringUtils.onCommas().splitToList((String) clazz.getField("params").get("")) .toArray(new String[]{})); } catch (NoSuchFieldException e1) { throw new ParameterException("Annotation " + clazz + " must have param or params field"); } catch (IllegalAccessException e1) { throw new ParameterException("While fetching parameter from annotation " + clazz, e); } } catch (IllegalAccessException e) { throw new ParameterException("While fetching parameter from annotation " + clazz, e); } }
java
public String getParamForAnnotation(Class<?> clazz) { try { return (String) clazz.getField("param").get(""); } catch (NoSuchFieldException e) { try { return getFirstExistingParamName( StringUtils.onCommas().splitToList((String) clazz.getField("params").get("")) .toArray(new String[]{})); } catch (NoSuchFieldException e1) { throw new ParameterException("Annotation " + clazz + " must have param or params field"); } catch (IllegalAccessException e1) { throw new ParameterException("While fetching parameter from annotation " + clazz, e); } } catch (IllegalAccessException e) { throw new ParameterException("While fetching parameter from annotation " + clazz, e); } }
[ "public", "String", "getParamForAnnotation", "(", "Class", "<", "?", ">", "clazz", ")", "{", "try", "{", "return", "(", "String", ")", "clazz", ".", "getField", "(", "\"param\"", ")", ".", "get", "(", "\"\"", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "try", "{", "return", "getFirstExistingParamName", "(", "StringUtils", ".", "onCommas", "(", ")", ".", "splitToList", "(", "(", "String", ")", "clazz", ".", "getField", "(", "\"params\"", ")", ".", "get", "(", "\"\"", ")", ")", ".", "toArray", "(", "new", "String", "[", "]", "{", "}", ")", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e1", ")", "{", "throw", "new", "ParameterException", "(", "\"Annotation \"", "+", "clazz", "+", "\" must have param or params field\"", ")", ";", "}", "catch", "(", "IllegalAccessException", "e1", ")", "{", "throw", "new", "ParameterException", "(", "\"While fetching parameter from annotation \"", "+", "clazz", ",", "e", ")", ";", "}", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "ParameterException", "(", "\"While fetching parameter from annotation \"", "+", "clazz", ",", "e", ")", ";", "}", "}" ]
Gets the parameter associated with an annotation. Provided with an annotation class, this will check first if it has a {@code String} field called {@code param}. If it does, its value is returned. If not, it checks for a {@code String} field called {@code params}. If it exists, it is split on ",", the elements are trimmed, and the return value of {@link #getFirstExistingParamName(String[])} on the resulting array is returned. If neither is present, a {@link ParameterException} is thrown. The reason this hack-y thing exists is that it is often convenient for Guice annotations to include on the annotation the parameter typically used to set it when configuring from a param file. However, we cannot specify array valued fields on annotations, so we need to use a comma-separated {@code String}.
[ "Gets", "the", "parameter", "associated", "with", "an", "annotation", ".", "Provided", "with", "an", "annotation", "class", "this", "will", "check", "first", "if", "it", "has", "a", "{", "@code", "String", "}", "field", "called", "{", "@code", "param", "}", ".", "If", "it", "does", "its", "value", "is", "returned", ".", "If", "not", "it", "checks", "for", "a", "{", "@code", "String", "}", "field", "called", "{", "@code", "params", "}", ".", "If", "it", "exists", "it", "is", "split", "on", "the", "elements", "are", "trimmed", "and", "the", "return", "value", "of", "{", "@link", "#getFirstExistingParamName", "(", "String", "[]", ")", "}", "on", "the", "resulting", "array", "is", "returned", ".", "If", "neither", "is", "present", "a", "{", "@link", "ParameterException", "}", "is", "thrown", "." ]
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java#L1216-L1232
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java
RoaringBitmap.maximumSerializedSize
public static long maximumSerializedSize(long cardinality, long universe_size) { """ Assume that one wants to store "cardinality" integers in [0, universe_size), this function returns an upper bound on the serialized size in bytes. @param cardinality maximal cardinality @param universe_size maximal value @return upper bound on the serialized size in bytes of the bitmap """ long contnbr = (universe_size + 65535) / 65536; if (contnbr > cardinality) { contnbr = cardinality; // we can't have more containers than we have values } final long headermax = Math.max(8, 4 + (contnbr + 7) / 8) + 8 * contnbr; final long valsarray = 2 * cardinality; final long valsbitmap = contnbr * 8192; final long valsbest = Math.min(valsarray, valsbitmap); return valsbest + headermax; }
java
public static long maximumSerializedSize(long cardinality, long universe_size) { long contnbr = (universe_size + 65535) / 65536; if (contnbr > cardinality) { contnbr = cardinality; // we can't have more containers than we have values } final long headermax = Math.max(8, 4 + (contnbr + 7) / 8) + 8 * contnbr; final long valsarray = 2 * cardinality; final long valsbitmap = contnbr * 8192; final long valsbest = Math.min(valsarray, valsbitmap); return valsbest + headermax; }
[ "public", "static", "long", "maximumSerializedSize", "(", "long", "cardinality", ",", "long", "universe_size", ")", "{", "long", "contnbr", "=", "(", "universe_size", "+", "65535", ")", "/", "65536", ";", "if", "(", "contnbr", ">", "cardinality", ")", "{", "contnbr", "=", "cardinality", ";", "// we can't have more containers than we have values", "}", "final", "long", "headermax", "=", "Math", ".", "max", "(", "8", ",", "4", "+", "(", "contnbr", "+", "7", ")", "/", "8", ")", "+", "8", "*", "contnbr", ";", "final", "long", "valsarray", "=", "2", "*", "cardinality", ";", "final", "long", "valsbitmap", "=", "contnbr", "*", "8192", ";", "final", "long", "valsbest", "=", "Math", ".", "min", "(", "valsarray", ",", "valsbitmap", ")", ";", "return", "valsbest", "+", "headermax", ";", "}" ]
Assume that one wants to store "cardinality" integers in [0, universe_size), this function returns an upper bound on the serialized size in bytes. @param cardinality maximal cardinality @param universe_size maximal value @return upper bound on the serialized size in bytes of the bitmap
[ "Assume", "that", "one", "wants", "to", "store", "cardinality", "integers", "in", "[", "0", "universe_size", ")", "this", "function", "returns", "an", "upper", "bound", "on", "the", "serialized", "size", "in", "bytes", "." ]
train
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringBitmap.java#L2532-L2543
apache/flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/expressions/ExpressionUtils.java
ExpressionUtils.isFunctionOfType
public static boolean isFunctionOfType(Expression expr, FunctionDefinition.Type type) { """ Checks if the expression is a function call of given type. @param expr expression to check @param type expected type of function @return true if the expression is function call of given type, false otherwise """ return expr instanceof CallExpression && ((CallExpression) expr).getFunctionDefinition().getType() == type; }
java
public static boolean isFunctionOfType(Expression expr, FunctionDefinition.Type type) { return expr instanceof CallExpression && ((CallExpression) expr).getFunctionDefinition().getType() == type; }
[ "public", "static", "boolean", "isFunctionOfType", "(", "Expression", "expr", ",", "FunctionDefinition", ".", "Type", "type", ")", "{", "return", "expr", "instanceof", "CallExpression", "&&", "(", "(", "CallExpression", ")", "expr", ")", ".", "getFunctionDefinition", "(", ")", ".", "getType", "(", ")", "==", "type", ";", "}" ]
Checks if the expression is a function call of given type. @param expr expression to check @param type expected type of function @return true if the expression is function call of given type, false otherwise
[ "Checks", "if", "the", "expression", "is", "a", "function", "call", "of", "given", "type", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-common/src/main/java/org/apache/flink/table/expressions/ExpressionUtils.java#L58-L61
molgenis/molgenis
molgenis-data-import/src/main/java/org/molgenis/data/importer/MyEntitiesValidationReport.java
MyEntitiesValidationReport.addAttribute
public MyEntitiesValidationReport addAttribute(String attributeName, AttributeState state) { """ Creates a new report, with an attribute added to the last added entity; @param attributeName name of the attribute to add @param state state of the attribute to add @return this report """ if (getImportOrder().isEmpty()) { throw new IllegalStateException("Must add entity first"); } String entityTypeId = getImportOrder().get(getImportOrder().size() - 1); valid = valid && state.isValid(); switch (state) { case IMPORTABLE: addField(fieldsImportable, entityTypeId, attributeName); break; case UNKNOWN: addField(fieldsUnknown, entityTypeId, attributeName); break; case AVAILABLE: addField(fieldsAvailable, entityTypeId, attributeName); break; case REQUIRED: addField(fieldsRequired, entityTypeId, attributeName); break; default: throw new UnexpectedEnumException(state); } return this; }
java
public MyEntitiesValidationReport addAttribute(String attributeName, AttributeState state) { if (getImportOrder().isEmpty()) { throw new IllegalStateException("Must add entity first"); } String entityTypeId = getImportOrder().get(getImportOrder().size() - 1); valid = valid && state.isValid(); switch (state) { case IMPORTABLE: addField(fieldsImportable, entityTypeId, attributeName); break; case UNKNOWN: addField(fieldsUnknown, entityTypeId, attributeName); break; case AVAILABLE: addField(fieldsAvailable, entityTypeId, attributeName); break; case REQUIRED: addField(fieldsRequired, entityTypeId, attributeName); break; default: throw new UnexpectedEnumException(state); } return this; }
[ "public", "MyEntitiesValidationReport", "addAttribute", "(", "String", "attributeName", ",", "AttributeState", "state", ")", "{", "if", "(", "getImportOrder", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Must add entity first\"", ")", ";", "}", "String", "entityTypeId", "=", "getImportOrder", "(", ")", ".", "get", "(", "getImportOrder", "(", ")", ".", "size", "(", ")", "-", "1", ")", ";", "valid", "=", "valid", "&&", "state", ".", "isValid", "(", ")", ";", "switch", "(", "state", ")", "{", "case", "IMPORTABLE", ":", "addField", "(", "fieldsImportable", ",", "entityTypeId", ",", "attributeName", ")", ";", "break", ";", "case", "UNKNOWN", ":", "addField", "(", "fieldsUnknown", ",", "entityTypeId", ",", "attributeName", ")", ";", "break", ";", "case", "AVAILABLE", ":", "addField", "(", "fieldsAvailable", ",", "entityTypeId", ",", "attributeName", ")", ";", "break", ";", "case", "REQUIRED", ":", "addField", "(", "fieldsRequired", ",", "entityTypeId", ",", "attributeName", ")", ";", "break", ";", "default", ":", "throw", "new", "UnexpectedEnumException", "(", "state", ")", ";", "}", "return", "this", ";", "}" ]
Creates a new report, with an attribute added to the last added entity; @param attributeName name of the attribute to add @param state state of the attribute to add @return this report
[ "Creates", "a", "new", "report", "with", "an", "attribute", "added", "to", "the", "last", "added", "entity", ";" ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-import/src/main/java/org/molgenis/data/importer/MyEntitiesValidationReport.java#L90-L113
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/StreamRecord.java
StreamRecord.withNewImage
public StreamRecord withNewImage(java.util.Map<String, AttributeValue> newImage) { """ <p> The item in the DynamoDB table as it appeared after it was modified. </p> @param newImage The item in the DynamoDB table as it appeared after it was modified. @return Returns a reference to this object so that method calls can be chained together. """ setNewImage(newImage); return this; }
java
public StreamRecord withNewImage(java.util.Map<String, AttributeValue> newImage) { setNewImage(newImage); return this; }
[ "public", "StreamRecord", "withNewImage", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "AttributeValue", ">", "newImage", ")", "{", "setNewImage", "(", "newImage", ")", ";", "return", "this", ";", "}" ]
<p> The item in the DynamoDB table as it appeared after it was modified. </p> @param newImage The item in the DynamoDB table as it appeared after it was modified. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "item", "in", "the", "DynamoDB", "table", "as", "it", "appeared", "after", "it", "was", "modified", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/StreamRecord.java#L239-L242
nohana/Amalgam
amalgam/src/main/java/com/amalgam/content/pm/SignatureUtils.java
SignatureUtils.ensureSameSignature
public static boolean ensureSameSignature(Context context, String targetPackageName, String expectedHash) { """ Ensure the running application and the target package has the same signature. @param context the running application context. @param targetPackageName the target package name. @param expectedHash signature hash that the target package is expected to have signed. @return true if the same signature. """ if (targetPackageName == null || expectedHash == null) { // cannot proceed anymore. return false; } String hash = expectedHash.replace(" ", ""); return hash.equals(getSignatureHexCode(context, targetPackageName)); }
java
public static boolean ensureSameSignature(Context context, String targetPackageName, String expectedHash) { if (targetPackageName == null || expectedHash == null) { // cannot proceed anymore. return false; } String hash = expectedHash.replace(" ", ""); return hash.equals(getSignatureHexCode(context, targetPackageName)); }
[ "public", "static", "boolean", "ensureSameSignature", "(", "Context", "context", ",", "String", "targetPackageName", ",", "String", "expectedHash", ")", "{", "if", "(", "targetPackageName", "==", "null", "||", "expectedHash", "==", "null", ")", "{", "// cannot proceed anymore.", "return", "false", ";", "}", "String", "hash", "=", "expectedHash", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ";", "return", "hash", ".", "equals", "(", "getSignatureHexCode", "(", "context", ",", "targetPackageName", ")", ")", ";", "}" ]
Ensure the running application and the target package has the same signature. @param context the running application context. @param targetPackageName the target package name. @param expectedHash signature hash that the target package is expected to have signed. @return true if the same signature.
[ "Ensure", "the", "running", "application", "and", "the", "target", "package", "has", "the", "same", "signature", "." ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/content/pm/SignatureUtils.java#L56-L63
cryptomator/native-functions
JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java
MacKeychainAccess.storePassword
public void storePassword(String account, CharSequence password) { """ Associates the specified password with the specified key in the system keychain. @param account Unique account identifier @param password Passphrase to store """ ByteBuffer pwBuf = UTF_8.encode(CharBuffer.wrap(password)); byte[] pwBytes = new byte[pwBuf.remaining()]; pwBuf.get(pwBytes); int errorCode = storePassword0(account.getBytes(UTF_8), pwBytes); Arrays.fill(pwBytes, (byte) 0x00); Arrays.fill(pwBuf.array(), (byte) 0x00); if (errorCode != OSSTATUS_SUCCESS) { throw new JniException("Failed to store password. Error code " + errorCode); } }
java
public void storePassword(String account, CharSequence password) { ByteBuffer pwBuf = UTF_8.encode(CharBuffer.wrap(password)); byte[] pwBytes = new byte[pwBuf.remaining()]; pwBuf.get(pwBytes); int errorCode = storePassword0(account.getBytes(UTF_8), pwBytes); Arrays.fill(pwBytes, (byte) 0x00); Arrays.fill(pwBuf.array(), (byte) 0x00); if (errorCode != OSSTATUS_SUCCESS) { throw new JniException("Failed to store password. Error code " + errorCode); } }
[ "public", "void", "storePassword", "(", "String", "account", ",", "CharSequence", "password", ")", "{", "ByteBuffer", "pwBuf", "=", "UTF_8", ".", "encode", "(", "CharBuffer", ".", "wrap", "(", "password", ")", ")", ";", "byte", "[", "]", "pwBytes", "=", "new", "byte", "[", "pwBuf", ".", "remaining", "(", ")", "]", ";", "pwBuf", ".", "get", "(", "pwBytes", ")", ";", "int", "errorCode", "=", "storePassword0", "(", "account", ".", "getBytes", "(", "UTF_8", ")", ",", "pwBytes", ")", ";", "Arrays", ".", "fill", "(", "pwBytes", ",", "(", "byte", ")", "0x00", ")", ";", "Arrays", ".", "fill", "(", "pwBuf", ".", "array", "(", ")", ",", "(", "byte", ")", "0x00", ")", ";", "if", "(", "errorCode", "!=", "OSSTATUS_SUCCESS", ")", "{", "throw", "new", "JniException", "(", "\"Failed to store password. Error code \"", "+", "errorCode", ")", ";", "}", "}" ]
Associates the specified password with the specified key in the system keychain. @param account Unique account identifier @param password Passphrase to store
[ "Associates", "the", "specified", "password", "with", "the", "specified", "key", "in", "the", "system", "keychain", "." ]
train
https://github.com/cryptomator/native-functions/blob/764cb1edbffbc2a4129c71011941adcbd4c12292/JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java#L28-L38
whitesource/agents
wss-agent-report/src/main/java/org/whitesource/agent/report/FileUtils.java
FileUtils.copyResource
public static void copyResource(String resource, File destination) throws IOException { """ Copy a classpath resource to a destination file. @param resource Path to resource to copy. @param destination File to copy resource to. @throws IOException exception2 """ InputStream is = null; FileOutputStream fos = null; try { is = FileUtils.class.getResourceAsStream("/" + resource); fos = new FileOutputStream(destination); final byte[] buffer = new byte[10 * 1024]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { close(is); close(fos); } }
java
public static void copyResource(String resource, File destination) throws IOException { InputStream is = null; FileOutputStream fos = null; try { is = FileUtils.class.getResourceAsStream("/" + resource); fos = new FileOutputStream(destination); final byte[] buffer = new byte[10 * 1024]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { close(is); close(fos); } }
[ "public", "static", "void", "copyResource", "(", "String", "resource", ",", "File", "destination", ")", "throws", "IOException", "{", "InputStream", "is", "=", "null", ";", "FileOutputStream", "fos", "=", "null", ";", "try", "{", "is", "=", "FileUtils", ".", "class", ".", "getResourceAsStream", "(", "\"/\"", "+", "resource", ")", ";", "fos", "=", "new", "FileOutputStream", "(", "destination", ")", ";", "final", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "10", "*", "1024", "]", ";", "int", "len", ";", "while", "(", "(", "len", "=", "is", ".", "read", "(", "buffer", ")", ")", ">", "0", ")", "{", "fos", ".", "write", "(", "buffer", ",", "0", ",", "len", ")", ";", "}", "}", "finally", "{", "close", "(", "is", ")", ";", "close", "(", "fos", ")", ";", "}", "}" ]
Copy a classpath resource to a destination file. @param resource Path to resource to copy. @param destination File to copy resource to. @throws IOException exception2
[ "Copy", "a", "classpath", "resource", "to", "a", "destination", "file", "." ]
train
https://github.com/whitesource/agents/blob/8a947a3dbad257aff70f23f79fb3a55ca90b765f/wss-agent-report/src/main/java/org/whitesource/agent/report/FileUtils.java#L38-L56
alkacon/opencms-core
src/org/opencms/ui/apps/CmsAppHierarchyPanel.java
CmsAppHierarchyPanel.addChild
public void addChild(String label, CmsAppHierarchyPanel child) { """ Adds a child category panel.<p> @param label the label @param child the child widget """ Panel panel = new Panel(); panel.setCaption(label); panel.setContent(child); addComponent(panel); }
java
public void addChild(String label, CmsAppHierarchyPanel child) { Panel panel = new Panel(); panel.setCaption(label); panel.setContent(child); addComponent(panel); }
[ "public", "void", "addChild", "(", "String", "label", ",", "CmsAppHierarchyPanel", "child", ")", "{", "Panel", "panel", "=", "new", "Panel", "(", ")", ";", "panel", ".", "setCaption", "(", "label", ")", ";", "panel", ".", "setContent", "(", "child", ")", ";", "addComponent", "(", "panel", ")", ";", "}" ]
Adds a child category panel.<p> @param label the label @param child the child widget
[ "Adds", "a", "child", "category", "panel", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/CmsAppHierarchyPanel.java#L77-L83
alipay/sofa-rpc
extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/http/HttpTracerUtils.java
HttpTracerUtils.parseTraceKey
public static void parseTraceKey(Map<String, String> tracerMap, String key, String value) { """ Parse tracer key @param tracerMap tracer map @param key tracer key @param value tracer value """ String lowKey = key.substring(PREFIX.length()); String realKey = TRACER_KEY_MAP.get(lowKey); tracerMap.put(realKey == null ? lowKey : realKey, value); }
java
public static void parseTraceKey(Map<String, String> tracerMap, String key, String value) { String lowKey = key.substring(PREFIX.length()); String realKey = TRACER_KEY_MAP.get(lowKey); tracerMap.put(realKey == null ? lowKey : realKey, value); }
[ "public", "static", "void", "parseTraceKey", "(", "Map", "<", "String", ",", "String", ">", "tracerMap", ",", "String", "key", ",", "String", "value", ")", "{", "String", "lowKey", "=", "key", ".", "substring", "(", "PREFIX", ".", "length", "(", ")", ")", ";", "String", "realKey", "=", "TRACER_KEY_MAP", ".", "get", "(", "lowKey", ")", ";", "tracerMap", ".", "put", "(", "realKey", "==", "null", "?", "lowKey", ":", "realKey", ",", "value", ")", ";", "}" ]
Parse tracer key @param tracerMap tracer map @param key tracer key @param value tracer value
[ "Parse", "tracer", "key" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/http/HttpTracerUtils.java#L61-L65
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.setAttribute
public static SetAttributeHandler setAttribute(final HttpHandler next, final String attribute, final String value, final ClassLoader classLoader) { """ Returns an attribute setting handler that can be used to set an arbitrary attribute on the exchange. This includes functions such as adding and removing headers etc. @param next The next handler @param attribute The attribute to set, specified as a string presentation of an {@link io.undertow.attribute.ExchangeAttribute} @param value The value to set, specified an a string representation of an {@link io.undertow.attribute.ExchangeAttribute} @param classLoader The class loader to use to parser the exchange attributes @return The handler """ return new SetAttributeHandler(next, attribute, value, classLoader); }
java
public static SetAttributeHandler setAttribute(final HttpHandler next, final String attribute, final String value, final ClassLoader classLoader) { return new SetAttributeHandler(next, attribute, value, classLoader); }
[ "public", "static", "SetAttributeHandler", "setAttribute", "(", "final", "HttpHandler", "next", ",", "final", "String", "attribute", ",", "final", "String", "value", ",", "final", "ClassLoader", "classLoader", ")", "{", "return", "new", "SetAttributeHandler", "(", "next", ",", "attribute", ",", "value", ",", "classLoader", ")", ";", "}" ]
Returns an attribute setting handler that can be used to set an arbitrary attribute on the exchange. This includes functions such as adding and removing headers etc. @param next The next handler @param attribute The attribute to set, specified as a string presentation of an {@link io.undertow.attribute.ExchangeAttribute} @param value The value to set, specified an a string representation of an {@link io.undertow.attribute.ExchangeAttribute} @param classLoader The class loader to use to parser the exchange attributes @return The handler
[ "Returns", "an", "attribute", "setting", "handler", "that", "can", "be", "used", "to", "set", "an", "arbitrary", "attribute", "on", "the", "exchange", ".", "This", "includes", "functions", "such", "as", "adding", "and", "removing", "headers", "etc", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L397-L399
io7m/jaffirm
com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Preconditions.java
Preconditions.checkPreconditionL
public static long checkPreconditionL( final long value, final boolean condition, final LongFunction<String> describer) { """ A {@code long} specialized version of {@link #checkPrecondition(Object, Predicate, Function)} @param condition The predicate @param value The value @param describer The describer of the predicate @return value @throws PreconditionViolationException If the predicate is false """ return innerCheckL(value, condition, describer); }
java
public static long checkPreconditionL( final long value, final boolean condition, final LongFunction<String> describer) { return innerCheckL(value, condition, describer); }
[ "public", "static", "long", "checkPreconditionL", "(", "final", "long", "value", ",", "final", "boolean", "condition", ",", "final", "LongFunction", "<", "String", ">", "describer", ")", "{", "return", "innerCheckL", "(", "value", ",", "condition", ",", "describer", ")", ";", "}" ]
A {@code long} specialized version of {@link #checkPrecondition(Object, Predicate, Function)} @param condition The predicate @param value The value @param describer The describer of the predicate @return value @throws PreconditionViolationException If the predicate is false
[ "A", "{", "@code", "long", "}", "specialized", "version", "of", "{", "@link", "#checkPrecondition", "(", "Object", "Predicate", "Function", ")", "}" ]
train
https://github.com/io7m/jaffirm/blob/c97d246242d381e48832838737418cfe4cb57b4d/com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Preconditions.java#L479-L485
tipsy/javalin
src/main/java/io/javalin/Javalin.java
Javalin.addHandler
public Javalin addHandler(@NotNull HandlerType handlerType, @NotNull String path, @NotNull Handler handler, @NotNull Set<Role> roles) { """ Adds a request handler for the specified handlerType and path to the instance. Requires an access manager to be set on the instance. This is the method that all the verb-methods (get/post/put/etc) call. @see AccessManager @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a> """ servlet.addHandler(handlerType, path, handler, roles); eventManager.fireHandlerAddedEvent(new HandlerMetaInfo(handlerType, Util.prefixContextPath(servlet.getConfig().contextPath, path), handler, roles)); return this; }
java
public Javalin addHandler(@NotNull HandlerType handlerType, @NotNull String path, @NotNull Handler handler, @NotNull Set<Role> roles) { servlet.addHandler(handlerType, path, handler, roles); eventManager.fireHandlerAddedEvent(new HandlerMetaInfo(handlerType, Util.prefixContextPath(servlet.getConfig().contextPath, path), handler, roles)); return this; }
[ "public", "Javalin", "addHandler", "(", "@", "NotNull", "HandlerType", "handlerType", ",", "@", "NotNull", "String", "path", ",", "@", "NotNull", "Handler", "handler", ",", "@", "NotNull", "Set", "<", "Role", ">", "roles", ")", "{", "servlet", ".", "addHandler", "(", "handlerType", ",", "path", ",", "handler", ",", "roles", ")", ";", "eventManager", ".", "fireHandlerAddedEvent", "(", "new", "HandlerMetaInfo", "(", "handlerType", ",", "Util", ".", "prefixContextPath", "(", "servlet", ".", "getConfig", "(", ")", ".", "contextPath", ",", "path", ")", ",", "handler", ",", "roles", ")", ")", ";", "return", "this", ";", "}" ]
Adds a request handler for the specified handlerType and path to the instance. Requires an access manager to be set on the instance. This is the method that all the verb-methods (get/post/put/etc) call. @see AccessManager @see <a href="https://javalin.io/documentation#handlers">Handlers in docs</a>
[ "Adds", "a", "request", "handler", "for", "the", "specified", "handlerType", "and", "path", "to", "the", "instance", ".", "Requires", "an", "access", "manager", "to", "be", "set", "on", "the", "instance", ".", "This", "is", "the", "method", "that", "all", "the", "verb", "-", "methods", "(", "get", "/", "post", "/", "put", "/", "etc", ")", "call", "." ]
train
https://github.com/tipsy/javalin/blob/68b2f7592f237db1c2b597e645697eb75fdaee53/src/main/java/io/javalin/Javalin.java#L268-L272
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_automaticCall_POST
public String billingAccount_line_serviceName_automaticCall_POST(String billingAccount, String serviceName, String bridgeNumberDialplan, String calledNumber, String callingNumber, OvhCallsGeneratorDialplanEnum dialplan, Boolean isAnonymous, String playbackAudioFileDialplan, Long timeout, String ttsTextDialplan) throws IOException { """ Make an automatic phone call. Return generated call identifier REST: POST /telephony/{billingAccount}/line/{serviceName}/automaticCall @param callingNumber [required] Optional, number where the call come from @param dialplan [required] Dialplan used for the call @param bridgeNumberDialplan [required] Number to call if transfer in dialplan selected @param isAnonymous [required] For anonymous call @param playbackAudioFileDialplan [required] Name of the audioFile (if needed) with extention. This audio file must have been upload previously @param ttsTextDialplan [required] Text to read if TTS on dialplan selected @param calledNumber [required] Number to call @param timeout [required] Timeout (in seconds). Default is 20 seconds @param billingAccount [required] The name of your billingAccount @param serviceName [required] """ String qPath = "/telephony/{billingAccount}/line/{serviceName}/automaticCall"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "bridgeNumberDialplan", bridgeNumberDialplan); addBody(o, "calledNumber", calledNumber); addBody(o, "callingNumber", callingNumber); addBody(o, "dialplan", dialplan); addBody(o, "isAnonymous", isAnonymous); addBody(o, "playbackAudioFileDialplan", playbackAudioFileDialplan); addBody(o, "timeout", timeout); addBody(o, "ttsTextDialplan", ttsTextDialplan); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
java
public String billingAccount_line_serviceName_automaticCall_POST(String billingAccount, String serviceName, String bridgeNumberDialplan, String calledNumber, String callingNumber, OvhCallsGeneratorDialplanEnum dialplan, Boolean isAnonymous, String playbackAudioFileDialplan, Long timeout, String ttsTextDialplan) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/automaticCall"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "bridgeNumberDialplan", bridgeNumberDialplan); addBody(o, "calledNumber", calledNumber); addBody(o, "callingNumber", callingNumber); addBody(o, "dialplan", dialplan); addBody(o, "isAnonymous", isAnonymous); addBody(o, "playbackAudioFileDialplan", playbackAudioFileDialplan); addBody(o, "timeout", timeout); addBody(o, "ttsTextDialplan", ttsTextDialplan); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
[ "public", "String", "billingAccount_line_serviceName_automaticCall_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "bridgeNumberDialplan", ",", "String", "calledNumber", ",", "String", "callingNumber", ",", "OvhCallsGeneratorDialplanEnum", "dialplan", ",", "Boolean", "isAnonymous", ",", "String", "playbackAudioFileDialplan", ",", "Long", "timeout", ",", "String", "ttsTextDialplan", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/line/{serviceName}/automaticCall\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"bridgeNumberDialplan\"", ",", "bridgeNumberDialplan", ")", ";", "addBody", "(", "o", ",", "\"calledNumber\"", ",", "calledNumber", ")", ";", "addBody", "(", "o", ",", "\"callingNumber\"", ",", "callingNumber", ")", ";", "addBody", "(", "o", ",", "\"dialplan\"", ",", "dialplan", ")", ";", "addBody", "(", "o", ",", "\"isAnonymous\"", ",", "isAnonymous", ")", ";", "addBody", "(", "o", ",", "\"playbackAudioFileDialplan\"", ",", "playbackAudioFileDialplan", ")", ";", "addBody", "(", "o", ",", "\"timeout\"", ",", "timeout", ")", ";", "addBody", "(", "o", ",", "\"ttsTextDialplan\"", ",", "ttsTextDialplan", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "String", ".", "class", ")", ";", "}" ]
Make an automatic phone call. Return generated call identifier REST: POST /telephony/{billingAccount}/line/{serviceName}/automaticCall @param callingNumber [required] Optional, number where the call come from @param dialplan [required] Dialplan used for the call @param bridgeNumberDialplan [required] Number to call if transfer in dialplan selected @param isAnonymous [required] For anonymous call @param playbackAudioFileDialplan [required] Name of the audioFile (if needed) with extention. This audio file must have been upload previously @param ttsTextDialplan [required] Text to read if TTS on dialplan selected @param calledNumber [required] Number to call @param timeout [required] Timeout (in seconds). Default is 20 seconds @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Make", "an", "automatic", "phone", "call", ".", "Return", "generated", "call", "identifier" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L1760-L1774
b3log/latke
latke-core/src/main/java/org/b3log/latke/plugin/PluginManager.java
PluginManager.setPluginProps
private static void setPluginProps(final String pluginDirName, final AbstractPlugin plugin, final Properties props) throws Exception { """ Sets the specified plugin's properties from the specified properties file under the specified plugin directory. @param pluginDirName the specified plugin directory @param plugin the specified plugin @param props the specified properties file @throws Exception exception """ final String author = props.getProperty(Plugin.PLUGIN_AUTHOR); final String name = props.getProperty(Plugin.PLUGIN_NAME); final String version = props.getProperty(Plugin.PLUGIN_VERSION); final String types = props.getProperty(Plugin.PLUGIN_TYPES); LOGGER.log(Level.TRACE, "Plugin[name={0}, author={1}, version={2}, types={3}]", name, author, version, types); plugin.setAuthor(author); plugin.setName(name); plugin.setId(name + "_" + version); plugin.setVersion(version); plugin.setDir(pluginDirName); plugin.readLangs(); // try to find the setting config.json final File settingFile = Latkes.getWebFile("/plugins/" + pluginDirName + "/config.json"); if (null != settingFile && settingFile.exists()) { try { final String config = FileUtils.readFileToString(settingFile); final JSONObject jsonObject = new JSONObject(config); plugin.setSetting(jsonObject); } catch (final IOException ie) { LOGGER.log(Level.ERROR, "reading the config of the plugin[" + name + "] failed", ie); } catch (final JSONException e) { LOGGER.log(Level.ERROR, "convert the config of the plugin[" + name + "] to json failed", e); } } Arrays.stream(types.split(",")).map(PluginType::valueOf).forEach(plugin::addType); }
java
private static void setPluginProps(final String pluginDirName, final AbstractPlugin plugin, final Properties props) throws Exception { final String author = props.getProperty(Plugin.PLUGIN_AUTHOR); final String name = props.getProperty(Plugin.PLUGIN_NAME); final String version = props.getProperty(Plugin.PLUGIN_VERSION); final String types = props.getProperty(Plugin.PLUGIN_TYPES); LOGGER.log(Level.TRACE, "Plugin[name={0}, author={1}, version={2}, types={3}]", name, author, version, types); plugin.setAuthor(author); plugin.setName(name); plugin.setId(name + "_" + version); plugin.setVersion(version); plugin.setDir(pluginDirName); plugin.readLangs(); // try to find the setting config.json final File settingFile = Latkes.getWebFile("/plugins/" + pluginDirName + "/config.json"); if (null != settingFile && settingFile.exists()) { try { final String config = FileUtils.readFileToString(settingFile); final JSONObject jsonObject = new JSONObject(config); plugin.setSetting(jsonObject); } catch (final IOException ie) { LOGGER.log(Level.ERROR, "reading the config of the plugin[" + name + "] failed", ie); } catch (final JSONException e) { LOGGER.log(Level.ERROR, "convert the config of the plugin[" + name + "] to json failed", e); } } Arrays.stream(types.split(",")).map(PluginType::valueOf).forEach(plugin::addType); }
[ "private", "static", "void", "setPluginProps", "(", "final", "String", "pluginDirName", ",", "final", "AbstractPlugin", "plugin", ",", "final", "Properties", "props", ")", "throws", "Exception", "{", "final", "String", "author", "=", "props", ".", "getProperty", "(", "Plugin", ".", "PLUGIN_AUTHOR", ")", ";", "final", "String", "name", "=", "props", ".", "getProperty", "(", "Plugin", ".", "PLUGIN_NAME", ")", ";", "final", "String", "version", "=", "props", ".", "getProperty", "(", "Plugin", ".", "PLUGIN_VERSION", ")", ";", "final", "String", "types", "=", "props", ".", "getProperty", "(", "Plugin", ".", "PLUGIN_TYPES", ")", ";", "LOGGER", ".", "log", "(", "Level", ".", "TRACE", ",", "\"Plugin[name={0}, author={1}, version={2}, types={3}]\"", ",", "name", ",", "author", ",", "version", ",", "types", ")", ";", "plugin", ".", "setAuthor", "(", "author", ")", ";", "plugin", ".", "setName", "(", "name", ")", ";", "plugin", ".", "setId", "(", "name", "+", "\"_\"", "+", "version", ")", ";", "plugin", ".", "setVersion", "(", "version", ")", ";", "plugin", ".", "setDir", "(", "pluginDirName", ")", ";", "plugin", ".", "readLangs", "(", ")", ";", "// try to find the setting config.json", "final", "File", "settingFile", "=", "Latkes", ".", "getWebFile", "(", "\"/plugins/\"", "+", "pluginDirName", "+", "\"/config.json\"", ")", ";", "if", "(", "null", "!=", "settingFile", "&&", "settingFile", ".", "exists", "(", ")", ")", "{", "try", "{", "final", "String", "config", "=", "FileUtils", ".", "readFileToString", "(", "settingFile", ")", ";", "final", "JSONObject", "jsonObject", "=", "new", "JSONObject", "(", "config", ")", ";", "plugin", ".", "setSetting", "(", "jsonObject", ")", ";", "}", "catch", "(", "final", "IOException", "ie", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "ERROR", ",", "\"reading the config of the plugin[\"", "+", "name", "+", "\"] failed\"", ",", "ie", ")", ";", "}", "catch", "(", "final", "JSONException", "e", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "ERROR", ",", "\"convert the config of the plugin[\"", "+", "name", "+", "\"] to json failed\"", ",", "e", ")", ";", "}", "}", "Arrays", ".", "stream", "(", "types", ".", "split", "(", "\",\"", ")", ")", ".", "map", "(", "PluginType", "::", "valueOf", ")", ".", "forEach", "(", "plugin", "::", "addType", ")", ";", "}" ]
Sets the specified plugin's properties from the specified properties file under the specified plugin directory. @param pluginDirName the specified plugin directory @param plugin the specified plugin @param props the specified properties file @throws Exception exception
[ "Sets", "the", "specified", "plugin", "s", "properties", "from", "the", "specified", "properties", "file", "under", "the", "specified", "plugin", "directory", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/plugin/PluginManager.java#L250-L282
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsEmbeddedDialogHandler.java
CmsEmbeddedDialogHandler.openDialog
public void openDialog(String dialogId, String contextType, List<CmsUUID> resources) { """ Opens the dialog with the given id.<p> @param dialogId the dialog id @param contextType the context type, used to check the action visibility @param resources the resource to handle """ openDialog(dialogId, contextType, resources, null); }
java
public void openDialog(String dialogId, String contextType, List<CmsUUID> resources) { openDialog(dialogId, contextType, resources, null); }
[ "public", "void", "openDialog", "(", "String", "dialogId", ",", "String", "contextType", ",", "List", "<", "CmsUUID", ">", "resources", ")", "{", "openDialog", "(", "dialogId", ",", "contextType", ",", "resources", ",", "null", ")", ";", "}" ]
Opens the dialog with the given id.<p> @param dialogId the dialog id @param contextType the context type, used to check the action visibility @param resources the resource to handle
[ "Opens", "the", "dialog", "with", "the", "given", "id", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsEmbeddedDialogHandler.java#L158-L161
JOML-CI/JOML
src/org/joml/Matrix4x3d.java
Matrix4x3d.rotateLocalX
public Matrix4x3d rotateLocalX(double ang, Matrix4x3d dest) { """ Pre-multiply a rotation around the X axis to this matrix by rotating the given amount of radians about the X axis and store the result in <code>dest</code>. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>R * M</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the rotation will be applied last! <p> In order to set the matrix to a rotation matrix without pre-multiplying the rotation transformation, use {@link #rotationX(double) rotationX()}. <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> @see #rotationX(double) @param ang the angle in radians to rotate about the X axis @param dest will hold the result @return dest """ double sin = Math.sin(ang); double cos = Math.cosFromSin(sin, ang); double nm01 = cos * m01 - sin * m02; double nm02 = sin * m01 + cos * m02; double nm11 = cos * m11 - sin * m12; double nm12 = sin * m11 + cos * m12; double nm21 = cos * m21 - sin * m22; double nm22 = sin * m21 + cos * m22; double nm31 = cos * m31 - sin * m32; double nm32 = sin * m31 + cos * m32; dest.m00 = m00; dest.m01 = nm01; dest.m02 = nm02; dest.m10 = m10; dest.m11 = nm11; dest.m12 = nm12; dest.m20 = m20; dest.m21 = nm21; dest.m22 = nm22; dest.m30 = m30; dest.m31 = nm31; dest.m32 = nm32; dest.properties = properties & ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return dest; }
java
public Matrix4x3d rotateLocalX(double ang, Matrix4x3d dest) { double sin = Math.sin(ang); double cos = Math.cosFromSin(sin, ang); double nm01 = cos * m01 - sin * m02; double nm02 = sin * m01 + cos * m02; double nm11 = cos * m11 - sin * m12; double nm12 = sin * m11 + cos * m12; double nm21 = cos * m21 - sin * m22; double nm22 = sin * m21 + cos * m22; double nm31 = cos * m31 - sin * m32; double nm32 = sin * m31 + cos * m32; dest.m00 = m00; dest.m01 = nm01; dest.m02 = nm02; dest.m10 = m10; dest.m11 = nm11; dest.m12 = nm12; dest.m20 = m20; dest.m21 = nm21; dest.m22 = nm22; dest.m30 = m30; dest.m31 = nm31; dest.m32 = nm32; dest.properties = properties & ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return dest; }
[ "public", "Matrix4x3d", "rotateLocalX", "(", "double", "ang", ",", "Matrix4x3d", "dest", ")", "{", "double", "sin", "=", "Math", ".", "sin", "(", "ang", ")", ";", "double", "cos", "=", "Math", ".", "cosFromSin", "(", "sin", ",", "ang", ")", ";", "double", "nm01", "=", "cos", "*", "m01", "-", "sin", "*", "m02", ";", "double", "nm02", "=", "sin", "*", "m01", "+", "cos", "*", "m02", ";", "double", "nm11", "=", "cos", "*", "m11", "-", "sin", "*", "m12", ";", "double", "nm12", "=", "sin", "*", "m11", "+", "cos", "*", "m12", ";", "double", "nm21", "=", "cos", "*", "m21", "-", "sin", "*", "m22", ";", "double", "nm22", "=", "sin", "*", "m21", "+", "cos", "*", "m22", ";", "double", "nm31", "=", "cos", "*", "m31", "-", "sin", "*", "m32", ";", "double", "nm32", "=", "sin", "*", "m31", "+", "cos", "*", "m32", ";", "dest", ".", "m00", "=", "m00", ";", "dest", ".", "m01", "=", "nm01", ";", "dest", ".", "m02", "=", "nm02", ";", "dest", ".", "m10", "=", "m10", ";", "dest", ".", "m11", "=", "nm11", ";", "dest", ".", "m12", "=", "nm12", ";", "dest", ".", "m20", "=", "m20", ";", "dest", ".", "m21", "=", "nm21", ";", "dest", ".", "m22", "=", "nm22", ";", "dest", ".", "m30", "=", "m30", ";", "dest", ".", "m31", "=", "nm31", ";", "dest", ".", "m32", "=", "nm32", ";", "dest", ".", "properties", "=", "properties", "&", "~", "(", "PROPERTY_IDENTITY", "|", "PROPERTY_TRANSLATION", ")", ";", "return", "dest", ";", "}" ]
Pre-multiply a rotation around the X axis to this matrix by rotating the given amount of radians about the X axis and store the result in <code>dest</code>. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>R * M</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the rotation will be applied last! <p> In order to set the matrix to a rotation matrix without pre-multiplying the rotation transformation, use {@link #rotationX(double) rotationX()}. <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> @see #rotationX(double) @param ang the angle in radians to rotate about the X axis @param dest will hold the result @return dest
[ "Pre", "-", "multiply", "a", "rotation", "around", "the", "X", "axis", "to", "this", "matrix", "by", "rotating", "the", "given", "amount", "of", "radians", "about", "the", "X", "axis", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", "code", ">", ".", "<p", ">", "When", "used", "with", "a", "right", "-", "handed", "coordinate", "system", "the", "produced", "rotation", "will", "rotate", "a", "vector", "counter", "-", "clockwise", "around", "the", "rotation", "axis", "when", "viewing", "along", "the", "negative", "axis", "direction", "towards", "the", "origin", ".", "When", "used", "with", "a", "left", "-", "handed", "coordinate", "system", "the", "rotation", "is", "clockwise", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "R<", "/", "code", ">", "the", "rotation", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "R", "*", "M<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "R", "*", "M", "*", "v<", "/", "code", ">", "the", "rotation", "will", "be", "applied", "last!", "<p", ">", "In", "order", "to", "set", "the", "matrix", "to", "a", "rotation", "matrix", "without", "pre", "-", "multiplying", "the", "rotation", "transformation", "use", "{", "@link", "#rotationX", "(", "double", ")", "rotationX", "()", "}", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Rotation_matrix#Rotation_matrix_from_axis_and_angle", ">", "http", ":", "//", "en", ".", "wikipedia", ".", "org<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L3584-L3609
javalite/activeweb
activeweb/src/main/java/org/javalite/activeweb/Captcha.java
Captcha.generateImage
public static byte[] generateImage(String text) { """ Generates a PNG image of text 180 pixels wide, 40 pixels high with white background. @param text expects string size eight (8) characters. @return byte array that is a PNG image generated with text displayed. """ int w = 180, h = 40; BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setColor(Color.white); g.fillRect(0, 0, w, h); g.setFont(new Font("Serif", Font.PLAIN, 26)); g.setColor(Color.blue); int start = 10; byte[] bytes = text.getBytes(); Random random = new Random(); for (int i = 0; i < bytes.length; i++) { g.setColor( new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.drawString(new String(new byte[]{bytes[i]}), start + (i * 20), (int) (Math.random() * 20 + 20)); } g.setColor(Color.white); for (int i = 0; i < 8; i++) { g.drawOval((int) (Math.random() * 160), (int) (Math.random() * 10), 30, 30); } g.dispose(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", bout); } catch (Exception e) { throw new RuntimeException(e); } return bout.toByteArray(); }
java
public static byte[] generateImage(String text) { int w = 180, h = 40; BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setColor(Color.white); g.fillRect(0, 0, w, h); g.setFont(new Font("Serif", Font.PLAIN, 26)); g.setColor(Color.blue); int start = 10; byte[] bytes = text.getBytes(); Random random = new Random(); for (int i = 0; i < bytes.length; i++) { g.setColor( new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.drawString(new String(new byte[]{bytes[i]}), start + (i * 20), (int) (Math.random() * 20 + 20)); } g.setColor(Color.white); for (int i = 0; i < 8; i++) { g.drawOval((int) (Math.random() * 160), (int) (Math.random() * 10), 30, 30); } g.dispose(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", bout); } catch (Exception e) { throw new RuntimeException(e); } return bout.toByteArray(); }
[ "public", "static", "byte", "[", "]", "generateImage", "(", "String", "text", ")", "{", "int", "w", "=", "180", ",", "h", "=", "40", ";", "BufferedImage", "image", "=", "new", "BufferedImage", "(", "w", ",", "h", ",", "BufferedImage", ".", "TYPE_INT_RGB", ")", ";", "Graphics2D", "g", "=", "image", ".", "createGraphics", "(", ")", ";", "g", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_FRACTIONALMETRICS", ",", "RenderingHints", ".", "VALUE_FRACTIONALMETRICS_ON", ")", ";", "g", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_TEXT_ANTIALIASING", ",", "RenderingHints", ".", "VALUE_TEXT_ANTIALIAS_ON", ")", ";", "g", ".", "setColor", "(", "Color", ".", "white", ")", ";", "g", ".", "fillRect", "(", "0", ",", "0", ",", "w", ",", "h", ")", ";", "g", ".", "setFont", "(", "new", "Font", "(", "\"Serif\"", ",", "Font", ".", "PLAIN", ",", "26", ")", ")", ";", "g", ".", "setColor", "(", "Color", ".", "blue", ")", ";", "int", "start", "=", "10", ";", "byte", "[", "]", "bytes", "=", "text", ".", "getBytes", "(", ")", ";", "Random", "random", "=", "new", "Random", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "g", ".", "setColor", "(", "new", "Color", "(", "random", ".", "nextInt", "(", "255", ")", ",", "random", ".", "nextInt", "(", "255", ")", ",", "random", ".", "nextInt", "(", "255", ")", ")", ")", ";", "g", ".", "drawString", "(", "new", "String", "(", "new", "byte", "[", "]", "{", "bytes", "[", "i", "]", "}", ")", ",", "start", "+", "(", "i", "*", "20", ")", ",", "(", "int", ")", "(", "Math", ".", "random", "(", ")", "*", "20", "+", "20", ")", ")", ";", "}", "g", ".", "setColor", "(", "Color", ".", "white", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "g", ".", "drawOval", "(", "(", "int", ")", "(", "Math", ".", "random", "(", ")", "*", "160", ")", ",", "(", "int", ")", "(", "Math", ".", "random", "(", ")", "*", "10", ")", ",", "30", ",", "30", ")", ";", "}", "g", ".", "dispose", "(", ")", ";", "ByteArrayOutputStream", "bout", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "ImageIO", ".", "write", "(", "image", ",", "\"png\"", ",", "bout", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "return", "bout", ".", "toByteArray", "(", ")", ";", "}" ]
Generates a PNG image of text 180 pixels wide, 40 pixels high with white background. @param text expects string size eight (8) characters. @return byte array that is a PNG image generated with text displayed.
[ "Generates", "a", "PNG", "image", "of", "text", "180", "pixels", "wide", "40", "pixels", "high", "with", "white", "background", "." ]
train
https://github.com/javalite/activeweb/blob/f25f589da94852b6f5625182360732e0861794a6/activeweb/src/main/java/org/javalite/activeweb/Captcha.java#L50-L81
foundation-runtime/service-directory
1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java
ServiceInstanceUtils.validateOptionalField
public static boolean validateOptionalField(String field, String reg) { """ Validate the optional field String against regex. @param field the field value String. @param reg the regex. @return true if field is empty of matched the pattern. """ if (field == null || field.isEmpty()) { return true; } return Pattern.matches(reg, field); }
java
public static boolean validateOptionalField(String field, String reg) { if (field == null || field.isEmpty()) { return true; } return Pattern.matches(reg, field); }
[ "public", "static", "boolean", "validateOptionalField", "(", "String", "field", ",", "String", "reg", ")", "{", "if", "(", "field", "==", "null", "||", "field", ".", "isEmpty", "(", ")", ")", "{", "return", "true", ";", "}", "return", "Pattern", ".", "matches", "(", "reg", ",", "field", ")", ";", "}" ]
Validate the optional field String against regex. @param field the field value String. @param reg the regex. @return true if field is empty of matched the pattern.
[ "Validate", "the", "optional", "field", "String", "against", "regex", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java#L103-L108
kuujo/vertigo
core/src/main/java/net/kuujo/vertigo/util/Args.java
Args.checkUriScheme
public static void checkUriScheme(String scheme, String message, Object... args) { """ Validates that an argument is a valid URI scheme. @param scheme The value to check. @param message An exception message. @param args Exception message arguments. """ String uri = String.format("%s://null", scheme); try { new URI(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException(String.format(message, args)); } }
java
public static void checkUriScheme(String scheme, String message, Object... args) { String uri = String.format("%s://null", scheme); try { new URI(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException(String.format(message, args)); } }
[ "public", "static", "void", "checkUriScheme", "(", "String", "scheme", ",", "String", "message", ",", "Object", "...", "args", ")", "{", "String", "uri", "=", "String", ".", "format", "(", "\"%s://null\"", ",", "scheme", ")", ";", "try", "{", "new", "URI", "(", "uri", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "message", ",", "args", ")", ")", ";", "}", "}" ]
Validates that an argument is a valid URI scheme. @param scheme The value to check. @param message An exception message. @param args Exception message arguments.
[ "Validates", "that", "an", "argument", "is", "a", "valid", "URI", "scheme", "." ]
train
https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/util/Args.java#L149-L156
optimatika/ojAlgo-finance
src/main/java/org/ojalgo/finance/FinanceUtils.java
FinanceUtils.toVolatilities
public static PrimitiveMatrix toVolatilities(Access2D<?> covariances, boolean clean) { """ Will extract the standard deviations (volatilities) from the input covariance matrix. If "cleaning" is enabled small variances will be replaced with a new minimal value. """ int size = Math.toIntExact(Math.min(covariances.countRows(), covariances.countColumns())); PrimitiveMatrix.DenseReceiver retVal = PrimitiveMatrix.FACTORY.makeDense(size); if (clean) { MatrixStore<Double> covarianceMtrx = MatrixStore.PRIMITIVE.makeWrapper(covariances).get(); double largest = covarianceMtrx.aggregateDiagonal(Aggregator.LARGEST); double limit = largest * size * PrimitiveMath.RELATIVELY_SMALL; double smallest = PrimitiveMath.SQRT.invoke(limit); for (int ij = 0; ij < size; ij++) { double variance = covariances.doubleValue(ij, ij); if (variance < limit) { retVal.set(ij, smallest); } else { retVal.set(ij, PrimitiveMath.SQRT.invoke(variance)); } } } else { for (int ij = 0; ij < size; ij++) { double variance = covariances.doubleValue(ij, ij); if (variance <= PrimitiveMath.ZERO) { retVal.set(ij, PrimitiveMath.ZERO); } else { retVal.set(ij, PrimitiveMath.SQRT.invoke(variance)); } } } return retVal.get(); }
java
public static PrimitiveMatrix toVolatilities(Access2D<?> covariances, boolean clean) { int size = Math.toIntExact(Math.min(covariances.countRows(), covariances.countColumns())); PrimitiveMatrix.DenseReceiver retVal = PrimitiveMatrix.FACTORY.makeDense(size); if (clean) { MatrixStore<Double> covarianceMtrx = MatrixStore.PRIMITIVE.makeWrapper(covariances).get(); double largest = covarianceMtrx.aggregateDiagonal(Aggregator.LARGEST); double limit = largest * size * PrimitiveMath.RELATIVELY_SMALL; double smallest = PrimitiveMath.SQRT.invoke(limit); for (int ij = 0; ij < size; ij++) { double variance = covariances.doubleValue(ij, ij); if (variance < limit) { retVal.set(ij, smallest); } else { retVal.set(ij, PrimitiveMath.SQRT.invoke(variance)); } } } else { for (int ij = 0; ij < size; ij++) { double variance = covariances.doubleValue(ij, ij); if (variance <= PrimitiveMath.ZERO) { retVal.set(ij, PrimitiveMath.ZERO); } else { retVal.set(ij, PrimitiveMath.SQRT.invoke(variance)); } } } return retVal.get(); }
[ "public", "static", "PrimitiveMatrix", "toVolatilities", "(", "Access2D", "<", "?", ">", "covariances", ",", "boolean", "clean", ")", "{", "int", "size", "=", "Math", ".", "toIntExact", "(", "Math", ".", "min", "(", "covariances", ".", "countRows", "(", ")", ",", "covariances", ".", "countColumns", "(", ")", ")", ")", ";", "PrimitiveMatrix", ".", "DenseReceiver", "retVal", "=", "PrimitiveMatrix", ".", "FACTORY", ".", "makeDense", "(", "size", ")", ";", "if", "(", "clean", ")", "{", "MatrixStore", "<", "Double", ">", "covarianceMtrx", "=", "MatrixStore", ".", "PRIMITIVE", ".", "makeWrapper", "(", "covariances", ")", ".", "get", "(", ")", ";", "double", "largest", "=", "covarianceMtrx", ".", "aggregateDiagonal", "(", "Aggregator", ".", "LARGEST", ")", ";", "double", "limit", "=", "largest", "*", "size", "*", "PrimitiveMath", ".", "RELATIVELY_SMALL", ";", "double", "smallest", "=", "PrimitiveMath", ".", "SQRT", ".", "invoke", "(", "limit", ")", ";", "for", "(", "int", "ij", "=", "0", ";", "ij", "<", "size", ";", "ij", "++", ")", "{", "double", "variance", "=", "covariances", ".", "doubleValue", "(", "ij", ",", "ij", ")", ";", "if", "(", "variance", "<", "limit", ")", "{", "retVal", ".", "set", "(", "ij", ",", "smallest", ")", ";", "}", "else", "{", "retVal", ".", "set", "(", "ij", ",", "PrimitiveMath", ".", "SQRT", ".", "invoke", "(", "variance", ")", ")", ";", "}", "}", "}", "else", "{", "for", "(", "int", "ij", "=", "0", ";", "ij", "<", "size", ";", "ij", "++", ")", "{", "double", "variance", "=", "covariances", ".", "doubleValue", "(", "ij", ",", "ij", ")", ";", "if", "(", "variance", "<=", "PrimitiveMath", ".", "ZERO", ")", "{", "retVal", ".", "set", "(", "ij", ",", "PrimitiveMath", ".", "ZERO", ")", ";", "}", "else", "{", "retVal", ".", "set", "(", "ij", ",", "PrimitiveMath", ".", "SQRT", ".", "invoke", "(", "variance", ")", ")", ";", "}", "}", "}", "return", "retVal", ".", "get", "(", ")", ";", "}" ]
Will extract the standard deviations (volatilities) from the input covariance matrix. If "cleaning" is enabled small variances will be replaced with a new minimal value.
[ "Will", "extract", "the", "standard", "deviations", "(", "volatilities", ")", "from", "the", "input", "covariance", "matrix", ".", "If", "cleaning", "is", "enabled", "small", "variances", "will", "be", "replaced", "with", "a", "new", "minimal", "value", "." ]
train
https://github.com/optimatika/ojAlgo-finance/blob/c8d3f7e1894d4263b7334bca3f4c060e466f8b15/src/main/java/org/ojalgo/finance/FinanceUtils.java#L471-L509
jbundle/jbundle
base/screen/control/servlet/src/main/java/org/jbundle/base/screen/control/servlet/message/trx/transport/xml/XMLMessageTransport.java
XMLMessageTransport.createExternalMessage
public ExternalMessage createExternalMessage(BaseMessage message, Object rawData) { """ Get the external message container for this Internal message. Typically, the overriding class supplies a default format for the transport type. <br/>NOTE: The message header from the internal message is copies, but not the message itself. @param The internalTrxMessage that I will convert to this external format. @return The (empty) External message. """ ExternalMessage externalTrxMessageOut = super.createExternalMessage(message, rawData); if (externalTrxMessageOut == null) { if (MessageTypeModel.MESSAGE_IN.equalsIgnoreCase((String)message.get(TrxMessageHeader.MESSAGE_PROCESS_TYPE))) externalTrxMessageOut = new XmlTrxMessageIn(message, rawData); else externalTrxMessageOut = new XmlTrxMessageOut(message, rawData); } return externalTrxMessageOut; }
java
public ExternalMessage createExternalMessage(BaseMessage message, Object rawData) { ExternalMessage externalTrxMessageOut = super.createExternalMessage(message, rawData); if (externalTrxMessageOut == null) { if (MessageTypeModel.MESSAGE_IN.equalsIgnoreCase((String)message.get(TrxMessageHeader.MESSAGE_PROCESS_TYPE))) externalTrxMessageOut = new XmlTrxMessageIn(message, rawData); else externalTrxMessageOut = new XmlTrxMessageOut(message, rawData); } return externalTrxMessageOut; }
[ "public", "ExternalMessage", "createExternalMessage", "(", "BaseMessage", "message", ",", "Object", "rawData", ")", "{", "ExternalMessage", "externalTrxMessageOut", "=", "super", ".", "createExternalMessage", "(", "message", ",", "rawData", ")", ";", "if", "(", "externalTrxMessageOut", "==", "null", ")", "{", "if", "(", "MessageTypeModel", ".", "MESSAGE_IN", ".", "equalsIgnoreCase", "(", "(", "String", ")", "message", ".", "get", "(", "TrxMessageHeader", ".", "MESSAGE_PROCESS_TYPE", ")", ")", ")", "externalTrxMessageOut", "=", "new", "XmlTrxMessageIn", "(", "message", ",", "rawData", ")", ";", "else", "externalTrxMessageOut", "=", "new", "XmlTrxMessageOut", "(", "message", ",", "rawData", ")", ";", "}", "return", "externalTrxMessageOut", ";", "}" ]
Get the external message container for this Internal message. Typically, the overriding class supplies a default format for the transport type. <br/>NOTE: The message header from the internal message is copies, but not the message itself. @param The internalTrxMessage that I will convert to this external format. @return The (empty) External message.
[ "Get", "the", "external", "message", "container", "for", "this", "Internal", "message", ".", "Typically", "the", "overriding", "class", "supplies", "a", "default", "format", "for", "the", "transport", "type", ".", "<br", "/", ">", "NOTE", ":", "The", "message", "header", "from", "the", "internal", "message", "is", "copies", "but", "not", "the", "message", "itself", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/control/servlet/src/main/java/org/jbundle/base/screen/control/servlet/message/trx/transport/xml/XMLMessageTransport.java#L79-L90
mapcode-foundation/mapcode-java
src/main/java/com/mapcode/MapcodeCodec.java
MapcodeCodec.encodeToInternational
@Nonnull public static Mapcode encodeToInternational(final double latDeg, final double lonDeg) throws IllegalArgumentException { """ Encode a lat/lon pair to its unambiguous, international mapcode. @param latDeg Latitude, accepted range: -90..90. @param lonDeg Longitude, accepted range: -180..180. @return International unambiguous mapcode (always exists), see {@link Mapcode}. @throws IllegalArgumentException Thrown if latitude or longitude are out of range. """ // Call mapcode encoder. @Nonnull final List<Mapcode> results = encode(latDeg, lonDeg, Territory.AAA); assert results != null; assert results.size() >= 1; return results.get(results.size() - 1); }
java
@Nonnull public static Mapcode encodeToInternational(final double latDeg, final double lonDeg) throws IllegalArgumentException { // Call mapcode encoder. @Nonnull final List<Mapcode> results = encode(latDeg, lonDeg, Territory.AAA); assert results != null; assert results.size() >= 1; return results.get(results.size() - 1); }
[ "@", "Nonnull", "public", "static", "Mapcode", "encodeToInternational", "(", "final", "double", "latDeg", ",", "final", "double", "lonDeg", ")", "throws", "IllegalArgumentException", "{", "// Call mapcode encoder.", "@", "Nonnull", "final", "List", "<", "Mapcode", ">", "results", "=", "encode", "(", "latDeg", ",", "lonDeg", ",", "Territory", ".", "AAA", ")", ";", "assert", "results", "!=", "null", ";", "assert", "results", ".", "size", "(", ")", ">=", "1", ";", "return", "results", ".", "get", "(", "results", ".", "size", "(", ")", "-", "1", ")", ";", "}" ]
Encode a lat/lon pair to its unambiguous, international mapcode. @param latDeg Latitude, accepted range: -90..90. @param lonDeg Longitude, accepted range: -180..180. @return International unambiguous mapcode (always exists), see {@link Mapcode}. @throws IllegalArgumentException Thrown if latitude or longitude are out of range.
[ "Encode", "a", "lat", "/", "lon", "pair", "to", "its", "unambiguous", "international", "mapcode", "." ]
train
https://github.com/mapcode-foundation/mapcode-java/blob/f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8/src/main/java/com/mapcode/MapcodeCodec.java#L266-L275
LearnLib/learnlib
algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java
AbstractTTTLearner.splitState
private void splitState(TTTTransition<I, D> transition, Word<I> tempDiscriminator, D oldOut, D newOut) { """ Splits a state in the hypothesis, using a temporary discriminator. The state to be split is identified by an incoming non-tree transition. This transition is subsequently turned into a spanning tree transition. @param transition the transition @param tempDiscriminator the temporary discriminator """ assert !transition.isTree(); notifyPreSplit(transition, tempDiscriminator); AbstractBaseDTNode<I, D> dtNode = transition.getNonTreeTarget(); assert dtNode.isLeaf(); TTTState<I, D> oldState = dtNode.getData(); assert oldState != null; TTTState<I, D> newState = makeTree(transition); AbstractBaseDTNode<I, D>.SplitResult children = split(dtNode, tempDiscriminator, oldOut, newOut); dtNode.setTemp(true); link(children.nodeOld, oldState); link(children.nodeNew, newState); if (dtNode.getParent() == null || !dtNode.getParent().isTemp()) { blockList.insertBlock(dtNode); } notifyPostSplit(transition, tempDiscriminator); }
java
private void splitState(TTTTransition<I, D> transition, Word<I> tempDiscriminator, D oldOut, D newOut) { assert !transition.isTree(); notifyPreSplit(transition, tempDiscriminator); AbstractBaseDTNode<I, D> dtNode = transition.getNonTreeTarget(); assert dtNode.isLeaf(); TTTState<I, D> oldState = dtNode.getData(); assert oldState != null; TTTState<I, D> newState = makeTree(transition); AbstractBaseDTNode<I, D>.SplitResult children = split(dtNode, tempDiscriminator, oldOut, newOut); dtNode.setTemp(true); link(children.nodeOld, oldState); link(children.nodeNew, newState); if (dtNode.getParent() == null || !dtNode.getParent().isTemp()) { blockList.insertBlock(dtNode); } notifyPostSplit(transition, tempDiscriminator); }
[ "private", "void", "splitState", "(", "TTTTransition", "<", "I", ",", "D", ">", "transition", ",", "Word", "<", "I", ">", "tempDiscriminator", ",", "D", "oldOut", ",", "D", "newOut", ")", "{", "assert", "!", "transition", ".", "isTree", "(", ")", ";", "notifyPreSplit", "(", "transition", ",", "tempDiscriminator", ")", ";", "AbstractBaseDTNode", "<", "I", ",", "D", ">", "dtNode", "=", "transition", ".", "getNonTreeTarget", "(", ")", ";", "assert", "dtNode", ".", "isLeaf", "(", ")", ";", "TTTState", "<", "I", ",", "D", ">", "oldState", "=", "dtNode", ".", "getData", "(", ")", ";", "assert", "oldState", "!=", "null", ";", "TTTState", "<", "I", ",", "D", ">", "newState", "=", "makeTree", "(", "transition", ")", ";", "AbstractBaseDTNode", "<", "I", ",", "D", ">", ".", "SplitResult", "children", "=", "split", "(", "dtNode", ",", "tempDiscriminator", ",", "oldOut", ",", "newOut", ")", ";", "dtNode", ".", "setTemp", "(", "true", ")", ";", "link", "(", "children", ".", "nodeOld", ",", "oldState", ")", ";", "link", "(", "children", ".", "nodeNew", ",", "newState", ")", ";", "if", "(", "dtNode", ".", "getParent", "(", ")", "==", "null", "||", "!", "dtNode", ".", "getParent", "(", ")", ".", "isTemp", "(", ")", ")", "{", "blockList", ".", "insertBlock", "(", "dtNode", ")", ";", "}", "notifyPostSplit", "(", "transition", ",", "tempDiscriminator", ")", ";", "}" ]
Splits a state in the hypothesis, using a temporary discriminator. The state to be split is identified by an incoming non-tree transition. This transition is subsequently turned into a spanning tree transition. @param transition the transition @param tempDiscriminator the temporary discriminator
[ "Splits", "a", "state", "in", "the", "hypothesis", "using", "a", "temporary", "discriminator", ".", "The", "state", "to", "be", "split", "is", "identified", "by", "an", "incoming", "non", "-", "tree", "transition", ".", "This", "transition", "is", "subsequently", "turned", "into", "a", "spanning", "tree", "transition", "." ]
train
https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java#L234-L257
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.isSame
public static <T extends Tree> Matcher<T> isSame(final Tree t) { """ Matches an AST node which is the same object reference as the given node. """ return new Matcher<T>() { @Override public boolean matches(T tree, VisitorState state) { return tree == t; } }; }
java
public static <T extends Tree> Matcher<T> isSame(final Tree t) { return new Matcher<T>() { @Override public boolean matches(T tree, VisitorState state) { return tree == t; } }; }
[ "public", "static", "<", "T", "extends", "Tree", ">", "Matcher", "<", "T", ">", "isSame", "(", "final", "Tree", "t", ")", "{", "return", "new", "Matcher", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "T", "tree", ",", "VisitorState", "state", ")", "{", "return", "tree", "==", "t", ";", "}", "}", ";", "}" ]
Matches an AST node which is the same object reference as the given node.
[ "Matches", "an", "AST", "node", "which", "is", "the", "same", "object", "reference", "as", "the", "given", "node", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L191-L198
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java
DatatypeConverter.getLong
public static final long getLong(byte[] data, int offset) { """ Read a long int from a byte array. @param data byte array @param offset start offset @return long value """ long result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 64; shiftBy += 8) { result |= ((long) (data[i] & 0xff)) << shiftBy; ++i; } return result; }
java
public static final long getLong(byte[] data, int offset) { long result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 64; shiftBy += 8) { result |= ((long) (data[i] & 0xff)) << shiftBy; ++i; } return result; }
[ "public", "static", "final", "long", "getLong", "(", "byte", "[", "]", "data", ",", "int", "offset", ")", "{", "long", "result", "=", "0", ";", "int", "i", "=", "offset", ";", "for", "(", "int", "shiftBy", "=", "0", ";", "shiftBy", "<", "64", ";", "shiftBy", "+=", "8", ")", "{", "result", "|=", "(", "(", "long", ")", "(", "data", "[", "i", "]", "&", "0xff", ")", ")", "<<", "shiftBy", ";", "++", "i", ";", "}", "return", "result", ";", "}" ]
Read a long int from a byte array. @param data byte array @param offset start offset @return long value
[ "Read", "a", "long", "int", "from", "a", "byte", "array", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java#L114-L124
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_calls_id_eavesdrop_POST
public OvhTask billingAccount_line_serviceName_calls_id_eavesdrop_POST(String billingAccount, String serviceName, Long id, String number) throws IOException { """ Eavesdrop on a call REST: POST /telephony/{billingAccount}/line/{serviceName}/calls/{id}/eavesdrop @param number [required] Phone number that will be called and bridged in the communication @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param id [required] Id of the object """ String qPath = "/telephony/{billingAccount}/line/{serviceName}/calls/{id}/eavesdrop"; StringBuilder sb = path(qPath, billingAccount, serviceName, id); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "number", number); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask billingAccount_line_serviceName_calls_id_eavesdrop_POST(String billingAccount, String serviceName, Long id, String number) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/calls/{id}/eavesdrop"; StringBuilder sb = path(qPath, billingAccount, serviceName, id); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "number", number); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "billingAccount_line_serviceName_calls_id_eavesdrop_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "Long", "id", ",", "String", "number", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/line/{serviceName}/calls/{id}/eavesdrop\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ",", "id", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"number\"", ",", "number", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Eavesdrop on a call REST: POST /telephony/{billingAccount}/line/{serviceName}/calls/{id}/eavesdrop @param number [required] Phone number that will be called and bridged in the communication @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param id [required] Id of the object
[ "Eavesdrop", "on", "a", "call" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L1932-L1939
carewebframework/carewebframework-vista
org.carewebframework.vista.api-parent/org.carewebframework.vista.api.core/src/main/java/org/carewebframework/vista/api/property/PropertyCollection.java
PropertyCollection.getValue
public int getValue(String name, int dflt) { """ Returns an integer property value. @param name Property name. @param dflt Default value if a property value is not found. @return Property value or default value if property value not found. """ try { return Integer.parseInt(getValue(name, Integer.toString(dflt))); } catch (Exception e) { return dflt; } }
java
public int getValue(String name, int dflt) { try { return Integer.parseInt(getValue(name, Integer.toString(dflt))); } catch (Exception e) { return dflt; } }
[ "public", "int", "getValue", "(", "String", "name", ",", "int", "dflt", ")", "{", "try", "{", "return", "Integer", ".", "parseInt", "(", "getValue", "(", "name", ",", "Integer", ".", "toString", "(", "dflt", ")", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "dflt", ";", "}", "}" ]
Returns an integer property value. @param name Property name. @param dflt Default value if a property value is not found. @return Property value or default value if property value not found.
[ "Returns", "an", "integer", "property", "value", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.api-parent/org.carewebframework.vista.api.core/src/main/java/org/carewebframework/vista/api/property/PropertyCollection.java#L162-L168
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/rule/EqualsRule.java
EqualsRule.getRule
public static Rule getRule(final String p1, final String p2) { """ Create new instance. @param p1 field, special treatment for level and timestamp. @param p2 value @return new instance """ if (p1.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) { return LevelEqualsRule.getRule(p2); } else if (p1.equalsIgnoreCase(LoggingEventFieldResolver.TIMESTAMP_FIELD)) { return TimestampEqualsRule.getRule(p2); } else { return new EqualsRule(p1, p2); } }
java
public static Rule getRule(final String p1, final String p2) { if (p1.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) { return LevelEqualsRule.getRule(p2); } else if (p1.equalsIgnoreCase(LoggingEventFieldResolver.TIMESTAMP_FIELD)) { return TimestampEqualsRule.getRule(p2); } else { return new EqualsRule(p1, p2); } }
[ "public", "static", "Rule", "getRule", "(", "final", "String", "p1", ",", "final", "String", "p2", ")", "{", "if", "(", "p1", ".", "equalsIgnoreCase", "(", "LoggingEventFieldResolver", ".", "LEVEL_FIELD", ")", ")", "{", "return", "LevelEqualsRule", ".", "getRule", "(", "p2", ")", ";", "}", "else", "if", "(", "p1", ".", "equalsIgnoreCase", "(", "LoggingEventFieldResolver", ".", "TIMESTAMP_FIELD", ")", ")", "{", "return", "TimestampEqualsRule", ".", "getRule", "(", "p2", ")", ";", "}", "else", "{", "return", "new", "EqualsRule", "(", "p1", ",", "p2", ")", ";", "}", "}" ]
Create new instance. @param p1 field, special treatment for level and timestamp. @param p2 value @return new instance
[ "Create", "new", "instance", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/rule/EqualsRule.java#L94-L102
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/operators/AbstractUdfOperator.java
AbstractUdfOperator.setBroadcastVariable
public void setBroadcastVariable(String name, Operator<?> root) { """ Binds the result produced by a plan rooted at {@code root} to a variable used by the UDF wrapped in this operator. @param root The root of the plan producing this input. """ if (name == null) { throw new IllegalArgumentException("The broadcast input name may not be null."); } if (root == null) { throw new IllegalArgumentException("The broadcast input root operator may not be null."); } this.broadcastInputs.put(name, root); }
java
public void setBroadcastVariable(String name, Operator<?> root) { if (name == null) { throw new IllegalArgumentException("The broadcast input name may not be null."); } if (root == null) { throw new IllegalArgumentException("The broadcast input root operator may not be null."); } this.broadcastInputs.put(name, root); }
[ "public", "void", "setBroadcastVariable", "(", "String", "name", ",", "Operator", "<", "?", ">", "root", ")", "{", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The broadcast input name may not be null.\"", ")", ";", "}", "if", "(", "root", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The broadcast input root operator may not be null.\"", ")", ";", "}", "this", ".", "broadcastInputs", ".", "put", "(", "name", ",", "root", ")", ";", "}" ]
Binds the result produced by a plan rooted at {@code root} to a variable used by the UDF wrapped in this operator. @param root The root of the plan producing this input.
[ "Binds", "the", "result", "produced", "by", "a", "plan", "rooted", "at", "{", "@code", "root", "}", "to", "a", "variable", "used", "by", "the", "UDF", "wrapped", "in", "this", "operator", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/operators/AbstractUdfOperator.java#L95-L104
database-rider/database-rider
rider-core/src/main/java/com/github/database/rider/core/util/AnnotationUtils.java
AnnotationUtils.isAnnotated
public static boolean isAnnotated(AnnotatedElement element, Class<? extends Annotation> annotationType) { """ @param element @param annotationType Determine if an annotation of {@code annotationType} is either <em>present</em> or <em>meta-present</em> on the supplied {@code element}. @return true element is annotated """ return findAnnotation(element, annotationType) != null; }
java
public static boolean isAnnotated(AnnotatedElement element, Class<? extends Annotation> annotationType) { return findAnnotation(element, annotationType) != null; }
[ "public", "static", "boolean", "isAnnotated", "(", "AnnotatedElement", "element", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationType", ")", "{", "return", "findAnnotation", "(", "element", ",", "annotationType", ")", "!=", "null", ";", "}" ]
@param element @param annotationType Determine if an annotation of {@code annotationType} is either <em>present</em> or <em>meta-present</em> on the supplied {@code element}. @return true element is annotated
[ "@param", "element", "@param", "annotationType" ]
train
https://github.com/database-rider/database-rider/blob/7545cc31118df9cfef3f89e27223b433a24fb5dd/rider-core/src/main/java/com/github/database/rider/core/util/AnnotationUtils.java#L41-L43
andrehertwig/admintool
admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java
AdminToolDBBrowserServiceImpl.getClobString
protected String getClobString(Clob clobObject, String encoding) throws IOException, SQLException, UnsupportedEncodingException { """ turns clob into a string @param clobObject @param encoding @return @throws IOException @throws SQLException @throws UnsupportedEncodingException """ if (null == clobObject) { return ""; } InputStream in = clobObject.getAsciiStream(); Reader read = new InputStreamReader(in, encoding); StringWriter write = new StringWriter(); String result = null; try { int c = -1; while ((c = read.read()) != -1) { write.write(c); } write.flush(); result = write.toString(); } finally { closeStream(write); closeStream(read); //should we close the ascii stream from database? or is it handled by connection // closeStream(in); } return result; }
java
protected String getClobString(Clob clobObject, String encoding) throws IOException, SQLException, UnsupportedEncodingException { if (null == clobObject) { return ""; } InputStream in = clobObject.getAsciiStream(); Reader read = new InputStreamReader(in, encoding); StringWriter write = new StringWriter(); String result = null; try { int c = -1; while ((c = read.read()) != -1) { write.write(c); } write.flush(); result = write.toString(); } finally { closeStream(write); closeStream(read); //should we close the ascii stream from database? or is it handled by connection // closeStream(in); } return result; }
[ "protected", "String", "getClobString", "(", "Clob", "clobObject", ",", "String", "encoding", ")", "throws", "IOException", ",", "SQLException", ",", "UnsupportedEncodingException", "{", "if", "(", "null", "==", "clobObject", ")", "{", "return", "\"\"", ";", "}", "InputStream", "in", "=", "clobObject", ".", "getAsciiStream", "(", ")", ";", "Reader", "read", "=", "new", "InputStreamReader", "(", "in", ",", "encoding", ")", ";", "StringWriter", "write", "=", "new", "StringWriter", "(", ")", ";", "String", "result", "=", "null", ";", "try", "{", "int", "c", "=", "-", "1", ";", "while", "(", "(", "c", "=", "read", ".", "read", "(", ")", ")", "!=", "-", "1", ")", "{", "write", ".", "write", "(", "c", ")", ";", "}", "write", ".", "flush", "(", ")", ";", "result", "=", "write", ".", "toString", "(", ")", ";", "}", "finally", "{", "closeStream", "(", "write", ")", ";", "closeStream", "(", "read", ")", ";", "//should we close the ascii stream from database? or is it handled by connection\r", "// closeStream(in);\r", "}", "return", "result", ";", "}" ]
turns clob into a string @param clobObject @param encoding @return @throws IOException @throws SQLException @throws UnsupportedEncodingException
[ "turns", "clob", "into", "a", "string" ]
train
https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-dbbrowser/src/main/java/de/chandre/admintool/db/AdminToolDBBrowserServiceImpl.java#L391-L414
zamrokk/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/helper/SDKUtil.java
SDKUtil.generateTarGz
public static void generateTarGz(String src, String target) throws IOException { """ Compress the given directory src to target tar.gz file @param src The source directory @param target The target tar.gz file @throws IOException """ File sourceDirectory = new File(src); File destinationArchive = new File(target); String sourcePath = sourceDirectory.getAbsolutePath(); FileOutputStream destinationOutputStream = new FileOutputStream(destinationArchive); TarArchiveOutputStream archiveOutputStream = new TarArchiveOutputStream(new GzipCompressorOutputStream(new BufferedOutputStream(destinationOutputStream))); archiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); try { Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, true); childrenFiles.remove(destinationArchive); ArchiveEntry archiveEntry; FileInputStream fileInputStream; for (File childFile : childrenFiles) { String childPath = childFile.getAbsolutePath(); String relativePath = childPath.substring((sourcePath.length() + 1), childPath.length()); relativePath = FilenameUtils.separatorsToUnix(relativePath); archiveEntry = new TarArchiveEntry(childFile, relativePath); fileInputStream = new FileInputStream(childFile); archiveOutputStream.putArchiveEntry(archiveEntry); try { IOUtils.copy(fileInputStream, archiveOutputStream); } finally { IOUtils.closeQuietly(fileInputStream); archiveOutputStream.closeArchiveEntry(); } } } finally { IOUtils.closeQuietly(archiveOutputStream); } }
java
public static void generateTarGz(String src, String target) throws IOException { File sourceDirectory = new File(src); File destinationArchive = new File(target); String sourcePath = sourceDirectory.getAbsolutePath(); FileOutputStream destinationOutputStream = new FileOutputStream(destinationArchive); TarArchiveOutputStream archiveOutputStream = new TarArchiveOutputStream(new GzipCompressorOutputStream(new BufferedOutputStream(destinationOutputStream))); archiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); try { Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, true); childrenFiles.remove(destinationArchive); ArchiveEntry archiveEntry; FileInputStream fileInputStream; for (File childFile : childrenFiles) { String childPath = childFile.getAbsolutePath(); String relativePath = childPath.substring((sourcePath.length() + 1), childPath.length()); relativePath = FilenameUtils.separatorsToUnix(relativePath); archiveEntry = new TarArchiveEntry(childFile, relativePath); fileInputStream = new FileInputStream(childFile); archiveOutputStream.putArchiveEntry(archiveEntry); try { IOUtils.copy(fileInputStream, archiveOutputStream); } finally { IOUtils.closeQuietly(fileInputStream); archiveOutputStream.closeArchiveEntry(); } } } finally { IOUtils.closeQuietly(archiveOutputStream); } }
[ "public", "static", "void", "generateTarGz", "(", "String", "src", ",", "String", "target", ")", "throws", "IOException", "{", "File", "sourceDirectory", "=", "new", "File", "(", "src", ")", ";", "File", "destinationArchive", "=", "new", "File", "(", "target", ")", ";", "String", "sourcePath", "=", "sourceDirectory", ".", "getAbsolutePath", "(", ")", ";", "FileOutputStream", "destinationOutputStream", "=", "new", "FileOutputStream", "(", "destinationArchive", ")", ";", "TarArchiveOutputStream", "archiveOutputStream", "=", "new", "TarArchiveOutputStream", "(", "new", "GzipCompressorOutputStream", "(", "new", "BufferedOutputStream", "(", "destinationOutputStream", ")", ")", ")", ";", "archiveOutputStream", ".", "setLongFileMode", "(", "TarArchiveOutputStream", ".", "LONGFILE_GNU", ")", ";", "try", "{", "Collection", "<", "File", ">", "childrenFiles", "=", "org", ".", "apache", ".", "commons", ".", "io", ".", "FileUtils", ".", "listFiles", "(", "sourceDirectory", ",", "null", ",", "true", ")", ";", "childrenFiles", ".", "remove", "(", "destinationArchive", ")", ";", "ArchiveEntry", "archiveEntry", ";", "FileInputStream", "fileInputStream", ";", "for", "(", "File", "childFile", ":", "childrenFiles", ")", "{", "String", "childPath", "=", "childFile", ".", "getAbsolutePath", "(", ")", ";", "String", "relativePath", "=", "childPath", ".", "substring", "(", "(", "sourcePath", ".", "length", "(", ")", "+", "1", ")", ",", "childPath", ".", "length", "(", ")", ")", ";", "relativePath", "=", "FilenameUtils", ".", "separatorsToUnix", "(", "relativePath", ")", ";", "archiveEntry", "=", "new", "TarArchiveEntry", "(", "childFile", ",", "relativePath", ")", ";", "fileInputStream", "=", "new", "FileInputStream", "(", "childFile", ")", ";", "archiveOutputStream", ".", "putArchiveEntry", "(", "archiveEntry", ")", ";", "try", "{", "IOUtils", ".", "copy", "(", "fileInputStream", ",", "archiveOutputStream", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "fileInputStream", ")", ";", "archiveOutputStream", ".", "closeArchiveEntry", "(", ")", ";", "}", "}", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "archiveOutputStream", ")", ";", "}", "}" ]
Compress the given directory src to target tar.gz file @param src The source directory @param target The target tar.gz file @throws IOException
[ "Compress", "the", "given", "directory", "src", "to", "target", "tar", ".", "gz", "file" ]
train
https://github.com/zamrokk/fabric-sdk-java/blob/d4993ca602f72d412cd682e1b92e805e48b27afa/src/main/java/org/hyperledger/fabric/sdk/helper/SDKUtil.java#L124-L159
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.getShortName
public static String getShortName(final ZoneId self, Locale locale) { """ Returns the name of this zone formatted according to the {@link java.time.format.TextStyle#SHORT} text style for the provided {@link java.util.Locale}. @param self a ZoneId @param locale a Locale @return the short display name of the ZoneId @since 2.5.0 """ return self.getDisplayName(TextStyle.SHORT, locale); }
java
public static String getShortName(final ZoneId self, Locale locale) { return self.getDisplayName(TextStyle.SHORT, locale); }
[ "public", "static", "String", "getShortName", "(", "final", "ZoneId", "self", ",", "Locale", "locale", ")", "{", "return", "self", ".", "getDisplayName", "(", "TextStyle", ".", "SHORT", ",", "locale", ")", ";", "}" ]
Returns the name of this zone formatted according to the {@link java.time.format.TextStyle#SHORT} text style for the provided {@link java.util.Locale}. @param self a ZoneId @param locale a Locale @return the short display name of the ZoneId @since 2.5.0
[ "Returns", "the", "name", "of", "this", "zone", "formatted", "according", "to", "the", "{", "@link", "java", ".", "time", ".", "format", ".", "TextStyle#SHORT", "}", "text", "style", "for", "the", "provided", "{", "@link", "java", ".", "util", ".", "Locale", "}", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L1822-L1824
RogerParkinson/madura-objects-parent
madura-objects/src/main/java/nz/co/senanque/validationengine/ValidationSession.java
ValidationSession.addListener
public void addListener(ValidationObject object, String name, SetterListener listener) { """ Add a setter listener to a field. @param object @param name @param listener """ m_validationEngine.addListener(object, name, this, listener); }
java
public void addListener(ValidationObject object, String name, SetterListener listener) { m_validationEngine.addListener(object, name, this, listener); }
[ "public", "void", "addListener", "(", "ValidationObject", "object", ",", "String", "name", ",", "SetterListener", "listener", ")", "{", "m_validationEngine", ".", "addListener", "(", "object", ",", "name", ",", "this", ",", "listener", ")", ";", "}" ]
Add a setter listener to a field. @param object @param name @param listener
[ "Add", "a", "setter", "listener", "to", "a", "field", "." ]
train
https://github.com/RogerParkinson/madura-objects-parent/blob/9b5385dd0437611f0ce8506f63646e018d06fb8e/madura-objects/src/main/java/nz/co/senanque/validationengine/ValidationSession.java#L115-L117
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.transformEntry
public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) { """ Copies an existing ZIP file and transforms a given entry in it. @param is a ZIP input stream. @param entry transformer for a ZIP entry. @param os a ZIP output stream. @return <code>true</code> if the entry was replaced. """ return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os); }
java
public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) { return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os); }
[ "public", "static", "boolean", "transformEntry", "(", "InputStream", "is", ",", "ZipEntryTransformerEntry", "entry", ",", "OutputStream", "os", ")", "{", "return", "transformEntries", "(", "is", ",", "new", "ZipEntryTransformerEntry", "[", "]", "{", "entry", "}", ",", "os", ")", ";", "}" ]
Copies an existing ZIP file and transforms a given entry in it. @param is a ZIP input stream. @param entry transformer for a ZIP entry. @param os a ZIP output stream. @return <code>true</code> if the entry was replaced.
[ "Copies", "an", "existing", "ZIP", "file", "and", "transforms", "a", "given", "entry", "in", "it", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2910-L2912
rwl/CSparseJ
src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_scatter.java
DZcs_scatter.cs_scatter
public static int cs_scatter(DZcs A, int j, double[] beta, int[] w, DZcsa x, int mark, DZcs C, int nz) { """ Scatters and sums a sparse vector A(:,j) into a dense vector, x = x + beta * A(:,j). @param A the sparse vector is A(:,j) @param j the column of A to use @param beta scalar multiplied by A(:,j) @param w size m, node i is marked if w[i] = mark @param x size m, ignored if null @param mark mark value of w @param C pattern of x accumulated in C.i @param nz pattern of x placed in C starting at C.i[nz] @return new value of nz, -1 on error """ int i, p, Ap[], Ai[], Ci[] ; DZcsa Ax = new DZcsa() ; if (!CS_CSC(A) || (w == null) || !CS_CSC(C)) return (-1) ; /* check inputs */ Ap = A.p ; Ai = A.i ; Ax.x = A.x ; Ci = C.i ; for (p = Ap [j]; p < Ap [j+1] ; p++) { i = Ai [p] ; /* A(i,j) is nonzero */ if (w [i] < mark) { w [i] = mark ; /* i is new entry in column j */ Ci [nz++] = i ; /* add i to pattern of C(:,j) */ if (x != null) x.set(i, cs_cmult(beta, Ax.get(p))) ; /* x(i) = beta*A(i,j) */ } else if (x != null) { x.set(i, cs_cplus(x.get(i), cs_cmult(beta, Ax.get(p)))); /* i exists in C(:,j) already */ } } return (nz) ; }
java
public static int cs_scatter(DZcs A, int j, double[] beta, int[] w, DZcsa x, int mark, DZcs C, int nz) { int i, p, Ap[], Ai[], Ci[] ; DZcsa Ax = new DZcsa() ; if (!CS_CSC(A) || (w == null) || !CS_CSC(C)) return (-1) ; /* check inputs */ Ap = A.p ; Ai = A.i ; Ax.x = A.x ; Ci = C.i ; for (p = Ap [j]; p < Ap [j+1] ; p++) { i = Ai [p] ; /* A(i,j) is nonzero */ if (w [i] < mark) { w [i] = mark ; /* i is new entry in column j */ Ci [nz++] = i ; /* add i to pattern of C(:,j) */ if (x != null) x.set(i, cs_cmult(beta, Ax.get(p))) ; /* x(i) = beta*A(i,j) */ } else if (x != null) { x.set(i, cs_cplus(x.get(i), cs_cmult(beta, Ax.get(p)))); /* i exists in C(:,j) already */ } } return (nz) ; }
[ "public", "static", "int", "cs_scatter", "(", "DZcs", "A", ",", "int", "j", ",", "double", "[", "]", "beta", ",", "int", "[", "]", "w", ",", "DZcsa", "x", ",", "int", "mark", ",", "DZcs", "C", ",", "int", "nz", ")", "{", "int", "i", ",", "p", ",", "Ap", "[", "]", ",", "Ai", "[", "]", ",", "Ci", "[", "]", ";", "DZcsa", "Ax", "=", "new", "DZcsa", "(", ")", ";", "if", "(", "!", "CS_CSC", "(", "A", ")", "||", "(", "w", "==", "null", ")", "||", "!", "CS_CSC", "(", "C", ")", ")", "return", "(", "-", "1", ")", ";", "/* check inputs */", "Ap", "=", "A", ".", "p", ";", "Ai", "=", "A", ".", "i", ";", "Ax", ".", "x", "=", "A", ".", "x", ";", "Ci", "=", "C", ".", "i", ";", "for", "(", "p", "=", "Ap", "[", "j", "]", ";", "p", "<", "Ap", "[", "j", "+", "1", "]", ";", "p", "++", ")", "{", "i", "=", "Ai", "[", "p", "]", ";", "/* A(i,j) is nonzero */", "if", "(", "w", "[", "i", "]", "<", "mark", ")", "{", "w", "[", "i", "]", "=", "mark", ";", "/* i is new entry in column j */", "Ci", "[", "nz", "++", "]", "=", "i", ";", "/* add i to pattern of C(:,j) */", "if", "(", "x", "!=", "null", ")", "x", ".", "set", "(", "i", ",", "cs_cmult", "(", "beta", ",", "Ax", ".", "get", "(", "p", ")", ")", ")", ";", "/* x(i) = beta*A(i,j) */", "}", "else", "if", "(", "x", "!=", "null", ")", "{", "x", ".", "set", "(", "i", ",", "cs_cplus", "(", "x", ".", "get", "(", "i", ")", ",", "cs_cmult", "(", "beta", ",", "Ax", ".", "get", "(", "p", ")", ")", ")", ")", ";", "/* i exists in C(:,j) already */", "}", "}", "return", "(", "nz", ")", ";", "}" ]
Scatters and sums a sparse vector A(:,j) into a dense vector, x = x + beta * A(:,j). @param A the sparse vector is A(:,j) @param j the column of A to use @param beta scalar multiplied by A(:,j) @param w size m, node i is marked if w[i] = mark @param x size m, ignored if null @param mark mark value of w @param C pattern of x accumulated in C.i @param nz pattern of x placed in C starting at C.i[nz] @return new value of nz, -1 on error
[ "Scatters", "and", "sums", "a", "sparse", "vector", "A", "(", ":", "j", ")", "into", "a", "dense", "vector", "x", "=", "x", "+", "beta", "*", "A", "(", ":", "j", ")", "." ]
train
https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_scatter.java#L65-L87
alkacon/opencms-core
src/org/opencms/main/OpenCmsCore.java
OpenCmsCore.updateContext
protected CmsObject updateContext(HttpServletRequest request, CmsObject cms) throws CmsException { """ This method updates the request context information.<p> The update information is:<br> <ul> <li>Requested Url</li> <li>Locale</li> <li>Encoding</li> <li>Remote Address</li> <li>Request Time</li> </ul> @param request the current request @param cms the cms object to update the request context for @return a new updated cms context @throws CmsException if something goes wrong """ // get the right site for the request String siteRoot = null; boolean isWorkplace = cms.getRequestContext().getUri().startsWith("/system/workplace/") || request.getRequestURI().startsWith(OpenCms.getSystemInfo().getWorkplaceContext()); if (isWorkplace && getRoleManager().hasRole(cms, CmsRole.ELEMENT_AUTHOR)) { // keep the site root for workplace requests siteRoot = cms.getRequestContext().getSiteRoot(); } else { CmsSite site = OpenCms.getSiteManager().matchRequest(request); siteRoot = site.getSiteRoot(); } return initCmsObject( request, cms.getRequestContext().getCurrentUser(), siteRoot, cms.getRequestContext().getCurrentProject().getUuid(), cms.getRequestContext().getOuFqn()); }
java
protected CmsObject updateContext(HttpServletRequest request, CmsObject cms) throws CmsException { // get the right site for the request String siteRoot = null; boolean isWorkplace = cms.getRequestContext().getUri().startsWith("/system/workplace/") || request.getRequestURI().startsWith(OpenCms.getSystemInfo().getWorkplaceContext()); if (isWorkplace && getRoleManager().hasRole(cms, CmsRole.ELEMENT_AUTHOR)) { // keep the site root for workplace requests siteRoot = cms.getRequestContext().getSiteRoot(); } else { CmsSite site = OpenCms.getSiteManager().matchRequest(request); siteRoot = site.getSiteRoot(); } return initCmsObject( request, cms.getRequestContext().getCurrentUser(), siteRoot, cms.getRequestContext().getCurrentProject().getUuid(), cms.getRequestContext().getOuFqn()); }
[ "protected", "CmsObject", "updateContext", "(", "HttpServletRequest", "request", ",", "CmsObject", "cms", ")", "throws", "CmsException", "{", "// get the right site for the request", "String", "siteRoot", "=", "null", ";", "boolean", "isWorkplace", "=", "cms", ".", "getRequestContext", "(", ")", ".", "getUri", "(", ")", ".", "startsWith", "(", "\"/system/workplace/\"", ")", "||", "request", ".", "getRequestURI", "(", ")", ".", "startsWith", "(", "OpenCms", ".", "getSystemInfo", "(", ")", ".", "getWorkplaceContext", "(", ")", ")", ";", "if", "(", "isWorkplace", "&&", "getRoleManager", "(", ")", ".", "hasRole", "(", "cms", ",", "CmsRole", ".", "ELEMENT_AUTHOR", ")", ")", "{", "// keep the site root for workplace requests", "siteRoot", "=", "cms", ".", "getRequestContext", "(", ")", ".", "getSiteRoot", "(", ")", ";", "}", "else", "{", "CmsSite", "site", "=", "OpenCms", ".", "getSiteManager", "(", ")", ".", "matchRequest", "(", "request", ")", ";", "siteRoot", "=", "site", ".", "getSiteRoot", "(", ")", ";", "}", "return", "initCmsObject", "(", "request", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ",", "siteRoot", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentProject", "(", ")", ".", "getUuid", "(", ")", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getOuFqn", "(", ")", ")", ";", "}" ]
This method updates the request context information.<p> The update information is:<br> <ul> <li>Requested Url</li> <li>Locale</li> <li>Encoding</li> <li>Remote Address</li> <li>Request Time</li> </ul> @param request the current request @param cms the cms object to update the request context for @return a new updated cms context @throws CmsException if something goes wrong
[ "This", "method", "updates", "the", "request", "context", "information", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/OpenCmsCore.java#L2253-L2272
OpenLiberty/open-liberty
dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceService.java
BaseTraceService.writeStreamOutput
protected synchronized void writeStreamOutput(SystemLogHolder holder, String txt, boolean rawStream) { """ Write the text to the associated original stream. This is preserved as a subroutine for extension by other delegates (test, JSR47 logging) @param tc StreamTraceComponent associated with original stream @param txt pre-formatted or raw message @param rawStream if true, this is from direct invocation of System.out or System.err """ if (holder == systemErr && rawStream) { txt = "[err] " + txt; } holder.originalStream.println(txt); }
java
protected synchronized void writeStreamOutput(SystemLogHolder holder, String txt, boolean rawStream) { if (holder == systemErr && rawStream) { txt = "[err] " + txt; } holder.originalStream.println(txt); }
[ "protected", "synchronized", "void", "writeStreamOutput", "(", "SystemLogHolder", "holder", ",", "String", "txt", ",", "boolean", "rawStream", ")", "{", "if", "(", "holder", "==", "systemErr", "&&", "rawStream", ")", "{", "txt", "=", "\"[err] \"", "+", "txt", ";", "}", "holder", ".", "originalStream", ".", "println", "(", "txt", ")", ";", "}" ]
Write the text to the associated original stream. This is preserved as a subroutine for extension by other delegates (test, JSR47 logging) @param tc StreamTraceComponent associated with original stream @param txt pre-formatted or raw message @param rawStream if true, this is from direct invocation of System.out or System.err
[ "Write", "the", "text", "to", "the", "associated", "original", "stream", ".", "This", "is", "preserved", "as", "a", "subroutine", "for", "extension", "by", "other", "delegates", "(", "test", "JSR47", "logging", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceService.java#L1283-L1288
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/ImageInfo.java
ImageInfo.newBuilder
public static Builder newBuilder(ImageId imageId, ImageConfiguration configuration) { """ Returns a builder for an {@code ImageInfo} object given the image identity and an image configuration. Use {@link DiskImageConfiguration} to create an image from an existing disk. Use {@link StorageImageConfiguration} to create an image from a file stored in Google Cloud Storage. """ return new BuilderImpl().setImageId(imageId).setConfiguration(configuration); }
java
public static Builder newBuilder(ImageId imageId, ImageConfiguration configuration) { return new BuilderImpl().setImageId(imageId).setConfiguration(configuration); }
[ "public", "static", "Builder", "newBuilder", "(", "ImageId", "imageId", ",", "ImageConfiguration", "configuration", ")", "{", "return", "new", "BuilderImpl", "(", ")", ".", "setImageId", "(", "imageId", ")", ".", "setConfiguration", "(", "configuration", ")", ";", "}" ]
Returns a builder for an {@code ImageInfo} object given the image identity and an image configuration. Use {@link DiskImageConfiguration} to create an image from an existing disk. Use {@link StorageImageConfiguration} to create an image from a file stored in Google Cloud Storage.
[ "Returns", "a", "builder", "for", "an", "{" ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/ImageInfo.java#L381-L383
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.checkTouchSlop
public boolean checkTouchSlop(int directions, int pointerId) { """ Check if the specified pointer tracked in the current gesture has crossed the required slop threshold. <p>This depends on internal state populated by {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on the results of this method after all currently available touch data has been provided to one of these two methods.</p> @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} @param pointerId ID of the pointer to slop check as specified by MotionEvent @return true if the slop threshold has been crossed, false otherwise """ if (!isPointerDown(pointerId)) { return false; } final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > mTouchSlop; } return false; }
java
public boolean checkTouchSlop(int directions, int pointerId) { if (!isPointerDown(pointerId)) { return false; } final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop; } else if (checkHorizontal) { return Math.abs(dx) > mTouchSlop; } else if (checkVertical) { return Math.abs(dy) > mTouchSlop; } return false; }
[ "public", "boolean", "checkTouchSlop", "(", "int", "directions", ",", "int", "pointerId", ")", "{", "if", "(", "!", "isPointerDown", "(", "pointerId", ")", ")", "{", "return", "false", ";", "}", "final", "boolean", "checkHorizontal", "=", "(", "directions", "&", "DIRECTION_HORIZONTAL", ")", "==", "DIRECTION_HORIZONTAL", ";", "final", "boolean", "checkVertical", "=", "(", "directions", "&", "DIRECTION_VERTICAL", ")", "==", "DIRECTION_VERTICAL", ";", "final", "float", "dx", "=", "mLastMotionX", "[", "pointerId", "]", "-", "mInitialMotionX", "[", "pointerId", "]", ";", "final", "float", "dy", "=", "mLastMotionY", "[", "pointerId", "]", "-", "mInitialMotionY", "[", "pointerId", "]", ";", "if", "(", "checkHorizontal", "&&", "checkVertical", ")", "{", "return", "dx", "*", "dx", "+", "dy", "*", "dy", ">", "mTouchSlop", "*", "mTouchSlop", ";", "}", "else", "if", "(", "checkHorizontal", ")", "{", "return", "Math", ".", "abs", "(", "dx", ")", ">", "mTouchSlop", ";", "}", "else", "if", "(", "checkVertical", ")", "{", "return", "Math", ".", "abs", "(", "dy", ")", ">", "mTouchSlop", ";", "}", "return", "false", ";", "}" ]
Check if the specified pointer tracked in the current gesture has crossed the required slop threshold. <p>This depends on internal state populated by {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on the results of this method after all currently available touch data has been provided to one of these two methods.</p> @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} @param pointerId ID of the pointer to slop check as specified by MotionEvent @return true if the slop threshold has been crossed, false otherwise
[ "Check", "if", "the", "specified", "pointer", "tracked", "in", "the", "current", "gesture", "has", "crossed", "the", "required", "slop", "threshold", "." ]
train
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L1349-L1368