repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/destination/subscription/DurableSubscriptionManager.java
DurableSubscriptionManager.isRegistered
public boolean isRegistered( String clientID , String subscriptionName ) { """ Test if a durable subscription exists @param clientID @param subscriptionName @return true if the subscription exists """ String key = clientID+"-"+subscriptionName; return subscriptions.containsKey(key); }
java
public boolean isRegistered( String clientID , String subscriptionName ) { String key = clientID+"-"+subscriptionName; return subscriptions.containsKey(key); }
[ "public", "boolean", "isRegistered", "(", "String", "clientID", ",", "String", "subscriptionName", ")", "{", "String", "key", "=", "clientID", "+", "\"-\"", "+", "subscriptionName", ";", "return", "subscriptions", ".", "containsKey", "(", "key", ")", ";", "}" ]
Test if a durable subscription exists @param clientID @param subscriptionName @return true if the subscription exists
[ "Test", "if", "a", "durable", "subscription", "exists" ]
train
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/destination/subscription/DurableSubscriptionManager.java#L73-L77
indeedeng/proctor
proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java
SvnWorkspaceProviderImpl.formatDirName
private static String formatDirName(final String prefix, final String suffix) { """ Returns the expected name of a workspace for a given suffix @param suffix @return """ // Replace all invalid characters with '-' final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate(); return String.format("%s-%s", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-')); }
java
private static String formatDirName(final String prefix, final String suffix) { // Replace all invalid characters with '-' final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate(); return String.format("%s-%s", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-')); }
[ "private", "static", "String", "formatDirName", "(", "final", "String", "prefix", ",", "final", "String", "suffix", ")", "{", "// Replace all invalid characters with '-'", "final", "CharMatcher", "invalidCharacters", "=", "VALID_SUFFIX_CHARS", ".", "negate", "(", ")", ";", "return", "String", ".", "format", "(", "\"%s-%s\"", ",", "prefix", ",", "invalidCharacters", ".", "trimAndCollapseFrom", "(", "suffix", ".", "toLowerCase", "(", ")", ",", "'", "'", ")", ")", ";", "}" ]
Returns the expected name of a workspace for a given suffix @param suffix @return
[ "Returns", "the", "expected", "name", "of", "a", "workspace", "for", "a", "given", "suffix" ]
train
https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java#L180-L184
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/quantiles/Util.java
Util.computeRetainedItems
static int computeRetainedItems(final int k, final long n) { """ Returns the number of retained valid items in the sketch given k and n. @param k the given configured k of the sketch @param n the current number of items seen by the sketch @return the number of retained items in the sketch given k and n. """ final int bbCnt = computeBaseBufferItems(k, n); final long bitPattern = computeBitPattern(k, n); final int validLevels = computeValidLevels(bitPattern); return bbCnt + (validLevels * k); }
java
static int computeRetainedItems(final int k, final long n) { final int bbCnt = computeBaseBufferItems(k, n); final long bitPattern = computeBitPattern(k, n); final int validLevels = computeValidLevels(bitPattern); return bbCnt + (validLevels * k); }
[ "static", "int", "computeRetainedItems", "(", "final", "int", "k", ",", "final", "long", "n", ")", "{", "final", "int", "bbCnt", "=", "computeBaseBufferItems", "(", "k", ",", "n", ")", ";", "final", "long", "bitPattern", "=", "computeBitPattern", "(", "k", ",", "n", ")", ";", "final", "int", "validLevels", "=", "computeValidLevels", "(", "bitPattern", ")", ";", "return", "bbCnt", "+", "(", "validLevels", "*", "k", ")", ";", "}" ]
Returns the number of retained valid items in the sketch given k and n. @param k the given configured k of the sketch @param n the current number of items seen by the sketch @return the number of retained items in the sketch given k and n.
[ "Returns", "the", "number", "of", "retained", "valid", "items", "in", "the", "sketch", "given", "k", "and", "n", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L321-L326
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.executeLargeBatch
@Override public long[] executeLargeBatch() throws SQLException { """ Execute batch, like executeBatch(), with returning results with long[]. For when row count may exceed Integer.MAX_VALUE. @return an array of update counts (one element for each command in the batch) @throws SQLException if a database error occur. """ checkClose(); int size; if (batchQueries == null || (size = batchQueries.size()) == 0) { return new long[0]; } lock.lock(); try { internalBatchExecution(size); return results.getCmdInformation().getLargeUpdateCounts(); } catch (SQLException initialSqlEx) { throw executeBatchExceptionEpilogue(initialSqlEx, size); } finally { executeBatchEpilogue(); lock.unlock(); } }
java
@Override public long[] executeLargeBatch() throws SQLException { checkClose(); int size; if (batchQueries == null || (size = batchQueries.size()) == 0) { return new long[0]; } lock.lock(); try { internalBatchExecution(size); return results.getCmdInformation().getLargeUpdateCounts(); } catch (SQLException initialSqlEx) { throw executeBatchExceptionEpilogue(initialSqlEx, size); } finally { executeBatchEpilogue(); lock.unlock(); } }
[ "@", "Override", "public", "long", "[", "]", "executeLargeBatch", "(", ")", "throws", "SQLException", "{", "checkClose", "(", ")", ";", "int", "size", ";", "if", "(", "batchQueries", "==", "null", "||", "(", "size", "=", "batchQueries", ".", "size", "(", ")", ")", "==", "0", ")", "{", "return", "new", "long", "[", "0", "]", ";", "}", "lock", ".", "lock", "(", ")", ";", "try", "{", "internalBatchExecution", "(", "size", ")", ";", "return", "results", ".", "getCmdInformation", "(", ")", ".", "getLargeUpdateCounts", "(", ")", ";", "}", "catch", "(", "SQLException", "initialSqlEx", ")", "{", "throw", "executeBatchExceptionEpilogue", "(", "initialSqlEx", ",", "size", ")", ";", "}", "finally", "{", "executeBatchEpilogue", "(", ")", ";", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Execute batch, like executeBatch(), with returning results with long[]. For when row count may exceed Integer.MAX_VALUE. @return an array of update counts (one element for each command in the batch) @throws SQLException if a database error occur.
[ "Execute", "batch", "like", "executeBatch", "()", "with", "returning", "results", "with", "long", "[]", ".", "For", "when", "row", "count", "may", "exceed", "Integer", ".", "MAX_VALUE", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L1310-L1329
hamcrest/hamcrest-junit
src/main/java/org/hamcrest/junit/MatcherAssume.java
MatcherAssume.assumeThat
public static <T> void assumeThat(String message, T actual, Matcher<? super T> matcher) { """ Call to assume that <code>actual</code> satisfies the condition specified by <code>matcher</code>. If not, the test halts and is ignored. Example: <pre>: assumeThat(1, is(1)); // passes foo(); // will execute assumeThat(0, is(1)); // assumption failure! test halts int x = 1 / 0; // will never execute </pre> @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} @param actual the computed value being compared @param matcher an expression, built of {@link Matcher}s, specifying allowed values @see org.hamcrest.CoreMatchers @see JUnitMatchers """ Matching.checkMatch(message, actual, matcher, new MismatchAction() { @Override public void mismatch(String description) { throw new AssumptionViolatedException(description); } }); }
java
public static <T> void assumeThat(String message, T actual, Matcher<? super T> matcher) { Matching.checkMatch(message, actual, matcher, new MismatchAction() { @Override public void mismatch(String description) { throw new AssumptionViolatedException(description); } }); }
[ "public", "static", "<", "T", ">", "void", "assumeThat", "(", "String", "message", ",", "T", "actual", ",", "Matcher", "<", "?", "super", "T", ">", "matcher", ")", "{", "Matching", ".", "checkMatch", "(", "message", ",", "actual", ",", "matcher", ",", "new", "MismatchAction", "(", ")", "{", "@", "Override", "public", "void", "mismatch", "(", "String", "description", ")", "{", "throw", "new", "AssumptionViolatedException", "(", "description", ")", ";", "}", "}", ")", ";", "}" ]
Call to assume that <code>actual</code> satisfies the condition specified by <code>matcher</code>. If not, the test halts and is ignored. Example: <pre>: assumeThat(1, is(1)); // passes foo(); // will execute assumeThat(0, is(1)); // assumption failure! test halts int x = 1 / 0; // will never execute </pre> @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} @param actual the computed value being compared @param matcher an expression, built of {@link Matcher}s, specifying allowed values @see org.hamcrest.CoreMatchers @see JUnitMatchers
[ "Call", "to", "assume", "that", "<code", ">", "actual<", "/", "code", ">", "satisfies", "the", "condition", "specified", "by", "<code", ">", "matcher<", "/", "code", ">", ".", "If", "not", "the", "test", "halts", "and", "is", "ignored", ".", "Example", ":", "<pre", ">", ":", "assumeThat", "(", "1", "is", "(", "1", "))", ";", "//", "passes", "foo", "()", ";", "//", "will", "execute", "assumeThat", "(", "0", "is", "(", "1", "))", ";", "//", "assumption", "failure!", "test", "halts", "int", "x", "=", "1", "/", "0", ";", "//", "will", "never", "execute", "<", "/", "pre", ">" ]
train
https://github.com/hamcrest/hamcrest-junit/blob/5e02d55230b560f255433bcc490afaeda9e1a043/src/main/java/org/hamcrest/junit/MatcherAssume.java#L71-L78
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/geometry/BondTools.java
BondTools.stereosAreOpposite
public static boolean stereosAreOpposite(IAtomContainer container, IAtom atom) { """ Says if of four atoms connected two one atom the up and down bonds are opposite or not, i. e.if it's tetrehedral or square planar. The method does not check if there are four atoms and if two or up and two are down @param atom The atom which is the center @param container The atomContainer the atom is in @return true=are opposite, false=are not """ List<IAtom> atoms = container.getConnectedAtomsList(atom); TreeMap<Double, Integer> hm = new TreeMap<Double, Integer>(); for (int i = 1; i < atoms.size(); i++) { hm.put(giveAngle(atom, atoms.get(0), atoms.get(i)), i); } Object[] ohere = hm.values().toArray(); IBond.Stereo stereoOne = container.getBond(atom, atoms.get(0)).getStereo(); IBond.Stereo stereoOpposite = container.getBond(atom, atoms.get((Integer) ohere[1])).getStereo(); return stereoOpposite == stereoOne; }
java
public static boolean stereosAreOpposite(IAtomContainer container, IAtom atom) { List<IAtom> atoms = container.getConnectedAtomsList(atom); TreeMap<Double, Integer> hm = new TreeMap<Double, Integer>(); for (int i = 1; i < atoms.size(); i++) { hm.put(giveAngle(atom, atoms.get(0), atoms.get(i)), i); } Object[] ohere = hm.values().toArray(); IBond.Stereo stereoOne = container.getBond(atom, atoms.get(0)).getStereo(); IBond.Stereo stereoOpposite = container.getBond(atom, atoms.get((Integer) ohere[1])).getStereo(); return stereoOpposite == stereoOne; }
[ "public", "static", "boolean", "stereosAreOpposite", "(", "IAtomContainer", "container", ",", "IAtom", "atom", ")", "{", "List", "<", "IAtom", ">", "atoms", "=", "container", ".", "getConnectedAtomsList", "(", "atom", ")", ";", "TreeMap", "<", "Double", ",", "Integer", ">", "hm", "=", "new", "TreeMap", "<", "Double", ",", "Integer", ">", "(", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "atoms", ".", "size", "(", ")", ";", "i", "++", ")", "{", "hm", ".", "put", "(", "giveAngle", "(", "atom", ",", "atoms", ".", "get", "(", "0", ")", ",", "atoms", ".", "get", "(", "i", ")", ")", ",", "i", ")", ";", "}", "Object", "[", "]", "ohere", "=", "hm", ".", "values", "(", ")", ".", "toArray", "(", ")", ";", "IBond", ".", "Stereo", "stereoOne", "=", "container", ".", "getBond", "(", "atom", ",", "atoms", ".", "get", "(", "0", ")", ")", ".", "getStereo", "(", ")", ";", "IBond", ".", "Stereo", "stereoOpposite", "=", "container", ".", "getBond", "(", "atom", ",", "atoms", ".", "get", "(", "(", "Integer", ")", "ohere", "[", "1", "]", ")", ")", ".", "getStereo", "(", ")", ";", "return", "stereoOpposite", "==", "stereoOne", ";", "}" ]
Says if of four atoms connected two one atom the up and down bonds are opposite or not, i. e.if it's tetrehedral or square planar. The method does not check if there are four atoms and if two or up and two are down @param atom The atom which is the center @param container The atomContainer the atom is in @return true=are opposite, false=are not
[ "Says", "if", "of", "four", "atoms", "connected", "two", "one", "atom", "the", "up", "and", "down", "bonds", "are", "opposite", "or", "not", "i", ".", "e", ".", "if", "it", "s", "tetrehedral", "or", "square", "planar", ".", "The", "method", "does", "not", "check", "if", "there", "are", "four", "atoms", "and", "if", "two", "or", "up", "and", "two", "are", "down" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/geometry/BondTools.java#L511-L521
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/PointSerializer.java
PointSerializer.writeShapeSpecificSerialization
@Override public void writeShapeSpecificSerialization(Point value, JsonGenerator jgen, SerializerProvider provider) throws IOException { """ Method that can be called to ask implementation to serialize values of type this serializer handles. @param value Value to serialize; can not be null. @param jgen Generator used to output resulting Json content @param provider Provider that can be used to get serializers for serializing Objects value contains, if any. @throws java.io.IOException If serialization failed. """ jgen.writeFieldName("type"); jgen.writeString("Point"); jgen.writeArrayFieldStart("coordinates"); // set beanproperty to null since we are not serializing a real property JsonSerializer<Object> ser = provider.findValueSerializer(Float.class, null); ser.serialize((float)value.getX(), jgen, provider); ser.serialize((float)value.getY(), jgen, provider); jgen.writeEndArray(); }
java
@Override public void writeShapeSpecificSerialization(Point value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeFieldName("type"); jgen.writeString("Point"); jgen.writeArrayFieldStart("coordinates"); // set beanproperty to null since we are not serializing a real property JsonSerializer<Object> ser = provider.findValueSerializer(Float.class, null); ser.serialize((float)value.getX(), jgen, provider); ser.serialize((float)value.getY(), jgen, provider); jgen.writeEndArray(); }
[ "@", "Override", "public", "void", "writeShapeSpecificSerialization", "(", "Point", "value", ",", "JsonGenerator", "jgen", ",", "SerializerProvider", "provider", ")", "throws", "IOException", "{", "jgen", ".", "writeFieldName", "(", "\"type\"", ")", ";", "jgen", ".", "writeString", "(", "\"Point\"", ")", ";", "jgen", ".", "writeArrayFieldStart", "(", "\"coordinates\"", ")", ";", "// set beanproperty to null since we are not serializing a real property", "JsonSerializer", "<", "Object", ">", "ser", "=", "provider", ".", "findValueSerializer", "(", "Float", ".", "class", ",", "null", ")", ";", "ser", ".", "serialize", "(", "(", "float", ")", "value", ".", "getX", "(", ")", ",", "jgen", ",", "provider", ")", ";", "ser", ".", "serialize", "(", "(", "float", ")", "value", ".", "getY", "(", ")", ",", "jgen", ",", "provider", ")", ";", "jgen", ".", "writeEndArray", "(", ")", ";", "}" ]
Method that can be called to ask implementation to serialize values of type this serializer handles. @param value Value to serialize; can not be null. @param jgen Generator used to output resulting Json content @param provider Provider that can be used to get serializers for serializing Objects value contains, if any. @throws java.io.IOException If serialization failed.
[ "Method", "that", "can", "be", "called", "to", "ask", "implementation", "to", "serialize", "values", "of", "type", "this", "serializer", "handles", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/PointSerializer.java#L57-L68
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/AbstractSarlScriptInteractiveSelector.java
AbstractSarlScriptInteractiveSelector.searchAndSelect
public ElementDescription searchAndSelect(boolean showEmptySelectionError, Object... scope) { """ Search the elements based on the given scope, and select one. If more than one element was found, the user selects interactively one. @param showEmptySelectionError indicates if this function shows an error when the selection is empty. @param scope the elements to consider for an element type that can be launched. @return the selected element; or {@code null} if there is no selection. """ try { final List<ElementDescription> elements = findElements(scope, PlatformUI.getWorkbench().getProgressService()); ElementDescription element = null; if (elements == null || elements.isEmpty()) { if (showEmptySelectionError) { SARLEclipsePlugin.getDefault().openError(getShell(), Messages.AbstractSarlScriptInteractiveSelector_1, MessageFormat.format(Messages.AbstractSarlScriptInteractiveSelector_2, getElementLabel()), null); } } else if (elements.size() > 1) { element = chooseElement(elements); } else { element = elements.get(0); } return element; } catch (InterruptedException exception) { // } catch (Exception exception) { SARLEclipsePlugin.getDefault().openError(getShell(), Messages.AbstractSarlScriptInteractiveSelector_1, null, exception); } return null; }
java
public ElementDescription searchAndSelect(boolean showEmptySelectionError, Object... scope) { try { final List<ElementDescription> elements = findElements(scope, PlatformUI.getWorkbench().getProgressService()); ElementDescription element = null; if (elements == null || elements.isEmpty()) { if (showEmptySelectionError) { SARLEclipsePlugin.getDefault().openError(getShell(), Messages.AbstractSarlScriptInteractiveSelector_1, MessageFormat.format(Messages.AbstractSarlScriptInteractiveSelector_2, getElementLabel()), null); } } else if (elements.size() > 1) { element = chooseElement(elements); } else { element = elements.get(0); } return element; } catch (InterruptedException exception) { // } catch (Exception exception) { SARLEclipsePlugin.getDefault().openError(getShell(), Messages.AbstractSarlScriptInteractiveSelector_1, null, exception); } return null; }
[ "public", "ElementDescription", "searchAndSelect", "(", "boolean", "showEmptySelectionError", ",", "Object", "...", "scope", ")", "{", "try", "{", "final", "List", "<", "ElementDescription", ">", "elements", "=", "findElements", "(", "scope", ",", "PlatformUI", ".", "getWorkbench", "(", ")", ".", "getProgressService", "(", ")", ")", ";", "ElementDescription", "element", "=", "null", ";", "if", "(", "elements", "==", "null", "||", "elements", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "showEmptySelectionError", ")", "{", "SARLEclipsePlugin", ".", "getDefault", "(", ")", ".", "openError", "(", "getShell", "(", ")", ",", "Messages", ".", "AbstractSarlScriptInteractiveSelector_1", ",", "MessageFormat", ".", "format", "(", "Messages", ".", "AbstractSarlScriptInteractiveSelector_2", ",", "getElementLabel", "(", ")", ")", ",", "null", ")", ";", "}", "}", "else", "if", "(", "elements", ".", "size", "(", ")", ">", "1", ")", "{", "element", "=", "chooseElement", "(", "elements", ")", ";", "}", "else", "{", "element", "=", "elements", ".", "get", "(", "0", ")", ";", "}", "return", "element", ";", "}", "catch", "(", "InterruptedException", "exception", ")", "{", "//", "}", "catch", "(", "Exception", "exception", ")", "{", "SARLEclipsePlugin", ".", "getDefault", "(", ")", ".", "openError", "(", "getShell", "(", ")", ",", "Messages", ".", "AbstractSarlScriptInteractiveSelector_1", ",", "null", ",", "exception", ")", ";", "}", "return", "null", ";", "}" ]
Search the elements based on the given scope, and select one. If more than one element was found, the user selects interactively one. @param showEmptySelectionError indicates if this function shows an error when the selection is empty. @param scope the elements to consider for an element type that can be launched. @return the selected element; or {@code null} if there is no selection.
[ "Search", "the", "elements", "based", "on", "the", "given", "scope", "and", "select", "one", ".", "If", "more", "than", "one", "element", "was", "found", "the", "user", "selects", "interactively", "one", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/AbstractSarlScriptInteractiveSelector.java#L277-L301
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java
SlotManager.registerTaskManager
public void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport) { """ Registers a new task manager at the slot manager. This will make the task managers slots known and, thus, available for allocation. @param taskExecutorConnection for the new task manager @param initialSlotReport for the new task manager """ checkInit(); LOG.debug("Registering TaskManager {} under {} at the SlotManager.", taskExecutorConnection.getResourceID(), taskExecutorConnection.getInstanceID()); // we identify task managers by their instance id if (taskManagerRegistrations.containsKey(taskExecutorConnection.getInstanceID())) { reportSlotStatus(taskExecutorConnection.getInstanceID(), initialSlotReport); } else { // first register the TaskManager ArrayList<SlotID> reportedSlots = new ArrayList<>(); for (SlotStatus slotStatus : initialSlotReport) { reportedSlots.add(slotStatus.getSlotID()); } TaskManagerRegistration taskManagerRegistration = new TaskManagerRegistration( taskExecutorConnection, reportedSlots); taskManagerRegistrations.put(taskExecutorConnection.getInstanceID(), taskManagerRegistration); // next register the new slots for (SlotStatus slotStatus : initialSlotReport) { registerSlot( slotStatus.getSlotID(), slotStatus.getAllocationID(), slotStatus.getJobID(), slotStatus.getResourceProfile(), taskExecutorConnection); } } }
java
public void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport) { checkInit(); LOG.debug("Registering TaskManager {} under {} at the SlotManager.", taskExecutorConnection.getResourceID(), taskExecutorConnection.getInstanceID()); // we identify task managers by their instance id if (taskManagerRegistrations.containsKey(taskExecutorConnection.getInstanceID())) { reportSlotStatus(taskExecutorConnection.getInstanceID(), initialSlotReport); } else { // first register the TaskManager ArrayList<SlotID> reportedSlots = new ArrayList<>(); for (SlotStatus slotStatus : initialSlotReport) { reportedSlots.add(slotStatus.getSlotID()); } TaskManagerRegistration taskManagerRegistration = new TaskManagerRegistration( taskExecutorConnection, reportedSlots); taskManagerRegistrations.put(taskExecutorConnection.getInstanceID(), taskManagerRegistration); // next register the new slots for (SlotStatus slotStatus : initialSlotReport) { registerSlot( slotStatus.getSlotID(), slotStatus.getAllocationID(), slotStatus.getJobID(), slotStatus.getResourceProfile(), taskExecutorConnection); } } }
[ "public", "void", "registerTaskManager", "(", "final", "TaskExecutorConnection", "taskExecutorConnection", ",", "SlotReport", "initialSlotReport", ")", "{", "checkInit", "(", ")", ";", "LOG", ".", "debug", "(", "\"Registering TaskManager {} under {} at the SlotManager.\"", ",", "taskExecutorConnection", ".", "getResourceID", "(", ")", ",", "taskExecutorConnection", ".", "getInstanceID", "(", ")", ")", ";", "// we identify task managers by their instance id", "if", "(", "taskManagerRegistrations", ".", "containsKey", "(", "taskExecutorConnection", ".", "getInstanceID", "(", ")", ")", ")", "{", "reportSlotStatus", "(", "taskExecutorConnection", ".", "getInstanceID", "(", ")", ",", "initialSlotReport", ")", ";", "}", "else", "{", "// first register the TaskManager", "ArrayList", "<", "SlotID", ">", "reportedSlots", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "SlotStatus", "slotStatus", ":", "initialSlotReport", ")", "{", "reportedSlots", ".", "add", "(", "slotStatus", ".", "getSlotID", "(", ")", ")", ";", "}", "TaskManagerRegistration", "taskManagerRegistration", "=", "new", "TaskManagerRegistration", "(", "taskExecutorConnection", ",", "reportedSlots", ")", ";", "taskManagerRegistrations", ".", "put", "(", "taskExecutorConnection", ".", "getInstanceID", "(", ")", ",", "taskManagerRegistration", ")", ";", "// next register the new slots", "for", "(", "SlotStatus", "slotStatus", ":", "initialSlotReport", ")", "{", "registerSlot", "(", "slotStatus", ".", "getSlotID", "(", ")", ",", "slotStatus", ".", "getAllocationID", "(", ")", ",", "slotStatus", ".", "getJobID", "(", ")", ",", "slotStatus", ".", "getResourceProfile", "(", ")", ",", "taskExecutorConnection", ")", ";", "}", "}", "}" ]
Registers a new task manager at the slot manager. This will make the task managers slots known and, thus, available for allocation. @param taskExecutorConnection for the new task manager @param initialSlotReport for the new task manager
[ "Registers", "a", "new", "task", "manager", "at", "the", "slot", "manager", ".", "This", "will", "make", "the", "task", "managers", "slots", "known", "and", "thus", "available", "for", "allocation", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java#L341-L374
Azure/azure-sdk-for-java
keyvault/resource-manager/v2016_10_01/src/main/java/com/microsoft/azure/management/keyvault/v2016_10_01/implementation/VaultsInner.java
VaultsInner.listByResourceGroupAsync
public Observable<Page<VaultInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) { """ The List operation gets information about the vaults associated with the subscription and within the specified resource group. @param resourceGroupName The name of the Resource Group to which the vault belongs. @param top Maximum number of results to return. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;VaultInner&gt; object """ return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top) .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() { @Override public Page<VaultInner> call(ServiceResponse<Page<VaultInner>> response) { return response.body(); } }); }
java
public Observable<Page<VaultInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top) .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() { @Override public Page<VaultInner> call(ServiceResponse<Page<VaultInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "VaultInner", ">", ">", "listByResourceGroupAsync", "(", "final", "String", "resourceGroupName", ",", "final", "Integer", "top", ")", "{", "return", "listByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "top", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "VaultInner", ">", ">", ",", "Page", "<", "VaultInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "VaultInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "VaultInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
The List operation gets information about the vaults associated with the subscription and within the specified resource group. @param resourceGroupName The name of the Resource Group to which the vault belongs. @param top Maximum number of results to return. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;VaultInner&gt; object
[ "The", "List", "operation", "gets", "information", "about", "the", "vaults", "associated", "with", "the", "subscription", "and", "within", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/resource-manager/v2016_10_01/src/main/java/com/microsoft/azure/management/keyvault/v2016_10_01/implementation/VaultsInner.java#L767-L775
code4everything/util
src/main/java/com/zhazhapan/util/LoggerUtils.java
LoggerUtils.formatString
private static String formatString(String message, Object[] values) { """ 格式化字符串 @param message 消息 @param values 格式化参数 @return 格式化的字符串 @since 1.0.8 """ if (Checker.isNotEmpty(message)) { if (Checker.isNotEmpty(values)) { return StrUtil.format(String.format(message, values), values); } return message; } return ValueConsts.EMPTY_STRING; }
java
private static String formatString(String message, Object[] values) { if (Checker.isNotEmpty(message)) { if (Checker.isNotEmpty(values)) { return StrUtil.format(String.format(message, values), values); } return message; } return ValueConsts.EMPTY_STRING; }
[ "private", "static", "String", "formatString", "(", "String", "message", ",", "Object", "[", "]", "values", ")", "{", "if", "(", "Checker", ".", "isNotEmpty", "(", "message", ")", ")", "{", "if", "(", "Checker", ".", "isNotEmpty", "(", "values", ")", ")", "{", "return", "StrUtil", ".", "format", "(", "String", ".", "format", "(", "message", ",", "values", ")", ",", "values", ")", ";", "}", "return", "message", ";", "}", "return", "ValueConsts", ".", "EMPTY_STRING", ";", "}" ]
格式化字符串 @param message 消息 @param values 格式化参数 @return 格式化的字符串 @since 1.0.8
[ "格式化字符串" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/LoggerUtils.java#L345-L353
aws/aws-sdk-java
aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/SetIdentityPoolRolesRequest.java
SetIdentityPoolRolesRequest.withRoles
public SetIdentityPoolRolesRequest withRoles(java.util.Map<String, String> roles) { """ <p> The map of roles associated with this pool. For a given role, the key will be either "authenticated" or "unauthenticated" and the value will be the Role ARN. </p> @param roles The map of roles associated with this pool. For a given role, the key will be either "authenticated" or "unauthenticated" and the value will be the Role ARN. @return Returns a reference to this object so that method calls can be chained together. """ setRoles(roles); return this; }
java
public SetIdentityPoolRolesRequest withRoles(java.util.Map<String, String> roles) { setRoles(roles); return this; }
[ "public", "SetIdentityPoolRolesRequest", "withRoles", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "roles", ")", "{", "setRoles", "(", "roles", ")", ";", "return", "this", ";", "}" ]
<p> The map of roles associated with this pool. For a given role, the key will be either "authenticated" or "unauthenticated" and the value will be the Role ARN. </p> @param roles The map of roles associated with this pool. For a given role, the key will be either "authenticated" or "unauthenticated" and the value will be the Role ARN. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "map", "of", "roles", "associated", "with", "this", "pool", ".", "For", "a", "given", "role", "the", "key", "will", "be", "either", "authenticated", "or", "unauthenticated", "and", "the", "value", "will", "be", "the", "Role", "ARN", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/SetIdentityPoolRolesRequest.java#L137-L140
JoeKerouac/utils
src/main/java/com/joe/utils/secure/KeyTools.java
KeyTools.buildKey
public static SecretKey buildKey(AbstractCipher.Algorithms algorithm, byte[] keySpec) { """ 使用指定keySpec构建对称加密的key @param algorithm 算法名称,当前仅支持AES和DES @param keySpec keySpec,多次调用该方法生成的key等效 @return 对称加密的key """ SecretKeySpec key = new SecretKeySpec(keySpec, algorithm.name()); return key; }
java
public static SecretKey buildKey(AbstractCipher.Algorithms algorithm, byte[] keySpec) { SecretKeySpec key = new SecretKeySpec(keySpec, algorithm.name()); return key; }
[ "public", "static", "SecretKey", "buildKey", "(", "AbstractCipher", ".", "Algorithms", "algorithm", ",", "byte", "[", "]", "keySpec", ")", "{", "SecretKeySpec", "key", "=", "new", "SecretKeySpec", "(", "keySpec", ",", "algorithm", ".", "name", "(", ")", ")", ";", "return", "key", ";", "}" ]
使用指定keySpec构建对称加密的key @param algorithm 算法名称,当前仅支持AES和DES @param keySpec keySpec,多次调用该方法生成的key等效 @return 对称加密的key
[ "使用指定keySpec构建对称加密的key" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/secure/KeyTools.java#L125-L128
fcrepo3/fcrepo
fcrepo-client/fcrepo-client-admin/src/main/resources/demo/demo-soapclient/DemoSOAPClient.java
DemoSOAPClient.pipeStream
public static void pipeStream(InputStream in, OutputStream out, int bufSize) throws IOException { """ Copies the contents of an InputStream to an OutputStream, then closes both. @param in The source stream. @param out The target stram. @param bufSize Number of bytes to attempt to copy at a time. @throws IOException If any sort of read/write error occurs on either stream. """ try { byte[] buf = new byte[bufSize]; int len; while ( ( len = in.read( buf ) ) > 0 ) { out.write( buf, 0, len ); } } finally { try { in.close(); out.close(); } catch (IOException e) { System.err.println("WARNING: Could not close stream."); } } }
java
public static void pipeStream(InputStream in, OutputStream out, int bufSize) throws IOException { try { byte[] buf = new byte[bufSize]; int len; while ( ( len = in.read( buf ) ) > 0 ) { out.write( buf, 0, len ); } } finally { try { in.close(); out.close(); } catch (IOException e) { System.err.println("WARNING: Could not close stream."); } } }
[ "public", "static", "void", "pipeStream", "(", "InputStream", "in", ",", "OutputStream", "out", ",", "int", "bufSize", ")", "throws", "IOException", "{", "try", "{", "byte", "[", "]", "buf", "=", "new", "byte", "[", "bufSize", "]", ";", "int", "len", ";", "while", "(", "(", "len", "=", "in", ".", "read", "(", "buf", ")", ")", ">", "0", ")", "{", "out", ".", "write", "(", "buf", ",", "0", ",", "len", ")", ";", "}", "}", "finally", "{", "try", "{", "in", ".", "close", "(", ")", ";", "out", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"WARNING: Could not close stream.\"", ")", ";", "}", "}", "}" ]
Copies the contents of an InputStream to an OutputStream, then closes both. @param in The source stream. @param out The target stram. @param bufSize Number of bytes to attempt to copy at a time. @throws IOException If any sort of read/write error occurs on either stream.
[ "Copies", "the", "contents", "of", "an", "InputStream", "to", "an", "OutputStream", "then", "closes", "both", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-client/fcrepo-client-admin/src/main/resources/demo/demo-soapclient/DemoSOAPClient.java#L218-L234
anotheria/moskito
moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java
HttpHelper.getHttpResponse
public static HttpResponse getHttpResponse(String url, UsernamePasswordCredentials credentials) throws IOException { """ Executes a request using the given URL and credentials. @param url the http URL to connect to. @param credentials credentials to use @return the response to the request. @throws IOException in case of a problem or the connection was aborted @throws ClientProtocolException in case of an http protocol error """ HttpGet request = new HttpGet(url); if (credentials != null) { URI uri = request.getURI(); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort()); Credentials cached = httpClient.getCredentialsProvider().getCredentials(authScope); if (!areSame(cached, credentials)) { httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } } return httpClient.execute(request); }
java
public static HttpResponse getHttpResponse(String url, UsernamePasswordCredentials credentials) throws IOException { HttpGet request = new HttpGet(url); if (credentials != null) { URI uri = request.getURI(); AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort()); Credentials cached = httpClient.getCredentialsProvider().getCredentials(authScope); if (!areSame(cached, credentials)) { httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } } return httpClient.execute(request); }
[ "public", "static", "HttpResponse", "getHttpResponse", "(", "String", "url", ",", "UsernamePasswordCredentials", "credentials", ")", "throws", "IOException", "{", "HttpGet", "request", "=", "new", "HttpGet", "(", "url", ")", ";", "if", "(", "credentials", "!=", "null", ")", "{", "URI", "uri", "=", "request", ".", "getURI", "(", ")", ";", "AuthScope", "authScope", "=", "new", "AuthScope", "(", "uri", ".", "getHost", "(", ")", ",", "uri", ".", "getPort", "(", ")", ")", ";", "Credentials", "cached", "=", "httpClient", ".", "getCredentialsProvider", "(", ")", ".", "getCredentials", "(", "authScope", ")", ";", "if", "(", "!", "areSame", "(", "cached", ",", "credentials", ")", ")", "{", "httpClient", ".", "getCredentialsProvider", "(", ")", ".", "setCredentials", "(", "authScope", ",", "credentials", ")", ";", "}", "}", "return", "httpClient", ".", "execute", "(", "request", ")", ";", "}" ]
Executes a request using the given URL and credentials. @param url the http URL to connect to. @param credentials credentials to use @return the response to the request. @throws IOException in case of a problem or the connection was aborted @throws ClientProtocolException in case of an http protocol error
[ "Executes", "a", "request", "using", "the", "given", "URL", "and", "credentials", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/fetcher/HttpHelper.java#L95-L106
calimero-project/calimero-core
src/tuwien/auto/calimero/dptxlator/TranslatorTypes.java
TranslatorTypes.hasTranslator
public static boolean hasTranslator(final int mainNumber, final String dptId) { """ Does a lookup if the specified DPT is supported by a DPT translator. @param mainNumber data type main number, number &ge; 0; use 0 to infer translator type from <code>dptId</code> argument only @param dptId datapoint type ID to lookup this particular kind of value translation @return <code>true</code> iff translator was found, <code>false</code> otherwise """ try { final MainType t = getMainType(getMainNumber(mainNumber, dptId)); if (t != null) return t.getSubTypes().get(dptId) != null; } catch (final NumberFormatException e) {} catch (final KNXException e) {} return false; }
java
public static boolean hasTranslator(final int mainNumber, final String dptId) { try { final MainType t = getMainType(getMainNumber(mainNumber, dptId)); if (t != null) return t.getSubTypes().get(dptId) != null; } catch (final NumberFormatException e) {} catch (final KNXException e) {} return false; }
[ "public", "static", "boolean", "hasTranslator", "(", "final", "int", "mainNumber", ",", "final", "String", "dptId", ")", "{", "try", "{", "final", "MainType", "t", "=", "getMainType", "(", "getMainNumber", "(", "mainNumber", ",", "dptId", ")", ")", ";", "if", "(", "t", "!=", "null", ")", "return", "t", ".", "getSubTypes", "(", ")", ".", "get", "(", "dptId", ")", "!=", "null", ";", "}", "catch", "(", "final", "NumberFormatException", "e", ")", "{", "}", "catch", "(", "final", "KNXException", "e", ")", "{", "}", "return", "false", ";", "}" ]
Does a lookup if the specified DPT is supported by a DPT translator. @param mainNumber data type main number, number &ge; 0; use 0 to infer translator type from <code>dptId</code> argument only @param dptId datapoint type ID to lookup this particular kind of value translation @return <code>true</code> iff translator was found, <code>false</code> otherwise
[ "Does", "a", "lookup", "if", "the", "specified", "DPT", "is", "supported", "by", "a", "DPT", "translator", "." ]
train
https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/dptxlator/TranslatorTypes.java#L533-L543
integration-technology/amazon-mws-orders
src/main/java/com/amazonservices/mws/client/MwsConnection.java
MwsConnection.includeRequestHeader
public void includeRequestHeader(String name, String value) { """ Sets the value of a request header to be included on every request @param name the name of the header to set @param value value to send with header """ checkUpdatable(); this.headers.put(name, value); }
java
public void includeRequestHeader(String name, String value) { checkUpdatable(); this.headers.put(name, value); }
[ "public", "void", "includeRequestHeader", "(", "String", "name", ",", "String", "value", ")", "{", "checkUpdatable", "(", ")", ";", "this", ".", "headers", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Sets the value of a request header to be included on every request @param name the name of the header to set @param value value to send with header
[ "Sets", "the", "value", "of", "a", "request", "header", "to", "be", "included", "on", "every", "request" ]
train
https://github.com/integration-technology/amazon-mws-orders/blob/042e8cd5b10588a30150222bf9c91faf4f130b3c/src/main/java/com/amazonservices/mws/client/MwsConnection.java#L973-L976
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javac/code/Types.java
Types.covariantReturnType
public boolean covariantReturnType(Type t, Type s, Warner warner) { """ Is t an appropriate return type in an overrider for a method that returns s? """ return isSameType(t, s) || allowCovariantReturns && !t.isPrimitive() && !s.isPrimitive() && isAssignable(t, s, warner); }
java
public boolean covariantReturnType(Type t, Type s, Warner warner) { return isSameType(t, s) || allowCovariantReturns && !t.isPrimitive() && !s.isPrimitive() && isAssignable(t, s, warner); }
[ "public", "boolean", "covariantReturnType", "(", "Type", "t", ",", "Type", "s", ",", "Warner", "warner", ")", "{", "return", "isSameType", "(", "t", ",", "s", ")", "||", "allowCovariantReturns", "&&", "!", "t", ".", "isPrimitive", "(", ")", "&&", "!", "s", ".", "isPrimitive", "(", ")", "&&", "isAssignable", "(", "t", ",", "s", ",", "warner", ")", ";", "}" ]
Is t an appropriate return type in an overrider for a method that returns s?
[ "Is", "t", "an", "appropriate", "return", "type", "in", "an", "overrider", "for", "a", "method", "that", "returns", "s?" ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/code/Types.java#L3952-L3959
rythmengine/rythmengine
src/main/java/org/rythmengine/RythmEngine.java
RythmEngine.getTemplateClass
public TemplateClass getTemplateClass(ITemplateResource resource) { """ (3rd party API, not for user application) Get an new template class by {@link org.rythmengine.resource.ITemplateResource template resource} @param resource the template resource @return template class """ String key = S.str(resource.getKey()); TemplateClass tc = classes().getByTemplate(key); if (null == tc) { tc = new TemplateClass(resource, this); } return tc; }
java
public TemplateClass getTemplateClass(ITemplateResource resource) { String key = S.str(resource.getKey()); TemplateClass tc = classes().getByTemplate(key); if (null == tc) { tc = new TemplateClass(resource, this); } return tc; }
[ "public", "TemplateClass", "getTemplateClass", "(", "ITemplateResource", "resource", ")", "{", "String", "key", "=", "S", ".", "str", "(", "resource", ".", "getKey", "(", ")", ")", ";", "TemplateClass", "tc", "=", "classes", "(", ")", ".", "getByTemplate", "(", "key", ")", ";", "if", "(", "null", "==", "tc", ")", "{", "tc", "=", "new", "TemplateClass", "(", "resource", ",", "this", ")", ";", "}", "return", "tc", ";", "}" ]
(3rd party API, not for user application) Get an new template class by {@link org.rythmengine.resource.ITemplateResource template resource} @param resource the template resource @return template class
[ "(", "3rd", "party", "API", "not", "for", "user", "application", ")", "Get", "an", "new", "template", "class", "by", "{", "@link", "org", ".", "rythmengine", ".", "resource", ".", "ITemplateResource", "template", "resource", "}" ]
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/RythmEngine.java#L930-L937
zaproxy/zaproxy
src/org/zaproxy/zap/extension/api/ApiImplementor.java
ApiImplementor.handleApiView
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { """ Override if implementing one or more views @param name the name of the requested view @param params the API request parameters @return the API response @throws ApiException if an error occurred while handling the API view endpoint """ throw new ApiException(ApiException.Type.BAD_VIEW, name); }
java
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { throw new ApiException(ApiException.Type.BAD_VIEW, name); }
[ "public", "ApiResponse", "handleApiView", "(", "String", "name", ",", "JSONObject", "params", ")", "throws", "ApiException", "{", "throw", "new", "ApiException", "(", "ApiException", ".", "Type", ".", "BAD_VIEW", ",", "name", ")", ";", "}" ]
Override if implementing one or more views @param name the name of the requested view @param params the API request parameters @return the API response @throws ApiException if an error occurred while handling the API view endpoint
[ "Override", "if", "implementing", "one", "or", "more", "views" ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/api/ApiImplementor.java#L324-L326
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.createHierarchicalEntityRoleWithServiceResponseAsync
public Observable<ServiceResponse<UUID>> createHierarchicalEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID hEntityId, CreateHierarchicalEntityRoleOptionalParameter createHierarchicalEntityRoleOptionalParameter) { """ Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @param createHierarchicalEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object """ if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (hEntityId == null) { throw new IllegalArgumentException("Parameter hEntityId is required and cannot be null."); } final String name = createHierarchicalEntityRoleOptionalParameter != null ? createHierarchicalEntityRoleOptionalParameter.name() : null; return createHierarchicalEntityRoleWithServiceResponseAsync(appId, versionId, hEntityId, name); }
java
public Observable<ServiceResponse<UUID>> createHierarchicalEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID hEntityId, CreateHierarchicalEntityRoleOptionalParameter createHierarchicalEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (hEntityId == null) { throw new IllegalArgumentException("Parameter hEntityId is required and cannot be null."); } final String name = createHierarchicalEntityRoleOptionalParameter != null ? createHierarchicalEntityRoleOptionalParameter.name() : null; return createHierarchicalEntityRoleWithServiceResponseAsync(appId, versionId, hEntityId, name); }
[ "public", "Observable", "<", "ServiceResponse", "<", "UUID", ">", ">", "createHierarchicalEntityRoleWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "hEntityId", ",", "CreateHierarchicalEntityRoleOptionalParameter", "createHierarchicalEntityRoleOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "endpoint", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.endpoint() is required and cannot be null.\"", ")", ";", "}", "if", "(", "appId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter appId is required and cannot be null.\"", ")", ";", "}", "if", "(", "versionId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter versionId is required and cannot be null.\"", ")", ";", "}", "if", "(", "hEntityId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter hEntityId is required and cannot be null.\"", ")", ";", "}", "final", "String", "name", "=", "createHierarchicalEntityRoleOptionalParameter", "!=", "null", "?", "createHierarchicalEntityRoleOptionalParameter", ".", "name", "(", ")", ":", "null", ";", "return", "createHierarchicalEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "hEntityId", ",", "name", ")", ";", "}" ]
Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @param createHierarchicalEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object
[ "Create", "an", "entity", "role", "for", "an", "entity", "in", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L9480-L9496
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/HiveJdbcConnector.java
HiveJdbcConnector.withHiveServerVersion
private HiveJdbcConnector withHiveServerVersion(int hiveServerVersion) { """ Set the {@link HiveJdbcConnector#hiveServerVersion}. The hiveServerVersion must be either 1 or 2. @param hiveServerVersion @return """ try { if (hiveServerVersion == 1) { Class.forName(HIVE_JDBC_DRIVER_NAME); } else if (hiveServerVersion == 2) { Class.forName(HIVE2_JDBC_DRIVER_NAME); } else { throw new RuntimeException(hiveServerVersion + " is not a valid HiveServer version."); } } catch (ClassNotFoundException e) { throw new RuntimeException("Cannot find a suitable driver of HiveServer version " + hiveServerVersion + ".", e); } this.hiveServerVersion = hiveServerVersion; return this; }
java
private HiveJdbcConnector withHiveServerVersion(int hiveServerVersion) { try { if (hiveServerVersion == 1) { Class.forName(HIVE_JDBC_DRIVER_NAME); } else if (hiveServerVersion == 2) { Class.forName(HIVE2_JDBC_DRIVER_NAME); } else { throw new RuntimeException(hiveServerVersion + " is not a valid HiveServer version."); } } catch (ClassNotFoundException e) { throw new RuntimeException("Cannot find a suitable driver of HiveServer version " + hiveServerVersion + ".", e); } this.hiveServerVersion = hiveServerVersion; return this; }
[ "private", "HiveJdbcConnector", "withHiveServerVersion", "(", "int", "hiveServerVersion", ")", "{", "try", "{", "if", "(", "hiveServerVersion", "==", "1", ")", "{", "Class", ".", "forName", "(", "HIVE_JDBC_DRIVER_NAME", ")", ";", "}", "else", "if", "(", "hiveServerVersion", "==", "2", ")", "{", "Class", ".", "forName", "(", "HIVE2_JDBC_DRIVER_NAME", ")", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "hiveServerVersion", "+", "\" is not a valid HiveServer version.\"", ")", ";", "}", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Cannot find a suitable driver of HiveServer version \"", "+", "hiveServerVersion", "+", "\".\"", ",", "e", ")", ";", "}", "this", ".", "hiveServerVersion", "=", "hiveServerVersion", ";", "return", "this", ";", "}" ]
Set the {@link HiveJdbcConnector#hiveServerVersion}. The hiveServerVersion must be either 1 or 2. @param hiveServerVersion @return
[ "Set", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HiveJdbcConnector.java#L136-L150
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/SVMLightClassifierFactory.java
SVMLightClassifierFactory.heldOutSetC
public void heldOutSetC(final GeneralDataset<L, F> trainSet, final GeneralDataset<L, F> devSet, final Scorer<L> scorer, LineSearcher minimizer) { """ This method will cross validate on the given data and number of folds to find the optimal C. The scorer is how you determine what to optimize for (F-score, accuracy, etc). The C is then saved, so that if you train a classifier after calling this method, that C will be used. """ useAlphaFile = true; boolean oldUseSigmoid = useSigmoid; useSigmoid = false; Function<Double,Double> negativeScorer = new Function<Double,Double> () { public Double apply(Double cToTry) { C = cToTry; SVMLightClassifier<L, F> classifier = trainClassifierBasic(trainSet); double score = scorer.score(classifier,devSet); return -score; } }; C = minimizer.minimize(negativeScorer); useAlphaFile = false; useSigmoid = oldUseSigmoid; }
java
public void heldOutSetC(final GeneralDataset<L, F> trainSet, final GeneralDataset<L, F> devSet, final Scorer<L> scorer, LineSearcher minimizer) { useAlphaFile = true; boolean oldUseSigmoid = useSigmoid; useSigmoid = false; Function<Double,Double> negativeScorer = new Function<Double,Double> () { public Double apply(Double cToTry) { C = cToTry; SVMLightClassifier<L, F> classifier = trainClassifierBasic(trainSet); double score = scorer.score(classifier,devSet); return -score; } }; C = minimizer.minimize(negativeScorer); useAlphaFile = false; useSigmoid = oldUseSigmoid; }
[ "public", "void", "heldOutSetC", "(", "final", "GeneralDataset", "<", "L", ",", "F", ">", "trainSet", ",", "final", "GeneralDataset", "<", "L", ",", "F", ">", "devSet", ",", "final", "Scorer", "<", "L", ">", "scorer", ",", "LineSearcher", "minimizer", ")", "{", "useAlphaFile", "=", "true", ";", "boolean", "oldUseSigmoid", "=", "useSigmoid", ";", "useSigmoid", "=", "false", ";", "Function", "<", "Double", ",", "Double", ">", "negativeScorer", "=", "new", "Function", "<", "Double", ",", "Double", ">", "(", ")", "{", "public", "Double", "apply", "(", "Double", "cToTry", ")", "{", "C", "=", "cToTry", ";", "SVMLightClassifier", "<", "L", ",", "F", ">", "classifier", "=", "trainClassifierBasic", "(", "trainSet", ")", ";", "double", "score", "=", "scorer", ".", "score", "(", "classifier", ",", "devSet", ")", ";", "return", "-", "score", ";", "}", "}", ";", "C", "=", "minimizer", ".", "minimize", "(", "negativeScorer", ")", ";", "useAlphaFile", "=", "false", ";", "useSigmoid", "=", "oldUseSigmoid", ";", "}" ]
This method will cross validate on the given data and number of folds to find the optimal C. The scorer is how you determine what to optimize for (F-score, accuracy, etc). The C is then saved, so that if you train a classifier after calling this method, that C will be used.
[ "This", "method", "will", "cross", "validate", "on", "the", "given", "data", "and", "number", "of", "folds", "to", "find", "the", "optimal", "C", ".", "The", "scorer", "is", "how", "you", "determine", "what", "to", "optimize", "for", "(", "F", "-", "score", "accuracy", "etc", ")", ".", "The", "C", "is", "then", "saved", "so", "that", "if", "you", "train", "a", "classifier", "after", "calling", "this", "method", "that", "C", "will", "be", "used", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/SVMLightClassifierFactory.java#L294-L315
jblas-project/jblas
src/main/java/org/jblas/Solve.java
Solve.pinv
public static DoubleMatrix pinv(DoubleMatrix A) { """ Computes the pseudo-inverse. Note, this function uses the solveLeastSquares and might produce different numerical solutions for the underdetermined case than matlab. @param A rectangular matrix @return matrix P such that A*P*A = A and P*A*P = P. """ return solveLeastSquares(A, DoubleMatrix.eye(A.rows)); }
java
public static DoubleMatrix pinv(DoubleMatrix A) { return solveLeastSquares(A, DoubleMatrix.eye(A.rows)); }
[ "public", "static", "DoubleMatrix", "pinv", "(", "DoubleMatrix", "A", ")", "{", "return", "solveLeastSquares", "(", "A", ",", "DoubleMatrix", ".", "eye", "(", "A", ".", "rows", ")", ")", ";", "}" ]
Computes the pseudo-inverse. Note, this function uses the solveLeastSquares and might produce different numerical solutions for the underdetermined case than matlab. @param A rectangular matrix @return matrix P such that A*P*A = A and P*A*P = P.
[ "Computes", "the", "pseudo", "-", "inverse", "." ]
train
https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/Solve.java#L104-L106
Yubico/yubico-j
src/com/yubico/base/CRC13239.java
CRC13239.getCRC
static public short getCRC(byte[] buf, int len) { """ <p>Method for calculating a CRC13239 checksum over a byte buffer.</p> @param buf byte buffer to be checksummed. @param len how much of the buffer should be checksummed @return CRC13239 checksum """ short i; short crc = 0x7fff; boolean isNeg = true; for(int j = 0; j < len; j++) { crc ^= buf[j] & 0xff; for (i = 0; i < 8; i++) { if ((crc & 1) == 0) { crc >>= 1; if (isNeg) { isNeg = false; crc |= 0x4000; } } else { crc >>= 1; if (isNeg) { crc ^= 0x4408; } else { crc ^= 0x0408; isNeg = true; } } } } return isNeg ? (short) (crc | (short) 0x8000) : crc; }
java
static public short getCRC(byte[] buf, int len) { short i; short crc = 0x7fff; boolean isNeg = true; for(int j = 0; j < len; j++) { crc ^= buf[j] & 0xff; for (i = 0; i < 8; i++) { if ((crc & 1) == 0) { crc >>= 1; if (isNeg) { isNeg = false; crc |= 0x4000; } } else { crc >>= 1; if (isNeg) { crc ^= 0x4408; } else { crc ^= 0x0408; isNeg = true; } } } } return isNeg ? (short) (crc | (short) 0x8000) : crc; }
[ "static", "public", "short", "getCRC", "(", "byte", "[", "]", "buf", ",", "int", "len", ")", "{", "short", "i", ";", "short", "crc", "=", "0x7fff", ";", "boolean", "isNeg", "=", "true", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "len", ";", "j", "++", ")", "{", "crc", "^=", "buf", "[", "j", "]", "&", "0xff", ";", "for", "(", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "if", "(", "(", "crc", "&", "1", ")", "==", "0", ")", "{", "crc", ">>=", "1", ";", "if", "(", "isNeg", ")", "{", "isNeg", "=", "false", ";", "crc", "|=", "0x4000", ";", "}", "}", "else", "{", "crc", ">>=", "1", ";", "if", "(", "isNeg", ")", "{", "crc", "^=", "0x4408", ";", "}", "else", "{", "crc", "^=", "0x0408", ";", "isNeg", "=", "true", ";", "}", "}", "}", "}", "return", "isNeg", "?", "(", "short", ")", "(", "crc", "|", "(", "short", ")", "0x8000", ")", ":", "crc", ";", "}" ]
<p>Method for calculating a CRC13239 checksum over a byte buffer.</p> @param buf byte buffer to be checksummed. @param len how much of the buffer should be checksummed @return CRC13239 checksum
[ "<p", ">", "Method", "for", "calculating", "a", "CRC13239", "checksum", "over", "a", "byte", "buffer", ".", "<", "/", "p", ">" ]
train
https://github.com/Yubico/yubico-j/blob/46b407e885b550f9438b9becdeeccb8ff763dc5a/src/com/yubico/base/CRC13239.java#L54-L83
westnordost/osmapi
src/main/java/de/westnordost/osmapi/changesets/ChangesetsDao.java
ChangesetsDao.getData
public void getData(long id, MapDataChangesHandler handler, MapDataFactory factory) { """ Get map data changes associated with the given changeset. @throws OsmAuthorizationException if not logged in @throws OsmNotFoundException if changeset with the given id does not exist """ osm.makeAuthenticatedRequest(CHANGESET + "/" + id + "/download", null, new MapDataChangesParser(handler, factory)); }
java
public void getData(long id, MapDataChangesHandler handler, MapDataFactory factory) { osm.makeAuthenticatedRequest(CHANGESET + "/" + id + "/download", null, new MapDataChangesParser(handler, factory)); }
[ "public", "void", "getData", "(", "long", "id", ",", "MapDataChangesHandler", "handler", ",", "MapDataFactory", "factory", ")", "{", "osm", ".", "makeAuthenticatedRequest", "(", "CHANGESET", "+", "\"/\"", "+", "id", "+", "\"/download\"", ",", "null", ",", "new", "MapDataChangesParser", "(", "handler", ",", "factory", ")", ")", ";", "}" ]
Get map data changes associated with the given changeset. @throws OsmAuthorizationException if not logged in @throws OsmNotFoundException if changeset with the given id does not exist
[ "Get", "map", "data", "changes", "associated", "with", "the", "given", "changeset", "." ]
train
https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/changesets/ChangesetsDao.java#L193-L197
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Waiter.java
Waiter.waitForText
public TextView waitForText(String text, int expectedMinimumNumberOfMatches, long timeout, boolean scroll) { """ Waits for a text to be shown. @param text the text that needs to be shown, specified as a regular expression @param expectedMinimumNumberOfMatches the minimum number of matches of text that must be shown. {@code 0} means any number of matches @param timeout the amount of time in milliseconds to wait @param scroll {@code true} if scrolling should be performed @return {@code true} if text is found and {@code false} if it is not found before the timeout """ return waitForText(TextView.class, text, expectedMinimumNumberOfMatches, timeout, scroll, false, true); }
java
public TextView waitForText(String text, int expectedMinimumNumberOfMatches, long timeout, boolean scroll) { return waitForText(TextView.class, text, expectedMinimumNumberOfMatches, timeout, scroll, false, true); }
[ "public", "TextView", "waitForText", "(", "String", "text", ",", "int", "expectedMinimumNumberOfMatches", ",", "long", "timeout", ",", "boolean", "scroll", ")", "{", "return", "waitForText", "(", "TextView", ".", "class", ",", "text", ",", "expectedMinimumNumberOfMatches", ",", "timeout", ",", "scroll", ",", "false", ",", "true", ")", ";", "}" ]
Waits for a text to be shown. @param text the text that needs to be shown, specified as a regular expression @param expectedMinimumNumberOfMatches the minimum number of matches of text that must be shown. {@code 0} means any number of matches @param timeout the amount of time in milliseconds to wait @param scroll {@code true} if scrolling should be performed @return {@code true} if text is found and {@code false} if it is not found before the timeout
[ "Waits", "for", "a", "text", "to", "be", "shown", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Waiter.java#L567-L569
jtrfp/javamod
src/main/java/de/quippy/javamod/multimedia/mp3/id3/MPEGAudioFrameHeader.java
MPEGAudioFrameHeader.readHeader
private void readHeader(RandomAccessInputStream raf, long location) throws IOException { """ Read in all the information found in the mpeg header. @param location the location of the header (found by findFrame) @exception FileNotFoundException if an error occurs @exception IOException if an error occurs """ byte[] head = new byte[HEADER_SIZE]; raf.seek(location); if (raf.read(head) != HEADER_SIZE) { throw new IOException("Error reading MPEG frame header."); } version = (head[1]&0x18)>>3; layer = (head[1]&0x06)>>1; crced = (head[1]&0x01)==0; bitRate = findBitRate((head[2]&0xF0)>>4, version, layer); sampleRate = findSampleRate((head[2]&0x0C)>>2, version); channelMode = (head[3]&0xC0)>>6; copyrighted = (head[3]&0x08)!=0; original = (head[3]&0x04)!=0; emphasis = head[3]&0x03; }
java
private void readHeader(RandomAccessInputStream raf, long location) throws IOException { byte[] head = new byte[HEADER_SIZE]; raf.seek(location); if (raf.read(head) != HEADER_SIZE) { throw new IOException("Error reading MPEG frame header."); } version = (head[1]&0x18)>>3; layer = (head[1]&0x06)>>1; crced = (head[1]&0x01)==0; bitRate = findBitRate((head[2]&0xF0)>>4, version, layer); sampleRate = findSampleRate((head[2]&0x0C)>>2, version); channelMode = (head[3]&0xC0)>>6; copyrighted = (head[3]&0x08)!=0; original = (head[3]&0x04)!=0; emphasis = head[3]&0x03; }
[ "private", "void", "readHeader", "(", "RandomAccessInputStream", "raf", ",", "long", "location", ")", "throws", "IOException", "{", "byte", "[", "]", "head", "=", "new", "byte", "[", "HEADER_SIZE", "]", ";", "raf", ".", "seek", "(", "location", ")", ";", "if", "(", "raf", ".", "read", "(", "head", ")", "!=", "HEADER_SIZE", ")", "{", "throw", "new", "IOException", "(", "\"Error reading MPEG frame header.\"", ")", ";", "}", "version", "=", "(", "head", "[", "1", "]", "&", "0x18", ")", ">>", "3", ";", "layer", "=", "(", "head", "[", "1", "]", "&", "0x06", ")", ">>", "1", ";", "crced", "=", "(", "head", "[", "1", "]", "&", "0x01", ")", "==", "0", ";", "bitRate", "=", "findBitRate", "(", "(", "head", "[", "2", "]", "&", "0xF0", ")", ">>", "4", ",", "version", ",", "layer", ")", ";", "sampleRate", "=", "findSampleRate", "(", "(", "head", "[", "2", "]", "&", "0x0C", ")", ">>", "2", ",", "version", ")", ";", "channelMode", "=", "(", "head", "[", "3", "]", "&", "0xC0", ")", ">>", "6", ";", "copyrighted", "=", "(", "head", "[", "3", "]", "&", "0x08", ")", "!=", "0", ";", "original", "=", "(", "head", "[", "3", "]", "&", "0x04", ")", "!=", "0", ";", "emphasis", "=", "head", "[", "3", "]", "&", "0x03", ";", "}" ]
Read in all the information found in the mpeg header. @param location the location of the header (found by findFrame) @exception FileNotFoundException if an error occurs @exception IOException if an error occurs
[ "Read", "in", "all", "the", "information", "found", "in", "the", "mpeg", "header", "." ]
train
https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mp3/id3/MPEGAudioFrameHeader.java#L224-L243
Esri/geometry-api-java
src/main/java/com/esri/core/geometry/Line.java
Line._isIntersectingHelper
static boolean _isIntersectingHelper(Line line1, Line line2) { """ Tests if two lines intersect using projection of one line to another. """ int s11 = line1._side(line2.m_xStart, line2.m_yStart); int s12 = line1._side(line2.m_xEnd, line2.m_yEnd); if (s11 < 0 && s12 < 0 || s11 > 0 && s12 > 0) return false;// no intersection. The line2 lies to one side of an // infinite line passing through line1 int s21 = line2._side(line1.m_xStart, line1.m_yStart); int s22 = line2._side(line1.m_xEnd, line1.m_yEnd); if (s21 < 0 && s22 < 0 || s21 > 0 && s22 > 0) return false;// no intersection.The line1 lies to one side of an // infinite line passing through line2 double len1 = line1.calculateLength2D(); double len2 = line2.calculateLength2D(); if (len1 > len2) { return line1._projectionIntersect(line2); } else { return line2._projectionIntersect(line1); } }
java
static boolean _isIntersectingHelper(Line line1, Line line2) { int s11 = line1._side(line2.m_xStart, line2.m_yStart); int s12 = line1._side(line2.m_xEnd, line2.m_yEnd); if (s11 < 0 && s12 < 0 || s11 > 0 && s12 > 0) return false;// no intersection. The line2 lies to one side of an // infinite line passing through line1 int s21 = line2._side(line1.m_xStart, line1.m_yStart); int s22 = line2._side(line1.m_xEnd, line1.m_yEnd); if (s21 < 0 && s22 < 0 || s21 > 0 && s22 > 0) return false;// no intersection.The line1 lies to one side of an // infinite line passing through line2 double len1 = line1.calculateLength2D(); double len2 = line2.calculateLength2D(); if (len1 > len2) { return line1._projectionIntersect(line2); } else { return line2._projectionIntersect(line1); } }
[ "static", "boolean", "_isIntersectingHelper", "(", "Line", "line1", ",", "Line", "line2", ")", "{", "int", "s11", "=", "line1", ".", "_side", "(", "line2", ".", "m_xStart", ",", "line2", ".", "m_yStart", ")", ";", "int", "s12", "=", "line1", ".", "_side", "(", "line2", ".", "m_xEnd", ",", "line2", ".", "m_yEnd", ")", ";", "if", "(", "s11", "<", "0", "&&", "s12", "<", "0", "||", "s11", ">", "0", "&&", "s12", ">", "0", ")", "return", "false", ";", "// no intersection. The line2 lies to one side of an", "// infinite line passing through line1", "int", "s21", "=", "line2", ".", "_side", "(", "line1", ".", "m_xStart", ",", "line1", ".", "m_yStart", ")", ";", "int", "s22", "=", "line2", ".", "_side", "(", "line1", ".", "m_xEnd", ",", "line1", ".", "m_yEnd", ")", ";", "if", "(", "s21", "<", "0", "&&", "s22", "<", "0", "||", "s21", ">", "0", "&&", "s22", ">", "0", ")", "return", "false", ";", "// no intersection.The line1 lies to one side of an", "// infinite line passing through line2", "double", "len1", "=", "line1", ".", "calculateLength2D", "(", ")", ";", "double", "len2", "=", "line2", ".", "calculateLength2D", "(", ")", ";", "if", "(", "len1", ">", "len2", ")", "{", "return", "line1", ".", "_projectionIntersect", "(", "line2", ")", ";", "}", "else", "{", "return", "line2", ".", "_projectionIntersect", "(", "line1", ")", ";", "}", "}" ]
Tests if two lines intersect using projection of one line to another.
[ "Tests", "if", "two", "lines", "intersect", "using", "projection", "of", "one", "line", "to", "another", "." ]
train
https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/Line.java#L600-L620
dropbox/dropbox-sdk-java
src/main/java/com/dropbox/core/v1/DbxClientV1.java
DbxClientV1.chunkedUploadFirst
public <E extends Throwable> String chunkedUploadFirst(int chunkSize, DbxStreamWriter<E> writer) throws DbxException, E { """ Upload the first chunk of a multi-chunk upload. @param chunkSize The number of bytes you're going to upload in this chunk. @param writer A callback that will be called when it's time to actually write out the body of the chunk. @return The ID designated by the Dropbox server to identify the chunked upload. """ HttpRequestor.Response response = chunkedUploadCommon(new String[0], chunkSize, writer); try { ChunkedUploadState correctedState = chunkedUploadCheckForOffsetCorrection(response); if (correctedState != null) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "Got offset correction response on first chunk."); } if (response.getStatusCode() == 404) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "Got a 404, but we didn't send an upload_id"); } if (response.getStatusCode() != 200) throw DbxRequestUtil.unexpectedStatus(response); ChunkedUploadState returnedState = chunkedUploadParse200(response); if (returnedState.offset != chunkSize) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "Sent " + chunkSize + " bytes, but returned offset is " + returnedState.offset); } return returnedState.uploadId; } finally { IOUtil.closeInput(response.getBody()); } }
java
public <E extends Throwable> String chunkedUploadFirst(int chunkSize, DbxStreamWriter<E> writer) throws DbxException, E { HttpRequestor.Response response = chunkedUploadCommon(new String[0], chunkSize, writer); try { ChunkedUploadState correctedState = chunkedUploadCheckForOffsetCorrection(response); if (correctedState != null) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "Got offset correction response on first chunk."); } if (response.getStatusCode() == 404) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "Got a 404, but we didn't send an upload_id"); } if (response.getStatusCode() != 200) throw DbxRequestUtil.unexpectedStatus(response); ChunkedUploadState returnedState = chunkedUploadParse200(response); if (returnedState.offset != chunkSize) { String requestId = DbxRequestUtil.getRequestId(response); throw new BadResponseException(requestId, "Sent " + chunkSize + " bytes, but returned offset is " + returnedState.offset); } return returnedState.uploadId; } finally { IOUtil.closeInput(response.getBody()); } }
[ "public", "<", "E", "extends", "Throwable", ">", "String", "chunkedUploadFirst", "(", "int", "chunkSize", ",", "DbxStreamWriter", "<", "E", ">", "writer", ")", "throws", "DbxException", ",", "E", "{", "HttpRequestor", ".", "Response", "response", "=", "chunkedUploadCommon", "(", "new", "String", "[", "0", "]", ",", "chunkSize", ",", "writer", ")", ";", "try", "{", "ChunkedUploadState", "correctedState", "=", "chunkedUploadCheckForOffsetCorrection", "(", "response", ")", ";", "if", "(", "correctedState", "!=", "null", ")", "{", "String", "requestId", "=", "DbxRequestUtil", ".", "getRequestId", "(", "response", ")", ";", "throw", "new", "BadResponseException", "(", "requestId", ",", "\"Got offset correction response on first chunk.\"", ")", ";", "}", "if", "(", "response", ".", "getStatusCode", "(", ")", "==", "404", ")", "{", "String", "requestId", "=", "DbxRequestUtil", ".", "getRequestId", "(", "response", ")", ";", "throw", "new", "BadResponseException", "(", "requestId", ",", "\"Got a 404, but we didn't send an upload_id\"", ")", ";", "}", "if", "(", "response", ".", "getStatusCode", "(", ")", "!=", "200", ")", "throw", "DbxRequestUtil", ".", "unexpectedStatus", "(", "response", ")", ";", "ChunkedUploadState", "returnedState", "=", "chunkedUploadParse200", "(", "response", ")", ";", "if", "(", "returnedState", ".", "offset", "!=", "chunkSize", ")", "{", "String", "requestId", "=", "DbxRequestUtil", ".", "getRequestId", "(", "response", ")", ";", "throw", "new", "BadResponseException", "(", "requestId", ",", "\"Sent \"", "+", "chunkSize", "+", "\" bytes, but returned offset is \"", "+", "returnedState", ".", "offset", ")", ";", "}", "return", "returnedState", ".", "uploadId", ";", "}", "finally", "{", "IOUtil", ".", "closeInput", "(", "response", ".", "getBody", "(", ")", ")", ";", "}", "}" ]
Upload the first chunk of a multi-chunk upload. @param chunkSize The number of bytes you're going to upload in this chunk. @param writer A callback that will be called when it's time to actually write out the body of the chunk. @return The ID designated by the Dropbox server to identify the chunked upload.
[ "Upload", "the", "first", "chunk", "of", "a", "multi", "-", "chunk", "upload", "." ]
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L1036-L1065
phax/ph-bdve
ph-bdve-ubl/src/main/java/com/helger/bdve/ubl/UBLValidation.java
UBLValidation.initUBL20
public static void initUBL20 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { """ Register all standard UBL 2.0 validation execution sets to the provided registry. @param aRegistry The registry to add the artefacts. May not be <code>null</code>. """ ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL20NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL20DocumentType e : EUBL20DocumentType.values ()) { final String sName = e.getLocalName (); final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_20); // No Schematrons here aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID, "UBL " + sName + " " + VERSION_20, bNotDeprecated, ValidationExecutorXSD.create (e))); } }
java
public static void initUBL20 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL20NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL20DocumentType e : EUBL20DocumentType.values ()) { final String sName = e.getLocalName (); final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_20); // No Schematrons here aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID, "UBL " + sName + " " + VERSION_20, bNotDeprecated, ValidationExecutorXSD.create (e))); } }
[ "public", "static", "void", "initUBL20", "(", "@", "Nonnull", "final", "ValidationExecutorSetRegistry", "aRegistry", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aRegistry", ",", "\"Registry\"", ")", ";", "// For better error messages", "LocationBeautifierSPI", ".", "addMappings", "(", "UBL20NamespaceContext", ".", "getInstance", "(", ")", ")", ";", "final", "boolean", "bNotDeprecated", "=", "false", ";", "for", "(", "final", "EUBL20DocumentType", "e", ":", "EUBL20DocumentType", ".", "values", "(", ")", ")", "{", "final", "String", "sName", "=", "e", ".", "getLocalName", "(", ")", ";", "final", "VESID", "aVESID", "=", "new", "VESID", "(", "GROUP_ID", ",", "sName", ".", "toLowerCase", "(", "Locale", ".", "US", ")", ",", "VERSION_20", ")", ";", "// No Schematrons here", "aRegistry", ".", "registerValidationExecutorSet", "(", "ValidationExecutorSet", ".", "create", "(", "aVESID", ",", "\"UBL \"", "+", "sName", "+", "\" \"", "+", "VERSION_20", ",", "bNotDeprecated", ",", "ValidationExecutorXSD", ".", "create", "(", "e", ")", ")", ")", ";", "}", "}" ]
Register all standard UBL 2.0 validation execution sets to the provided registry. @param aRegistry The registry to add the artefacts. May not be <code>null</code>.
[ "Register", "all", "standard", "UBL", "2", ".", "0", "validation", "execution", "sets", "to", "the", "provided", "registry", "." ]
train
https://github.com/phax/ph-bdve/blob/2438f491174cd8989567fcdf129b273bd217e89f/ph-bdve-ubl/src/main/java/com/helger/bdve/ubl/UBLValidation.java#L342-L361
knowm/XChart
xchart/src/main/java/org/knowm/xchart/CategoryChart.java
CategoryChart.addSeries
public CategorySeries addSeries(String seriesName, double[] xData, double[] yData) { """ Add a series for a Category type chart using using double arrays @param seriesName @param xData the X-Axis data @param xData the Y-Axis data @return A Series object that you can set properties on """ return addSeries(seriesName, xData, yData, null); }
java
public CategorySeries addSeries(String seriesName, double[] xData, double[] yData) { return addSeries(seriesName, xData, yData, null); }
[ "public", "CategorySeries", "addSeries", "(", "String", "seriesName", ",", "double", "[", "]", "xData", ",", "double", "[", "]", "yData", ")", "{", "return", "addSeries", "(", "seriesName", ",", "xData", ",", "yData", ",", "null", ")", ";", "}" ]
Add a series for a Category type chart using using double arrays @param seriesName @param xData the X-Axis data @param xData the Y-Axis data @return A Series object that you can set properties on
[ "Add", "a", "series", "for", "a", "Category", "type", "chart", "using", "using", "double", "arrays" ]
train
https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/CategoryChart.java#L83-L86
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/RegionMap.java
RegionMap.toSubRegion
public RegionMap toSubRegion( Envelope envelope ) { """ Creates a new {@link RegionMap} cropped on the new bounds and snapped on the original grid. <p><b>The supplied bounds are contained in the resulting region.</b></p> @param envelope the envelope to snap. @return the new {@link RegionMap}. """ double w = envelope.getMinX(); double s = envelope.getMinY(); double e = envelope.getMaxX(); double n = envelope.getMaxY(); return toSubRegion(n, s, w, e); }
java
public RegionMap toSubRegion( Envelope envelope ) { double w = envelope.getMinX(); double s = envelope.getMinY(); double e = envelope.getMaxX(); double n = envelope.getMaxY(); return toSubRegion(n, s, w, e); }
[ "public", "RegionMap", "toSubRegion", "(", "Envelope", "envelope", ")", "{", "double", "w", "=", "envelope", ".", "getMinX", "(", ")", ";", "double", "s", "=", "envelope", ".", "getMinY", "(", ")", ";", "double", "e", "=", "envelope", ".", "getMaxX", "(", ")", ";", "double", "n", "=", "envelope", ".", "getMaxY", "(", ")", ";", "return", "toSubRegion", "(", "n", ",", "s", ",", "w", ",", "e", ")", ";", "}" ]
Creates a new {@link RegionMap} cropped on the new bounds and snapped on the original grid. <p><b>The supplied bounds are contained in the resulting region.</b></p> @param envelope the envelope to snap. @return the new {@link RegionMap}.
[ "Creates", "a", "new", "{", "@link", "RegionMap", "}", "cropped", "on", "the", "new", "bounds", "and", "snapped", "on", "the", "original", "grid", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/RegionMap.java#L258-L264
aws/aws-sdk-java
aws-java-sdk-iotanalytics/src/main/java/com/amazonaws/services/iotanalytics/model/AddAttributesActivity.java
AddAttributesActivity.withAttributes
public AddAttributesActivity withAttributes(java.util.Map<String, String> attributes) { """ <p> A list of 1-50 "AttributeNameMapping" objects that map an existing attribute to a new attribute. </p> <note> <p> The existing attributes remain in the message, so if you want to remove the originals, use "RemoveAttributeActivity". </p> </note> @param attributes A list of 1-50 "AttributeNameMapping" objects that map an existing attribute to a new attribute.</p> <note> <p> The existing attributes remain in the message, so if you want to remove the originals, use "RemoveAttributeActivity". </p> @return Returns a reference to this object so that method calls can be chained together. """ setAttributes(attributes); return this; }
java
public AddAttributesActivity withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
[ "public", "AddAttributesActivity", "withAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "setAttributes", "(", "attributes", ")", ";", "return", "this", ";", "}" ]
<p> A list of 1-50 "AttributeNameMapping" objects that map an existing attribute to a new attribute. </p> <note> <p> The existing attributes remain in the message, so if you want to remove the originals, use "RemoveAttributeActivity". </p> </note> @param attributes A list of 1-50 "AttributeNameMapping" objects that map an existing attribute to a new attribute.</p> <note> <p> The existing attributes remain in the message, so if you want to remove the originals, use "RemoveAttributeActivity". </p> @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "list", "of", "1", "-", "50", "AttributeNameMapping", "objects", "that", "map", "an", "existing", "attribute", "to", "a", "new", "attribute", ".", "<", "/", "p", ">", "<note", ">", "<p", ">", "The", "existing", "attributes", "remain", "in", "the", "message", "so", "if", "you", "want", "to", "remove", "the", "originals", "use", "RemoveAttributeActivity", ".", "<", "/", "p", ">", "<", "/", "note", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iotanalytics/src/main/java/com/amazonaws/services/iotanalytics/model/AddAttributesActivity.java#L164-L167
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java
ProgramUtils.executeCommandWithResult
public static ExecutionResult executeCommandWithResult( final Logger logger, final String[] command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstancePath) throws IOException, InterruptedException { """ Executes a command on the VM and retrieves all the result. <p> This includes the process's exit value, its normal output as well as the error flow. </p> @param logger a logger (not null) @param command a command to execute (not null, not empty) @param workingDir the working directory for the command @param environmentVars a map containing environment variables (can be null) @param applicationName the roboconf application name (null if not specified) @param scopedInstancePath the roboconf scoped instance path (null if not specified) @throws IOException if a new process could not be created @throws InterruptedException if the new process encountered a process """ logger.fine( "Executing command: " + Arrays.toString( command )); // Setup ProcessBuilder pb = new ProcessBuilder( command ); if( workingDir != null ) pb.directory(workingDir); Map<String,String> env = pb.environment(); if( environmentVars != null && env != null ) { // No putAll() here: null key or value would cause NPE // (see ProcessBuilder.environment() javadoc). for( Map.Entry<String,String> entry : environmentVars.entrySet()) { if( entry.getKey() != null && entry.getValue() != null ) env.put( entry.getKey(), entry.getValue()); } } // Prepare the result StringBuilder normalOutput = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); int exitValue = -1; // Execute Process process = pb.start(); // Store process in ThreadLocal, so it can be cancelled later (eg. if blocked) logger.fine("Storing process [" + applicationName + "] [" + scopedInstancePath + "]"); ProcessStore.setProcess(applicationName, scopedInstancePath, process); try { new Thread( new OutputRunnable( process, true, errorOutput, logger )).start(); new Thread( new OutputRunnable( process, false, normalOutput, logger )).start(); exitValue = process.waitFor(); if( exitValue != 0 ) logger.warning( "Command execution returned a non-zero code. Code:" + exitValue ); } finally { ProcessStore.clearProcess(applicationName, scopedInstancePath); } return new ExecutionResult( normalOutput.toString().trim(), errorOutput.toString().trim(), exitValue ); }
java
public static ExecutionResult executeCommandWithResult( final Logger logger, final String[] command, final File workingDir, final Map<String,String> environmentVars, final String applicationName, final String scopedInstancePath) throws IOException, InterruptedException { logger.fine( "Executing command: " + Arrays.toString( command )); // Setup ProcessBuilder pb = new ProcessBuilder( command ); if( workingDir != null ) pb.directory(workingDir); Map<String,String> env = pb.environment(); if( environmentVars != null && env != null ) { // No putAll() here: null key or value would cause NPE // (see ProcessBuilder.environment() javadoc). for( Map.Entry<String,String> entry : environmentVars.entrySet()) { if( entry.getKey() != null && entry.getValue() != null ) env.put( entry.getKey(), entry.getValue()); } } // Prepare the result StringBuilder normalOutput = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); int exitValue = -1; // Execute Process process = pb.start(); // Store process in ThreadLocal, so it can be cancelled later (eg. if blocked) logger.fine("Storing process [" + applicationName + "] [" + scopedInstancePath + "]"); ProcessStore.setProcess(applicationName, scopedInstancePath, process); try { new Thread( new OutputRunnable( process, true, errorOutput, logger )).start(); new Thread( new OutputRunnable( process, false, normalOutput, logger )).start(); exitValue = process.waitFor(); if( exitValue != 0 ) logger.warning( "Command execution returned a non-zero code. Code:" + exitValue ); } finally { ProcessStore.clearProcess(applicationName, scopedInstancePath); } return new ExecutionResult( normalOutput.toString().trim(), errorOutput.toString().trim(), exitValue ); }
[ "public", "static", "ExecutionResult", "executeCommandWithResult", "(", "final", "Logger", "logger", ",", "final", "String", "[", "]", "command", ",", "final", "File", "workingDir", ",", "final", "Map", "<", "String", ",", "String", ">", "environmentVars", ",", "final", "String", "applicationName", ",", "final", "String", "scopedInstancePath", ")", "throws", "IOException", ",", "InterruptedException", "{", "logger", ".", "fine", "(", "\"Executing command: \"", "+", "Arrays", ".", "toString", "(", "command", ")", ")", ";", "// Setup", "ProcessBuilder", "pb", "=", "new", "ProcessBuilder", "(", "command", ")", ";", "if", "(", "workingDir", "!=", "null", ")", "pb", ".", "directory", "(", "workingDir", ")", ";", "Map", "<", "String", ",", "String", ">", "env", "=", "pb", ".", "environment", "(", ")", ";", "if", "(", "environmentVars", "!=", "null", "&&", "env", "!=", "null", ")", "{", "// No putAll() here: null key or value would cause NPE", "// (see ProcessBuilder.environment() javadoc).", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "environmentVars", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getKey", "(", ")", "!=", "null", "&&", "entry", ".", "getValue", "(", ")", "!=", "null", ")", "env", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "// Prepare the result", "StringBuilder", "normalOutput", "=", "new", "StringBuilder", "(", ")", ";", "StringBuilder", "errorOutput", "=", "new", "StringBuilder", "(", ")", ";", "int", "exitValue", "=", "-", "1", ";", "// Execute", "Process", "process", "=", "pb", ".", "start", "(", ")", ";", "// Store process in ThreadLocal, so it can be cancelled later (eg. if blocked)", "logger", ".", "fine", "(", "\"Storing process [\"", "+", "applicationName", "+", "\"] [\"", "+", "scopedInstancePath", "+", "\"]\"", ")", ";", "ProcessStore", ".", "setProcess", "(", "applicationName", ",", "scopedInstancePath", ",", "process", ")", ";", "try", "{", "new", "Thread", "(", "new", "OutputRunnable", "(", "process", ",", "true", ",", "errorOutput", ",", "logger", ")", ")", ".", "start", "(", ")", ";", "new", "Thread", "(", "new", "OutputRunnable", "(", "process", ",", "false", ",", "normalOutput", ",", "logger", ")", ")", ".", "start", "(", ")", ";", "exitValue", "=", "process", ".", "waitFor", "(", ")", ";", "if", "(", "exitValue", "!=", "0", ")", "logger", ".", "warning", "(", "\"Command execution returned a non-zero code. Code:\"", "+", "exitValue", ")", ";", "}", "finally", "{", "ProcessStore", ".", "clearProcess", "(", "applicationName", ",", "scopedInstancePath", ")", ";", "}", "return", "new", "ExecutionResult", "(", "normalOutput", ".", "toString", "(", ")", ".", "trim", "(", ")", ",", "errorOutput", ".", "toString", "(", ")", ".", "trim", "(", ")", ",", "exitValue", ")", ";", "}" ]
Executes a command on the VM and retrieves all the result. <p> This includes the process's exit value, its normal output as well as the error flow. </p> @param logger a logger (not null) @param command a command to execute (not null, not empty) @param workingDir the working directory for the command @param environmentVars a map containing environment variables (can be null) @param applicationName the roboconf application name (null if not specified) @param scopedInstancePath the roboconf scoped instance path (null if not specified) @throws IOException if a new process could not be created @throws InterruptedException if the new process encountered a process
[ "Executes", "a", "command", "on", "the", "VM", "and", "retrieves", "all", "the", "result", ".", "<p", ">", "This", "includes", "the", "process", "s", "exit", "value", "its", "normal", "output", "as", "well", "as", "the", "error", "flow", ".", "<", "/", "p", ">" ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/ProgramUtils.java#L69-L123
OpenLiberty/open-liberty
dev/com.ibm.ws.mongo/src/com/ibm/ws/mongo/internal/MongoService.java
MongoService.assertLibrary
private void assertLibrary(ClassLoader loader, boolean sslEnabled) { """ This private worker method will assert that the configured shared library has the correct level of the mongoDB java driver. It will throw a RuntimeException if it is : <li> unable to locate com.mongodb.Mongo.class or com.mongodb.MongoDB.class <li> if the configured library is less than the min supported level """ Class<?> MongoClient = loadClass(loader, com_mongodb_MongoClient); int minor = -1, major = -1; if (MongoClient == null) { // Version 1.0 of the mongo driver used these static variables, but were deprecated in a subsequent release. // If getMajor/MinorVersion doesn't exist, will check for these fields. Class<?> Mongo = loadClass(loader, "com.mongodb.Mongo"); // If we can't find either class, die if (Mongo == null) { // CWKKD0014.missing.driver=CWKKD0014E: The {0} service was unable to locate the required MongoDB driver classes at shared library {1}. throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0014.missing.driver", MONGO, libraryRef.getService().id())); } major = getVersionFromMongo(Mongo, "MAJOR_VERSION"); minor = getVersionFromMongo(Mongo, "MINOR_VERSION"); } else { major = getVersionFromMongoClient(MongoClient, "getMajorVersion"); minor = getVersionFromMongoClient(MongoClient, "getMinorVersion"); } final int MIN_MAJOR = 2; final int MIN_MINOR = 10; final int SSL_MIN_MINOR = 11; final int CERT_AUTH_MIN_MINOR = 12; if (useCertAuth && ((major < MIN_MAJOR) || (major == MIN_MAJOR && minor < CERT_AUTH_MIN_MINOR))) { Tr.error(tc, "CWKKD0023.ssl.certauth.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + CERT_AUTH_MIN_MINOR, major + "." + minor); throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0023.ssl.certauth.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + CERT_AUTH_MIN_MINOR, major + "." + minor)); } if (sslEnabled && ((major < MIN_MAJOR) || (major == MIN_MAJOR && minor < SSL_MIN_MINOR))) { Tr.error(tc, "CWKKD0017.ssl.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + SSL_MIN_MINOR, major + "." + minor); throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0017.ssl.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + SSL_MIN_MINOR, major + "." + minor)); } if (major > MIN_MAJOR || (major == MIN_MAJOR && minor >= MIN_MINOR)) { return; } // CWKKD0013.unsupported.driver=CWKKD0013E: The {0} service encountered down level version of the MongoDB // driver at shared library {1}. Expected a minimum level of {2}, but found {3}. Tr.error(tc, "CWKKD0013.unsupported.driver", MONGO, libraryRef.getService().id(), MIN_MAJOR + "." + MIN_MINOR, major + "." + minor); throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0013.unsupported.driver", MONGO, libraryRef.getService().id(), MIN_MAJOR + "." + MIN_MINOR, major + "." + minor)); }
java
private void assertLibrary(ClassLoader loader, boolean sslEnabled) { Class<?> MongoClient = loadClass(loader, com_mongodb_MongoClient); int minor = -1, major = -1; if (MongoClient == null) { // Version 1.0 of the mongo driver used these static variables, but were deprecated in a subsequent release. // If getMajor/MinorVersion doesn't exist, will check for these fields. Class<?> Mongo = loadClass(loader, "com.mongodb.Mongo"); // If we can't find either class, die if (Mongo == null) { // CWKKD0014.missing.driver=CWKKD0014E: The {0} service was unable to locate the required MongoDB driver classes at shared library {1}. throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0014.missing.driver", MONGO, libraryRef.getService().id())); } major = getVersionFromMongo(Mongo, "MAJOR_VERSION"); minor = getVersionFromMongo(Mongo, "MINOR_VERSION"); } else { major = getVersionFromMongoClient(MongoClient, "getMajorVersion"); minor = getVersionFromMongoClient(MongoClient, "getMinorVersion"); } final int MIN_MAJOR = 2; final int MIN_MINOR = 10; final int SSL_MIN_MINOR = 11; final int CERT_AUTH_MIN_MINOR = 12; if (useCertAuth && ((major < MIN_MAJOR) || (major == MIN_MAJOR && minor < CERT_AUTH_MIN_MINOR))) { Tr.error(tc, "CWKKD0023.ssl.certauth.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + CERT_AUTH_MIN_MINOR, major + "." + minor); throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0023.ssl.certauth.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + CERT_AUTH_MIN_MINOR, major + "." + minor)); } if (sslEnabled && ((major < MIN_MAJOR) || (major == MIN_MAJOR && minor < SSL_MIN_MINOR))) { Tr.error(tc, "CWKKD0017.ssl.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + SSL_MIN_MINOR, major + "." + minor); throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0017.ssl.incompatible.driver", MONGO, id, libraryRef.getService().id(), MIN_MAJOR + "." + SSL_MIN_MINOR, major + "." + minor)); } if (major > MIN_MAJOR || (major == MIN_MAJOR && minor >= MIN_MINOR)) { return; } // CWKKD0013.unsupported.driver=CWKKD0013E: The {0} service encountered down level version of the MongoDB // driver at shared library {1}. Expected a minimum level of {2}, but found {3}. Tr.error(tc, "CWKKD0013.unsupported.driver", MONGO, libraryRef.getService().id(), MIN_MAJOR + "." + MIN_MINOR, major + "." + minor); throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0013.unsupported.driver", MONGO, libraryRef.getService().id(), MIN_MAJOR + "." + MIN_MINOR, major + "." + minor)); }
[ "private", "void", "assertLibrary", "(", "ClassLoader", "loader", ",", "boolean", "sslEnabled", ")", "{", "Class", "<", "?", ">", "MongoClient", "=", "loadClass", "(", "loader", ",", "com_mongodb_MongoClient", ")", ";", "int", "minor", "=", "-", "1", ",", "major", "=", "-", "1", ";", "if", "(", "MongoClient", "==", "null", ")", "{", "// Version 1.0 of the mongo driver used these static variables, but were deprecated in a subsequent release.", "// If getMajor/MinorVersion doesn't exist, will check for these fields.", "Class", "<", "?", ">", "Mongo", "=", "loadClass", "(", "loader", ",", "\"com.mongodb.Mongo\"", ")", ";", "// If we can't find either class, die", "if", "(", "Mongo", "==", "null", ")", "{", "// CWKKD0014.missing.driver=CWKKD0014E: The {0} service was unable to locate the required MongoDB driver classes at shared library {1}.", "throw", "new", "RuntimeException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"CWKKD0014.missing.driver\"", ",", "MONGO", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ")", ")", ";", "}", "major", "=", "getVersionFromMongo", "(", "Mongo", ",", "\"MAJOR_VERSION\"", ")", ";", "minor", "=", "getVersionFromMongo", "(", "Mongo", ",", "\"MINOR_VERSION\"", ")", ";", "}", "else", "{", "major", "=", "getVersionFromMongoClient", "(", "MongoClient", ",", "\"getMajorVersion\"", ")", ";", "minor", "=", "getVersionFromMongoClient", "(", "MongoClient", ",", "\"getMinorVersion\"", ")", ";", "}", "final", "int", "MIN_MAJOR", "=", "2", ";", "final", "int", "MIN_MINOR", "=", "10", ";", "final", "int", "SSL_MIN_MINOR", "=", "11", ";", "final", "int", "CERT_AUTH_MIN_MINOR", "=", "12", ";", "if", "(", "useCertAuth", "&&", "(", "(", "major", "<", "MIN_MAJOR", ")", "||", "(", "major", "==", "MIN_MAJOR", "&&", "minor", "<", "CERT_AUTH_MIN_MINOR", ")", ")", ")", "{", "Tr", ".", "error", "(", "tc", ",", "\"CWKKD0023.ssl.certauth.incompatible.driver\"", ",", "MONGO", ",", "id", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ",", "MIN_MAJOR", "+", "\".\"", "+", "CERT_AUTH_MIN_MINOR", ",", "major", "+", "\".\"", "+", "minor", ")", ";", "throw", "new", "RuntimeException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"CWKKD0023.ssl.certauth.incompatible.driver\"", ",", "MONGO", ",", "id", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ",", "MIN_MAJOR", "+", "\".\"", "+", "CERT_AUTH_MIN_MINOR", ",", "major", "+", "\".\"", "+", "minor", ")", ")", ";", "}", "if", "(", "sslEnabled", "&&", "(", "(", "major", "<", "MIN_MAJOR", ")", "||", "(", "major", "==", "MIN_MAJOR", "&&", "minor", "<", "SSL_MIN_MINOR", ")", ")", ")", "{", "Tr", ".", "error", "(", "tc", ",", "\"CWKKD0017.ssl.incompatible.driver\"", ",", "MONGO", ",", "id", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ",", "MIN_MAJOR", "+", "\".\"", "+", "SSL_MIN_MINOR", ",", "major", "+", "\".\"", "+", "minor", ")", ";", "throw", "new", "RuntimeException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"CWKKD0017.ssl.incompatible.driver\"", ",", "MONGO", ",", "id", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ",", "MIN_MAJOR", "+", "\".\"", "+", "SSL_MIN_MINOR", ",", "major", "+", "\".\"", "+", "minor", ")", ")", ";", "}", "if", "(", "major", ">", "MIN_MAJOR", "||", "(", "major", "==", "MIN_MAJOR", "&&", "minor", ">=", "MIN_MINOR", ")", ")", "{", "return", ";", "}", "// CWKKD0013.unsupported.driver=CWKKD0013E: The {0} service encountered down level version of the MongoDB", "// driver at shared library {1}. Expected a minimum level of {2}, but found {3}.", "Tr", ".", "error", "(", "tc", ",", "\"CWKKD0013.unsupported.driver\"", ",", "MONGO", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ",", "MIN_MAJOR", "+", "\".\"", "+", "MIN_MINOR", ",", "major", "+", "\".\"", "+", "minor", ")", ";", "throw", "new", "RuntimeException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"CWKKD0013.unsupported.driver\"", ",", "MONGO", ",", "libraryRef", ".", "getService", "(", ")", ".", "id", "(", ")", ",", "MIN_MAJOR", "+", "\".\"", "+", "MIN_MINOR", ",", "major", "+", "\".\"", "+", "minor", ")", ")", ";", "}" ]
This private worker method will assert that the configured shared library has the correct level of the mongoDB java driver. It will throw a RuntimeException if it is : <li> unable to locate com.mongodb.Mongo.class or com.mongodb.MongoDB.class <li> if the configured library is less than the min supported level
[ "This", "private", "worker", "method", "will", "assert", "that", "the", "configured", "shared", "library", "has", "the", "correct", "level", "of", "the", "mongoDB", "java", "driver", ".", "It", "will", "throw", "a", "RuntimeException", "if", "it", "is", ":", "<li", ">", "unable", "to", "locate", "com", ".", "mongodb", ".", "Mongo", ".", "class", "or", "com", ".", "mongodb", ".", "MongoDB", ".", "class", "<li", ">", "if", "the", "configured", "library", "is", "less", "than", "the", "min", "supported", "level" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.mongo/src/com/ibm/ws/mongo/internal/MongoService.java#L823-L871
opsmatters/opsmatters-core
src/main/java/com/opsmatters/core/documents/FileColumn.java
FileColumn.parseDateTime
private long parseDateTime(String str, String format) { """ Parses the given date string in the given format to a milliseconds vale. @param str The formatted date to be parsed @param format The format to use when parsing the date @return The date in milliseconds """ return FormatUtilities.getDateTime(str, format, false, true); }
java
private long parseDateTime(String str, String format) { return FormatUtilities.getDateTime(str, format, false, true); }
[ "private", "long", "parseDateTime", "(", "String", "str", ",", "String", "format", ")", "{", "return", "FormatUtilities", ".", "getDateTime", "(", "str", ",", "format", ",", "false", ",", "true", ")", ";", "}" ]
Parses the given date string in the given format to a milliseconds vale. @param str The formatted date to be parsed @param format The format to use when parsing the date @return The date in milliseconds
[ "Parses", "the", "given", "date", "string", "in", "the", "given", "format", "to", "a", "milliseconds", "vale", "." ]
train
https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/documents/FileColumn.java#L690-L693
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsSitemapNavPosCalculator.java
CmsSitemapNavPosCalculator.getPositionInfo
private PositionInfo getPositionInfo(List<CmsJspNavElement> navigation, int index) { """ Gets the position info bean for a given position.<p> @param navigation the navigation element list @param index the index in the navigation element list @return the position info bean for a given position """ if ((index < 0) || (index >= navigation.size())) { return new PositionInfo(false, -1); } float navPos = navigation.get(index).getNavPosition(); return new PositionInfo(true, navPos); }
java
private PositionInfo getPositionInfo(List<CmsJspNavElement> navigation, int index) { if ((index < 0) || (index >= navigation.size())) { return new PositionInfo(false, -1); } float navPos = navigation.get(index).getNavPosition(); return new PositionInfo(true, navPos); }
[ "private", "PositionInfo", "getPositionInfo", "(", "List", "<", "CmsJspNavElement", ">", "navigation", ",", "int", "index", ")", "{", "if", "(", "(", "index", "<", "0", ")", "||", "(", "index", ">=", "navigation", ".", "size", "(", ")", ")", ")", "{", "return", "new", "PositionInfo", "(", "false", ",", "-", "1", ")", ";", "}", "float", "navPos", "=", "navigation", ".", "get", "(", "index", ")", ".", "getNavPosition", "(", ")", ";", "return", "new", "PositionInfo", "(", "true", ",", "navPos", ")", ";", "}" ]
Gets the position info bean for a given position.<p> @param navigation the navigation element list @param index the index in the navigation element list @return the position info bean for a given position
[ "Gets", "the", "position", "info", "bean", "for", "a", "given", "position", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsSitemapNavPosCalculator.java#L269-L276
jeremylong/DependencyCheck
utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java
Settings.setArrayIfNotEmpty
public void setArrayIfNotEmpty(@NotNull final String key, @Nullable final String[] value) { """ Sets a property value only if the array value is not null and not empty. @param key the key for the property @param value the value for the property """ if (null != value && value.length > 0) { setString(key, new Gson().toJson(value)); } }
java
public void setArrayIfNotEmpty(@NotNull final String key, @Nullable final String[] value) { if (null != value && value.length > 0) { setString(key, new Gson().toJson(value)); } }
[ "public", "void", "setArrayIfNotEmpty", "(", "@", "NotNull", "final", "String", "key", ",", "@", "Nullable", "final", "String", "[", "]", "value", ")", "{", "if", "(", "null", "!=", "value", "&&", "value", ".", "length", ">", "0", ")", "{", "setString", "(", "key", ",", "new", "Gson", "(", ")", ".", "toJson", "(", "value", ")", ")", ";", "}", "}" ]
Sets a property value only if the array value is not null and not empty. @param key the key for the property @param value the value for the property
[ "Sets", "a", "property", "value", "only", "if", "the", "array", "value", "is", "not", "null", "and", "not", "empty", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L700-L704
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.setOrtho2D
public Matrix4d setOrtho2D(double left, double right, double bottom, double top) { """ Set this matrix to be an orthographic projection transformation for a right-handed coordinate system. <p> This method is equivalent to calling {@link #setOrtho(double, double, double, double, double, double) setOrtho()} with <code>zNear=-1</code> and <code>zFar=+1</code>. <p> In order to apply the orthographic projection to an already existing transformation, use {@link #ortho2D(double, double, double, double) ortho2D()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #setOrtho(double, double, double, double, double, double) @see #ortho2D(double, double, double, double) @param left the distance from the center to the left frustum edge @param right the distance from the center to the right frustum edge @param bottom the distance from the center to the bottom frustum edge @param top the distance from the center to the top frustum edge @return this """ if ((properties & PROPERTY_IDENTITY) == 0) _identity(); m00 = 2.0 / (right - left); m11 = 2.0 / (top - bottom); m22 = -1.0; m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); properties = PROPERTY_AFFINE; return this; }
java
public Matrix4d setOrtho2D(double left, double right, double bottom, double top) { if ((properties & PROPERTY_IDENTITY) == 0) _identity(); m00 = 2.0 / (right - left); m11 = 2.0 / (top - bottom); m22 = -1.0; m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); properties = PROPERTY_AFFINE; return this; }
[ "public", "Matrix4d", "setOrtho2D", "(", "double", "left", ",", "double", "right", ",", "double", "bottom", ",", "double", "top", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "==", "0", ")", "_identity", "(", ")", ";", "m00", "=", "2.0", "/", "(", "right", "-", "left", ")", ";", "m11", "=", "2.0", "/", "(", "top", "-", "bottom", ")", ";", "m22", "=", "-", "1.0", ";", "m30", "=", "(", "right", "+", "left", ")", "/", "(", "left", "-", "right", ")", ";", "m31", "=", "(", "top", "+", "bottom", ")", "/", "(", "bottom", "-", "top", ")", ";", "properties", "=", "PROPERTY_AFFINE", ";", "return", "this", ";", "}" ]
Set this matrix to be an orthographic projection transformation for a right-handed coordinate system. <p> This method is equivalent to calling {@link #setOrtho(double, double, double, double, double, double) setOrtho()} with <code>zNear=-1</code> and <code>zFar=+1</code>. <p> In order to apply the orthographic projection to an already existing transformation, use {@link #ortho2D(double, double, double, double) ortho2D()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #setOrtho(double, double, double, double, double, double) @see #ortho2D(double, double, double, double) @param left the distance from the center to the left frustum edge @param right the distance from the center to the right frustum edge @param bottom the distance from the center to the bottom frustum edge @param top the distance from the center to the top frustum edge @return this
[ "Set", "this", "matrix", "to", "be", "an", "orthographic", "projection", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", "{", "@link", "#setOrtho", "(", "double", "double", "double", "double", "double", "double", ")", "setOrtho", "()", "}", "with", "<code", ">", "zNear", "=", "-", "1<", "/", "code", ">", "and", "<code", ">", "zFar", "=", "+", "1<", "/", "code", ">", ".", "<p", ">", "In", "order", "to", "apply", "the", "orthographic", "projection", "to", "an", "already", "existing", "transformation", "use", "{", "@link", "#ortho2D", "(", "double", "double", "double", "double", ")", "ortho2D", "()", "}", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "www", ".", "songho", ".", "ca", "/", "opengl", "/", "gl_projectionmatrix", ".", "html#ortho", ">", "http", ":", "//", "www", ".", "songho", ".", "ca<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L10750-L10760
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java
PercentileDistributionSummary.computeIfAbsent
private static PercentileDistributionSummary computeIfAbsent( Registry registry, Id id, long min, long max) { """ Only create a new instance of the counter if there is not a cached copy. The array for keeping track of the counter per bucket is quite large (1-2k depending on pointer size) and can lead to a high allocation rate if the timer is not reused in a high volume call site. """ Object summary = Utils.computeIfAbsent( registry.state(), id, i -> new PercentileDistributionSummary(registry, id, min, max)); return (summary instanceof PercentileDistributionSummary) ? ((PercentileDistributionSummary) summary).withRange(min, max) : new PercentileDistributionSummary(registry, id, min, max); }
java
private static PercentileDistributionSummary computeIfAbsent( Registry registry, Id id, long min, long max) { Object summary = Utils.computeIfAbsent( registry.state(), id, i -> new PercentileDistributionSummary(registry, id, min, max)); return (summary instanceof PercentileDistributionSummary) ? ((PercentileDistributionSummary) summary).withRange(min, max) : new PercentileDistributionSummary(registry, id, min, max); }
[ "private", "static", "PercentileDistributionSummary", "computeIfAbsent", "(", "Registry", "registry", ",", "Id", "id", ",", "long", "min", ",", "long", "max", ")", "{", "Object", "summary", "=", "Utils", ".", "computeIfAbsent", "(", "registry", ".", "state", "(", ")", ",", "id", ",", "i", "->", "new", "PercentileDistributionSummary", "(", "registry", ",", "id", ",", "min", ",", "max", ")", ")", ";", "return", "(", "summary", "instanceof", "PercentileDistributionSummary", ")", "?", "(", "(", "PercentileDistributionSummary", ")", "summary", ")", ".", "withRange", "(", "min", ",", "max", ")", ":", "new", "PercentileDistributionSummary", "(", "registry", ",", "id", ",", "min", ",", "max", ")", ";", "}" ]
Only create a new instance of the counter if there is not a cached copy. The array for keeping track of the counter per bucket is quite large (1-2k depending on pointer size) and can lead to a high allocation rate if the timer is not reused in a high volume call site.
[ "Only", "create", "a", "new", "instance", "of", "the", "counter", "if", "there", "is", "not", "a", "cached", "copy", ".", "The", "array", "for", "keeping", "track", "of", "the", "counter", "per", "bucket", "is", "quite", "large", "(", "1", "-", "2k", "depending", "on", "pointer", "size", ")", "and", "can", "lead", "to", "a", "high", "allocation", "rate", "if", "the", "timer", "is", "not", "reused", "in", "a", "high", "volume", "call", "site", "." ]
train
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java#L67-L74
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/compiler/batch/SarlBatchCompiler.java
SarlBatchCompiler.notifiesIssueMessageListeners
private void notifiesIssueMessageListeners(Issue issue, org.eclipse.emf.common.util.URI uri, String message) { """ Replies the message for the given issue. @param issue the issue. @param uri URI to the problem. @param message the formatted message. @since 0.6 """ for (final IssueMessageListener listener : this.messageListeners) { listener.onIssue(issue, uri, message); } }
java
private void notifiesIssueMessageListeners(Issue issue, org.eclipse.emf.common.util.URI uri, String message) { for (final IssueMessageListener listener : this.messageListeners) { listener.onIssue(issue, uri, message); } }
[ "private", "void", "notifiesIssueMessageListeners", "(", "Issue", "issue", ",", "org", ".", "eclipse", ".", "emf", ".", "common", ".", "util", ".", "URI", "uri", ",", "String", "message", ")", "{", "for", "(", "final", "IssueMessageListener", "listener", ":", "this", ".", "messageListeners", ")", "{", "listener", ".", "onIssue", "(", "issue", ",", "uri", ",", "message", ")", ";", "}", "}" ]
Replies the message for the given issue. @param issue the issue. @param uri URI to the problem. @param message the formatted message. @since 0.6
[ "Replies", "the", "message", "for", "the", "given", "issue", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/compiler/batch/SarlBatchCompiler.java#L449-L453
spring-projects/spring-security-oauth
spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/OAuthProviderProcessingFilter.java
OAuthProviderProcessingFilter.parametersAreAdequate
protected boolean parametersAreAdequate(Map<String, String> oauthParams) { """ By default, OAuth parameters are adequate if a consumer key is present. @param oauthParams The oauth params. @return Whether the parsed parameters are adequate. """ return oauthParams.containsKey(OAuthConsumerParameter.oauth_consumer_key.toString()); }
java
protected boolean parametersAreAdequate(Map<String, String> oauthParams) { return oauthParams.containsKey(OAuthConsumerParameter.oauth_consumer_key.toString()); }
[ "protected", "boolean", "parametersAreAdequate", "(", "Map", "<", "String", ",", "String", ">", "oauthParams", ")", "{", "return", "oauthParams", ".", "containsKey", "(", "OAuthConsumerParameter", ".", "oauth_consumer_key", ".", "toString", "(", ")", ")", ";", "}" ]
By default, OAuth parameters are adequate if a consumer key is present. @param oauthParams The oauth params. @return Whether the parsed parameters are adequate.
[ "By", "default", "OAuth", "parameters", "are", "adequate", "if", "a", "consumer", "key", "is", "present", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/OAuthProviderProcessingFilter.java#L220-L222
jklingsporn/vertx-jooq
vertx-jooq-generate/src/main/java/io/github/jklingsporn/vertx/jooq/generate/VertxGenerator.java
VertxGenerator.generateFetchMethods
protected void generateFetchMethods(TableDefinition table, JavaWriter out) { """ Copied (more ore less) from JavaGenerator. Generates fetchByCYZ- and fetchOneByCYZ-methods @param table @param out """ VertxJavaWriter vOut = (VertxJavaWriter) out; String pType = vOut.ref(getStrategy().getFullJavaClassName(table, GeneratorStrategy.Mode.POJO)); UniqueKeyDefinition primaryKey = table.getPrimaryKey(); ColumnDefinition firstPrimaryKeyColumn = primaryKey.getKeyColumns().get(0); for (ColumnDefinition column : table.getColumns()) { final String colName = column.getOutputName(); final String colClass = getStrategy().getJavaClassName(column); final String colType = vOut.ref(getJavaType(column.getType())); final String colIdentifier = vOut.ref(getStrategy().getFullJavaIdentifier(column), colRefSegments(column)); //fetchById is already defined in VertxDAO if(!firstPrimaryKeyColumn.equals(column)){ // fetchBy[Column]([T]...) // ----------------------- generateFindManyByMethods(out, pType, colName, colClass, colType, colIdentifier); } ukLoop: for (UniqueKeyDefinition uk : column.getUniqueKeys()) { // If column is part of a single-column unique key... if (uk.getKeyColumns().size() == 1 && uk.getKeyColumns().get(0).equals(column) && !uk.isPrimaryKey()) { // fetchOneBy[Column]([T]) // ----------------------- generateFindOneByMethods(out, pType, colName, colClass, colType, colIdentifier); break ukLoop; } } } }
java
protected void generateFetchMethods(TableDefinition table, JavaWriter out){ VertxJavaWriter vOut = (VertxJavaWriter) out; String pType = vOut.ref(getStrategy().getFullJavaClassName(table, GeneratorStrategy.Mode.POJO)); UniqueKeyDefinition primaryKey = table.getPrimaryKey(); ColumnDefinition firstPrimaryKeyColumn = primaryKey.getKeyColumns().get(0); for (ColumnDefinition column : table.getColumns()) { final String colName = column.getOutputName(); final String colClass = getStrategy().getJavaClassName(column); final String colType = vOut.ref(getJavaType(column.getType())); final String colIdentifier = vOut.ref(getStrategy().getFullJavaIdentifier(column), colRefSegments(column)); //fetchById is already defined in VertxDAO if(!firstPrimaryKeyColumn.equals(column)){ // fetchBy[Column]([T]...) // ----------------------- generateFindManyByMethods(out, pType, colName, colClass, colType, colIdentifier); } ukLoop: for (UniqueKeyDefinition uk : column.getUniqueKeys()) { // If column is part of a single-column unique key... if (uk.getKeyColumns().size() == 1 && uk.getKeyColumns().get(0).equals(column) && !uk.isPrimaryKey()) { // fetchOneBy[Column]([T]) // ----------------------- generateFindOneByMethods(out, pType, colName, colClass, colType, colIdentifier); break ukLoop; } } } }
[ "protected", "void", "generateFetchMethods", "(", "TableDefinition", "table", ",", "JavaWriter", "out", ")", "{", "VertxJavaWriter", "vOut", "=", "(", "VertxJavaWriter", ")", "out", ";", "String", "pType", "=", "vOut", ".", "ref", "(", "getStrategy", "(", ")", ".", "getFullJavaClassName", "(", "table", ",", "GeneratorStrategy", ".", "Mode", ".", "POJO", ")", ")", ";", "UniqueKeyDefinition", "primaryKey", "=", "table", ".", "getPrimaryKey", "(", ")", ";", "ColumnDefinition", "firstPrimaryKeyColumn", "=", "primaryKey", ".", "getKeyColumns", "(", ")", ".", "get", "(", "0", ")", ";", "for", "(", "ColumnDefinition", "column", ":", "table", ".", "getColumns", "(", ")", ")", "{", "final", "String", "colName", "=", "column", ".", "getOutputName", "(", ")", ";", "final", "String", "colClass", "=", "getStrategy", "(", ")", ".", "getJavaClassName", "(", "column", ")", ";", "final", "String", "colType", "=", "vOut", ".", "ref", "(", "getJavaType", "(", "column", ".", "getType", "(", ")", ")", ")", ";", "final", "String", "colIdentifier", "=", "vOut", ".", "ref", "(", "getStrategy", "(", ")", ".", "getFullJavaIdentifier", "(", "column", ")", ",", "colRefSegments", "(", "column", ")", ")", ";", "//fetchById is already defined in VertxDAO", "if", "(", "!", "firstPrimaryKeyColumn", ".", "equals", "(", "column", ")", ")", "{", "// fetchBy[Column]([T]...)", "// -----------------------", "generateFindManyByMethods", "(", "out", ",", "pType", ",", "colName", ",", "colClass", ",", "colType", ",", "colIdentifier", ")", ";", "}", "ukLoop", ":", "for", "(", "UniqueKeyDefinition", "uk", ":", "column", ".", "getUniqueKeys", "(", ")", ")", "{", "// If column is part of a single-column unique key...", "if", "(", "uk", ".", "getKeyColumns", "(", ")", ".", "size", "(", ")", "==", "1", "&&", "uk", ".", "getKeyColumns", "(", ")", ".", "get", "(", "0", ")", ".", "equals", "(", "column", ")", "&&", "!", "uk", ".", "isPrimaryKey", "(", ")", ")", "{", "// fetchOneBy[Column]([T])", "// -----------------------", "generateFindOneByMethods", "(", "out", ",", "pType", ",", "colName", ",", "colClass", ",", "colType", ",", "colIdentifier", ")", ";", "break", "ukLoop", ";", "}", "}", "}", "}" ]
Copied (more ore less) from JavaGenerator. Generates fetchByCYZ- and fetchOneByCYZ-methods @param table @param out
[ "Copied", "(", "more", "ore", "less", ")", "from", "JavaGenerator", ".", "Generates", "fetchByCYZ", "-", "and", "fetchOneByCYZ", "-", "methods" ]
train
https://github.com/jklingsporn/vertx-jooq/blob/0db00b5e040639c309691dfbc125034fa3346d88/vertx-jooq-generate/src/main/java/io/github/jklingsporn/vertx/jooq/generate/VertxGenerator.java#L390-L425
UrielCh/ovh-java-sdk
ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java
ApiOvhHorizonView.serviceName_dedicatedHorizon_customerUser_username_GET
public OvhCustomerUser serviceName_dedicatedHorizon_customerUser_username_GET(String serviceName, String username) throws IOException { """ Get this object properties REST: GET /horizonView/{serviceName}/dedicatedHorizon/customerUser/{username} @param serviceName [required] Domain of the service @param username [required] Customer username of your HaaS User """ String qPath = "/horizonView/{serviceName}/dedicatedHorizon/customerUser/{username}"; StringBuilder sb = path(qPath, serviceName, username); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCustomerUser.class); }
java
public OvhCustomerUser serviceName_dedicatedHorizon_customerUser_username_GET(String serviceName, String username) throws IOException { String qPath = "/horizonView/{serviceName}/dedicatedHorizon/customerUser/{username}"; StringBuilder sb = path(qPath, serviceName, username); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCustomerUser.class); }
[ "public", "OvhCustomerUser", "serviceName_dedicatedHorizon_customerUser_username_GET", "(", "String", "serviceName", ",", "String", "username", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/horizonView/{serviceName}/dedicatedHorizon/customerUser/{username}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "username", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhCustomerUser", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /horizonView/{serviceName}/dedicatedHorizon/customerUser/{username} @param serviceName [required] Domain of the service @param username [required] Customer username of your HaaS User
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-horizonView/src/main/java/net/minidev/ovh/api/ApiOvhHorizonView.java#L476-L481
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/format/FastDateFormat.java
FastDateFormat.getTimeInstance
public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) { """ 获得 {@link FastDateFormat} 实例<br> 支持缓存 @param style time style: FULL, LONG, MEDIUM, or SHORT @param timeZone optional time zone, overrides time zone of formatted time @param locale {@link Locale} 日期地理位置 @return 本地化 {@link FastDateFormat} """ return cache.getTimeInstance(style, timeZone, locale); }
java
public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) { return cache.getTimeInstance(style, timeZone, locale); }
[ "public", "static", "FastDateFormat", "getTimeInstance", "(", "final", "int", "style", ",", "final", "TimeZone", "timeZone", ",", "final", "Locale", "locale", ")", "{", "return", "cache", ".", "getTimeInstance", "(", "style", ",", "timeZone", ",", "locale", ")", ";", "}" ]
获得 {@link FastDateFormat} 实例<br> 支持缓存 @param style time style: FULL, LONG, MEDIUM, or SHORT @param timeZone optional time zone, overrides time zone of formatted time @param locale {@link Locale} 日期地理位置 @return 本地化 {@link FastDateFormat}
[ "获得", "{", "@link", "FastDateFormat", "}", "实例<br", ">", "支持缓存" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/format/FastDateFormat.java#L207-L209
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/MustBeClosedChecker.java
MustBeClosedChecker.matchMethodInvocation
@Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { """ Check that invocations of methods annotated with {@link MustBeClosed} are called within the resource variable initializer of a try-with-resources statement. """ if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) { return NO_MATCH; } if (CONSTRUCTOR.matches(tree, state)) { return NO_MATCH; } return matchNewClassOrMethodInvocation(tree, state); }
java
@Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) { return NO_MATCH; } if (CONSTRUCTOR.matches(tree, state)) { return NO_MATCH; } return matchNewClassOrMethodInvocation(tree, state); }
[ "@", "Override", "public", "Description", "matchMethodInvocation", "(", "MethodInvocationTree", "tree", ",", "VisitorState", "state", ")", "{", "if", "(", "!", "HAS_MUST_BE_CLOSED_ANNOTATION", ".", "matches", "(", "tree", ",", "state", ")", ")", "{", "return", "NO_MATCH", ";", "}", "if", "(", "CONSTRUCTOR", ".", "matches", "(", "tree", ",", "state", ")", ")", "{", "return", "NO_MATCH", ";", "}", "return", "matchNewClassOrMethodInvocation", "(", "tree", ",", "state", ")", ";", "}" ]
Check that invocations of methods annotated with {@link MustBeClosed} are called within the resource variable initializer of a try-with-resources statement.
[ "Check", "that", "invocations", "of", "methods", "annotated", "with", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/MustBeClosedChecker.java#L108-L117
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br/br.java
br.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ br_responses result = (br_responses) service.get_payload_formatter().string_to_resource(br_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_response_array); } br[] result_br = new br[result.br_response_array.length]; for(int i = 0; i < result.br_response_array.length; i++) { result_br[i] = result.br_response_array[i].br[0]; } return result_br; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { br_responses result = (br_responses) service.get_payload_formatter().string_to_resource(br_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_response_array); } br[] result_br = new br[result.br_response_array.length]; for(int i = 0; i < result.br_response_array.length; i++) { result_br[i] = result.br_response_array[i].br[0]; } return result_br; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "br_responses", "result", "=", "(", "br_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "br_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "br_response_array", ")", ";", "}", "br", "[", "]", "result_br", "=", "new", "br", "[", "result", ".", "br_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "br_response_array", ".", "length", ";", "i", "++", ")", "{", "result_br", "[", "i", "]", "=", "result", ".", "br_response_array", "[", "i", "]", ".", "br", "[", "0", "]", ";", "}", "return", "result_br", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br.java#L883-L900
apache/flink
flink-core/src/main/java/org/apache/flink/types/parser/SqlTimestampParser.java
SqlTimestampParser.parseField
public static final Timestamp parseField(byte[] bytes, int startPos, int length, char delimiter) { """ Static utility to parse a field of type Timestamp from a byte sequence that represents text characters (such as when read from a file stream). @param bytes The bytes containing the text data that should be parsed. @param startPos The offset to start the parsing. @param length The length of the byte sequence (counting from the offset). @param delimiter The delimiter that terminates the field. @return The parsed value. @throws IllegalArgumentException Thrown when the value cannot be parsed because the text represents not a correct number. """ final int limitedLen = nextStringLength(bytes, startPos, length, delimiter); if (limitedLen > 0 && (Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[startPos + limitedLen - 1]))) { throw new NumberFormatException("There is leading or trailing whitespace in the numeric field."); } final String str = new String(bytes, startPos, limitedLen, ConfigConstants.DEFAULT_CHARSET); return Timestamp.valueOf(str); }
java
public static final Timestamp parseField(byte[] bytes, int startPos, int length, char delimiter) { final int limitedLen = nextStringLength(bytes, startPos, length, delimiter); if (limitedLen > 0 && (Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[startPos + limitedLen - 1]))) { throw new NumberFormatException("There is leading or trailing whitespace in the numeric field."); } final String str = new String(bytes, startPos, limitedLen, ConfigConstants.DEFAULT_CHARSET); return Timestamp.valueOf(str); }
[ "public", "static", "final", "Timestamp", "parseField", "(", "byte", "[", "]", "bytes", ",", "int", "startPos", ",", "int", "length", ",", "char", "delimiter", ")", "{", "final", "int", "limitedLen", "=", "nextStringLength", "(", "bytes", ",", "startPos", ",", "length", ",", "delimiter", ")", ";", "if", "(", "limitedLen", ">", "0", "&&", "(", "Character", ".", "isWhitespace", "(", "bytes", "[", "startPos", "]", ")", "||", "Character", ".", "isWhitespace", "(", "bytes", "[", "startPos", "+", "limitedLen", "-", "1", "]", ")", ")", ")", "{", "throw", "new", "NumberFormatException", "(", "\"There is leading or trailing whitespace in the numeric field.\"", ")", ";", "}", "final", "String", "str", "=", "new", "String", "(", "bytes", ",", "startPos", ",", "limitedLen", ",", "ConfigConstants", ".", "DEFAULT_CHARSET", ")", ";", "return", "Timestamp", ".", "valueOf", "(", "str", ")", ";", "}" ]
Static utility to parse a field of type Timestamp from a byte sequence that represents text characters (such as when read from a file stream). @param bytes The bytes containing the text data that should be parsed. @param startPos The offset to start the parsing. @param length The length of the byte sequence (counting from the offset). @param delimiter The delimiter that terminates the field. @return The parsed value. @throws IllegalArgumentException Thrown when the value cannot be parsed because the text represents not a correct number.
[ "Static", "utility", "to", "parse", "a", "field", "of", "type", "Timestamp", "from", "a", "byte", "sequence", "that", "represents", "text", "characters", "(", "such", "as", "when", "read", "from", "a", "file", "stream", ")", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/parser/SqlTimestampParser.java#L98-L108
sagiegurari/fax4j
src/main/java/org/fax4j/spi/http/HTTPFaxClientSpi.java
HTTPFaxClientSpi.updateFaxJob
protected void updateFaxJob(FaxJob faxJob,HTTPResponse httpResponse,FaxActionType faxActionType) { """ Updates the fax job based on the data from the HTTP response. @param faxJob The fax job object @param httpResponse The HTTP response @param faxActionType The fax action type """ this.httpResponseHandler.updateFaxJob(faxJob,httpResponse,faxActionType); }
java
protected void updateFaxJob(FaxJob faxJob,HTTPResponse httpResponse,FaxActionType faxActionType) { this.httpResponseHandler.updateFaxJob(faxJob,httpResponse,faxActionType); }
[ "protected", "void", "updateFaxJob", "(", "FaxJob", "faxJob", ",", "HTTPResponse", "httpResponse", ",", "FaxActionType", "faxActionType", ")", "{", "this", ".", "httpResponseHandler", ".", "updateFaxJob", "(", "faxJob", ",", "httpResponse", ",", "faxActionType", ")", ";", "}" ]
Updates the fax job based on the data from the HTTP response. @param faxJob The fax job object @param httpResponse The HTTP response @param faxActionType The fax action type
[ "Updates", "the", "fax", "job", "based", "on", "the", "data", "from", "the", "HTTP", "response", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/http/HTTPFaxClientSpi.java#L641-L644
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.indexOfAnyBut
public static int indexOfAnyBut(String str, String searchChars) { """ <p>Search a String to find the first index of any character not in the given set of characters.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> search string will return <code>-1</code>.</p> <pre> GosuStringUtil.indexOfAnyBut(null, *) = -1 GosuStringUtil.indexOfAnyBut("", *) = -1 GosuStringUtil.indexOfAnyBut(*, null) = -1 GosuStringUtil.indexOfAnyBut(*, "") = -1 GosuStringUtil.indexOfAnyBut("zzabyycdxx", "za") = 3 GosuStringUtil.indexOfAnyBut("zzabyycdxx", "") = 0 GosuStringUtil.indexOfAnyBut("aba","ab") = -1 </pre> @param str the String to check, may be null @param searchChars the chars to search for, may be null @return the index of any of the chars, -1 if no match or null input @since 2.0 """ if (isEmpty(str) || isEmpty(searchChars)) { return -1; } for (int i = 0; i < str.length(); i++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; }
java
public static int indexOfAnyBut(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return -1; } for (int i = 0; i < str.length(); i++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; }
[ "public", "static", "int", "indexOfAnyBut", "(", "String", "str", ",", "String", "searchChars", ")", "{", "if", "(", "isEmpty", "(", "str", ")", "||", "isEmpty", "(", "searchChars", ")", ")", "{", "return", "-", "1", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "str", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "searchChars", ".", "indexOf", "(", "str", ".", "charAt", "(", "i", ")", ")", "<", "0", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
<p>Search a String to find the first index of any character not in the given set of characters.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> search string will return <code>-1</code>.</p> <pre> GosuStringUtil.indexOfAnyBut(null, *) = -1 GosuStringUtil.indexOfAnyBut("", *) = -1 GosuStringUtil.indexOfAnyBut(*, null) = -1 GosuStringUtil.indexOfAnyBut(*, "") = -1 GosuStringUtil.indexOfAnyBut("zzabyycdxx", "za") = 3 GosuStringUtil.indexOfAnyBut("zzabyycdxx", "") = 0 GosuStringUtil.indexOfAnyBut("aba","ab") = -1 </pre> @param str the String to check, may be null @param searchChars the chars to search for, may be null @return the index of any of the chars, -1 if no match or null input @since 2.0
[ "<p", ">", "Search", "a", "String", "to", "find", "the", "first", "index", "of", "any", "character", "not", "in", "the", "given", "set", "of", "characters", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L1247-L1257
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.addArgsFor
public void addArgsFor(SDVariable[] variables, DifferentialFunction function) { """ Adds incoming arguments for the specified differential function to the graph @param variables variables that are arguments (inputs) to the specified function @param function Function """ String[] varNames = new String[variables.length]; for (int i = 0; i < varNames.length; i++) { if (variables[i] == null) throw new ND4JIllegalStateException("Found null variable at index " + i); varNames[i] = variables[i].getVarName(); } addArgsFor(varNames, function); }
java
public void addArgsFor(SDVariable[] variables, DifferentialFunction function) { String[] varNames = new String[variables.length]; for (int i = 0; i < varNames.length; i++) { if (variables[i] == null) throw new ND4JIllegalStateException("Found null variable at index " + i); varNames[i] = variables[i].getVarName(); } addArgsFor(varNames, function); }
[ "public", "void", "addArgsFor", "(", "SDVariable", "[", "]", "variables", ",", "DifferentialFunction", "function", ")", "{", "String", "[", "]", "varNames", "=", "new", "String", "[", "variables", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "varNames", ".", "length", ";", "i", "++", ")", "{", "if", "(", "variables", "[", "i", "]", "==", "null", ")", "throw", "new", "ND4JIllegalStateException", "(", "\"Found null variable at index \"", "+", "i", ")", ";", "varNames", "[", "i", "]", "=", "variables", "[", "i", "]", ".", "getVarName", "(", ")", ";", "}", "addArgsFor", "(", "varNames", ",", "function", ")", ";", "}" ]
Adds incoming arguments for the specified differential function to the graph @param variables variables that are arguments (inputs) to the specified function @param function Function
[ "Adds", "incoming", "arguments", "for", "the", "specified", "differential", "function", "to", "the", "graph" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L1193-L1201
google/closure-compiler
src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java
FeatureSet.with
@VisibleForTesting public FeatureSet with(Set<Feature> newFeatures) { """ Returns a feature set combining all the features from {@code this} and {@code newFeatures}. """ return new FeatureSet(union(features, newFeatures)); }
java
@VisibleForTesting public FeatureSet with(Set<Feature> newFeatures) { return new FeatureSet(union(features, newFeatures)); }
[ "@", "VisibleForTesting", "public", "FeatureSet", "with", "(", "Set", "<", "Feature", ">", "newFeatures", ")", "{", "return", "new", "FeatureSet", "(", "union", "(", "features", ",", "newFeatures", ")", ")", ";", "}" ]
Returns a feature set combining all the features from {@code this} and {@code newFeatures}.
[ "Returns", "a", "feature", "set", "combining", "all", "the", "features", "from", "{" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java#L373-L376
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java
PersistenceController.upsertMessageStatus
public Observable<Boolean> upsertMessageStatus(ChatMessageStatus status) { """ Insert new message status. @param status New message status. @return Observable emitting result. """ return asObservable(new Executor<Boolean>() { @Override void execute(ChatStore store, Emitter<Boolean> emitter) { store.beginTransaction(); boolean isSuccessful = store.update(status) && doUpdateConversationFromEvent(store, status.getConversationId(), status.getConversationEventId(), status.getUpdatedOn()); store.endTransaction(); emitter.onNext(isSuccessful); emitter.onCompleted(); } }); }
java
public Observable<Boolean> upsertMessageStatus(ChatMessageStatus status) { return asObservable(new Executor<Boolean>() { @Override void execute(ChatStore store, Emitter<Boolean> emitter) { store.beginTransaction(); boolean isSuccessful = store.update(status) && doUpdateConversationFromEvent(store, status.getConversationId(), status.getConversationEventId(), status.getUpdatedOn()); store.endTransaction(); emitter.onNext(isSuccessful); emitter.onCompleted(); } }); }
[ "public", "Observable", "<", "Boolean", ">", "upsertMessageStatus", "(", "ChatMessageStatus", "status", ")", "{", "return", "asObservable", "(", "new", "Executor", "<", "Boolean", ">", "(", ")", "{", "@", "Override", "void", "execute", "(", "ChatStore", "store", ",", "Emitter", "<", "Boolean", ">", "emitter", ")", "{", "store", ".", "beginTransaction", "(", ")", ";", "boolean", "isSuccessful", "=", "store", ".", "update", "(", "status", ")", "&&", "doUpdateConversationFromEvent", "(", "store", ",", "status", ".", "getConversationId", "(", ")", ",", "status", ".", "getConversationEventId", "(", ")", ",", "status", ".", "getUpdatedOn", "(", ")", ")", ";", "store", ".", "endTransaction", "(", ")", ";", "emitter", ".", "onNext", "(", "isSuccessful", ")", ";", "emitter", ".", "onCompleted", "(", ")", ";", "}", "}", ")", ";", "}" ]
Insert new message status. @param status New message status. @return Observable emitting result.
[ "Insert", "new", "message", "status", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java#L362-L377
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java
ThreadLocalRandom.internalNextLong
final long internalNextLong(long origin, long bound) { """ The form of nextLong used by LongStream Spliterators. If origin is greater than bound, acts as unbounded form of nextLong, else as bounded form. @param origin the least value, unless greater than bound @param bound the upper bound (exclusive), must not equal origin @return a pseudorandom value """ long r = mix64(nextSeed()); if (origin < bound) { long n = bound - origin, m = n - 1; if ((n & m) == 0L) // power of two r = (r & m) + origin; else if (n > 0L) { // reject over-represented candidates for (long u = r >>> 1; // ensure nonnegative u + m - (r = u % n) < 0L; // rejection check u = mix64(nextSeed()) >>> 1) // retry ; r += origin; } else { // range not representable as long while (r < origin || r >= bound) r = mix64(nextSeed()); } } return r; }
java
final long internalNextLong(long origin, long bound) { long r = mix64(nextSeed()); if (origin < bound) { long n = bound - origin, m = n - 1; if ((n & m) == 0L) // power of two r = (r & m) + origin; else if (n > 0L) { // reject over-represented candidates for (long u = r >>> 1; // ensure nonnegative u + m - (r = u % n) < 0L; // rejection check u = mix64(nextSeed()) >>> 1) // retry ; r += origin; } else { // range not representable as long while (r < origin || r >= bound) r = mix64(nextSeed()); } } return r; }
[ "final", "long", "internalNextLong", "(", "long", "origin", ",", "long", "bound", ")", "{", "long", "r", "=", "mix64", "(", "nextSeed", "(", ")", ")", ";", "if", "(", "origin", "<", "bound", ")", "{", "long", "n", "=", "bound", "-", "origin", ",", "m", "=", "n", "-", "1", ";", "if", "(", "(", "n", "&", "m", ")", "==", "0L", ")", "// power of two", "r", "=", "(", "r", "&", "m", ")", "+", "origin", ";", "else", "if", "(", "n", ">", "0L", ")", "{", "// reject over-represented candidates", "for", "(", "long", "u", "=", "r", ">>>", "1", ";", "// ensure nonnegative", "u", "+", "m", "-", "(", "r", "=", "u", "%", "n", ")", "<", "0L", ";", "// rejection check", "u", "=", "mix64", "(", "nextSeed", "(", ")", ")", ">>>", "1", ")", "// retry", ";", "r", "+=", "origin", ";", "}", "else", "{", "// range not representable as long", "while", "(", "r", "<", "origin", "||", "r", ">=", "bound", ")", "r", "=", "mix64", "(", "nextSeed", "(", ")", ")", ";", "}", "}", "return", "r", ";", "}" ]
The form of nextLong used by LongStream Spliterators. If origin is greater than bound, acts as unbounded form of nextLong, else as bounded form. @param origin the least value, unless greater than bound @param bound the upper bound (exclusive), must not equal origin @return a pseudorandom value
[ "The", "form", "of", "nextLong", "used", "by", "LongStream", "Spliterators", ".", "If", "origin", "is", "greater", "than", "bound", "acts", "as", "unbounded", "form", "of", "nextLong", "else", "as", "bounded", "form", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/ThreadLocalRandom.java#L210-L229
rey5137/material
app/src/main/java/com/rey/material/app/Recurring.java
Recurring.getDay
private static int getDay(Calendar cal, int dayOfWeek, int orderNum) { """ Get the day in month of the current month of Calendar. @param cal @param dayOfWeek The day of week. @param orderNum The order number, 0 mean the first, -1 mean the last. @return The day int month """ int day = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, day); int lastWeekday = cal.get(Calendar.DAY_OF_WEEK); int shift = lastWeekday >= dayOfWeek ? (lastWeekday - dayOfWeek) : (lastWeekday + 7 - dayOfWeek); //find last dayOfWeek of this month day -= shift; if(orderNum < 0) return day; cal.set(Calendar.DAY_OF_MONTH, day); int lastOrderNum = (cal.get(Calendar.DAY_OF_MONTH) - 1) / 7; if(orderNum >= lastOrderNum) return day; return day - (lastOrderNum - orderNum) * 7; }
java
private static int getDay(Calendar cal, int dayOfWeek, int orderNum){ int day = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, day); int lastWeekday = cal.get(Calendar.DAY_OF_WEEK); int shift = lastWeekday >= dayOfWeek ? (lastWeekday - dayOfWeek) : (lastWeekday + 7 - dayOfWeek); //find last dayOfWeek of this month day -= shift; if(orderNum < 0) return day; cal.set(Calendar.DAY_OF_MONTH, day); int lastOrderNum = (cal.get(Calendar.DAY_OF_MONTH) - 1) / 7; if(orderNum >= lastOrderNum) return day; return day - (lastOrderNum - orderNum) * 7; }
[ "private", "static", "int", "getDay", "(", "Calendar", "cal", ",", "int", "dayOfWeek", ",", "int", "orderNum", ")", "{", "int", "day", "=", "cal", ".", "getActualMaximum", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "day", ")", ";", "int", "lastWeekday", "=", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_WEEK", ")", ";", "int", "shift", "=", "lastWeekday", ">=", "dayOfWeek", "?", "(", "lastWeekday", "-", "dayOfWeek", ")", ":", "(", "lastWeekday", "+", "7", "-", "dayOfWeek", ")", ";", "//find last dayOfWeek of this month", "day", "-=", "shift", ";", "if", "(", "orderNum", "<", "0", ")", "return", "day", ";", "cal", ".", "set", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "day", ")", ";", "int", "lastOrderNum", "=", "(", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", "-", "1", ")", "/", "7", ";", "if", "(", "orderNum", ">=", "lastOrderNum", ")", "return", "day", ";", "return", "day", "-", "(", "lastOrderNum", "-", "orderNum", ")", "*", "7", ";", "}" ]
Get the day in month of the current month of Calendar. @param cal @param dayOfWeek The day of week. @param orderNum The order number, 0 mean the first, -1 mean the last. @return The day int month
[ "Get", "the", "day", "in", "month", "of", "the", "current", "month", "of", "Calendar", "." ]
train
https://github.com/rey5137/material/blob/1bbcac2686a0023ef7720d3fe455bb116d115af8/app/src/main/java/com/rey/material/app/Recurring.java#L331-L351
groupon/monsoon
impl/src/main/java/com/groupon/lex/metrics/misc/MonitorMonitor.java
MonitorMonitor.transform
@Override public void transform(Context<MutableTimeSeriesCollectionPair> ctx) { """ Emit an alert monitor.down, which is in the OK state. @param ctx Rule evaluation context. """ DateTime now = ctx.getTSData().getCurrentCollection().getTimestamp(); ctx.getTSData().getCurrentCollection().addMetrics(MONITOR_GROUP, get_metrics_(now, ctx)); ctx.getAlertManager().accept(new Alert(now, MONITOR_DOWN_ALERT, () -> "builtin rule", Optional.of(false), Duration.ZERO, "builtin rule: monitor is not running for some time", EMPTY_MAP)); }
java
@Override public void transform(Context<MutableTimeSeriesCollectionPair> ctx) { DateTime now = ctx.getTSData().getCurrentCollection().getTimestamp(); ctx.getTSData().getCurrentCollection().addMetrics(MONITOR_GROUP, get_metrics_(now, ctx)); ctx.getAlertManager().accept(new Alert(now, MONITOR_DOWN_ALERT, () -> "builtin rule", Optional.of(false), Duration.ZERO, "builtin rule: monitor is not running for some time", EMPTY_MAP)); }
[ "@", "Override", "public", "void", "transform", "(", "Context", "<", "MutableTimeSeriesCollectionPair", ">", "ctx", ")", "{", "DateTime", "now", "=", "ctx", ".", "getTSData", "(", ")", ".", "getCurrentCollection", "(", ")", ".", "getTimestamp", "(", ")", ";", "ctx", ".", "getTSData", "(", ")", ".", "getCurrentCollection", "(", ")", ".", "addMetrics", "(", "MONITOR_GROUP", ",", "get_metrics_", "(", "now", ",", "ctx", ")", ")", ";", "ctx", ".", "getAlertManager", "(", ")", ".", "accept", "(", "new", "Alert", "(", "now", ",", "MONITOR_DOWN_ALERT", ",", "(", ")", "->", "\"builtin rule\"", ",", "Optional", ".", "of", "(", "false", ")", ",", "Duration", ".", "ZERO", ",", "\"builtin rule: monitor is not running for some time\"", ",", "EMPTY_MAP", ")", ")", ";", "}" ]
Emit an alert monitor.down, which is in the OK state. @param ctx Rule evaluation context.
[ "Emit", "an", "alert", "monitor", ".", "down", "which", "is", "in", "the", "OK", "state", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/impl/src/main/java/com/groupon/lex/metrics/misc/MonitorMonitor.java#L136-L143
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/remote/ResponseAttachmentInputStreamSupport.java
ResponseAttachmentInputStreamSupport.shutdown
public final synchronized void shutdown() { """ Closes any registered stream entries that have not yet been consumed """ // synchronize on 'this' to avoid races with registerStreams stopped = true; // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor if (cleanupTaskFuture != null) { cleanupTaskFuture.cancel(false); } // Close remaining streams for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) { InputStreamKey key = entry.getKey(); TimedStreamEntry timedStreamEntry = entry.getValue(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it closeStreamEntry(timedStreamEntry, key.requestId, key.index); } } }
java
public final synchronized void shutdown() { // synchronize on 'this' to avoid races with registerStreams stopped = true; // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor if (cleanupTaskFuture != null) { cleanupTaskFuture.cancel(false); } // Close remaining streams for (Map.Entry<InputStreamKey, TimedStreamEntry> entry : streamMap.entrySet()) { InputStreamKey key = entry.getKey(); TimedStreamEntry timedStreamEntry = entry.getValue(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (timedStreamEntry) { // ensure there's no race with a request that got a ref before we removed it closeStreamEntry(timedStreamEntry, key.requestId, key.index); } } }
[ "public", "final", "synchronized", "void", "shutdown", "(", ")", "{", "// synchronize on 'this' to avoid races with registerStreams", "stopped", "=", "true", ";", "// If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor", "if", "(", "cleanupTaskFuture", "!=", "null", ")", "{", "cleanupTaskFuture", ".", "cancel", "(", "false", ")", ";", "}", "// Close remaining streams", "for", "(", "Map", ".", "Entry", "<", "InputStreamKey", ",", "TimedStreamEntry", ">", "entry", ":", "streamMap", ".", "entrySet", "(", ")", ")", "{", "InputStreamKey", "key", "=", "entry", ".", "getKey", "(", ")", ";", "TimedStreamEntry", "timedStreamEntry", "=", "entry", ".", "getValue", "(", ")", ";", "//noinspection SynchronizationOnLocalVariableOrMethodParameter", "synchronized", "(", "timedStreamEntry", ")", "{", "// ensure there's no race with a request that got a ref before we removed it", "closeStreamEntry", "(", "timedStreamEntry", ",", "key", ".", "requestId", ",", "key", ".", "index", ")", ";", "}", "}", "}" ]
Closes any registered stream entries that have not yet been consumed
[ "Closes", "any", "registered", "stream", "entries", "that", "have", "not", "yet", "been", "consumed" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/remote/ResponseAttachmentInputStreamSupport.java#L184-L200
nextreports/nextreports-engine
src/ro/nextreports/engine/querybuilder/sql/dialect/DialectFactory.java
DialectFactory.determineDialect
public static Dialect determineDialect(String databaseName, String databaseMajorVersion) throws DialectException { """ Determine the appropriate Dialect to use given the database product name and major version. @param databaseName The name of the database product (obtained from metadata). @param databaseMajorVersion The major version of the database product (obtained from metadata). @return An appropriate dialect instance. @throws DialectException """ if (databaseName == null) { throw new DialectException("Dialect must be explicitly set"); } String dialectName; // TODO workaround for firebird (databaseName='Firebird 2.0.LI-V2.0.3.12981 Firebird 2.0/tcp (decebal)/P10') if (databaseName.startsWith(FIREBIRD)) { dialectName = FirebirdDialect.class.getName(); } else if (databaseName.startsWith(MSACCESS)) { dialectName = MSAccessDialect.class.getName(); } else { DialectMapper mapper = MAPPERS.get(databaseName); if (mapper == null) { throw new DialectException( "Dialect must be explicitly set for database: " + databaseName ); } dialectName = mapper.getDialectClass(databaseMajorVersion); } return buildDialect(dialectName); }
java
public static Dialect determineDialect(String databaseName, String databaseMajorVersion) throws DialectException { if (databaseName == null) { throw new DialectException("Dialect must be explicitly set"); } String dialectName; // TODO workaround for firebird (databaseName='Firebird 2.0.LI-V2.0.3.12981 Firebird 2.0/tcp (decebal)/P10') if (databaseName.startsWith(FIREBIRD)) { dialectName = FirebirdDialect.class.getName(); } else if (databaseName.startsWith(MSACCESS)) { dialectName = MSAccessDialect.class.getName(); } else { DialectMapper mapper = MAPPERS.get(databaseName); if (mapper == null) { throw new DialectException( "Dialect must be explicitly set for database: " + databaseName ); } dialectName = mapper.getDialectClass(databaseMajorVersion); } return buildDialect(dialectName); }
[ "public", "static", "Dialect", "determineDialect", "(", "String", "databaseName", ",", "String", "databaseMajorVersion", ")", "throws", "DialectException", "{", "if", "(", "databaseName", "==", "null", ")", "{", "throw", "new", "DialectException", "(", "\"Dialect must be explicitly set\"", ")", ";", "}", "String", "dialectName", ";", "// TODO workaround for firebird (databaseName='Firebird 2.0.LI-V2.0.3.12981 Firebird 2.0/tcp (decebal)/P10')", "if", "(", "databaseName", ".", "startsWith", "(", "FIREBIRD", ")", ")", "{", "dialectName", "=", "FirebirdDialect", ".", "class", ".", "getName", "(", ")", ";", "}", "else", "if", "(", "databaseName", ".", "startsWith", "(", "MSACCESS", ")", ")", "{", "dialectName", "=", "MSAccessDialect", ".", "class", ".", "getName", "(", ")", ";", "}", "else", "{", "DialectMapper", "mapper", "=", "MAPPERS", ".", "get", "(", "databaseName", ")", ";", "if", "(", "mapper", "==", "null", ")", "{", "throw", "new", "DialectException", "(", "\"Dialect must be explicitly set for database: \"", "+", "databaseName", ")", ";", "}", "dialectName", "=", "mapper", ".", "getDialectClass", "(", "databaseMajorVersion", ")", ";", "}", "return", "buildDialect", "(", "dialectName", ")", ";", "}" ]
Determine the appropriate Dialect to use given the database product name and major version. @param databaseName The name of the database product (obtained from metadata). @param databaseMajorVersion The major version of the database product (obtained from metadata). @return An appropriate dialect instance. @throws DialectException
[ "Determine", "the", "appropriate", "Dialect", "to", "use", "given", "the", "database", "product", "name", "and", "major", "version", "." ]
train
https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/querybuilder/sql/dialect/DialectFactory.java#L84-L105
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Validator.java
Validator.validateUpperCase
public static <T extends CharSequence> T validateUpperCase(T value, String errorMsg) throws ValidateException { """ 验证字符串是否全部为大写字母 @param <T> 字符串类型 @param value 表单值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常 @since 3.3.0 """ if (false == isUpperCase(value)) { throw new ValidateException(errorMsg); } return value; }
java
public static <T extends CharSequence> T validateUpperCase(T value, String errorMsg) throws ValidateException { if (false == isUpperCase(value)) { throw new ValidateException(errorMsg); } return value; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validateUpperCase", "(", "T", "value", ",", "String", "errorMsg", ")", "throws", "ValidateException", "{", "if", "(", "false", "==", "isUpperCase", "(", "value", ")", ")", "{", "throw", "new", "ValidateException", "(", "errorMsg", ")", ";", "}", "return", "value", ";", "}" ]
验证字符串是否全部为大写字母 @param <T> 字符串类型 @param value 表单值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常 @since 3.3.0
[ "验证字符串是否全部为大写字母" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L486-L491
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/IllegalGuardedBy.java
IllegalGuardedBy.checkGuardedBy
public static void checkGuardedBy(boolean condition, String formatString, Object... formatArgs) { """ Throws an {@link IllegalGuardedBy} exception if the given condition is false. """ if (!condition) { throw new IllegalGuardedBy(String.format(formatString, formatArgs)); } }
java
public static void checkGuardedBy(boolean condition, String formatString, Object... formatArgs) { if (!condition) { throw new IllegalGuardedBy(String.format(formatString, formatArgs)); } }
[ "public", "static", "void", "checkGuardedBy", "(", "boolean", "condition", ",", "String", "formatString", ",", "Object", "...", "formatArgs", ")", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "IllegalGuardedBy", "(", "String", ".", "format", "(", "formatString", ",", "formatArgs", ")", ")", ";", "}", "}" ]
Throws an {@link IllegalGuardedBy} exception if the given condition is false.
[ "Throws", "an", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/IllegalGuardedBy.java#L37-L41
Viascom/groundwork
foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/builder/FoxHttpRequestBuilder.java
FoxHttpRequestBuilder.addRequestHeader
public FoxHttpRequestBuilder addRequestHeader(String name, String value) { """ Add a new header entry @param name name of the header entry @param value value of the header entry @return FoxHttpRequestBuilder (this) """ foxHttpRequest.getRequestHeader().addHeader(name, value); return this; }
java
public FoxHttpRequestBuilder addRequestHeader(String name, String value) { foxHttpRequest.getRequestHeader().addHeader(name, value); return this; }
[ "public", "FoxHttpRequestBuilder", "addRequestHeader", "(", "String", "name", ",", "String", "value", ")", "{", "foxHttpRequest", ".", "getRequestHeader", "(", ")", ".", "addHeader", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Add a new header entry @param name name of the header entry @param value value of the header entry @return FoxHttpRequestBuilder (this)
[ "Add", "a", "new", "header", "entry" ]
train
https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/builder/FoxHttpRequestBuilder.java#L192-L195
eobermuhlner/big-math
ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java
BigDecimalMath.log10
public static BigDecimal log10(BigDecimal x, MathContext mathContext) { """ Calculates the logarithm of {@link BigDecimal} x to the base 10. @param x the {@link BigDecimal} to calculate the logarithm base 10 for @param mathContext the {@link MathContext} used for the result @return the calculated natural logarithm {@link BigDecimal} to the base 10 with the precision specified in the <code>mathContext</code> @throws ArithmeticException if x &lt;= 0 @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision """ checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 2, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTen(mc), mc); return round(result, mathContext); }
java
public static BigDecimal log10(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 2, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTen(mc), mc); return round(result, mathContext); }
[ "public", "static", "BigDecimal", "log10", "(", "BigDecimal", "x", ",", "MathContext", "mathContext", ")", "{", "checkMathContext", "(", "mathContext", ")", ";", "MathContext", "mc", "=", "new", "MathContext", "(", "mathContext", ".", "getPrecision", "(", ")", "+", "2", ",", "mathContext", ".", "getRoundingMode", "(", ")", ")", ";", "BigDecimal", "result", "=", "log", "(", "x", ",", "mc", ")", ".", "divide", "(", "logTen", "(", "mc", ")", ",", "mc", ")", ";", "return", "round", "(", "result", ",", "mathContext", ")", ";", "}" ]
Calculates the logarithm of {@link BigDecimal} x to the base 10. @param x the {@link BigDecimal} to calculate the logarithm base 10 for @param mathContext the {@link MathContext} used for the result @return the calculated natural logarithm {@link BigDecimal} to the base 10 with the precision specified in the <code>mathContext</code> @throws ArithmeticException if x &lt;= 0 @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
[ "Calculates", "the", "logarithm", "of", "{", "@link", "BigDecimal", "}", "x", "to", "the", "base", "10", "." ]
train
https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java#L936-L942
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java
ImageVectorizer.shutDown
public void shutDown() { """ Shuts the vectorization executor down, waiting for up to 10 seconds for the remaining tasks to complete. See http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html """ vectorizationExecutor.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!vectorizationExecutor.awaitTermination(10, TimeUnit.SECONDS)) { vectorizationExecutor.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!vectorizationExecutor.awaitTermination(10, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted vectorizationExecutor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
java
public void shutDown() { vectorizationExecutor.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!vectorizationExecutor.awaitTermination(10, TimeUnit.SECONDS)) { vectorizationExecutor.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!vectorizationExecutor.awaitTermination(10, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted vectorizationExecutor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
[ "public", "void", "shutDown", "(", ")", "{", "vectorizationExecutor", ".", "shutdown", "(", ")", ";", "// Disable new tasks from being submitted\r", "try", "{", "// Wait a while for existing tasks to terminate\r", "if", "(", "!", "vectorizationExecutor", ".", "awaitTermination", "(", "10", ",", "TimeUnit", ".", "SECONDS", ")", ")", "{", "vectorizationExecutor", ".", "shutdownNow", "(", ")", ";", "// Cancel currently executing tasks\r", "// Wait a while for tasks to respond to being cancelled\r", "if", "(", "!", "vectorizationExecutor", ".", "awaitTermination", "(", "10", ",", "TimeUnit", ".", "SECONDS", ")", ")", "System", ".", "err", ".", "println", "(", "\"Pool did not terminate\"", ")", ";", "}", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "// (Re-)Cancel if current thread also interrupted\r", "vectorizationExecutor", ".", "shutdownNow", "(", ")", ";", "// Preserve interrupt status\r", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}" ]
Shuts the vectorization executor down, waiting for up to 10 seconds for the remaining tasks to complete. See http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
[ "Shuts", "the", "vectorization", "executor", "down", "waiting", "for", "up", "to", "10", "seconds", "for", "the", "remaining", "tasks", "to", "complete", ".", "See", "http", ":", "//", "docs", ".", "oracle", ".", "com", "/", "javase", "/", "7", "/", "docs", "/", "api", "/", "java", "/", "util", "/", "concurrent", "/", "ExecutorService", ".", "html" ]
train
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/vectorization/ImageVectorizer.java#L222-L238
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java
PersonGroupPersonsImpl.updateWithServiceResponseAsync
public Observable<ServiceResponse<Void>> updateWithServiceResponseAsync(String personGroupId, UUID personId, UpdatePersonGroupPersonsOptionalParameter updateOptionalParameter) { """ Update name or userData of a person. @param personGroupId Id referencing a particular person group. @param personId Id referencing a particular person. @param updateOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } if (personGroupId == null) { throw new IllegalArgumentException("Parameter personGroupId is required and cannot be null."); } if (personId == null) { throw new IllegalArgumentException("Parameter personId is required and cannot be null."); } final String name = updateOptionalParameter != null ? updateOptionalParameter.name() : null; final String userData = updateOptionalParameter != null ? updateOptionalParameter.userData() : null; return updateWithServiceResponseAsync(personGroupId, personId, name, userData); }
java
public Observable<ServiceResponse<Void>> updateWithServiceResponseAsync(String personGroupId, UUID personId, UpdatePersonGroupPersonsOptionalParameter updateOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } if (personGroupId == null) { throw new IllegalArgumentException("Parameter personGroupId is required and cannot be null."); } if (personId == null) { throw new IllegalArgumentException("Parameter personId is required and cannot be null."); } final String name = updateOptionalParameter != null ? updateOptionalParameter.name() : null; final String userData = updateOptionalParameter != null ? updateOptionalParameter.userData() : null; return updateWithServiceResponseAsync(personGroupId, personId, name, userData); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Void", ">", ">", "updateWithServiceResponseAsync", "(", "String", "personGroupId", ",", "UUID", "personId", ",", "UpdatePersonGroupPersonsOptionalParameter", "updateOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "azureRegion", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.azureRegion() is required and cannot be null.\"", ")", ";", "}", "if", "(", "personGroupId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter personGroupId is required and cannot be null.\"", ")", ";", "}", "if", "(", "personId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter personId is required and cannot be null.\"", ")", ";", "}", "final", "String", "name", "=", "updateOptionalParameter", "!=", "null", "?", "updateOptionalParameter", ".", "name", "(", ")", ":", "null", ";", "final", "String", "userData", "=", "updateOptionalParameter", "!=", "null", "?", "updateOptionalParameter", ".", "userData", "(", ")", ":", "null", ";", "return", "updateWithServiceResponseAsync", "(", "personGroupId", ",", "personId", ",", "name", ",", "userData", ")", ";", "}" ]
Update name or userData of a person. @param personGroupId Id referencing a particular person group. @param personId Id referencing a particular person. @param updateOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Update", "name", "or", "userData", "of", "a", "person", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java#L665-L679
alkacon/opencms-core
src/org/opencms/module/CmsModuleXmlHandler.java
CmsModuleXmlHandler.addParameter
public void addParameter(String key, String value) { """ Adds a module parameter to the module configuration.<p> @param key the parameter key @param value the parameter value """ if (CmsStringUtil.isNotEmpty(key)) { key = key.trim(); } if (CmsStringUtil.isNotEmpty(value)) { value = value.trim(); } m_parameters.put(key, value); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_MOD_PARAM_KEY_2, key, value)); } }
java
public void addParameter(String key, String value) { if (CmsStringUtil.isNotEmpty(key)) { key = key.trim(); } if (CmsStringUtil.isNotEmpty(value)) { value = value.trim(); } m_parameters.put(key, value); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_MOD_PARAM_KEY_2, key, value)); } }
[ "public", "void", "addParameter", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "CmsStringUtil", ".", "isNotEmpty", "(", "key", ")", ")", "{", "key", "=", "key", ".", "trim", "(", ")", ";", "}", "if", "(", "CmsStringUtil", ".", "isNotEmpty", "(", "value", ")", ")", "{", "value", "=", "value", ".", "trim", "(", ")", ";", "}", "m_parameters", ".", "put", "(", "key", ",", "value", ")", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_ADD_MOD_PARAM_KEY_2", ",", "key", ",", "value", ")", ")", ";", "}", "}" ]
Adds a module parameter to the module configuration.<p> @param key the parameter key @param value the parameter value
[ "Adds", "a", "module", "parameter", "to", "the", "module", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleXmlHandler.java#L611-L623
ujmp/universal-java-matrix-package
ujmp-core/src/main/java/org/ujmp/core/io/ImportMatrixM.java
ImportMatrixM.fromString
public static Matrix fromString(String string, Object... parameters) { """ Creates a DefaultDenseStringMatrix2D from a given String. The string contains the rows of the matrix separated by semicolons or new lines. The columns of the matrix are separated by spaces or commas. All types of brackets are ignored. <p> Examples: "[1 2 3; 4 5 6]" or "(test1,test2);(test3,test4)" @param string the string to parse @return a StringMatrix with the desired values """ string = string.replaceAll(StringUtil.BRACKETS, ""); String[] rows = string.split(StringUtil.SEMICOLONORNEWLINE); String[] cols = rows[0].split(StringUtil.COLONORSPACES); Object[][] values = new String[rows.length][cols.length]; for (int r = 0; r < rows.length; r++) { cols = rows[r].split(StringUtil.COLONORSPACES); for (int c = 0; c < cols.length; c++) { values[r][c] = cols[c]; } } return Matrix.Factory.linkToArray(values); }
java
public static Matrix fromString(String string, Object... parameters) { string = string.replaceAll(StringUtil.BRACKETS, ""); String[] rows = string.split(StringUtil.SEMICOLONORNEWLINE); String[] cols = rows[0].split(StringUtil.COLONORSPACES); Object[][] values = new String[rows.length][cols.length]; for (int r = 0; r < rows.length; r++) { cols = rows[r].split(StringUtil.COLONORSPACES); for (int c = 0; c < cols.length; c++) { values[r][c] = cols[c]; } } return Matrix.Factory.linkToArray(values); }
[ "public", "static", "Matrix", "fromString", "(", "String", "string", ",", "Object", "...", "parameters", ")", "{", "string", "=", "string", ".", "replaceAll", "(", "StringUtil", ".", "BRACKETS", ",", "\"\"", ")", ";", "String", "[", "]", "rows", "=", "string", ".", "split", "(", "StringUtil", ".", "SEMICOLONORNEWLINE", ")", ";", "String", "[", "]", "cols", "=", "rows", "[", "0", "]", ".", "split", "(", "StringUtil", ".", "COLONORSPACES", ")", ";", "Object", "[", "]", "[", "]", "values", "=", "new", "String", "[", "rows", ".", "length", "]", "[", "cols", ".", "length", "]", ";", "for", "(", "int", "r", "=", "0", ";", "r", "<", "rows", ".", "length", ";", "r", "++", ")", "{", "cols", "=", "rows", "[", "r", "]", ".", "split", "(", "StringUtil", ".", "COLONORSPACES", ")", ";", "for", "(", "int", "c", "=", "0", ";", "c", "<", "cols", ".", "length", ";", "c", "++", ")", "{", "values", "[", "r", "]", "[", "c", "]", "=", "cols", "[", "c", "]", ";", "}", "}", "return", "Matrix", ".", "Factory", ".", "linkToArray", "(", "values", ")", ";", "}" ]
Creates a DefaultDenseStringMatrix2D from a given String. The string contains the rows of the matrix separated by semicolons or new lines. The columns of the matrix are separated by spaces or commas. All types of brackets are ignored. <p> Examples: "[1 2 3; 4 5 6]" or "(test1,test2);(test3,test4)" @param string the string to parse @return a StringMatrix with the desired values
[ "Creates", "a", "DefaultDenseStringMatrix2D", "from", "a", "given", "String", ".", "The", "string", "contains", "the", "rows", "of", "the", "matrix", "separated", "by", "semicolons", "or", "new", "lines", ".", "The", "columns", "of", "the", "matrix", "are", "separated", "by", "spaces", "or", "commas", ".", "All", "types", "of", "brackets", "are", "ignored", ".", "<p", ">", "Examples", ":", "[", "1", "2", "3", ";", "4", "5", "6", "]", "or", "(", "test1", "test2", ")", ";", "(", "test3", "test4", ")" ]
train
https://github.com/ujmp/universal-java-matrix-package/blob/b7e1d293adeadaf35d208ffe8884028d6c06b63b/ujmp-core/src/main/java/org/ujmp/core/io/ImportMatrixM.java#L52-L64
OpenLiberty/open-liberty
dev/com.ibm.websphere.javaee.el.3.0/src/javax/el/Util.java
Util.isCoercibleFrom
private static boolean isCoercibleFrom(Object src, Class<?> target) { """ /* This method duplicates code in org.apache.el.util.ReflectionUtil. When making changes keep the code in sync. """ // TODO: This isn't pretty but it works. Significant refactoring would // be required to avoid the exception. try { getExpressionFactory().coerceToType(src, target); } catch (ELException e) { return false; } return true; }
java
private static boolean isCoercibleFrom(Object src, Class<?> target) { // TODO: This isn't pretty but it works. Significant refactoring would // be required to avoid the exception. try { getExpressionFactory().coerceToType(src, target); } catch (ELException e) { return false; } return true; }
[ "private", "static", "boolean", "isCoercibleFrom", "(", "Object", "src", ",", "Class", "<", "?", ">", "target", ")", "{", "// TODO: This isn't pretty but it works. Significant refactoring would", "// be required to avoid the exception.", "try", "{", "getExpressionFactory", "(", ")", ".", "coerceToType", "(", "src", ",", "target", ")", ";", "}", "catch", "(", "ELException", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
/* This method duplicates code in org.apache.el.util.ReflectionUtil. When making changes keep the code in sync.
[ "/", "*", "This", "method", "duplicates", "code", "in", "org", ".", "apache", ".", "el", ".", "util", ".", "ReflectionUtil", ".", "When", "making", "changes", "keep", "the", "code", "in", "sync", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.javaee.el.3.0/src/javax/el/Util.java#L502-L511
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/service/persistence/CPAttachmentFileEntryUtil.java
CPAttachmentFileEntryUtil.removeByUUID_G
public static CPAttachmentFileEntry removeByUUID_G(String uuid, long groupId) throws com.liferay.commerce.product.exception.NoSuchCPAttachmentFileEntryException { """ Removes the cp attachment file entry where uuid = &#63; and groupId = &#63; from the database. @param uuid the uuid @param groupId the group ID @return the cp attachment file entry that was removed """ return getPersistence().removeByUUID_G(uuid, groupId); }
java
public static CPAttachmentFileEntry removeByUUID_G(String uuid, long groupId) throws com.liferay.commerce.product.exception.NoSuchCPAttachmentFileEntryException { return getPersistence().removeByUUID_G(uuid, groupId); }
[ "public", "static", "CPAttachmentFileEntry", "removeByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "com", ".", "liferay", ".", "commerce", ".", "product", ".", "exception", ".", "NoSuchCPAttachmentFileEntryException", "{", "return", "getPersistence", "(", ")", ".", "removeByUUID_G", "(", "uuid", ",", "groupId", ")", ";", "}" ]
Removes the cp attachment file entry where uuid = &#63; and groupId = &#63; from the database. @param uuid the uuid @param groupId the group ID @return the cp attachment file entry that was removed
[ "Removes", "the", "cp", "attachment", "file", "entry", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/service/persistence/CPAttachmentFileEntryUtil.java#L320-L323
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/impl/UserInputInlineMenuButton.java
UserInputInlineMenuButton.handlePress
@Override public void handlePress(CallbackQuery query) { """ Initiates a conversation with the chat awaiting text input On input executes callback @param query unused @see Conversation @see TextPrompt """ executeCallback(); if (textCallback != null && inputGiven) { inputGiven = false; Conversation.builder(query.getBotInstance()) .forWhom(owner.getBaseMessage().getChat()) .silent(true) .prompts().last(new TextPrompt() { @Override public boolean process(ConversationContext context, TextContent input) { textCallback.accept(UserInputInlineMenuButton.this, input.getContent()); inputGiven = true; return false; } @Override public SendableMessage promptMessage(ConversationContext context) { return null; } }).build().begin(); } }
java
@Override public void handlePress(CallbackQuery query) { executeCallback(); if (textCallback != null && inputGiven) { inputGiven = false; Conversation.builder(query.getBotInstance()) .forWhom(owner.getBaseMessage().getChat()) .silent(true) .prompts().last(new TextPrompt() { @Override public boolean process(ConversationContext context, TextContent input) { textCallback.accept(UserInputInlineMenuButton.this, input.getContent()); inputGiven = true; return false; } @Override public SendableMessage promptMessage(ConversationContext context) { return null; } }).build().begin(); } }
[ "@", "Override", "public", "void", "handlePress", "(", "CallbackQuery", "query", ")", "{", "executeCallback", "(", ")", ";", "if", "(", "textCallback", "!=", "null", "&&", "inputGiven", ")", "{", "inputGiven", "=", "false", ";", "Conversation", ".", "builder", "(", "query", ".", "getBotInstance", "(", ")", ")", ".", "forWhom", "(", "owner", ".", "getBaseMessage", "(", ")", ".", "getChat", "(", ")", ")", ".", "silent", "(", "true", ")", ".", "prompts", "(", ")", ".", "last", "(", "new", "TextPrompt", "(", ")", "{", "@", "Override", "public", "boolean", "process", "(", "ConversationContext", "context", ",", "TextContent", "input", ")", "{", "textCallback", ".", "accept", "(", "UserInputInlineMenuButton", ".", "this", ",", "input", ".", "getContent", "(", ")", ")", ";", "inputGiven", "=", "true", ";", "return", "false", ";", "}", "@", "Override", "public", "SendableMessage", "promptMessage", "(", "ConversationContext", "context", ")", "{", "return", "null", ";", "}", "}", ")", ".", "build", "(", ")", ".", "begin", "(", ")", ";", "}", "}" ]
Initiates a conversation with the chat awaiting text input On input executes callback @param query unused @see Conversation @see TextPrompt
[ "Initiates", "a", "conversation", "with", "the", "chat", "awaiting", "text", "input", "On", "input", "executes", "callback" ]
train
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/impl/UserInputInlineMenuButton.java#L70-L94
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java
ChangeRequest.applyTo
public ChangeRequest applyTo(String zoneName, Dns.ChangeRequestOption... options) { """ Applies this change request to the zone identified by {@code zoneName}. @throws DnsException upon failure or if zone is not found """ return dns.applyChangeRequest(zoneName, this, options); }
java
public ChangeRequest applyTo(String zoneName, Dns.ChangeRequestOption... options) { return dns.applyChangeRequest(zoneName, this, options); }
[ "public", "ChangeRequest", "applyTo", "(", "String", "zoneName", ",", "Dns", ".", "ChangeRequestOption", "...", "options", ")", "{", "return", "dns", ".", "applyChangeRequest", "(", "zoneName", ",", "this", ",", "options", ")", ";", "}" ]
Applies this change request to the zone identified by {@code zoneName}. @throws DnsException upon failure or if zone is not found
[ "Applies", "this", "change", "request", "to", "the", "zone", "identified", "by", "{", "@code", "zoneName", "}", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java#L148-L150
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java
PoolsImpl.enableAutoScale
public void enableAutoScale(String poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions) { """ Enables automatic scaling for a pool. You cannot enable automatic scaling on a pool if a resize operation is in progress on the pool. If automatic scaling of the pool is currently disabled, you must specify a valid autoscale formula as part of the request. If automatic scaling of the pool is already enabled, you may specify a new autoscale formula and/or a new evaluation interval. You cannot call this API for the same pool more than once every 30 seconds. @param poolId The ID of the pool on which to enable automatic scaling. @param poolEnableAutoScaleParameter The parameters for the request. @param poolEnableAutoScaleOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ enableAutoScaleWithServiceResponseAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions).toBlocking().single().body(); }
java
public void enableAutoScale(String poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions) { enableAutoScaleWithServiceResponseAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions).toBlocking().single().body(); }
[ "public", "void", "enableAutoScale", "(", "String", "poolId", ",", "PoolEnableAutoScaleParameter", "poolEnableAutoScaleParameter", ",", "PoolEnableAutoScaleOptions", "poolEnableAutoScaleOptions", ")", "{", "enableAutoScaleWithServiceResponseAsync", "(", "poolId", ",", "poolEnableAutoScaleParameter", ",", "poolEnableAutoScaleOptions", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Enables automatic scaling for a pool. You cannot enable automatic scaling on a pool if a resize operation is in progress on the pool. If automatic scaling of the pool is currently disabled, you must specify a valid autoscale formula as part of the request. If automatic scaling of the pool is already enabled, you may specify a new autoscale formula and/or a new evaluation interval. You cannot call this API for the same pool more than once every 30 seconds. @param poolId The ID of the pool on which to enable automatic scaling. @param poolEnableAutoScaleParameter The parameters for the request. @param poolEnableAutoScaleOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Enables", "automatic", "scaling", "for", "a", "pool", ".", "You", "cannot", "enable", "automatic", "scaling", "on", "a", "pool", "if", "a", "resize", "operation", "is", "in", "progress", "on", "the", "pool", ".", "If", "automatic", "scaling", "of", "the", "pool", "is", "currently", "disabled", "you", "must", "specify", "a", "valid", "autoscale", "formula", "as", "part", "of", "the", "request", ".", "If", "automatic", "scaling", "of", "the", "pool", "is", "already", "enabled", "you", "may", "specify", "a", "new", "autoscale", "formula", "and", "/", "or", "a", "new", "evaluation", "interval", ".", "You", "cannot", "call", "this", "API", "for", "the", "same", "pool", "more", "than", "once", "every", "30", "seconds", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L2369-L2371
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.getCertificateContactsAsync
public ServiceFuture<Contacts> getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback<Contacts> serviceCallback) { """ Lists the certificate contacts for a specified key vault. The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. This operation requires the certificates/managecontacts permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object """ return ServiceFuture.fromResponse(getCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); }
java
public ServiceFuture<Contacts> getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback<Contacts> serviceCallback) { return ServiceFuture.fromResponse(getCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); }
[ "public", "ServiceFuture", "<", "Contacts", ">", "getCertificateContactsAsync", "(", "String", "vaultBaseUrl", ",", "final", "ServiceCallback", "<", "Contacts", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "fromResponse", "(", "getCertificateContactsWithServiceResponseAsync", "(", "vaultBaseUrl", ")", ",", "serviceCallback", ")", ";", "}" ]
Lists the certificate contacts for a specified key vault. The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. This operation requires the certificates/managecontacts permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "the", "certificate", "contacts", "for", "a", "specified", "key", "vault", ".", "The", "GetCertificateContacts", "operation", "returns", "the", "set", "of", "certificate", "contact", "resources", "in", "the", "specified", "key", "vault", ".", "This", "operation", "requires", "the", "certificates", "/", "managecontacts", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5514-L5516
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/AvroFlattener.java
AvroFlattener.flattenUnion
private Schema flattenUnion(Schema schema, boolean shouldPopulateLineage, boolean flattenComplexTypes) { """ * Flatten Union Schema @param schema Union Schema to flatten @param shouldPopulateLineage If lineage information should be tagged in the field, this is true when we are un-nesting fields @param flattenComplexTypes Flatten complex types recursively other than Record and Option @return Flattened Union Schema """ Preconditions.checkNotNull(schema); Preconditions.checkArgument(Schema.Type.UNION.equals(schema.getType())); Schema flattenedSchema; List<Schema> flattenedUnionMembers = new ArrayList<>(); if (null != schema.getTypes() && schema.getTypes().size() > 0) { for (Schema oldUnionMember : schema.getTypes()) { if (flattenComplexTypes) { // It's member might still recursively contain records flattenedUnionMembers.add(flatten(oldUnionMember, shouldPopulateLineage, flattenComplexTypes)); } else { flattenedUnionMembers.add(oldUnionMember); } } } flattenedSchema = Schema.createUnion(flattenedUnionMembers); return flattenedSchema; }
java
private Schema flattenUnion(Schema schema, boolean shouldPopulateLineage, boolean flattenComplexTypes) { Preconditions.checkNotNull(schema); Preconditions.checkArgument(Schema.Type.UNION.equals(schema.getType())); Schema flattenedSchema; List<Schema> flattenedUnionMembers = new ArrayList<>(); if (null != schema.getTypes() && schema.getTypes().size() > 0) { for (Schema oldUnionMember : schema.getTypes()) { if (flattenComplexTypes) { // It's member might still recursively contain records flattenedUnionMembers.add(flatten(oldUnionMember, shouldPopulateLineage, flattenComplexTypes)); } else { flattenedUnionMembers.add(oldUnionMember); } } } flattenedSchema = Schema.createUnion(flattenedUnionMembers); return flattenedSchema; }
[ "private", "Schema", "flattenUnion", "(", "Schema", "schema", ",", "boolean", "shouldPopulateLineage", ",", "boolean", "flattenComplexTypes", ")", "{", "Preconditions", ".", "checkNotNull", "(", "schema", ")", ";", "Preconditions", ".", "checkArgument", "(", "Schema", ".", "Type", ".", "UNION", ".", "equals", "(", "schema", ".", "getType", "(", ")", ")", ")", ";", "Schema", "flattenedSchema", ";", "List", "<", "Schema", ">", "flattenedUnionMembers", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "null", "!=", "schema", ".", "getTypes", "(", ")", "&&", "schema", ".", "getTypes", "(", ")", ".", "size", "(", ")", ">", "0", ")", "{", "for", "(", "Schema", "oldUnionMember", ":", "schema", ".", "getTypes", "(", ")", ")", "{", "if", "(", "flattenComplexTypes", ")", "{", "// It's member might still recursively contain records", "flattenedUnionMembers", ".", "add", "(", "flatten", "(", "oldUnionMember", ",", "shouldPopulateLineage", ",", "flattenComplexTypes", ")", ")", ";", "}", "else", "{", "flattenedUnionMembers", ".", "add", "(", "oldUnionMember", ")", ";", "}", "}", "}", "flattenedSchema", "=", "Schema", ".", "createUnion", "(", "flattenedUnionMembers", ")", ";", "return", "flattenedSchema", ";", "}" ]
* Flatten Union Schema @param schema Union Schema to flatten @param shouldPopulateLineage If lineage information should be tagged in the field, this is true when we are un-nesting fields @param flattenComplexTypes Flatten complex types recursively other than Record and Option @return Flattened Union Schema
[ "*", "Flatten", "Union", "Schema" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroFlattener.java#L271-L291
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/utils/Assert.java
Assert.parameterNotEmpty
public static void parameterNotEmpty(final String name, final String value) { """ Validates that the value is not empty @param name the parameter name @param value the proposed parameter value """ if (value != null && value.length() == 0) { raiseError(format("Parameter '%s' is expected to NOT be empty.", name)); } }
java
public static void parameterNotEmpty(final String name, final String value) { if (value != null && value.length() == 0) { raiseError(format("Parameter '%s' is expected to NOT be empty.", name)); } }
[ "public", "static", "void", "parameterNotEmpty", "(", "final", "String", "name", ",", "final", "String", "value", ")", "{", "if", "(", "value", "!=", "null", "&&", "value", ".", "length", "(", ")", "==", "0", ")", "{", "raiseError", "(", "format", "(", "\"Parameter '%s' is expected to NOT be empty.\"", ",", "name", ")", ")", ";", "}", "}" ]
Validates that the value is not empty @param name the parameter name @param value the proposed parameter value
[ "Validates", "that", "the", "value", "is", "not", "empty" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/utils/Assert.java#L73-L77
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSConnectionRequestInfoImpl.java
WSConnectionRequestInfoImpl.matchSchema
private final boolean matchSchema(WSConnectionRequestInfoImpl cri) { """ Determine if the schema property matches. It is considered to match if - Both schema values are unspecified. - Both schema values are the same value. - One of the schema values is unspecified and the other CRI requested the default value. @return true if the schema match, otherwise false. """ // At least one of the CRIs should know the default value. String defaultValue = defaultSchema == null ? cri.defaultSchema : defaultSchema; return match(ivSchema, cri.ivSchema) || ivSchema == null && match(defaultValue, cri.ivSchema) || cri.ivSchema == null && match(ivSchema, defaultValue); }
java
private final boolean matchSchema(WSConnectionRequestInfoImpl cri){ // At least one of the CRIs should know the default value. String defaultValue = defaultSchema == null ? cri.defaultSchema : defaultSchema; return match(ivSchema, cri.ivSchema) || ivSchema == null && match(defaultValue, cri.ivSchema) || cri.ivSchema == null && match(ivSchema, defaultValue); }
[ "private", "final", "boolean", "matchSchema", "(", "WSConnectionRequestInfoImpl", "cri", ")", "{", "// At least one of the CRIs should know the default value.", "String", "defaultValue", "=", "defaultSchema", "==", "null", "?", "cri", ".", "defaultSchema", ":", "defaultSchema", ";", "return", "match", "(", "ivSchema", ",", "cri", ".", "ivSchema", ")", "||", "ivSchema", "==", "null", "&&", "match", "(", "defaultValue", ",", "cri", ".", "ivSchema", ")", "||", "cri", ".", "ivSchema", "==", "null", "&&", "match", "(", "ivSchema", ",", "defaultValue", ")", ";", "}" ]
Determine if the schema property matches. It is considered to match if - Both schema values are unspecified. - Both schema values are the same value. - One of the schema values is unspecified and the other CRI requested the default value. @return true if the schema match, otherwise false.
[ "Determine", "if", "the", "schema", "property", "matches", ".", "It", "is", "considered", "to", "match", "if", "-", "Both", "schema", "values", "are", "unspecified", ".", "-", "Both", "schema", "values", "are", "the", "same", "value", ".", "-", "One", "of", "the", "schema", "values", "is", "unspecified", "and", "the", "other", "CRI", "requested", "the", "default", "value", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSConnectionRequestInfoImpl.java#L591-L598
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/values/TimeValueConverter.java
TimeValueConverter.writeValue
@Override public void writeValue(TimeValue value, Resource resource) throws RDFHandlerException { """ Write the auxiliary RDF data for encoding the given value. @param value the value to write @param resource the (subject) URI to use to represent this value in RDF @throws RDFHandlerException """ this.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE, RdfWriter.WB_TIME_VALUE); this.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME, TimeValueConverter.getTimeLiteral(value, this.rdfWriter)); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_PRECISION, value.getPrecision()); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_TIMEZONE, value.getTimezoneOffset()); this.rdfWriter.writeTripleUriObject(resource, RdfWriter.WB_TIME_CALENDAR_MODEL, value.getPreferredCalendarModel()); }
java
@Override public void writeValue(TimeValue value, Resource resource) throws RDFHandlerException { this.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE, RdfWriter.WB_TIME_VALUE); this.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME, TimeValueConverter.getTimeLiteral(value, this.rdfWriter)); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_PRECISION, value.getPrecision()); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_TIMEZONE, value.getTimezoneOffset()); this.rdfWriter.writeTripleUriObject(resource, RdfWriter.WB_TIME_CALENDAR_MODEL, value.getPreferredCalendarModel()); }
[ "@", "Override", "public", "void", "writeValue", "(", "TimeValue", "value", ",", "Resource", "resource", ")", "throws", "RDFHandlerException", "{", "this", ".", "rdfWriter", ".", "writeTripleValueObject", "(", "resource", ",", "RdfWriter", ".", "RDF_TYPE", ",", "RdfWriter", ".", "WB_TIME_VALUE", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleValueObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME", ",", "TimeValueConverter", ".", "getTimeLiteral", "(", "value", ",", "this", ".", "rdfWriter", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleIntegerObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME_PRECISION", ",", "value", ".", "getPrecision", "(", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleIntegerObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME_TIMEZONE", ",", "value", ".", "getTimezoneOffset", "(", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME_CALENDAR_MODEL", ",", "value", ".", "getPreferredCalendarModel", "(", ")", ")", ";", "}" ]
Write the auxiliary RDF data for encoding the given value. @param value the value to write @param resource the (subject) URI to use to represent this value in RDF @throws RDFHandlerException
[ "Write", "the", "auxiliary", "RDF", "data", "for", "encoding", "the", "given", "value", "." ]
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/values/TimeValueConverter.java#L78-L95
apache/groovy
src/main/java/org/codehaus/groovy/antlr/treewalker/SourcePrinter.java
SourcePrinter.visitStringConstructor
public void visitStringConstructor(GroovySourceAST t,int visit) { """ String characters only used by lexer, never visited/created directly """ if (visit == OPENING_VISIT) { stringConstructorCounter = 0; print(t,visit,"\""); } if (visit == SUBSEQUENT_VISIT) { // every other subsequent visit use an escaping $ if (stringConstructorCounter % 2 == 0) { print(t,visit,"$"); } stringConstructorCounter++; } if (visit == CLOSING_VISIT) { print(t,visit,"\""); } }
java
public void visitStringConstructor(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { stringConstructorCounter = 0; print(t,visit,"\""); } if (visit == SUBSEQUENT_VISIT) { // every other subsequent visit use an escaping $ if (stringConstructorCounter % 2 == 0) { print(t,visit,"$"); } stringConstructorCounter++; } if (visit == CLOSING_VISIT) { print(t,visit,"\""); } }
[ "public", "void", "visitStringConstructor", "(", "GroovySourceAST", "t", ",", "int", "visit", ")", "{", "if", "(", "visit", "==", "OPENING_VISIT", ")", "{", "stringConstructorCounter", "=", "0", ";", "print", "(", "t", ",", "visit", ",", "\"\\\"\"", ")", ";", "}", "if", "(", "visit", "==", "SUBSEQUENT_VISIT", ")", "{", "// every other subsequent visit use an escaping $", "if", "(", "stringConstructorCounter", "%", "2", "==", "0", ")", "{", "print", "(", "t", ",", "visit", ",", "\"$\"", ")", ";", "}", "stringConstructorCounter", "++", ";", "}", "if", "(", "visit", "==", "CLOSING_VISIT", ")", "{", "print", "(", "t", ",", "visit", ",", "\"\\\"\"", ")", ";", "}", "}" ]
String characters only used by lexer, never visited/created directly
[ "String", "characters", "only", "used", "by", "lexer", "never", "visited", "/", "created", "directly" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/antlr/treewalker/SourcePrinter.java#L871-L886
wildfly/wildfly-maven-plugin
core/src/main/java/org/wildfly/plugin/core/ServerHelper.java
ServerHelper.waitForStandalone
public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout) throws InterruptedException, RuntimeException, TimeoutException { """ Waits the given amount of time in seconds for a standalone server to start. @param client the client used to communicate with the server @param startupTimeout the time, in seconds, to wait for the server start @throws InterruptedException if interrupted while waiting for the server to start @throws RuntimeException if the process has died @throws TimeoutException if the timeout has been reached and the server is still not started """ waitForStandalone(null, client, startupTimeout); }
java
public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout) throws InterruptedException, RuntimeException, TimeoutException { waitForStandalone(null, client, startupTimeout); }
[ "public", "static", "void", "waitForStandalone", "(", "final", "ModelControllerClient", "client", ",", "final", "long", "startupTimeout", ")", "throws", "InterruptedException", ",", "RuntimeException", ",", "TimeoutException", "{", "waitForStandalone", "(", "null", ",", "client", ",", "startupTimeout", ")", ";", "}" ]
Waits the given amount of time in seconds for a standalone server to start. @param client the client used to communicate with the server @param startupTimeout the time, in seconds, to wait for the server start @throws InterruptedException if interrupted while waiting for the server to start @throws RuntimeException if the process has died @throws TimeoutException if the timeout has been reached and the server is still not started
[ "Waits", "the", "given", "amount", "of", "time", "in", "seconds", "for", "a", "standalone", "server", "to", "start", "." ]
train
https://github.com/wildfly/wildfly-maven-plugin/blob/c0e2d7ee28e511092561801959eae253b2b56def/core/src/main/java/org/wildfly/plugin/core/ServerHelper.java#L287-L290
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java
GoogleMapShapeConverter.toPolygon
public Polygon toPolygon(PolygonOptions polygon, boolean hasZ, boolean hasM) { """ Convert a {@link com.google.android.gms.maps.model.Polygon} to a {@link Polygon} @param polygon polygon options @param hasZ has z flag @param hasM has m flag @return polygon """ return toPolygon(polygon.getPoints(), polygon.getHoles(), hasZ, hasM); }
java
public Polygon toPolygon(PolygonOptions polygon, boolean hasZ, boolean hasM) { return toPolygon(polygon.getPoints(), polygon.getHoles(), hasZ, hasM); }
[ "public", "Polygon", "toPolygon", "(", "PolygonOptions", "polygon", ",", "boolean", "hasZ", ",", "boolean", "hasM", ")", "{", "return", "toPolygon", "(", "polygon", ".", "getPoints", "(", ")", ",", "polygon", ".", "getHoles", "(", ")", ",", "hasZ", ",", "hasM", ")", ";", "}" ]
Convert a {@link com.google.android.gms.maps.model.Polygon} to a {@link Polygon} @param polygon polygon options @param hasZ has z flag @param hasM has m flag @return polygon
[ "Convert", "a", "{", "@link", "com", ".", "google", ".", "android", ".", "gms", ".", "maps", ".", "model", ".", "Polygon", "}", "to", "a", "{", "@link", "Polygon", "}" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java#L635-L637
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
LambdaToMethod.makePrivateSyntheticMethod
private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) { """ Create new synthetic method with given flags, name, type, owner """ return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner); }
java
private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) { return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner); }
[ "private", "MethodSymbol", "makePrivateSyntheticMethod", "(", "long", "flags", ",", "Name", "name", ",", "Type", "type", ",", "Symbol", "owner", ")", "{", "return", "new", "MethodSymbol", "(", "flags", "|", "SYNTHETIC", "|", "PRIVATE", ",", "name", ",", "type", ",", "owner", ")", ";", "}" ]
Create new synthetic method with given flags, name, type, owner
[ "Create", "new", "synthetic", "method", "with", "given", "flags", "name", "type", "owner" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L768-L770
korpling/ANNIS
annis-libgui/src/main/java/annis/libgui/Helper.java
Helper.getAnnisWebResource
public static WebResource getAnnisWebResource(String uri, AnnisUser user) { """ Gets or creates a web resource to the ANNIS service. @param uri The URI where the service can be found @param user The user object or null (should be of type {@link AnnisUser}). @return A reference to the ANNIS service root resource. """ if (user != null) { try { return user.getClient().resource(uri); } catch (LoginDataLostException ex) { log.error( "Could not restore the login-data from session, user will invalidated", ex); setUser(null); UI ui = UI.getCurrent(); if (ui instanceof AnnisBaseUI) { ((AnnisBaseUI) ui).getLoginDataLostBus().post(ex); } } } // use the anonymous client if (anonymousClient.get() == null) { // anonymous client not created yet anonymousClient.set(createRESTClient()); } return anonymousClient.get().resource(uri); }
java
public static WebResource getAnnisWebResource(String uri, AnnisUser user) { if (user != null) { try { return user.getClient().resource(uri); } catch (LoginDataLostException ex) { log.error( "Could not restore the login-data from session, user will invalidated", ex); setUser(null); UI ui = UI.getCurrent(); if (ui instanceof AnnisBaseUI) { ((AnnisBaseUI) ui).getLoginDataLostBus().post(ex); } } } // use the anonymous client if (anonymousClient.get() == null) { // anonymous client not created yet anonymousClient.set(createRESTClient()); } return anonymousClient.get().resource(uri); }
[ "public", "static", "WebResource", "getAnnisWebResource", "(", "String", "uri", ",", "AnnisUser", "user", ")", "{", "if", "(", "user", "!=", "null", ")", "{", "try", "{", "return", "user", ".", "getClient", "(", ")", ".", "resource", "(", "uri", ")", ";", "}", "catch", "(", "LoginDataLostException", "ex", ")", "{", "log", ".", "error", "(", "\"Could not restore the login-data from session, user will invalidated\"", ",", "ex", ")", ";", "setUser", "(", "null", ")", ";", "UI", "ui", "=", "UI", ".", "getCurrent", "(", ")", ";", "if", "(", "ui", "instanceof", "AnnisBaseUI", ")", "{", "(", "(", "AnnisBaseUI", ")", "ui", ")", ".", "getLoginDataLostBus", "(", ")", ".", "post", "(", "ex", ")", ";", "}", "}", "}", "// use the anonymous client", "if", "(", "anonymousClient", ".", "get", "(", ")", "==", "null", ")", "{", "// anonymous client not created yet", "anonymousClient", ".", "set", "(", "createRESTClient", "(", ")", ")", ";", "}", "return", "anonymousClient", ".", "get", "(", ")", ".", "resource", "(", "uri", ")", ";", "}" ]
Gets or creates a web resource to the ANNIS service. @param uri The URI where the service can be found @param user The user object or null (should be of type {@link AnnisUser}). @return A reference to the ANNIS service root resource.
[ "Gets", "or", "creates", "a", "web", "resource", "to", "the", "ANNIS", "service", "." ]
train
https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-libgui/src/main/java/annis/libgui/Helper.java#L239-L270
OpenBEL/openbel-framework
org.openbel.framework.api/src/main/java/org/openbel/framework/api/OrthologizedKam.java
OrthologizedKam.wrapNode
private KamNode wrapNode(KamNode kamNode) { """ Wrap a {@link KamNode} as an {@link OrthologousNode} to allow conversion of the node label by the {@link SpeciesDialect}. @param kamNode {@link KamNode} @return the wrapped kam node, <ol> <li>{@code null} if {@code kamNode} input is {@code null}</li> <li>{@link OrthologousNode} if {@code kamNode} has orthologized</li> <li>the original {@code kamNode} input if it has not orthologized</li> </ol> """ if (kamNode == null) { return null; } TermParameter param = ntp.get(kamNode.getId()); if (param != null) { return new OrthologousNode(kamNode, param); } return kamNode; }
java
private KamNode wrapNode(KamNode kamNode) { if (kamNode == null) { return null; } TermParameter param = ntp.get(kamNode.getId()); if (param != null) { return new OrthologousNode(kamNode, param); } return kamNode; }
[ "private", "KamNode", "wrapNode", "(", "KamNode", "kamNode", ")", "{", "if", "(", "kamNode", "==", "null", ")", "{", "return", "null", ";", "}", "TermParameter", "param", "=", "ntp", ".", "get", "(", "kamNode", ".", "getId", "(", ")", ")", ";", "if", "(", "param", "!=", "null", ")", "{", "return", "new", "OrthologousNode", "(", "kamNode", ",", "param", ")", ";", "}", "return", "kamNode", ";", "}" ]
Wrap a {@link KamNode} as an {@link OrthologousNode} to allow conversion of the node label by the {@link SpeciesDialect}. @param kamNode {@link KamNode} @return the wrapped kam node, <ol> <li>{@code null} if {@code kamNode} input is {@code null}</li> <li>{@link OrthologousNode} if {@code kamNode} has orthologized</li> <li>the original {@code kamNode} input if it has not orthologized</li> </ol>
[ "Wrap", "a", "{", "@link", "KamNode", "}", "as", "an", "{", "@link", "OrthologousNode", "}", "to", "allow", "conversion", "of", "the", "node", "label", "by", "the", "{", "@link", "SpeciesDialect", "}", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.api/src/main/java/org/openbel/framework/api/OrthologizedKam.java#L526-L537
aalmiray/Json-lib
src/main/java/net/sf/json/JSONObject.java
JSONObject.element
public JSONObject element( String key, long value ) { """ Put a key/long pair in the JSONObject. @param key A key string. @param value A long which is the value. @return this. @throws JSONException If the key is null. """ verifyIsNull(); return element( key, new Long( value ) ); }
java
public JSONObject element( String key, long value ) { verifyIsNull(); return element( key, new Long( value ) ); }
[ "public", "JSONObject", "element", "(", "String", "key", ",", "long", "value", ")", "{", "verifyIsNull", "(", ")", ";", "return", "element", "(", "key", ",", "new", "Long", "(", "value", ")", ")", ";", "}" ]
Put a key/long pair in the JSONObject. @param key A key string. @param value A long which is the value. @return this. @throws JSONException If the key is null.
[ "Put", "a", "key", "/", "long", "pair", "in", "the", "JSONObject", "." ]
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONObject.java#L1640-L1643
ow2-chameleon/fuchsia
bases/knx/calimero/src/main/java/tuwien/auto/calimero/tools/NetworkMonitor.java
NetworkMonitor.createMonitor
private void createMonitor(LinkListener l) throws KNXException { """ Creates a new network monitor using the supplied options. <p> @throws KNXException on problems on monitor creation """ final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium"); if (options.containsKey("serial")) { final String p = (String) options.get("serial"); try { m = new KNXNetworkMonitorFT12(Integer.parseInt(p), medium); } catch (final NumberFormatException e) { m = new KNXNetworkMonitorFT12(p, medium); } } else { // create local and remote socket address for monitor link final InetSocketAddress local = createLocalSocket((InetAddress) options .get("localhost"), (Integer) options.get("localport")); final InetSocketAddress host = new InetSocketAddress((InetAddress) options .get("host"), ((Integer) options.get("port")).intValue()); // create the monitor link, based on the KNXnet/IP protocol // specify whether network address translation shall be used, // and tell the physical medium of the KNX network m = new KNXNetworkMonitorIP(local, host, options.containsKey("nat"), medium); } // add the log writer for monitor log events LogManager.getManager().addWriter(m.getName(), w); // on console we want to have all possible information, so enable // decoding of a received raw frame by the monitor link m.setDecodeRawFrames(true); // listen to monitor link events m.addMonitorListener(l); // we always need a link closed notification (even with user supplied listener) m.addMonitorListener(new LinkListener() { public void indication(FrameEvent e) {} public void linkClosed(CloseEvent e) { System.out.println("network monitor exit, " + e.getReason()); synchronized (NetworkMonitor.this) { NetworkMonitor.this.notify(); } } }); }
java
private void createMonitor(LinkListener l) throws KNXException { final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium"); if (options.containsKey("serial")) { final String p = (String) options.get("serial"); try { m = new KNXNetworkMonitorFT12(Integer.parseInt(p), medium); } catch (final NumberFormatException e) { m = new KNXNetworkMonitorFT12(p, medium); } } else { // create local and remote socket address for monitor link final InetSocketAddress local = createLocalSocket((InetAddress) options .get("localhost"), (Integer) options.get("localport")); final InetSocketAddress host = new InetSocketAddress((InetAddress) options .get("host"), ((Integer) options.get("port")).intValue()); // create the monitor link, based on the KNXnet/IP protocol // specify whether network address translation shall be used, // and tell the physical medium of the KNX network m = new KNXNetworkMonitorIP(local, host, options.containsKey("nat"), medium); } // add the log writer for monitor log events LogManager.getManager().addWriter(m.getName(), w); // on console we want to have all possible information, so enable // decoding of a received raw frame by the monitor link m.setDecodeRawFrames(true); // listen to monitor link events m.addMonitorListener(l); // we always need a link closed notification (even with user supplied listener) m.addMonitorListener(new LinkListener() { public void indication(FrameEvent e) {} public void linkClosed(CloseEvent e) { System.out.println("network monitor exit, " + e.getReason()); synchronized (NetworkMonitor.this) { NetworkMonitor.this.notify(); } } }); }
[ "private", "void", "createMonitor", "(", "LinkListener", "l", ")", "throws", "KNXException", "{", "final", "KNXMediumSettings", "medium", "=", "(", "KNXMediumSettings", ")", "options", ".", "get", "(", "\"medium\"", ")", ";", "if", "(", "options", ".", "containsKey", "(", "\"serial\"", ")", ")", "{", "final", "String", "p", "=", "(", "String", ")", "options", ".", "get", "(", "\"serial\"", ")", ";", "try", "{", "m", "=", "new", "KNXNetworkMonitorFT12", "(", "Integer", ".", "parseInt", "(", "p", ")", ",", "medium", ")", ";", "}", "catch", "(", "final", "NumberFormatException", "e", ")", "{", "m", "=", "new", "KNXNetworkMonitorFT12", "(", "p", ",", "medium", ")", ";", "}", "}", "else", "{", "// create local and remote socket address for monitor link\r", "final", "InetSocketAddress", "local", "=", "createLocalSocket", "(", "(", "InetAddress", ")", "options", ".", "get", "(", "\"localhost\"", ")", ",", "(", "Integer", ")", "options", ".", "get", "(", "\"localport\"", ")", ")", ";", "final", "InetSocketAddress", "host", "=", "new", "InetSocketAddress", "(", "(", "InetAddress", ")", "options", ".", "get", "(", "\"host\"", ")", ",", "(", "(", "Integer", ")", "options", ".", "get", "(", "\"port\"", ")", ")", ".", "intValue", "(", ")", ")", ";", "// create the monitor link, based on the KNXnet/IP protocol\r", "// specify whether network address translation shall be used,\r", "// and tell the physical medium of the KNX network\r", "m", "=", "new", "KNXNetworkMonitorIP", "(", "local", ",", "host", ",", "options", ".", "containsKey", "(", "\"nat\"", ")", ",", "medium", ")", ";", "}", "// add the log writer for monitor log events\r", "LogManager", ".", "getManager", "(", ")", ".", "addWriter", "(", "m", ".", "getName", "(", ")", ",", "w", ")", ";", "// on console we want to have all possible information, so enable\r", "// decoding of a received raw frame by the monitor link\r", "m", ".", "setDecodeRawFrames", "(", "true", ")", ";", "// listen to monitor link events\r", "m", ".", "addMonitorListener", "(", "l", ")", ";", "// we always need a link closed notification (even with user supplied listener)\r", "m", ".", "addMonitorListener", "(", "new", "LinkListener", "(", ")", "{", "public", "void", "indication", "(", "FrameEvent", "e", ")", "{", "}", "public", "void", "linkClosed", "(", "CloseEvent", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"network monitor exit, \"", "+", "e", ".", "getReason", "(", ")", ")", ";", "synchronized", "(", "NetworkMonitor", ".", "this", ")", "{", "NetworkMonitor", ".", "this", ".", "notify", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Creates a new network monitor using the supplied options. <p> @throws KNXException on problems on monitor creation
[ "Creates", "a", "new", "network", "monitor", "using", "the", "supplied", "options", ".", "<p", ">" ]
train
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/tools/NetworkMonitor.java#L247-L290
couchbase/java-dcp-client
src/main/java/com/couchbase/client/dcp/config/DcpControl.java
DcpControl.put
public DcpControl put(final Names name, final String value) { """ Store/Override a control parameter. @param name the name of the control parameter. @param value the stringified version what it should be set to. @return the {@link DcpControl} instance for chainability. """ // Provide a default NOOP interval because the client needs // to know the interval in order to detect dead connections. if (name == Names.ENABLE_NOOP && get(Names.SET_NOOP_INTERVAL) == null) { put(Names.SET_NOOP_INTERVAL, Integer.toString(DEFAULT_NOOP_INTERVAL_SECONDS)); } values.put(name.value(), value); return this; }
java
public DcpControl put(final Names name, final String value) { // Provide a default NOOP interval because the client needs // to know the interval in order to detect dead connections. if (name == Names.ENABLE_NOOP && get(Names.SET_NOOP_INTERVAL) == null) { put(Names.SET_NOOP_INTERVAL, Integer.toString(DEFAULT_NOOP_INTERVAL_SECONDS)); } values.put(name.value(), value); return this; }
[ "public", "DcpControl", "put", "(", "final", "Names", "name", ",", "final", "String", "value", ")", "{", "// Provide a default NOOP interval because the client needs", "// to know the interval in order to detect dead connections.", "if", "(", "name", "==", "Names", ".", "ENABLE_NOOP", "&&", "get", "(", "Names", ".", "SET_NOOP_INTERVAL", ")", "==", "null", ")", "{", "put", "(", "Names", ".", "SET_NOOP_INTERVAL", ",", "Integer", ".", "toString", "(", "DEFAULT_NOOP_INTERVAL_SECONDS", ")", ")", ";", "}", "values", ".", "put", "(", "name", ".", "value", "(", ")", ",", "value", ")", ";", "return", "this", ";", "}" ]
Store/Override a control parameter. @param name the name of the control parameter. @param value the stringified version what it should be set to. @return the {@link DcpControl} instance for chainability.
[ "Store", "/", "Override", "a", "control", "parameter", "." ]
train
https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/config/DcpControl.java#L81-L90
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.deleteImageRegions
public void deleteImageRegions(UUID projectId, List<String> regionIds) { """ Delete a set of image regions. @param projectId The project id @param regionIds Regions to delete. Limited to 64 @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 """ deleteImageRegionsWithServiceResponseAsync(projectId, regionIds).toBlocking().single().body(); }
java
public void deleteImageRegions(UUID projectId, List<String> regionIds) { deleteImageRegionsWithServiceResponseAsync(projectId, regionIds).toBlocking().single().body(); }
[ "public", "void", "deleteImageRegions", "(", "UUID", "projectId", ",", "List", "<", "String", ">", "regionIds", ")", "{", "deleteImageRegionsWithServiceResponseAsync", "(", "projectId", ",", "regionIds", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Delete a set of image regions. @param projectId The project id @param regionIds Regions to delete. Limited to 64 @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
[ "Delete", "a", "set", "of", "image", "regions", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L3257-L3259
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java
SecureDfuImpl.writeOpCode
private void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value) throws DeviceDisconnectedException, DfuException, UploadAbortedException { """ Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or the device gets disconnected. If connection state will change, or an error will occur, an exception will be thrown. @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT. @param value the value to write to the characteristic. @throws DeviceDisconnectedException @throws DfuException @throws UploadAbortedException """ writeOpCode(characteristic, value, false); }
java
private void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value) throws DeviceDisconnectedException, DfuException, UploadAbortedException { writeOpCode(characteristic, value, false); }
[ "private", "void", "writeOpCode", "(", "@", "NonNull", "final", "BluetoothGattCharacteristic", "characteristic", ",", "@", "NonNull", "final", "byte", "[", "]", "value", ")", "throws", "DeviceDisconnectedException", ",", "DfuException", ",", "UploadAbortedException", "{", "writeOpCode", "(", "characteristic", ",", "value", ",", "false", ")", ";", "}" ]
Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or the device gets disconnected. If connection state will change, or an error will occur, an exception will be thrown. @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT. @param value the value to write to the characteristic. @throws DeviceDisconnectedException @throws DfuException @throws UploadAbortedException
[ "Writes", "the", "operation", "code", "to", "the", "characteristic", ".", "This", "method", "is", "SYNCHRONOUS", "and", "wait", "until", "the", "{", "@link", "android", ".", "bluetooth", ".", "BluetoothGattCallback#onCharacteristicWrite", "(", "android", ".", "bluetooth", ".", "BluetoothGatt", "android", ".", "bluetooth", ".", "BluetoothGattCharacteristic", "int", ")", "}", "will", "be", "called", "or", "the", "device", "gets", "disconnected", ".", "If", "connection", "state", "will", "change", "or", "an", "error", "will", "occur", "an", "exception", "will", "be", "thrown", "." ]
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L791-L794
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.isThreadSafeType
public Violation isThreadSafeType( boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) { """ Returns an {@link Violation} explaining whether the type is threadsafe. @param allowContainerTypeParameters true when checking the instantiation of an {@code typeParameterAnnotation}-annotated type parameter; indicates that {@code containerTypeParameters} should be ignored @param containerTypeParameters type parameters in enclosing elements' containerOf specifications @param type to check for thread-safety """ return type.accept( new ThreadSafeTypeVisitor(allowContainerTypeParameters, containerTypeParameters), null); }
java
public Violation isThreadSafeType( boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) { return type.accept( new ThreadSafeTypeVisitor(allowContainerTypeParameters, containerTypeParameters), null); }
[ "public", "Violation", "isThreadSafeType", "(", "boolean", "allowContainerTypeParameters", ",", "Set", "<", "String", ">", "containerTypeParameters", ",", "Type", "type", ")", "{", "return", "type", ".", "accept", "(", "new", "ThreadSafeTypeVisitor", "(", "allowContainerTypeParameters", ",", "containerTypeParameters", ")", ",", "null", ")", ";", "}" ]
Returns an {@link Violation} explaining whether the type is threadsafe. @param allowContainerTypeParameters true when checking the instantiation of an {@code typeParameterAnnotation}-annotated type parameter; indicates that {@code containerTypeParameters} should be ignored @param containerTypeParameters type parameters in enclosing elements' containerOf specifications @param type to check for thread-safety
[ "Returns", "an", "{", "@link", "Violation", "}", "explaining", "whether", "the", "type", "is", "threadsafe", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L494-L498
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/MultiNormalizerHybrid.java
MultiNormalizerHybrid.revertFeatures
@Override public void revertFeatures(@NonNull INDArray[] features, INDArray[] maskArrays) { """ Undo (revert) the normalization applied by this DataNormalization instance to the entire inputs array @param features The normalized array of inputs @param maskArrays Optional mask arrays belonging to the inputs """ for (int i = 0; i < features.length; i++) { revertFeatures(features, maskArrays, i); } }
java
@Override public void revertFeatures(@NonNull INDArray[] features, INDArray[] maskArrays) { for (int i = 0; i < features.length; i++) { revertFeatures(features, maskArrays, i); } }
[ "@", "Override", "public", "void", "revertFeatures", "(", "@", "NonNull", "INDArray", "[", "]", "features", ",", "INDArray", "[", "]", "maskArrays", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "features", ".", "length", ";", "i", "++", ")", "{", "revertFeatures", "(", "features", ",", "maskArrays", ",", "i", ")", ";", "}", "}" ]
Undo (revert) the normalization applied by this DataNormalization instance to the entire inputs array @param features The normalized array of inputs @param maskArrays Optional mask arrays belonging to the inputs
[ "Undo", "(", "revert", ")", "the", "normalization", "applied", "by", "this", "DataNormalization", "instance", "to", "the", "entire", "inputs", "array" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/MultiNormalizerHybrid.java#L366-L371
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java
BinaryRowSerializer.pointTo
public void pointTo(int length, BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException { """ Point row to memory segments with offset(in the AbstractPagedInputView) and length. @param length row length. @param reuse reuse BinaryRow object. @param headerLessView source memory segments container. """ checkArgument(headerLessView.getHeaderLength() == 0); if (length < 0) { throw new IOException(String.format( "Read unexpected bytes in source of positionInSegment[%d] and limitInSegment[%d]", headerLessView.getCurrentPositionInSegment(), headerLessView.getCurrentSegmentLimit() )); } int remainInSegment = headerLessView.getCurrentSegmentLimit() - headerLessView.getCurrentPositionInSegment(); MemorySegment currSeg = headerLessView.getCurrentSegment(); int currPosInSeg = headerLessView.getCurrentPositionInSegment(); if (remainInSegment >= length) { // all in one segment, that's good. reuse.pointTo(currSeg, currPosInSeg, length); headerLessView.skipBytesToRead(length); } else { pointToMultiSegments( reuse, headerLessView, length, length - remainInSegment, currSeg, currPosInSeg ); } }
java
public void pointTo(int length, BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException { checkArgument(headerLessView.getHeaderLength() == 0); if (length < 0) { throw new IOException(String.format( "Read unexpected bytes in source of positionInSegment[%d] and limitInSegment[%d]", headerLessView.getCurrentPositionInSegment(), headerLessView.getCurrentSegmentLimit() )); } int remainInSegment = headerLessView.getCurrentSegmentLimit() - headerLessView.getCurrentPositionInSegment(); MemorySegment currSeg = headerLessView.getCurrentSegment(); int currPosInSeg = headerLessView.getCurrentPositionInSegment(); if (remainInSegment >= length) { // all in one segment, that's good. reuse.pointTo(currSeg, currPosInSeg, length); headerLessView.skipBytesToRead(length); } else { pointToMultiSegments( reuse, headerLessView, length, length - remainInSegment, currSeg, currPosInSeg ); } }
[ "public", "void", "pointTo", "(", "int", "length", ",", "BinaryRow", "reuse", ",", "AbstractPagedInputView", "headerLessView", ")", "throws", "IOException", "{", "checkArgument", "(", "headerLessView", ".", "getHeaderLength", "(", ")", "==", "0", ")", ";", "if", "(", "length", "<", "0", ")", "{", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"Read unexpected bytes in source of positionInSegment[%d] and limitInSegment[%d]\"", ",", "headerLessView", ".", "getCurrentPositionInSegment", "(", ")", ",", "headerLessView", ".", "getCurrentSegmentLimit", "(", ")", ")", ")", ";", "}", "int", "remainInSegment", "=", "headerLessView", ".", "getCurrentSegmentLimit", "(", ")", "-", "headerLessView", ".", "getCurrentPositionInSegment", "(", ")", ";", "MemorySegment", "currSeg", "=", "headerLessView", ".", "getCurrentSegment", "(", ")", ";", "int", "currPosInSeg", "=", "headerLessView", ".", "getCurrentPositionInSegment", "(", ")", ";", "if", "(", "remainInSegment", ">=", "length", ")", "{", "// all in one segment, that's good.", "reuse", ".", "pointTo", "(", "currSeg", ",", "currPosInSeg", ",", "length", ")", ";", "headerLessView", ".", "skipBytesToRead", "(", "length", ")", ";", "}", "else", "{", "pointToMultiSegments", "(", "reuse", ",", "headerLessView", ",", "length", ",", "length", "-", "remainInSegment", ",", "currSeg", ",", "currPosInSeg", ")", ";", "}", "}" ]
Point row to memory segments with offset(in the AbstractPagedInputView) and length. @param length row length. @param reuse reuse BinaryRow object. @param headerLessView source memory segments container.
[ "Point", "row", "to", "memory", "segments", "with", "offset", "(", "in", "the", "AbstractPagedInputView", ")", "and", "length", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java#L224-L253
redkale/redkale
src/org/redkale/source/EntityInfo.java
EntityInfo.getSQLColumn
public String getSQLColumn(String tabalis, String fieldname) { """ 根据field字段名获取数据库对应的字段名 @param tabalis 表别名 @param fieldname 字段名 @return String """ return this.aliasmap == null ? (tabalis == null ? fieldname : (tabalis + '.' + fieldname)) : (tabalis == null ? aliasmap.getOrDefault(fieldname, fieldname) : (tabalis + '.' + aliasmap.getOrDefault(fieldname, fieldname))); }
java
public String getSQLColumn(String tabalis, String fieldname) { return this.aliasmap == null ? (tabalis == null ? fieldname : (tabalis + '.' + fieldname)) : (tabalis == null ? aliasmap.getOrDefault(fieldname, fieldname) : (tabalis + '.' + aliasmap.getOrDefault(fieldname, fieldname))); }
[ "public", "String", "getSQLColumn", "(", "String", "tabalis", ",", "String", "fieldname", ")", "{", "return", "this", ".", "aliasmap", "==", "null", "?", "(", "tabalis", "==", "null", "?", "fieldname", ":", "(", "tabalis", "+", "'", "'", "+", "fieldname", ")", ")", ":", "(", "tabalis", "==", "null", "?", "aliasmap", ".", "getOrDefault", "(", "fieldname", ",", "fieldname", ")", ":", "(", "tabalis", "+", "'", "'", "+", "aliasmap", ".", "getOrDefault", "(", "fieldname", ",", "fieldname", ")", ")", ")", ";", "}" ]
根据field字段名获取数据库对应的字段名 @param tabalis 表别名 @param fieldname 字段名 @return String
[ "根据field字段名获取数据库对应的字段名" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/EntityInfo.java#L877-L880
threerings/nenya
core/src/main/java/com/threerings/miso/client/MisoScenePanel.java
MisoScenePanel.paintBits
@Override protected void paintBits (Graphics2D gfx, int layer, Rectangle dirty) { """ We don't want sprites rendered using the standard mechanism because we intersperse them with objects in our scene and need to manage their z-order. """ _animmgr.paint(gfx, layer, dirty); }
java
@Override protected void paintBits (Graphics2D gfx, int layer, Rectangle dirty) { _animmgr.paint(gfx, layer, dirty); }
[ "@", "Override", "protected", "void", "paintBits", "(", "Graphics2D", "gfx", ",", "int", "layer", ",", "Rectangle", "dirty", ")", "{", "_animmgr", ".", "paint", "(", "gfx", ",", "layer", ",", "dirty", ")", ";", "}" ]
We don't want sprites rendered using the standard mechanism because we intersperse them with objects in our scene and need to manage their z-order.
[ "We", "don", "t", "want", "sprites", "rendered", "using", "the", "standard", "mechanism", "because", "we", "intersperse", "them", "with", "objects", "in", "our", "scene", "and", "need", "to", "manage", "their", "z", "-", "order", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L1253-L1257
KyoriPowered/text
api/src/main/java/net/kyori/text/KeybindComponent.java
KeybindComponent.of
public static KeybindComponent of(final @NonNull String keybind, final @Nullable TextColor color, final @NonNull Set<TextDecoration> decorations) { """ Creates a keybind component with content, and optional color and decorations. @param keybind the keybind @param color the color @param decorations the decorations @return the keybind component """ return builder(keybind).color(color).decorations(decorations, true).build(); }
java
public static KeybindComponent of(final @NonNull String keybind, final @Nullable TextColor color, final @NonNull Set<TextDecoration> decorations) { return builder(keybind).color(color).decorations(decorations, true).build(); }
[ "public", "static", "KeybindComponent", "of", "(", "final", "@", "NonNull", "String", "keybind", ",", "final", "@", "Nullable", "TextColor", "color", ",", "final", "@", "NonNull", "Set", "<", "TextDecoration", ">", "decorations", ")", "{", "return", "builder", "(", "keybind", ")", ".", "color", "(", "color", ")", ".", "decorations", "(", "decorations", ",", "true", ")", ".", "build", "(", ")", ";", "}" ]
Creates a keybind component with content, and optional color and decorations. @param keybind the keybind @param color the color @param decorations the decorations @return the keybind component
[ "Creates", "a", "keybind", "component", "with", "content", "and", "optional", "color", "and", "decorations", "." ]
train
https://github.com/KyoriPowered/text/blob/4496c593bf89e8fb036dd6efe26f8ac60f7655c9/api/src/main/java/net/kyori/text/KeybindComponent.java#L97-L99
groupe-sii/ogham
ogham-core/src/main/java/fr/sii/ogham/core/util/bean/BeanWrapperUtils.java
BeanWrapperUtils.getReadMethod
public static Method getReadMethod(Object bean, String name) { """ Get a read {@link Method} for a particular property. @param bean the bean instance @param name the name of the property @return the getter method for the property """ return getReadMethods(bean).get(name); }
java
public static Method getReadMethod(Object bean, String name) { return getReadMethods(bean).get(name); }
[ "public", "static", "Method", "getReadMethod", "(", "Object", "bean", ",", "String", "name", ")", "{", "return", "getReadMethods", "(", "bean", ")", ".", "get", "(", "name", ")", ";", "}" ]
Get a read {@link Method} for a particular property. @param bean the bean instance @param name the name of the property @return the getter method for the property
[ "Get", "a", "read", "{", "@link", "Method", "}", "for", "a", "particular", "property", "." ]
train
https://github.com/groupe-sii/ogham/blob/e273b845604add74b5a25dfd931cb3c166b1008f/ogham-core/src/main/java/fr/sii/ogham/core/util/bean/BeanWrapperUtils.java#L98-L100
OpenTSDB/opentsdb
src/tsd/HttpSerializer.java
HttpSerializer.formatThreadStatsV1
public ChannelBuffer formatThreadStatsV1(final List<Map<String, Object>> stats) { """ Format a list of thread statistics @param stats The thread statistics list to format @return A ChannelBuffer object to pass on to the caller @throws BadRequestException if the plugin has not implemented this method @since 2.2 """ throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "The requested API endpoint has not been implemented", this.getClass().getCanonicalName() + " has not implemented formatThreadStatsV1"); }
java
public ChannelBuffer formatThreadStatsV1(final List<Map<String, Object>> stats) { throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "The requested API endpoint has not been implemented", this.getClass().getCanonicalName() + " has not implemented formatThreadStatsV1"); }
[ "public", "ChannelBuffer", "formatThreadStatsV1", "(", "final", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "stats", ")", "{", "throw", "new", "BadRequestException", "(", "HttpResponseStatus", ".", "NOT_IMPLEMENTED", ",", "\"The requested API endpoint has not been implemented\"", ",", "this", ".", "getClass", "(", ")", ".", "getCanonicalName", "(", ")", "+", "\" has not implemented formatThreadStatsV1\"", ")", ";", "}" ]
Format a list of thread statistics @param stats The thread statistics list to format @return A ChannelBuffer object to pass on to the caller @throws BadRequestException if the plugin has not implemented this method @since 2.2
[ "Format", "a", "list", "of", "thread", "statistics" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/HttpSerializer.java#L726-L731
dain/leveldb
leveldb/src/main/java/org/iq80/leveldb/util/Slice.java
Slice.setBytes
public void setBytes(int index, Slice src, int srcIndex, int length) { """ Transfers the specified source buffer's data to this buffer starting at the specified absolute {@code index}. @param srcIndex the first index of the source @param length the number of bytes to transfer @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, if the specified {@code srcIndex} is less than {@code 0}, if {@code index + length} is greater than {@code this.capacity}, or if {@code srcIndex + length} is greater than {@code src.capacity} """ setBytes(index, src.data, src.offset + srcIndex, length); }
java
public void setBytes(int index, Slice src, int srcIndex, int length) { setBytes(index, src.data, src.offset + srcIndex, length); }
[ "public", "void", "setBytes", "(", "int", "index", ",", "Slice", "src", ",", "int", "srcIndex", ",", "int", "length", ")", "{", "setBytes", "(", "index", ",", "src", ".", "data", ",", "src", ".", "offset", "+", "srcIndex", ",", "length", ")", ";", "}" ]
Transfers the specified source buffer's data to this buffer starting at the specified absolute {@code index}. @param srcIndex the first index of the source @param length the number of bytes to transfer @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0}, if the specified {@code srcIndex} is less than {@code 0}, if {@code index + length} is greater than {@code this.capacity}, or if {@code srcIndex + length} is greater than {@code src.capacity}
[ "Transfers", "the", "specified", "source", "buffer", "s", "data", "to", "this", "buffer", "starting", "at", "the", "specified", "absolute", "{", "@code", "index", "}", "." ]
train
https://github.com/dain/leveldb/blob/7994065b48eada2ef29e7fefd172c2ad1e0110eb/leveldb/src/main/java/org/iq80/leveldb/util/Slice.java#L367-L370
osglworks/java-mvc
src/main/java/org/osgl/mvc/result/Conflict.java
Conflict.of
public static Conflict of(int errorCode, Throwable cause) { """ Returns a static Conflict instance and set the {@link #payload} thread local with error code and cause specified When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param cause the cause @param errorCode the app defined error code @return a static Conflict instance as described above """ if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(CONFLICT)); } else { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; } }
java
public static Conflict of(int errorCode, Throwable cause) { if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(CONFLICT)); } else { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; } }
[ "public", "static", "Conflict", "of", "(", "int", "errorCode", ",", "Throwable", "cause", ")", "{", "if", "(", "_localizedErrorMsg", "(", ")", ")", "{", "return", "of", "(", "errorCode", ",", "cause", ",", "defaultMessage", "(", "CONFLICT", ")", ")", ";", "}", "else", "{", "touchPayload", "(", ")", ".", "errorCode", "(", "errorCode", ")", ".", "cause", "(", "cause", ")", ";", "return", "_INSTANCE", ";", "}", "}" ]
Returns a static Conflict instance and set the {@link #payload} thread local with error code and cause specified When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param cause the cause @param errorCode the app defined error code @return a static Conflict instance as described above
[ "Returns", "a", "static", "Conflict", "instance", "and", "set", "the", "{", "@link", "#payload", "}", "thread", "local", "with", "error", "code", "and", "cause", "specified" ]
train
https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/Conflict.java#L206-L213
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/FieldAccessor.java
FieldAccessor.getValue
public Object getValue(final Object targetObj) { """ オブジェクトのフィールドの値を取得します。 <p>getterが存在する場合は、getterメソッド経由で取得します。</p> @param targetObj オブジェクト(インスタンス) @return フィールドの値。 @throws IllegalArgumentException {@literal targetObj == null.} @throws FieldAccessException {@literal 値の取得に失敗した場合。} """ ArgUtils.notNull(targetObj, "targetObj"); if(targetGetter.isPresent()) { try { return targetGetter.get().invoke(targetObj); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new FieldAccessException(this, "fail getter value", e); } } else if(targetField.isPresent()) { try { return targetField.get().get(targetObj); } catch (IllegalArgumentException | IllegalAccessException e) { throw new FieldAccessException(this, "fail get field value", e); } } else { throw new FieldAccessException(this, "not found getter method or field."); } }
java
public Object getValue(final Object targetObj) { ArgUtils.notNull(targetObj, "targetObj"); if(targetGetter.isPresent()) { try { return targetGetter.get().invoke(targetObj); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new FieldAccessException(this, "fail getter value", e); } } else if(targetField.isPresent()) { try { return targetField.get().get(targetObj); } catch (IllegalArgumentException | IllegalAccessException e) { throw new FieldAccessException(this, "fail get field value", e); } } else { throw new FieldAccessException(this, "not found getter method or field."); } }
[ "public", "Object", "getValue", "(", "final", "Object", "targetObj", ")", "{", "ArgUtils", ".", "notNull", "(", "targetObj", ",", "\"targetObj\"", ")", ";", "if", "(", "targetGetter", ".", "isPresent", "(", ")", ")", "{", "try", "{", "return", "targetGetter", ".", "get", "(", ")", ".", "invoke", "(", "targetObj", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "IllegalArgumentException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "FieldAccessException", "(", "this", ",", "\"fail getter value\"", ",", "e", ")", ";", "}", "}", "else", "if", "(", "targetField", ".", "isPresent", "(", ")", ")", "{", "try", "{", "return", "targetField", ".", "get", "(", ")", ".", "get", "(", "targetObj", ")", ";", "}", "catch", "(", "IllegalArgumentException", "|", "IllegalAccessException", "e", ")", "{", "throw", "new", "FieldAccessException", "(", "this", ",", "\"fail get field value\"", ",", "e", ")", ";", "}", "}", "else", "{", "throw", "new", "FieldAccessException", "(", "this", ",", "\"not found getter method or field.\"", ")", ";", "}", "}" ]
オブジェクトのフィールドの値を取得します。 <p>getterが存在する場合は、getterメソッド経由で取得します。</p> @param targetObj オブジェクト(インスタンス) @return フィールドの値。 @throws IllegalArgumentException {@literal targetObj == null.} @throws FieldAccessException {@literal 値の取得に失敗した場合。}
[ "オブジェクトのフィールドの値を取得します。", "<p", ">", "getterが存在する場合は、getterメソッド経由で取得します。<", "/", "p", ">" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/FieldAccessor.java#L164-L186
joniles/mpxj
src/main/java/net/sf/mpxj/RecurringData.java
RecurringData.setCalendarToOrdinalRelativeDay
private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber) { """ Moves a calendar to the nth named day of the month. @param calendar current date @param dayNumber nth day """ int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int requiredDayOfWeek = getDayOfWeek().getValue(); int dayOfWeekOffset = 0; if (requiredDayOfWeek > currentDayOfWeek) { dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek; } else { if (requiredDayOfWeek < currentDayOfWeek) { dayOfWeekOffset = 7 - (currentDayOfWeek - requiredDayOfWeek); } } if (dayOfWeekOffset != 0) { calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset); } if (dayNumber > 1) { calendar.add(Calendar.DAY_OF_YEAR, (7 * (dayNumber - 1))); } }
java
private void setCalendarToOrdinalRelativeDay(Calendar calendar, int dayNumber) { int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int requiredDayOfWeek = getDayOfWeek().getValue(); int dayOfWeekOffset = 0; if (requiredDayOfWeek > currentDayOfWeek) { dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek; } else { if (requiredDayOfWeek < currentDayOfWeek) { dayOfWeekOffset = 7 - (currentDayOfWeek - requiredDayOfWeek); } } if (dayOfWeekOffset != 0) { calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset); } if (dayNumber > 1) { calendar.add(Calendar.DAY_OF_YEAR, (7 * (dayNumber - 1))); } }
[ "private", "void", "setCalendarToOrdinalRelativeDay", "(", "Calendar", "calendar", ",", "int", "dayNumber", ")", "{", "int", "currentDayOfWeek", "=", "calendar", ".", "get", "(", "Calendar", ".", "DAY_OF_WEEK", ")", ";", "int", "requiredDayOfWeek", "=", "getDayOfWeek", "(", ")", ".", "getValue", "(", ")", ";", "int", "dayOfWeekOffset", "=", "0", ";", "if", "(", "requiredDayOfWeek", ">", "currentDayOfWeek", ")", "{", "dayOfWeekOffset", "=", "requiredDayOfWeek", "-", "currentDayOfWeek", ";", "}", "else", "{", "if", "(", "requiredDayOfWeek", "<", "currentDayOfWeek", ")", "{", "dayOfWeekOffset", "=", "7", "-", "(", "currentDayOfWeek", "-", "requiredDayOfWeek", ")", ";", "}", "}", "if", "(", "dayOfWeekOffset", "!=", "0", ")", "{", "calendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "dayOfWeekOffset", ")", ";", "}", "if", "(", "dayNumber", ">", "1", ")", "{", "calendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "(", "7", "*", "(", "dayNumber", "-", "1", ")", ")", ")", ";", "}", "}" ]
Moves a calendar to the nth named day of the month. @param calendar current date @param dayNumber nth day
[ "Moves", "a", "calendar", "to", "the", "nth", "named", "day", "of", "the", "month", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/RecurringData.java#L640-L666