repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
Ordinastie/MalisisCore
src/main/java/net/malisis/core/asm/AsmUtils.java
AsmUtils.changeFieldAccess
public static Field changeFieldAccess(Class<?> clazz, String fieldName, String srgName, boolean silenced) { try { Field f = clazz.getDeclaredField(MalisisCore.isObfEnv ? srgName : fieldName); f.setAccessible(true); Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(f, f.getModifiers() & ~Modifier.FINAL); return f; } catch (ReflectiveOperationException e) { if (!silenced) MalisisCore.log.error("Could not change access for field " + clazz.getSimpleName() + "." + (MalisisCore.isObfEnv ? srgName : fieldName), e); return null; } }
java
public static Field changeFieldAccess(Class<?> clazz, String fieldName, String srgName, boolean silenced) { try { Field f = clazz.getDeclaredField(MalisisCore.isObfEnv ? srgName : fieldName); f.setAccessible(true); Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(f, f.getModifiers() & ~Modifier.FINAL); return f; } catch (ReflectiveOperationException e) { if (!silenced) MalisisCore.log.error("Could not change access for field " + clazz.getSimpleName() + "." + (MalisisCore.isObfEnv ? srgName : fieldName), e); return null; } }
[ "public", "static", "Field", "changeFieldAccess", "(", "Class", "<", "?", ">", "clazz", ",", "String", "fieldName", ",", "String", "srgName", ",", "boolean", "silenced", ")", "{", "try", "{", "Field", "f", "=", "clazz", ".", "getDeclaredField", "(", "MalisisCore", ".", "isObfEnv", "?", "srgName", ":", "fieldName", ")", ";", "f", ".", "setAccessible", "(", "true", ")", ";", "Field", "modifiers", "=", "Field", ".", "class", ".", "getDeclaredField", "(", "\"modifiers\"", ")", ";", "modifiers", ".", "setAccessible", "(", "true", ")", ";", "modifiers", ".", "setInt", "(", "f", ",", "f", ".", "getModifiers", "(", ")", "&", "~", "Modifier", ".", "FINAL", ")", ";", "return", "f", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "if", "(", "!", "silenced", ")", "MalisisCore", ".", "log", ".", "error", "(", "\"Could not change access for field \"", "+", "clazz", ".", "getSimpleName", "(", ")", "+", "\".\"", "+", "(", "MalisisCore", ".", "isObfEnv", "?", "srgName", ":", "fieldName", ")", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Changes the access level for the specified field for a class. @param clazz the clazz @param fieldName the field name @param srgName the srg name @param silenced the silenced @return the field
[ "Changes", "the", "access", "level", "for", "the", "specified", "field", "for", "a", "class", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/asm/AsmUtils.java#L339-L359
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/ServerSetup.java
ServerSetup.configureJavaMailSessionProperties
public Properties configureJavaMailSessionProperties(Properties properties, boolean debug) { Properties props = new Properties(); if (debug) { props.setProperty("mail.debug", "true"); // System.setProperty("mail.socket.debug", "true"); } // Set local host address (makes tests much faster. If this is not set java mail always looks for the address) props.setProperty(MAIL_DOT + getProtocol() + ".localaddress", String.valueOf(ServerSetup.getLocalHostAddress())); props.setProperty(MAIL_DOT + getProtocol() + ".port", String.valueOf(getPort())); props.setProperty(MAIL_DOT + getProtocol() + ".host", String.valueOf(getBindAddress())); if (isSecure()) { props.put(MAIL_DOT + getProtocol() + ".starttls.enable", Boolean.TRUE); props.setProperty(MAIL_DOT + getProtocol() + ".socketFactory.class", DummySSLSocketFactory.class.getName()); props.setProperty(MAIL_DOT + getProtocol() + ".socketFactory.fallback", "false"); } // Timeouts props.setProperty(MAIL_DOT + getProtocol() + ".connectiontimeout", Long.toString(getConnectionTimeout() < 0L ? ServerSetup.CONNECTION_TIMEOUT : getConnectionTimeout())); props.setProperty(MAIL_DOT + getProtocol() + ".timeout", Long.toString(getReadTimeout() < 0L ? ServerSetup.READ_TIMEOUT : getReadTimeout())); // Note: "mail." + setup.getProtocol() + ".writetimeout" breaks TLS/SSL Dummy Socket and makes tests run 6x slower!!! // Therefore we do not by default configure writetimeout. if (getWriteTimeout() >= 0L) { props.setProperty(MAIL_DOT + getProtocol() + ".writetimeout", Long.toString(getWriteTimeout())); } // Protocol specific extensions if (getProtocol().startsWith(PROTOCOL_SMTP)) { props.setProperty("mail.transport.protocol", getProtocol()); props.setProperty("mail.transport.protocol.rfc822", getProtocol()); } // Auto configure stores. props.setProperty("mail.store.protocol", getProtocol()); // Merge with optional additional properties if (null != properties && !properties.isEmpty()) { props.putAll(properties); } return props; }
java
public Properties configureJavaMailSessionProperties(Properties properties, boolean debug) { Properties props = new Properties(); if (debug) { props.setProperty("mail.debug", "true"); // System.setProperty("mail.socket.debug", "true"); } // Set local host address (makes tests much faster. If this is not set java mail always looks for the address) props.setProperty(MAIL_DOT + getProtocol() + ".localaddress", String.valueOf(ServerSetup.getLocalHostAddress())); props.setProperty(MAIL_DOT + getProtocol() + ".port", String.valueOf(getPort())); props.setProperty(MAIL_DOT + getProtocol() + ".host", String.valueOf(getBindAddress())); if (isSecure()) { props.put(MAIL_DOT + getProtocol() + ".starttls.enable", Boolean.TRUE); props.setProperty(MAIL_DOT + getProtocol() + ".socketFactory.class", DummySSLSocketFactory.class.getName()); props.setProperty(MAIL_DOT + getProtocol() + ".socketFactory.fallback", "false"); } // Timeouts props.setProperty(MAIL_DOT + getProtocol() + ".connectiontimeout", Long.toString(getConnectionTimeout() < 0L ? ServerSetup.CONNECTION_TIMEOUT : getConnectionTimeout())); props.setProperty(MAIL_DOT + getProtocol() + ".timeout", Long.toString(getReadTimeout() < 0L ? ServerSetup.READ_TIMEOUT : getReadTimeout())); // Note: "mail." + setup.getProtocol() + ".writetimeout" breaks TLS/SSL Dummy Socket and makes tests run 6x slower!!! // Therefore we do not by default configure writetimeout. if (getWriteTimeout() >= 0L) { props.setProperty(MAIL_DOT + getProtocol() + ".writetimeout", Long.toString(getWriteTimeout())); } // Protocol specific extensions if (getProtocol().startsWith(PROTOCOL_SMTP)) { props.setProperty("mail.transport.protocol", getProtocol()); props.setProperty("mail.transport.protocol.rfc822", getProtocol()); } // Auto configure stores. props.setProperty("mail.store.protocol", getProtocol()); // Merge with optional additional properties if (null != properties && !properties.isEmpty()) { props.putAll(properties); } return props; }
[ "public", "Properties", "configureJavaMailSessionProperties", "(", "Properties", "properties", ",", "boolean", "debug", ")", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "if", "(", "debug", ")", "{", "props", ".", "setProperty", "(", "\"mail.debug\"", ",", "\"true\"", ")", ";", "// System.setProperty(\"mail.socket.debug\", \"true\");\r", "}", "// Set local host address (makes tests much faster. If this is not set java mail always looks for the address)\r", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".localaddress\"", ",", "String", ".", "valueOf", "(", "ServerSetup", ".", "getLocalHostAddress", "(", ")", ")", ")", ";", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".port\"", ",", "String", ".", "valueOf", "(", "getPort", "(", ")", ")", ")", ";", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".host\"", ",", "String", ".", "valueOf", "(", "getBindAddress", "(", ")", ")", ")", ";", "if", "(", "isSecure", "(", ")", ")", "{", "props", ".", "put", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".starttls.enable\"", ",", "Boolean", ".", "TRUE", ")", ";", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".socketFactory.class\"", ",", "DummySSLSocketFactory", ".", "class", ".", "getName", "(", ")", ")", ";", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".socketFactory.fallback\"", ",", "\"false\"", ")", ";", "}", "// Timeouts\r", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".connectiontimeout\"", ",", "Long", ".", "toString", "(", "getConnectionTimeout", "(", ")", "<", "0L", "?", "ServerSetup", ".", "CONNECTION_TIMEOUT", ":", "getConnectionTimeout", "(", ")", ")", ")", ";", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".timeout\"", ",", "Long", ".", "toString", "(", "getReadTimeout", "(", ")", "<", "0L", "?", "ServerSetup", ".", "READ_TIMEOUT", ":", "getReadTimeout", "(", ")", ")", ")", ";", "// Note: \"mail.\" + setup.getProtocol() + \".writetimeout\" breaks TLS/SSL Dummy Socket and makes tests run 6x slower!!!\r", "// Therefore we do not by default configure writetimeout.\r", "if", "(", "getWriteTimeout", "(", ")", ">=", "0L", ")", "{", "props", ".", "setProperty", "(", "MAIL_DOT", "+", "getProtocol", "(", ")", "+", "\".writetimeout\"", ",", "Long", ".", "toString", "(", "getWriteTimeout", "(", ")", ")", ")", ";", "}", "// Protocol specific extensions\r", "if", "(", "getProtocol", "(", ")", ".", "startsWith", "(", "PROTOCOL_SMTP", ")", ")", "{", "props", ".", "setProperty", "(", "\"mail.transport.protocol\"", ",", "getProtocol", "(", ")", ")", ";", "props", ".", "setProperty", "(", "\"mail.transport.protocol.rfc822\"", ",", "getProtocol", "(", ")", ")", ";", "}", "// Auto configure stores.\r", "props", ".", "setProperty", "(", "\"mail.store.protocol\"", ",", "getProtocol", "(", ")", ")", ";", "// Merge with optional additional properties\r", "if", "(", "null", "!=", "properties", "&&", "!", "properties", ".", "isEmpty", "(", ")", ")", "{", "props", ".", "putAll", "(", "properties", ")", ";", "}", "return", "props", ";", "}" ]
Creates default properties for a JavaMail session. Concrete server implementations can add protocol specific settings. <p/> For details see <ul> <li>http://docs.oracle.com/javaee/6/api/javax/mail/package-summary.html for some general settings</li> <li>https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html for valid SMTP properties.</li> <li>https://javamail.java.net/nonav/docs/api/com/sun/mail/imap/package-summary.html for valid IMAP properties</li> <li>https://javamail.java.net/nonav/docs/api/com/sun/mail/pop3/package-summary.html for valid POP3 properties.</li> </ul @param properties additional and optional properties which overwrite automatically added properties. Can be null. @param debug sets JavaMail debug properties @return default properties.
[ "Creates", "default", "properties", "for", "a", "JavaMail", "session", ".", "Concrete", "server", "implementations", "can", "add", "protocol", "specific", "settings", ".", "<p", "/", ">", "For", "details", "see", "<ul", ">", "<li", ">", "http", ":", "//", "docs", ".", "oracle", ".", "com", "/", "javaee", "/", "6", "/", "api", "/", "javax", "/", "mail", "/", "package", "-", "summary", ".", "html", "for", "some", "general", "settings<", "/", "li", ">", "<li", ">", "https", ":", "//", "javamail", ".", "java", ".", "net", "/", "nonav", "/", "docs", "/", "api", "/", "com", "/", "sun", "/", "mail", "/", "smtp", "/", "package", "-", "summary", ".", "html", "for", "valid", "SMTP", "properties", ".", "<", "/", "li", ">", "<li", ">", "https", ":", "//", "javamail", ".", "java", ".", "net", "/", "nonav", "/", "docs", "/", "api", "/", "com", "/", "sun", "/", "mail", "/", "imap", "/", "package", "-", "summary", ".", "html", "for", "valid", "IMAP", "properties<", "/", "li", ">", "<li", ">", "https", ":", "//", "javamail", ".", "java", ".", "net", "/", "nonav", "/", "docs", "/", "api", "/", "com", "/", "sun", "/", "mail", "/", "pop3", "/", "package", "-", "summary", ".", "html", "for", "valid", "POP3", "properties", ".", "<", "/", "li", ">", "<", "/", "ul" ]
train
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/ServerSetup.java#L195-L240
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/utilities/StringUtility.java
StringUtility.prettyPrint
public static String prettyPrint(String in, int lineLength, String delim) { // make a guess about resulting length to minimize copying StringBuilder sb = new StringBuilder(in.length() + in.length()/lineLength); if (delim == null) { delim = " "; } StringTokenizer st = new StringTokenizer(in, delim); int charCount = 0; while (st.hasMoreTokens()) { String s = st.nextToken(); charCount = charCount + s.length(); if (charCount < lineLength) { sb.append(s); sb.append(' '); charCount++; } else { sb.append('\n'); sb.append(s); sb.append(' '); charCount = s.length() + 1; } } return sb.toString(); }
java
public static String prettyPrint(String in, int lineLength, String delim) { // make a guess about resulting length to minimize copying StringBuilder sb = new StringBuilder(in.length() + in.length()/lineLength); if (delim == null) { delim = " "; } StringTokenizer st = new StringTokenizer(in, delim); int charCount = 0; while (st.hasMoreTokens()) { String s = st.nextToken(); charCount = charCount + s.length(); if (charCount < lineLength) { sb.append(s); sb.append(' '); charCount++; } else { sb.append('\n'); sb.append(s); sb.append(' '); charCount = s.length() + 1; } } return sb.toString(); }
[ "public", "static", "String", "prettyPrint", "(", "String", "in", ",", "int", "lineLength", ",", "String", "delim", ")", "{", "// make a guess about resulting length to minimize copying", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "in", ".", "length", "(", ")", "+", "in", ".", "length", "(", ")", "/", "lineLength", ")", ";", "if", "(", "delim", "==", "null", ")", "{", "delim", "=", "\" \"", ";", "}", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "in", ",", "delim", ")", ";", "int", "charCount", "=", "0", ";", "while", "(", "st", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "s", "=", "st", ".", "nextToken", "(", ")", ";", "charCount", "=", "charCount", "+", "s", ".", "length", "(", ")", ";", "if", "(", "charCount", "<", "lineLength", ")", "{", "sb", ".", "append", "(", "s", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "charCount", "++", ";", "}", "else", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "s", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "charCount", "=", "s", ".", "length", "(", ")", "+", "1", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Method that attempts to break a string up into lines no longer than the specified line length. <p>The string is assumed to consist of tokens separated by a delimeter. The default delimiter is a space. If the last token to be added to a line exceeds the specified line length, it is written on the next line so actual line length is approximate given the specified line length and the length of tokens in the string. @param in The input string to be split into lines. @param lineLength The maximum length of each line. @param delim The character delimiter separating each token in the input string; if null, defaults to the space character. @return A string split into multiple lines whose length is less than the specified length. Actual length is approximate depending on line length, token size, and how many complete tokens will fit into the specified line length.
[ "Method", "that", "attempts", "to", "break", "a", "string", "up", "into", "lines", "no", "longer", "than", "the", "specified", "line", "length", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/utilities/StringUtility.java#L42-L65
kohsuke/com4j
runtime/src/main/java/com4j/COM4J.java
COM4J.getActiveObject
public static <T extends Com4jObject> T getActiveObject(Class<T> primaryInterface, String clsid ) { return getActiveObject(primaryInterface,new GUID(clsid)); }
java
public static <T extends Com4jObject> T getActiveObject(Class<T> primaryInterface, String clsid ) { return getActiveObject(primaryInterface,new GUID(clsid)); }
[ "public", "static", "<", "T", "extends", "Com4jObject", ">", "T", "getActiveObject", "(", "Class", "<", "T", ">", "primaryInterface", ",", "String", "clsid", ")", "{", "return", "getActiveObject", "(", "primaryInterface", ",", "new", "GUID", "(", "clsid", ")", ")", ";", "}" ]
Gets an already object from the running object table. @param <T> the type of the return value and the type parameter of the class object of primaryInterface @param primaryInterface The returned COM object is returned as this interface. Must be non-null. Passing in {@link Com4jObject} allows the caller to create a new instance without knowing its primary interface. @param clsid The CLSID of the COM object to be retrieved, in the "<tt>{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}</tt>" format, or the ProgID of the object (like "Microsoft.XMLParser.1.0") @return non-null valid object. @throws ComException if the retrieval fails. @see #getActiveObject(Class,GUID)
[ "Gets", "an", "already", "object", "from", "the", "running", "object", "table", "." ]
train
https://github.com/kohsuke/com4j/blob/1e690b805fb0e4e9ef61560e20a56335aecb0b24/runtime/src/main/java/com4j/COM4J.java#L185-L187
santhosh-tekuri/jlibs
swing/src/main/java/jlibs/swing/SwingUtil.java
SwingUtil.setInitialFocus
public static void setInitialFocus(Window window, final Component comp){ window.addWindowFocusListener(new WindowAdapter(){ @Override public void windowGainedFocus(WindowEvent we){ comp.requestFocusInWindow(); we.getWindow().removeWindowFocusListener(this); } }); }
java
public static void setInitialFocus(Window window, final Component comp){ window.addWindowFocusListener(new WindowAdapter(){ @Override public void windowGainedFocus(WindowEvent we){ comp.requestFocusInWindow(); we.getWindow().removeWindowFocusListener(this); } }); }
[ "public", "static", "void", "setInitialFocus", "(", "Window", "window", ",", "final", "Component", "comp", ")", "{", "window", ".", "addWindowFocusListener", "(", "new", "WindowAdapter", "(", ")", "{", "@", "Override", "public", "void", "windowGainedFocus", "(", "WindowEvent", "we", ")", "{", "comp", ".", "requestFocusInWindow", "(", ")", ";", "we", ".", "getWindow", "(", ")", ".", "removeWindowFocusListener", "(", "this", ")", ";", "}", "}", ")", ";", "}" ]
sets intial focus in window to the specified component @param window window on which focus has to be set @param comp component which need to have initial focus
[ "sets", "intial", "focus", "in", "window", "to", "the", "specified", "component" ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/swing/src/main/java/jlibs/swing/SwingUtil.java#L40-L48
jtmelton/appsensor
analysis-engines/appsensor-analysis-rules/src/main/java/org/owasp/appsensor/analysis/AggregateEventAnalysisEngine.java
AggregateEventAnalysisEngine.getQueueInterval
public Interval getQueueInterval(Queue<Event> queue, Event tailEvent) { DateTime endTime = DateUtils.fromString(tailEvent.getTimestamp()); DateTime startTime = DateUtils.fromString(queue.peek().getTimestamp()); return new Interval((int)endTime.minus(startTime.getMillis()).getMillis(), "milliseconds"); }
java
public Interval getQueueInterval(Queue<Event> queue, Event tailEvent) { DateTime endTime = DateUtils.fromString(tailEvent.getTimestamp()); DateTime startTime = DateUtils.fromString(queue.peek().getTimestamp()); return new Interval((int)endTime.minus(startTime.getMillis()).getMillis(), "milliseconds"); }
[ "public", "Interval", "getQueueInterval", "(", "Queue", "<", "Event", ">", "queue", ",", "Event", "tailEvent", ")", "{", "DateTime", "endTime", "=", "DateUtils", ".", "fromString", "(", "tailEvent", ".", "getTimestamp", "(", ")", ")", ";", "DateTime", "startTime", "=", "DateUtils", ".", "fromString", "(", "queue", ".", "peek", "(", ")", ".", "getTimestamp", "(", ")", ")", ";", "return", "new", "Interval", "(", "(", "int", ")", "endTime", ".", "minus", "(", "startTime", ".", "getMillis", "(", ")", ")", ".", "getMillis", "(", ")", ",", "\"milliseconds\"", ")", ";", "}" ]
Determines the time between the {@link Event} at the head of the queue and the {@link Event} at the tail of the queue. @param queue a queue of {@link Event}s @param tailEvent the {@link Event} at the tail of the queue @return the duration of the queue as an {@link Interval}
[ "Determines", "the", "time", "between", "the", "{", "@link", "Event", "}", "at", "the", "head", "of", "the", "queue", "and", "the", "{", "@link", "Event", "}", "at", "the", "tail", "of", "the", "queue", "." ]
train
https://github.com/jtmelton/appsensor/blob/c3b4e9ada50fdee974e0d618ec4bdfabc2163798/analysis-engines/appsensor-analysis-rules/src/main/java/org/owasp/appsensor/analysis/AggregateEventAnalysisEngine.java#L241-L246
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java
ArrayUtil.removeBlank
public static <T extends CharSequence> T[] removeBlank(T[] array) { return filter(array, new Filter<T>() { @Override public boolean accept(T t) { return false == StrUtil.isBlank(t); } }); }
java
public static <T extends CharSequence> T[] removeBlank(T[] array) { return filter(array, new Filter<T>() { @Override public boolean accept(T t) { return false == StrUtil.isBlank(t); } }); }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "[", "]", "removeBlank", "(", "T", "[", "]", "array", ")", "{", "return", "filter", "(", "array", ",", "new", "Filter", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "boolean", "accept", "(", "T", "t", ")", "{", "return", "false", "==", "StrUtil", ".", "isBlank", "(", "t", ")", ";", "}", "}", ")", ";", "}" ]
去除{@code null}或者""或者空白字符串 元素 @param array 数组 @return 处理后的数组 @since 3.2.2
[ "去除", "{", "@code", "null", "}", "或者", "或者空白字符串", "元素" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L814-L821
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getGuildLogInfo
public void getGuildLogInfo(String id, String api, Callback<List<GuildLog>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildLogInfo(id, api).enqueue(callback); }
java
public void getGuildLogInfo(String id, String api, Callback<List<GuildLog>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildLogInfo(id, api).enqueue(callback); }
[ "public", "void", "getGuildLogInfo", "(", "String", "id", ",", "String", "api", ",", "Callback", "<", "List", "<", "GuildLog", ">", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ParamType", ".", "GUILD", ",", "id", ")", ",", "new", "ParamChecker", "(", "ParamType", ".", "API", ",", "api", ")", ")", ";", "gw2API", ".", "getGuildLogInfo", "(", "id", ",", "api", ")", ".", "enqueue", "(", "callback", ")", ";", "}" ]
For more info on guild log API go <a href="https://wiki.guildwars2.com/wiki/API:2/guild/:id/log">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions<br/> @param id guild id @param api Guild leader's Guild Wars 2 API key @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see GuildLog guild log info
[ "For", "more", "info", "on", "guild", "log", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "guild", "/", ":", "id", "/", "log", ">", "here<", "/", "a", ">", "<br", "/", ">", "Give", "user", "the", "access", "to", "{", "@link", "Callback#onResponse", "(", "Call", "Response", ")", "}", "and", "{", "@link", "Callback#onFailure", "(", "Call", "Throwable", ")", "}", "methods", "for", "custom", "interactions<br", "/", ">" ]
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1468-L1471
alkacon/opencms-core
src/org/opencms/jsp/Messages.java
Messages.getLocalizedMessage
public static String getLocalizedMessage(CmsMessageContainer container, PageContext context) { return Messages.getLocalizedMessage(container, context.getRequest()); }
java
public static String getLocalizedMessage(CmsMessageContainer container, PageContext context) { return Messages.getLocalizedMessage(container, context.getRequest()); }
[ "public", "static", "String", "getLocalizedMessage", "(", "CmsMessageContainer", "container", ",", "PageContext", "context", ")", "{", "return", "Messages", ".", "getLocalizedMessage", "(", "container", ",", "context", ".", "getRequest", "(", ")", ")", ";", "}" ]
Returns the String for the given CmsMessageContainer localized to the current user's locale if available or to the default locale else. <p> This method is needed for localization of non- {@link org.opencms.main.CmsException} instances that have to be thrown here due to API constraints (javax.servlet.jsp). <p> @param container A CmsMessageContainer containing the message to localize. @param context The page context that is known to any calling {@link javax.servlet.jsp.tagext.TagSupport} instance (member <code>pageContext</code>). @return the String for the given CmsMessageContainer localized to the current user's locale if available or to the default locale else. <p>
[ "Returns", "the", "String", "for", "the", "given", "CmsMessageContainer", "localized", "to", "the", "current", "user", "s", "locale", "if", "available", "or", "to", "the", "default", "locale", "else", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/Messages.java#L315-L318
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java
PoolOperations.createPool
public void createPool(String poolId, String virtualMachineSize, CloudServiceConfiguration cloudServiceConfiguration, int targetDedicatedNodes) throws BatchErrorException, IOException { createPool(poolId, virtualMachineSize, cloudServiceConfiguration, targetDedicatedNodes, 0, null); }
java
public void createPool(String poolId, String virtualMachineSize, CloudServiceConfiguration cloudServiceConfiguration, int targetDedicatedNodes) throws BatchErrorException, IOException { createPool(poolId, virtualMachineSize, cloudServiceConfiguration, targetDedicatedNodes, 0, null); }
[ "public", "void", "createPool", "(", "String", "poolId", ",", "String", "virtualMachineSize", ",", "CloudServiceConfiguration", "cloudServiceConfiguration", ",", "int", "targetDedicatedNodes", ")", "throws", "BatchErrorException", ",", "IOException", "{", "createPool", "(", "poolId", ",", "virtualMachineSize", ",", "cloudServiceConfiguration", ",", "targetDedicatedNodes", ",", "0", ",", "null", ")", ";", "}" ]
Adds a pool to the Batch account. @param poolId The ID of the pool. @param virtualMachineSize The size of virtual machines in the pool. See <a href= "https://azure.microsoft.com/documentation/articles/virtual-machines-size-specs/">https://azure.microsoft.com/documentation/articles/virtual-machines-size-specs/</a> for sizes. @param cloudServiceConfiguration The {@link CloudServiceConfiguration} for the pool. @param targetDedicatedNodes The desired number of dedicated compute nodes in the pool. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Adds", "a", "pool", "to", "the", "Batch", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L288-L292
drewwills/cernunnos
cernunnos-core/src/main/java/org/danann/cernunnos/runtime/ScriptRunner.java
ScriptRunner.run
public TaskResponse run(Element m, TaskRequest req) { // Assertions. if (m == null) { String msg = "Argument 'm [Element]' cannot be null."; throw new IllegalArgumentException(msg); } return run(compileTask(m), req); }
java
public TaskResponse run(Element m, TaskRequest req) { // Assertions. if (m == null) { String msg = "Argument 'm [Element]' cannot be null."; throw new IllegalArgumentException(msg); } return run(compileTask(m), req); }
[ "public", "TaskResponse", "run", "(", "Element", "m", ",", "TaskRequest", "req", ")", "{", "// Assertions.", "if", "(", "m", "==", "null", ")", "{", "String", "msg", "=", "\"Argument 'm [Element]' cannot be null.\"", ";", "throw", "new", "IllegalArgumentException", "(", "msg", ")", ";", "}", "return", "run", "(", "compileTask", "(", "m", ")", ",", "req", ")", ";", "}" ]
Invokes the script defined by the specified element with the specified <code>TaskRequest</code>. @param m An <code>Element</code> that defines a Task. @param req A <code>TaskRequest</code> prepared externally. @return The <code>TaskResponse</code> that results from invoking the specified script.
[ "Invokes", "the", "script", "defined", "by", "the", "specified", "element", "with", "the", "specified", "<code", ">", "TaskRequest<", "/", "code", ">", "." ]
train
https://github.com/drewwills/cernunnos/blob/dc6848e0253775e22b6c869fd06506d4ddb6d728/cernunnos-core/src/main/java/org/danann/cernunnos/runtime/ScriptRunner.java#L171-L181
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.readNormalDay
private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay) { int dayNumber = weekDay.getDayType().intValue(); Day day = Day.getInstance(dayNumber); calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking())); ProjectCalendarHours hours = calendar.addCalendarHours(day); Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes(); if (times != null) { for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime()) { Date startTime = period.getFromTime(); Date endTime = period.getToTime(); if (startTime != null && endTime != null) { if (startTime.getTime() >= endTime.getTime()) { endTime = DateHelper.addDays(endTime, 1); } hours.addRange(new DateRange(startTime, endTime)); } } } }
java
private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay) { int dayNumber = weekDay.getDayType().intValue(); Day day = Day.getInstance(dayNumber); calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking())); ProjectCalendarHours hours = calendar.addCalendarHours(day); Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes(); if (times != null) { for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime()) { Date startTime = period.getFromTime(); Date endTime = period.getToTime(); if (startTime != null && endTime != null) { if (startTime.getTime() >= endTime.getTime()) { endTime = DateHelper.addDays(endTime, 1); } hours.addRange(new DateRange(startTime, endTime)); } } } }
[ "private", "void", "readNormalDay", "(", "ProjectCalendar", "calendar", ",", "Project", ".", "Calendars", ".", "Calendar", ".", "WeekDays", ".", "WeekDay", "weekDay", ")", "{", "int", "dayNumber", "=", "weekDay", ".", "getDayType", "(", ")", ".", "intValue", "(", ")", ";", "Day", "day", "=", "Day", ".", "getInstance", "(", "dayNumber", ")", ";", "calendar", ".", "setWorkingDay", "(", "day", ",", "BooleanHelper", ".", "getBoolean", "(", "weekDay", ".", "isDayWorking", "(", ")", ")", ")", ";", "ProjectCalendarHours", "hours", "=", "calendar", ".", "addCalendarHours", "(", "day", ")", ";", "Project", ".", "Calendars", ".", "Calendar", ".", "WeekDays", ".", "WeekDay", ".", "WorkingTimes", "times", "=", "weekDay", ".", "getWorkingTimes", "(", ")", ";", "if", "(", "times", "!=", "null", ")", "{", "for", "(", "Project", ".", "Calendars", ".", "Calendar", ".", "WeekDays", ".", "WeekDay", ".", "WorkingTimes", ".", "WorkingTime", "period", ":", "times", ".", "getWorkingTime", "(", ")", ")", "{", "Date", "startTime", "=", "period", ".", "getFromTime", "(", ")", ";", "Date", "endTime", "=", "period", ".", "getToTime", "(", ")", ";", "if", "(", "startTime", "!=", "null", "&&", "endTime", "!=", "null", ")", "{", "if", "(", "startTime", ".", "getTime", "(", ")", ">=", "endTime", ".", "getTime", "(", ")", ")", "{", "endTime", "=", "DateHelper", ".", "addDays", "(", "endTime", ",", "1", ")", ";", "}", "hours", ".", "addRange", "(", "new", "DateRange", "(", "startTime", ",", "endTime", ")", ")", ";", "}", "}", "}", "}" ]
This method extracts data for a normal working day from an MSPDI file. @param calendar Calendar data @param weekDay Day data
[ "This", "method", "extracts", "data", "for", "a", "normal", "working", "day", "from", "an", "MSPDI", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L516-L542
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/hook/AmLogServerEndPoint.java
AmLogServerEndPoint.onClose
@OnClose public void onClose(Session session, CloseReason closeReason) { logger.info("WebSocket closed. : SessionId={}, Reason={}", session.getId(), closeReason.toString()); AmLogServerAdapter.getInstance().onClose(session); }
java
@OnClose public void onClose(Session session, CloseReason closeReason) { logger.info("WebSocket closed. : SessionId={}, Reason={}", session.getId(), closeReason.toString()); AmLogServerAdapter.getInstance().onClose(session); }
[ "@", "OnClose", "public", "void", "onClose", "(", "Session", "session", ",", "CloseReason", "closeReason", ")", "{", "logger", ".", "info", "(", "\"WebSocket closed. : SessionId={}, Reason={}\"", ",", "session", ".", "getId", "(", ")", ",", "closeReason", ".", "toString", "(", ")", ")", ";", "AmLogServerAdapter", ".", "getInstance", "(", ")", ".", "onClose", "(", "session", ")", ";", "}" ]
Websocket connection close. @param session session @param closeReason closeReason
[ "Websocket", "connection", "close", "." ]
train
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/hook/AmLogServerEndPoint.java#L59-L65
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/OjbMemberTagsHandler.java
OjbMemberTagsHandler.memberTagValue
public String memberTagValue(Properties attributes) throws XDocletException { if (getCurrentField() != null) { // setting field to true will override the for_class value. attributes.setProperty("field", "true"); return getExpandedDelimitedTagValue(attributes, FOR_FIELD); } else if (getCurrentMethod() != null) { return getExpandedDelimitedTagValue(attributes, FOR_METHOD); } else { return null; } }
java
public String memberTagValue(Properties attributes) throws XDocletException { if (getCurrentField() != null) { // setting field to true will override the for_class value. attributes.setProperty("field", "true"); return getExpandedDelimitedTagValue(attributes, FOR_FIELD); } else if (getCurrentMethod() != null) { return getExpandedDelimitedTagValue(attributes, FOR_METHOD); } else { return null; } }
[ "public", "String", "memberTagValue", "(", "Properties", "attributes", ")", "throws", "XDocletException", "{", "if", "(", "getCurrentField", "(", ")", "!=", "null", ")", "{", "// setting field to true will override the for_class value.\r", "attributes", ".", "setProperty", "(", "\"field\"", ",", "\"true\"", ")", ";", "return", "getExpandedDelimitedTagValue", "(", "attributes", ",", "FOR_FIELD", ")", ";", "}", "else", "if", "(", "getCurrentMethod", "(", ")", "!=", "null", ")", "{", "return", "getExpandedDelimitedTagValue", "(", "attributes", ",", "FOR_METHOD", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the value of the tag/parameter combination for the current member tag @param attributes The attributes of the template tag @return Description of the Returned Value @exception XDocletException Description of Exception @doc.tag type="content" @doc.param name="tagName" optional="false" description="The tag name." @doc.param name="paramName" description="The parameter name. If not specified, then the raw content of the tag is returned." @doc.param name="paramNum" description="The zero-based parameter number. It's used if the user used the space-separated format for specifying parameters." @doc.param name="values" description="The valid values for the parameter, comma separated. An error message is printed if the parameter value is not one of the values." @doc.param name="default" description="The default value is returned if parameter not specified by user for the tag."
[ "Returns", "the", "value", "of", "the", "tag", "/", "parameter", "combination", "for", "the", "current", "member", "tag" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbMemberTagsHandler.java#L423-L436
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_mailingList_mailingListAddress_PUT
public void organizationName_service_exchangeService_mailingList_mailingListAddress_PUT(String organizationName, String exchangeService, String mailingListAddress, OvhMailingList body) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}"; StringBuilder sb = path(qPath, organizationName, exchangeService, mailingListAddress); exec(qPath, "PUT", sb.toString(), body); }
java
public void organizationName_service_exchangeService_mailingList_mailingListAddress_PUT(String organizationName, String exchangeService, String mailingListAddress, OvhMailingList body) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}"; StringBuilder sb = path(qPath, organizationName, exchangeService, mailingListAddress); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "organizationName_service_exchangeService_mailingList_mailingListAddress_PUT", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "String", "mailingListAddress", ",", "OvhMailingList", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "organizationName", ",", "exchangeService", ",", "mailingListAddress", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress} @param body [required] New object properties @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param mailingListAddress [required] The mailing list address
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L1340-L1344
Netflix/servo
servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java
Monitors.registerObject
public static void registerObject(String id, Object obj) { DefaultMonitorRegistry.getInstance().register(newObjectMonitor(id, obj)); }
java
public static void registerObject(String id, Object obj) { DefaultMonitorRegistry.getInstance().register(newObjectMonitor(id, obj)); }
[ "public", "static", "void", "registerObject", "(", "String", "id", ",", "Object", "obj", ")", "{", "DefaultMonitorRegistry", ".", "getInstance", "(", ")", ".", "register", "(", "newObjectMonitor", "(", "id", ",", "obj", ")", ")", ";", "}" ]
Register an object with the default registry. Equivalent to {@code DefaultMonitorRegistry.getInstance().register(Monitors.newObjectMonitor(id, obj))}.
[ "Register", "an", "object", "with", "the", "default", "registry", ".", "Equivalent", "to", "{" ]
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L215-L217
sporniket/core
sporniket-core-ml/src/main/java/com/sporniket/libre/lang/html/HtmlUtils.java
HtmlUtils.generateAttribute
public static String generateAttribute(String attributeName, String value) { return SgmlUtils.generateAttribute(attributeName, value); }
java
public static String generateAttribute(String attributeName, String value) { return SgmlUtils.generateAttribute(attributeName, value); }
[ "public", "static", "String", "generateAttribute", "(", "String", "attributeName", ",", "String", "value", ")", "{", "return", "SgmlUtils", ".", "generateAttribute", "(", "attributeName", ",", "value", ")", ";", "}" ]
Generate the HTML code for an attribute. @param attributeName the name of the attribute. @param value the value of the attribute. @return the HTML attribute.
[ "Generate", "the", "HTML", "code", "for", "an", "attribute", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ml/src/main/java/com/sporniket/libre/lang/html/HtmlUtils.java#L216-L219
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/store/VFSStoreResource.java
VFSStoreResource.read
@Override public InputStream read() throws EFapsException { StoreResourceInputStream in = null; try { final FileObject file = this.manager.resolveFile(this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); if (!file.isReadable()) { VFSStoreResource.LOG.error("file for " + this.storeFileName + " not readable"); throw new EFapsException(VFSStoreResource.class, "#####file not readable"); } in = new VFSStoreResourceInputStream(this, file); } catch (final FileSystemException e) { VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e); throw new EFapsException(VFSStoreResource.class, "read.Throwable", e); } catch (final IOException e) { VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e); throw new EFapsException(VFSStoreResource.class, "read.Throwable", e); } return in; }
java
@Override public InputStream read() throws EFapsException { StoreResourceInputStream in = null; try { final FileObject file = this.manager.resolveFile(this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); if (!file.isReadable()) { VFSStoreResource.LOG.error("file for " + this.storeFileName + " not readable"); throw new EFapsException(VFSStoreResource.class, "#####file not readable"); } in = new VFSStoreResourceInputStream(this, file); } catch (final FileSystemException e) { VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e); throw new EFapsException(VFSStoreResource.class, "read.Throwable", e); } catch (final IOException e) { VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e); throw new EFapsException(VFSStoreResource.class, "read.Throwable", e); } return in; }
[ "@", "Override", "public", "InputStream", "read", "(", ")", "throws", "EFapsException", "{", "StoreResourceInputStream", "in", "=", "null", ";", "try", "{", "final", "FileObject", "file", "=", "this", ".", "manager", ".", "resolveFile", "(", "this", ".", "storeFileName", "+", "VFSStoreResource", ".", "EXTENSION_NORMAL", ")", ";", "if", "(", "!", "file", ".", "isReadable", "(", ")", ")", "{", "VFSStoreResource", ".", "LOG", ".", "error", "(", "\"file for \"", "+", "this", ".", "storeFileName", "+", "\" not readable\"", ")", ";", "throw", "new", "EFapsException", "(", "VFSStoreResource", ".", "class", ",", "\"#####file not readable\"", ")", ";", "}", "in", "=", "new", "VFSStoreResourceInputStream", "(", "this", ",", "file", ")", ";", "}", "catch", "(", "final", "FileSystemException", "e", ")", "{", "VFSStoreResource", ".", "LOG", ".", "error", "(", "\"read of \"", "+", "this", ".", "storeFileName", "+", "\" failed\"", ",", "e", ")", ";", "throw", "new", "EFapsException", "(", "VFSStoreResource", ".", "class", ",", "\"read.Throwable\"", ",", "e", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "VFSStoreResource", ".", "LOG", ".", "error", "(", "\"read of \"", "+", "this", ".", "storeFileName", "+", "\" failed\"", ",", "e", ")", ";", "throw", "new", "EFapsException", "(", "VFSStoreResource", ".", "class", ",", "\"read.Throwable\"", ",", "e", ")", ";", "}", "return", "in", ";", "}" ]
Returns for the file the input stream. @return input stream of the file with the content @throws EFapsException on error
[ "Returns", "for", "the", "file", "the", "input", "stream", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/store/VFSStoreResource.java#L348-L368
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/client/proxyqueue/impl/LockedMessageEnumerationImpl.java
LockedMessageEnumerationImpl.deleteMessages
private void deleteMessages(JsMessage[] messagesToDelete, SITransaction transaction) throws SISessionUnavailableException, SISessionDroppedException, SIConnectionUnavailableException, SIConnectionDroppedException, SIResourceException, SIConnectionLostException, SILimitExceededException, SIIncorrectCallException, SIMessageNotLockedException, SIErrorException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc,"deleteMessages"); int priority = JFapChannelConstants.PRIORITY_MEDIUM; // d178368 if (transaction != null) { Transaction commsTransaction = (Transaction)transaction; priority = commsTransaction.getLowestMessagePriority(); // d178368 // f181927 // Inform the transaction that our consumer session has deleted // a recoverable message under this transaction. This means that if // a rollback is performed (and strict rollback ordering is enabled) // we can ensure that this message will be redelivered in order. commsTransaction.associateConsumer(consumerSession); } // begin F219476.2 SIMessageHandle[] messageHandles = new SIMessageHandle[messagesToDelete.length]; for (int x = 0; x < messagesToDelete.length; x++) // f192215 { if (messagesToDelete[x] != null) { messageHandles[x] = messagesToDelete[x].getMessageHandle(); } } convHelper.deleteMessages(messageHandles, transaction, priority); // d178368 // end F219476.2 // } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc,"deleteMessages"); }
java
private void deleteMessages(JsMessage[] messagesToDelete, SITransaction transaction) throws SISessionUnavailableException, SISessionDroppedException, SIConnectionUnavailableException, SIConnectionDroppedException, SIResourceException, SIConnectionLostException, SILimitExceededException, SIIncorrectCallException, SIMessageNotLockedException, SIErrorException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc,"deleteMessages"); int priority = JFapChannelConstants.PRIORITY_MEDIUM; // d178368 if (transaction != null) { Transaction commsTransaction = (Transaction)transaction; priority = commsTransaction.getLowestMessagePriority(); // d178368 // f181927 // Inform the transaction that our consumer session has deleted // a recoverable message under this transaction. This means that if // a rollback is performed (and strict rollback ordering is enabled) // we can ensure that this message will be redelivered in order. commsTransaction.associateConsumer(consumerSession); } // begin F219476.2 SIMessageHandle[] messageHandles = new SIMessageHandle[messagesToDelete.length]; for (int x = 0; x < messagesToDelete.length; x++) // f192215 { if (messagesToDelete[x] != null) { messageHandles[x] = messagesToDelete[x].getMessageHandle(); } } convHelper.deleteMessages(messageHandles, transaction, priority); // d178368 // end F219476.2 // } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc,"deleteMessages"); }
[ "private", "void", "deleteMessages", "(", "JsMessage", "[", "]", "messagesToDelete", ",", "SITransaction", "transaction", ")", "throws", "SISessionUnavailableException", ",", "SISessionDroppedException", ",", "SIConnectionUnavailableException", ",", "SIConnectionDroppedException", ",", "SIResourceException", ",", "SIConnectionLostException", ",", "SILimitExceededException", ",", "SIIncorrectCallException", ",", "SIMessageNotLockedException", ",", "SIErrorException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "this", ",", "tc", ",", "\"deleteMessages\"", ")", ";", "int", "priority", "=", "JFapChannelConstants", ".", "PRIORITY_MEDIUM", ";", "// d178368", "if", "(", "transaction", "!=", "null", ")", "{", "Transaction", "commsTransaction", "=", "(", "Transaction", ")", "transaction", ";", "priority", "=", "commsTransaction", ".", "getLowestMessagePriority", "(", ")", ";", "// d178368 // f181927", "// Inform the transaction that our consumer session has deleted", "// a recoverable message under this transaction. This means that if", "// a rollback is performed (and strict rollback ordering is enabled)", "// we can ensure that this message will be redelivered in order.", "commsTransaction", ".", "associateConsumer", "(", "consumerSession", ")", ";", "}", "// begin F219476.2", "SIMessageHandle", "[", "]", "messageHandles", "=", "new", "SIMessageHandle", "[", "messagesToDelete", ".", "length", "]", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "messagesToDelete", ".", "length", ";", "x", "++", ")", "// f192215", "{", "if", "(", "messagesToDelete", "[", "x", "]", "!=", "null", ")", "{", "messageHandles", "[", "x", "]", "=", "messagesToDelete", "[", "x", "]", ".", "getMessageHandle", "(", ")", ";", "}", "}", "convHelper", ".", "deleteMessages", "(", "messageHandles", ",", "transaction", ",", "priority", ")", ";", "// d178368", "// end F219476.2", "// }", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "this", ",", "tc", ",", "\"deleteMessages\"", ")", ";", "}" ]
This private method actually performs the delete by asking the conversation helper to flow the request across the wire. However, this method does not obtain any locks required to perform this operation and as such should be called by a method that does do this. @param messagesToDelete @param transaction @throws SICommsException
[ "This", "private", "method", "actually", "performs", "the", "delete", "by", "asking", "the", "conversation", "helper", "to", "flow", "the", "request", "across", "the", "wire", ".", "However", "this", "method", "does", "not", "obtain", "any", "locks", "required", "to", "perform", "this", "operation", "and", "as", "such", "should", "be", "called", "by", "a", "method", "that", "does", "do", "this", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/client/proxyqueue/impl/LockedMessageEnumerationImpl.java#L371-L407
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.takeQueueTicket
static String takeQueueTicket(ZooKeeper zookeeper, String lockNode) throws InterruptedException, KeeperException { // The ticket number includes a random component to decrease the chances of collision. Collision is handled // neatly, but it saves a few actions if there is no need to retry ticket acquisition. String ticket = String.format("nr-%014d-%04d", System.currentTimeMillis(), random.nextInt(10000)); if (grabTicket(zookeeper, lockNode, ticket)) { return ticket; } else { return takeQueueTicket(zookeeper, lockNode); } }
java
static String takeQueueTicket(ZooKeeper zookeeper, String lockNode) throws InterruptedException, KeeperException { // The ticket number includes a random component to decrease the chances of collision. Collision is handled // neatly, but it saves a few actions if there is no need to retry ticket acquisition. String ticket = String.format("nr-%014d-%04d", System.currentTimeMillis(), random.nextInt(10000)); if (grabTicket(zookeeper, lockNode, ticket)) { return ticket; } else { return takeQueueTicket(zookeeper, lockNode); } }
[ "static", "String", "takeQueueTicket", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ")", "throws", "InterruptedException", ",", "KeeperException", "{", "// The ticket number includes a random component to decrease the chances of collision. Collision is handled", "// neatly, but it saves a few actions if there is no need to retry ticket acquisition.", "String", "ticket", "=", "String", ".", "format", "(", "\"nr-%014d-%04d\"", ",", "System", ".", "currentTimeMillis", "(", ")", ",", "random", ".", "nextInt", "(", "10000", ")", ")", ";", "if", "(", "grabTicket", "(", "zookeeper", ",", "lockNode", ",", "ticket", ")", ")", "{", "return", "ticket", ";", "}", "else", "{", "return", "takeQueueTicket", "(", "zookeeper", ",", "lockNode", ")", ";", "}", "}" ]
Take a ticket for the queue. If the ticket was already claimed by another process, this method retries until it succeeds. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @return The claimed ticket.
[ "Take", "a", "ticket", "for", "the", "queue", ".", "If", "the", "ticket", "was", "already", "claimed", "by", "another", "process", "this", "method", "retries", "until", "it", "succeeds", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L185-L194
symphonyoss/messageml-utils
src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java
MessageMLParser.validateEntities
private static void validateEntities(org.w3c.dom.Element document, JsonNode entityJson) throws InvalidInputException, ProcessingException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nodes; try { XPathExpression expr = xpath.compile("//@data-entity-id"); nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ProcessingException("Internal error processing document tree: " + e.getMessage()); } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String entityId = ((org.w3c.dom.Attr) node).getValue(); JsonNode entityNode = entityJson.findPath(entityId); if (entityNode.isMissingNode()) { throw new InvalidInputException("Error processing EntityJSON: " + "no entity data provided for \"data-entity-id\"=\"" + entityId + "\""); } else if (!entityNode.isObject()) { throw new InvalidInputException("Error processing EntityJSON: " + "the node \"" + entityId + "\" has to be an object"); } } }
java
private static void validateEntities(org.w3c.dom.Element document, JsonNode entityJson) throws InvalidInputException, ProcessingException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nodes; try { XPathExpression expr = xpath.compile("//@data-entity-id"); nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ProcessingException("Internal error processing document tree: " + e.getMessage()); } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String entityId = ((org.w3c.dom.Attr) node).getValue(); JsonNode entityNode = entityJson.findPath(entityId); if (entityNode.isMissingNode()) { throw new InvalidInputException("Error processing EntityJSON: " + "no entity data provided for \"data-entity-id\"=\"" + entityId + "\""); } else if (!entityNode.isObject()) { throw new InvalidInputException("Error processing EntityJSON: " + "the node \"" + entityId + "\" has to be an object"); } } }
[ "private", "static", "void", "validateEntities", "(", "org", ".", "w3c", ".", "dom", ".", "Element", "document", ",", "JsonNode", "entityJson", ")", "throws", "InvalidInputException", ",", "ProcessingException", "{", "XPathFactory", "xPathfactory", "=", "XPathFactory", ".", "newInstance", "(", ")", ";", "XPath", "xpath", "=", "xPathfactory", ".", "newXPath", "(", ")", ";", "NodeList", "nodes", ";", "try", "{", "XPathExpression", "expr", "=", "xpath", ".", "compile", "(", "\"//@data-entity-id\"", ")", ";", "nodes", "=", "(", "NodeList", ")", "expr", ".", "evaluate", "(", "document", ",", "XPathConstants", ".", "NODESET", ")", ";", "}", "catch", "(", "XPathExpressionException", "e", ")", "{", "throw", "new", "ProcessingException", "(", "\"Internal error processing document tree: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "node", "=", "nodes", ".", "item", "(", "i", ")", ";", "String", "entityId", "=", "(", "(", "org", ".", "w3c", ".", "dom", ".", "Attr", ")", "node", ")", ".", "getValue", "(", ")", ";", "JsonNode", "entityNode", "=", "entityJson", ".", "findPath", "(", "entityId", ")", ";", "if", "(", "entityNode", ".", "isMissingNode", "(", ")", ")", "{", "throw", "new", "InvalidInputException", "(", "\"Error processing EntityJSON: \"", "+", "\"no entity data provided for \\\"data-entity-id\\\"=\\\"\"", "+", "entityId", "+", "\"\\\"\"", ")", ";", "}", "else", "if", "(", "!", "entityNode", ".", "isObject", "(", ")", ")", "{", "throw", "new", "InvalidInputException", "(", "\"Error processing EntityJSON: \"", "+", "\"the node \\\"\"", "+", "entityId", "+", "\"\\\" has to be an object\"", ")", ";", "}", "}", "}" ]
Check whether <i>data-entity-id</i> attributes in the message match EntityJSON entities.
[ "Check", "whether", "<i", ">", "data", "-", "entity", "-", "id<", "/", "i", ">", "attributes", "in", "the", "message", "match", "EntityJSON", "entities", "." ]
train
https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L142-L168
jingwei/krati
krati-main/src/main/java/krati/util/SourceWaterMarks.java
SourceWaterMarks.saveHWMark
public void saveHWMark(String source, long hwm) { WaterMarkEntry wmEntry = sourceWaterMarkMap.get(source); if (wmEntry != null) { wmEntry.setHWMScn(Math.max(hwm, wmEntry.getHWMScn())); } else { wmEntry = new WaterMarkEntry(source); wmEntry.setHWMScn(hwm); sourceWaterMarkMap.put(source, wmEntry); } }
java
public void saveHWMark(String source, long hwm) { WaterMarkEntry wmEntry = sourceWaterMarkMap.get(source); if (wmEntry != null) { wmEntry.setHWMScn(Math.max(hwm, wmEntry.getHWMScn())); } else { wmEntry = new WaterMarkEntry(source); wmEntry.setHWMScn(hwm); sourceWaterMarkMap.put(source, wmEntry); } }
[ "public", "void", "saveHWMark", "(", "String", "source", ",", "long", "hwm", ")", "{", "WaterMarkEntry", "wmEntry", "=", "sourceWaterMarkMap", ".", "get", "(", "source", ")", ";", "if", "(", "wmEntry", "!=", "null", ")", "{", "wmEntry", ".", "setHWMScn", "(", "Math", ".", "max", "(", "hwm", ",", "wmEntry", ".", "getHWMScn", "(", ")", ")", ")", ";", "}", "else", "{", "wmEntry", "=", "new", "WaterMarkEntry", "(", "source", ")", ";", "wmEntry", ".", "setHWMScn", "(", "hwm", ")", ";", "sourceWaterMarkMap", ".", "put", "(", "source", ",", "wmEntry", ")", ";", "}", "}" ]
Saves the high water mark of a source. This method has the same functionality as {@link #setHWMScn(String, long)}. @param source - the source @param hwm - the high water mark
[ "Saves", "the", "high", "water", "mark", "of", "a", "source", ".", "This", "method", "has", "the", "same", "functionality", "as", "{", "@link", "#setHWMScn", "(", "String", "long", ")", "}", "." ]
train
https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/util/SourceWaterMarks.java#L229-L239
intellimate/Izou
src/main/java/org/intellimate/izou/system/sound/SoundManager.java
SoundManager.addNonPermanent
private void addNonPermanent(AddOnModel addOnModel, IzouSoundLineBaseClass izouSoundLine) { debug("adding " + izouSoundLine + " from " + addOnModel + " to non-permanent"); if (izouSoundLine.isPermanent()) izouSoundLine.setToNonPermanent(); List<WeakReference<IzouSoundLineBaseClass>> weakReferences = nonPermanent.get(addOnModel); if (weakReferences == null) weakReferences = Collections.synchronizedList(new ArrayList<>()); nonPermanent.put(addOnModel, weakReferences); weakReferences.add(new WeakReference<>(izouSoundLine)); }
java
private void addNonPermanent(AddOnModel addOnModel, IzouSoundLineBaseClass izouSoundLine) { debug("adding " + izouSoundLine + " from " + addOnModel + " to non-permanent"); if (izouSoundLine.isPermanent()) izouSoundLine.setToNonPermanent(); List<WeakReference<IzouSoundLineBaseClass>> weakReferences = nonPermanent.get(addOnModel); if (weakReferences == null) weakReferences = Collections.synchronizedList(new ArrayList<>()); nonPermanent.put(addOnModel, weakReferences); weakReferences.add(new WeakReference<>(izouSoundLine)); }
[ "private", "void", "addNonPermanent", "(", "AddOnModel", "addOnModel", ",", "IzouSoundLineBaseClass", "izouSoundLine", ")", "{", "debug", "(", "\"adding \"", "+", "izouSoundLine", "+", "\" from \"", "+", "addOnModel", "+", "\" to non-permanent\"", ")", ";", "if", "(", "izouSoundLine", ".", "isPermanent", "(", ")", ")", "izouSoundLine", ".", "setToNonPermanent", "(", ")", ";", "List", "<", "WeakReference", "<", "IzouSoundLineBaseClass", ">", ">", "weakReferences", "=", "nonPermanent", ".", "get", "(", "addOnModel", ")", ";", "if", "(", "weakReferences", "==", "null", ")", "weakReferences", "=", "Collections", ".", "synchronizedList", "(", "new", "ArrayList", "<>", "(", ")", ")", ";", "nonPermanent", ".", "put", "(", "addOnModel", ",", "weakReferences", ")", ";", "weakReferences", ".", "add", "(", "new", "WeakReference", "<>", "(", "izouSoundLine", ")", ")", ";", "}" ]
adds the IzouSoundLine as NonPermanent @param addOnModel the AddonModel to @param izouSoundLine the IzouSoundLine to add
[ "adds", "the", "IzouSoundLine", "as", "NonPermanent" ]
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/system/sound/SoundManager.java#L227-L236
kiegroup/droolsjbpm-integration
kie-spring-boot/kie-spring-boot-autoconfiguration/kie-server-spring-boot-autoconfiguration-jbpm/src/main/java/org/kie/server/springboot/jbpm/ContainerAliasResolver.java
ContainerAliasResolver.forTaskInstance
public String forTaskInstance(String alias, long taskId) { return registry.getContainerId(alias, new ByTaskIdContainerLocator(taskId)); }
java
public String forTaskInstance(String alias, long taskId) { return registry.getContainerId(alias, new ByTaskIdContainerLocator(taskId)); }
[ "public", "String", "forTaskInstance", "(", "String", "alias", ",", "long", "taskId", ")", "{", "return", "registry", ".", "getContainerId", "(", "alias", ",", "new", "ByTaskIdContainerLocator", "(", "taskId", ")", ")", ";", "}" ]
Looks up container id for given alias that is associated with task instance @param alias container alias @param taskId unique task instance id @return @throws IllegalArgumentException in case there are no containers for given alias
[ "Looks", "up", "container", "id", "for", "given", "alias", "that", "is", "associated", "with", "task", "instance" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-spring-boot/kie-spring-boot-autoconfiguration/kie-server-spring-boot-autoconfiguration-jbpm/src/main/java/org/kie/server/springboot/jbpm/ContainerAliasResolver.java#L76-L78
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java
SARLQuickfixProvider.fixIncompatibleReturnType
@Fix(org.eclipse.xtext.xbase.validation.IssueCodes.INCOMPATIBLE_RETURN_TYPE) public void fixIncompatibleReturnType(final Issue issue, IssueResolutionAcceptor acceptor) { ReturnTypeReplaceModification.accept(this, issue, acceptor); }
java
@Fix(org.eclipse.xtext.xbase.validation.IssueCodes.INCOMPATIBLE_RETURN_TYPE) public void fixIncompatibleReturnType(final Issue issue, IssueResolutionAcceptor acceptor) { ReturnTypeReplaceModification.accept(this, issue, acceptor); }
[ "@", "Fix", "(", "org", ".", "eclipse", ".", "xtext", ".", "xbase", ".", "validation", ".", "IssueCodes", ".", "INCOMPATIBLE_RETURN_TYPE", ")", "public", "void", "fixIncompatibleReturnType", "(", "final", "Issue", "issue", ",", "IssueResolutionAcceptor", "acceptor", ")", "{", "ReturnTypeReplaceModification", ".", "accept", "(", "this", ",", "issue", ",", "acceptor", ")", ";", "}" ]
Quick fix for "Incompatible return type". @param issue the issue. @param acceptor the quick fix acceptor.
[ "Quick", "fix", "for", "Incompatible", "return", "type", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L866-L869
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createNiceMock
public static <T> T createNiceMock(Class<T> type, Object... constructorArguments) { Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new NiceMockStrategy(), constructorArgs, (Method[]) null); }
java
public static <T> T createNiceMock(Class<T> type, Object... constructorArguments) { Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new NiceMockStrategy(), constructorArgs, (Method[]) null); }
[ "public", "static", "<", "T", ">", "T", "createNiceMock", "(", "Class", "<", "T", ">", "type", ",", "Object", "...", "constructorArguments", ")", "{", "Constructor", "<", "?", ">", "constructor", "=", "WhiteboxImpl", ".", "findUniqueConstructorOrThrowException", "(", "type", ",", "constructorArguments", ")", ";", "ConstructorArgs", "constructorArgs", "=", "new", "ConstructorArgs", "(", "constructor", ",", "constructorArguments", ")", ";", "return", "doMock", "(", "type", ",", "false", ",", "new", "NiceMockStrategy", "(", ")", ",", "constructorArgs", ",", "(", "Method", "[", "]", ")", "null", ")", ";", "}" ]
Creates a nice mock object that supports mocking of final and native methods and invokes a specific constructor based on the supplied argument values. @param <T> the type of the mock object @param type the type of the mock object @param constructorArguments The constructor arguments that will be used to invoke a certain constructor. @return the mock object.
[ "Creates", "a", "nice", "mock", "object", "that", "supports", "mocking", "of", "final", "and", "native", "methods", "and", "invokes", "a", "specific", "constructor", "based", "on", "the", "supplied", "argument", "values", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L237-L241
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/Name.java
Name.simple
@VisibleForTesting static Name simple(String name) { switch (name) { case ".": return SELF; case "..": return PARENT; default: return new Name(name, name); } }
java
@VisibleForTesting static Name simple(String name) { switch (name) { case ".": return SELF; case "..": return PARENT; default: return new Name(name, name); } }
[ "@", "VisibleForTesting", "static", "Name", "simple", "(", "String", "name", ")", "{", "switch", "(", "name", ")", "{", "case", "\".\"", ":", "return", "SELF", ";", "case", "\"..\"", ":", "return", "PARENT", ";", "default", ":", "return", "new", "Name", "(", "name", ",", "name", ")", ";", "}", "}" ]
Creates a new name with no normalization done on the given string.
[ "Creates", "a", "new", "name", "with", "no", "normalization", "done", "on", "the", "given", "string", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/Name.java#L52-L62
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseOpticalFlowKlt.java
DenseOpticalFlowKlt.checkNeighbors
protected void checkNeighbors( int cx , int cy , float score , float flowX , float flowY , ImageFlow output ) { int x0 = Math.max(0,cx-regionRadius); int x1 = Math.min(output.width, cx + regionRadius + 1); int y0 = Math.max(0,cy-regionRadius); int y1 = Math.min(output.height, cy + regionRadius + 1); for( int i = y0; i < y1; i++ ) { int index = width*i + x0; for( int j = x0; j < x1; j++ , index++ ) { float s = scores[ index ]; ImageFlow.D f = output.data[index]; if( s > score ) { f.set(flowX,flowY); scores[index] = score; } else if( s == score ) { // Pick solution with the least motion when ambiguous float m0 = f.x*f.x + f.y*f.y; float m1 = flowX*flowX + flowY*flowY; if( m1 < m0 ) { f.set(flowX,flowY); scores[index] = score; } } } } }
java
protected void checkNeighbors( int cx , int cy , float score , float flowX , float flowY , ImageFlow output ) { int x0 = Math.max(0,cx-regionRadius); int x1 = Math.min(output.width, cx + regionRadius + 1); int y0 = Math.max(0,cy-regionRadius); int y1 = Math.min(output.height, cy + regionRadius + 1); for( int i = y0; i < y1; i++ ) { int index = width*i + x0; for( int j = x0; j < x1; j++ , index++ ) { float s = scores[ index ]; ImageFlow.D f = output.data[index]; if( s > score ) { f.set(flowX,flowY); scores[index] = score; } else if( s == score ) { // Pick solution with the least motion when ambiguous float m0 = f.x*f.x + f.y*f.y; float m1 = flowX*flowX + flowY*flowY; if( m1 < m0 ) { f.set(flowX,flowY); scores[index] = score; } } } } }
[ "protected", "void", "checkNeighbors", "(", "int", "cx", ",", "int", "cy", ",", "float", "score", ",", "float", "flowX", ",", "float", "flowY", ",", "ImageFlow", "output", ")", "{", "int", "x0", "=", "Math", ".", "max", "(", "0", ",", "cx", "-", "regionRadius", ")", ";", "int", "x1", "=", "Math", ".", "min", "(", "output", ".", "width", ",", "cx", "+", "regionRadius", "+", "1", ")", ";", "int", "y0", "=", "Math", ".", "max", "(", "0", ",", "cy", "-", "regionRadius", ")", ";", "int", "y1", "=", "Math", ".", "min", "(", "output", ".", "height", ",", "cy", "+", "regionRadius", "+", "1", ")", ";", "for", "(", "int", "i", "=", "y0", ";", "i", "<", "y1", ";", "i", "++", ")", "{", "int", "index", "=", "width", "*", "i", "+", "x0", ";", "for", "(", "int", "j", "=", "x0", ";", "j", "<", "x1", ";", "j", "++", ",", "index", "++", ")", "{", "float", "s", "=", "scores", "[", "index", "]", ";", "ImageFlow", ".", "D", "f", "=", "output", ".", "data", "[", "index", "]", ";", "if", "(", "s", ">", "score", ")", "{", "f", ".", "set", "(", "flowX", ",", "flowY", ")", ";", "scores", "[", "index", "]", "=", "score", ";", "}", "else", "if", "(", "s", "==", "score", ")", "{", "// Pick solution with the least motion when ambiguous", "float", "m0", "=", "f", ".", "x", "*", "f", ".", "x", "+", "f", ".", "y", "*", "f", ".", "y", ";", "float", "m1", "=", "flowX", "*", "flowX", "+", "flowY", "*", "flowY", ";", "if", "(", "m1", "<", "m0", ")", "{", "f", ".", "set", "(", "flowX", ",", "flowY", ")", ";", "scores", "[", "index", "]", "=", "score", ";", "}", "}", "}", "}", "}" ]
Examines every pixel inside the region centered at (cx,cy) to see if their optical flow has a worse score the one specified in 'flow'
[ "Examines", "every", "pixel", "inside", "the", "region", "centered", "at", "(", "cx", "cy", ")", "to", "see", "if", "their", "optical", "flow", "has", "a", "worse", "score", "the", "one", "specified", "in", "flow" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseOpticalFlowKlt.java#L105-L131
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java
StringUtilities.checkSameName
public static String checkSameName( List<String> strings, String string ) { int index = 1; for( int i = 0; i < strings.size(); i++ ) { if (index == 10000) { // something odd is going on throw new RuntimeException(); } String existingString = strings.get(i); existingString = existingString.trim(); if (existingString.trim().equals(string.trim())) { // name exists, change the name of the entering if (string.endsWith(")")) { string = string.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { string = string + " (" + (index++) + ")"; } // start again i = 0; } } return string; }
java
public static String checkSameName( List<String> strings, String string ) { int index = 1; for( int i = 0; i < strings.size(); i++ ) { if (index == 10000) { // something odd is going on throw new RuntimeException(); } String existingString = strings.get(i); existingString = existingString.trim(); if (existingString.trim().equals(string.trim())) { // name exists, change the name of the entering if (string.endsWith(")")) { string = string.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { string = string + " (" + (index++) + ")"; } // start again i = 0; } } return string; }
[ "public", "static", "String", "checkSameName", "(", "List", "<", "String", ">", "strings", ",", "String", "string", ")", "{", "int", "index", "=", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "strings", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "index", "==", "10000", ")", "{", "// something odd is going on", "throw", "new", "RuntimeException", "(", ")", ";", "}", "String", "existingString", "=", "strings", ".", "get", "(", "i", ")", ";", "existingString", "=", "existingString", ".", "trim", "(", ")", ";", "if", "(", "existingString", ".", "trim", "(", ")", ".", "equals", "(", "string", ".", "trim", "(", ")", ")", ")", "{", "// name exists, change the name of the entering", "if", "(", "string", ".", "endsWith", "(", "\")\"", ")", ")", "{", "string", "=", "string", ".", "trim", "(", ")", ".", "replaceFirst", "(", "\"\\\\([0-9]+\\\\)$\"", ",", "\"(\"", "+", "(", "index", "++", ")", "+", "\")\"", ")", ";", "}", "else", "{", "string", "=", "string", "+", "\" (\"", "+", "(", "index", "++", ")", "+", "\")\"", ";", "}", "// start again", "i", "=", "0", ";", "}", "}", "return", "string", ";", "}" ]
Checks if the list of strings supplied contains the supplied string. <p>If the string is contained it changes the name by adding a number. <p>The spaces are trimmed away before performing name equality. @param strings the list of existing strings. @param string the proposed new string, to be changed if colliding. @return the new non-colliding name for the string.
[ "Checks", "if", "the", "list", "of", "strings", "supplied", "contains", "the", "supplied", "string", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java#L47-L68
zaproxy/zaproxy
src/org/zaproxy/zap/control/AddOn.java
AddOn.versionMatches
private static boolean versionMatches(AddOn addOn, AddOnDep dependency) { if (addOn.version.matches(dependency.getVersion())) { return true; } if (addOn.semVer != null && addOn.semVer.matches(dependency.getVersion())) { return true; } return false; }
java
private static boolean versionMatches(AddOn addOn, AddOnDep dependency) { if (addOn.version.matches(dependency.getVersion())) { return true; } if (addOn.semVer != null && addOn.semVer.matches(dependency.getVersion())) { return true; } return false; }
[ "private", "static", "boolean", "versionMatches", "(", "AddOn", "addOn", ",", "AddOnDep", "dependency", ")", "{", "if", "(", "addOn", ".", "version", ".", "matches", "(", "dependency", ".", "getVersion", "(", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "addOn", ".", "semVer", "!=", "null", "&&", "addOn", ".", "semVer", ".", "matches", "(", "dependency", ".", "getVersion", "(", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Tells whether or not the given add-on version matches the one required by the dependency. <p> This methods is required to also check the {@code semVer} of the add-on, once removed it can match the version directly. @param addOn the add-on to check @param dependency the dependency @return {@code true} if the version matches, {@code false} otherwise.
[ "Tells", "whether", "or", "not", "the", "given", "add", "-", "on", "version", "matches", "the", "one", "required", "by", "the", "dependency", ".", "<p", ">", "This", "methods", "is", "required", "to", "also", "check", "the", "{", "@code", "semVer", "}", "of", "the", "add", "-", "on", "once", "removed", "it", "can", "match", "the", "version", "directly", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/control/AddOn.java#L1424-L1434
selendroid/selendroid
selendroid-server/src/main/java/io/selendroid/server/extension/ExtensionLoader.java
ExtensionLoader.loadHandler
public BaseRequestHandler loadHandler(String handlerClassName, String uri) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<? extends BaseRequestHandler> handlerClass = classLoader.loadClass(handlerClassName).asSubclass(BaseRequestHandler.class); Constructor<? extends BaseRequestHandler> constructor = handlerClass.getConstructor(String.class); return constructor.newInstance(uri); }
java
public BaseRequestHandler loadHandler(String handlerClassName, String uri) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<? extends BaseRequestHandler> handlerClass = classLoader.loadClass(handlerClassName).asSubclass(BaseRequestHandler.class); Constructor<? extends BaseRequestHandler> constructor = handlerClass.getConstructor(String.class); return constructor.newInstance(uri); }
[ "public", "BaseRequestHandler", "loadHandler", "(", "String", "handlerClassName", ",", "String", "uri", ")", "throws", "ClassNotFoundException", ",", "NoSuchMethodException", ",", "IllegalAccessException", ",", "InvocationTargetException", ",", "InstantiationException", "{", "Class", "<", "?", "extends", "BaseRequestHandler", ">", "handlerClass", "=", "classLoader", ".", "loadClass", "(", "handlerClassName", ")", ".", "asSubclass", "(", "BaseRequestHandler", ".", "class", ")", ";", "Constructor", "<", "?", "extends", "BaseRequestHandler", ">", "constructor", "=", "handlerClass", ".", "getConstructor", "(", "String", ".", "class", ")", ";", "return", "constructor", ".", "newInstance", "(", "uri", ")", ";", "}" ]
Loads a {@link BaseRequestHandler} class from the extension dex.
[ "Loads", "a", "{" ]
train
https://github.com/selendroid/selendroid/blob/a32c1a96c973b80c14a588b1075f084201f7fe94/selendroid-server/src/main/java/io/selendroid/server/extension/ExtensionLoader.java#L110-L119
Azure/azure-sdk-for-java
redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/PatchSchedulesInner.java
PatchSchedulesInner.listByRedisResourceAsync
public Observable<Page<RedisPatchScheduleInner>> listByRedisResourceAsync(final String resourceGroupName, final String cacheName) { return listByRedisResourceWithServiceResponseAsync(resourceGroupName, cacheName) .map(new Func1<ServiceResponse<Page<RedisPatchScheduleInner>>, Page<RedisPatchScheduleInner>>() { @Override public Page<RedisPatchScheduleInner> call(ServiceResponse<Page<RedisPatchScheduleInner>> response) { return response.body(); } }); }
java
public Observable<Page<RedisPatchScheduleInner>> listByRedisResourceAsync(final String resourceGroupName, final String cacheName) { return listByRedisResourceWithServiceResponseAsync(resourceGroupName, cacheName) .map(new Func1<ServiceResponse<Page<RedisPatchScheduleInner>>, Page<RedisPatchScheduleInner>>() { @Override public Page<RedisPatchScheduleInner> call(ServiceResponse<Page<RedisPatchScheduleInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "RedisPatchScheduleInner", ">", ">", "listByRedisResourceAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "cacheName", ")", "{", "return", "listByRedisResourceWithServiceResponseAsync", "(", "resourceGroupName", ",", "cacheName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "RedisPatchScheduleInner", ">", ">", ",", "Page", "<", "RedisPatchScheduleInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "RedisPatchScheduleInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "RedisPatchScheduleInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets all patch schedules in the specified redis cache (there is only one). @param resourceGroupName The name of the resource group. @param cacheName The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RedisPatchScheduleInner&gt; object
[ "Gets", "all", "patch", "schedules", "in", "the", "specified", "redis", "cache", "(", "there", "is", "only", "one", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/PatchSchedulesInner.java#L137-L145
Waikato/moa
moa/src/main/java/moa/gui/visualization/GraphScatter.java
GraphScatter.scatter
private void scatter(Graphics g, int i) { int height = getHeight(); int width = getWidth(); int x = (int)(((this.variedParamValues[i] - this.lower_x_value) / (this.upper_x_value - this.lower_x_value)) * width); double value = this.measures[i].getLastValue(this.measureSelected); if(Double.isNaN(value)){ // no result for this budget yet return; } int y = (int)(height - (value / this.upper_y_value) * height); g.setColor(this.colors[i]); if (this.isStandardDeviationPainted) { int len = (int) ((this.measureStds[i].getLastValue(this.measureSelected)/this.upper_y_value)*height); paintStandardDeviation(g, len, x, y); } g.fillOval(x - DOT_SIZE/2, y - DOT_SIZE/2, DOT_SIZE, DOT_SIZE); }
java
private void scatter(Graphics g, int i) { int height = getHeight(); int width = getWidth(); int x = (int)(((this.variedParamValues[i] - this.lower_x_value) / (this.upper_x_value - this.lower_x_value)) * width); double value = this.measures[i].getLastValue(this.measureSelected); if(Double.isNaN(value)){ // no result for this budget yet return; } int y = (int)(height - (value / this.upper_y_value) * height); g.setColor(this.colors[i]); if (this.isStandardDeviationPainted) { int len = (int) ((this.measureStds[i].getLastValue(this.measureSelected)/this.upper_y_value)*height); paintStandardDeviation(g, len, x, y); } g.fillOval(x - DOT_SIZE/2, y - DOT_SIZE/2, DOT_SIZE, DOT_SIZE); }
[ "private", "void", "scatter", "(", "Graphics", "g", ",", "int", "i", ")", "{", "int", "height", "=", "getHeight", "(", ")", ";", "int", "width", "=", "getWidth", "(", ")", ";", "int", "x", "=", "(", "int", ")", "(", "(", "(", "this", ".", "variedParamValues", "[", "i", "]", "-", "this", ".", "lower_x_value", ")", "/", "(", "this", ".", "upper_x_value", "-", "this", ".", "lower_x_value", ")", ")", "*", "width", ")", ";", "double", "value", "=", "this", ".", "measures", "[", "i", "]", ".", "getLastValue", "(", "this", ".", "measureSelected", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "value", ")", ")", "{", "// no result for this budget yet", "return", ";", "}", "int", "y", "=", "(", "int", ")", "(", "height", "-", "(", "value", "/", "this", ".", "upper_y_value", ")", "*", "height", ")", ";", "g", ".", "setColor", "(", "this", ".", "colors", "[", "i", "]", ")", ";", "if", "(", "this", ".", "isStandardDeviationPainted", ")", "{", "int", "len", "=", "(", "int", ")", "(", "(", "this", ".", "measureStds", "[", "i", "]", ".", "getLastValue", "(", "this", ".", "measureSelected", ")", "/", "this", ".", "upper_y_value", ")", "*", "height", ")", ";", "paintStandardDeviation", "(", "g", ",", "len", ",", "x", ",", "y", ")", ";", "}", "g", ".", "fillOval", "(", "x", "-", "DOT_SIZE", "/", "2", ",", "y", "-", "DOT_SIZE", "/", "2", ",", "DOT_SIZE", ",", "DOT_SIZE", ")", ";", "}" ]
Paint a dot onto the panel. @param g graphics object @param i index of the varied parameter
[ "Paint", "a", "dot", "onto", "the", "panel", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/GraphScatter.java#L76-L100
apereo/cas
core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/RegisteredServiceAccessStrategyUtils.java
RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService
static void ensurePrincipalAccessIsAllowedForService(final Service service, final RegisteredService registeredService, final String principalId, final Map<String, Object> attributes) { ensureServiceAccessIsAllowed(service, registeredService); if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principalId, attributes)) { LOGGER.warn("Cannot grant access to service [{}] because it is not authorized for use by [{}].", service.getId(), principalId); val handlerErrors = new HashMap<String, Throwable>(); val message = String.format("Cannot grant service access to %s", principalId); val exception = new UnauthorizedServiceForPrincipalException(message, registeredService, principalId, attributes); handlerErrors.put(UnauthorizedServiceForPrincipalException.class.getSimpleName(), exception); throw new PrincipalException(UnauthorizedServiceForPrincipalException.CODE_UNAUTHZ_SERVICE, handlerErrors, new HashMap<>()); } }
java
static void ensurePrincipalAccessIsAllowedForService(final Service service, final RegisteredService registeredService, final String principalId, final Map<String, Object> attributes) { ensureServiceAccessIsAllowed(service, registeredService); if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principalId, attributes)) { LOGGER.warn("Cannot grant access to service [{}] because it is not authorized for use by [{}].", service.getId(), principalId); val handlerErrors = new HashMap<String, Throwable>(); val message = String.format("Cannot grant service access to %s", principalId); val exception = new UnauthorizedServiceForPrincipalException(message, registeredService, principalId, attributes); handlerErrors.put(UnauthorizedServiceForPrincipalException.class.getSimpleName(), exception); throw new PrincipalException(UnauthorizedServiceForPrincipalException.CODE_UNAUTHZ_SERVICE, handlerErrors, new HashMap<>()); } }
[ "static", "void", "ensurePrincipalAccessIsAllowedForService", "(", "final", "Service", "service", ",", "final", "RegisteredService", "registeredService", ",", "final", "String", "principalId", ",", "final", "Map", "<", "String", ",", "Object", ">", "attributes", ")", "{", "ensureServiceAccessIsAllowed", "(", "service", ",", "registeredService", ")", ";", "if", "(", "!", "registeredService", ".", "getAccessStrategy", "(", ")", ".", "doPrincipalAttributesAllowServiceAccess", "(", "principalId", ",", "attributes", ")", ")", "{", "LOGGER", ".", "warn", "(", "\"Cannot grant access to service [{}] because it is not authorized for use by [{}].\"", ",", "service", ".", "getId", "(", ")", ",", "principalId", ")", ";", "val", "handlerErrors", "=", "new", "HashMap", "<", "String", ",", "Throwable", ">", "(", ")", ";", "val", "message", "=", "String", ".", "format", "(", "\"Cannot grant service access to %s\"", ",", "principalId", ")", ";", "val", "exception", "=", "new", "UnauthorizedServiceForPrincipalException", "(", "message", ",", "registeredService", ",", "principalId", ",", "attributes", ")", ";", "handlerErrors", ".", "put", "(", "UnauthorizedServiceForPrincipalException", ".", "class", ".", "getSimpleName", "(", ")", ",", "exception", ")", ";", "throw", "new", "PrincipalException", "(", "UnauthorizedServiceForPrincipalException", ".", "CODE_UNAUTHZ_SERVICE", ",", "handlerErrors", ",", "new", "HashMap", "<>", "(", ")", ")", ";", "}", "}" ]
Ensure principal access is allowed for service. @param service the service @param registeredService the registered service @param principalId the principal id @param attributes the attributes
[ "Ensure", "principal", "access", "is", "allowed", "for", "service", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-api/src/main/java/org/apereo/cas/services/RegisteredServiceAccessStrategyUtils.java#L96-L110
diffplug/durian
src/com/diffplug/common/base/Either.java
Either.acceptBoth
public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) { left.accept(isLeft() ? getLeft() : defaultLeft); right.accept(isRight() ? getRight() : defaultRight); }
java
public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) { left.accept(isLeft() ? getLeft() : defaultLeft); right.accept(isRight() ? getRight() : defaultRight); }
[ "public", "final", "void", "acceptBoth", "(", "Consumer", "<", "?", "super", "L", ">", "left", ",", "Consumer", "<", "?", "super", "R", ">", "right", ",", "L", "defaultLeft", ",", "R", "defaultRight", ")", "{", "left", ".", "accept", "(", "isLeft", "(", ")", "?", "getLeft", "(", ")", ":", "defaultLeft", ")", ";", "right", ".", "accept", "(", "isRight", "(", ")", "?", "getRight", "(", ")", ":", "defaultRight", ")", ";", "}" ]
Accepts both the left and right consumers, using the default values to set the empty side.
[ "Accepts", "both", "the", "left", "and", "right", "consumers", "using", "the", "default", "values", "to", "set", "the", "empty", "side", "." ]
train
https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/Either.java#L104-L107
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_outplanNotification_POST
public OvhConsumptionThreshold billingAccount_outplanNotification_POST(String billingAccount, OvhOutplanNotificationBlockEnum block, String notifyEmail, Double percentage) throws IOException { String qPath = "/telephony/{billingAccount}/outplanNotification"; StringBuilder sb = path(qPath, billingAccount); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "block", block); addBody(o, "notifyEmail", notifyEmail); addBody(o, "percentage", percentage); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhConsumptionThreshold.class); }
java
public OvhConsumptionThreshold billingAccount_outplanNotification_POST(String billingAccount, OvhOutplanNotificationBlockEnum block, String notifyEmail, Double percentage) throws IOException { String qPath = "/telephony/{billingAccount}/outplanNotification"; StringBuilder sb = path(qPath, billingAccount); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "block", block); addBody(o, "notifyEmail", notifyEmail); addBody(o, "percentage", percentage); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhConsumptionThreshold.class); }
[ "public", "OvhConsumptionThreshold", "billingAccount_outplanNotification_POST", "(", "String", "billingAccount", ",", "OvhOutplanNotificationBlockEnum", "block", ",", "String", "notifyEmail", ",", "Double", "percentage", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/outplanNotification\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"block\"", ",", "block", ")", ";", "addBody", "(", "o", ",", "\"notifyEmail\"", ",", "notifyEmail", ")", ";", "addBody", "(", "o", ",", "\"percentage\"", ",", "percentage", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhConsumptionThreshold", ".", "class", ")", ";", "}" ]
Add an outplan notification on the billing account REST: POST /telephony/{billingAccount}/outplanNotification @param percentage [required] The notification percentage of maximum outplan @param block [required] The blocking type of the associate lines @param notifyEmail [required] Override the nichandle email for this notification @param billingAccount [required] The name of your billingAccount
[ "Add", "an", "outplan", "notification", "on", "the", "billing", "account" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L8328-L8337
fuinorg/objects4j
src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java
TableColumnInfo.create
public static TableColumnInfo create(@NotNull final Field field, @NotNull final Locale locale) { Contract.requireArgNotNull("field", field); Contract.requireArgNotNull("locale", locale); final TableColumn tableColumn = field.getAnnotation(TableColumn.class); if (tableColumn == null) { return null; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer(); final FieldTextInfo labelInfo = analyzer.createFieldInfo(field, locale, Label.class); final FieldTextInfo shortLabelInfo = analyzer.createFieldInfo(field, locale, ShortLabel.class); final FieldTextInfo tooltipInfo = analyzer.createFieldInfo(field, locale, Tooltip.class); final int pos = tableColumn.pos(); final FontSize fontSize = new FontSize(tableColumn.width(), tableColumn.unit()); final String getter = getGetter(tableColumn, field.getName()); final String labelText; if (labelInfo == null) { labelText = null; } else { labelText = labelInfo.getTextOrField(); } final String shortLabelText; if (shortLabelInfo == null) { shortLabelText = null; } else { shortLabelText = shortLabelInfo.getText(); } final String tooltipText; if (tooltipInfo == null) { tooltipText = null; } else { tooltipText = tooltipInfo.getText(); } return new TableColumnInfo(field, labelText, shortLabelText, tooltipText, pos, fontSize, getter); }
java
public static TableColumnInfo create(@NotNull final Field field, @NotNull final Locale locale) { Contract.requireArgNotNull("field", field); Contract.requireArgNotNull("locale", locale); final TableColumn tableColumn = field.getAnnotation(TableColumn.class); if (tableColumn == null) { return null; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer(); final FieldTextInfo labelInfo = analyzer.createFieldInfo(field, locale, Label.class); final FieldTextInfo shortLabelInfo = analyzer.createFieldInfo(field, locale, ShortLabel.class); final FieldTextInfo tooltipInfo = analyzer.createFieldInfo(field, locale, Tooltip.class); final int pos = tableColumn.pos(); final FontSize fontSize = new FontSize(tableColumn.width(), tableColumn.unit()); final String getter = getGetter(tableColumn, field.getName()); final String labelText; if (labelInfo == null) { labelText = null; } else { labelText = labelInfo.getTextOrField(); } final String shortLabelText; if (shortLabelInfo == null) { shortLabelText = null; } else { shortLabelText = shortLabelInfo.getText(); } final String tooltipText; if (tooltipInfo == null) { tooltipText = null; } else { tooltipText = tooltipInfo.getText(); } return new TableColumnInfo(field, labelText, shortLabelText, tooltipText, pos, fontSize, getter); }
[ "public", "static", "TableColumnInfo", "create", "(", "@", "NotNull", "final", "Field", "field", ",", "@", "NotNull", "final", "Locale", "locale", ")", "{", "Contract", ".", "requireArgNotNull", "(", "\"field\"", ",", "field", ")", ";", "Contract", ".", "requireArgNotNull", "(", "\"locale\"", ",", "locale", ")", ";", "final", "TableColumn", "tableColumn", "=", "field", ".", "getAnnotation", "(", "TableColumn", ".", "class", ")", ";", "if", "(", "tableColumn", "==", "null", ")", "{", "return", "null", ";", "}", "final", "AnnotationAnalyzer", "analyzer", "=", "new", "AnnotationAnalyzer", "(", ")", ";", "final", "FieldTextInfo", "labelInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "Label", ".", "class", ")", ";", "final", "FieldTextInfo", "shortLabelInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "ShortLabel", ".", "class", ")", ";", "final", "FieldTextInfo", "tooltipInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "Tooltip", ".", "class", ")", ";", "final", "int", "pos", "=", "tableColumn", ".", "pos", "(", ")", ";", "final", "FontSize", "fontSize", "=", "new", "FontSize", "(", "tableColumn", ".", "width", "(", ")", ",", "tableColumn", ".", "unit", "(", ")", ")", ";", "final", "String", "getter", "=", "getGetter", "(", "tableColumn", ",", "field", ".", "getName", "(", ")", ")", ";", "final", "String", "labelText", ";", "if", "(", "labelInfo", "==", "null", ")", "{", "labelText", "=", "null", ";", "}", "else", "{", "labelText", "=", "labelInfo", ".", "getTextOrField", "(", ")", ";", "}", "final", "String", "shortLabelText", ";", "if", "(", "shortLabelInfo", "==", "null", ")", "{", "shortLabelText", "=", "null", ";", "}", "else", "{", "shortLabelText", "=", "shortLabelInfo", ".", "getText", "(", ")", ";", "}", "final", "String", "tooltipText", ";", "if", "(", "tooltipInfo", "==", "null", ")", "{", "tooltipText", "=", "null", ";", "}", "else", "{", "tooltipText", "=", "tooltipInfo", ".", "getText", "(", ")", ";", "}", "return", "new", "TableColumnInfo", "(", "field", ",", "labelText", ",", "shortLabelText", ",", "tooltipText", ",", "pos", ",", "fontSize", ",", "getter", ")", ";", "}" ]
Return the table column information for a given field. @param field Field to check for <code>@TableColumn</code> and <code>@Label</code> annotations. @param locale Locale to use. @return Information or <code>null</code>.
[ "Return", "the", "table", "column", "information", "for", "a", "given", "field", "." ]
train
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java#L241-L281
autermann/yaml
src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java
YamlMappingNode.put
public T put(YamlNode key, byte value) { return put(key, getNodeFactory().byteNode(value)); }
java
public T put(YamlNode key, byte value) { return put(key, getNodeFactory().byteNode(value)); }
[ "public", "T", "put", "(", "YamlNode", "key", ",", "byte", "value", ")", "{", "return", "put", "(", "key", ",", "getNodeFactory", "(", ")", ".", "byteNode", "(", "value", ")", ")", ";", "}" ]
Adds the specified {@code key}/{@code value} pair to this mapping. @param key the key @param value the value @return {@code this}
[ "Adds", "the", "specified", "{", "@code", "key", "}", "/", "{", "@code", "value", "}", "pair", "to", "this", "mapping", "." ]
train
https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L420-L422
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.subtractInPlace
public static <E> void subtractInPlace(double[] target, Counter<E> arg, Index<E> idx) { for (Map.Entry<E, Double> entry : arg.entrySet()) { target[idx.indexOf(entry.getKey())] -= entry.getValue(); } }
java
public static <E> void subtractInPlace(double[] target, Counter<E> arg, Index<E> idx) { for (Map.Entry<E, Double> entry : arg.entrySet()) { target[idx.indexOf(entry.getKey())] -= entry.getValue(); } }
[ "public", "static", "<", "E", ">", "void", "subtractInPlace", "(", "double", "[", "]", "target", ",", "Counter", "<", "E", ">", "arg", ",", "Index", "<", "E", ">", "idx", ")", "{", "for", "(", "Map", ".", "Entry", "<", "E", ",", "Double", ">", "entry", ":", "arg", ".", "entrySet", "(", ")", ")", "{", "target", "[", "idx", ".", "indexOf", "(", "entry", ".", "getKey", "(", ")", ")", "]", "-=", "entry", ".", "getValue", "(", ")", ";", "}", "}" ]
Sets each value of double[] target to be target[idx.indexOf(k)]-a.getCount(k) for all keys k in arg
[ "Sets", "each", "value", "of", "double", "[]", "target", "to", "be", "target", "[", "idx", ".", "indexOf", "(", "k", ")", "]", "-", "a", ".", "getCount", "(", "k", ")", "for", "all", "keys", "k", "in", "arg" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L402-L406
JadiraOrg/jadira
cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java
UnsafeOperations.deepCopyObjectField
public final void deepCopyObjectField(Object obj, Object copy, Field field) { deepCopyObjectAtOffset(obj, copy, field.getType(), getObjectFieldOffset(field), new IdentityHashMap<Object, Object>(100)); }
java
public final void deepCopyObjectField(Object obj, Object copy, Field field) { deepCopyObjectAtOffset(obj, copy, field.getType(), getObjectFieldOffset(field), new IdentityHashMap<Object, Object>(100)); }
[ "public", "final", "void", "deepCopyObjectField", "(", "Object", "obj", ",", "Object", "copy", ",", "Field", "field", ")", "{", "deepCopyObjectAtOffset", "(", "obj", ",", "copy", ",", "field", ".", "getType", "(", ")", ",", "getObjectFieldOffset", "(", "field", ")", ",", "new", "IdentityHashMap", "<", "Object", ",", "Object", ">", "(", "100", ")", ")", ";", "}" ]
Copies the object of the specified type from the given field in the source object to the same field in the copy, visiting the object during the copy so that its fields are also copied @param obj The object to copy from @param copy The target object @param field Field to be copied
[ "Copies", "the", "object", "of", "the", "specified", "type", "from", "the", "given", "field", "in", "the", "source", "object", "to", "the", "same", "field", "in", "the", "copy", "visiting", "the", "object", "during", "the", "copy", "so", "that", "its", "fields", "are", "also", "copied" ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java#L441-L444
berkesa/datatree
src/main/java/io/datatree/Tree.java
Tree.putMap
public Tree putMap(String path) { return putObjectInternal(path, new LinkedHashMap<String, Object>(), false); }
java
public Tree putMap(String path) { return putObjectInternal(path, new LinkedHashMap<String, Object>(), false); }
[ "public", "Tree", "putMap", "(", "String", "path", ")", "{", "return", "putObjectInternal", "(", "path", ",", "new", "LinkedHashMap", "<", "String", ",", "Object", ">", "(", ")", ",", "false", ")", ";", "}" ]
Associates the specified Map (~= JSON object) container with the specified path. If the structure previously contained a mapping for the path, the old value is replaced. Sample code:<br> <br> Tree node = new Tree();<br> Tree map = node.putMap("a.b.c");<br> map.put("d.e.f", 123); @param path path with which the specified Map is to be associated @return Tree of the new Map
[ "Associates", "the", "specified", "Map", "(", "~", "=", "JSON", "object", ")", "container", "with", "the", "specified", "path", ".", "If", "the", "structure", "previously", "contained", "a", "mapping", "for", "the", "path", "the", "old", "value", "is", "replaced", ".", "Sample", "code", ":", "<br", ">", "<br", ">", "Tree", "node", "=", "new", "Tree", "()", ";", "<br", ">", "Tree", "map", "=", "node", ".", "putMap", "(", "a", ".", "b", ".", "c", ")", ";", "<br", ">", "map", ".", "put", "(", "d", ".", "e", ".", "f", "123", ")", ";" ]
train
https://github.com/berkesa/datatree/blob/79aea9b45c7b46ab28af0a09310bc01c421c6b3a/src/main/java/io/datatree/Tree.java#L2010-L2012
denisneuling/apitrary.jar
apitrary-api-client/src/main/java/com/apitrary/api/transport/ApiClientTransportFactory.java
ApiClientTransportFactory.newTransport
public Transport newTransport(ApitraryApi apitraryApi, Class<Transport> transportClazz) { try { Transport transport = transportClazz.newInstance(); transport.setApitraryApi(apitraryApi); return transport; } catch (IllegalAccessException e) { throw new ApiTransportException(e); } catch (InstantiationException e) { throw new ApiTransportException(e); } }
java
public Transport newTransport(ApitraryApi apitraryApi, Class<Transport> transportClazz) { try { Transport transport = transportClazz.newInstance(); transport.setApitraryApi(apitraryApi); return transport; } catch (IllegalAccessException e) { throw new ApiTransportException(e); } catch (InstantiationException e) { throw new ApiTransportException(e); } }
[ "public", "Transport", "newTransport", "(", "ApitraryApi", "apitraryApi", ",", "Class", "<", "Transport", ">", "transportClazz", ")", "{", "try", "{", "Transport", "transport", "=", "transportClazz", ".", "newInstance", "(", ")", ";", "transport", ".", "setApitraryApi", "(", "apitraryApi", ")", ";", "return", "transport", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "ApiTransportException", "(", "e", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "ApiTransportException", "(", "e", ")", ";", "}", "}" ]
<p>newTransport.</p> @param apitraryApi a {@link com.apitrary.api.ApitraryApi} object. @param transportClazz a {@link java.lang.Class} object. @return a {@link com.apitrary.api.transport.Transport} object.
[ "<p", ">", "newTransport", ".", "<", "/", "p", ">" ]
train
https://github.com/denisneuling/apitrary.jar/blob/b7f639a1e735c60ba2b1b62851926757f5de8628/apitrary-api-client/src/main/java/com/apitrary/api/transport/ApiClientTransportFactory.java#L75-L85
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java
MurmurHash3Adaptor.asInt
public static int asInt(final double datum, final int n) { final double d = (datum == 0.0) ? 0.0 : datum; //canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };//canonicalize all NaN forms return asInteger(data, n); //data is long[] }
java
public static int asInt(final double datum, final int n) { final double d = (datum == 0.0) ? 0.0 : datum; //canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };//canonicalize all NaN forms return asInteger(data, n); //data is long[] }
[ "public", "static", "int", "asInt", "(", "final", "double", "datum", ",", "final", "int", "n", ")", "{", "final", "double", "d", "=", "(", "datum", "==", "0.0", ")", "?", "0.0", ":", "datum", ";", "//canonicalize -0.0, 0.0", "final", "long", "[", "]", "data", "=", "{", "Double", ".", "doubleToLongBits", "(", "d", ")", "}", ";", "//canonicalize all NaN forms", "return", "asInteger", "(", "data", ",", "n", ")", ";", "//data is long[]", "}" ]
Returns a deterministic uniform random integer between zero (inclusive) and n (exclusive) given the input double. @param datum the given double. @param n The upper exclusive bound of the integers produced. Must be &gt; 1. @return deterministic uniform random integer
[ "Returns", "a", "deterministic", "uniform", "random", "integer", "between", "zero", "(", "inclusive", ")", "and", "n", "(", "exclusive", ")", "given", "the", "input", "double", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hash/MurmurHash3Adaptor.java#L292-L296
DiUS/pact-jvm
pact-jvm-consumer-java8/src/main/java/io/pactfoundation/consumer/dsl/LambdaDslObject.java
LambdaDslObject.minArrayLike
public LambdaDslObject minArrayLike(String name, Integer size, Consumer<LambdaDslObject> nestedObject) { final PactDslJsonBody minArrayLike = object.minArrayLike(name, size); final LambdaDslObject dslObject = new LambdaDslObject(minArrayLike); nestedObject.accept(dslObject); minArrayLike.closeArray(); return this; }
java
public LambdaDslObject minArrayLike(String name, Integer size, Consumer<LambdaDslObject> nestedObject) { final PactDslJsonBody minArrayLike = object.minArrayLike(name, size); final LambdaDslObject dslObject = new LambdaDslObject(minArrayLike); nestedObject.accept(dslObject); minArrayLike.closeArray(); return this; }
[ "public", "LambdaDslObject", "minArrayLike", "(", "String", "name", ",", "Integer", "size", ",", "Consumer", "<", "LambdaDslObject", ">", "nestedObject", ")", "{", "final", "PactDslJsonBody", "minArrayLike", "=", "object", ".", "minArrayLike", "(", "name", ",", "size", ")", ";", "final", "LambdaDslObject", "dslObject", "=", "new", "LambdaDslObject", "(", "minArrayLike", ")", ";", "nestedObject", ".", "accept", "(", "dslObject", ")", ";", "minArrayLike", ".", "closeArray", "(", ")", ";", "return", "this", ";", "}" ]
Attribute that is an array with a minimum size where each item must match the following example @param name field name @param size minimum size of the array
[ "Attribute", "that", "is", "an", "array", "with", "a", "minimum", "size", "where", "each", "item", "must", "match", "the", "following", "example" ]
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer-java8/src/main/java/io/pactfoundation/consumer/dsl/LambdaDslObject.java#L438-L444
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java
MapApi.getNullableOptional
public static <T> Optional<T> getNullableOptional(final Map map, final Class<T> clazz, final Object... path) { return getNullable(map, Optional.class, path); }
java
public static <T> Optional<T> getNullableOptional(final Map map, final Class<T> clazz, final Object... path) { return getNullable(map, Optional.class, path); }
[ "public", "static", "<", "T", ">", "Optional", "<", "T", ">", "getNullableOptional", "(", "final", "Map", "map", ",", "final", "Class", "<", "T", ">", "clazz", ",", "final", "Object", "...", "path", ")", "{", "return", "getNullable", "(", "map", ",", "Optional", ".", "class", ",", "path", ")", ";", "}" ]
Get optional value by path. @param <T> optional value type @param clazz type of value @param map subject @param path nodes to walk in map @return value
[ "Get", "optional", "value", "by", "path", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapApi.java#L283-L285
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/JCROrganizationServiceImpl.java
JCROrganizationServiceImpl.getStorageSession
Session getStorageSession() throws RepositoryException { try { ManageableRepository repository = getWorkingRepository(); String workspaceName = storageWorkspace; if (workspaceName == null) { workspaceName = repository.getConfiguration().getDefaultWorkspaceName(); } return repository.getSystemSession(workspaceName); } catch (RepositoryConfigurationException e) { throw new RepositoryException("Can not get system session", e); } }
java
Session getStorageSession() throws RepositoryException { try { ManageableRepository repository = getWorkingRepository(); String workspaceName = storageWorkspace; if (workspaceName == null) { workspaceName = repository.getConfiguration().getDefaultWorkspaceName(); } return repository.getSystemSession(workspaceName); } catch (RepositoryConfigurationException e) { throw new RepositoryException("Can not get system session", e); } }
[ "Session", "getStorageSession", "(", ")", "throws", "RepositoryException", "{", "try", "{", "ManageableRepository", "repository", "=", "getWorkingRepository", "(", ")", ";", "String", "workspaceName", "=", "storageWorkspace", ";", "if", "(", "workspaceName", "==", "null", ")", "{", "workspaceName", "=", "repository", ".", "getConfiguration", "(", ")", ".", "getDefaultWorkspaceName", "(", ")", ";", "}", "return", "repository", ".", "getSystemSession", "(", "workspaceName", ")", ";", "}", "catch", "(", "RepositoryConfigurationException", "e", ")", "{", "throw", "new", "RepositoryException", "(", "\"Can not get system session\"", ",", "e", ")", ";", "}", "}" ]
Return system Session to org-service storage workspace. For internal use only. @return system session @throws RepositoryException if any Exception is occurred
[ "Return", "system", "Session", "to", "org", "-", "service", "storage", "workspace", ".", "For", "internal", "use", "only", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/JCROrganizationServiceImpl.java#L331-L349
aws/aws-sdk-java
aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/internal/validation/ValidationContext.java
ValidationContext.assertNotEmpty
public void assertNotEmpty(Collection<?> collection, String propertyName) { if (CollectionUtils.isNullOrEmpty(collection)) { problemReporter.report(new Problem(this, String.format("%s requires one or more items", propertyName))); } }
java
public void assertNotEmpty(Collection<?> collection, String propertyName) { if (CollectionUtils.isNullOrEmpty(collection)) { problemReporter.report(new Problem(this, String.format("%s requires one or more items", propertyName))); } }
[ "public", "void", "assertNotEmpty", "(", "Collection", "<", "?", ">", "collection", ",", "String", "propertyName", ")", "{", "if", "(", "CollectionUtils", ".", "isNullOrEmpty", "(", "collection", ")", ")", "{", "problemReporter", ".", "report", "(", "new", "Problem", "(", "this", ",", "String", ".", "format", "(", "\"%s requires one or more items\"", ",", "propertyName", ")", ")", ")", ";", "}", "}" ]
Asserts the collection is not null and not empty, reporting to {@link ProblemReporter} with this context if it is. @param collection Collection to assert on. @param propertyName Name of property.
[ "Asserts", "the", "collection", "is", "not", "null", "and", "not", "empty", "reporting", "to", "{", "@link", "ProblemReporter", "}", "with", "this", "context", "if", "it", "is", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/internal/validation/ValidationContext.java#L90-L94
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/proxy/AbstractProxyFactory.java
AbstractProxyFactory.retrieveCollectionProxyConstructor
private static Constructor retrieveCollectionProxyConstructor(Class proxyClass, Class baseType, String typeDesc) { if(proxyClass == null) { throw new MetadataException("No " + typeDesc + " specified."); } if(proxyClass.isInterface() || Modifier.isAbstract(proxyClass.getModifiers()) || !baseType.isAssignableFrom(proxyClass)) { throw new MetadataException("Illegal class " + proxyClass.getName() + " specified for " + typeDesc + ". Must be a concrete subclass of " + baseType.getName()); } Class[] paramType = {PBKey.class, Class.class, Query.class}; try { return proxyClass.getConstructor(paramType); } catch(NoSuchMethodException ex) { throw new MetadataException("The class " + proxyClass.getName() + " specified for " + typeDesc + " is required to have a public constructor with signature (" + PBKey.class.getName() + ", " + Class.class.getName() + ", " + Query.class.getName() + ")."); } }
java
private static Constructor retrieveCollectionProxyConstructor(Class proxyClass, Class baseType, String typeDesc) { if(proxyClass == null) { throw new MetadataException("No " + typeDesc + " specified."); } if(proxyClass.isInterface() || Modifier.isAbstract(proxyClass.getModifiers()) || !baseType.isAssignableFrom(proxyClass)) { throw new MetadataException("Illegal class " + proxyClass.getName() + " specified for " + typeDesc + ". Must be a concrete subclass of " + baseType.getName()); } Class[] paramType = {PBKey.class, Class.class, Query.class}; try { return proxyClass.getConstructor(paramType); } catch(NoSuchMethodException ex) { throw new MetadataException("The class " + proxyClass.getName() + " specified for " + typeDesc + " is required to have a public constructor with signature (" + PBKey.class.getName() + ", " + Class.class.getName() + ", " + Query.class.getName() + ")."); } }
[ "private", "static", "Constructor", "retrieveCollectionProxyConstructor", "(", "Class", "proxyClass", ",", "Class", "baseType", ",", "String", "typeDesc", ")", "{", "if", "(", "proxyClass", "==", "null", ")", "{", "throw", "new", "MetadataException", "(", "\"No \"", "+", "typeDesc", "+", "\" specified.\"", ")", ";", "}", "if", "(", "proxyClass", ".", "isInterface", "(", ")", "||", "Modifier", ".", "isAbstract", "(", "proxyClass", ".", "getModifiers", "(", ")", ")", "||", "!", "baseType", ".", "isAssignableFrom", "(", "proxyClass", ")", ")", "{", "throw", "new", "MetadataException", "(", "\"Illegal class \"", "+", "proxyClass", ".", "getName", "(", ")", "+", "\" specified for \"", "+", "typeDesc", "+", "\". Must be a concrete subclass of \"", "+", "baseType", ".", "getName", "(", ")", ")", ";", "}", "Class", "[", "]", "paramType", "=", "{", "PBKey", ".", "class", ",", "Class", ".", "class", ",", "Query", ".", "class", "}", ";", "try", "{", "return", "proxyClass", ".", "getConstructor", "(", "paramType", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ex", ")", "{", "throw", "new", "MetadataException", "(", "\"The class \"", "+", "proxyClass", ".", "getName", "(", ")", "+", "\" specified for \"", "+", "typeDesc", "+", "\" is required to have a public constructor with signature (\"", "+", "PBKey", ".", "class", ".", "getName", "(", ")", "+", "\", \"", "+", "Class", ".", "class", ".", "getName", "(", ")", "+", "\", \"", "+", "Query", ".", "class", ".", "getName", "(", ")", "+", "\").\"", ")", ";", "}", "}" ]
Retrieves the constructor that is used by OJB to create instances of the given collection proxy class. @param proxyClass The proxy class @param baseType The required base type of the proxy class @param typeDesc The type of collection proxy @return The constructor
[ "Retrieves", "the", "constructor", "that", "is", "used", "by", "OJB", "to", "create", "instances", "of", "the", "given", "collection", "proxy", "class", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/proxy/AbstractProxyFactory.java#L180-L216
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.removeMultiple
@Nonnull public static String removeMultiple (@Nullable final String sInputString, @Nonnull final char [] aRemoveChars) { ValueEnforcer.notNull (aRemoveChars, "RemoveChars"); // Any input text? if (hasNoText (sInputString)) return ""; // Anything to remove? if (aRemoveChars.length == 0) return sInputString; final StringBuilder aSB = new StringBuilder (sInputString.length ()); iterateChars (sInputString, cInput -> { if (!ArrayHelper.contains (aRemoveChars, cInput)) aSB.append (cInput); }); return aSB.toString (); }
java
@Nonnull public static String removeMultiple (@Nullable final String sInputString, @Nonnull final char [] aRemoveChars) { ValueEnforcer.notNull (aRemoveChars, "RemoveChars"); // Any input text? if (hasNoText (sInputString)) return ""; // Anything to remove? if (aRemoveChars.length == 0) return sInputString; final StringBuilder aSB = new StringBuilder (sInputString.length ()); iterateChars (sInputString, cInput -> { if (!ArrayHelper.contains (aRemoveChars, cInput)) aSB.append (cInput); }); return aSB.toString (); }
[ "@", "Nonnull", "public", "static", "String", "removeMultiple", "(", "@", "Nullable", "final", "String", "sInputString", ",", "@", "Nonnull", "final", "char", "[", "]", "aRemoveChars", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aRemoveChars", ",", "\"RemoveChars\"", ")", ";", "// Any input text?", "if", "(", "hasNoText", "(", "sInputString", ")", ")", "return", "\"\"", ";", "// Anything to remove?", "if", "(", "aRemoveChars", ".", "length", "==", "0", ")", "return", "sInputString", ";", "final", "StringBuilder", "aSB", "=", "new", "StringBuilder", "(", "sInputString", ".", "length", "(", ")", ")", ";", "iterateChars", "(", "sInputString", ",", "cInput", "->", "{", "if", "(", "!", "ArrayHelper", ".", "contains", "(", "aRemoveChars", ",", "cInput", ")", ")", "aSB", ".", "append", "(", "cInput", ")", ";", "}", ")", ";", "return", "aSB", ".", "toString", "(", ")", ";", "}" ]
Optimized remove method that removes a set of characters from an input string! @param sInputString The input string. @param aRemoveChars The characters to remove. May not be <code>null</code>. @return The version of the string without the passed characters or an empty String if the input string was <code>null</code>.
[ "Optimized", "remove", "method", "that", "removes", "a", "set", "of", "characters", "from", "an", "input", "string!" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L5196-L5215
phax/ph-web
ph-servlet/src/main/java/com/helger/servlet/cookie/CookieHelper.java
CookieHelper.removeCookie
public static void removeCookie (@Nonnull final HttpServletResponse aHttpResponse, @Nonnull final Cookie aCookie) { ValueEnforcer.notNull (aHttpResponse, "HttpResponse"); ValueEnforcer.notNull (aCookie, "aCookie"); // expire the cookie! aCookie.setMaxAge (0); aHttpResponse.addCookie (aCookie); }
java
public static void removeCookie (@Nonnull final HttpServletResponse aHttpResponse, @Nonnull final Cookie aCookie) { ValueEnforcer.notNull (aHttpResponse, "HttpResponse"); ValueEnforcer.notNull (aCookie, "aCookie"); // expire the cookie! aCookie.setMaxAge (0); aHttpResponse.addCookie (aCookie); }
[ "public", "static", "void", "removeCookie", "(", "@", "Nonnull", "final", "HttpServletResponse", "aHttpResponse", ",", "@", "Nonnull", "final", "Cookie", "aCookie", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aHttpResponse", ",", "\"HttpResponse\"", ")", ";", "ValueEnforcer", ".", "notNull", "(", "aCookie", ",", "\"aCookie\"", ")", ";", "// expire the cookie!", "aCookie", ".", "setMaxAge", "(", "0", ")", ";", "aHttpResponse", ".", "addCookie", "(", "aCookie", ")", ";", "}" ]
Remove a cookie by setting the max age to 0. @param aHttpResponse The HTTP response. May not be <code>null</code>. @param aCookie The cookie to be removed. May not be <code>null</code>.
[ "Remove", "a", "cookie", "by", "setting", "the", "max", "age", "to", "0", "." ]
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-servlet/src/main/java/com/helger/servlet/cookie/CookieHelper.java#L135-L143
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/LinearContourLabelChang2004.java
LinearContourLabelChang2004.scanForOne
private int scanForOne(byte[] data , int index , int end ) { while (index < end && data[index] != 1) { index++; } return index; }
java
private int scanForOne(byte[] data , int index , int end ) { while (index < end && data[index] != 1) { index++; } return index; }
[ "private", "int", "scanForOne", "(", "byte", "[", "]", "data", ",", "int", "index", ",", "int", "end", ")", "{", "while", "(", "index", "<", "end", "&&", "data", "[", "index", "]", "!=", "1", ")", "{", "index", "++", ";", "}", "return", "index", ";", "}" ]
Faster when there's a specialized function which searches for one pixels
[ "Faster", "when", "there", "s", "a", "specialized", "function", "which", "searches", "for", "one", "pixels" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/LinearContourLabelChang2004.java#L157-L162
xetorthio/jedis
src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java
JedisClusterCRC16.getCRC16
public static int getCRC16(byte[] bytes, int s, int e) { int crc = 0x0000; for (int i = s; i < e; i++) { crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (bytes[i] & 0xFF)) & 0xFF]); } return crc & 0xFFFF; }
java
public static int getCRC16(byte[] bytes, int s, int e) { int crc = 0x0000; for (int i = s; i < e; i++) { crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (bytes[i] & 0xFF)) & 0xFF]); } return crc & 0xFFFF; }
[ "public", "static", "int", "getCRC16", "(", "byte", "[", "]", "bytes", ",", "int", "s", ",", "int", "e", ")", "{", "int", "crc", "=", "0x0000", ";", "for", "(", "int", "i", "=", "s", ";", "i", "<", "e", ";", "i", "++", ")", "{", "crc", "=", "(", "(", "crc", "<<", "8", ")", "^", "LOOKUP_TABLE", "[", "(", "(", "crc", ">>>", "8", ")", "^", "(", "bytes", "[", "i", "]", "&", "0xFF", ")", ")", "&", "0xFF", "]", ")", ";", "}", "return", "crc", "&", "0xFFFF", ";", "}" ]
Create a CRC16 checksum from the bytes. implementation is from mp911de/lettuce, modified with some more optimizations @param bytes @param s @param e @return CRC16 as integer value See <a href="https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331">Issue 733</a>
[ "Create", "a", "CRC16", "checksum", "from", "the", "bytes", ".", "implementation", "is", "from", "mp911de", "/", "lettuce", "modified", "with", "some", "more", "optimizations" ]
train
https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java#L83-L90
alkacon/opencms-core
src/org/opencms/search/CmsSearchManager.java
CmsSearchManager.rebuildIndex
public void rebuildIndex(String indexName, I_CmsReport report) throws CmsException { try { SEARCH_MANAGER_LOCK.lock(); // get the search index by name I_CmsSearchIndex index = getIndex(indexName); // update the index updateIndex(index, report, null); // clean up the extraction result cache cleanExtractionCache(); } finally { SEARCH_MANAGER_LOCK.unlock(); } }
java
public void rebuildIndex(String indexName, I_CmsReport report) throws CmsException { try { SEARCH_MANAGER_LOCK.lock(); // get the search index by name I_CmsSearchIndex index = getIndex(indexName); // update the index updateIndex(index, report, null); // clean up the extraction result cache cleanExtractionCache(); } finally { SEARCH_MANAGER_LOCK.unlock(); } }
[ "public", "void", "rebuildIndex", "(", "String", "indexName", ",", "I_CmsReport", "report", ")", "throws", "CmsException", "{", "try", "{", "SEARCH_MANAGER_LOCK", ".", "lock", "(", ")", ";", "// get the search index by name", "I_CmsSearchIndex", "index", "=", "getIndex", "(", "indexName", ")", ";", "// update the index", "updateIndex", "(", "index", ",", "report", ",", "null", ")", ";", "// clean up the extraction result cache", "cleanExtractionCache", "(", ")", ";", "}", "finally", "{", "SEARCH_MANAGER_LOCK", ".", "unlock", "(", ")", ";", "}", "}" ]
Rebuilds (if required creates) the index with the given name.<p> @param indexName the name of the index to rebuild @param report the report object to write messages (or <code>null</code>) @throws CmsException if something goes wrong
[ "Rebuilds", "(", "if", "required", "creates", ")", "the", "index", "with", "the", "given", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchManager.java#L1708-L1721
phax/ph-javacc-maven-plugin
src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java
AbstractJavaCCMojo.determineNonGeneratedSourceRoots
private void determineNonGeneratedSourceRoots () throws MojoExecutionException { this.nonGeneratedSourceRoots = new LinkedHashSet <> (); try { final String targetPrefix = new File (this.project.getBuild ().getDirectory ()).getCanonicalPath () + File.separator; final List <String> sourceRoots = this.project.getCompileSourceRoots (); for (final String aElement : sourceRoots) { File sourceRoot = new File (aElement); if (!sourceRoot.isAbsolute ()) { sourceRoot = new File (this.project.getBasedir (), sourceRoot.getPath ()); } final String sourcePath = sourceRoot.getCanonicalPath (); if (!sourcePath.startsWith (targetPrefix)) { this.nonGeneratedSourceRoots.add (sourceRoot); getLog ().debug ("Non-generated compile source root: " + sourceRoot); } else { getLog ().debug ("Generated compile source root: " + sourceRoot); } } } catch (final IOException e) { throw new MojoExecutionException ("Failed to determine non-generated source roots", e); } }
java
private void determineNonGeneratedSourceRoots () throws MojoExecutionException { this.nonGeneratedSourceRoots = new LinkedHashSet <> (); try { final String targetPrefix = new File (this.project.getBuild ().getDirectory ()).getCanonicalPath () + File.separator; final List <String> sourceRoots = this.project.getCompileSourceRoots (); for (final String aElement : sourceRoots) { File sourceRoot = new File (aElement); if (!sourceRoot.isAbsolute ()) { sourceRoot = new File (this.project.getBasedir (), sourceRoot.getPath ()); } final String sourcePath = sourceRoot.getCanonicalPath (); if (!sourcePath.startsWith (targetPrefix)) { this.nonGeneratedSourceRoots.add (sourceRoot); getLog ().debug ("Non-generated compile source root: " + sourceRoot); } else { getLog ().debug ("Generated compile source root: " + sourceRoot); } } } catch (final IOException e) { throw new MojoExecutionException ("Failed to determine non-generated source roots", e); } }
[ "private", "void", "determineNonGeneratedSourceRoots", "(", ")", "throws", "MojoExecutionException", "{", "this", ".", "nonGeneratedSourceRoots", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "try", "{", "final", "String", "targetPrefix", "=", "new", "File", "(", "this", ".", "project", ".", "getBuild", "(", ")", ".", "getDirectory", "(", ")", ")", ".", "getCanonicalPath", "(", ")", "+", "File", ".", "separator", ";", "final", "List", "<", "String", ">", "sourceRoots", "=", "this", ".", "project", ".", "getCompileSourceRoots", "(", ")", ";", "for", "(", "final", "String", "aElement", ":", "sourceRoots", ")", "{", "File", "sourceRoot", "=", "new", "File", "(", "aElement", ")", ";", "if", "(", "!", "sourceRoot", ".", "isAbsolute", "(", ")", ")", "{", "sourceRoot", "=", "new", "File", "(", "this", ".", "project", ".", "getBasedir", "(", ")", ",", "sourceRoot", ".", "getPath", "(", ")", ")", ";", "}", "final", "String", "sourcePath", "=", "sourceRoot", ".", "getCanonicalPath", "(", ")", ";", "if", "(", "!", "sourcePath", ".", "startsWith", "(", "targetPrefix", ")", ")", "{", "this", ".", "nonGeneratedSourceRoots", ".", "add", "(", "sourceRoot", ")", ";", "getLog", "(", ")", ".", "debug", "(", "\"Non-generated compile source root: \"", "+", "sourceRoot", ")", ";", "}", "else", "{", "getLog", "(", ")", ".", "debug", "(", "\"Generated compile source root: \"", "+", "sourceRoot", ")", ";", "}", "}", "}", "catch", "(", "final", "IOException", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Failed to determine non-generated source roots\"", ",", "e", ")", ";", "}", "}" ]
Determines those compile source roots of the project that do not reside below the project's build directories. These compile source roots are assumed to contain hand-crafted sources that must not be overwritten with generated files. In most cases, this is simply "${project.build.sourceDirectory}". @throws MojoExecutionException If the compile source rotos could not be determined.
[ "Determines", "those", "compile", "source", "roots", "of", "the", "project", "that", "do", "not", "reside", "below", "the", "project", "s", "build", "directories", ".", "These", "compile", "source", "roots", "are", "assumed", "to", "contain", "hand", "-", "crafted", "sources", "that", "must", "not", "be", "overwritten", "with", "generated", "files", ".", "In", "most", "cases", "this", "is", "simply", "$", "{", "project", ".", "build", ".", "sourceDirectory", "}", "." ]
train
https://github.com/phax/ph-javacc-maven-plugin/blob/99497a971fe59ab2289258ca7ddcfa40e651f19f/src/main/java/org/codehaus/mojo/javacc/AbstractJavaCCMojo.java#L650-L681
UrielCh/ovh-java-sdk
ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java
ApiOvhXdsl.serviceName_lines_number_GET
public net.minidev.ovh.api.xdsl.OvhLine serviceName_lines_number_GET(String serviceName, String number) throws IOException { String qPath = "/xdsl/{serviceName}/lines/{number}"; StringBuilder sb = path(qPath, serviceName, number); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, net.minidev.ovh.api.xdsl.OvhLine.class); }
java
public net.minidev.ovh.api.xdsl.OvhLine serviceName_lines_number_GET(String serviceName, String number) throws IOException { String qPath = "/xdsl/{serviceName}/lines/{number}"; StringBuilder sb = path(qPath, serviceName, number); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, net.minidev.ovh.api.xdsl.OvhLine.class); }
[ "public", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "xdsl", ".", "OvhLine", "serviceName_lines_number_GET", "(", "String", "serviceName", ",", "String", "number", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/xdsl/{serviceName}/lines/{number}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "number", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "xdsl", ".", "OvhLine", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /xdsl/{serviceName}/lines/{number} @param serviceName [required] The internal name of your XDSL offer @param number [required] The number of the line
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L443-L448
dropwizard/metrics
metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java
PickledGraphite.pickleMetrics
byte[] pickleMetrics(List<MetricTuple> metrics) throws IOException { // Extremely rough estimate of 75 bytes per message ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); Writer pickled = new OutputStreamWriter(out, charset); pickled.append(MARK); pickled.append(LIST); for (MetricTuple tuple : metrics) { // start the outer tuple pickled.append(MARK); // the metric name is a string. pickled.append(STRING); // the single quotes are to match python's repr("abcd") pickled.append(QUOTE); pickled.append(tuple.name); pickled.append(QUOTE); pickled.append(LF); // start the inner tuple pickled.append(MARK); // timestamp is a long pickled.append(LONG); pickled.append(Long.toString(tuple.timestamp)); // the trailing L is to match python's repr(long(1234)) pickled.append(LONG); pickled.append(LF); // and the value is a string. pickled.append(STRING); pickled.append(QUOTE); pickled.append(tuple.value); pickled.append(QUOTE); pickled.append(LF); pickled.append(TUPLE); // inner close pickled.append(TUPLE); // outer close pickled.append(APPEND); } // every pickle ends with STOP pickled.append(STOP); pickled.flush(); return out.toByteArray(); }
java
byte[] pickleMetrics(List<MetricTuple> metrics) throws IOException { // Extremely rough estimate of 75 bytes per message ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); Writer pickled = new OutputStreamWriter(out, charset); pickled.append(MARK); pickled.append(LIST); for (MetricTuple tuple : metrics) { // start the outer tuple pickled.append(MARK); // the metric name is a string. pickled.append(STRING); // the single quotes are to match python's repr("abcd") pickled.append(QUOTE); pickled.append(tuple.name); pickled.append(QUOTE); pickled.append(LF); // start the inner tuple pickled.append(MARK); // timestamp is a long pickled.append(LONG); pickled.append(Long.toString(tuple.timestamp)); // the trailing L is to match python's repr(long(1234)) pickled.append(LONG); pickled.append(LF); // and the value is a string. pickled.append(STRING); pickled.append(QUOTE); pickled.append(tuple.value); pickled.append(QUOTE); pickled.append(LF); pickled.append(TUPLE); // inner close pickled.append(TUPLE); // outer close pickled.append(APPEND); } // every pickle ends with STOP pickled.append(STOP); pickled.flush(); return out.toByteArray(); }
[ "byte", "[", "]", "pickleMetrics", "(", "List", "<", "MetricTuple", ">", "metrics", ")", "throws", "IOException", "{", "// Extremely rough estimate of 75 bytes per message", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", "metrics", ".", "size", "(", ")", "*", "75", ")", ";", "Writer", "pickled", "=", "new", "OutputStreamWriter", "(", "out", ",", "charset", ")", ";", "pickled", ".", "append", "(", "MARK", ")", ";", "pickled", ".", "append", "(", "LIST", ")", ";", "for", "(", "MetricTuple", "tuple", ":", "metrics", ")", "{", "// start the outer tuple", "pickled", ".", "append", "(", "MARK", ")", ";", "// the metric name is a string.", "pickled", ".", "append", "(", "STRING", ")", ";", "// the single quotes are to match python's repr(\"abcd\")", "pickled", ".", "append", "(", "QUOTE", ")", ";", "pickled", ".", "append", "(", "tuple", ".", "name", ")", ";", "pickled", ".", "append", "(", "QUOTE", ")", ";", "pickled", ".", "append", "(", "LF", ")", ";", "// start the inner tuple", "pickled", ".", "append", "(", "MARK", ")", ";", "// timestamp is a long", "pickled", ".", "append", "(", "LONG", ")", ";", "pickled", ".", "append", "(", "Long", ".", "toString", "(", "tuple", ".", "timestamp", ")", ")", ";", "// the trailing L is to match python's repr(long(1234))", "pickled", ".", "append", "(", "LONG", ")", ";", "pickled", ".", "append", "(", "LF", ")", ";", "// and the value is a string.", "pickled", ".", "append", "(", "STRING", ")", ";", "pickled", ".", "append", "(", "QUOTE", ")", ";", "pickled", ".", "append", "(", "tuple", ".", "value", ")", ";", "pickled", ".", "append", "(", "QUOTE", ")", ";", "pickled", ".", "append", "(", "LF", ")", ";", "pickled", ".", "append", "(", "TUPLE", ")", ";", "// inner close", "pickled", ".", "append", "(", "TUPLE", ")", ";", "// outer close", "pickled", ".", "append", "(", "APPEND", ")", ";", "}", "// every pickle ends with STOP", "pickled", ".", "append", "(", "STOP", ")", ";", "pickled", ".", "flush", "(", ")", ";", "return", "out", ".", "toByteArray", "(", ")", ";", "}" ]
See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html @throws IOException shouldn't happen because we write to memory.
[ "See", ":", "http", ":", "//", "readthedocs", ".", "org", "/", "docs", "/", "graphite", "/", "en", "/", "1", ".", "0", "/", "feeding", "-", "carbon", ".", "html" ]
train
https://github.com/dropwizard/metrics/blob/3c6105a0b9b4416c59e16b6b841b123052d6f57d/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java#L282-L331
belaban/JGroups
src/org/jgroups/protocols/tom/SenderManager.java
SenderManager.addNewMessageToSend
public void addNewMessageToSend(MessageID messageID, Collection<Address> destinations, long initialSequenceNumber, boolean deliverToMyself) { MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself); if (deliverToMyself) { messageInfo.setProposeReceived(messageID.getAddress()); } sentMessages.put(messageID, messageInfo); }
java
public void addNewMessageToSend(MessageID messageID, Collection<Address> destinations, long initialSequenceNumber, boolean deliverToMyself) { MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself); if (deliverToMyself) { messageInfo.setProposeReceived(messageID.getAddress()); } sentMessages.put(messageID, messageInfo); }
[ "public", "void", "addNewMessageToSend", "(", "MessageID", "messageID", ",", "Collection", "<", "Address", ">", "destinations", ",", "long", "initialSequenceNumber", ",", "boolean", "deliverToMyself", ")", "{", "MessageInfo", "messageInfo", "=", "new", "MessageInfo", "(", "destinations", ",", "initialSequenceNumber", ",", "deliverToMyself", ")", ";", "if", "(", "deliverToMyself", ")", "{", "messageInfo", ".", "setProposeReceived", "(", "messageID", ".", "getAddress", "(", ")", ")", ";", "}", "sentMessages", ".", "put", "(", "messageID", ",", "messageInfo", ")", ";", "}" ]
Add a new message sent @param messageID the message ID @param destinations the destination set @param initialSequenceNumber the initial sequence number @param deliverToMyself true if *this* member is in destination sent, false otherwise
[ "Add", "a", "new", "message", "sent" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/tom/SenderManager.java#L28-L35
FasterXML/woodstox
src/main/java/com/ctc/wstx/evt/WstxEventReader.java
WstxEventReader.getErrorDesc
protected String getErrorDesc(int errorType, int currEvent) { // Defaults are mostly fine, except we can easily add event type desc switch (errorType) { case ERR_GETELEMTEXT_NOT_START_ELEM: return ErrorConsts.ERR_STATE_NOT_STELEM+", got "+ErrorConsts.tokenTypeDesc(currEvent); case ERR_GETELEMTEXT_NON_TEXT_EVENT: return "Expected a text token, got "+ErrorConsts.tokenTypeDesc(currEvent); case ERR_NEXTTAG_NON_WS_TEXT: return "Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got "+ErrorConsts.tokenTypeDesc(currEvent); case ERR_NEXTTAG_WRONG_TYPE: return "Got "+ErrorConsts.tokenTypeDesc(currEvent)+", instead of START_ELEMENT, END_ELEMENT or SPACE"; } return null; }
java
protected String getErrorDesc(int errorType, int currEvent) { // Defaults are mostly fine, except we can easily add event type desc switch (errorType) { case ERR_GETELEMTEXT_NOT_START_ELEM: return ErrorConsts.ERR_STATE_NOT_STELEM+", got "+ErrorConsts.tokenTypeDesc(currEvent); case ERR_GETELEMTEXT_NON_TEXT_EVENT: return "Expected a text token, got "+ErrorConsts.tokenTypeDesc(currEvent); case ERR_NEXTTAG_NON_WS_TEXT: return "Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got "+ErrorConsts.tokenTypeDesc(currEvent); case ERR_NEXTTAG_WRONG_TYPE: return "Got "+ErrorConsts.tokenTypeDesc(currEvent)+", instead of START_ELEMENT, END_ELEMENT or SPACE"; } return null; }
[ "protected", "String", "getErrorDesc", "(", "int", "errorType", ",", "int", "currEvent", ")", "{", "// Defaults are mostly fine, except we can easily add event type desc", "switch", "(", "errorType", ")", "{", "case", "ERR_GETELEMTEXT_NOT_START_ELEM", ":", "return", "ErrorConsts", ".", "ERR_STATE_NOT_STELEM", "+", "\", got \"", "+", "ErrorConsts", ".", "tokenTypeDesc", "(", "currEvent", ")", ";", "case", "ERR_GETELEMTEXT_NON_TEXT_EVENT", ":", "return", "\"Expected a text token, got \"", "+", "ErrorConsts", ".", "tokenTypeDesc", "(", "currEvent", ")", ";", "case", "ERR_NEXTTAG_NON_WS_TEXT", ":", "return", "\"Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got \"", "+", "ErrorConsts", ".", "tokenTypeDesc", "(", "currEvent", ")", ";", "case", "ERR_NEXTTAG_WRONG_TYPE", ":", "return", "\"Got \"", "+", "ErrorConsts", ".", "tokenTypeDesc", "(", "currEvent", ")", "+", "\", instead of START_ELEMENT, END_ELEMENT or SPACE\"", ";", "}", "return", "null", ";", "}" ]
Method called upon encountering a problem that should result in an exception being thrown. If non-null String is returned. that will be used as the message of exception thrown; if null, a standard message will be used instead. @param errorType Type of the problem, one of <code>ERR_</code> constants @param eventType Type of the event that triggered the problem, if any; -1 if not available.
[ "Method", "called", "upon", "encountering", "a", "problem", "that", "should", "result", "in", "an", "exception", "being", "thrown", ".", "If", "non", "-", "null", "String", "is", "returned", ".", "that", "will", "be", "used", "as", "the", "message", "of", "exception", "thrown", ";", "if", "null", "a", "standard", "message", "will", "be", "used", "instead", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/evt/WstxEventReader.java#L173-L187
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/kits/WalletAppKit.java
WalletAppKit.setUserAgent
public WalletAppKit setUserAgent(String userAgent, String version) { this.userAgent = checkNotNull(userAgent); this.version = checkNotNull(version); return this; }
java
public WalletAppKit setUserAgent(String userAgent, String version) { this.userAgent = checkNotNull(userAgent); this.version = checkNotNull(version); return this; }
[ "public", "WalletAppKit", "setUserAgent", "(", "String", "userAgent", ",", "String", "version", ")", "{", "this", ".", "userAgent", "=", "checkNotNull", "(", "userAgent", ")", ";", "this", ".", "version", "=", "checkNotNull", "(", "version", ")", ";", "return", "this", ";", "}" ]
Sets the string that will appear in the subver field of the version message. @param userAgent A short string that should be the name of your app, e.g. "My Wallet" @param version A short string that contains the version number, e.g. "1.0-BETA"
[ "Sets", "the", "string", "that", "will", "appear", "in", "the", "subver", "field", "of", "the", "version", "message", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java#L190-L194
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPolicyDefinitionsInner.java
ServiceEndpointPolicyDefinitionsInner.createOrUpdate
public ServiceEndpointPolicyDefinitionInner createOrUpdate(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).toBlocking().last().body(); }
java
public ServiceEndpointPolicyDefinitionInner createOrUpdate(String resourceGroupName, String serviceEndpointPolicyName, String serviceEndpointPolicyDefinitionName, ServiceEndpointPolicyDefinitionInner serviceEndpointPolicyDefinitions) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, serviceEndpointPolicyDefinitionName, serviceEndpointPolicyDefinitions).toBlocking().last().body(); }
[ "public", "ServiceEndpointPolicyDefinitionInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serviceEndpointPolicyName", ",", "String", "serviceEndpointPolicyDefinitionName", ",", "ServiceEndpointPolicyDefinitionInner", "serviceEndpointPolicyDefinitions", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serviceEndpointPolicyName", ",", "serviceEndpointPolicyDefinitionName", ",", "serviceEndpointPolicyDefinitions", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a service endpoint policy definition in the specified service endpoint policy. @param resourceGroupName The name of the resource group. @param serviceEndpointPolicyName The name of the service endpoint policy. @param serviceEndpointPolicyDefinitionName The name of the service endpoint policy definition name. @param serviceEndpointPolicyDefinitions Parameters supplied to the create or update service endpoint policy 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 ServiceEndpointPolicyDefinitionInner object if successful.
[ "Creates", "or", "updates", "a", "service", "endpoint", "policy", "definition", "in", "the", "specified", "service", "endpoint", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPolicyDefinitionsInner.java#L362-L364
phax/ph-commons
ph-charset/src/main/java/com/helger/charset/utf7/UTF7StyleCharsetEncoder.java
UTF7StyleCharsetEncoder._encodeBase64
private void _encodeBase64 (final char ch, final ByteBuffer out) { if (!m_bBase64mode) out.put (m_nShift); m_bBase64mode = true; m_nBitsToOutput += 16; while (m_nBitsToOutput >= 6) { m_nBitsToOutput -= 6; m_nSextet += (ch >> m_nBitsToOutput); m_nSextet &= 0x3F; out.put (m_aBase64.getChar (m_nSextet)); m_nSextet = 0; } m_nSextet = (ch << (6 - m_nBitsToOutput)) & 0x3F; }
java
private void _encodeBase64 (final char ch, final ByteBuffer out) { if (!m_bBase64mode) out.put (m_nShift); m_bBase64mode = true; m_nBitsToOutput += 16; while (m_nBitsToOutput >= 6) { m_nBitsToOutput -= 6; m_nSextet += (ch >> m_nBitsToOutput); m_nSextet &= 0x3F; out.put (m_aBase64.getChar (m_nSextet)); m_nSextet = 0; } m_nSextet = (ch << (6 - m_nBitsToOutput)) & 0x3F; }
[ "private", "void", "_encodeBase64", "(", "final", "char", "ch", ",", "final", "ByteBuffer", "out", ")", "{", "if", "(", "!", "m_bBase64mode", ")", "out", ".", "put", "(", "m_nShift", ")", ";", "m_bBase64mode", "=", "true", ";", "m_nBitsToOutput", "+=", "16", ";", "while", "(", "m_nBitsToOutput", ">=", "6", ")", "{", "m_nBitsToOutput", "-=", "6", ";", "m_nSextet", "+=", "(", "ch", ">>", "m_nBitsToOutput", ")", ";", "m_nSextet", "&=", "0x3F", ";", "out", ".", "put", "(", "m_aBase64", ".", "getChar", "(", "m_nSextet", ")", ")", ";", "m_nSextet", "=", "0", ";", "}", "m_nSextet", "=", "(", "ch", "<<", "(", "6", "-", "m_nBitsToOutput", ")", ")", "&", "0x3F", ";", "}" ]
<p> Writes the bytes necessary to encode a character in <i>base 64 mode</i>. All bytes which are fully determined will be written. The fields <code>bitsToOutput</code> and <code>sextet</code> are used to remember the bytes not yet fully determined. </p> @param out @param ch
[ "<p", ">", "Writes", "the", "bytes", "necessary", "to", "encode", "a", "character", "in", "<i", ">", "base", "64", "mode<", "/", "i", ">", ".", "All", "bytes", "which", "are", "fully", "determined", "will", "be", "written", ".", "The", "fields", "<code", ">", "bitsToOutput<", "/", "code", ">", "and", "<code", ">", "sextet<", "/", "code", ">", "are", "used", "to", "remember", "the", "bytes", "not", "yet", "fully", "determined", ".", "<", "/", "p", ">" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-charset/src/main/java/com/helger/charset/utf7/UTF7StyleCharsetEncoder.java#L196-L211
lessthanoptimal/ddogleg
src/org/ddogleg/solver/FitQuadratic1D.java
FitQuadratic1D.process
public boolean process( int offset , int length , double ...data ) { if( data.length < 3 ) throw new IllegalArgumentException("At least three points"); A.reshape(data.length,3); y.reshape(data.length,1); int indexDst = 0; int indexSrc = offset; for( int i = 0; i < length; i++ ) { double d = data[indexSrc++]; A.data[indexDst++] = i*i; A.data[indexDst++] = i; A.data[indexDst++] = 1; y.data[i] = d; } if( !solver.setA(A) ) return false; solver.solve(y,x); return true; }
java
public boolean process( int offset , int length , double ...data ) { if( data.length < 3 ) throw new IllegalArgumentException("At least three points"); A.reshape(data.length,3); y.reshape(data.length,1); int indexDst = 0; int indexSrc = offset; for( int i = 0; i < length; i++ ) { double d = data[indexSrc++]; A.data[indexDst++] = i*i; A.data[indexDst++] = i; A.data[indexDst++] = 1; y.data[i] = d; } if( !solver.setA(A) ) return false; solver.solve(y,x); return true; }
[ "public", "boolean", "process", "(", "int", "offset", ",", "int", "length", ",", "double", "...", "data", ")", "{", "if", "(", "data", ".", "length", "<", "3", ")", "throw", "new", "IllegalArgumentException", "(", "\"At least three points\"", ")", ";", "A", ".", "reshape", "(", "data", ".", "length", ",", "3", ")", ";", "y", ".", "reshape", "(", "data", ".", "length", ",", "1", ")", ";", "int", "indexDst", "=", "0", ";", "int", "indexSrc", "=", "offset", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "double", "d", "=", "data", "[", "indexSrc", "++", "]", ";", "A", ".", "data", "[", "indexDst", "++", "]", "=", "i", "*", "i", ";", "A", ".", "data", "[", "indexDst", "++", "]", "=", "i", ";", "A", ".", "data", "[", "indexDst", "++", "]", "=", "1", ";", "y", ".", "data", "[", "i", "]", "=", "d", ";", "}", "if", "(", "!", "solver", ".", "setA", "(", "A", ")", ")", "return", "false", ";", "solver", ".", "solve", "(", "y", ",", "x", ")", ";", "return", "true", ";", "}" ]
Computes polynomial coefficients for the given data. @param length Number of elements in data with relevant data. @param data Set of observation data. @return true if successful or false if it fails.
[ "Computes", "polynomial", "coefficients", "for", "the", "given", "data", "." ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/solver/FitQuadratic1D.java#L52-L77
HanSolo/SteelSeries-Swing
src/main/java/eu/hansolo/steelseries/tools/Model.java
Model.setMaxValue
public void setMaxValue(final double MAX_VALUE) { // check min-max values if (Double.compare(MAX_VALUE, minValue) == 0) { throw new IllegalArgumentException("Max value cannot be equal to min value"); } if (Double.compare(MAX_VALUE, minValue) < 0) { maxValue = minValue; minValue = MAX_VALUE; } else { maxValue = MAX_VALUE; } calculate(); validate(); calcAngleStep(); fireStateChanged(); }
java
public void setMaxValue(final double MAX_VALUE) { // check min-max values if (Double.compare(MAX_VALUE, minValue) == 0) { throw new IllegalArgumentException("Max value cannot be equal to min value"); } if (Double.compare(MAX_VALUE, minValue) < 0) { maxValue = minValue; minValue = MAX_VALUE; } else { maxValue = MAX_VALUE; } calculate(); validate(); calcAngleStep(); fireStateChanged(); }
[ "public", "void", "setMaxValue", "(", "final", "double", "MAX_VALUE", ")", "{", "// check min-max values", "if", "(", "Double", ".", "compare", "(", "MAX_VALUE", ",", "minValue", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Max value cannot be equal to min value\"", ")", ";", "}", "if", "(", "Double", ".", "compare", "(", "MAX_VALUE", ",", "minValue", ")", "<", "0", ")", "{", "maxValue", "=", "minValue", ";", "minValue", "=", "MAX_VALUE", ";", "}", "else", "{", "maxValue", "=", "MAX_VALUE", ";", "}", "calculate", "(", ")", ";", "validate", "(", ")", ";", "calcAngleStep", "(", ")", ";", "fireStateChanged", "(", ")", ";", "}" ]
Sets the maximum value that will be used for the calculation of the nice maximum vlaue for the scale. @param MAX_VALUE
[ "Sets", "the", "maximum", "value", "that", "will", "be", "used", "for", "the", "calculation", "of", "the", "nice", "maximum", "vlaue", "for", "the", "scale", "." ]
train
https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/tools/Model.java#L386-L402
zaproxy/zaproxy
src/org/parosproxy/paros/network/HttpMethodHelper.java
HttpMethodHelper.createRequestMethod
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException { return createRequestMethod(header, body, null); }
java
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException { return createRequestMethod(header, body, null); }
[ "public", "HttpMethod", "createRequestMethod", "(", "HttpRequestHeader", "header", ",", "HttpBody", "body", ")", "throws", "URIException", "{", "return", "createRequestMethod", "(", "header", ",", "body", ",", "null", ")", ";", "}" ]
may be replaced by the New method - however the New method is not yet fully tested so this is stil used.
[ "may", "be", "replaced", "by", "the", "New", "method", "-", "however", "the", "New", "method", "is", "not", "yet", "fully", "tested", "so", "this", "is", "stil", "used", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/network/HttpMethodHelper.java#L136-L138
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java
ArtifactorySearch.processResponse
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException { final JsonObject asJsonObject; try (final InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)) { asJsonObject = new JsonParser().parse(streamReader).getAsJsonObject(); } final JsonArray results = asJsonObject.getAsJsonArray("results"); final int numFound = results.size(); if (numFound == 0) { throw new FileNotFoundException("Artifact " + dependency + " not found in Artifactory"); } final List<MavenArtifact> result = new ArrayList<>(numFound); for (JsonElement jsonElement : results) { final JsonObject checksumList = jsonElement.getAsJsonObject().getAsJsonObject("checksums"); final JsonPrimitive sha256Primitive = checksumList.getAsJsonPrimitive("sha256"); final String sha1 = checksumList.getAsJsonPrimitive("sha1").getAsString(); final String sha256 = sha256Primitive == null ? null : sha256Primitive.getAsString(); final String md5 = checksumList.getAsJsonPrimitive("md5").getAsString(); checkHashes(dependency, sha1, sha256, md5); final String downloadUri = jsonElement.getAsJsonObject().getAsJsonPrimitive("downloadUri").getAsString(); final String path = jsonElement.getAsJsonObject().getAsJsonPrimitive("path").getAsString(); final Matcher pathMatcher = PATH_PATTERN.matcher(path); if (!pathMatcher.matches()) { throw new IllegalStateException("Cannot extract the Maven information from the apth retrieved in Artifactory " + path); } final String groupId = pathMatcher.group("groupId").replace('/', '.'); final String artifactId = pathMatcher.group("artifactId"); final String version = pathMatcher.group("version"); result.add(new MavenArtifact(groupId, artifactId, version, downloadUri, MavenArtifact.derivePomUrl(artifactId, version, downloadUri))); } return result; }
java
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException { final JsonObject asJsonObject; try (final InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)) { asJsonObject = new JsonParser().parse(streamReader).getAsJsonObject(); } final JsonArray results = asJsonObject.getAsJsonArray("results"); final int numFound = results.size(); if (numFound == 0) { throw new FileNotFoundException("Artifact " + dependency + " not found in Artifactory"); } final List<MavenArtifact> result = new ArrayList<>(numFound); for (JsonElement jsonElement : results) { final JsonObject checksumList = jsonElement.getAsJsonObject().getAsJsonObject("checksums"); final JsonPrimitive sha256Primitive = checksumList.getAsJsonPrimitive("sha256"); final String sha1 = checksumList.getAsJsonPrimitive("sha1").getAsString(); final String sha256 = sha256Primitive == null ? null : sha256Primitive.getAsString(); final String md5 = checksumList.getAsJsonPrimitive("md5").getAsString(); checkHashes(dependency, sha1, sha256, md5); final String downloadUri = jsonElement.getAsJsonObject().getAsJsonPrimitive("downloadUri").getAsString(); final String path = jsonElement.getAsJsonObject().getAsJsonPrimitive("path").getAsString(); final Matcher pathMatcher = PATH_PATTERN.matcher(path); if (!pathMatcher.matches()) { throw new IllegalStateException("Cannot extract the Maven information from the apth retrieved in Artifactory " + path); } final String groupId = pathMatcher.group("groupId").replace('/', '.'); final String artifactId = pathMatcher.group("artifactId"); final String version = pathMatcher.group("version"); result.add(new MavenArtifact(groupId, artifactId, version, downloadUri, MavenArtifact.derivePomUrl(artifactId, version, downloadUri))); } return result; }
[ "protected", "List", "<", "MavenArtifact", ">", "processResponse", "(", "Dependency", "dependency", ",", "HttpURLConnection", "conn", ")", "throws", "IOException", "{", "final", "JsonObject", "asJsonObject", ";", "try", "(", "final", "InputStreamReader", "streamReader", "=", "new", "InputStreamReader", "(", "conn", ".", "getInputStream", "(", ")", ",", "StandardCharsets", ".", "UTF_8", ")", ")", "{", "asJsonObject", "=", "new", "JsonParser", "(", ")", ".", "parse", "(", "streamReader", ")", ".", "getAsJsonObject", "(", ")", ";", "}", "final", "JsonArray", "results", "=", "asJsonObject", ".", "getAsJsonArray", "(", "\"results\"", ")", ";", "final", "int", "numFound", "=", "results", ".", "size", "(", ")", ";", "if", "(", "numFound", "==", "0", ")", "{", "throw", "new", "FileNotFoundException", "(", "\"Artifact \"", "+", "dependency", "+", "\" not found in Artifactory\"", ")", ";", "}", "final", "List", "<", "MavenArtifact", ">", "result", "=", "new", "ArrayList", "<>", "(", "numFound", ")", ";", "for", "(", "JsonElement", "jsonElement", ":", "results", ")", "{", "final", "JsonObject", "checksumList", "=", "jsonElement", ".", "getAsJsonObject", "(", ")", ".", "getAsJsonObject", "(", "\"checksums\"", ")", ";", "final", "JsonPrimitive", "sha256Primitive", "=", "checksumList", ".", "getAsJsonPrimitive", "(", "\"sha256\"", ")", ";", "final", "String", "sha1", "=", "checksumList", ".", "getAsJsonPrimitive", "(", "\"sha1\"", ")", ".", "getAsString", "(", ")", ";", "final", "String", "sha256", "=", "sha256Primitive", "==", "null", "?", "null", ":", "sha256Primitive", ".", "getAsString", "(", ")", ";", "final", "String", "md5", "=", "checksumList", ".", "getAsJsonPrimitive", "(", "\"md5\"", ")", ".", "getAsString", "(", ")", ";", "checkHashes", "(", "dependency", ",", "sha1", ",", "sha256", ",", "md5", ")", ";", "final", "String", "downloadUri", "=", "jsonElement", ".", "getAsJsonObject", "(", ")", ".", "getAsJsonPrimitive", "(", "\"downloadUri\"", ")", ".", "getAsString", "(", ")", ";", "final", "String", "path", "=", "jsonElement", ".", "getAsJsonObject", "(", ")", ".", "getAsJsonPrimitive", "(", "\"path\"", ")", ".", "getAsString", "(", ")", ";", "final", "Matcher", "pathMatcher", "=", "PATH_PATTERN", ".", "matcher", "(", "path", ")", ";", "if", "(", "!", "pathMatcher", ".", "matches", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot extract the Maven information from the apth retrieved in Artifactory \"", "+", "path", ")", ";", "}", "final", "String", "groupId", "=", "pathMatcher", ".", "group", "(", "\"groupId\"", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "final", "String", "artifactId", "=", "pathMatcher", ".", "group", "(", "\"artifactId\"", ")", ";", "final", "String", "version", "=", "pathMatcher", ".", "group", "(", "\"version\"", ")", ";", "result", ".", "add", "(", "new", "MavenArtifact", "(", "groupId", ",", "artifactId", ",", "version", ",", "downloadUri", ",", "MavenArtifact", ".", "derivePomUrl", "(", "artifactId", ",", "version", ",", "downloadUri", ")", ")", ")", ";", "}", "return", "result", ";", "}" ]
Process the Artifactory response. @param dependency the dependency @param conn the HTTP URL Connection @return a list of the Maven Artifact information @throws IOException thrown if there is an I/O error
[ "Process", "the", "Artifactory", "response", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java#L196-L234
elki-project/elki
elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/vafile/VALPNormDistance.java
VALPNormDistance.initializeLookupTable
private void initializeLookupTable(double[][] splitPositions, NumberVector query, double p) { final int dimensions = splitPositions.length; final int bordercount = splitPositions[0].length; lookup = new double[dimensions][bordercount]; for(int d = 0; d < dimensions; d++) { final double val = query.doubleValue(d); for(int i = 0; i < bordercount; i++) { lookup[d][i] = FastMath.pow(splitPositions[d][i] - val, p); } } }
java
private void initializeLookupTable(double[][] splitPositions, NumberVector query, double p) { final int dimensions = splitPositions.length; final int bordercount = splitPositions[0].length; lookup = new double[dimensions][bordercount]; for(int d = 0; d < dimensions; d++) { final double val = query.doubleValue(d); for(int i = 0; i < bordercount; i++) { lookup[d][i] = FastMath.pow(splitPositions[d][i] - val, p); } } }
[ "private", "void", "initializeLookupTable", "(", "double", "[", "]", "[", "]", "splitPositions", ",", "NumberVector", "query", ",", "double", "p", ")", "{", "final", "int", "dimensions", "=", "splitPositions", ".", "length", ";", "final", "int", "bordercount", "=", "splitPositions", "[", "0", "]", ".", "length", ";", "lookup", "=", "new", "double", "[", "dimensions", "]", "[", "bordercount", "]", ";", "for", "(", "int", "d", "=", "0", ";", "d", "<", "dimensions", ";", "d", "++", ")", "{", "final", "double", "val", "=", "query", ".", "doubleValue", "(", "d", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bordercount", ";", "i", "++", ")", "{", "lookup", "[", "d", "]", "[", "i", "]", "=", "FastMath", ".", "pow", "(", "splitPositions", "[", "d", "]", "[", "i", "]", "-", "val", ",", "p", ")", ";", "}", "}", "}" ]
Initialize the lookup table. @param splitPositions Split positions @param query Query vector @param p p
[ "Initialize", "the", "lookup", "table", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/vafile/VALPNormDistance.java#L157-L167
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/FindbugsPlugin.java
FindbugsPlugin.saveCurrentBugCollection
public static void saveCurrentBugCollection(IProject project, IProgressMonitor monitor) throws CoreException { if (isBugCollectionDirty(project)) { SortedBugCollection bugCollection = (SortedBugCollection) project.getSessionProperty(SESSION_PROPERTY_BUG_COLLECTION); if (bugCollection != null) { writeBugCollection(project, bugCollection, monitor); } } }
java
public static void saveCurrentBugCollection(IProject project, IProgressMonitor monitor) throws CoreException { if (isBugCollectionDirty(project)) { SortedBugCollection bugCollection = (SortedBugCollection) project.getSessionProperty(SESSION_PROPERTY_BUG_COLLECTION); if (bugCollection != null) { writeBugCollection(project, bugCollection, monitor); } } }
[ "public", "static", "void", "saveCurrentBugCollection", "(", "IProject", "project", ",", "IProgressMonitor", "monitor", ")", "throws", "CoreException", "{", "if", "(", "isBugCollectionDirty", "(", "project", ")", ")", "{", "SortedBugCollection", "bugCollection", "=", "(", "SortedBugCollection", ")", "project", ".", "getSessionProperty", "(", "SESSION_PROPERTY_BUG_COLLECTION", ")", ";", "if", "(", "bugCollection", "!=", "null", ")", "{", "writeBugCollection", "(", "project", ",", "bugCollection", ",", "monitor", ")", ";", "}", "}", "}" ]
If necessary, save current bug collection for project to disk. @param project the project @param monitor a progress monitor @throws CoreException
[ "If", "necessary", "save", "current", "bug", "collection", "for", "project", "to", "disk", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/FindbugsPlugin.java#L764-L772
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.service/src/com/ibm/wsspi/kernel/service/utils/ConcurrentServiceReferenceMap.java
ConcurrentServiceReferenceMap.putReference
public boolean putReference(K key, ServiceReference<V> reference) { if (key == null || reference == null) return false; ConcurrentServiceReferenceElement<V> element = new ConcurrentServiceReferenceElement<V>(referenceName, reference); return (elementMap.put(key, element) != null); }
java
public boolean putReference(K key, ServiceReference<V> reference) { if (key == null || reference == null) return false; ConcurrentServiceReferenceElement<V> element = new ConcurrentServiceReferenceElement<V>(referenceName, reference); return (elementMap.put(key, element) != null); }
[ "public", "boolean", "putReference", "(", "K", "key", ",", "ServiceReference", "<", "V", ">", "reference", ")", "{", "if", "(", "key", "==", "null", "||", "reference", "==", "null", ")", "return", "false", ";", "ConcurrentServiceReferenceElement", "<", "V", ">", "element", "=", "new", "ConcurrentServiceReferenceElement", "<", "V", ">", "(", "referenceName", ",", "reference", ")", ";", "return", "(", "elementMap", ".", "put", "(", "key", ",", "element", ")", "!=", "null", ")", ";", "}" ]
Associates the reference with the key. @param key Key associated with this reference @param reference ServiceReference for the target service @return true if this is replacing a previous (non-null) service reference
[ "Associates", "the", "reference", "with", "the", "key", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.service/src/com/ibm/wsspi/kernel/service/utils/ConcurrentServiceReferenceMap.java#L118-L124
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/domain/builders/SubReportBuilder.java
SubReportBuilder.setDataSource
public SubReportBuilder setDataSource(String expression) { return setDataSource(DJConstants.DATA_SOURCE_ORIGIN_PARAMETER, DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE, expression); }
java
public SubReportBuilder setDataSource(String expression) { return setDataSource(DJConstants.DATA_SOURCE_ORIGIN_PARAMETER, DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE, expression); }
[ "public", "SubReportBuilder", "setDataSource", "(", "String", "expression", ")", "{", "return", "setDataSource", "(", "DJConstants", ".", "DATA_SOURCE_ORIGIN_PARAMETER", ",", "DJConstants", ".", "DATA_SOURCE_TYPE_JRDATASOURCE", ",", "expression", ")", ";", "}" ]
like addDataSource(int origin, String expression) but the origin will be from a Parameter @param expression @return
[ "like", "addDataSource", "(", "int", "origin", "String", "expression", ")", "but", "the", "origin", "will", "be", "from", "a", "Parameter" ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/builders/SubReportBuilder.java#L129-L131
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/concurrent/JRebirth.java
JRebirth.runIntoJTP
public static void runIntoJTP(final String runnableName, final PriorityLevel runnablePriority, final Runnable runnable) { runIntoJTP(new JrbReferenceRunnable(runnableName, runnablePriority, runnable)); }
java
public static void runIntoJTP(final String runnableName, final PriorityLevel runnablePriority, final Runnable runnable) { runIntoJTP(new JrbReferenceRunnable(runnableName, runnablePriority, runnable)); }
[ "public", "static", "void", "runIntoJTP", "(", "final", "String", "runnableName", ",", "final", "PriorityLevel", "runnablePriority", ",", "final", "Runnable", "runnable", ")", "{", "runIntoJTP", "(", "new", "JrbReferenceRunnable", "(", "runnableName", ",", "runnablePriority", ",", "runnable", ")", ")", ";", "}" ]
Run into the JRebirth Thread Pool [JTP]. Be careful this method can be called through any thread. @param runnableName the name of the runnable for logging purpose @param runnablePriority the priority to try to apply to the runnable @param runnable the task to run
[ "Run", "into", "the", "JRebirth", "Thread", "Pool", "[", "JTP", "]", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/concurrent/JRebirth.java#L341-L343
MenoData/Time4J
base/src/main/java/net/time4j/engine/AbstractMetric.java
AbstractMetric.compare
@Override public int compare(U u1, U u2) { return Double.compare(u2.getLength(), u1.getLength()); // descending }
java
@Override public int compare(U u1, U u2) { return Double.compare(u2.getLength(), u1.getLength()); // descending }
[ "@", "Override", "public", "int", "compare", "(", "U", "u1", ",", "U", "u2", ")", "{", "return", "Double", ".", "compare", "(", "u2", ".", "getLength", "(", ")", ",", "u1", ".", "getLength", "(", ")", ")", ";", "// descending", "}" ]
/*[deutsch] <p>Vergleicht Zeiteinheiten absteigend nach ihrer L&auml;nge. </p> @param u1 first time unit @param u2 second time unit @return negative, zero or positive if u1 is greater, equal to or smaller than u2
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Vergleicht", "Zeiteinheiten", "absteigend", "nach", "ihrer", "L&auml", ";", "nge", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/engine/AbstractMetric.java#L152-L157
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java
BitcoinSerializer.makeInventoryMessage
@Override public InventoryMessage makeInventoryMessage(byte[] payloadBytes, int length) throws ProtocolException { return new InventoryMessage(params, payloadBytes, this, length); }
java
@Override public InventoryMessage makeInventoryMessage(byte[] payloadBytes, int length) throws ProtocolException { return new InventoryMessage(params, payloadBytes, this, length); }
[ "@", "Override", "public", "InventoryMessage", "makeInventoryMessage", "(", "byte", "[", "]", "payloadBytes", ",", "int", "length", ")", "throws", "ProtocolException", "{", "return", "new", "InventoryMessage", "(", "params", ",", "payloadBytes", ",", "this", ",", "length", ")", ";", "}" ]
Make an inventory message from the payload. Extension point for alternative serialization format support.
[ "Make", "an", "inventory", "message", "from", "the", "payload", ".", "Extension", "point", "for", "alternative", "serialization", "format", "support", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L299-L302
TNG/JGiven
jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java
Attachment.fromBinaryInputStream
public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException { return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType ); }
java
public static Attachment fromBinaryInputStream( InputStream inputStream, MediaType mediaType ) throws IOException { return fromBinaryBytes( ByteStreams.toByteArray( inputStream ), mediaType ); }
[ "public", "static", "Attachment", "fromBinaryInputStream", "(", "InputStream", "inputStream", ",", "MediaType", "mediaType", ")", "throws", "IOException", "{", "return", "fromBinaryBytes", "(", "ByteStreams", ".", "toByteArray", "(", "inputStream", ")", ",", "mediaType", ")", ";", "}" ]
Creates an attachment from a binary input stream. The content of the stream will be transformed into a Base64 encoded string @throws IOException if an I/O error occurs @throws java.lang.IllegalArgumentException if mediaType is not binary
[ "Creates", "an", "attachment", "from", "a", "binary", "input", "stream", ".", "The", "content", "of", "the", "stream", "will", "be", "transformed", "into", "a", "Base64", "encoded", "string" ]
train
https://github.com/TNG/JGiven/blob/1a69248fc6d7eb380cdc4542e3be273842889748/jgiven-core/src/main/java/com/tngtech/jgiven/attachment/Attachment.java#L176-L178
OpenLiberty/open-liberty
dev/com.ibm.ws.org.apache.jasper.el/src/org/apache/el/lang/ELSupport.java
ELSupport.coerceToBoolean
public static final Boolean coerceToBoolean(final ELContext ctx, final Object obj) { // previous el 2.2 implementation returned false if obj is null // so pass in true for primitive to force the same behavior return coerceToBoolean(ctx, obj, true); }
java
public static final Boolean coerceToBoolean(final ELContext ctx, final Object obj) { // previous el 2.2 implementation returned false if obj is null // so pass in true for primitive to force the same behavior return coerceToBoolean(ctx, obj, true); }
[ "public", "static", "final", "Boolean", "coerceToBoolean", "(", "final", "ELContext", "ctx", ",", "final", "Object", "obj", ")", "{", "// previous el 2.2 implementation returned false if obj is null", "// so pass in true for primitive to force the same behavior", "return", "coerceToBoolean", "(", "ctx", ",", "obj", ",", "true", ")", ";", "}" ]
Convert an object to Boolean. Null and empty string are false. @param ctx the context in which this conversion is taking place @param obj the object to convert @return the Boolean value of the object @throws ELException if object is not Boolean or String
[ "Convert", "an", "object", "to", "Boolean", ".", "Null", "and", "empty", "string", "are", "false", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.jasper.el/src/org/apache/el/lang/ELSupport.java#L312-L316
javalite/activejdbc
javalite-common/src/main/java/org/javalite/common/Util.java
Util.readResource
public static String readResource(String resourceName, String charset) { InputStream is = Util.class.getResourceAsStream(resourceName); try { return read(is, charset); } catch (IOException e) { throw new RuntimeException(e); } finally { closeQuietly(is); } }
java
public static String readResource(String resourceName, String charset) { InputStream is = Util.class.getResourceAsStream(resourceName); try { return read(is, charset); } catch (IOException e) { throw new RuntimeException(e); } finally { closeQuietly(is); } }
[ "public", "static", "String", "readResource", "(", "String", "resourceName", ",", "String", "charset", ")", "{", "InputStream", "is", "=", "Util", ".", "class", ".", "getResourceAsStream", "(", "resourceName", ")", ";", "try", "{", "return", "read", "(", "is", ",", "charset", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "finally", "{", "closeQuietly", "(", "is", ")", ";", "}", "}" ]
Reads contents of resource fully into a string. @param resourceName resource name. @param charset name of supported charset @return entire contents of resource as string.
[ "Reads", "contents", "of", "resource", "fully", "into", "a", "string", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/Util.java#L67-L76
ArcBees/gwtquery
gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/events/EventsListener.java
EventsListener.dispatchEvent
public void dispatchEvent(Event event, String eventName) { int typeInt = Event.getTypeInt(eventName); Object[] handlerData = $(element).data(EVENT_DATA); for (int i = 0, l = elementEvents.length(); i < l; i++) { BindFunction listener = elementEvents.get(i); String namespace = JsUtils.prop(event, "namespace"); boolean matchEV = listener != null && (listener.hasEventType(typeInt) || listener.isTypeOf(eventName)); boolean matchNS = matchEV && (isNullOrEmpty(namespace) || listener.nameSpace.equals(namespace)); if (matchEV && matchNS) { if (!listener.fire(event, typeInt, eventName, handlerData)) { event.stopPropagation(); event.preventDefault(); } } } }
java
public void dispatchEvent(Event event, String eventName) { int typeInt = Event.getTypeInt(eventName); Object[] handlerData = $(element).data(EVENT_DATA); for (int i = 0, l = elementEvents.length(); i < l; i++) { BindFunction listener = elementEvents.get(i); String namespace = JsUtils.prop(event, "namespace"); boolean matchEV = listener != null && (listener.hasEventType(typeInt) || listener.isTypeOf(eventName)); boolean matchNS = matchEV && (isNullOrEmpty(namespace) || listener.nameSpace.equals(namespace)); if (matchEV && matchNS) { if (!listener.fire(event, typeInt, eventName, handlerData)) { event.stopPropagation(); event.preventDefault(); } } } }
[ "public", "void", "dispatchEvent", "(", "Event", "event", ",", "String", "eventName", ")", "{", "int", "typeInt", "=", "Event", ".", "getTypeInt", "(", "eventName", ")", ";", "Object", "[", "]", "handlerData", "=", "$", "(", "element", ")", ".", "data", "(", "EVENT_DATA", ")", ";", "for", "(", "int", "i", "=", "0", ",", "l", "=", "elementEvents", ".", "length", "(", ")", ";", "i", "<", "l", ";", "i", "++", ")", "{", "BindFunction", "listener", "=", "elementEvents", ".", "get", "(", "i", ")", ";", "String", "namespace", "=", "JsUtils", ".", "prop", "(", "event", ",", "\"namespace\"", ")", ";", "boolean", "matchEV", "=", "listener", "!=", "null", "&&", "(", "listener", ".", "hasEventType", "(", "typeInt", ")", "||", "listener", ".", "isTypeOf", "(", "eventName", ")", ")", ";", "boolean", "matchNS", "=", "matchEV", "&&", "(", "isNullOrEmpty", "(", "namespace", ")", "||", "listener", ".", "nameSpace", ".", "equals", "(", "namespace", ")", ")", ";", "if", "(", "matchEV", "&&", "matchNS", ")", "{", "if", "(", "!", "listener", ".", "fire", "(", "event", ",", "typeInt", ",", "eventName", ",", "handlerData", ")", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", "}", "}", "}" ]
Dispatch an event in this element but changing the type, it's useful for special events.
[ "Dispatch", "an", "event", "in", "this", "element", "but", "changing", "the", "type", "it", "s", "useful", "for", "special", "events", "." ]
train
https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/events/EventsListener.java#L557-L572
foundation-runtime/service-directory
1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java
ServiceInstanceUtils.validateMetadata
public static void validateMetadata(Map<String, String> metadata) throws ServiceException { for ( String key : metadata.keySet()){ if (!validateRequiredField(key, metaKeyRegEx)){ throw new ServiceException( ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR, ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR.getMessageTemplate(),key ); } } }
java
public static void validateMetadata(Map<String, String> metadata) throws ServiceException { for ( String key : metadata.keySet()){ if (!validateRequiredField(key, metaKeyRegEx)){ throw new ServiceException( ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR, ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR.getMessageTemplate(),key ); } } }
[ "public", "static", "void", "validateMetadata", "(", "Map", "<", "String", ",", "String", ">", "metadata", ")", "throws", "ServiceException", "{", "for", "(", "String", "key", ":", "metadata", ".", "keySet", "(", ")", ")", "{", "if", "(", "!", "validateRequiredField", "(", "key", ",", "metaKeyRegEx", ")", ")", "{", "throw", "new", "ServiceException", "(", "ErrorCode", ".", "SERVICE_INSTANCE_METAKEY_FORMAT_ERROR", ",", "ErrorCode", ".", "SERVICE_INSTANCE_METAKEY_FORMAT_ERROR", ".", "getMessageTemplate", "(", ")", ",", "key", ")", ";", "}", "}", "}" ]
Validate the ServiceInstance Metadata. @param metadata the service instance metadata map. @throws ServiceException
[ "Validate", "the", "ServiceInstance", "Metadata", "." ]
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#L194-L204
legsem/legstar-core2
legstar-base/src/main/java/com/legstar/base/type/primitive/CobolDecimalType.java
CobolDecimalType.valueOf
@SuppressWarnings("unchecked") public static <D extends Number> D valueOf(Class < D > clazz, String str) { if (clazz.equals(Short.class)) { return (D) Short.valueOf(intPart(str)); } else if (clazz.equals(Integer.class)) { return (D) Integer.valueOf(intPart(str)); } else if (clazz.equals(Long.class)) { return (D) Long.valueOf(intPart(str)); } else if (clazz.equals(BigDecimal.class)) { return (D) new BigDecimal(str); } else if (clazz.equals(BigInteger.class)) { return (D) new BigInteger(intPart(str)); } throw new IllegalArgumentException("Unsupported java type " + clazz); }
java
@SuppressWarnings("unchecked") public static <D extends Number> D valueOf(Class < D > clazz, String str) { if (clazz.equals(Short.class)) { return (D) Short.valueOf(intPart(str)); } else if (clazz.equals(Integer.class)) { return (D) Integer.valueOf(intPart(str)); } else if (clazz.equals(Long.class)) { return (D) Long.valueOf(intPart(str)); } else if (clazz.equals(BigDecimal.class)) { return (D) new BigDecimal(str); } else if (clazz.equals(BigInteger.class)) { return (D) new BigInteger(intPart(str)); } throw new IllegalArgumentException("Unsupported java type " + clazz); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "D", "extends", "Number", ">", "D", "valueOf", "(", "Class", "<", "D", ">", "clazz", ",", "String", "str", ")", "{", "if", "(", "clazz", ".", "equals", "(", "Short", ".", "class", ")", ")", "{", "return", "(", "D", ")", "Short", ".", "valueOf", "(", "intPart", "(", "str", ")", ")", ";", "}", "else", "if", "(", "clazz", ".", "equals", "(", "Integer", ".", "class", ")", ")", "{", "return", "(", "D", ")", "Integer", ".", "valueOf", "(", "intPart", "(", "str", ")", ")", ";", "}", "else", "if", "(", "clazz", ".", "equals", "(", "Long", ".", "class", ")", ")", "{", "return", "(", "D", ")", "Long", ".", "valueOf", "(", "intPart", "(", "str", ")", ")", ";", "}", "else", "if", "(", "clazz", ".", "equals", "(", "BigDecimal", ".", "class", ")", ")", "{", "return", "(", "D", ")", "new", "BigDecimal", "(", "str", ")", ";", "}", "else", "if", "(", "clazz", ".", "equals", "(", "BigInteger", ".", "class", ")", ")", "{", "return", "(", "D", ")", "new", "BigInteger", "(", "intPart", "(", "str", ")", ")", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported java type \"", "+", "clazz", ")", ";", "}" ]
Given a string representation of a numeric value, convert that to the target java Number type. <p/> If the target is an integer type, we trim any fractional part. @param clazz the java Number type @param str the string representation of a numeric value @return the java Number obtained from the input string @throws NumberFormatException if umber cannot be derived from the input string
[ "Given", "a", "string", "representation", "of", "a", "numeric", "value", "convert", "that", "to", "the", "target", "java", "Number", "type", ".", "<p", "/", ">", "If", "the", "target", "is", "an", "integer", "type", "we", "trim", "any", "fractional", "part", "." ]
train
https://github.com/legsem/legstar-core2/blob/f74d25d5b2b21a2ebaaaf2162b3fb7138dca40c6/legstar-base/src/main/java/com/legstar/base/type/primitive/CobolDecimalType.java#L193-L207
apereo/cas
core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/AbstractWebApplicationServiceResponseBuilder.java
AbstractWebApplicationServiceResponseBuilder.buildPost
protected Response buildPost(final WebApplicationService service, final Map<String, String> parameters) { return DefaultResponse.getPostResponse(service.getOriginalUrl(), parameters); }
java
protected Response buildPost(final WebApplicationService service, final Map<String, String> parameters) { return DefaultResponse.getPostResponse(service.getOriginalUrl(), parameters); }
[ "protected", "Response", "buildPost", "(", "final", "WebApplicationService", "service", ",", "final", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "return", "DefaultResponse", ".", "getPostResponse", "(", "service", ".", "getOriginalUrl", "(", ")", ",", "parameters", ")", ";", "}" ]
Build post. @param service the service @param parameters the parameters @return the response
[ "Build", "post", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/AbstractWebApplicationServiceResponseBuilder.java#L66-L68
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.expandConfig
private Map<String, String> expandConfig(Map<String, String> map) { return expandAllProperties(map, getPropertyLookup().getPropertiesMap()); }
java
private Map<String, String> expandConfig(Map<String, String> map) { return expandAllProperties(map, getPropertyLookup().getPropertiesMap()); }
[ "private", "Map", "<", "String", ",", "String", ">", "expandConfig", "(", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "return", "expandAllProperties", "(", "map", ",", "getPropertyLookup", "(", ")", ".", "getPropertiesMap", "(", ")", ")", ";", "}" ]
Expand embedded framework property references in the map values @param map map @return expanded map
[ "Expand", "embedded", "framework", "property", "references", "in", "the", "map", "values" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L313-L315
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/UserApi.java
UserApi.createCustomAttribute
public CustomAttribute createCustomAttribute(final Object userIdOrUsername, final String key, final String value) throws GitLabApiException { if (Objects.isNull(key) || key.trim().isEmpty()) { throw new IllegalArgumentException("Key can't be null or empty"); } if (Objects.isNull(value) || value.trim().isEmpty()) { throw new IllegalArgumentException("Value can't be null or empty"); } GitLabApiForm formData = new GitLabApiForm().withParam("value", value); Response response = put(Response.Status.OK, formData.asMap(), "users", getUserIdOrUsername(userIdOrUsername), "custom_attributes", key); return (response.readEntity(CustomAttribute.class)); }
java
public CustomAttribute createCustomAttribute(final Object userIdOrUsername, final String key, final String value) throws GitLabApiException { if (Objects.isNull(key) || key.trim().isEmpty()) { throw new IllegalArgumentException("Key can't be null or empty"); } if (Objects.isNull(value) || value.trim().isEmpty()) { throw new IllegalArgumentException("Value can't be null or empty"); } GitLabApiForm formData = new GitLabApiForm().withParam("value", value); Response response = put(Response.Status.OK, formData.asMap(), "users", getUserIdOrUsername(userIdOrUsername), "custom_attributes", key); return (response.readEntity(CustomAttribute.class)); }
[ "public", "CustomAttribute", "createCustomAttribute", "(", "final", "Object", "userIdOrUsername", ",", "final", "String", "key", ",", "final", "String", "value", ")", "throws", "GitLabApiException", "{", "if", "(", "Objects", ".", "isNull", "(", "key", ")", "||", "key", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Key can't be null or empty\"", ")", ";", "}", "if", "(", "Objects", ".", "isNull", "(", "value", ")", "||", "value", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Value can't be null or empty\"", ")", ";", "}", "GitLabApiForm", "formData", "=", "new", "GitLabApiForm", "(", ")", ".", "withParam", "(", "\"value\"", ",", "value", ")", ";", "Response", "response", "=", "put", "(", "Response", ".", "Status", ".", "OK", ",", "formData", ".", "asMap", "(", ")", ",", "\"users\"", ",", "getUserIdOrUsername", "(", "userIdOrUsername", ")", ",", "\"custom_attributes\"", ",", "key", ")", ";", "return", "(", "response", ".", "readEntity", "(", "CustomAttribute", ".", "class", ")", ")", ";", "}" ]
Creates custom attribute for the given user @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance @param key for the customAttribute @param value or the customAttribute @return the created CustomAttribute @throws GitLabApiException on failure while setting customAttributes
[ "Creates", "custom", "attribute", "for", "the", "given", "user" ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/UserApi.java#L911-L924
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/ArgumentProcessor.java
ArgumentProcessor.forType
public static <T> ArgumentProcessor<T> forType(Class<? extends T> beanType) { return newInstance(beanType, new GnuParser()); }
java
public static <T> ArgumentProcessor<T> forType(Class<? extends T> beanType) { return newInstance(beanType, new GnuParser()); }
[ "public", "static", "<", "T", ">", "ArgumentProcessor", "<", "T", ">", "forType", "(", "Class", "<", "?", "extends", "T", ">", "beanType", ")", "{", "return", "newInstance", "(", "beanType", ",", "new", "GnuParser", "(", ")", ")", ";", "}" ]
Create new instance with default parser, a {@link GnuParser} @param <T> Type of the bean @param beanType Type of the bean @return Instance of an implementation of argument processor
[ "Create", "new", "instance", "with", "default", "parser", "a", "{", "@link", "GnuParser", "}" ]
train
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/ArgumentProcessor.java#L25-L27
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/map/AbstractIntDoubleMap.java
AbstractIntDoubleMap.keyOf
public int keyOf(final double value) { final int[] foundKey = new int[1]; boolean notFound = forEachPair( new IntDoubleProcedure() { public boolean apply(int iterKey, double iterValue) { boolean found = value == iterValue; if (found) foundKey[0] = iterKey; return !found; } } ); if (notFound) return Integer.MIN_VALUE; return foundKey[0]; }
java
public int keyOf(final double value) { final int[] foundKey = new int[1]; boolean notFound = forEachPair( new IntDoubleProcedure() { public boolean apply(int iterKey, double iterValue) { boolean found = value == iterValue; if (found) foundKey[0] = iterKey; return !found; } } ); if (notFound) return Integer.MIN_VALUE; return foundKey[0]; }
[ "public", "int", "keyOf", "(", "final", "double", "value", ")", "{", "final", "int", "[", "]", "foundKey", "=", "new", "int", "[", "1", "]", ";", "boolean", "notFound", "=", "forEachPair", "(", "new", "IntDoubleProcedure", "(", ")", "{", "public", "boolean", "apply", "(", "int", "iterKey", ",", "double", "iterValue", ")", "{", "boolean", "found", "=", "value", "==", "iterValue", ";", "if", "(", "found", ")", "foundKey", "[", "0", "]", "=", "iterKey", ";", "return", "!", "found", ";", "}", "}", ")", ";", "if", "(", "notFound", ")", "return", "Integer", ".", "MIN_VALUE", ";", "return", "foundKey", "[", "0", "]", ";", "}" ]
Returns the first key the given value is associated with. It is often a good idea to first check with {@link #containsValue(double)} whether there exists an association from a key to this value. Search order is guaranteed to be <i>identical</i> to the order used by method {@link #forEachKey(IntProcedure)}. @param value the value to search for. @return the first key for which holds <tt>get(key) == value</tt>; returns <tt>Integer.MIN_VALUE</tt> if no such key exists.
[ "Returns", "the", "first", "key", "the", "given", "value", "is", "associated", "with", ".", "It", "is", "often", "a", "good", "idea", "to", "first", "check", "with", "{", "@link", "#containsValue", "(", "double", ")", "}", "whether", "there", "exists", "an", "association", "from", "a", "key", "to", "this", "value", ".", "Search", "order", "is", "guaranteed", "to", "be", "<i", ">", "identical<", "/", "i", ">", "to", "the", "order", "used", "by", "method", "{", "@link", "#forEachKey", "(", "IntProcedure", ")", "}", "." ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/map/AbstractIntDoubleMap.java#L200-L213
playn/playn
scene/src/playn/scene/LayerUtil.java
LayerUtil.layerToScreen
public static Point layerToScreen(Layer layer, float x, float y) { Point into = new Point(x, y); return layerToScreen(layer, into, into); }
java
public static Point layerToScreen(Layer layer, float x, float y) { Point into = new Point(x, y); return layerToScreen(layer, into, into); }
[ "public", "static", "Point", "layerToScreen", "(", "Layer", "layer", ",", "float", "x", ",", "float", "y", ")", "{", "Point", "into", "=", "new", "Point", "(", "x", ",", "y", ")", ";", "return", "layerToScreen", "(", "layer", ",", "into", ",", "into", ")", ";", "}" ]
Converts the supplied point from coordinates relative to the specified layer to screen coordinates.
[ "Converts", "the", "supplied", "point", "from", "coordinates", "relative", "to", "the", "specified", "layer", "to", "screen", "coordinates", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/scene/src/playn/scene/LayerUtil.java#L44-L47
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.appendCopy
protected void appendCopy(RoaringArray sa, int startingIndex, int end) { extendArray(end - startingIndex); for (int i = startingIndex; i < end; ++i) { this.keys[this.size] = sa.keys[i]; this.values[this.size] = sa.values[i].clone(); this.size++; } }
java
protected void appendCopy(RoaringArray sa, int startingIndex, int end) { extendArray(end - startingIndex); for (int i = startingIndex; i < end; ++i) { this.keys[this.size] = sa.keys[i]; this.values[this.size] = sa.values[i].clone(); this.size++; } }
[ "protected", "void", "appendCopy", "(", "RoaringArray", "sa", ",", "int", "startingIndex", ",", "int", "end", ")", "{", "extendArray", "(", "end", "-", "startingIndex", ")", ";", "for", "(", "int", "i", "=", "startingIndex", ";", "i", "<", "end", ";", "++", "i", ")", "{", "this", ".", "keys", "[", "this", ".", "size", "]", "=", "sa", ".", "keys", "[", "i", "]", ";", "this", ".", "values", "[", "this", ".", "size", "]", "=", "sa", ".", "values", "[", "i", "]", ".", "clone", "(", ")", ";", "this", ".", "size", "++", ";", "}", "}" ]
Append copies of the values from another array @param sa other array @param startingIndex starting index in the other array @param end endingIndex (exclusive) in the other array
[ "Append", "copies", "of", "the", "values", "from", "another", "array" ]
train
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L208-L215
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java
ExpressRouteCrossConnectionsInner.createOrUpdateAsync
public Observable<ExpressRouteCrossConnectionInner> createOrUpdateAsync(String resourceGroupName, String crossConnectionName, ExpressRouteCrossConnectionInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, crossConnectionName, parameters).map(new Func1<ServiceResponse<ExpressRouteCrossConnectionInner>, ExpressRouteCrossConnectionInner>() { @Override public ExpressRouteCrossConnectionInner call(ServiceResponse<ExpressRouteCrossConnectionInner> response) { return response.body(); } }); }
java
public Observable<ExpressRouteCrossConnectionInner> createOrUpdateAsync(String resourceGroupName, String crossConnectionName, ExpressRouteCrossConnectionInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, crossConnectionName, parameters).map(new Func1<ServiceResponse<ExpressRouteCrossConnectionInner>, ExpressRouteCrossConnectionInner>() { @Override public ExpressRouteCrossConnectionInner call(ServiceResponse<ExpressRouteCrossConnectionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExpressRouteCrossConnectionInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "crossConnectionName", ",", "ExpressRouteCrossConnectionInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "crossConnectionName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ExpressRouteCrossConnectionInner", ">", ",", "ExpressRouteCrossConnectionInner", ">", "(", ")", "{", "@", "Override", "public", "ExpressRouteCrossConnectionInner", "call", "(", "ServiceResponse", "<", "ExpressRouteCrossConnectionInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Update the specified ExpressRouteCrossConnection. @param resourceGroupName The name of the resource group. @param crossConnectionName The name of the ExpressRouteCrossConnection. @param parameters Parameters supplied to the update express route crossConnection operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Update", "the", "specified", "ExpressRouteCrossConnection", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L471-L478
alkacon/opencms-core
src/org/opencms/ui/A_CmsUI.java
A_CmsUI.openPageOrWarn
public void openPageOrWarn(String link, String target) { openPageOrWarn(link, target, CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_POPUP_BLOCKED_0)); }
java
public void openPageOrWarn(String link, String target) { openPageOrWarn(link, target, CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_POPUP_BLOCKED_0)); }
[ "public", "void", "openPageOrWarn", "(", "String", "link", ",", "String", "target", ")", "{", "openPageOrWarn", "(", "link", ",", "target", ",", "CmsVaadinUtils", ".", "getMessageText", "(", "org", ".", "opencms", ".", "ui", ".", "Messages", ".", "GUI_POPUP_BLOCKED_0", ")", ")", ";", "}" ]
Tries to open a new browser window, and shows a warning if opening the window fails (usually because of popup blockers).<p> @param link the URL to open in the new window @param target the target window name
[ "Tries", "to", "open", "a", "new", "browser", "window", "and", "shows", "a", "warning", "if", "opening", "the", "window", "fails", "(", "usually", "because", "of", "popup", "blockers", ")", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/A_CmsUI.java#L230-L233
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/TypedMap.java
TypedMap.put
public V put(K pKey, V pValue) { if (!pKey.isCompatibleValue(pValue)) { throw new IllegalArgumentException("incompatible value for key"); } return entries.put(pKey, pValue); }
java
public V put(K pKey, V pValue) { if (!pKey.isCompatibleValue(pValue)) { throw new IllegalArgumentException("incompatible value for key"); } return entries.put(pKey, pValue); }
[ "public", "V", "put", "(", "K", "pKey", ",", "V", "pValue", ")", "{", "if", "(", "!", "pKey", ".", "isCompatibleValue", "(", "pValue", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"incompatible value for key\"", ")", ";", "}", "return", "entries", ".", "put", "(", "pKey", ",", "pValue", ")", ";", "}" ]
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. @param pKey key with which the specified value is to be associated. @param pValue value to be associated with the specified key. @return previous value associated with specified key, or {@code null} if there was no mapping for key. A {@code null} return can also indicate that the map previously associated {@code null} with the specified pKey, if the implementation supports {@code null} values. @throws IllegalArgumentException if the value is not compatible with the key. @see TypedMap.Key
[ "Associates", "the", "specified", "value", "with", "the", "specified", "key", "in", "this", "map", ".", "If", "the", "map", "previously", "contained", "a", "mapping", "for", "the", "key", "the", "old", "value", "is", "replaced", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/TypedMap.java#L202-L207
JM-Lab/utils-java8
src/main/java/kr/jm/utils/helper/JMThread.java
JMThread.getLimitedBlockingQueue
public static <E> BlockingQueue<E> getLimitedBlockingQueue(int maxQueue) { return new LinkedBlockingQueue<E>(maxQueue) { @Override public boolean offer(E e) { return putInsteadOfOffer(this, e); } }; }
java
public static <E> BlockingQueue<E> getLimitedBlockingQueue(int maxQueue) { return new LinkedBlockingQueue<E>(maxQueue) { @Override public boolean offer(E e) { return putInsteadOfOffer(this, e); } }; }
[ "public", "static", "<", "E", ">", "BlockingQueue", "<", "E", ">", "getLimitedBlockingQueue", "(", "int", "maxQueue", ")", "{", "return", "new", "LinkedBlockingQueue", "<", "E", ">", "(", "maxQueue", ")", "{", "@", "Override", "public", "boolean", "offer", "(", "E", "e", ")", "{", "return", "putInsteadOfOffer", "(", "this", ",", "e", ")", ";", "}", "}", ";", "}" ]
Gets limited blocking queue. @param <E> the type parameter @param maxQueue the max queue @return the limited blocking queue
[ "Gets", "limited", "blocking", "queue", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMThread.java#L598-L605
OpenLiberty/open-liberty
dev/com.ibm.ws.jca.inbound.security/src/com/ibm/ws/jca/security/internal/J2CSecurityHelper.java
J2CSecurityHelper.updateCustomHashtable
private static void updateCustomHashtable(Hashtable<String, Object> credData, String realmName, String uniqueId, String securityName, List<?> groupList) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "updateCustomHashtable", new Object[] { credData, realmName, uniqueId, securityName, groupList }); } String cacheKey = getCacheKey(uniqueId, realmName); credData.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, cacheKey); credData.put(AttributeNameConstants.WSCREDENTIAL_REALM, realmName); credData.put(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME, securityName); if (uniqueId != null) { credData.put(AttributeNameConstants.WSCREDENTIAL_UNIQUEID, uniqueId); } // If uniqueId is not set then the login will fail later and the work will not execute if (groupList != null && !groupList.isEmpty()) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Adding groups found in registry", groupList); } credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groupList); } else { credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, new ArrayList<String>()); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "updateCustomHashtable"); } }
java
private static void updateCustomHashtable(Hashtable<String, Object> credData, String realmName, String uniqueId, String securityName, List<?> groupList) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "updateCustomHashtable", new Object[] { credData, realmName, uniqueId, securityName, groupList }); } String cacheKey = getCacheKey(uniqueId, realmName); credData.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, cacheKey); credData.put(AttributeNameConstants.WSCREDENTIAL_REALM, realmName); credData.put(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME, securityName); if (uniqueId != null) { credData.put(AttributeNameConstants.WSCREDENTIAL_UNIQUEID, uniqueId); } // If uniqueId is not set then the login will fail later and the work will not execute if (groupList != null && !groupList.isEmpty()) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Adding groups found in registry", groupList); } credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groupList); } else { credData.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, new ArrayList<String>()); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "updateCustomHashtable"); } }
[ "private", "static", "void", "updateCustomHashtable", "(", "Hashtable", "<", "String", ",", "Object", ">", "credData", ",", "String", "realmName", ",", "String", "uniqueId", ",", "String", "securityName", ",", "List", "<", "?", ">", "groupList", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "entry", "(", "tc", ",", "\"updateCustomHashtable\"", ",", "new", "Object", "[", "]", "{", "credData", ",", "realmName", ",", "uniqueId", ",", "securityName", ",", "groupList", "}", ")", ";", "}", "String", "cacheKey", "=", "getCacheKey", "(", "uniqueId", ",", "realmName", ")", ";", "credData", ".", "put", "(", "AttributeNameConstants", ".", "WSCREDENTIAL_CACHE_KEY", ",", "cacheKey", ")", ";", "credData", ".", "put", "(", "AttributeNameConstants", ".", "WSCREDENTIAL_REALM", ",", "realmName", ")", ";", "credData", ".", "put", "(", "AttributeNameConstants", ".", "WSCREDENTIAL_SECURITYNAME", ",", "securityName", ")", ";", "if", "(", "uniqueId", "!=", "null", ")", "{", "credData", ".", "put", "(", "AttributeNameConstants", ".", "WSCREDENTIAL_UNIQUEID", ",", "uniqueId", ")", ";", "}", "// If uniqueId is not set then the login will fail later and the work will not execute", "if", "(", "groupList", "!=", "null", "&&", "!", "groupList", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"Adding groups found in registry\"", ",", "groupList", ")", ";", "}", "credData", ".", "put", "(", "AttributeNameConstants", ".", "WSCREDENTIAL_GROUPS", ",", "groupList", ")", ";", "}", "else", "{", "credData", ".", "put", "(", "AttributeNameConstants", ".", "WSCREDENTIAL_GROUPS", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ")", ";", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "exit", "(", "tc", ",", "\"updateCustomHashtable\"", ")", ";", "}", "}" ]
This method updates the hashtable provided with the information that is required for custom hashtable login. The hashtable should contain the following parameters for this to succeed. Key: com.ibm.wsspi.security.cred.uniqueId, Value: user: ldap.austin.ibm.com:389/cn=pbirk,o=ibm,c=us Key: com.ibm.wsspi.security.cred.realm, Value: ldap.austin.ibm.com:389 Key: com.ibm.wsspi.security.cred.securityName, Value: pbirk Key: com.ibm.wsspi.security.cred.longSecurityName, Value: cn=pbirk,o=ibm,c=us (Optional) Key: com.ibm.wsspi.security.cred.groups, Value: group:cn=group1,o=ibm,c=us| group:cn=group2,o=ibm,c=us|group:cn=group3,o=ibm,c=us Key: com.ibm.wsspi.security.cred.cacheKey, Value: Location:9.43.21.23 (note: accessID gets appended to this value for cache lookup). @param credData The hashtable that we are going to populate with the required properties @param realmName The name of the realm that this user belongs to @param uniqueId The uniqueId of the user @param securityName The securityName of the user. @param groupList The list of groups that this user belongs to.
[ "This", "method", "updates", "the", "hashtable", "provided", "with", "the", "information", "that", "is", "required", "for", "custom", "hashtable", "login", ".", "The", "hashtable", "should", "contain", "the", "following", "parameters", "for", "this", "to", "succeed", ".", "Key", ":", "com", ".", "ibm", ".", "wsspi", ".", "security", ".", "cred", ".", "uniqueId", "Value", ":", "user", ":", "ldap", ".", "austin", ".", "ibm", ".", "com", ":", "389", "/", "cn", "=", "pbirk", "o", "=", "ibm", "c", "=", "us", "Key", ":", "com", ".", "ibm", ".", "wsspi", ".", "security", ".", "cred", ".", "realm", "Value", ":", "ldap", ".", "austin", ".", "ibm", ".", "com", ":", "389", "Key", ":", "com", ".", "ibm", ".", "wsspi", ".", "security", ".", "cred", ".", "securityName", "Value", ":", "pbirk", "Key", ":", "com", ".", "ibm", ".", "wsspi", ".", "security", ".", "cred", ".", "longSecurityName", "Value", ":", "cn", "=", "pbirk", "o", "=", "ibm", "c", "=", "us", "(", "Optional", ")", "Key", ":", "com", ".", "ibm", ".", "wsspi", ".", "security", ".", "cred", ".", "groups", "Value", ":", "group", ":", "cn", "=", "group1", "o", "=", "ibm", "c", "=", "us|", "group", ":", "cn", "=", "group2", "o", "=", "ibm", "c", "=", "us|group", ":", "cn", "=", "group3", "o", "=", "ibm", "c", "=", "us", "Key", ":", "com", ".", "ibm", ".", "wsspi", ".", "security", ".", "cred", ".", "cacheKey", "Value", ":", "Location", ":", "9", ".", "43", ".", "21", ".", "23", "(", "note", ":", "accessID", "gets", "appended", "to", "this", "value", "for", "cache", "lookup", ")", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca.inbound.security/src/com/ibm/ws/jca/security/internal/J2CSecurityHelper.java#L82-L105
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/Range.java
Range.sumBoundaries
public Range sumBoundaries(final Range plus) { int newMin = min + plus.min; int newMax = max == RANGE_MAX || plus.max == RANGE_MAX ? RANGE_MAX : max + plus.max; return new Range(newMin, newMax); }
java
public Range sumBoundaries(final Range plus) { int newMin = min + plus.min; int newMax = max == RANGE_MAX || plus.max == RANGE_MAX ? RANGE_MAX : max + plus.max; return new Range(newMin, newMax); }
[ "public", "Range", "sumBoundaries", "(", "final", "Range", "plus", ")", "{", "int", "newMin", "=", "min", "+", "plus", ".", "min", ";", "int", "newMax", "=", "max", "==", "RANGE_MAX", "||", "plus", ".", "max", "==", "RANGE_MAX", "?", "RANGE_MAX", ":", "max", "+", "plus", ".", "max", ";", "return", "new", "Range", "(", "newMin", ",", "newMax", ")", ";", "}" ]
Sums the boundaries of this range with the ones of the passed. So the returned range has this.min + plus.min as minimum and this.max + plus.max as maximum respectively. @return a range object whose boundaries are summed
[ "Sums", "the", "boundaries", "of", "this", "range", "with", "the", "ones", "of", "the", "passed", ".", "So", "the", "returned", "range", "has", "this", ".", "min", "+", "plus", ".", "min", "as", "minimum", "and", "this", ".", "max", "+", "plus", ".", "max", "as", "maximum", "respectively", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/Range.java#L69-L73
jbundle/jbundle
thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageQueue.java
BaseMessageQueue.getMessageReceiver
public BaseMessageReceiver getMessageReceiver() { if (m_receiver == null) { m_receiver = this.createMessageReceiver(); if (m_receiver != null) new Thread(m_receiver, "MessageReceiver").start(); } return m_receiver; }
java
public BaseMessageReceiver getMessageReceiver() { if (m_receiver == null) { m_receiver = this.createMessageReceiver(); if (m_receiver != null) new Thread(m_receiver, "MessageReceiver").start(); } return m_receiver; }
[ "public", "BaseMessageReceiver", "getMessageReceiver", "(", ")", "{", "if", "(", "m_receiver", "==", "null", ")", "{", "m_receiver", "=", "this", ".", "createMessageReceiver", "(", ")", ";", "if", "(", "m_receiver", "!=", "null", ")", "new", "Thread", "(", "m_receiver", ",", "\"MessageReceiver\"", ")", ".", "start", "(", ")", ";", "}", "return", "m_receiver", ";", "}" ]
Get the message receiver. Create it if it doesn't exist. @return The message receiver.
[ "Get", "the", "message", "receiver", ".", "Create", "it", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageQueue.java#L170-L179
jgroups-extras/jgroups-kubernetes
src/main/java/org/jgroups/protocols/kubernetes/pem/Asn1Object.java
Asn1Object.getString
public String getString() throws IOException { String encoding; switch (type) { // Not all are Latin-1 but it's the closest thing case DerParser.NUMERIC_STRING: case DerParser.PRINTABLE_STRING: case DerParser.VIDEOTEX_STRING: case DerParser.IA5_STRING: case DerParser.GRAPHIC_STRING: case DerParser.ISO646_STRING: case DerParser.GENERAL_STRING: encoding = "ISO-8859-1"; //$NON-NLS-1$ break; case DerParser.BMP_STRING: encoding = "UTF-16BE"; //$NON-NLS-1$ break; case DerParser.UTF8_STRING: encoding = "UTF-8"; //$NON-NLS-1$ break; case DerParser.UNIVERSAL_STRING: throw new IOException("Invalid DER: can't handle UCS-4 string"); //$NON-NLS-1$ default: throw new IOException("Invalid DER: object is not a string"); //$NON-NLS-1$ } return new String(value, encoding); }
java
public String getString() throws IOException { String encoding; switch (type) { // Not all are Latin-1 but it's the closest thing case DerParser.NUMERIC_STRING: case DerParser.PRINTABLE_STRING: case DerParser.VIDEOTEX_STRING: case DerParser.IA5_STRING: case DerParser.GRAPHIC_STRING: case DerParser.ISO646_STRING: case DerParser.GENERAL_STRING: encoding = "ISO-8859-1"; //$NON-NLS-1$ break; case DerParser.BMP_STRING: encoding = "UTF-16BE"; //$NON-NLS-1$ break; case DerParser.UTF8_STRING: encoding = "UTF-8"; //$NON-NLS-1$ break; case DerParser.UNIVERSAL_STRING: throw new IOException("Invalid DER: can't handle UCS-4 string"); //$NON-NLS-1$ default: throw new IOException("Invalid DER: object is not a string"); //$NON-NLS-1$ } return new String(value, encoding); }
[ "public", "String", "getString", "(", ")", "throws", "IOException", "{", "String", "encoding", ";", "switch", "(", "type", ")", "{", "// Not all are Latin-1 but it's the closest thing\r", "case", "DerParser", ".", "NUMERIC_STRING", ":", "case", "DerParser", ".", "PRINTABLE_STRING", ":", "case", "DerParser", ".", "VIDEOTEX_STRING", ":", "case", "DerParser", ".", "IA5_STRING", ":", "case", "DerParser", ".", "GRAPHIC_STRING", ":", "case", "DerParser", ".", "ISO646_STRING", ":", "case", "DerParser", ".", "GENERAL_STRING", ":", "encoding", "=", "\"ISO-8859-1\"", ";", "//$NON-NLS-1$\r", "break", ";", "case", "DerParser", ".", "BMP_STRING", ":", "encoding", "=", "\"UTF-16BE\"", ";", "//$NON-NLS-1$\r", "break", ";", "case", "DerParser", ".", "UTF8_STRING", ":", "encoding", "=", "\"UTF-8\"", ";", "//$NON-NLS-1$\r", "break", ";", "case", "DerParser", ".", "UNIVERSAL_STRING", ":", "throw", "new", "IOException", "(", "\"Invalid DER: can't handle UCS-4 string\"", ")", ";", "//$NON-NLS-1$\r", "default", ":", "throw", "new", "IOException", "(", "\"Invalid DER: object is not a string\"", ")", ";", "//$NON-NLS-1$\r", "}", "return", "new", "String", "(", "value", ",", "encoding", ")", ";", "}" ]
Get value as string. Most strings are treated as Latin-1. @return Java string @throws IOException
[ "Get", "value", "as", "string", ".", "Most", "strings", "are", "treated", "as", "Latin", "-", "1", "." ]
train
https://github.com/jgroups-extras/jgroups-kubernetes/blob/f3e42b540c61e860e749c501849312c0c224f3fb/src/main/java/org/jgroups/protocols/kubernetes/pem/Asn1Object.java#L116-L149
future-architect/uroborosql
src/main/java/jp/co/future/uroborosql/converter/MapResultSetConverter.java
MapResultSetConverter.getValue
private Object getValue(final ResultSet rs, final ResultSetMetaData rsmd, final int columnIndex) throws SQLException { JavaType javaType = this.dialect.getJavaType(rsmd.getColumnType(columnIndex), rsmd.getColumnTypeName(columnIndex)); return this.mapperManager.getValue(javaType, rs, columnIndex); }
java
private Object getValue(final ResultSet rs, final ResultSetMetaData rsmd, final int columnIndex) throws SQLException { JavaType javaType = this.dialect.getJavaType(rsmd.getColumnType(columnIndex), rsmd.getColumnTypeName(columnIndex)); return this.mapperManager.getValue(javaType, rs, columnIndex); }
[ "private", "Object", "getValue", "(", "final", "ResultSet", "rs", ",", "final", "ResultSetMetaData", "rsmd", ",", "final", "int", "columnIndex", ")", "throws", "SQLException", "{", "JavaType", "javaType", "=", "this", ".", "dialect", ".", "getJavaType", "(", "rsmd", ".", "getColumnType", "(", "columnIndex", ")", ",", "rsmd", ".", "getColumnTypeName", "(", "columnIndex", ")", ")", ";", "return", "this", ".", "mapperManager", ".", "getValue", "(", "javaType", ",", "rs", ",", "columnIndex", ")", ";", "}" ]
ResultSetからMapperManager経由で値を取得する @param rs ResultSet @param rsmd ResultSetMetadata @param columnIndex カラムインデックス @return 指定したカラムインデックスの値 @throws SQLException
[ "ResultSetからMapperManager経由で値を取得する" ]
train
https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/converter/MapResultSetConverter.java#L91-L96
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.serviceName_datacenter_POST
public OvhTask serviceName_datacenter_POST(String serviceName, String commercialRangeName, String vrackName) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/datacenter"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "commercialRangeName", commercialRangeName); addBody(o, "vrackName", vrackName); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_datacenter_POST(String serviceName, String commercialRangeName, String vrackName) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/datacenter"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "commercialRangeName", commercialRangeName); addBody(o, "vrackName", vrackName); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_datacenter_POST", "(", "String", "serviceName", ",", "String", "commercialRangeName", ",", "String", "vrackName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/{serviceName}/datacenter\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"commercialRangeName\"", ",", "commercialRangeName", ")", ";", "addBody", "(", "o", ",", "\"vrackName\"", ",", "vrackName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Add a new Datacenter in your Private Cloud REST: POST /dedicatedCloud/{serviceName}/datacenter @param vrackName [required] Name of the Vrack link to the new datacenter. @param commercialRangeName [required] The commercial range of this new datacenter. You can see what commercial ranges are orderable on this API section : /dedicatedCloud/commercialRange/ @param serviceName [required] Domain of the service
[ "Add", "a", "new", "Datacenter", "in", "your", "Private", "Cloud" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1572-L1580
facebookarchive/hadoop-20
src/contrib/data_join/src/java/org/apache/hadoop/contrib/utils/join/JobBase.java
JobBase.addDoubleValue
protected Double addDoubleValue(Object name, double inc) { Double val = this.doubleCounters.get(name); Double retv = null; if (val == null) { retv = new Double(inc); } else { retv = new Double(val.doubleValue() + inc); } this.doubleCounters.put(name, retv); return retv; }
java
protected Double addDoubleValue(Object name, double inc) { Double val = this.doubleCounters.get(name); Double retv = null; if (val == null) { retv = new Double(inc); } else { retv = new Double(val.doubleValue() + inc); } this.doubleCounters.put(name, retv); return retv; }
[ "protected", "Double", "addDoubleValue", "(", "Object", "name", ",", "double", "inc", ")", "{", "Double", "val", "=", "this", ".", "doubleCounters", ".", "get", "(", "name", ")", ";", "Double", "retv", "=", "null", ";", "if", "(", "val", "==", "null", ")", "{", "retv", "=", "new", "Double", "(", "inc", ")", ";", "}", "else", "{", "retv", "=", "new", "Double", "(", "val", ".", "doubleValue", "(", ")", "+", "inc", ")", ";", "}", "this", ".", "doubleCounters", ".", "put", "(", "name", ",", "retv", ")", ";", "return", "retv", ";", "}" ]
Increment the given counter by the given incremental value If the counter does not exist, one is created with value 0. @param name the counter name @param inc the incremental value @return the updated value.
[ "Increment", "the", "given", "counter", "by", "the", "given", "incremental", "value", "If", "the", "counter", "does", "not", "exist", "one", "is", "created", "with", "value", "0", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/data_join/src/java/org/apache/hadoop/contrib/utils/join/JobBase.java#L121-L131
infinispan/infinispan
core/src/main/java/org/infinispan/cache/impl/CacheImpl.java
CacheImpl.getInvocationContextWithImplicitTransaction
InvocationContext getInvocationContextWithImplicitTransaction(int keyCount, boolean forceCreateTransaction) { InvocationContext invocationContext; boolean txInjected = false; if (transactional) { Transaction transaction = getOngoingTransaction(true); if (transaction == null && (forceCreateTransaction || config.transaction().autoCommit())) { transaction = tryBegin(); txInjected = true; } invocationContext = invocationContextFactory.createInvocationContext(transaction, txInjected); } else { invocationContext = invocationContextFactory.createInvocationContext(true, keyCount); } return invocationContext; }
java
InvocationContext getInvocationContextWithImplicitTransaction(int keyCount, boolean forceCreateTransaction) { InvocationContext invocationContext; boolean txInjected = false; if (transactional) { Transaction transaction = getOngoingTransaction(true); if (transaction == null && (forceCreateTransaction || config.transaction().autoCommit())) { transaction = tryBegin(); txInjected = true; } invocationContext = invocationContextFactory.createInvocationContext(transaction, txInjected); } else { invocationContext = invocationContextFactory.createInvocationContext(true, keyCount); } return invocationContext; }
[ "InvocationContext", "getInvocationContextWithImplicitTransaction", "(", "int", "keyCount", ",", "boolean", "forceCreateTransaction", ")", "{", "InvocationContext", "invocationContext", ";", "boolean", "txInjected", "=", "false", ";", "if", "(", "transactional", ")", "{", "Transaction", "transaction", "=", "getOngoingTransaction", "(", "true", ")", ";", "if", "(", "transaction", "==", "null", "&&", "(", "forceCreateTransaction", "||", "config", ".", "transaction", "(", ")", ".", "autoCommit", "(", ")", ")", ")", "{", "transaction", "=", "tryBegin", "(", ")", ";", "txInjected", "=", "true", ";", "}", "invocationContext", "=", "invocationContextFactory", ".", "createInvocationContext", "(", "transaction", ",", "txInjected", ")", ";", "}", "else", "{", "invocationContext", "=", "invocationContextFactory", ".", "createInvocationContext", "(", "true", ",", "keyCount", ")", ";", "}", "return", "invocationContext", ";", "}" ]
Same as {@link #getInvocationContextWithImplicitTransaction(int)} except if <b>forceCreateTransaction</b> is true then autoCommit doesn't have to be enabled to start a new transaction. @param keyCount how many keys are expected to be changed @param forceCreateTransaction if true then a transaction is always started if there wasn't one @return the invocation context
[ "Same", "as", "{", "@link", "#getInvocationContextWithImplicitTransaction", "(", "int", ")", "}", "except", "if", "<b", ">", "forceCreateTransaction<", "/", "b", ">", "is", "true", "then", "autoCommit", "doesn", "t", "have", "to", "be", "enabled", "to", "start", "a", "new", "transaction", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/cache/impl/CacheImpl.java#L1033-L1047
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.pathString
protected DocPath pathString(ClassDoc cd, DocPath name) { return pathString(cd.containingPackage(), name); }
java
protected DocPath pathString(ClassDoc cd, DocPath name) { return pathString(cd.containingPackage(), name); }
[ "protected", "DocPath", "pathString", "(", "ClassDoc", "cd", ",", "DocPath", "name", ")", "{", "return", "pathString", "(", "cd", ".", "containingPackage", "(", ")", ",", "name", ")", ";", "}" ]
Return the path to the class page for a classdoc. @param cd Class to which the path is requested. @param name Name of the file(doesn't include path).
[ "Return", "the", "path", "to", "the", "class", "page", "for", "a", "classdoc", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L914-L916
threerings/narya
core/src/main/java/com/threerings/crowd/chat/server/SpeakUtil.java
SpeakUtil.noteMessage
protected static void noteMessage (SpeakObject sender, Name username, UserMessage msg) { // fill in the message's time stamp if necessary if (msg.timestamp == 0L) { msg.timestamp = System.currentTimeMillis(); } // Log.info("Noted that " + username + " heard " + msg + "."); // notify any message observers _messageOp.init(sender, username, msg); _messageObs.apply(_messageOp); }
java
protected static void noteMessage (SpeakObject sender, Name username, UserMessage msg) { // fill in the message's time stamp if necessary if (msg.timestamp == 0L) { msg.timestamp = System.currentTimeMillis(); } // Log.info("Noted that " + username + " heard " + msg + "."); // notify any message observers _messageOp.init(sender, username, msg); _messageObs.apply(_messageOp); }
[ "protected", "static", "void", "noteMessage", "(", "SpeakObject", "sender", ",", "Name", "username", ",", "UserMessage", "msg", ")", "{", "// fill in the message's time stamp if necessary", "if", "(", "msg", ".", "timestamp", "==", "0L", ")", "{", "msg", ".", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "// Log.info(\"Noted that \" + username + \" heard \" + msg + \".\");", "// notify any message observers", "_messageOp", ".", "init", "(", "sender", ",", "username", ",", "msg", ")", ";", "_messageObs", ".", "apply", "(", "_messageOp", ")", ";", "}" ]
Notes that the specified user was privy to the specified message. If {@link ChatMessage#timestamp} is not already filled in, it will be.
[ "Notes", "that", "the", "specified", "user", "was", "privy", "to", "the", "specified", "message", ".", "If", "{" ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/SpeakUtil.java#L199-L211
hawkular/hawkular-inventory
hawkular-inventory-rest-api/src/main/java/org/hawkular/inventory/rest/ResponseUtil.java
ResponseUtil.createPagingHeader
public static void createPagingHeader(final Response.ResponseBuilder builder, final UriInfo uriInfo, final Page<?> resultList) { UriBuilder uriBuilder; PageContext pc = resultList.getPageContext(); int page = pc.getPageNumber(); List<Link> links = new ArrayList<>(); if (pc.isLimited() && resultList.getTotalSize() > (pc.getPageNumber() + 1) * pc.getPageSize()) { int nextPage = page + 1; uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", nextPage); links.add(new Link("next", uriBuilder.build().toString())); } if (page > 0) { int prevPage = page - 1; uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", prevPage); links.add(new Link("prev", uriBuilder.build().toString())); } // A link to the last page if (pc.isLimited()) { long lastPage = resultList.getTotalSize() / pc.getPageSize(); if (resultList.getTotalSize() % pc.getPageSize() == 0) { lastPage -= 1; } uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", lastPage); links.add(new Link("last", uriBuilder.build().toString())); } // A link to the current page uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed StringBuilder linkHeader = new StringBuilder(new Link("current", uriBuilder.build().toString()) .rfc5988String()); //followed by the rest of the link defined above links.forEach((l) -> linkHeader.append(", ").append(l.rfc5988String())); //add that all as a single Link header to the response builder.header("Link", linkHeader.toString()); // Create a total size header builder.header("X-Total-Count", resultList.getTotalSize()); }
java
public static void createPagingHeader(final Response.ResponseBuilder builder, final UriInfo uriInfo, final Page<?> resultList) { UriBuilder uriBuilder; PageContext pc = resultList.getPageContext(); int page = pc.getPageNumber(); List<Link> links = new ArrayList<>(); if (pc.isLimited() && resultList.getTotalSize() > (pc.getPageNumber() + 1) * pc.getPageSize()) { int nextPage = page + 1; uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", nextPage); links.add(new Link("next", uriBuilder.build().toString())); } if (page > 0) { int prevPage = page - 1; uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", prevPage); links.add(new Link("prev", uriBuilder.build().toString())); } // A link to the last page if (pc.isLimited()) { long lastPage = resultList.getTotalSize() / pc.getPageSize(); if (resultList.getTotalSize() % pc.getPageSize() == 0) { lastPage -= 1; } uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed uriBuilder.replaceQueryParam("page", lastPage); links.add(new Link("last", uriBuilder.build().toString())); } // A link to the current page uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed StringBuilder linkHeader = new StringBuilder(new Link("current", uriBuilder.build().toString()) .rfc5988String()); //followed by the rest of the link defined above links.forEach((l) -> linkHeader.append(", ").append(l.rfc5988String())); //add that all as a single Link header to the response builder.header("Link", linkHeader.toString()); // Create a total size header builder.header("X-Total-Count", resultList.getTotalSize()); }
[ "public", "static", "void", "createPagingHeader", "(", "final", "Response", ".", "ResponseBuilder", "builder", ",", "final", "UriInfo", "uriInfo", ",", "final", "Page", "<", "?", ">", "resultList", ")", "{", "UriBuilder", "uriBuilder", ";", "PageContext", "pc", "=", "resultList", ".", "getPageContext", "(", ")", ";", "int", "page", "=", "pc", ".", "getPageNumber", "(", ")", ";", "List", "<", "Link", ">", "links", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "pc", ".", "isLimited", "(", ")", "&&", "resultList", ".", "getTotalSize", "(", ")", ">", "(", "pc", ".", "getPageNumber", "(", ")", "+", "1", ")", "*", "pc", ".", "getPageSize", "(", ")", ")", "{", "int", "nextPage", "=", "page", "+", "1", ";", "uriBuilder", "=", "uriInfo", ".", "getRequestUriBuilder", "(", ")", ";", "// adds ?q, ?per_page, ?page, etc. if needed", "uriBuilder", ".", "replaceQueryParam", "(", "\"page\"", ",", "nextPage", ")", ";", "links", ".", "add", "(", "new", "Link", "(", "\"next\"", ",", "uriBuilder", ".", "build", "(", ")", ".", "toString", "(", ")", ")", ")", ";", "}", "if", "(", "page", ">", "0", ")", "{", "int", "prevPage", "=", "page", "-", "1", ";", "uriBuilder", "=", "uriInfo", ".", "getRequestUriBuilder", "(", ")", ";", "// adds ?q, ?per_page, ?page, etc. if needed", "uriBuilder", ".", "replaceQueryParam", "(", "\"page\"", ",", "prevPage", ")", ";", "links", ".", "add", "(", "new", "Link", "(", "\"prev\"", ",", "uriBuilder", ".", "build", "(", ")", ".", "toString", "(", ")", ")", ")", ";", "}", "// A link to the last page", "if", "(", "pc", ".", "isLimited", "(", ")", ")", "{", "long", "lastPage", "=", "resultList", ".", "getTotalSize", "(", ")", "/", "pc", ".", "getPageSize", "(", ")", ";", "if", "(", "resultList", ".", "getTotalSize", "(", ")", "%", "pc", ".", "getPageSize", "(", ")", "==", "0", ")", "{", "lastPage", "-=", "1", ";", "}", "uriBuilder", "=", "uriInfo", ".", "getRequestUriBuilder", "(", ")", ";", "// adds ?q, ?per_page, ?page, etc. if needed", "uriBuilder", ".", "replaceQueryParam", "(", "\"page\"", ",", "lastPage", ")", ";", "links", ".", "add", "(", "new", "Link", "(", "\"last\"", ",", "uriBuilder", ".", "build", "(", ")", ".", "toString", "(", ")", ")", ")", ";", "}", "// A link to the current page", "uriBuilder", "=", "uriInfo", ".", "getRequestUriBuilder", "(", ")", ";", "// adds ?q, ?per_page, ?page, etc. if needed", "StringBuilder", "linkHeader", "=", "new", "StringBuilder", "(", "new", "Link", "(", "\"current\"", ",", "uriBuilder", ".", "build", "(", ")", ".", "toString", "(", ")", ")", ".", "rfc5988String", "(", ")", ")", ";", "//followed by the rest of the link defined above", "links", ".", "forEach", "(", "(", "l", ")", "-", ">", "linkHeader", ".", "append", "(", "\", \"", ")", ".", "append", "(", "l", ".", "rfc5988String", "(", ")", ")", ")", ";", "//add that all as a single Link header to the response", "builder", ".", "header", "(", "\"Link\"", ",", "linkHeader", ".", "toString", "(", ")", ")", ";", "// Create a total size header", "builder", ".", "header", "(", "\"X-Total-Count\"", ",", "resultList", ".", "getTotalSize", "(", ")", ")", ";", "}" ]
Create the paging headers for collections and attach them to the passed builder. Those are represented as <i>Link:</i> http headers that carry the URL for the pages and the respective relation. <br/>In addition a <i>X-Total-Count</i> header is created that contains the whole collection size. @param builder The ResponseBuilder that receives the headers @param uriInfo The uriInfo of the incoming request to build the urls @param resultList The collection with its paging information
[ "Create", "the", "paging", "headers", "for", "collections", "and", "attach", "them", "to", "the", "passed", "builder", ".", "Those", "are", "represented", "as", "<i", ">", "Link", ":", "<", "/", "i", ">", "http", "headers", "that", "carry", "the", "URL", "for", "the", "pages", "and", "the", "respective", "relation", ".", "<br", "/", ">", "In", "addition", "a", "<i", ">", "X", "-", "Total", "-", "Count<", "/", "i", ">", "header", "is", "created", "that", "contains", "the", "whole", "collection", "size", "." ]
train
https://github.com/hawkular/hawkular-inventory/blob/f56dc10323dca21777feb5b609a9e9cc70ffaf62/hawkular-inventory-rest-api/src/main/java/org/hawkular/inventory/rest/ResponseUtil.java#L176-L227