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
wealthfront/magellan
magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java
Navigator.onCreate
public void onCreate(Activity activity, Bundle savedInstanceState) { """ Initializes the Navigator with Activity instance and Bundle for saved instance state. Call this method from {@link Activity#onCreate(Bundle) onCreate} of the Activity associated with this Navigator. @param activity Activity associated with application @param savedInstanceState state to restore from previously destroyed activity @throws IllegalStateException when no {@link ScreenContainer} view present in hierarchy with view id of container """ this.activity = activity; container = (ScreenContainer) activity.findViewById(R.id.magellan_container); checkState(container != null, "There must be a ScreenContainer whose id is R.id.magellan_container in the view hierarchy"); for (Screen screen : backStack) { screen.restore(savedInstanceState); screen.onRestore(savedInstanceState); } showCurrentScreen(FORWARD); }
java
public void onCreate(Activity activity, Bundle savedInstanceState) { this.activity = activity; container = (ScreenContainer) activity.findViewById(R.id.magellan_container); checkState(container != null, "There must be a ScreenContainer whose id is R.id.magellan_container in the view hierarchy"); for (Screen screen : backStack) { screen.restore(savedInstanceState); screen.onRestore(savedInstanceState); } showCurrentScreen(FORWARD); }
[ "public", "void", "onCreate", "(", "Activity", "activity", ",", "Bundle", "savedInstanceState", ")", "{", "this", ".", "activity", "=", "activity", ";", "container", "=", "(", "ScreenContainer", ")", "activity", ".", "findViewById", "(", "R", ".", "id", ".",...
Initializes the Navigator with Activity instance and Bundle for saved instance state. Call this method from {@link Activity#onCreate(Bundle) onCreate} of the Activity associated with this Navigator. @param activity Activity associated with application @param savedInstanceState state to restore from previously destroyed activity @throws IllegalStateException when no {@link ScreenContainer} view present in hierarchy with view id of container
[ "Initializes", "the", "Navigator", "with", "Activity", "instance", "and", "Bundle", "for", "saved", "instance", "state", "." ]
train
https://github.com/wealthfront/magellan/blob/f690979161a97e40fb9d11dc9d7e3c8cf85ba312/magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java#L86-L95
KyoriPowered/lunar
src/main/java/net/kyori/lunar/graph/MoreGraphs.java
MoreGraphs.orderedTopologicalSort
public static <T> @NonNull List<T> orderedTopologicalSort(final @NonNull Graph<T> graph, final @NonNull Comparator<T> comparator) { """ Sorts a directed acyclic graph into a list. <p>The particular order of elements without prerequisites is determined by the comparator.</p> @param graph the graph to be sorted @param comparator the comparator @param <T> the node type @return the sorted list @throws CyclePresentException if the graph has cycles @throws IllegalArgumentException if the graph is not directed or allows self loops """ return topologicalSort(graph, new ComparatorSortType<>(comparator)); }
java
public static <T> @NonNull List<T> orderedTopologicalSort(final @NonNull Graph<T> graph, final @NonNull Comparator<T> comparator) { return topologicalSort(graph, new ComparatorSortType<>(comparator)); }
[ "public", "static", "<", "T", ">", "@", "NonNull", "List", "<", "T", ">", "orderedTopologicalSort", "(", "final", "@", "NonNull", "Graph", "<", "T", ">", "graph", ",", "final", "@", "NonNull", "Comparator", "<", "T", ">", "comparator", ")", "{", "retur...
Sorts a directed acyclic graph into a list. <p>The particular order of elements without prerequisites is determined by the comparator.</p> @param graph the graph to be sorted @param comparator the comparator @param <T> the node type @return the sorted list @throws CyclePresentException if the graph has cycles @throws IllegalArgumentException if the graph is not directed or allows self loops
[ "Sorts", "a", "directed", "acyclic", "graph", "into", "a", "list", "." ]
train
https://github.com/KyoriPowered/lunar/blob/6856747d9034a2fe0c8d0a8a0150986797732b5c/src/main/java/net/kyori/lunar/graph/MoreGraphs.java#L72-L74
r0adkll/PostOffice
library/src/main/java/com/r0adkll/postoffice/PostOffice.java
PostOffice.newProgressMail
public static Delivery newProgressMail(@NotNull Context ctx, CharSequence title, String suffix, boolean indeterminate) { """ Create a new ProgressDialog 'Mail' delivery to display @param ctx the application context @param title the dialog title @param suffix the progress text suffix @param indeterminate the progress indeterminate flag @return the new Delivery """ Delivery.Builder builder = new Delivery.Builder(ctx) .setTitle(title) .setStyle(new ProgressStyle.Builder(ctx) .setIndeterminate(indeterminate) .setCloseOnFinish(true) .setPercentageMode(false) .setSuffix(suffix) .build()); // Override some defaults return builder.setCancelable(false) .setCanceledOnTouchOutside(false) .build(); }
java
public static Delivery newProgressMail(@NotNull Context ctx, CharSequence title, String suffix, boolean indeterminate){ Delivery.Builder builder = new Delivery.Builder(ctx) .setTitle(title) .setStyle(new ProgressStyle.Builder(ctx) .setIndeterminate(indeterminate) .setCloseOnFinish(true) .setPercentageMode(false) .setSuffix(suffix) .build()); // Override some defaults return builder.setCancelable(false) .setCanceledOnTouchOutside(false) .build(); }
[ "public", "static", "Delivery", "newProgressMail", "(", "@", "NotNull", "Context", "ctx", ",", "CharSequence", "title", ",", "String", "suffix", ",", "boolean", "indeterminate", ")", "{", "Delivery", ".", "Builder", "builder", "=", "new", "Delivery", ".", "Bui...
Create a new ProgressDialog 'Mail' delivery to display @param ctx the application context @param title the dialog title @param suffix the progress text suffix @param indeterminate the progress indeterminate flag @return the new Delivery
[ "Create", "a", "new", "ProgressDialog", "Mail", "delivery", "to", "display" ]
train
https://github.com/r0adkll/PostOffice/blob/f98e365fd66c004ccce64ee87d9f471b97e4e3c2/library/src/main/java/com/r0adkll/postoffice/PostOffice.java#L369-L383
ThreeTen/threetenbp
src/main/java/org/threeten/bp/chrono/Chronology.java
Chronology.updateResolveMap
void updateResolveMap(Map<TemporalField, Long> fieldValues, ChronoField field, long value) { """ Updates the map of field-values during resolution. @param field the field to update, not null @param value the value to update, not null @throws DateTimeException if a conflict occurs """ Long current = fieldValues.get(field); if (current != null && current.longValue() != value) { throw new DateTimeException("Invalid state, field: " + field + " " + current + " conflicts with " + field + " " + value); } fieldValues.put(field, value); }
java
void updateResolveMap(Map<TemporalField, Long> fieldValues, ChronoField field, long value) { Long current = fieldValues.get(field); if (current != null && current.longValue() != value) { throw new DateTimeException("Invalid state, field: " + field + " " + current + " conflicts with " + field + " " + value); } fieldValues.put(field, value); }
[ "void", "updateResolveMap", "(", "Map", "<", "TemporalField", ",", "Long", ">", "fieldValues", ",", "ChronoField", "field", ",", "long", "value", ")", "{", "Long", "current", "=", "fieldValues", ".", "get", "(", "field", ")", ";", "if", "(", "current", "...
Updates the map of field-values during resolution. @param field the field to update, not null @param value the value to update, not null @throws DateTimeException if a conflict occurs
[ "Updates", "the", "map", "of", "field", "-", "values", "during", "resolution", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/chrono/Chronology.java#L802-L808
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/TemporaryFileScanWriter.java
TemporaryFileScanWriter.blockUntilOpenShardsAtMost
private boolean blockUntilOpenShardsAtMost(int maxOpenShards, @Nullable TransferKey permittedKey, Instant timeout) throws IOException, InterruptedException { """ Blocks until the number of open shards is equal to or less than the provided threshold or the current time is after the timeout timestamp. """ Stopwatch stopWatch = Stopwatch.createStarted(); Instant now; _lock.lock(); try { while (!_closed && maxOpenShardsGreaterThan(maxOpenShards, permittedKey) && (now = Instant.now()).isBefore(timeout)) { // Stop blocking if there is an exception propagateExceptionIfPresent(); // Wait no longer than 30 seconds; we want to log at least every 30 seconds we've been waiting. long waitTime = Math.min(Duration.ofSeconds(30).toMillis(), Duration.between(now, timeout).toMillis()); _shardFilesClosedOrExceptionCaught.await(waitTime, TimeUnit.MILLISECONDS); if (!maxOpenShardsGreaterThan(maxOpenShards, permittedKey)) { propagateExceptionIfPresent(); return true; } _log.debug("After {} seconds task {} still has {} open shards", stopWatch.elapsed(TimeUnit.SECONDS), _taskId, _openShardFiles.size()); } propagateExceptionIfPresent(); return !maxOpenShardsGreaterThan(maxOpenShards, permittedKey); } finally { _lock.unlock(); } }
java
private boolean blockUntilOpenShardsAtMost(int maxOpenShards, @Nullable TransferKey permittedKey, Instant timeout) throws IOException, InterruptedException { Stopwatch stopWatch = Stopwatch.createStarted(); Instant now; _lock.lock(); try { while (!_closed && maxOpenShardsGreaterThan(maxOpenShards, permittedKey) && (now = Instant.now()).isBefore(timeout)) { // Stop blocking if there is an exception propagateExceptionIfPresent(); // Wait no longer than 30 seconds; we want to log at least every 30 seconds we've been waiting. long waitTime = Math.min(Duration.ofSeconds(30).toMillis(), Duration.between(now, timeout).toMillis()); _shardFilesClosedOrExceptionCaught.await(waitTime, TimeUnit.MILLISECONDS); if (!maxOpenShardsGreaterThan(maxOpenShards, permittedKey)) { propagateExceptionIfPresent(); return true; } _log.debug("After {} seconds task {} still has {} open shards", stopWatch.elapsed(TimeUnit.SECONDS), _taskId, _openShardFiles.size()); } propagateExceptionIfPresent(); return !maxOpenShardsGreaterThan(maxOpenShards, permittedKey); } finally { _lock.unlock(); } }
[ "private", "boolean", "blockUntilOpenShardsAtMost", "(", "int", "maxOpenShards", ",", "@", "Nullable", "TransferKey", "permittedKey", ",", "Instant", "timeout", ")", "throws", "IOException", ",", "InterruptedException", "{", "Stopwatch", "stopWatch", "=", "Stopwatch", ...
Blocks until the number of open shards is equal to or less than the provided threshold or the current time is after the timeout timestamp.
[ "Blocks", "until", "the", "number", "of", "open", "shards", "is", "equal", "to", "or", "less", "than", "the", "provided", "threshold", "or", "the", "current", "time", "is", "after", "the", "timeout", "timestamp", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/TemporaryFileScanWriter.java#L232-L263
carewebframework/carewebframework-vista
org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/FMDate.java
FMDate.setCalendar
private long setCalendar(Calendar cal, int part, long value, long div) { """ Sets a calendar component based on the input value. Meant to be called successively, with the return value used as the input value for the next call, to extract lower digits from the input value to be set into the calendar component. @param cal Calendar component. @param part Calendar component to be set. @param value Current value. @param div Modulus for value to be extracted. @return Original value divided by modulus. """ cal.set(part, (int) (value % div)); return value / div; }
java
private long setCalendar(Calendar cal, int part, long value, long div) { cal.set(part, (int) (value % div)); return value / div; }
[ "private", "long", "setCalendar", "(", "Calendar", "cal", ",", "int", "part", ",", "long", "value", ",", "long", "div", ")", "{", "cal", ".", "set", "(", "part", ",", "(", "int", ")", "(", "value", "%", "div", ")", ")", ";", "return", "value", "/...
Sets a calendar component based on the input value. Meant to be called successively, with the return value used as the input value for the next call, to extract lower digits from the input value to be set into the calendar component. @param cal Calendar component. @param part Calendar component to be set. @param value Current value. @param div Modulus for value to be extracted. @return Original value divided by modulus.
[ "Sets", "a", "calendar", "component", "based", "on", "the", "input", "value", ".", "Meant", "to", "be", "called", "successively", "with", "the", "return", "value", "used", "as", "the", "input", "value", "for", "the", "next", "call", "to", "extract", "lower...
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/FMDate.java#L149-L152
alkacon/opencms-core
src/org/opencms/webdav/CmsWebdavServlet.java
CmsWebdavServlet.generateLockDiscovery
private boolean generateLockDiscovery(String path, Element elem, HttpServletRequest req) { """ Print the lock discovery information associated with a path.<p> @param path the path to the resource @param elem the dom element where to add the lock discovery elements @param req the servlet request we are processing @return true if at least one lock was displayed """ CmsRepositoryLockInfo lock = m_session.getLock(path); if (lock != null) { Element lockElem = addElement(elem, TAG_LOCKDISCOVERY); addLockElement(lock, lockElem, generateLockToken(req, lock)); return true; } return false; }
java
private boolean generateLockDiscovery(String path, Element elem, HttpServletRequest req) { CmsRepositoryLockInfo lock = m_session.getLock(path); if (lock != null) { Element lockElem = addElement(elem, TAG_LOCKDISCOVERY); addLockElement(lock, lockElem, generateLockToken(req, lock)); return true; } return false; }
[ "private", "boolean", "generateLockDiscovery", "(", "String", "path", ",", "Element", "elem", ",", "HttpServletRequest", "req", ")", "{", "CmsRepositoryLockInfo", "lock", "=", "m_session", ".", "getLock", "(", "path", ")", ";", "if", "(", "lock", "!=", "null",...
Print the lock discovery information associated with a path.<p> @param path the path to the resource @param elem the dom element where to add the lock discovery elements @param req the servlet request we are processing @return true if at least one lock was displayed
[ "Print", "the", "lock", "discovery", "information", "associated", "with", "a", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/webdav/CmsWebdavServlet.java#L3029-L3042
RestComm/media-core
rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpComparator.java
SdpComparator.negotiateVideo
public RTPFormats negotiateVideo(SessionDescription sdp, RTPFormats formats) { """ Negotiates the video formats to be used in the call. @param sdp The session description @param formats The available formats @return The supported formats. If no formats are supported the returned list will be empty. """ this.video.clean(); MediaDescriptorField descriptor = sdp.getVideoDescriptor(); descriptor.getFormats().intersection(formats, this.video); return this.video; }
java
public RTPFormats negotiateVideo(SessionDescription sdp, RTPFormats formats) { this.video.clean(); MediaDescriptorField descriptor = sdp.getVideoDescriptor(); descriptor.getFormats().intersection(formats, this.video); return this.video; }
[ "public", "RTPFormats", "negotiateVideo", "(", "SessionDescription", "sdp", ",", "RTPFormats", "formats", ")", "{", "this", ".", "video", ".", "clean", "(", ")", ";", "MediaDescriptorField", "descriptor", "=", "sdp", ".", "getVideoDescriptor", "(", ")", ";", "...
Negotiates the video formats to be used in the call. @param sdp The session description @param formats The available formats @return The supported formats. If no formats are supported the returned list will be empty.
[ "Negotiates", "the", "video", "formats", "to", "be", "used", "in", "the", "call", "." ]
train
https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpComparator.java#L83-L88
wcm-io/wcm-io-wcm
commons/src/main/java/io/wcm/wcm/commons/util/Template.java
Template.forPage
@SafeVarargs public static <E extends Enum<E> & TemplatePathInfo> TemplatePathInfo forPage(@NotNull Page page, @NotNull Class<E> @NotNull... templateEnums) { """ Lookup template for given page. @param page Page @param templateEnums Templates @param <E> Template enum @return The {@link TemplatePathInfo} instance or null for unknown template paths """ if (page == null || templateEnums == null) { return null; } String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class); return forTemplatePath(templatePath, templateEnums); }
java
@SafeVarargs public static <E extends Enum<E> & TemplatePathInfo> TemplatePathInfo forPage(@NotNull Page page, @NotNull Class<E> @NotNull... templateEnums) { if (page == null || templateEnums == null) { return null; } String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class); return forTemplatePath(templatePath, templateEnums); }
[ "@", "SafeVarargs", "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", "&", "TemplatePathInfo", ">", "TemplatePathInfo", "forPage", "(", "@", "NotNull", "Page", "page", ",", "@", "NotNull", "Class", "<", "E", ">", "@", "NotNull", ".", ".", ...
Lookup template for given page. @param page Page @param templateEnums Templates @param <E> Template enum @return The {@link TemplatePathInfo} instance or null for unknown template paths
[ "Lookup", "template", "for", "given", "page", "." ]
train
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/util/Template.java#L173-L180
apache/flink
flink-core/src/main/java/org/apache/flink/core/io/SimpleVersionedSerialization.java
SimpleVersionedSerialization.writeVersionAndSerialize
public static <T> void writeVersionAndSerialize(SimpleVersionedSerializer<T> serializer, T datum, DataOutputView out) throws IOException { """ Serializes the version and datum into a stream. <p>Data serialized via this method can be deserialized via {@link #readVersionAndDeSerialize(SimpleVersionedSerializer, DataInputView)}. <p>The first four bytes will be occupied by the version, as returned by {@link SimpleVersionedSerializer#getVersion()}. The remaining bytes will be the serialized datum, as produced by {@link SimpleVersionedSerializer#serialize(Object)}, plus its length. The resulting array will hence be eight bytes larger than the serialized datum. @param serializer The serializer to serialize the datum with. @param datum The datum to serialize. @param out The stream to serialize to. """ checkNotNull(serializer, "serializer"); checkNotNull(datum, "datum"); checkNotNull(out, "out"); final byte[] data = serializer.serialize(datum); out.writeInt(serializer.getVersion()); out.writeInt(data.length); out.write(data); }
java
public static <T> void writeVersionAndSerialize(SimpleVersionedSerializer<T> serializer, T datum, DataOutputView out) throws IOException { checkNotNull(serializer, "serializer"); checkNotNull(datum, "datum"); checkNotNull(out, "out"); final byte[] data = serializer.serialize(datum); out.writeInt(serializer.getVersion()); out.writeInt(data.length); out.write(data); }
[ "public", "static", "<", "T", ">", "void", "writeVersionAndSerialize", "(", "SimpleVersionedSerializer", "<", "T", ">", "serializer", ",", "T", "datum", ",", "DataOutputView", "out", ")", "throws", "IOException", "{", "checkNotNull", "(", "serializer", ",", "\"s...
Serializes the version and datum into a stream. <p>Data serialized via this method can be deserialized via {@link #readVersionAndDeSerialize(SimpleVersionedSerializer, DataInputView)}. <p>The first four bytes will be occupied by the version, as returned by {@link SimpleVersionedSerializer#getVersion()}. The remaining bytes will be the serialized datum, as produced by {@link SimpleVersionedSerializer#serialize(Object)}, plus its length. The resulting array will hence be eight bytes larger than the serialized datum. @param serializer The serializer to serialize the datum with. @param datum The datum to serialize. @param out The stream to serialize to.
[ "Serializes", "the", "version", "and", "datum", "into", "a", "stream", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/core/io/SimpleVersionedSerialization.java#L52-L62
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/ExecUtilities.java
ExecUtilities.runCommand
public static boolean runCommand(final Process p, final OutputStream output) { """ Run a Process, and read the various streams so there is not a buffer overrun. @param p The Process to be executed @param output The Stream to receive the Process' output stream @return true if the Process returned 0, false otherwise """ return runCommand(p, output, output, new ArrayList<String>()); }
java
public static boolean runCommand(final Process p, final OutputStream output) { return runCommand(p, output, output, new ArrayList<String>()); }
[ "public", "static", "boolean", "runCommand", "(", "final", "Process", "p", ",", "final", "OutputStream", "output", ")", "{", "return", "runCommand", "(", "p", ",", "output", ",", "output", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ")", ";", ...
Run a Process, and read the various streams so there is not a buffer overrun. @param p The Process to be executed @param output The Stream to receive the Process' output stream @return true if the Process returned 0, false otherwise
[ "Run", "a", "Process", "and", "read", "the", "various", "streams", "so", "there", "is", "not", "a", "buffer", "overrun", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/ExecUtilities.java#L48-L50
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.getAndDecryptDouble
public Double getAndDecryptDouble(String name, String providerName) throws Exception { """ Retrieves the value from the field name and casts it to {@link Double}. Note that if value was stored as another numerical type, some truncation or rounding may occur. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName the crypto provider name for decryption @return the result or null if it does not exist. """ //let it fail in the more general case where it isn't actually a number Number number = (Number) getAndDecrypt(name, providerName); if (number == null) { return null; } else if (number instanceof Double) { return (Double) number; } else { return number.doubleValue(); //autoboxing to Double } }
java
public Double getAndDecryptDouble(String name, String providerName) throws Exception { //let it fail in the more general case where it isn't actually a number Number number = (Number) getAndDecrypt(name, providerName); if (number == null) { return null; } else if (number instanceof Double) { return (Double) number; } else { return number.doubleValue(); //autoboxing to Double } }
[ "public", "Double", "getAndDecryptDouble", "(", "String", "name", ",", "String", "providerName", ")", "throws", "Exception", "{", "//let it fail in the more general case where it isn't actually a number", "Number", "number", "=", "(", "Number", ")", "getAndDecrypt", "(", ...
Retrieves the value from the field name and casts it to {@link Double}. Note that if value was stored as another numerical type, some truncation or rounding may occur. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName the crypto provider name for decryption @return the result or null if it does not exist.
[ "Retrieves", "the", "value", "from", "the", "field", "name", "and", "casts", "it", "to", "{", "@link", "Double", "}", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L599-L609
threerings/nenya
tools/src/main/java/com/threerings/media/tile/bundle/tools/TileSetBundlerTask.java
TileSetBundlerTask.getTargetPath
protected String getTargetPath (File fromDir, String path) { """ Returns the target path in which our bundler will write the tile set. """ return path.substring(0, path.length()-4) + ".jar"; }
java
protected String getTargetPath (File fromDir, String path) { return path.substring(0, path.length()-4) + ".jar"; }
[ "protected", "String", "getTargetPath", "(", "File", "fromDir", ",", "String", "path", ")", "{", "return", "path", ".", "substring", "(", "0", ",", "path", ".", "length", "(", ")", "-", "4", ")", "+", "\".jar\"", ";", "}" ]
Returns the target path in which our bundler will write the tile set.
[ "Returns", "the", "target", "path", "in", "which", "our", "bundler", "will", "write", "the", "tile", "set", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/tools/src/main/java/com/threerings/media/tile/bundle/tools/TileSetBundlerTask.java#L162-L165
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/JsonMapper.java
JsonMapper.addClassSerializer
public <T> void addClassSerializer(Class<? extends T> classToMap, JsonSerializer<T> classSerializer) { """ Adds a serializer to this mapper. Allows a user to alter the serialization behavior for a certain type. @param classToMap the class to map @param classSerializer the serializer @param <T> the type of objects that will be serialized by the given serializer """ setNewObjectMapper(); // Is this right, setting a new object mapper on each add operation? SimpleModule mod = new SimpleModule("GeolatteCommonModule-" + classSerializer.getClass().getSimpleName()); mod.addSerializer(classToMap, classSerializer); mapper.registerModule(mod); }
java
public <T> void addClassSerializer(Class<? extends T> classToMap, JsonSerializer<T> classSerializer) { setNewObjectMapper(); // Is this right, setting a new object mapper on each add operation? SimpleModule mod = new SimpleModule("GeolatteCommonModule-" + classSerializer.getClass().getSimpleName()); mod.addSerializer(classToMap, classSerializer); mapper.registerModule(mod); }
[ "public", "<", "T", ">", "void", "addClassSerializer", "(", "Class", "<", "?", "extends", "T", ">", "classToMap", ",", "JsonSerializer", "<", "T", ">", "classSerializer", ")", "{", "setNewObjectMapper", "(", ")", ";", "// Is this right, setting a new object mapper...
Adds a serializer to this mapper. Allows a user to alter the serialization behavior for a certain type. @param classToMap the class to map @param classSerializer the serializer @param <T> the type of objects that will be serialized by the given serializer
[ "Adds", "a", "serializer", "to", "this", "mapper", ".", "Allows", "a", "user", "to", "alter", "the", "serialization", "behavior", "for", "a", "certain", "type", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/JsonMapper.java#L234-L239
thorntail/thorntail
meta/fraction-metadata/src/main/java/org/wildfly/swarm/fractions/FractionDescriptor.java
FractionDescriptor.fromGav
public static FractionDescriptor fromGav(final FractionList fractionList, final String gav) { """ Retrieves a {@link FractionDescriptor} from the {@code fractionList} based on the {@code gav} string. <p>The {@code gav} string contains colon-delimited Maven artifact coordinates. Supported formats are:</p> <ul> <li>{@code artifactId}: the groupId {@code org.wildfly.swarm} is presumed</li> <li>{@code artifactId:version}: the groupId {@code org.wildfly.swarm} is presumed</li> <li>{@code groupId:artifactId:version}</li> </ul> <p>If the {@code fractionList} doesn't contain such fraction, an exception is thrown.</p> """ final String[] parts = gav.split(":"); FractionDescriptor desc = null; switch (parts.length) { case 1: desc = fractionList.getFractionDescriptor(THORNTAIL_GROUP_ID, parts[0]); if (desc == null) { throw new RuntimeException("Fraction not found: " + gav); } break; case 2: desc = fractionList.getFractionDescriptor(THORNTAIL_GROUP_ID, parts[0]); if (desc == null) { throw new RuntimeException("Fraction not found: " + gav); } if (!desc.getVersion().equals(parts[1])) { throw new RuntimeException("Version mismatch: requested " + gav + ", found " + desc.av()); } break; case 3: desc = fractionList.getFractionDescriptor(parts[0], parts[1]); if (desc == null) { throw new RuntimeException("Fraction not found: " + gav); } if (!desc.getVersion().equals(parts[2])) { throw new RuntimeException("Version mismatch: requested " + gav + ", found " + desc.gav()); } break; default: throw new RuntimeException("Invalid fraction spec: " + gav); } return desc; }
java
public static FractionDescriptor fromGav(final FractionList fractionList, final String gav) { final String[] parts = gav.split(":"); FractionDescriptor desc = null; switch (parts.length) { case 1: desc = fractionList.getFractionDescriptor(THORNTAIL_GROUP_ID, parts[0]); if (desc == null) { throw new RuntimeException("Fraction not found: " + gav); } break; case 2: desc = fractionList.getFractionDescriptor(THORNTAIL_GROUP_ID, parts[0]); if (desc == null) { throw new RuntimeException("Fraction not found: " + gav); } if (!desc.getVersion().equals(parts[1])) { throw new RuntimeException("Version mismatch: requested " + gav + ", found " + desc.av()); } break; case 3: desc = fractionList.getFractionDescriptor(parts[0], parts[1]); if (desc == null) { throw new RuntimeException("Fraction not found: " + gav); } if (!desc.getVersion().equals(parts[2])) { throw new RuntimeException("Version mismatch: requested " + gav + ", found " + desc.gav()); } break; default: throw new RuntimeException("Invalid fraction spec: " + gav); } return desc; }
[ "public", "static", "FractionDescriptor", "fromGav", "(", "final", "FractionList", "fractionList", ",", "final", "String", "gav", ")", "{", "final", "String", "[", "]", "parts", "=", "gav", ".", "split", "(", "\":\"", ")", ";", "FractionDescriptor", "desc", ...
Retrieves a {@link FractionDescriptor} from the {@code fractionList} based on the {@code gav} string. <p>The {@code gav} string contains colon-delimited Maven artifact coordinates. Supported formats are:</p> <ul> <li>{@code artifactId}: the groupId {@code org.wildfly.swarm} is presumed</li> <li>{@code artifactId:version}: the groupId {@code org.wildfly.swarm} is presumed</li> <li>{@code groupId:artifactId:version}</li> </ul> <p>If the {@code fractionList} doesn't contain such fraction, an exception is thrown.</p>
[ "Retrieves", "a", "{", "@link", "FractionDescriptor", "}", "from", "the", "{", "@code", "fractionList", "}", "based", "on", "the", "{", "@code", "gav", "}", "string", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/meta/fraction-metadata/src/main/java/org/wildfly/swarm/fractions/FractionDescriptor.java#L57-L91
ModeShape/modeshape
sequencers/modeshape-sequencer-java/src/main/java/org/modeshape/sequencer/javafile/AbstractJavaMetadata.java
AbstractJavaMetadata.processPrimitiveType
protected FieldMetadata processPrimitiveType( FieldDeclaration fieldDeclaration ) { """ Process the primitive type of a {@link FieldDeclaration}. @param fieldDeclaration - the field declaration. @return PrimitiveFieldMetadata. """ PrimitiveType primitiveType = (PrimitiveType)fieldDeclaration.getType(); FieldMetadata primitiveFieldMetadata = FieldMetadata.primitiveType(primitiveType.getPrimitiveTypeCode().toString()); primitiveFieldMetadata.setName(getFieldName(fieldDeclaration)); // modifiers processModifiersOfFieldDeclaration(fieldDeclaration, primitiveFieldMetadata); // variables processVariablesOfVariableDeclarationFragment(fieldDeclaration, primitiveFieldMetadata); return primitiveFieldMetadata; }
java
protected FieldMetadata processPrimitiveType( FieldDeclaration fieldDeclaration ) { PrimitiveType primitiveType = (PrimitiveType)fieldDeclaration.getType(); FieldMetadata primitiveFieldMetadata = FieldMetadata.primitiveType(primitiveType.getPrimitiveTypeCode().toString()); primitiveFieldMetadata.setName(getFieldName(fieldDeclaration)); // modifiers processModifiersOfFieldDeclaration(fieldDeclaration, primitiveFieldMetadata); // variables processVariablesOfVariableDeclarationFragment(fieldDeclaration, primitiveFieldMetadata); return primitiveFieldMetadata; }
[ "protected", "FieldMetadata", "processPrimitiveType", "(", "FieldDeclaration", "fieldDeclaration", ")", "{", "PrimitiveType", "primitiveType", "=", "(", "PrimitiveType", ")", "fieldDeclaration", ".", "getType", "(", ")", ";", "FieldMetadata", "primitiveFieldMetadata", "="...
Process the primitive type of a {@link FieldDeclaration}. @param fieldDeclaration - the field declaration. @return PrimitiveFieldMetadata.
[ "Process", "the", "primitive", "type", "of", "a", "{", "@link", "FieldDeclaration", "}", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-java/src/main/java/org/modeshape/sequencer/javafile/AbstractJavaMetadata.java#L633-L643
jbake-org/jbake
jbake-core/src/main/java/org/jbake/template/TemplateEngines.java
TemplateEngines.tryLoadEngine
private static AbstractTemplateEngine tryLoadEngine(final JBakeConfiguration config, final ContentStore db, String engineClassName) { """ This method is used to search for a specific class, telling if loading the engine would succeed. This is typically used to avoid loading optional modules. @param config the configuration @param db database instance @param engineClassName engine class, used both as a hint to find it and to create the engine itself. @return null if the engine is not available, an instance of the engine otherwise """ try { @SuppressWarnings("unchecked") Class<? extends AbstractTemplateEngine> engineClass = (Class<? extends AbstractTemplateEngine>) Class.forName(engineClassName, false, TemplateEngines.class.getClassLoader()); Constructor<? extends AbstractTemplateEngine> ctor = engineClass.getConstructor(JBakeConfiguration.class, ContentStore.class); return ctor.newInstance(config, db); } catch (Throwable e) { // not all engines might be necessary, therefore only emit class loading issue with level warn LOGGER.warn("unable to load engine", e); return null; } }
java
private static AbstractTemplateEngine tryLoadEngine(final JBakeConfiguration config, final ContentStore db, String engineClassName) { try { @SuppressWarnings("unchecked") Class<? extends AbstractTemplateEngine> engineClass = (Class<? extends AbstractTemplateEngine>) Class.forName(engineClassName, false, TemplateEngines.class.getClassLoader()); Constructor<? extends AbstractTemplateEngine> ctor = engineClass.getConstructor(JBakeConfiguration.class, ContentStore.class); return ctor.newInstance(config, db); } catch (Throwable e) { // not all engines might be necessary, therefore only emit class loading issue with level warn LOGGER.warn("unable to load engine", e); return null; } }
[ "private", "static", "AbstractTemplateEngine", "tryLoadEngine", "(", "final", "JBakeConfiguration", "config", ",", "final", "ContentStore", "db", ",", "String", "engineClassName", ")", "{", "try", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Class", "<"...
This method is used to search for a specific class, telling if loading the engine would succeed. This is typically used to avoid loading optional modules. @param config the configuration @param db database instance @param engineClassName engine class, used both as a hint to find it and to create the engine itself. @return null if the engine is not available, an instance of the engine otherwise
[ "This", "method", "is", "used", "to", "search", "for", "a", "specific", "class", "telling", "if", "loading", "the", "engine", "would", "succeed", ".", "This", "is", "typically", "used", "to", "avoid", "loading", "optional", "modules", "." ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/template/TemplateEngines.java#L74-L85
HubSpot/jinjava
src/main/java/com/hubspot/jinjava/Jinjava.java
Jinjava.renderForResult
public RenderResult renderForResult(String template, Map<String, ?> bindings) { """ Render the given template using the given context bindings. This method returns some metadata about the render process, including any errors which may have been encountered such as unknown variables or syntax errors. This method will not throw any exceptions; it is up to the caller to inspect the renderResult.errors collection if necessary / desired. @param template jinja source template @param bindings map of objects to put into scope for this rendering action @return result object containing rendered output, render context, and any encountered errors """ return renderForResult(template, bindings, globalConfig); }
java
public RenderResult renderForResult(String template, Map<String, ?> bindings) { return renderForResult(template, bindings, globalConfig); }
[ "public", "RenderResult", "renderForResult", "(", "String", "template", ",", "Map", "<", "String", ",", "?", ">", "bindings", ")", "{", "return", "renderForResult", "(", "template", ",", "bindings", ",", "globalConfig", ")", ";", "}" ]
Render the given template using the given context bindings. This method returns some metadata about the render process, including any errors which may have been encountered such as unknown variables or syntax errors. This method will not throw any exceptions; it is up to the caller to inspect the renderResult.errors collection if necessary / desired. @param template jinja source template @param bindings map of objects to put into scope for this rendering action @return result object containing rendered output, render context, and any encountered errors
[ "Render", "the", "given", "template", "using", "the", "given", "context", "bindings", ".", "This", "method", "returns", "some", "metadata", "about", "the", "render", "process", "including", "any", "errors", "which", "may", "have", "been", "encountered", "such", ...
train
https://github.com/HubSpot/jinjava/blob/ce570935630f49c666170d2330b0b9ba4eddb955/src/main/java/com/hubspot/jinjava/Jinjava.java#L173-L175
auth0/Auth0.Android
auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.java
AuthenticationAPIClient.loginWithPhoneNumber
@SuppressWarnings("WeakerAccess") public AuthenticationRequest loginWithPhoneNumber(@NonNull String phoneNumber, @NonNull String verificationCode, @NonNull String connection) { """ Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow) The default scope used is 'openid'. Requires your Application to have the <b>Resource Owner</b> Legacy Grant Type enabled. See <a href="https://auth0.com/docs/clients/client-grant-types">Client Grant Types</a> to learn how to enable it. Example usage: <pre> {@code client.loginWithPhoneNumber("{phone number}", "{code}", "{passwordless connection name}") .start(new BaseCallback<Credentials>() { {@literal}Override public void onSuccess(Credentials payload) { } {@literal}@Override public void onFailure(AuthenticationException error) { } }); } </pre> @param phoneNumber where the user received the verification code @param verificationCode sent by Auth0 via SMS @param connection to end the passwordless authentication on @return a request to configure and start that will yield {@link Credentials} """ Map<String, Object> parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, phoneNumber) .set(PASSWORD_KEY, verificationCode) .setGrantType(GRANT_TYPE_PASSWORD) .setClientId(getClientId()) .setConnection(connection) .asDictionary(); return loginWithResourceOwner(parameters); }
java
@SuppressWarnings("WeakerAccess") public AuthenticationRequest loginWithPhoneNumber(@NonNull String phoneNumber, @NonNull String verificationCode, @NonNull String connection) { Map<String, Object> parameters = ParameterBuilder.newAuthenticationBuilder() .set(USERNAME_KEY, phoneNumber) .set(PASSWORD_KEY, verificationCode) .setGrantType(GRANT_TYPE_PASSWORD) .setClientId(getClientId()) .setConnection(connection) .asDictionary(); return loginWithResourceOwner(parameters); }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "AuthenticationRequest", "loginWithPhoneNumber", "(", "@", "NonNull", "String", "phoneNumber", ",", "@", "NonNull", "String", "verificationCode", ",", "@", "NonNull", "String", "connection", ")", "{", ...
Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow) The default scope used is 'openid'. Requires your Application to have the <b>Resource Owner</b> Legacy Grant Type enabled. See <a href="https://auth0.com/docs/clients/client-grant-types">Client Grant Types</a> to learn how to enable it. Example usage: <pre> {@code client.loginWithPhoneNumber("{phone number}", "{code}", "{passwordless connection name}") .start(new BaseCallback<Credentials>() { {@literal}Override public void onSuccess(Credentials payload) { } {@literal}@Override public void onFailure(AuthenticationException error) { } }); } </pre> @param phoneNumber where the user received the verification code @param verificationCode sent by Auth0 via SMS @param connection to end the passwordless authentication on @return a request to configure and start that will yield {@link Credentials}
[ "Log", "in", "a", "user", "using", "a", "phone", "number", "and", "a", "verification", "code", "received", "via", "SMS", "(", "Part", "of", "passwordless", "login", "flow", ")", "The", "default", "scope", "used", "is", "openid", ".", "Requires", "your", ...
train
https://github.com/auth0/Auth0.Android/blob/ee37b7f94d989c1fbab2cb1378c87fdcaf7a8156/auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.java#L340-L350
SeaCloudsEU/SeaCloudsPlatform
deployer/src/main/java/org/apache/brooklyn/entity/cloudfoundry/CloudFoundryEntityImpl.java
CloudFoundryEntityImpl.disconnectServiceUpIsRunning
protected void disconnectServiceUpIsRunning() { """ For disconnecting the {@link #SERVICE_UP} feed. <p/> Should be called from {@link #disconnectSensors()}. @see #connectServiceUpIsRunning() """ if (serviceProcessIsRunning != null) serviceProcessIsRunning.stop(); // set null so the SERVICE_UP enricher runs (possibly removing it), then remove so // everything is removed // TODO race because the is-running check may be mid-task setAttribute(SERVICE_PROCESS_IS_RUNNING, null); removeAttribute(SERVICE_PROCESS_IS_RUNNING); }
java
protected void disconnectServiceUpIsRunning() { if (serviceProcessIsRunning != null) serviceProcessIsRunning.stop(); // set null so the SERVICE_UP enricher runs (possibly removing it), then remove so // everything is removed // TODO race because the is-running check may be mid-task setAttribute(SERVICE_PROCESS_IS_RUNNING, null); removeAttribute(SERVICE_PROCESS_IS_RUNNING); }
[ "protected", "void", "disconnectServiceUpIsRunning", "(", ")", "{", "if", "(", "serviceProcessIsRunning", "!=", "null", ")", "serviceProcessIsRunning", ".", "stop", "(", ")", ";", "// set null so the SERVICE_UP enricher runs (possibly removing it), then remove so", "// everythi...
For disconnecting the {@link #SERVICE_UP} feed. <p/> Should be called from {@link #disconnectSensors()}. @see #connectServiceUpIsRunning()
[ "For", "disconnecting", "the", "{", "@link", "#SERVICE_UP", "}", "feed", ".", "<p", "/", ">", "Should", "be", "called", "from", "{", "@link", "#disconnectSensors", "()", "}", "." ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/deployer/src/main/java/org/apache/brooklyn/entity/cloudfoundry/CloudFoundryEntityImpl.java#L381-L388
ksclarke/vertx-pairtree
src/main/java/info/freelibrary/pairtree/PairtreeFactory.java
PairtreeFactory.getPairtree
public Pairtree getPairtree(final String aBucket, final String aBucketPath) throws PairtreeException { """ Gets the S3 based Pairtree using the supplied S3 bucket and bucket path. @param aBucket An S3 bucket in which to create the Pairtree @param aBucketPath A path in the S3 bucket at which to put the Pairtree @return A Pairtree root @throws PairtreeException If there is trouble creating the Pairtree """ if (myAccessKey.isPresent() && mySecretKey.isPresent()) { final String accessKey = myAccessKey.get(); final String secretKey = mySecretKey.get(); if (myRegion.isPresent()) { return new S3Pairtree(myVertx, aBucket, aBucketPath, accessKey, secretKey, myRegion.get()); } else { return new S3Pairtree(myVertx, aBucket, aBucketPath, accessKey, secretKey); } } else { throw new PairtreeException(MessageCodes.PT_021); } }
java
public Pairtree getPairtree(final String aBucket, final String aBucketPath) throws PairtreeException { if (myAccessKey.isPresent() && mySecretKey.isPresent()) { final String accessKey = myAccessKey.get(); final String secretKey = mySecretKey.get(); if (myRegion.isPresent()) { return new S3Pairtree(myVertx, aBucket, aBucketPath, accessKey, secretKey, myRegion.get()); } else { return new S3Pairtree(myVertx, aBucket, aBucketPath, accessKey, secretKey); } } else { throw new PairtreeException(MessageCodes.PT_021); } }
[ "public", "Pairtree", "getPairtree", "(", "final", "String", "aBucket", ",", "final", "String", "aBucketPath", ")", "throws", "PairtreeException", "{", "if", "(", "myAccessKey", ".", "isPresent", "(", ")", "&&", "mySecretKey", ".", "isPresent", "(", ")", ")", ...
Gets the S3 based Pairtree using the supplied S3 bucket and bucket path. @param aBucket An S3 bucket in which to create the Pairtree @param aBucketPath A path in the S3 bucket at which to put the Pairtree @return A Pairtree root @throws PairtreeException If there is trouble creating the Pairtree
[ "Gets", "the", "S3", "based", "Pairtree", "using", "the", "supplied", "S3", "bucket", "and", "bucket", "path", "." ]
train
https://github.com/ksclarke/vertx-pairtree/blob/b2ea1e32057e5df262e9265540d346a732b718df/src/main/java/info/freelibrary/pairtree/PairtreeFactory.java#L140-L153
alkacon/opencms-core
src/org/opencms/file/CmsLinkRewriter.java
CmsLinkRewriter.getConfiguredEncoding
protected String getConfiguredEncoding(CmsObject cms, CmsResource resource) throws CmsException { """ Gets the encoding which is configured at the location of a given resource.<p> @param cms the current CMS context @param resource the resource for which the configured encoding should be retrieved @return the configured encoding for the resource @throws CmsException if something goes wrong """ String encoding = null; try { encoding = cms.readPropertyObject( resource.getRootPath(), CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(); } catch (CmsException e) { // encoding will be null } if (encoding == null) { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); } else { encoding = CmsEncoder.lookupEncoding(encoding, null); if (encoding == null) { throw new CmsXmlException( Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ENC_1, resource.getRootPath())); } } return encoding; }
java
protected String getConfiguredEncoding(CmsObject cms, CmsResource resource) throws CmsException { String encoding = null; try { encoding = cms.readPropertyObject( resource.getRootPath(), CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(); } catch (CmsException e) { // encoding will be null } if (encoding == null) { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); } else { encoding = CmsEncoder.lookupEncoding(encoding, null); if (encoding == null) { throw new CmsXmlException( Messages.get().container(Messages.ERR_XMLCONTENT_INVALID_ENC_1, resource.getRootPath())); } } return encoding; }
[ "protected", "String", "getConfiguredEncoding", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "String", "encoding", "=", "null", ";", "try", "{", "encoding", "=", "cms", ".", "readPropertyObject", "(", "resource", "...
Gets the encoding which is configured at the location of a given resource.<p> @param cms the current CMS context @param resource the resource for which the configured encoding should be retrieved @return the configured encoding for the resource @throws CmsException if something goes wrong
[ "Gets", "the", "encoding", "which", "is", "configured", "at", "the", "location", "of", "a", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsLinkRewriter.java#L402-L423
mboudreau/Alternator
src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java
DynamoDBMapper.setValue
private <T> void setValue(final T toReturn, final Method getter, AttributeValue value) { """ Sets the value in the return object corresponding to the service result. """ Method setter = reflector.getSetter(getter); ArgumentUnmarshaller unmarhsaller = reflector.getArgumentUnmarshaller(toReturn, getter, setter); unmarhsaller.typeCheck(value, setter); Object argument; try { argument = unmarhsaller.unmarshall(value); } catch ( IllegalArgumentException e ) { throw new DynamoDBMappingException("Couldn't unmarshall value " + value + " for " + setter, e); } catch ( ParseException e ) { throw new DynamoDBMappingException("Error attempting to parse date string " + value + " for "+ setter, e); } safeInvoke(setter, toReturn, argument); }
java
private <T> void setValue(final T toReturn, final Method getter, AttributeValue value) { Method setter = reflector.getSetter(getter); ArgumentUnmarshaller unmarhsaller = reflector.getArgumentUnmarshaller(toReturn, getter, setter); unmarhsaller.typeCheck(value, setter); Object argument; try { argument = unmarhsaller.unmarshall(value); } catch ( IllegalArgumentException e ) { throw new DynamoDBMappingException("Couldn't unmarshall value " + value + " for " + setter, e); } catch ( ParseException e ) { throw new DynamoDBMappingException("Error attempting to parse date string " + value + " for "+ setter, e); } safeInvoke(setter, toReturn, argument); }
[ "private", "<", "T", ">", "void", "setValue", "(", "final", "T", "toReturn", ",", "final", "Method", "getter", ",", "AttributeValue", "value", ")", "{", "Method", "setter", "=", "reflector", ".", "getSetter", "(", "getter", ")", ";", "ArgumentUnmarshaller", ...
Sets the value in the return object corresponding to the service result.
[ "Sets", "the", "value", "in", "the", "return", "object", "corresponding", "to", "the", "service", "result", "." ]
train
https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java#L339-L355
vdmeer/skb-java-base
src/main/java/de/vandermeer/skb/base/info/AbstractFileInfo.java
AbstractFileInfo.tryResource
protected final boolean tryResource(String directory, String fileName) { """ Try to locate a file as resource. @param directory a directory to locate the file in @param fileName a file name with optional path information @return true if the file was found, false otherwise """ String path = directory + "/" + fileName; if(directory==null){ path = fileName; } URL url; ClassLoader loader = Thread.currentThread().getContextClassLoader(); url = loader.getResource(path); if(url==null){ loader = AbstractFileInfo.class.getClassLoader(); url = loader.getResource(path); } if(url==null){ this.errors.addError("could not get Resource URL"); return false; } this.url = url; this.fullFileName = FilenameUtils.getName(fileName); if(directory!=null){ this.setRootPath = directory; } return true; }
java
protected final boolean tryResource(String directory, String fileName){ String path = directory + "/" + fileName; if(directory==null){ path = fileName; } URL url; ClassLoader loader = Thread.currentThread().getContextClassLoader(); url = loader.getResource(path); if(url==null){ loader = AbstractFileInfo.class.getClassLoader(); url = loader.getResource(path); } if(url==null){ this.errors.addError("could not get Resource URL"); return false; } this.url = url; this.fullFileName = FilenameUtils.getName(fileName); if(directory!=null){ this.setRootPath = directory; } return true; }
[ "protected", "final", "boolean", "tryResource", "(", "String", "directory", ",", "String", "fileName", ")", "{", "String", "path", "=", "directory", "+", "\"/\"", "+", "fileName", ";", "if", "(", "directory", "==", "null", ")", "{", "path", "=", "fileName"...
Try to locate a file as resource. @param directory a directory to locate the file in @param fileName a file name with optional path information @return true if the file was found, false otherwise
[ "Try", "to", "locate", "a", "file", "as", "resource", "." ]
train
https://github.com/vdmeer/skb-java-base/blob/6d845bcc482aa9344d016e80c0c3455aeae13a13/src/main/java/de/vandermeer/skb/base/info/AbstractFileInfo.java#L357-L383
playn/playn
core/src/playn/core/TextBlock.java
TextBlock.getBounds
public static Rectangle getBounds(TextLayout[] lines, Rectangle into) { """ Computes the bounds of a block of text. The {@code x} component of the bounds may be positive, indicating that the text should be rendered at that offset. This is to account for the fact that some text renders to the left of its reported origin due to font extravagance. """ // some font glyphs start rendering at a negative inset, blowing outside their bounding box // (naughty!); in such cases, we use xAdjust to shift everything to the right to ensure that we // don't paint outside our reported bounding box (so that someone can create a single canvas of // bounding box size and render this text layout into it at (0,0) and nothing will get cut off) float xAdjust = 0, twidth = 0, theight = 0; for (TextLayout layout : lines) { IRectangle bounds = layout.bounds; xAdjust = Math.max(xAdjust, -Math.min(0, bounds.x())); // we use layout.width() here not bounds width because layout width includes extra space // needed for lines that start rendering at a positive x offset whereas bounds.width() is // only the precise width of the rendered text twidth = Math.max(twidth, layout.size.width()); if (layout != lines[0]) theight += layout.leading(); // leading only applied to lines after 0 theight += layout.ascent() + layout.descent(); } into.setBounds(xAdjust, 0, xAdjust+twidth, theight); return into; }
java
public static Rectangle getBounds(TextLayout[] lines, Rectangle into) { // some font glyphs start rendering at a negative inset, blowing outside their bounding box // (naughty!); in such cases, we use xAdjust to shift everything to the right to ensure that we // don't paint outside our reported bounding box (so that someone can create a single canvas of // bounding box size and render this text layout into it at (0,0) and nothing will get cut off) float xAdjust = 0, twidth = 0, theight = 0; for (TextLayout layout : lines) { IRectangle bounds = layout.bounds; xAdjust = Math.max(xAdjust, -Math.min(0, bounds.x())); // we use layout.width() here not bounds width because layout width includes extra space // needed for lines that start rendering at a positive x offset whereas bounds.width() is // only the precise width of the rendered text twidth = Math.max(twidth, layout.size.width()); if (layout != lines[0]) theight += layout.leading(); // leading only applied to lines after 0 theight += layout.ascent() + layout.descent(); } into.setBounds(xAdjust, 0, xAdjust+twidth, theight); return into; }
[ "public", "static", "Rectangle", "getBounds", "(", "TextLayout", "[", "]", "lines", ",", "Rectangle", "into", ")", "{", "// some font glyphs start rendering at a negative inset, blowing outside their bounding box", "// (naughty!); in such cases, we use xAdjust to shift everything to th...
Computes the bounds of a block of text. The {@code x} component of the bounds may be positive, indicating that the text should be rendered at that offset. This is to account for the fact that some text renders to the left of its reported origin due to font extravagance.
[ "Computes", "the", "bounds", "of", "a", "block", "of", "text", ".", "The", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/TextBlock.java#L69-L88
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/Version.java
Version.with
public Version with(Qualifier qualifier, int qualifierNumber) { """ Sets the {@link Version.Qualifier} for this {@link Version}. @param qualifier {@link Version.Qualifier}. @param qualifierNumber {@link Version.Qualifier} number. @return this {@link Version} reference. """ this.qualifier = defaultIfNull(qualifier, Qualifier.UNDEFINED); this.qualifierNumber = Math.max(qualifierNumber, 0); return this; }
java
public Version with(Qualifier qualifier, int qualifierNumber) { this.qualifier = defaultIfNull(qualifier, Qualifier.UNDEFINED); this.qualifierNumber = Math.max(qualifierNumber, 0); return this; }
[ "public", "Version", "with", "(", "Qualifier", "qualifier", ",", "int", "qualifierNumber", ")", "{", "this", ".", "qualifier", "=", "defaultIfNull", "(", "qualifier", ",", "Qualifier", ".", "UNDEFINED", ")", ";", "this", ".", "qualifierNumber", "=", "Math", ...
Sets the {@link Version.Qualifier} for this {@link Version}. @param qualifier {@link Version.Qualifier}. @param qualifierNumber {@link Version.Qualifier} number. @return this {@link Version} reference.
[ "Sets", "the", "{", "@link", "Version", ".", "Qualifier", "}", "for", "this", "{", "@link", "Version", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Version.java#L616-L620
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/base/Json.java
Json.resource_to_string
public String resource_to_string(base_resource resrc, options option) { """ Converts NetScaler SDX resource to Json string. @param resrc API resource. @param option options class object. @return returns a String """ String result = "{ "; if (option != null && option.get_action() != null) result = result + "\"params\": {\"action\":\"" + option.get_action() + "\"},"; result = result + "\"" + resrc.get_object_type() + "\":" + this.resource_to_string(resrc) + "}"; return result; }
java
public String resource_to_string(base_resource resrc, options option) { String result = "{ "; if (option != null && option.get_action() != null) result = result + "\"params\": {\"action\":\"" + option.get_action() + "\"},"; result = result + "\"" + resrc.get_object_type() + "\":" + this.resource_to_string(resrc) + "}"; return result; }
[ "public", "String", "resource_to_string", "(", "base_resource", "resrc", ",", "options", "option", ")", "{", "String", "result", "=", "\"{ \"", ";", "if", "(", "option", "!=", "null", "&&", "option", ".", "get_action", "(", ")", "!=", "null", ")", "result"...
Converts NetScaler SDX resource to Json string. @param resrc API resource. @param option options class object. @return returns a String
[ "Converts", "NetScaler", "SDX", "resource", "to", "Json", "string", "." ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/base/Json.java#L64-L72
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_clusternode_binding.java
clusterinstance_clusternode_binding.count_filtered
public static long count_filtered(nitro_service service, Long clid, String filter) throws Exception { """ Use this API to count the filtered set of clusterinstance_clusternode_binding resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ clusterinstance_clusternode_binding obj = new clusterinstance_clusternode_binding(); obj.set_clid(clid); options option = new options(); option.set_count(true); option.set_filter(filter); clusterinstance_clusternode_binding[] response = (clusterinstance_clusternode_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; }
java
public static long count_filtered(nitro_service service, Long clid, String filter) throws Exception{ clusterinstance_clusternode_binding obj = new clusterinstance_clusternode_binding(); obj.set_clid(clid); options option = new options(); option.set_count(true); option.set_filter(filter); clusterinstance_clusternode_binding[] response = (clusterinstance_clusternode_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; }
[ "public", "static", "long", "count_filtered", "(", "nitro_service", "service", ",", "Long", "clid", ",", "String", "filter", ")", "throws", "Exception", "{", "clusterinstance_clusternode_binding", "obj", "=", "new", "clusterinstance_clusternode_binding", "(", ")", ";"...
Use this API to count the filtered set of clusterinstance_clusternode_binding resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
[ "Use", "this", "API", "to", "count", "the", "filtered", "set", "of", "clusterinstance_clusternode_binding", "resources", ".", "filter", "string", "should", "be", "in", "JSON", "format", ".", "eg", ":", "port", ":", "80", "servicetype", ":", "HTTP", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/cluster/clusterinstance_clusternode_binding.java#L285-L296
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/SimpleResourceDefinition.java
SimpleResourceDefinition.registerAddOperation
protected void registerAddOperation(final ManagementResourceRegistration registration, final AbstractAddStepHandler handler, OperationEntry.Flag... flags) { """ Registers add operation <p/> Registers add operation @param registration resource on which to register @param handler operation handler to register @param flags with flags """ registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD, new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild), OperationEntry.EntryType.PUBLIC, flags) , handler); }
java
protected void registerAddOperation(final ManagementResourceRegistration registration, final AbstractAddStepHandler handler, OperationEntry.Flag... flags) { registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD, new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild), OperationEntry.EntryType.PUBLIC, flags) , handler); }
[ "protected", "void", "registerAddOperation", "(", "final", "ManagementResourceRegistration", "registration", ",", "final", "AbstractAddStepHandler", "handler", ",", "OperationEntry", ".", "Flag", "...", "flags", ")", "{", "registration", ".", "registerOperationHandler", "...
Registers add operation <p/> Registers add operation @param registration resource on which to register @param handler operation handler to register @param flags with flags
[ "Registers", "add", "operation", "<p", "/", ">", "Registers", "add", "operation" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/SimpleResourceDefinition.java#L450-L455
jmrozanec/cron-utils
src/main/java/com/cronutils/parser/FieldParser.java
FieldParser.stringToInt
@VisibleForTesting protected int stringToInt(final String exp) { """ Maps string expression to integer. If no mapping is found, will try to parse String as Integer @param exp - expression to be mapped @return integer value for string expression """ final Integer value = fieldConstraints.getStringMappingValue(exp); if (value != null) { return value; } else { try { return Integer.parseInt(exp); } catch (final NumberFormatException e) { final String invalidChars = new StringValidations(fieldConstraints).removeValidChars(exp); throw new IllegalArgumentException(String.format("Invalid chars in expression! Expression: %s Invalid chars: %s", exp, invalidChars)); } } }
java
@VisibleForTesting protected int stringToInt(final String exp) { final Integer value = fieldConstraints.getStringMappingValue(exp); if (value != null) { return value; } else { try { return Integer.parseInt(exp); } catch (final NumberFormatException e) { final String invalidChars = new StringValidations(fieldConstraints).removeValidChars(exp); throw new IllegalArgumentException(String.format("Invalid chars in expression! Expression: %s Invalid chars: %s", exp, invalidChars)); } } }
[ "@", "VisibleForTesting", "protected", "int", "stringToInt", "(", "final", "String", "exp", ")", "{", "final", "Integer", "value", "=", "fieldConstraints", ".", "getStringMappingValue", "(", "exp", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "retur...
Maps string expression to integer. If no mapping is found, will try to parse String as Integer @param exp - expression to be mapped @return integer value for string expression
[ "Maps", "string", "expression", "to", "integer", ".", "If", "no", "mapping", "is", "found", "will", "try", "to", "parse", "String", "as", "Integer" ]
train
https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/parser/FieldParser.java#L259-L272
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/xpath/XPathHelper.java
XPathHelper.createNewXPath
@Nonnull public static XPath createNewXPath (@Nonnull final XPathFactory aXPathFactory, @Nullable final XPathFunctionResolver aFunctionResolver) { """ Create a new {@link XPath} with the passed function resolver. @param aXPathFactory The XPath factory object to use. May not be <code>null</code>. @param aFunctionResolver Function resolver to be used. May be <code>null</code>. @return The created non-<code>null</code> {@link XPath} object """ return createNewXPath (aXPathFactory, (XPathVariableResolver) null, aFunctionResolver, (NamespaceContext) null); }
java
@Nonnull public static XPath createNewXPath (@Nonnull final XPathFactory aXPathFactory, @Nullable final XPathFunctionResolver aFunctionResolver) { return createNewXPath (aXPathFactory, (XPathVariableResolver) null, aFunctionResolver, (NamespaceContext) null); }
[ "@", "Nonnull", "public", "static", "XPath", "createNewXPath", "(", "@", "Nonnull", "final", "XPathFactory", "aXPathFactory", ",", "@", "Nullable", "final", "XPathFunctionResolver", "aFunctionResolver", ")", "{", "return", "createNewXPath", "(", "aXPathFactory", ",", ...
Create a new {@link XPath} with the passed function resolver. @param aXPathFactory The XPath factory object to use. May not be <code>null</code>. @param aFunctionResolver Function resolver to be used. May be <code>null</code>. @return The created non-<code>null</code> {@link XPath} object
[ "Create", "a", "new", "{", "@link", "XPath", "}", "with", "the", "passed", "function", "resolver", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/xpath/XPathHelper.java#L193-L198
VoltDB/voltdb
third_party/java/src/org/apache/commons_voltpatches/cli/OptionGroup.java
OptionGroup.setSelected
public void setSelected(Option option) throws AlreadySelectedException { """ Set the selected option of this group to <code>name</code>. @param option the option that is selected @throws AlreadySelectedException if an option from this group has already been selected. """ if (option == null) { // reset the option previously selected selected = null; return; } // if no option has already been selected or the // same option is being reselected then set the // selected member variable if (selected == null || selected.equals(option.getKey())) { selected = option.getKey(); } else { throw new AlreadySelectedException(this, option); } }
java
public void setSelected(Option option) throws AlreadySelectedException { if (option == null) { // reset the option previously selected selected = null; return; } // if no option has already been selected or the // same option is being reselected then set the // selected member variable if (selected == null || selected.equals(option.getKey())) { selected = option.getKey(); } else { throw new AlreadySelectedException(this, option); } }
[ "public", "void", "setSelected", "(", "Option", "option", ")", "throws", "AlreadySelectedException", "{", "if", "(", "option", "==", "null", ")", "{", "// reset the option previously selected", "selected", "=", "null", ";", "return", ";", "}", "// if no option has a...
Set the selected option of this group to <code>name</code>. @param option the option that is selected @throws AlreadySelectedException if an option from this group has already been selected.
[ "Set", "the", "selected", "option", "of", "this", "group", "to", "<code", ">", "name<", "/", "code", ">", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/OptionGroup.java#L86-L106
azkaban/azkaban
az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopJobUtils.java
HadoopJobUtils.loadHadoopSecurityManager
public static HadoopSecurityManager loadHadoopSecurityManager(Props props, Logger log) throws RuntimeException { """ Based on the HADOOP_SECURITY_MANAGER_CLASS_PARAM setting in the incoming props, finds the correct HadoopSecurityManager Java class @return a HadoopSecurityManager object. Will throw exception if any errors occur (including not finding a class) @throws RuntimeException : If any errors happen along the way. """ Class<?> hadoopSecurityManagerClass = props.getClass(HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, HadoopJobUtils.class.getClassLoader()); log.info("Loading hadoop security manager " + hadoopSecurityManagerClass.getName()); HadoopSecurityManager hadoopSecurityManager = null; try { Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class); hadoopSecurityManager = (HadoopSecurityManager) getInstanceMethod.invoke( hadoopSecurityManagerClass, props); } catch (InvocationTargetException e) { String errMsg = "Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause(); log.error(errMsg); throw new RuntimeException(errMsg, e); } catch (Exception e) { throw new RuntimeException(e); } return hadoopSecurityManager; }
java
public static HadoopSecurityManager loadHadoopSecurityManager(Props props, Logger log) throws RuntimeException { Class<?> hadoopSecurityManagerClass = props.getClass(HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, HadoopJobUtils.class.getClassLoader()); log.info("Loading hadoop security manager " + hadoopSecurityManagerClass.getName()); HadoopSecurityManager hadoopSecurityManager = null; try { Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class); hadoopSecurityManager = (HadoopSecurityManager) getInstanceMethod.invoke( hadoopSecurityManagerClass, props); } catch (InvocationTargetException e) { String errMsg = "Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause(); log.error(errMsg); throw new RuntimeException(errMsg, e); } catch (Exception e) { throw new RuntimeException(e); } return hadoopSecurityManager; }
[ "public", "static", "HadoopSecurityManager", "loadHadoopSecurityManager", "(", "Props", "props", ",", "Logger", "log", ")", "throws", "RuntimeException", "{", "Class", "<", "?", ">", "hadoopSecurityManagerClass", "=", "props", ".", "getClass", "(", "HADOOP_SECURITY_MA...
Based on the HADOOP_SECURITY_MANAGER_CLASS_PARAM setting in the incoming props, finds the correct HadoopSecurityManager Java class @return a HadoopSecurityManager object. Will throw exception if any errors occur (including not finding a class) @throws RuntimeException : If any errors happen along the way.
[ "Based", "on", "the", "HADOOP_SECURITY_MANAGER_CLASS_PARAM", "setting", "in", "the", "incoming", "props", "finds", "the", "correct", "HadoopSecurityManager", "Java", "class" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/HadoopJobUtils.java#L119-L141
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherFactory.java
HystrixMetricsPublisherFactory.createOrRetrievePublisherForThreadPool
public static HystrixMetricsPublisherThreadPool createOrRetrievePublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) { """ Get an instance of {@link HystrixMetricsPublisherThreadPool} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixThreadPool} instance. @param threadPoolKey Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation @param metrics Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation @param properties Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation @return {@link HystrixMetricsPublisherThreadPool} instance """ return SINGLETON.getPublisherForThreadPool(threadPoolKey, metrics, properties); }
java
public static HystrixMetricsPublisherThreadPool createOrRetrievePublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) { return SINGLETON.getPublisherForThreadPool(threadPoolKey, metrics, properties); }
[ "public", "static", "HystrixMetricsPublisherThreadPool", "createOrRetrievePublisherForThreadPool", "(", "HystrixThreadPoolKey", "threadPoolKey", ",", "HystrixThreadPoolMetrics", "metrics", ",", "HystrixThreadPoolProperties", "properties", ")", "{", "return", "SINGLETON", ".", "ge...
Get an instance of {@link HystrixMetricsPublisherThreadPool} with the given factory {@link HystrixMetricsPublisher} implementation for each {@link HystrixThreadPool} instance. @param threadPoolKey Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation @param metrics Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation @param properties Pass-thru to {@link HystrixMetricsPublisher#getMetricsPublisherForThreadPool} implementation @return {@link HystrixMetricsPublisherThreadPool} instance
[ "Get", "an", "instance", "of", "{", "@link", "HystrixMetricsPublisherThreadPool", "}", "with", "the", "given", "factory", "{", "@link", "HystrixMetricsPublisher", "}", "implementation", "for", "each", "{", "@link", "HystrixThreadPool", "}", "instance", "." ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherFactory.java#L63-L65
assertthat/selenium-shutterbug
src/main/java/com/assertthat/selenium_shutterbug/core/PageSnapshot.java
PageSnapshot.highlightWithText
public PageSnapshot highlightWithText(WebElement element, Color elementColor, int lineWidth, String text, Color textColor, Font textFont) { """ Highlight WebElement within the page, same as in {@link #highlight(WebElement)} but providing ability to override default color, font values. @param element WebElement to be highlighted @param elementColor element highlight color @param lineWidth line width around the element @param text text to be placed above the highlighted element @param textColor color of the text @param textFont text font @return instance of type PageSnapshot """ try { highlight(element, elementColor, 0); Coordinates coords = new Coordinates(element, devicePixelRatio); image = ImageProcessor.addText(image, coords.getX(), coords.getY() - textFont.getSize() / 2, text, textColor, textFont); } catch (RasterFormatException rfe) { throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE, rfe); } return this; }
java
public PageSnapshot highlightWithText(WebElement element, Color elementColor, int lineWidth, String text, Color textColor, Font textFont) { try { highlight(element, elementColor, 0); Coordinates coords = new Coordinates(element, devicePixelRatio); image = ImageProcessor.addText(image, coords.getX(), coords.getY() - textFont.getSize() / 2, text, textColor, textFont); } catch (RasterFormatException rfe) { throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE, rfe); } return this; }
[ "public", "PageSnapshot", "highlightWithText", "(", "WebElement", "element", ",", "Color", "elementColor", ",", "int", "lineWidth", ",", "String", "text", ",", "Color", "textColor", ",", "Font", "textFont", ")", "{", "try", "{", "highlight", "(", "element", ",...
Highlight WebElement within the page, same as in {@link #highlight(WebElement)} but providing ability to override default color, font values. @param element WebElement to be highlighted @param elementColor element highlight color @param lineWidth line width around the element @param text text to be placed above the highlighted element @param textColor color of the text @param textFont text font @return instance of type PageSnapshot
[ "Highlight", "WebElement", "within", "the", "page", "same", "as", "in", "{", "@link", "#highlight", "(", "WebElement", ")", "}", "but", "providing", "ability", "to", "override", "default", "color", "font", "values", "." ]
train
https://github.com/assertthat/selenium-shutterbug/blob/770d9b92423200d262c9ab70e40405921d81e262/src/main/java/com/assertthat/selenium_shutterbug/core/PageSnapshot.java#L92-L101
openengsb/openengsb
components/ekb/graphdb-orient/src/main/java/org/openengsb/core/ekb/graph/orient/internal/OrientModelGraph.java
OrientModelGraph.alreadyVisited
private boolean alreadyVisited(ODocument neighbor, ODocument[] steps) { """ Checks if a model is already visited in the path search algorithm. Needed for the loop detection. """ for (ODocument step : steps) { ODocument out = graph.getOutVertex(step); if (out.equals(neighbor)) { return true; } } return false; }
java
private boolean alreadyVisited(ODocument neighbor, ODocument[] steps) { for (ODocument step : steps) { ODocument out = graph.getOutVertex(step); if (out.equals(neighbor)) { return true; } } return false; }
[ "private", "boolean", "alreadyVisited", "(", "ODocument", "neighbor", ",", "ODocument", "[", "]", "steps", ")", "{", "for", "(", "ODocument", "step", ":", "steps", ")", "{", "ODocument", "out", "=", "graph", ".", "getOutVertex", "(", "step", ")", ";", "i...
Checks if a model is already visited in the path search algorithm. Needed for the loop detection.
[ "Checks", "if", "a", "model", "is", "already", "visited", "in", "the", "path", "search", "algorithm", ".", "Needed", "for", "the", "loop", "detection", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/graphdb-orient/src/main/java/org/openengsb/core/ekb/graph/orient/internal/OrientModelGraph.java#L362-L370
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java
RatelimitManager.calculateOffset
private void calculateOffset(long currentTime, RestRequestResult result) { """ Calculates the offset of the local time and discord's time. @param currentTime The current time. @param result The result of the rest request. """ // Double-checked locking for better performance if ((api.getTimeOffset() != null) || (result == null) || (result.getResponse() == null)) { return; } synchronized (api) { if (api.getTimeOffset() == null) { // Discord sends the date in their header in the format RFC_1123_DATE_TIME // We use this header to calculate a possible offset between our local time and the discord time String date = result.getResponse().header("Date"); if (date != null) { long discordTimestamp = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME) .toInstant().toEpochMilli(); api.setTimeOffset((discordTimestamp - currentTime)); logger.debug("Calculated an offset of {} to the Discord time.", api::getTimeOffset); } } } }
java
private void calculateOffset(long currentTime, RestRequestResult result) { // Double-checked locking for better performance if ((api.getTimeOffset() != null) || (result == null) || (result.getResponse() == null)) { return; } synchronized (api) { if (api.getTimeOffset() == null) { // Discord sends the date in their header in the format RFC_1123_DATE_TIME // We use this header to calculate a possible offset between our local time and the discord time String date = result.getResponse().header("Date"); if (date != null) { long discordTimestamp = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME) .toInstant().toEpochMilli(); api.setTimeOffset((discordTimestamp - currentTime)); logger.debug("Calculated an offset of {} to the Discord time.", api::getTimeOffset); } } } }
[ "private", "void", "calculateOffset", "(", "long", "currentTime", ",", "RestRequestResult", "result", ")", "{", "// Double-checked locking for better performance", "if", "(", "(", "api", ".", "getTimeOffset", "(", ")", "!=", "null", ")", "||", "(", "result", "==",...
Calculates the offset of the local time and discord's time. @param currentTime The current time. @param result The result of the rest request.
[ "Calculates", "the", "offset", "of", "the", "local", "time", "and", "discord", "s", "time", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java#L212-L230
VoltDB/voltdb
src/frontend/org/voltdb/export/processors/GuestProcessor.java
GuestProcessor.extractCommittedSpHandle
private long extractCommittedSpHandle(ExportRow row, long committedSeqNo) { """ If the row is the last committed row, return the SpHandle, otherwise return 0 @param row the export row @param committedSeqNo the sequence number of the last committed row @return """ long ret = 0; if (committedSeqNo == ExportDataSource.NULL_COMMITTED_SEQNO) { return ret; } // Get the rows's sequence number (3rd column) long seqNo = (long) row.values[2]; if (seqNo != committedSeqNo) { return ret; } // Get the row's sp handle (1rst column) ret = (long) row.values[0]; return ret; }
java
private long extractCommittedSpHandle(ExportRow row, long committedSeqNo) { long ret = 0; if (committedSeqNo == ExportDataSource.NULL_COMMITTED_SEQNO) { return ret; } // Get the rows's sequence number (3rd column) long seqNo = (long) row.values[2]; if (seqNo != committedSeqNo) { return ret; } // Get the row's sp handle (1rst column) ret = (long) row.values[0]; return ret; }
[ "private", "long", "extractCommittedSpHandle", "(", "ExportRow", "row", ",", "long", "committedSeqNo", ")", "{", "long", "ret", "=", "0", ";", "if", "(", "committedSeqNo", "==", "ExportDataSource", ".", "NULL_COMMITTED_SEQNO", ")", "{", "return", "ret", ";", "...
If the row is the last committed row, return the SpHandle, otherwise return 0 @param row the export row @param committedSeqNo the sequence number of the last committed row @return
[ "If", "the", "row", "is", "the", "last", "committed", "row", "return", "the", "SpHandle", "otherwise", "return", "0" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/export/processors/GuestProcessor.java#L506-L521
looly/hutool
hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java
CollUtil.getFieldValues
public static List<Object> getFieldValues(Iterable<?> collection, final String fieldName, boolean ignoreNull) { """ 获取给定Bean列表中指定字段名对应字段值的列表<br> 列表元素支持Bean与Map @param collection Bean集合或Map集合 @param fieldName 字段名或map的键 @param ignoreNull 是否忽略值为{@code null}的字段 @return 字段值列表 @since 4.5.7 """ return extract(collection, new Editor<Object>() { @Override public Object edit(Object bean) { if (bean instanceof Map) { return ((Map<?, ?>) bean).get(fieldName); } else { return ReflectUtil.getFieldValue(bean, fieldName); } } }, ignoreNull); }
java
public static List<Object> getFieldValues(Iterable<?> collection, final String fieldName, boolean ignoreNull) { return extract(collection, new Editor<Object>() { @Override public Object edit(Object bean) { if (bean instanceof Map) { return ((Map<?, ?>) bean).get(fieldName); } else { return ReflectUtil.getFieldValue(bean, fieldName); } } }, ignoreNull); }
[ "public", "static", "List", "<", "Object", ">", "getFieldValues", "(", "Iterable", "<", "?", ">", "collection", ",", "final", "String", "fieldName", ",", "boolean", "ignoreNull", ")", "{", "return", "extract", "(", "collection", ",", "new", "Editor", "<", ...
获取给定Bean列表中指定字段名对应字段值的列表<br> 列表元素支持Bean与Map @param collection Bean集合或Map集合 @param fieldName 字段名或map的键 @param ignoreNull 是否忽略值为{@code null}的字段 @return 字段值列表 @since 4.5.7
[ "获取给定Bean列表中指定字段名对应字段值的列表<br", ">", "列表元素支持Bean与Map" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java#L1173-L1184
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java
ExpressRouteCircuitsInner.beginListRoutesTableSummaryAsync
public Observable<ExpressRouteCircuitsRoutesTableSummaryListResultInner> beginListRoutesTableSummaryAsync(String resourceGroupName, String circuitName, String peeringName, String devicePath) { """ Gets the currently advertised routes table summary associated with the express route circuit in a resource group. @param resourceGroupName The name of the resource group. @param circuitName The name of the express route circuit. @param peeringName The name of the peering. @param devicePath The path of the device. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteCircuitsRoutesTableSummaryListResultInner object """ return beginListRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCircuitsRoutesTableSummaryListResultInner>, ExpressRouteCircuitsRoutesTableSummaryListResultInner>() { @Override public ExpressRouteCircuitsRoutesTableSummaryListResultInner call(ServiceResponse<ExpressRouteCircuitsRoutesTableSummaryListResultInner> response) { return response.body(); } }); }
java
public Observable<ExpressRouteCircuitsRoutesTableSummaryListResultInner> beginListRoutesTableSummaryAsync(String resourceGroupName, String circuitName, String peeringName, String devicePath) { return beginListRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCircuitsRoutesTableSummaryListResultInner>, ExpressRouteCircuitsRoutesTableSummaryListResultInner>() { @Override public ExpressRouteCircuitsRoutesTableSummaryListResultInner call(ServiceResponse<ExpressRouteCircuitsRoutesTableSummaryListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExpressRouteCircuitsRoutesTableSummaryListResultInner", ">", "beginListRoutesTableSummaryAsync", "(", "String", "resourceGroupName", ",", "String", "circuitName", ",", "String", "peeringName", ",", "String", "devicePath", ")", "{", "return", "b...
Gets the currently advertised routes table summary associated with the express route circuit in a resource group. @param resourceGroupName The name of the resource group. @param circuitName The name of the express route circuit. @param peeringName The name of the peering. @param devicePath The path of the device. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteCircuitsRoutesTableSummaryListResultInner object
[ "Gets", "the", "currently", "advertised", "routes", "table", "summary", "associated", "with", "the", "express", "route", "circuit", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java#L1348-L1355
blackdoor/blackdoor
src/main/java/black/door/struct/GenericMap.java
GenericMap.get
public <T> T get(String key, Class<T> type) { """ Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.) @param key @param type @return the value to which the specified key is mapped, or null if this map contains no mapping for the key """ return type.cast(grab(key)); }
java
public <T> T get(String key, Class<T> type) { return type.cast(grab(key)); }
[ "public", "<", "T", ">", "T", "get", "(", "String", "key", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "type", ".", "cast", "(", "grab", "(", "key", ")", ")", ";", "}" ]
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.) @param key @param type @return the value to which the specified key is mapped, or null if this map contains no mapping for the key
[ "Returns", "the", "value", "to", "which", "the", "specified", "key", "is", "mapped", "or", "null", "if", "this", "map", "contains", "no", "mapping", "for", "the", "key", ".", "More", "formally", "if", "this", "map", "contains", "a", "mapping", "from", "a...
train
https://github.com/blackdoor/blackdoor/blob/060c7a71dfafb85e10e8717736e6d3160262e96b/src/main/java/black/door/struct/GenericMap.java#L89-L91
alkacon/opencms-core
src/org/opencms/main/CmsEventManager.java
CmsEventManager.fireEvent
public void fireEvent(int type, Map<String, Object> data) { """ Notify all event listeners that a particular event has occurred.<p> @param type event type @param data event data """ fireEvent(new CmsEvent(type, data)); }
java
public void fireEvent(int type, Map<String, Object> data) { fireEvent(new CmsEvent(type, data)); }
[ "public", "void", "fireEvent", "(", "int", "type", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "{", "fireEvent", "(", "new", "CmsEvent", "(", "type", ",", "data", ")", ")", ";", "}" ]
Notify all event listeners that a particular event has occurred.<p> @param type event type @param data event data
[ "Notify", "all", "event", "listeners", "that", "a", "particular", "event", "has", "occurred", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsEventManager.java#L137-L140
facebookarchive/hadoop-20
src/core/org/apache/hadoop/net/NetUtils.java
NetUtils.getOutputStream
public static OutputStream getOutputStream(Socket socket, long timeout) throws IOException { """ Returns OutputStream for the socket. If the socket has an associated SocketChannel then it returns a {@link SocketOutputStream} with the given timeout. If the socket does not have a channel, {@link Socket#getOutputStream()} is returned. In the later case, the timeout argument is ignored and the write will wait until data is available.<br><br> Any socket created using socket factories returned by {@link #NetUtils}, must use this interface instead of {@link Socket#getOutputStream()}. @see Socket#getChannel() @param socket @param timeout timeout in milliseconds. This may not always apply. zero for waiting as long as necessary. @return OutputStream for writing to the socket. @throws IOException """ return (socket.getChannel() == null) ? socket.getOutputStream() : new SocketOutputStream(socket, timeout); }
java
public static OutputStream getOutputStream(Socket socket, long timeout) throws IOException { return (socket.getChannel() == null) ? socket.getOutputStream() : new SocketOutputStream(socket, timeout); }
[ "public", "static", "OutputStream", "getOutputStream", "(", "Socket", "socket", ",", "long", "timeout", ")", "throws", "IOException", "{", "return", "(", "socket", ".", "getChannel", "(", ")", "==", "null", ")", "?", "socket", ".", "getOutputStream", "(", ")...
Returns OutputStream for the socket. If the socket has an associated SocketChannel then it returns a {@link SocketOutputStream} with the given timeout. If the socket does not have a channel, {@link Socket#getOutputStream()} is returned. In the later case, the timeout argument is ignored and the write will wait until data is available.<br><br> Any socket created using socket factories returned by {@link #NetUtils}, must use this interface instead of {@link Socket#getOutputStream()}. @see Socket#getChannel() @param socket @param timeout timeout in milliseconds. This may not always apply. zero for waiting as long as necessary. @return OutputStream for writing to the socket. @throws IOException
[ "Returns", "OutputStream", "for", "the", "socket", ".", "If", "the", "socket", "has", "an", "associated", "SocketChannel", "then", "it", "returns", "a", "{", "@link", "SocketOutputStream", "}", "with", "the", "given", "timeout", ".", "If", "the", "socket", "...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/net/NetUtils.java#L390-L394
carewebframework/carewebframework-core
org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/render/AbstractRenderer.java
AbstractRenderer.createLabel
public Label createLabel(BaseComponent parent, Object value) { """ Creates a label for a string value. @param parent BaseComponent that will be the parent of the label. @param value Value to be used as label text. @return The newly created label. """ return createLabel(parent, value, null, null); }
java
public Label createLabel(BaseComponent parent, Object value) { return createLabel(parent, value, null, null); }
[ "public", "Label", "createLabel", "(", "BaseComponent", "parent", ",", "Object", "value", ")", "{", "return", "createLabel", "(", "parent", ",", "value", ",", "null", ",", "null", ")", ";", "}" ]
Creates a label for a string value. @param parent BaseComponent that will be the parent of the label. @param value Value to be used as label text. @return The newly created label.
[ "Creates", "a", "label", "for", "a", "string", "value", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/render/AbstractRenderer.java#L75-L77
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java
AccountsInner.addStorageAccount
public void addStorageAccount(String resourceGroupName, String accountName, String storageAccountName, AddStorageAccountParameters parameters) { """ Updates the specified Data Lake Analytics account to add an Azure Storage account. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account. @param accountName The name of the Data Lake Analytics account to which to add the Azure Storage account. @param storageAccountName The name of the Azure Storage account to add @param parameters The parameters containing the access key and optional suffix for the Azure Storage Account. @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 """ addStorageAccountWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName, parameters).toBlocking().single().body(); }
java
public void addStorageAccount(String resourceGroupName, String accountName, String storageAccountName, AddStorageAccountParameters parameters) { addStorageAccountWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName, parameters).toBlocking().single().body(); }
[ "public", "void", "addStorageAccount", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "storageAccountName", ",", "AddStorageAccountParameters", "parameters", ")", "{", "addStorageAccountWithServiceResponseAsync", "(", "resourceGroupName", ","...
Updates the specified Data Lake Analytics account to add an Azure Storage account. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account. @param accountName The name of the Data Lake Analytics account to which to add the Azure Storage account. @param storageAccountName The name of the Azure Storage account to add @param parameters The parameters containing the access key and optional suffix for the Azure Storage Account. @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
[ "Updates", "the", "specified", "Data", "Lake", "Analytics", "account", "to", "add", "an", "Azure", "Storage", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L477-L479
ag-gipp/MathMLTools
mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/GoldUtils.java
GoldUtils.writeGoldFile
public static void writeGoldFile(Path outputPath, JsonGouldiBean goldEntry) { """ Writes a gouldi entry to the given path. Note that if the file already exists, it will be overwritten and logging a warning message. @param outputPath where the gouldi entry will be stored @param goldEntry the gouldi entry as java object @throws IOException """ try { try { Files.createFile(outputPath); } catch (FileAlreadyExistsException e) { LOG.warn("File already exists!"); } try (Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputPath.toFile()), "UTF-8"))) { out.write(goldEntry.toString()); } } catch (IOException e) { LOG.error(e); throw new RuntimeException(e); } }
java
public static void writeGoldFile(Path outputPath, JsonGouldiBean goldEntry) { try { try { Files.createFile(outputPath); } catch (FileAlreadyExistsException e) { LOG.warn("File already exists!"); } try (Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputPath.toFile()), "UTF-8"))) { out.write(goldEntry.toString()); } } catch (IOException e) { LOG.error(e); throw new RuntimeException(e); } }
[ "public", "static", "void", "writeGoldFile", "(", "Path", "outputPath", ",", "JsonGouldiBean", "goldEntry", ")", "{", "try", "{", "try", "{", "Files", ".", "createFile", "(", "outputPath", ")", ";", "}", "catch", "(", "FileAlreadyExistsException", "e", ")", ...
Writes a gouldi entry to the given path. Note that if the file already exists, it will be overwritten and logging a warning message. @param outputPath where the gouldi entry will be stored @param goldEntry the gouldi entry as java object @throws IOException
[ "Writes", "a", "gouldi", "entry", "to", "the", "given", "path", ".", "Note", "that", "if", "the", "file", "already", "exists", "it", "will", "be", "overwritten", "and", "logging", "a", "warning", "message", "." ]
train
https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-gold/src/main/java/com/formulasearchengine/mathmltools/gold/GoldUtils.java#L42-L57
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java
StorageTreeFactory.configureStoragePlugin
private void configureStoragePlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { """ Configures storage plugins with the builder @param builder builder @param index current prop index @param configProps configuration properties """ String pref1 = getStorageConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String path = configProps.get(pref1 + SEP + PATH); boolean removePathPrefix = Boolean.parseBoolean(configProps.get(pref1 + SEP + REMOVE_PATH_PREFIX)); Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); Tree<ResourceMeta> resourceMetaTree = loadPlugin( pluginType, config, storagePluginProviderService ); if (index == 1 && PathUtil.isRoot(path)) { logger.debug("New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.base(resourceMetaTree); } else { logger.debug("Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.subTree(PathUtil.asPath(path.trim()), resourceMetaTree, !removePathPrefix); } }
java
private void configureStoragePlugin(TreeBuilder<ResourceMeta> builder, int index, Map<String, String> configProps) { String pref1 = getStorageConfigPrefix() + SEP + index; String pluginType = configProps.get(pref1 + SEP + TYPE); String path = configProps.get(pref1 + SEP + PATH); boolean removePathPrefix = Boolean.parseBoolean(configProps.get(pref1 + SEP + REMOVE_PATH_PREFIX)); Map<String, String> config = subPropertyMap(pref1 + SEP + CONFIG + SEP, configProps); config = expandConfig(config); Tree<ResourceMeta> resourceMetaTree = loadPlugin( pluginType, config, storagePluginProviderService ); if (index == 1 && PathUtil.isRoot(path)) { logger.debug("New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.base(resourceMetaTree); } else { logger.debug("Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config); builder.subTree(PathUtil.asPath(path.trim()), resourceMetaTree, !removePathPrefix); } }
[ "private", "void", "configureStoragePlugin", "(", "TreeBuilder", "<", "ResourceMeta", ">", "builder", ",", "int", "index", ",", "Map", "<", "String", ",", "String", ">", "configProps", ")", "{", "String", "pref1", "=", "getStorageConfigPrefix", "(", ")", "+", ...
Configures storage plugins with the builder @param builder builder @param index current prop index @param configProps configuration properties
[ "Configures", "storage", "plugins", "with", "the", "builder" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/StorageTreeFactory.java#L283-L304
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
SDBaseOps.standardDeviation
public SDVariable standardDeviation(String name, SDVariable x, boolean biasCorrected, boolean keepDims, int... dimensions) { """ Stardard deviation array reduction operation, optionally along specified dimensions<br> Note that if keepDims = true, the output variable has the same rank as the input variable, with the reduced dimensions having size 1. This can be useful for later broadcast operations (such as subtracting the mean along a dimension).<br> Example: if input has shape [a,b,c] and dimensions=[1] then output has shape: keepDims = true: [a,1,c]<br> keepDims = false: [a,c] @param x Input variable @param biasCorrected If true: divide by (N-1) (i.e., sample stdev). If false: divide by N (population stdev) @param keepDims If true: keep the dimensions that are reduced on (as size 1). False: remove the reduction dimensions @param dimensions Dimensions to reduce over. If dimensions are not specified, full array reduction is performed @return Output variable: reduced array of rank (input rank - num dimensions) """ validateNumerical("standard deviation", x); SDVariable result = f().std(x, biasCorrected, keepDims, dimensions); return updateVariableNameAndReference(result, name); }
java
public SDVariable standardDeviation(String name, SDVariable x, boolean biasCorrected, boolean keepDims, int... dimensions) { validateNumerical("standard deviation", x); SDVariable result = f().std(x, biasCorrected, keepDims, dimensions); return updateVariableNameAndReference(result, name); }
[ "public", "SDVariable", "standardDeviation", "(", "String", "name", ",", "SDVariable", "x", ",", "boolean", "biasCorrected", ",", "boolean", "keepDims", ",", "int", "...", "dimensions", ")", "{", "validateNumerical", "(", "\"standard deviation\"", ",", "x", ")", ...
Stardard deviation array reduction operation, optionally along specified dimensions<br> Note that if keepDims = true, the output variable has the same rank as the input variable, with the reduced dimensions having size 1. This can be useful for later broadcast operations (such as subtracting the mean along a dimension).<br> Example: if input has shape [a,b,c] and dimensions=[1] then output has shape: keepDims = true: [a,1,c]<br> keepDims = false: [a,c] @param x Input variable @param biasCorrected If true: divide by (N-1) (i.e., sample stdev). If false: divide by N (population stdev) @param keepDims If true: keep the dimensions that are reduced on (as size 1). False: remove the reduction dimensions @param dimensions Dimensions to reduce over. If dimensions are not specified, full array reduction is performed @return Output variable: reduced array of rank (input rank - num dimensions)
[ "Stardard", "deviation", "array", "reduction", "operation", "optionally", "along", "specified", "dimensions<br", ">", "Note", "that", "if", "keepDims", "=", "true", "the", "output", "variable", "has", "the", "same", "rank", "as", "the", "input", "variable", "wit...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L2600-L2604
JM-Lab/utils-elasticsearch
src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java
JMElasticsearchIndex.sendData
public IndexResponse sendData(String jsonSource, String index, String type, String id) { """ Send data index response. @param jsonSource the json source @param index the index @param type the type @param id the id @return the index response """ return indexQuery(buildIndexRequest(jsonSource, index, type, id)); }
java
public IndexResponse sendData(String jsonSource, String index, String type, String id) { return indexQuery(buildIndexRequest(jsonSource, index, type, id)); }
[ "public", "IndexResponse", "sendData", "(", "String", "jsonSource", ",", "String", "index", ",", "String", "type", ",", "String", "id", ")", "{", "return", "indexQuery", "(", "buildIndexRequest", "(", "jsonSource", ",", "index", ",", "type", ",", "id", ")", ...
Send data index response. @param jsonSource the json source @param index the index @param type the type @param id the id @return the index response
[ "Send", "data", "index", "response", "." ]
train
https://github.com/JM-Lab/utils-elasticsearch/blob/6ccec90e1e51d65d2af5efbb6d7b9f9bad90e638/src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java#L235-L238
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/AzureFirewallsInner.java
AzureFirewallsInner.beginCreateOrUpdate
public AzureFirewallInner beginCreateOrUpdate(String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) { """ Creates or updates the specified Azure Firewall. @param resourceGroupName The name of the resource group. @param azureFirewallName The name of the Azure Firewall. @param parameters Parameters supplied to the create or update Azure Firewall operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AzureFirewallInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, azureFirewallName, parameters).toBlocking().single().body(); }
java
public AzureFirewallInner beginCreateOrUpdate(String resourceGroupName, String azureFirewallName, AzureFirewallInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, azureFirewallName, parameters).toBlocking().single().body(); }
[ "public", "AzureFirewallInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "azureFirewallName", ",", "AzureFirewallInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "azureFirewa...
Creates or updates the specified Azure Firewall. @param resourceGroupName The name of the resource group. @param azureFirewallName The name of the Azure Firewall. @param parameters Parameters supplied to the create or update Azure Firewall operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AzureFirewallInner object if successful.
[ "Creates", "or", "updates", "the", "specified", "Azure", "Firewall", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/AzureFirewallsInner.java#L426-L428
ujmp/universal-java-matrix-package
ujmp-core/src/main/java/org/ujmp/core/doublematrix/calculation/general/decomposition/Ginv.java
Ginv.swapCols
public static void swapCols(DenseDoubleMatrix2D matrix, long col1, long col2) { """ Swap components in the two columns. @param matrix the matrix to modify @param col1 the first row @param col2 the second row """ double temp = 0; long rows = matrix.getRowCount(); for (long row = 0; row < rows; row++) { temp = matrix.getDouble(row, col1); matrix.setDouble(matrix.getDouble(row, col2), row, col1); matrix.setDouble(temp, row, col2); } }
java
public static void swapCols(DenseDoubleMatrix2D matrix, long col1, long col2) { double temp = 0; long rows = matrix.getRowCount(); for (long row = 0; row < rows; row++) { temp = matrix.getDouble(row, col1); matrix.setDouble(matrix.getDouble(row, col2), row, col1); matrix.setDouble(temp, row, col2); } }
[ "public", "static", "void", "swapCols", "(", "DenseDoubleMatrix2D", "matrix", ",", "long", "col1", ",", "long", "col2", ")", "{", "double", "temp", "=", "0", ";", "long", "rows", "=", "matrix", ".", "getRowCount", "(", ")", ";", "for", "(", "long", "ro...
Swap components in the two columns. @param matrix the matrix to modify @param col1 the first row @param col2 the second row
[ "Swap", "components", "in", "the", "two", "columns", "." ]
train
https://github.com/ujmp/universal-java-matrix-package/blob/b7e1d293adeadaf35d208ffe8884028d6c06b63b/ujmp-core/src/main/java/org/ujmp/core/doublematrix/calculation/general/decomposition/Ginv.java#L164-L172
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/functions/Functions.java
Functions.randomString
public static String randomString(Long numberOfLetters, String notationMethod, boolean useNumbers, TestContext context) { """ Runs random string function with arguments. @param numberOfLetters @param notationMethod @param useNumbers @return """ return new RandomStringFunction().execute(Arrays.asList(String.valueOf(numberOfLetters), notationMethod, String.valueOf(useNumbers)), context); }
java
public static String randomString(Long numberOfLetters, String notationMethod, boolean useNumbers, TestContext context) { return new RandomStringFunction().execute(Arrays.asList(String.valueOf(numberOfLetters), notationMethod, String.valueOf(useNumbers)), context); }
[ "public", "static", "String", "randomString", "(", "Long", "numberOfLetters", ",", "String", "notationMethod", ",", "boolean", "useNumbers", ",", "TestContext", "context", ")", "{", "return", "new", "RandomStringFunction", "(", ")", ".", "execute", "(", "Arrays", ...
Runs random string function with arguments. @param numberOfLetters @param notationMethod @param useNumbers @return
[ "Runs", "random", "string", "function", "with", "arguments", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/functions/Functions.java#L208-L210
strator-dev/greenpepper
greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/I18nUtil.java
I18nUtil.getResourceBundle
public static ResourceBundle getResourceBundle(String bundleName, Locale locale) { """ <p>getResourceBundle.</p> @param bundleName a {@link java.lang.String} object. @param locale a {@link java.util.Locale} object. @return a {@link java.util.ResourceBundle} object. """ return ResourceBundle.getBundle(bundleName, locale); }
java
public static ResourceBundle getResourceBundle(String bundleName, Locale locale) { return ResourceBundle.getBundle(bundleName, locale); }
[ "public", "static", "ResourceBundle", "getResourceBundle", "(", "String", "bundleName", ",", "Locale", "locale", ")", "{", "return", "ResourceBundle", ".", "getBundle", "(", "bundleName", ",", "locale", ")", ";", "}" ]
<p>getResourceBundle.</p> @param bundleName a {@link java.lang.String} object. @param locale a {@link java.util.Locale} object. @return a {@link java.util.ResourceBundle} object.
[ "<p", ">", "getResourceBundle", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/I18nUtil.java#L69-L72
lightblue-platform/lightblue-client
hystrix/src/main/java/com/redhat/lightblue/client/hystrix/graphite/ServoGraphiteSetup.java
ServoGraphiteSetup.registerStatsdMetricObserver
protected static void registerStatsdMetricObserver(List<MetricObserver> observers, String prefix, String host, String port) { """ If there is sufficient configuration, register a StatsD metric observer to publish metrics. Requires at a minimum a host. Optionally can set prefix as well as port. The prefix defaults to an empty string and port defaults to '8125'. """ // verify at least hostname is set, else cannot configure this observer if (null == host || host.trim().isEmpty()) { LOGGER.info("StatdsMetricObserver not configured, missing environment variable: {}", ENV_STATSD_HOSTNAME); return; } LOGGER.debug("{} environment variable is: {}", ENV_STATSD_PREFIX, prefix); LOGGER.debug("{} environment variable is: {}", ENV_STATSD_HOSTNAME, host); LOGGER.debug("{} environment variable is: {}", ENV_STATSD_PORT, port); int iport = -1; if (port != null && !port.isEmpty()) { try { iport = Integer.valueOf(port); } catch (NumberFormatException e) { iport = -1; LOGGER.warn("Configured port is not an integer. Falling back to default"); } } if (iport < 0) { iport = 8125; //default statsd port LOGGER.debug("Using default port: " + port); } LOGGER.debug("StatsdMetricObserver prefix: " + prefix); LOGGER.debug("StatsdMetricObserver host: " + host); LOGGER.debug("StatsdMetricObserver port: " + iport); observers.add(new StatsdMetricObserver(prefix, host, iport)); }
java
protected static void registerStatsdMetricObserver(List<MetricObserver> observers, String prefix, String host, String port) { // verify at least hostname is set, else cannot configure this observer if (null == host || host.trim().isEmpty()) { LOGGER.info("StatdsMetricObserver not configured, missing environment variable: {}", ENV_STATSD_HOSTNAME); return; } LOGGER.debug("{} environment variable is: {}", ENV_STATSD_PREFIX, prefix); LOGGER.debug("{} environment variable is: {}", ENV_STATSD_HOSTNAME, host); LOGGER.debug("{} environment variable is: {}", ENV_STATSD_PORT, port); int iport = -1; if (port != null && !port.isEmpty()) { try { iport = Integer.valueOf(port); } catch (NumberFormatException e) { iport = -1; LOGGER.warn("Configured port is not an integer. Falling back to default"); } } if (iport < 0) { iport = 8125; //default statsd port LOGGER.debug("Using default port: " + port); } LOGGER.debug("StatsdMetricObserver prefix: " + prefix); LOGGER.debug("StatsdMetricObserver host: " + host); LOGGER.debug("StatsdMetricObserver port: " + iport); observers.add(new StatsdMetricObserver(prefix, host, iport)); }
[ "protected", "static", "void", "registerStatsdMetricObserver", "(", "List", "<", "MetricObserver", ">", "observers", ",", "String", "prefix", ",", "String", "host", ",", "String", "port", ")", "{", "// verify at least hostname is set, else cannot configure this observer", ...
If there is sufficient configuration, register a StatsD metric observer to publish metrics. Requires at a minimum a host. Optionally can set prefix as well as port. The prefix defaults to an empty string and port defaults to '8125'.
[ "If", "there", "is", "sufficient", "configuration", "register", "a", "StatsD", "metric", "observer", "to", "publish", "metrics", ".", "Requires", "at", "a", "minimum", "a", "host", ".", "Optionally", "can", "set", "prefix", "as", "well", "as", "port", ".", ...
train
https://github.com/lightblue-platform/lightblue-client/blob/03790aff34e90d3889f60fd6c603c21a21dc1a40/hystrix/src/main/java/com/redhat/lightblue/client/hystrix/graphite/ServoGraphiteSetup.java#L159-L190
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/logging/StoringLocalLogs.java
StoringLocalLogs.addEntry
@Override public void addEntry(String logType, LogEntry entry) { """ Add a new log entry to the local storage. @param logType the log type to store @param entry the entry to store """ if (!logTypesToInclude.contains(logType)) { return; } if (!localLogs.containsKey(logType)) { List<LogEntry> entries = new ArrayList<>(); entries.add(entry); localLogs.put(logType, entries); } else { localLogs.get(logType).add(entry); } }
java
@Override public void addEntry(String logType, LogEntry entry) { if (!logTypesToInclude.contains(logType)) { return; } if (!localLogs.containsKey(logType)) { List<LogEntry> entries = new ArrayList<>(); entries.add(entry); localLogs.put(logType, entries); } else { localLogs.get(logType).add(entry); } }
[ "@", "Override", "public", "void", "addEntry", "(", "String", "logType", ",", "LogEntry", "entry", ")", "{", "if", "(", "!", "logTypesToInclude", ".", "contains", "(", "logType", ")", ")", "{", "return", ";", "}", "if", "(", "!", "localLogs", ".", "con...
Add a new log entry to the local storage. @param logType the log type to store @param entry the entry to store
[ "Add", "a", "new", "log", "entry", "to", "the", "local", "storage", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/logging/StoringLocalLogs.java#L59-L72
JodaOrg/joda-money
src/main/java/org/joda/money/BigMoney.java
BigMoney.ofScale
public static BigMoney ofScale(CurrencyUnit currency, BigDecimal amount, int scale, RoundingMode roundingMode) { """ Obtains an instance of {@code BigMoney} from a {@code double} using a well-defined conversion, rounding as necessary. <p> This allows you to create an instance with a specific currency and amount. If the amount has a scale in excess of the scale of the currency then the excess fractional digits are rounded using the rounding mode. The result will have a minimum scale of zero. @param currency the currency, not null @param amount the amount of money, not null @param scale the scale to use, zero or positive @param roundingMode the rounding mode to use, not null @return the new instance, never null @throws ArithmeticException if the rounding fails """ MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); MoneyUtils.checkNotNull(amount, "Amount must not be null"); MoneyUtils.checkNotNull(roundingMode, "RoundingMode must not be null"); amount = amount.setScale(scale, roundingMode); return BigMoney.of(currency, amount); }
java
public static BigMoney ofScale(CurrencyUnit currency, BigDecimal amount, int scale, RoundingMode roundingMode) { MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); MoneyUtils.checkNotNull(amount, "Amount must not be null"); MoneyUtils.checkNotNull(roundingMode, "RoundingMode must not be null"); amount = amount.setScale(scale, roundingMode); return BigMoney.of(currency, amount); }
[ "public", "static", "BigMoney", "ofScale", "(", "CurrencyUnit", "currency", ",", "BigDecimal", "amount", ",", "int", "scale", ",", "RoundingMode", "roundingMode", ")", "{", "MoneyUtils", ".", "checkNotNull", "(", "currency", ",", "\"CurrencyUnit must not be null\"", ...
Obtains an instance of {@code BigMoney} from a {@code double} using a well-defined conversion, rounding as necessary. <p> This allows you to create an instance with a specific currency and amount. If the amount has a scale in excess of the scale of the currency then the excess fractional digits are rounded using the rounding mode. The result will have a minimum scale of zero. @param currency the currency, not null @param amount the amount of money, not null @param scale the scale to use, zero or positive @param roundingMode the rounding mode to use, not null @return the new instance, never null @throws ArithmeticException if the rounding fails
[ "Obtains", "an", "instance", "of", "{", "@code", "BigMoney", "}", "from", "a", "{", "@code", "double", "}", "using", "a", "well", "-", "defined", "conversion", "rounding", "as", "necessary", ".", "<p", ">", "This", "allows", "you", "to", "create", "an", ...
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L151-L157
gwt-maven-plugin/gwt-maven-plugin
src/main/java/org/codehaus/mojo/gwt/ClasspathBuilder.java
ClasspathBuilder.addResources
private void addResources( final Collection<File> items, final Collection<Resource> resources ) { """ Add source path and resource paths of the project to the list of classpath items. @param items Classpath items. @param resources """ for ( Resource resource : resources ) { items.add( new File( resource.getDirectory() ) ); } }
java
private void addResources( final Collection<File> items, final Collection<Resource> resources ) { for ( Resource resource : resources ) { items.add( new File( resource.getDirectory() ) ); } }
[ "private", "void", "addResources", "(", "final", "Collection", "<", "File", ">", "items", ",", "final", "Collection", "<", "Resource", ">", "resources", ")", "{", "for", "(", "Resource", "resource", ":", "resources", ")", "{", "items", ".", "add", "(", "...
Add source path and resource paths of the project to the list of classpath items. @param items Classpath items. @param resources
[ "Add", "source", "path", "and", "resource", "paths", "of", "the", "project", "to", "the", "list", "of", "classpath", "items", "." ]
train
https://github.com/gwt-maven-plugin/gwt-maven-plugin/blob/0cdd5054b43f182cc22a8acf61ec79ac42b0dfdc/src/main/java/org/codehaus/mojo/gwt/ClasspathBuilder.java#L287-L293
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/convert/MultipleFieldConverter.java
MultipleFieldConverter.setData
public int setData(Object state, boolean bDisplayOption, int iMoveMode) { """ For binary fields, set the current state. @param state The state to set this field. @param bDisplayOption Display changed fields if true. @param iMoveMode The move mode. @return The error code (or NORMAL_RETURN). """ // Must be overidden m_bSetData = true; // Make sure getNextConverter is called correctly (if it is called). int iErrorCode = super.setData(state, bDisplayOption, iMoveMode); m_bSetData = false; return iErrorCode; }
java
public int setData(Object state, boolean bDisplayOption, int iMoveMode) { // Must be overidden m_bSetData = true; // Make sure getNextConverter is called correctly (if it is called). int iErrorCode = super.setData(state, bDisplayOption, iMoveMode); m_bSetData = false; return iErrorCode; }
[ "public", "int", "setData", "(", "Object", "state", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "// Must be overidden", "m_bSetData", "=", "true", ";", "// Make sure getNextConverter is called correctly (if it is called).", "int", "iErrorCode", "=...
For binary fields, set the current state. @param state The state to set this field. @param bDisplayOption Display changed fields if true. @param iMoveMode The move mode. @return The error code (or NORMAL_RETURN).
[ "For", "binary", "fields", "set", "the", "current", "state", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/convert/MultipleFieldConverter.java#L129-L135
jfinal/jfinal
src/main/java/com/jfinal/core/Controller.java
Controller.getPara
public String getPara(String name, String defaultValue) { """ Returns the value of a request parameter as a String, or default value if the parameter does not exist. @param name a String specifying the name of the parameter @param defaultValue a String value be returned when the value of parameter is null @return a String representing the single value of the parameter """ String result = request.getParameter(name); return result != null && !"".equals(result) ? result : defaultValue; }
java
public String getPara(String name, String defaultValue) { String result = request.getParameter(name); return result != null && !"".equals(result) ? result : defaultValue; }
[ "public", "String", "getPara", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "String", "result", "=", "request", ".", "getParameter", "(", "name", ")", ";", "return", "result", "!=", "null", "&&", "!", "\"\"", ".", "equals", "(", "resul...
Returns the value of a request parameter as a String, or default value if the parameter does not exist. @param name a String specifying the name of the parameter @param defaultValue a String value be returned when the value of parameter is null @return a String representing the single value of the parameter
[ "Returns", "the", "value", "of", "a", "request", "parameter", "as", "a", "String", "or", "default", "value", "if", "the", "parameter", "does", "not", "exist", "." ]
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/core/Controller.java#L177-L180
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CharacterExtensions.java
CharacterExtensions.operator_power
@Pure @Inline(value="$3.pow($1, $2)", imported=Math.class) public static double operator_power(char a, int b) { """ The binary <code>power</code> operator. This is the equivalent to the Java's <code>Math.pow()</code> function. @param a a character. @param b an integer. @return <code>Math.pow(a, b)</code> @since 2.3 """ return Math.pow(a, b); }
java
@Pure @Inline(value="$3.pow($1, $2)", imported=Math.class) public static double operator_power(char a, int b) { return Math.pow(a, b); }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"$3.pow($1, $2)\"", ",", "imported", "=", "Math", ".", "class", ")", "public", "static", "double", "operator_power", "(", "char", "a", ",", "int", "b", ")", "{", "return", "Math", ".", "pow", "(", "a", ...
The binary <code>power</code> operator. This is the equivalent to the Java's <code>Math.pow()</code> function. @param a a character. @param b an integer. @return <code>Math.pow(a, b)</code> @since 2.3
[ "The", "binary", "<code", ">", "power<", "/", "code", ">", "operator", ".", "This", "is", "the", "equivalent", "to", "the", "Java", "s", "<code", ">", "Math", ".", "pow", "()", "<", "/", "code", ">", "function", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/CharacterExtensions.java#L837-L841
classgraph/classgraph
src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java
FileUtils.readAllBytesAsString
public static String readAllBytesAsString(final InputStream inputStream, final long fileSize) throws IOException { """ Read all the bytes in an {@link InputStream} as a String. @param inputStream The {@link InputStream}. @param fileSize The file size, if known, otherwise -1L. @return The contents of the {@link InputStream} as a String. @throws IOException If the contents could not be read. """ final SimpleEntry<byte[], Integer> ent = readAllBytes(inputStream, fileSize); final byte[] buf = ent.getKey(); final int bufBytesUsed = ent.getValue(); return new String(buf, 0, bufBytesUsed, StandardCharsets.UTF_8); }
java
public static String readAllBytesAsString(final InputStream inputStream, final long fileSize) throws IOException { final SimpleEntry<byte[], Integer> ent = readAllBytes(inputStream, fileSize); final byte[] buf = ent.getKey(); final int bufBytesUsed = ent.getValue(); return new String(buf, 0, bufBytesUsed, StandardCharsets.UTF_8); }
[ "public", "static", "String", "readAllBytesAsString", "(", "final", "InputStream", "inputStream", ",", "final", "long", "fileSize", ")", "throws", "IOException", "{", "final", "SimpleEntry", "<", "byte", "[", "]", ",", "Integer", ">", "ent", "=", "readAllBytes",...
Read all the bytes in an {@link InputStream} as a String. @param inputStream The {@link InputStream}. @param fileSize The file size, if known, otherwise -1L. @return The contents of the {@link InputStream} as a String. @throws IOException If the contents could not be read.
[ "Read", "all", "the", "bytes", "in", "an", "{", "@link", "InputStream", "}", "as", "a", "String", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L241-L247
lessthanoptimal/ddogleg
src/org/ddogleg/solver/PolynomialOps.java
PolynomialOps.createRootFinder
public static PolynomialRoots createRootFinder( int maxCoefficients , RootFinderType which ) { """ Creates different polynomial root finders. @param maxCoefficients The maximum number of coefficients that will be processed. This is the order + 1 @param which 0 = Sturm and 1 = companion matrix. @return PolynomialRoots """ switch( which ) { case STURM: FindRealRootsSturm sturm = new FindRealRootsSturm(maxCoefficients,-1,1e-10,200,200); return new WrapRealRootsSturm(sturm); case EVD: return new RootFinderCompanion(); default: throw new IllegalArgumentException("Unknown algorithm: "+which); } }
java
public static PolynomialRoots createRootFinder( int maxCoefficients , RootFinderType which ) { switch( which ) { case STURM: FindRealRootsSturm sturm = new FindRealRootsSturm(maxCoefficients,-1,1e-10,200,200); return new WrapRealRootsSturm(sturm); case EVD: return new RootFinderCompanion(); default: throw new IllegalArgumentException("Unknown algorithm: "+which); } }
[ "public", "static", "PolynomialRoots", "createRootFinder", "(", "int", "maxCoefficients", ",", "RootFinderType", "which", ")", "{", "switch", "(", "which", ")", "{", "case", "STURM", ":", "FindRealRootsSturm", "sturm", "=", "new", "FindRealRootsSturm", "(", "maxCo...
Creates different polynomial root finders. @param maxCoefficients The maximum number of coefficients that will be processed. This is the order + 1 @param which 0 = Sturm and 1 = companion matrix. @return PolynomialRoots
[ "Creates", "different", "polynomial", "root", "finders", "." ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/solver/PolynomialOps.java#L229-L241
groupon/robo-remote
RoboRemoteServer/apklib/src/main/com/groupon/roboremote/roboremoteserver/robotium/Solo2.java
Solo2.waitForActivity
public boolean waitForActivity(ComponentName name, int retryTime) { """ Wait for activity to become active (by component name) @param name @param retryTime """ final int retryPeriod = 250; int retryNum = retryTime / retryPeriod; for (int i = 0; i < retryNum; i++) { if (this.getCurrentActivity().getComponentName().equals(name)) { break; } if (i == retryNum - 1) { return false; } this.sleep(retryPeriod); } return true; }
java
public boolean waitForActivity(ComponentName name, int retryTime) { final int retryPeriod = 250; int retryNum = retryTime / retryPeriod; for (int i = 0; i < retryNum; i++) { if (this.getCurrentActivity().getComponentName().equals(name)) { break; } if (i == retryNum - 1) { return false; } this.sleep(retryPeriod); } return true; }
[ "public", "boolean", "waitForActivity", "(", "ComponentName", "name", ",", "int", "retryTime", ")", "{", "final", "int", "retryPeriod", "=", "250", ";", "int", "retryNum", "=", "retryTime", "/", "retryPeriod", ";", "for", "(", "int", "i", "=", "0", ";", ...
Wait for activity to become active (by component name) @param name @param retryTime
[ "Wait", "for", "activity", "to", "become", "active", "(", "by", "component", "name", ")" ]
train
https://github.com/groupon/robo-remote/blob/12d242faad50bf90f98657ca9a0c0c3ae1993f07/RoboRemoteServer/apklib/src/main/com/groupon/roboremote/roboremoteserver/robotium/Solo2.java#L191-L204
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java
WsByteBufferUtils.asString
public static final String asString(WsByteBuffer buff, int position, int limit) { """ Convert a buffer to a string using the input starting position and ending limit. @param buff @param position @param limit @return String """ byte[] data = asByteArray(buff, position, limit); return (null != data) ? new String(data) : null; }
java
public static final String asString(WsByteBuffer buff, int position, int limit) { byte[] data = asByteArray(buff, position, limit); return (null != data) ? new String(data) : null; }
[ "public", "static", "final", "String", "asString", "(", "WsByteBuffer", "buff", ",", "int", "position", ",", "int", "limit", ")", "{", "byte", "[", "]", "data", "=", "asByteArray", "(", "buff", ",", "position", ",", "limit", ")", ";", "return", "(", "n...
Convert a buffer to a string using the input starting position and ending limit. @param buff @param position @param limit @return String
[ "Convert", "a", "buffer", "to", "a", "string", "using", "the", "input", "starting", "position", "and", "ending", "limit", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java#L131-L134
joniles/mpxj
src/main/java/net/sf/mpxj/common/InputStreamHelper.java
InputStreamHelper.writeStreamToTempFile
public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException { """ Copy the data from an InputStream to a temp file. @param inputStream data source @param tempFileSuffix suffix to use for temp file @return File instance """ FileOutputStream outputStream = null; try { File file = File.createTempFile("mpxj", tempFileSuffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return file; } finally { if (outputStream != null) { outputStream.close(); } } }
java
public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException { FileOutputStream outputStream = null; try { File file = File.createTempFile("mpxj", tempFileSuffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return file; } finally { if (outputStream != null) { outputStream.close(); } } }
[ "public", "static", "File", "writeStreamToTempFile", "(", "InputStream", "inputStream", ",", "String", "tempFileSuffix", ")", "throws", "IOException", "{", "FileOutputStream", "outputStream", "=", "null", ";", "try", "{", "File", "file", "=", "File", ".", "createT...
Copy the data from an InputStream to a temp file. @param inputStream data source @param tempFileSuffix suffix to use for temp file @return File instance
[ "Copy", "the", "data", "from", "an", "InputStream", "to", "a", "temp", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/common/InputStreamHelper.java#L46-L74
intellimate/Izou
src/main/java/org/intellimate/izou/system/sound/SoundManager.java
SoundManager.requestPermanent
public void requestPermanent(AddOnModel addOnModel, Identification source, boolean nonJava) { """ tries to register the AddonModel as permanent @param addOnModel the AddonModel to register @param source the Source which requested the usage @param nonJava true if it is not using java to play sounds """ debug("requesting permanent for addon: " + addOnModel); boolean notUsing = isUsing.compareAndSet(false, true); if (!notUsing) { debug("already used by " + permanentAddOn); synchronized (permanentUserReadWriteLock) { if (permanentAddOn != null && permanentAddOn.equals(addOnModel)) { if (knownIdentification == null) knownIdentification = source; return; } else { endPermanent(permanentAddOn); addAsPermanent(addOnModel, source, nonJava); } } } else { addAsPermanent(addOnModel, source, nonJava); } }
java
public void requestPermanent(AddOnModel addOnModel, Identification source, boolean nonJava) { debug("requesting permanent for addon: " + addOnModel); boolean notUsing = isUsing.compareAndSet(false, true); if (!notUsing) { debug("already used by " + permanentAddOn); synchronized (permanentUserReadWriteLock) { if (permanentAddOn != null && permanentAddOn.equals(addOnModel)) { if (knownIdentification == null) knownIdentification = source; return; } else { endPermanent(permanentAddOn); addAsPermanent(addOnModel, source, nonJava); } } } else { addAsPermanent(addOnModel, source, nonJava); } }
[ "public", "void", "requestPermanent", "(", "AddOnModel", "addOnModel", ",", "Identification", "source", ",", "boolean", "nonJava", ")", "{", "debug", "(", "\"requesting permanent for addon: \"", "+", "addOnModel", ")", ";", "boolean", "notUsing", "=", "isUsing", "."...
tries to register the AddonModel as permanent @param addOnModel the AddonModel to register @param source the Source which requested the usage @param nonJava true if it is not using java to play sounds
[ "tries", "to", "register", "the", "AddonModel", "as", "permanent" ]
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/system/sound/SoundManager.java#L244-L262
mapbox/mapbox-navigation-android
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java
DistanceFormatter.formatDistance
public SpannableString formatDistance(double distance) { """ Returns a formatted SpannableString with bold and size formatting. I.e., "10 mi", "350 m" @param distance in meters @return SpannableString representation which has a bolded number and units which have a relative size of .65 times the size of the number """ double distanceSmallUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, smallUnit); double distanceLargeUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, largeUnit); // If the distance is greater than 10 miles/kilometers, then round to nearest mile/kilometer if (distanceLargeUnit > LARGE_UNIT_THRESHOLD) { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 0), largeUnit); // If the distance is less than 401 feet/meters, round by fifty feet/meters } else if (distanceSmallUnit < SMALL_UNIT_THRESHOLD) { return getDistanceString(roundToClosestIncrement(distanceSmallUnit), smallUnit); // If the distance is between 401 feet/meters and 10 miles/kilometers, then round to one decimal place } else { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 1), largeUnit); } }
java
public SpannableString formatDistance(double distance) { double distanceSmallUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, smallUnit); double distanceLargeUnit = TurfConversion.convertLength(distance, TurfConstants.UNIT_METERS, largeUnit); // If the distance is greater than 10 miles/kilometers, then round to nearest mile/kilometer if (distanceLargeUnit > LARGE_UNIT_THRESHOLD) { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 0), largeUnit); // If the distance is less than 401 feet/meters, round by fifty feet/meters } else if (distanceSmallUnit < SMALL_UNIT_THRESHOLD) { return getDistanceString(roundToClosestIncrement(distanceSmallUnit), smallUnit); // If the distance is between 401 feet/meters and 10 miles/kilometers, then round to one decimal place } else { return getDistanceString(roundToDecimalPlace(distanceLargeUnit, 1), largeUnit); } }
[ "public", "SpannableString", "formatDistance", "(", "double", "distance", ")", "{", "double", "distanceSmallUnit", "=", "TurfConversion", ".", "convertLength", "(", "distance", ",", "TurfConstants", ".", "UNIT_METERS", ",", "smallUnit", ")", ";", "double", "distance...
Returns a formatted SpannableString with bold and size formatting. I.e., "10 mi", "350 m" @param distance in meters @return SpannableString representation which has a bolded number and units which have a relative size of .65 times the size of the number
[ "Returns", "a", "formatted", "SpannableString", "with", "bold", "and", "size", "formatting", ".", "I", ".", "e", ".", "10", "mi", "350", "m" ]
train
https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java#L92-L106
apache/flink
flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java
DateTimeUtils.addMonths
public static long addMonths(long timestamp, int m) { """ Adds a given number of months to a timestamp, represented as the number of milliseconds since the epoch. """ final long millis = DateTimeUtils.floorMod(timestamp, DateTimeUtils.MILLIS_PER_DAY); timestamp -= millis; final long x = addMonths((int) (timestamp / DateTimeUtils.MILLIS_PER_DAY), m); return x * DateTimeUtils.MILLIS_PER_DAY + millis; }
java
public static long addMonths(long timestamp, int m) { final long millis = DateTimeUtils.floorMod(timestamp, DateTimeUtils.MILLIS_PER_DAY); timestamp -= millis; final long x = addMonths((int) (timestamp / DateTimeUtils.MILLIS_PER_DAY), m); return x * DateTimeUtils.MILLIS_PER_DAY + millis; }
[ "public", "static", "long", "addMonths", "(", "long", "timestamp", ",", "int", "m", ")", "{", "final", "long", "millis", "=", "DateTimeUtils", ".", "floorMod", "(", "timestamp", ",", "DateTimeUtils", ".", "MILLIS_PER_DAY", ")", ";", "timestamp", "-=", "milli...
Adds a given number of months to a timestamp, represented as the number of milliseconds since the epoch.
[ "Adds", "a", "given", "number", "of", "months", "to", "a", "timestamp", "represented", "as", "the", "number", "of", "milliseconds", "since", "the", "epoch", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java#L1059-L1066
morimekta/utils
io-util/src/main/java/net/morimekta/util/Strings.java
Strings.joinP
public static String joinP(String delimiter, int... values) { """ Join array with delimiter. @param delimiter The delimiter. @param values The int array to join. @return The joined string. """ StringBuilder builder = new StringBuilder(values.length + (delimiter.length() * values.length)); boolean first = true; for (int i : values) { if (first) { first = false; } else { builder.append(delimiter); } builder.append(Integer.toString(i)); } return builder.toString(); }
java
public static String joinP(String delimiter, int... values) { StringBuilder builder = new StringBuilder(values.length + (delimiter.length() * values.length)); boolean first = true; for (int i : values) { if (first) { first = false; } else { builder.append(delimiter); } builder.append(Integer.toString(i)); } return builder.toString(); }
[ "public", "static", "String", "joinP", "(", "String", "delimiter", ",", "int", "...", "values", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "values", ".", "length", "+", "(", "delimiter", ".", "length", "(", ")", "*", "values", ...
Join array with delimiter. @param delimiter The delimiter. @param values The int array to join. @return The joined string.
[ "Join", "array", "with", "delimiter", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Strings.java#L304-L316
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP14Reader.java
MPP14Reader.processHyperlinkData
private void processHyperlinkData(Resource resource, byte[] data) { """ This method is used to extract the resource hyperlink attributes from a block of data and call the appropriate modifier methods to configure the specified task object. @param resource resource instance @param data hyperlink data block """ if (data != null) { int offset = 12; String hyperlink; String address; String subaddress; offset += 12; hyperlink = MPPUtility.getUnicodeString(data, offset); offset += ((hyperlink.length() + 1) * 2); offset += 12; address = MPPUtility.getUnicodeString(data, offset); offset += ((address.length() + 1) * 2); offset += 12; subaddress = MPPUtility.getUnicodeString(data, offset); resource.setHyperlink(hyperlink); resource.setHyperlinkAddress(address); resource.setHyperlinkSubAddress(subaddress); } }
java
private void processHyperlinkData(Resource resource, byte[] data) { if (data != null) { int offset = 12; String hyperlink; String address; String subaddress; offset += 12; hyperlink = MPPUtility.getUnicodeString(data, offset); offset += ((hyperlink.length() + 1) * 2); offset += 12; address = MPPUtility.getUnicodeString(data, offset); offset += ((address.length() + 1) * 2); offset += 12; subaddress = MPPUtility.getUnicodeString(data, offset); resource.setHyperlink(hyperlink); resource.setHyperlinkAddress(address); resource.setHyperlinkSubAddress(subaddress); } }
[ "private", "void", "processHyperlinkData", "(", "Resource", "resource", ",", "byte", "[", "]", "data", ")", "{", "if", "(", "data", "!=", "null", ")", "{", "int", "offset", "=", "12", ";", "String", "hyperlink", ";", "String", "address", ";", "String", ...
This method is used to extract the resource hyperlink attributes from a block of data and call the appropriate modifier methods to configure the specified task object. @param resource resource instance @param data hyperlink data block
[ "This", "method", "is", "used", "to", "extract", "the", "resource", "hyperlink", "attributes", "from", "a", "block", "of", "data", "and", "call", "the", "appropriate", "modifier", "methods", "to", "configure", "the", "specified", "task", "object", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP14Reader.java#L1547-L1571
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java
ApiKeyRealm.hasPermissionById
public boolean hasPermissionById(String id, Permission permission) { """ Test for whether an API key has a specific permission using its ID. """ return hasPermissionsById(id, ImmutableList.of(permission)); }
java
public boolean hasPermissionById(String id, Permission permission) { return hasPermissionsById(id, ImmutableList.of(permission)); }
[ "public", "boolean", "hasPermissionById", "(", "String", "id", ",", "Permission", "permission", ")", "{", "return", "hasPermissionsById", "(", "id", ",", "ImmutableList", ".", "of", "(", "permission", ")", ")", ";", "}" ]
Test for whether an API key has a specific permission using its ID.
[ "Test", "for", "whether", "an", "API", "key", "has", "a", "specific", "permission", "using", "its", "ID", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L440-L442
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/MediaservicesInner.java
MediaservicesInner.getByResourceGroupAsync
public Observable<MediaServiceInner> getByResourceGroupAsync(String resourceGroupName, String accountName) { """ Get a Media Services account. Get the details of a Media Services account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the MediaServiceInner object """ return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<MediaServiceInner>, MediaServiceInner>() { @Override public MediaServiceInner call(ServiceResponse<MediaServiceInner> response) { return response.body(); } }); }
java
public Observable<MediaServiceInner> getByResourceGroupAsync(String resourceGroupName, String accountName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<MediaServiceInner>, MediaServiceInner>() { @Override public MediaServiceInner call(ServiceResponse<MediaServiceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "MediaServiceInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ")", ".", "m...
Get a Media Services account. Get the details of a Media Services account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the MediaServiceInner object
[ "Get", "a", "Media", "Services", "account", ".", "Get", "the", "details", "of", "a", "Media", "Services", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/MediaservicesInner.java#L269-L276
Axway/Grapes
commons/src/main/java/org/axway/grapes/commons/datamodel/DataModelFactory.java
DataModelFactory.createDependency
public static Dependency createDependency(final Artifact artifact, final String scope) throws UnsupportedScopeException { """ Generates a dependency regarding the parameters. @param artifact Artifact @param scope String @return Dependency @throws UnsupportedScopeException """ try{ final Scope depScope = Scope.valueOf(scope.toUpperCase()); return createDependency(artifact, depScope); } catch(IllegalArgumentException e){ LOG.log(Level.SEVERE, String.format("Cannot identify scope for string %s. Details: %s", scope, e.getMessage()), e); throw new UnsupportedScopeException(); } }
java
public static Dependency createDependency(final Artifact artifact, final String scope) throws UnsupportedScopeException{ try{ final Scope depScope = Scope.valueOf(scope.toUpperCase()); return createDependency(artifact, depScope); } catch(IllegalArgumentException e){ LOG.log(Level.SEVERE, String.format("Cannot identify scope for string %s. Details: %s", scope, e.getMessage()), e); throw new UnsupportedScopeException(); } }
[ "public", "static", "Dependency", "createDependency", "(", "final", "Artifact", "artifact", ",", "final", "String", "scope", ")", "throws", "UnsupportedScopeException", "{", "try", "{", "final", "Scope", "depScope", "=", "Scope", ".", "valueOf", "(", "scope", "....
Generates a dependency regarding the parameters. @param artifact Artifact @param scope String @return Dependency @throws UnsupportedScopeException
[ "Generates", "a", "dependency", "regarding", "the", "parameters", "." ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/commons/src/main/java/org/axway/grapes/commons/datamodel/DataModelFactory.java#L159-L168
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.isNotEquals
public static <T> void isNotEquals( final T argument, String argumentName, final T object, String objectName ) { """ Asserts that the specified first object is not {@link Object#equals(Object) equal to} the specified second object. This method does take null references into consideration. @param <T> @param argument The argument to assert equal to <code>object</code>. @param argumentName The name that will be used within the exception message for the argument should an exception be thrown @param object The object to assert as equal to <code>argument</code>. @param objectName The name that will be used within the exception message for <code>object</code> should an exception be thrown; if <code>null</code> and <code>object</code> is not <code>null</code>, <code>object.toString()</code> will be used. @throws IllegalArgumentException If the specified objects are equals. """ if (argument == null) { if (object != null) return; // fall through ... both are null } else { if (!argument.equals(object)) return; // handles object==null // fall through ... they are equal } if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustNotBeEquals.text(argumentName, objectName)); }
java
public static <T> void isNotEquals( final T argument, String argumentName, final T object, String objectName ) { if (argument == null) { if (object != null) return; // fall through ... both are null } else { if (!argument.equals(object)) return; // handles object==null // fall through ... they are equal } if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustNotBeEquals.text(argumentName, objectName)); }
[ "public", "static", "<", "T", ">", "void", "isNotEquals", "(", "final", "T", "argument", ",", "String", "argumentName", ",", "final", "T", "object", ",", "String", "objectName", ")", "{", "if", "(", "argument", "==", "null", ")", "{", "if", "(", "objec...
Asserts that the specified first object is not {@link Object#equals(Object) equal to} the specified second object. This method does take null references into consideration. @param <T> @param argument The argument to assert equal to <code>object</code>. @param argumentName The name that will be used within the exception message for the argument should an exception be thrown @param object The object to assert as equal to <code>argument</code>. @param objectName The name that will be used within the exception message for <code>object</code> should an exception be thrown; if <code>null</code> and <code>object</code> is not <code>null</code>, <code>object.toString()</code> will be used. @throws IllegalArgumentException If the specified objects are equals.
[ "Asserts", "that", "the", "specified", "first", "object", "is", "not", "{", "@link", "Object#equals", "(", "Object", ")", "equal", "to", "}", "the", "specified", "second", "object", ".", "This", "method", "does", "take", "null", "references", "into", "consid...
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L545-L558
reactor/reactor-netty
src/main/java/reactor/netty/tcp/TcpClient.java
TcpClient.doOnLifecycle
public final TcpClient doOnLifecycle(Consumer<? super Bootstrap> doOnConnect, Consumer<? super Connection> doOnConnected, Consumer<? super Connection> doOnDisconnected) { """ Setup all lifecycle callbacks called on or after {@link io.netty.channel.Channel} has been connected and after it has been disconnected. @param doOnConnect a consumer observing client start event @param doOnConnected a consumer observing client started event @param doOnDisconnected a consumer observing client stop event @return a new {@link TcpClient} """ Objects.requireNonNull(doOnConnect, "doOnConnect"); Objects.requireNonNull(doOnConnected, "doOnConnected"); Objects.requireNonNull(doOnDisconnected, "doOnDisconnected"); return new TcpClientDoOn(this, doOnConnect, doOnConnected, doOnDisconnected); }
java
public final TcpClient doOnLifecycle(Consumer<? super Bootstrap> doOnConnect, Consumer<? super Connection> doOnConnected, Consumer<? super Connection> doOnDisconnected) { Objects.requireNonNull(doOnConnect, "doOnConnect"); Objects.requireNonNull(doOnConnected, "doOnConnected"); Objects.requireNonNull(doOnDisconnected, "doOnDisconnected"); return new TcpClientDoOn(this, doOnConnect, doOnConnected, doOnDisconnected); }
[ "public", "final", "TcpClient", "doOnLifecycle", "(", "Consumer", "<", "?", "super", "Bootstrap", ">", "doOnConnect", ",", "Consumer", "<", "?", "super", "Connection", ">", "doOnConnected", ",", "Consumer", "<", "?", "super", "Connection", ">", "doOnDisconnected...
Setup all lifecycle callbacks called on or after {@link io.netty.channel.Channel} has been connected and after it has been disconnected. @param doOnConnect a consumer observing client start event @param doOnConnected a consumer observing client started event @param doOnDisconnected a consumer observing client stop event @return a new {@link TcpClient}
[ "Setup", "all", "lifecycle", "callbacks", "called", "on", "or", "after", "{", "@link", "io", ".", "netty", ".", "channel", ".", "Channel", "}", "has", "been", "connected", "and", "after", "it", "has", "been", "disconnected", "." ]
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/TcpClient.java#L277-L284
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_acl_GET
public ArrayList<String> project_serviceName_acl_GET(String serviceName, OvhAclTypeEnum type) throws IOException { """ Get ACL on your cloud project REST: GET /cloud/project/{serviceName}/acl @param type [required] Filter the value of type property (=) @param serviceName [required] The project id """ String qPath = "/cloud/project/{serviceName}/acl"; StringBuilder sb = path(qPath, serviceName); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> project_serviceName_acl_GET(String serviceName, OvhAclTypeEnum type) throws IOException { String qPath = "/cloud/project/{serviceName}/acl"; StringBuilder sb = path(qPath, serviceName); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "project_serviceName_acl_GET", "(", "String", "serviceName", ",", "OvhAclTypeEnum", "type", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/acl\"", ";", "StringBuilder", "sb", "=", "...
Get ACL on your cloud project REST: GET /cloud/project/{serviceName}/acl @param type [required] Filter the value of type property (=) @param serviceName [required] The project id
[ "Get", "ACL", "on", "your", "cloud", "project" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L347-L353
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/TableReader.java
TableReader.readUUID
protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException { """ Read the optional row header and UUID. @param stream input stream @param map row map """ int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16; map.put("UNKNOWN0", stream.readBytes(unknown0Size)); map.put("UUID", stream.readUUID()); }
java
protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException { int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16; map.put("UNKNOWN0", stream.readBytes(unknown0Size)); map.put("UUID", stream.readUUID()); }
[ "protected", "void", "readUUID", "(", "StreamReader", "stream", ",", "Map", "<", "String", ",", "Object", ">", "map", ")", "throws", "IOException", "{", "int", "unknown0Size", "=", "stream", ".", "getMajorVersion", "(", ")", ">", "5", "?", "8", ":", "16"...
Read the optional row header and UUID. @param stream input stream @param map row map
[ "Read", "the", "optional", "row", "header", "and", "UUID", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/TableReader.java#L124-L129
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/VirtualWANsInner.java
VirtualWANsInner.beginUpdateTags
public VirtualWANInner beginUpdateTags(String resourceGroupName, String virtualWANName) { """ Updates a VirtualWAN tags. @param resourceGroupName The resource group name of the VirtualWan. @param virtualWANName The name of the VirtualWAN being updated. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualWANInner object if successful. """ return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualWANName).toBlocking().single().body(); }
java
public VirtualWANInner beginUpdateTags(String resourceGroupName, String virtualWANName) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualWANName).toBlocking().single().body(); }
[ "public", "VirtualWANInner", "beginUpdateTags", "(", "String", "resourceGroupName", ",", "String", "virtualWANName", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualWANName", ")", ".", "toBlocking", "(", ")", ".", "s...
Updates a VirtualWAN tags. @param resourceGroupName The resource group name of the VirtualWan. @param virtualWANName The name of the VirtualWAN being updated. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualWANInner object if successful.
[ "Updates", "a", "VirtualWAN", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/VirtualWANsInner.java#L521-L523
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/type/impl/ManyToOneType.java
ManyToOneType.scheduleBatchLoadIfNeeded
private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException { """ Register the entity as batch loadable, if enabled Copied from {@link org.hibernate.type.ManyToOneType#scheduleBatchLoadIfNeeded} """ //cannot batch fetch by unique key (property-ref associations) if ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) { EntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() ); EntityKey entityKey = session.generateEntityKey( id, persister ); if ( !session.getPersistenceContext().containsEntity( entityKey ) ) { session.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey ); } } }
java
private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException { //cannot batch fetch by unique key (property-ref associations) if ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) { EntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() ); EntityKey entityKey = session.generateEntityKey( id, persister ); if ( !session.getPersistenceContext().containsEntity( entityKey ) ) { session.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey ); } } }
[ "private", "void", "scheduleBatchLoadIfNeeded", "(", "Serializable", "id", ",", "SharedSessionContractImplementor", "session", ")", "throws", "MappingException", "{", "//cannot batch fetch by unique key (property-ref associations)", "if", "(", "StringHelper", ".", "isEmpty", "(...
Register the entity as batch loadable, if enabled Copied from {@link org.hibernate.type.ManyToOneType#scheduleBatchLoadIfNeeded}
[ "Register", "the", "entity", "as", "batch", "loadable", "if", "enabled" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/type/impl/ManyToOneType.java#L80-L89
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/utils/disruptor/RingBuffer.java
RingBuffer.publishEvents
public <A> void publishEvents(EventTranslatorOneArg<E, A> translator, int batchStartsAt, int batchSize, A[] arg0) { """ Allows one user supplied argument per event. @param translator The user specified translation for each event @param batchStartsAt The first element of the array which is within the batch. @param batchSize The actual size of the batch @param arg0 An array of user supplied arguments, one element per event. @see #publishEvents(EventTranslator[]) """ checkBounds(arg0, batchStartsAt, batchSize); final long finalSequence = sequencer.next(batchSize); translateAndPublishBatch(translator, arg0, batchStartsAt, batchSize, finalSequence); }
java
public <A> void publishEvents(EventTranslatorOneArg<E, A> translator, int batchStartsAt, int batchSize, A[] arg0) { checkBounds(arg0, batchStartsAt, batchSize); final long finalSequence = sequencer.next(batchSize); translateAndPublishBatch(translator, arg0, batchStartsAt, batchSize, finalSequence); }
[ "public", "<", "A", ">", "void", "publishEvents", "(", "EventTranslatorOneArg", "<", "E", ",", "A", ">", "translator", ",", "int", "batchStartsAt", ",", "int", "batchSize", ",", "A", "[", "]", "arg0", ")", "{", "checkBounds", "(", "arg0", ",", "batchStar...
Allows one user supplied argument per event. @param translator The user specified translation for each event @param batchStartsAt The first element of the array which is within the batch. @param batchSize The actual size of the batch @param arg0 An array of user supplied arguments, one element per event. @see #publishEvents(EventTranslator[])
[ "Allows", "one", "user", "supplied", "argument", "per", "event", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/utils/disruptor/RingBuffer.java#L584-L588
alkacon/opencms-core
src/org/opencms/loader/CmsResourceManager.java
CmsResourceManager.getMimeType
public String getMimeType(String filename, String encoding, String defaultMimeType) { """ Returns the MIME type for a specified file name.<p> If an encoding parameter that is not <code>null</code> is provided, the returned MIME type is extended with a <code>; charset={encoding}</code> setting.<p> If no MIME type for the given filename can be determined, the provided default is used.<p> @param filename the file name to check the MIME type for @param encoding the default encoding (charset) in case of MIME types is of type "text" @param defaultMimeType the default MIME type to use if no matching type for the filename is found @return the MIME type for a specified file """ String mimeType = null; int lastDot = filename.lastIndexOf('.'); // check the MIME type for the file extension if ((lastDot > 0) && (lastDot < (filename.length() - 1))) { mimeType = m_mimeTypes.get(filename.substring(lastDot).toLowerCase(Locale.ENGLISH)); } if (mimeType == null) { mimeType = defaultMimeType; if (mimeType == null) { // no default MIME type was provided return null; } } StringBuffer result = new StringBuffer(mimeType); if ((encoding != null) && (mimeType.startsWith("text") || mimeType.endsWith("javascript")) && (mimeType.indexOf("charset") == -1)) { result.append("; charset="); result.append(encoding); } return result.toString(); }
java
public String getMimeType(String filename, String encoding, String defaultMimeType) { String mimeType = null; int lastDot = filename.lastIndexOf('.'); // check the MIME type for the file extension if ((lastDot > 0) && (lastDot < (filename.length() - 1))) { mimeType = m_mimeTypes.get(filename.substring(lastDot).toLowerCase(Locale.ENGLISH)); } if (mimeType == null) { mimeType = defaultMimeType; if (mimeType == null) { // no default MIME type was provided return null; } } StringBuffer result = new StringBuffer(mimeType); if ((encoding != null) && (mimeType.startsWith("text") || mimeType.endsWith("javascript")) && (mimeType.indexOf("charset") == -1)) { result.append("; charset="); result.append(encoding); } return result.toString(); }
[ "public", "String", "getMimeType", "(", "String", "filename", ",", "String", "encoding", ",", "String", "defaultMimeType", ")", "{", "String", "mimeType", "=", "null", ";", "int", "lastDot", "=", "filename", ".", "lastIndexOf", "(", "'", "'", ")", ";", "//...
Returns the MIME type for a specified file name.<p> If an encoding parameter that is not <code>null</code> is provided, the returned MIME type is extended with a <code>; charset={encoding}</code> setting.<p> If no MIME type for the given filename can be determined, the provided default is used.<p> @param filename the file name to check the MIME type for @param encoding the default encoding (charset) in case of MIME types is of type "text" @param defaultMimeType the default MIME type to use if no matching type for the filename is found @return the MIME type for a specified file
[ "Returns", "the", "MIME", "type", "for", "a", "specified", "file", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsResourceManager.java#L810-L833
amzn/ion-java
src/com/amazon/ion/util/IonStreamUtils.java
IonStreamUtils.writeIntList
public static void writeIntList(IonWriter writer, byte[] values) throws IOException { """ writes an IonList with a series of IonInt values. This starts a List, writes the values (without any annoations) and closes the list. For text and tree writers this is just a convienience, but for the binary writer it can be optimized internally. @param values signed byte values to populate the lists int's with """ if (writer instanceof _Private_ListWriter) { ((_Private_ListWriter)writer).writeIntList(values); return; } writer.stepIn(IonType.LIST); for (int ii=0; ii<values.length; ii++) { writer.writeInt(values[ii]); } writer.stepOut(); }
java
public static void writeIntList(IonWriter writer, byte[] values) throws IOException { if (writer instanceof _Private_ListWriter) { ((_Private_ListWriter)writer).writeIntList(values); return; } writer.stepIn(IonType.LIST); for (int ii=0; ii<values.length; ii++) { writer.writeInt(values[ii]); } writer.stepOut(); }
[ "public", "static", "void", "writeIntList", "(", "IonWriter", "writer", ",", "byte", "[", "]", "values", ")", "throws", "IOException", "{", "if", "(", "writer", "instanceof", "_Private_ListWriter", ")", "{", "(", "(", "_Private_ListWriter", ")", "writer", ")",...
writes an IonList with a series of IonInt values. This starts a List, writes the values (without any annoations) and closes the list. For text and tree writers this is just a convienience, but for the binary writer it can be optimized internally. @param values signed byte values to populate the lists int's with
[ "writes", "an", "IonList", "with", "a", "series", "of", "IonInt", "values", ".", "This", "starts", "a", "List", "writes", "the", "values", "(", "without", "any", "annoations", ")", "and", "closes", "the", "list", ".", "For", "text", "and", "tree", "write...
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonStreamUtils.java#L210-L223
HubSpot/Singularity
SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosSchedulerClient.java
SingularityMesosSchedulerClient.frameworkMessage
public void frameworkMessage(ExecutorID executorId, AgentID agentId, byte[] data) { """ Sent by the scheduler to send arbitrary binary data to the executor. Mesos neither interprets this data nor makes any guarantees about the delivery of this message to the executor. data is raw bytes encoded in Base64. @param executorId @param agentId @param data """ Builder message = build() .setMessage(Message.newBuilder().setAgentId(agentId).setExecutorId(executorId).setData(ByteString.copyFrom(data))); sendCall(message, Type.MESSAGE); }
java
public void frameworkMessage(ExecutorID executorId, AgentID agentId, byte[] data) { Builder message = build() .setMessage(Message.newBuilder().setAgentId(agentId).setExecutorId(executorId).setData(ByteString.copyFrom(data))); sendCall(message, Type.MESSAGE); }
[ "public", "void", "frameworkMessage", "(", "ExecutorID", "executorId", ",", "AgentID", "agentId", ",", "byte", "[", "]", "data", ")", "{", "Builder", "message", "=", "build", "(", ")", ".", "setMessage", "(", "Message", ".", "newBuilder", "(", ")", ".", ...
Sent by the scheduler to send arbitrary binary data to the executor. Mesos neither interprets this data nor makes any guarantees about the delivery of this message to the executor. data is raw bytes encoded in Base64. @param executorId @param agentId @param data
[ "Sent", "by", "the", "scheduler", "to", "send", "arbitrary", "binary", "data", "to", "the", "executor", ".", "Mesos", "neither", "interprets", "this", "data", "nor", "makes", "any", "guarantees", "about", "the", "delivery", "of", "this", "message", "to", "th...
train
https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosSchedulerClient.java#L410-L414
d-tarasov/android-intents
library/src/com/dmitriy/tarasov/android/intents/IntentUtils.java
IntentUtils.pickContact
public static Intent pickContact(String scope) { """ Pick contact from phone book @param scope You can restrict selection by passing required content type. Examples: <p/> <code><pre> // Select only from users with emails IntentUtils.pickContact(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE); <p/> // Select only from users with phone numbers on pre Eclair devices IntentUtils.pickContact(Contacts.Phones.CONTENT_TYPE); <p/> // Select only from users with phone numbers on devices with Eclair and higher IntentUtils.pickContact(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); </pre></code> """ Intent intent; if (isSupportsContactsV2()) { intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://com.android.contacts/contacts")); } else { intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI); } if (!TextUtils.isEmpty(scope)) { intent.setType(scope); } return intent; }
java
public static Intent pickContact(String scope) { Intent intent; if (isSupportsContactsV2()) { intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://com.android.contacts/contacts")); } else { intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI); } if (!TextUtils.isEmpty(scope)) { intent.setType(scope); } return intent; }
[ "public", "static", "Intent", "pickContact", "(", "String", "scope", ")", "{", "Intent", "intent", ";", "if", "(", "isSupportsContactsV2", "(", ")", ")", "{", "intent", "=", "new", "Intent", "(", "Intent", ".", "ACTION_PICK", ",", "Uri", ".", "parse", "(...
Pick contact from phone book @param scope You can restrict selection by passing required content type. Examples: <p/> <code><pre> // Select only from users with emails IntentUtils.pickContact(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE); <p/> // Select only from users with phone numbers on pre Eclair devices IntentUtils.pickContact(Contacts.Phones.CONTENT_TYPE); <p/> // Select only from users with phone numbers on devices with Eclair and higher IntentUtils.pickContact(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); </pre></code>
[ "Pick", "contact", "from", "phone", "book" ]
train
https://github.com/d-tarasov/android-intents/blob/ac3c6e2fd88057708988a96eda6240c29efe1b9a/library/src/com/dmitriy/tarasov/android/intents/IntentUtils.java#L397-L409
JOML-CI/JOML
src/org/joml/Intersectionf.java
Intersectionf.distancePointPlane
public static float distancePointPlane(float pointX, float pointY, float pointZ, float v0X, float v0Y, float v0Z, float v1X, float v1Y, float v1Z, float v2X, float v2Y, float v2Z) { """ Determine the signed distance of the given point <code>(pointX, pointY, pointZ)</code> to the plane of the triangle specified by its three points <code>(v0X, v0Y, v0Z)</code>, <code>(v1X, v1Y, v1Z)</code> and <code>(v2X, v2Y, v2Z)</code>. <p> If the point lies on the front-facing side of the triangle's plane, that is, if the triangle has counter-clockwise winding order as seen from the point, then this method returns a positive number. @param pointX the x coordinate of the point @param pointY the y coordinate of the point @param pointZ the z coordinate of the point @param v0X the x coordinate of the first vertex of the triangle @param v0Y the y coordinate of the first vertex of the triangle @param v0Z the z coordinate of the first vertex of the triangle @param v1X the x coordinate of the second vertex of the triangle @param v1Y the y coordinate of the second vertex of the triangle @param v1Z the z coordinate of the second vertex of the triangle @param v2X the x coordinate of the third vertex of the triangle @param v2Y the y coordinate of the third vertex of the triangle @param v2Z the z coordinate of the third vertex of the triangle @return the signed distance between the point and the plane of the triangle """ float v1Y0Y = v1Y - v0Y; float v2Z0Z = v2Z - v0Z; float v2Y0Y = v2Y - v0Y; float v1Z0Z = v1Z - v0Z; float v2X0X = v2X - v0X; float v1X0X = v1X - v0X; float a = v1Y0Y * v2Z0Z - v2Y0Y * v1Z0Z; float b = v1Z0Z * v2X0X - v2Z0Z * v1X0X; float c = v1X0X * v2Y0Y - v2X0X * v1Y0Y; float d = -(a * v0X + b * v0Y + c * v0Z); return distancePointPlane(pointX, pointY, pointZ, a, b, c, d); }
java
public static float distancePointPlane(float pointX, float pointY, float pointZ, float v0X, float v0Y, float v0Z, float v1X, float v1Y, float v1Z, float v2X, float v2Y, float v2Z) { float v1Y0Y = v1Y - v0Y; float v2Z0Z = v2Z - v0Z; float v2Y0Y = v2Y - v0Y; float v1Z0Z = v1Z - v0Z; float v2X0X = v2X - v0X; float v1X0X = v1X - v0X; float a = v1Y0Y * v2Z0Z - v2Y0Y * v1Z0Z; float b = v1Z0Z * v2X0X - v2Z0Z * v1X0X; float c = v1X0X * v2Y0Y - v2X0X * v1Y0Y; float d = -(a * v0X + b * v0Y + c * v0Z); return distancePointPlane(pointX, pointY, pointZ, a, b, c, d); }
[ "public", "static", "float", "distancePointPlane", "(", "float", "pointX", ",", "float", "pointY", ",", "float", "pointZ", ",", "float", "v0X", ",", "float", "v0Y", ",", "float", "v0Z", ",", "float", "v1X", ",", "float", "v1Y", ",", "float", "v1Z", ",", ...
Determine the signed distance of the given point <code>(pointX, pointY, pointZ)</code> to the plane of the triangle specified by its three points <code>(v0X, v0Y, v0Z)</code>, <code>(v1X, v1Y, v1Z)</code> and <code>(v2X, v2Y, v2Z)</code>. <p> If the point lies on the front-facing side of the triangle's plane, that is, if the triangle has counter-clockwise winding order as seen from the point, then this method returns a positive number. @param pointX the x coordinate of the point @param pointY the y coordinate of the point @param pointZ the z coordinate of the point @param v0X the x coordinate of the first vertex of the triangle @param v0Y the y coordinate of the first vertex of the triangle @param v0Z the z coordinate of the first vertex of the triangle @param v1X the x coordinate of the second vertex of the triangle @param v1Y the y coordinate of the second vertex of the triangle @param v1Z the z coordinate of the second vertex of the triangle @param v2X the x coordinate of the third vertex of the triangle @param v2Y the y coordinate of the third vertex of the triangle @param v2Z the z coordinate of the third vertex of the triangle @return the signed distance between the point and the plane of the triangle
[ "Determine", "the", "signed", "distance", "of", "the", "given", "point", "<code", ">", "(", "pointX", "pointY", "pointZ", ")", "<", "/", "code", ">", "to", "the", "plane", "of", "the", "triangle", "specified", "by", "its", "three", "points", "<code", ">"...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectionf.java#L996-L1009
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/util/Util.java
Util.cacheFile
public static File cacheFile(@javax.annotation.Nonnull final String url, @javax.annotation.Nonnull final String file) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { """ Cache file file. @param url the url @param file the file @return the file @throws IOException the io exception @throws NoSuchAlgorithmException the no such algorithm exception @throws KeyStoreException the key store exception @throws KeyManagementException the key management exception """ if (!new File(file).exists()) { IOUtils.copy(get(url), new FileOutputStream(file)); } return new File(file); }
java
public static File cacheFile(@javax.annotation.Nonnull final String url, @javax.annotation.Nonnull final String file) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { if (!new File(file).exists()) { IOUtils.copy(get(url), new FileOutputStream(file)); } return new File(file); }
[ "public", "static", "File", "cacheFile", "(", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "String", "url", ",", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "String", "file", ")", "throws", "IOException", ",", "NoSuchAlgorithmExcepti...
Cache file file. @param url the url @param file the file @return the file @throws IOException the io exception @throws NoSuchAlgorithmException the no such algorithm exception @throws KeyStoreException the key store exception @throws KeyManagementException the key management exception
[ "Cache", "file", "file", "." ]
train
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/Util.java#L200-L205
RuedigerMoeller/kontraktor
modules/kontraktor-reallive/src/main/java/org/nustaq/reallive/impl/StorageDriver.java
StorageDriver.atomicQuery
public IPromise atomicQuery(String key, RLFunction<Record,Object> action) { """ apply the function to the record with given key and return the result inside a promise changes to the record inside the function are applied to the real record and a change message is generated. In case the function returns a changemessage (add,putRecord,remove ..), the change message is applied to the original record and the change is broadcasted @param key @param action @return the result of function. """ Record rec = getStore().get(key); if ( rec == null ) { final Object apply = action.apply(rec); if ( apply instanceof ChangeMessage ) { receive( (ChangeMessage) apply ) ; } return new Promise(apply); } else { PatchingRecord pr = new PatchingRecord(rec); final Object res = action.apply(pr); if ( res instanceof ChangeMessage ) { receive( (ChangeMessage) res ) ; } else { UpdateMessage updates = pr.getUpdates(0); if (updates != null) { receive(updates); } } return new Promise(res); } }
java
public IPromise atomicQuery(String key, RLFunction<Record,Object> action) { Record rec = getStore().get(key); if ( rec == null ) { final Object apply = action.apply(rec); if ( apply instanceof ChangeMessage ) { receive( (ChangeMessage) apply ) ; } return new Promise(apply); } else { PatchingRecord pr = new PatchingRecord(rec); final Object res = action.apply(pr); if ( res instanceof ChangeMessage ) { receive( (ChangeMessage) res ) ; } else { UpdateMessage updates = pr.getUpdates(0); if (updates != null) { receive(updates); } } return new Promise(res); } }
[ "public", "IPromise", "atomicQuery", "(", "String", "key", ",", "RLFunction", "<", "Record", ",", "Object", ">", "action", ")", "{", "Record", "rec", "=", "getStore", "(", ")", ".", "get", "(", "key", ")", ";", "if", "(", "rec", "==", "null", ")", ...
apply the function to the record with given key and return the result inside a promise changes to the record inside the function are applied to the real record and a change message is generated. In case the function returns a changemessage (add,putRecord,remove ..), the change message is applied to the original record and the change is broadcasted @param key @param action @return the result of function.
[ "apply", "the", "function", "to", "the", "record", "with", "given", "key", "and", "return", "the", "result", "inside", "a", "promise" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/kontraktor-reallive/src/main/java/org/nustaq/reallive/impl/StorageDriver.java#L171-L194
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/AboutDialog.java
AboutParams.set
private void set(String key, String... values) { """ Add first non-null/non-empty value to map. @param key The key to be added (is translated to a label value). @param values The list of possible values. """ String value = get(values); if (value != null) { put(getLabel(key), value); } }
java
private void set(String key, String... values) { String value = get(values); if (value != null) { put(getLabel(key), value); } }
[ "private", "void", "set", "(", "String", "key", ",", "String", "...", "values", ")", "{", "String", "value", "=", "get", "(", "values", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "put", "(", "getLabel", "(", "key", ")", ",", "value", "...
Add first non-null/non-empty value to map. @param key The key to be added (is translated to a label value). @param values The list of possible values.
[ "Add", "first", "non", "-", "null", "/", "non", "-", "empty", "value", "to", "map", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/AboutDialog.java#L122-L128
future-architect/uroborosql
src/main/java/jp/co/future/uroborosql/parameter/ReaderParameter.java
ReaderParameter.setReaderParameter
protected int setReaderParameter(final PreparedStatement preparedStatement, int index) throws SQLException { """ ステートメントにストリームパラメータを登録。 @param preparedStatement ステートメント @param index パラメータインデックス @return 次のパラメータインデックス @throws SQLException SQL例外 """ if (len > -1) { preparedStatement.setCharacterStream(index, reader, len); } else { preparedStatement.setCharacterStream(index, reader); } parameterLog(index); index++; return index; }
java
protected int setReaderParameter(final PreparedStatement preparedStatement, int index) throws SQLException { if (len > -1) { preparedStatement.setCharacterStream(index, reader, len); } else { preparedStatement.setCharacterStream(index, reader); } parameterLog(index); index++; return index; }
[ "protected", "int", "setReaderParameter", "(", "final", "PreparedStatement", "preparedStatement", ",", "int", "index", ")", "throws", "SQLException", "{", "if", "(", "len", ">", "-", "1", ")", "{", "preparedStatement", ".", "setCharacterStream", "(", "index", ",...
ステートメントにストリームパラメータを登録。 @param preparedStatement ステートメント @param index パラメータインデックス @return 次のパラメータインデックス @throws SQLException SQL例外
[ "ステートメントにストリームパラメータを登録。" ]
train
https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/parameter/ReaderParameter.java#L76-L86
aws/aws-cloudtrail-processing-library
src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/S3SourceSerializer.java
S3SourceSerializer.addCloudTrailLogsAndMessageAttributes
private void addCloudTrailLogsAndMessageAttributes(Message sqsMessage, JsonNode s3RecordsNode, List<CloudTrailLog> cloudTrailLogs) { """ As long as there is at least one CloudTrail log object: <p> <li>Add the CloudTrail log object key to the list.</li> <li>Add <code>accountId</code> extracted from log object key to <code>sqsMessage</code>.</li> <li>Add {@link SourceType#CloudTrailLog} to the <code>sqsMessage</code>.</li> </p> If there is no CloudTrail log object and it is a valid S3 message, CPL adds only {@link SourceType#Other} to the <code>sqsMessage</code>. """ SourceType sourceType = SourceType.Other; for (JsonNode s3Record: s3RecordsNode) { String bucketName = s3Record.at(S3_BUCKET_NAME).textValue(); String objectKey = s3Record.at(S3_OBJECT_KEY).textValue(); String eventName = s3Record.get(EVENT_NAME).textValue(); SourceType currSourceType = sourceIdentifier.identifyWithEventName(objectKey, eventName); if (currSourceType == SourceType.CloudTrailLog) { cloudTrailLogs.add(new CloudTrailLog(bucketName, objectKey)); sourceType = currSourceType; LibraryUtils.setMessageAccountId(sqsMessage, objectKey); } } sqsMessage.addAttributesEntry(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey(), sourceType.name()); }
java
private void addCloudTrailLogsAndMessageAttributes(Message sqsMessage, JsonNode s3RecordsNode, List<CloudTrailLog> cloudTrailLogs) { SourceType sourceType = SourceType.Other; for (JsonNode s3Record: s3RecordsNode) { String bucketName = s3Record.at(S3_BUCKET_NAME).textValue(); String objectKey = s3Record.at(S3_OBJECT_KEY).textValue(); String eventName = s3Record.get(EVENT_NAME).textValue(); SourceType currSourceType = sourceIdentifier.identifyWithEventName(objectKey, eventName); if (currSourceType == SourceType.CloudTrailLog) { cloudTrailLogs.add(new CloudTrailLog(bucketName, objectKey)); sourceType = currSourceType; LibraryUtils.setMessageAccountId(sqsMessage, objectKey); } } sqsMessage.addAttributesEntry(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey(), sourceType.name()); }
[ "private", "void", "addCloudTrailLogsAndMessageAttributes", "(", "Message", "sqsMessage", ",", "JsonNode", "s3RecordsNode", ",", "List", "<", "CloudTrailLog", ">", "cloudTrailLogs", ")", "{", "SourceType", "sourceType", "=", "SourceType", ".", "Other", ";", "for", "...
As long as there is at least one CloudTrail log object: <p> <li>Add the CloudTrail log object key to the list.</li> <li>Add <code>accountId</code> extracted from log object key to <code>sqsMessage</code>.</li> <li>Add {@link SourceType#CloudTrailLog} to the <code>sqsMessage</code>.</li> </p> If there is no CloudTrail log object and it is a valid S3 message, CPL adds only {@link SourceType#Other} to the <code>sqsMessage</code>.
[ "As", "long", "as", "there", "is", "at", "least", "one", "CloudTrail", "log", "object", ":", "<p", ">", "<li", ">", "Add", "the", "CloudTrail", "log", "object", "key", "to", "the", "list", ".", "<", "/", "li", ">", "<li", ">", "Add", "<code", ">", ...
train
https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/S3SourceSerializer.java#L80-L97
PrashamTrivedi/SharedPreferenceInspector
sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/PrefsAdapter.java
PrefsAdapter.getView
@Override public View getView(int position, View convertView, ViewGroup parent) { """ Get a View that displays the data at the specified position in the data set. You can either create a View manually or inflate it from an XML layout file. When the View is inflated, the parent View (GridView, ListView...) will apply default layout parameters unless you use {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)} to specify a root view and to prevent attachment to the root. @param position The position of the item within the adapter's data set of the item whose view we want. @param convertView The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view. Heterogeneous lists can specify their number of view types, so that this View is always of the right type (see {@link #getViewTypeCount()} and {@link #getItemViewType(int)}). @param parent The parent that this view will eventually be attached to @return A View corresponding to the data at the specified position. """ ViewHolder holder; Pair<String, ?> keyVal = getItem(position); if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.preference_item, parent, false); holder.key = (TextView) convertView.findViewById(R.id.key); holder.value = (TextView) convertView.findViewById(R.id.value); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.key.setText(keyVal.first); String value = ""; Object second = keyVal.second; if (second != null) { value = second.toString() + " (" + second.getClass().getSimpleName() + ")"; } holder.value.setText(value); return convertView; }
java
@Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; Pair<String, ?> keyVal = getItem(position); if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.preference_item, parent, false); holder.key = (TextView) convertView.findViewById(R.id.key); holder.value = (TextView) convertView.findViewById(R.id.value); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.key.setText(keyVal.first); String value = ""; Object second = keyVal.second; if (second != null) { value = second.toString() + " (" + second.getClass().getSimpleName() + ")"; } holder.value.setText(value); return convertView; }
[ "@", "Override", "public", "View", "getView", "(", "int", "position", ",", "View", "convertView", ",", "ViewGroup", "parent", ")", "{", "ViewHolder", "holder", ";", "Pair", "<", "String", ",", "?", ">", "keyVal", "=", "getItem", "(", "position", ")", ";"...
Get a View that displays the data at the specified position in the data set. You can either create a View manually or inflate it from an XML layout file. When the View is inflated, the parent View (GridView, ListView...) will apply default layout parameters unless you use {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)} to specify a root view and to prevent attachment to the root. @param position The position of the item within the adapter's data set of the item whose view we want. @param convertView The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view. Heterogeneous lists can specify their number of view types, so that this View is always of the right type (see {@link #getViewTypeCount()} and {@link #getItemViewType(int)}). @param parent The parent that this view will eventually be attached to @return A View corresponding to the data at the specified position.
[ "Get", "a", "View", "that", "displays", "the", "data", "at", "the", "specified", "position", "in", "the", "data", "set", ".", "You", "can", "either", "create", "a", "View", "manually", "or", "inflate", "it", "from", "an", "XML", "layout", "file", ".", ...
train
https://github.com/PrashamTrivedi/SharedPreferenceInspector/blob/c04d567c4d0fc5e0f8cda308ca85df19c6b3b838/sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/PrefsAdapter.java#L87-L110
hawtio/hawtio
hawtio-system/src/main/java/io/hawt/jmx/RBACRegistry.java
RBACRegistry.tryAddRBACInfo
@SuppressWarnings("unchecked") private void tryAddRBACInfo(Map<String, Object> result) throws MBeanException, InstanceNotFoundException, ReflectionException { """ If we have access to <code>hawtio:type=security,area=jolokia,name=RBACDecorator</code>, we can add RBAC information @param result """ if (mBeanServer != null && mBeanServer.isRegistered(rbacDecorator)) { mBeanServer.invoke(rbacDecorator, "decorate", new Object[] { result }, new String[] { Map.class.getName() }); } }
java
@SuppressWarnings("unchecked") private void tryAddRBACInfo(Map<String, Object> result) throws MBeanException, InstanceNotFoundException, ReflectionException { if (mBeanServer != null && mBeanServer.isRegistered(rbacDecorator)) { mBeanServer.invoke(rbacDecorator, "decorate", new Object[] { result }, new String[] { Map.class.getName() }); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "tryAddRBACInfo", "(", "Map", "<", "String", ",", "Object", ">", "result", ")", "throws", "MBeanException", ",", "InstanceNotFoundException", ",", "ReflectionException", "{", "if", "(", "mBeanS...
If we have access to <code>hawtio:type=security,area=jolokia,name=RBACDecorator</code>, we can add RBAC information @param result
[ "If", "we", "have", "access", "to", "<code", ">", "hawtio", ":", "type", "=", "security", "area", "=", "jolokia", "name", "=", "RBACDecorator<", "/", "code", ">", "we", "can", "add", "RBAC", "information" ]
train
https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/hawtio-system/src/main/java/io/hawt/jmx/RBACRegistry.java#L311-L316
zeromq/jeromq
src/main/java/org/zeromq/util/ZData.java
ZData.streq
public static boolean streq(byte[] data, String str) { """ String equals. Uses String compareTo for the comparison (lexigraphical) @param str String to compare with data @param data the binary data to compare @return True if data matches given string """ if (data == null) { return false; } return new String(data, ZMQ.CHARSET).compareTo(str) == 0; }
java
public static boolean streq(byte[] data, String str) { if (data == null) { return false; } return new String(data, ZMQ.CHARSET).compareTo(str) == 0; }
[ "public", "static", "boolean", "streq", "(", "byte", "[", "]", "data", ",", "String", "str", ")", "{", "if", "(", "data", "==", "null", ")", "{", "return", "false", ";", "}", "return", "new", "String", "(", "data", ",", "ZMQ", ".", "CHARSET", ")", ...
String equals. Uses String compareTo for the comparison (lexigraphical) @param str String to compare with data @param data the binary data to compare @return True if data matches given string
[ "String", "equals", ".", "Uses", "String", "compareTo", "for", "the", "comparison", "(", "lexigraphical", ")" ]
train
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/util/ZData.java#L37-L43
helun/Ektorp
org.ektorp/src/main/java/org/ektorp/util/Documents.java
Documents.registerAccessor
public static void registerAccessor(Class<?> documentType, DocumentAccessor accessor) { """ Used to register a custom DocumentAccessor for a particular class. Any existing accessor for the class will be overridden. @param documentType @param accessor """ Assert.notNull(documentType, "documentType may not be null"); Assert.notNull(accessor, "accessor may not be null"); if (accessors.containsKey(documentType)) { DocumentAccessor existing = getAccessor(documentType); LOG.warn(String.format("DocumentAccessor for class %s already exists: %s will be overridden by %s", documentType, existing.getClass(), accessor.getClass())); } putAccessor(documentType, accessor); LOG.debug("Registered document accessor: {} for class: {}", accessor.getClass(), documentType); }
java
public static void registerAccessor(Class<?> documentType, DocumentAccessor accessor) { Assert.notNull(documentType, "documentType may not be null"); Assert.notNull(accessor, "accessor may not be null"); if (accessors.containsKey(documentType)) { DocumentAccessor existing = getAccessor(documentType); LOG.warn(String.format("DocumentAccessor for class %s already exists: %s will be overridden by %s", documentType, existing.getClass(), accessor.getClass())); } putAccessor(documentType, accessor); LOG.debug("Registered document accessor: {} for class: {}", accessor.getClass(), documentType); }
[ "public", "static", "void", "registerAccessor", "(", "Class", "<", "?", ">", "documentType", ",", "DocumentAccessor", "accessor", ")", "{", "Assert", ".", "notNull", "(", "documentType", ",", "\"documentType may not be null\"", ")", ";", "Assert", ".", "notNull", ...
Used to register a custom DocumentAccessor for a particular class. Any existing accessor for the class will be overridden. @param documentType @param accessor
[ "Used", "to", "register", "a", "custom", "DocumentAccessor", "for", "a", "particular", "class", ".", "Any", "existing", "accessor", "for", "the", "class", "will", "be", "overridden", "." ]
train
https://github.com/helun/Ektorp/blob/b822c0d656aefb90a5e0cb5ec2de3daa969e3eaa/org.ektorp/src/main/java/org/ektorp/util/Documents.java#L47-L56
HubSpot/Singularity
SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java
SingularityClient.getTaskState
public Optional<SingularityTaskState> getTaskState(String taskId) { """ Get the current state of a task by its task ID, will only search active/inactive tasks, not pending @param taskId The task ID to search for @return A {@link SingularityTaskState} if the task was found among active or inactive tasks """ final Function<String, String> requestUri = (host) -> String.format(TRACK_BY_TASK_ID_FORMAT, getApiBase(host), taskId); return getSingle(requestUri, "track by task id", taskId, SingularityTaskState.class); }
java
public Optional<SingularityTaskState> getTaskState(String taskId) { final Function<String, String> requestUri = (host) -> String.format(TRACK_BY_TASK_ID_FORMAT, getApiBase(host), taskId); return getSingle(requestUri, "track by task id", taskId, SingularityTaskState.class); }
[ "public", "Optional", "<", "SingularityTaskState", ">", "getTaskState", "(", "String", "taskId", ")", "{", "final", "Function", "<", "String", ",", "String", ">", "requestUri", "=", "(", "host", ")", "-", ">", "String", ".", "format", "(", "TRACK_BY_TASK_ID_...
Get the current state of a task by its task ID, will only search active/inactive tasks, not pending @param taskId The task ID to search for @return A {@link SingularityTaskState} if the task was found among active or inactive tasks
[ "Get", "the", "current", "state", "of", "a", "task", "by", "its", "task", "ID", "will", "only", "search", "active", "/", "inactive", "tasks", "not", "pending" ]
train
https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java#L1561-L1564
xmlunit/xmlunit
xmlunit-assertj/src/main/java/org/xmlunit/assertj/SingleNodeAssert.java
SingleNodeAssert.hasAttribute
public SingleNodeAssert hasAttribute(String attributeName, String attributeValue) { """ Verifies that node has attribute with given name and value. @throws AssertionError if the actual node is {@code null}. @throws AssertionError if node has not attribute with given name and value. """ isNotNull(); final Map.Entry<QName, String> attribute = attributeForName(attributeName); if (attribute == null || !attribute.getValue().equals(attributeValue)) { throwAssertionError(shouldHaveAttributeWithValue(actual.getNodeName(), attributeName, attributeValue)); } return this; }
java
public SingleNodeAssert hasAttribute(String attributeName, String attributeValue) { isNotNull(); final Map.Entry<QName, String> attribute = attributeForName(attributeName); if (attribute == null || !attribute.getValue().equals(attributeValue)) { throwAssertionError(shouldHaveAttributeWithValue(actual.getNodeName(), attributeName, attributeValue)); } return this; }
[ "public", "SingleNodeAssert", "hasAttribute", "(", "String", "attributeName", ",", "String", "attributeValue", ")", "{", "isNotNull", "(", ")", ";", "final", "Map", ".", "Entry", "<", "QName", ",", "String", ">", "attribute", "=", "attributeForName", "(", "att...
Verifies that node has attribute with given name and value. @throws AssertionError if the actual node is {@code null}. @throws AssertionError if node has not attribute with given name and value.
[ "Verifies", "that", "node", "has", "attribute", "with", "given", "name", "and", "value", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-assertj/src/main/java/org/xmlunit/assertj/SingleNodeAssert.java#L70-L79
liferay/com-liferay-commerce
commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java
CommerceCurrencyPersistenceImpl.findByGroupId
@Override public List<CommerceCurrency> findByGroupId(long groupId, int start, int end) { """ Returns a range of all the commerce currencies where groupId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceCurrencyModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param start the lower bound of the range of commerce currencies @param end the upper bound of the range of commerce currencies (not inclusive) @return the range of matching commerce currencies """ return findByGroupId(groupId, start, end, null); }
java
@Override public List<CommerceCurrency> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceCurrency", ">", "findByGroupId", "(", "long", "groupId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce currencies where groupId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceCurrencyModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param groupId the group ID @param start the lower bound of the range of commerce currencies @param end the upper bound of the range of commerce currencies (not inclusive) @return the range of matching commerce currencies
[ "Returns", "a", "range", "of", "all", "the", "commerce", "currencies", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L1531-L1534
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShippingMethodPersistenceImpl.java
CommerceShippingMethodPersistenceImpl.removeByG_E
@Override public CommerceShippingMethod removeByG_E(long groupId, String engineKey) throws NoSuchShippingMethodException { """ Removes the commerce shipping method where groupId = &#63; and engineKey = &#63; from the database. @param groupId the group ID @param engineKey the engine key @return the commerce shipping method that was removed """ CommerceShippingMethod commerceShippingMethod = findByG_E(groupId, engineKey); return remove(commerceShippingMethod); }
java
@Override public CommerceShippingMethod removeByG_E(long groupId, String engineKey) throws NoSuchShippingMethodException { CommerceShippingMethod commerceShippingMethod = findByG_E(groupId, engineKey); return remove(commerceShippingMethod); }
[ "@", "Override", "public", "CommerceShippingMethod", "removeByG_E", "(", "long", "groupId", ",", "String", "engineKey", ")", "throws", "NoSuchShippingMethodException", "{", "CommerceShippingMethod", "commerceShippingMethod", "=", "findByG_E", "(", "groupId", ",", "engineK...
Removes the commerce shipping method where groupId = &#63; and engineKey = &#63; from the database. @param groupId the group ID @param engineKey the engine key @return the commerce shipping method that was removed
[ "Removes", "the", "commerce", "shipping", "method", "where", "groupId", "=", "&#63", ";", "and", "engineKey", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceShippingMethodPersistenceImpl.java#L773-L780
jbundle/jbundle
base/screen/view/data/src/main/java/org/jbundle/base/screen/view/data/DDataAccessScreen.java
DDataAccessScreen.sendData
public void sendData(Object req, Object res) throws Exception, IOException { """ Process an HTML get or post. You must override this method. @param req The servlet request. @param res The servlet response object. @exception ServletException From inherited class. @exception IOException From inherited class. """ this.sendData((HttpServletRequest)req, (HttpServletResponse)res); }
java
public void sendData(Object req, Object res) throws Exception, IOException { this.sendData((HttpServletRequest)req, (HttpServletResponse)res); }
[ "public", "void", "sendData", "(", "Object", "req", ",", "Object", "res", ")", "throws", "Exception", ",", "IOException", "{", "this", ".", "sendData", "(", "(", "HttpServletRequest", ")", "req", ",", "(", "HttpServletResponse", ")", "res", ")", ";", "}" ]
Process an HTML get or post. You must override this method. @param req The servlet request. @param res The servlet response object. @exception ServletException From inherited class. @exception IOException From inherited class.
[ "Process", "an", "HTML", "get", "or", "post", ".", "You", "must", "override", "this", "method", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/data/src/main/java/org/jbundle/base/screen/view/data/DDataAccessScreen.java#L84-L88
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createStrictPartialMock
public static synchronized <T> T createStrictPartialMock(Class<T> type, String methodNameToMock, Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) { """ Strictly mock a single specific method. Use this to handle overloaded methods. @param <T> The type of the mock. @param type The type that'll be used to create a mock instance. @param methodNameToMock The name of the method to mock @param firstArgumentType The type of the first parameter of the method to mock @param additionalArgumentTypes Optionally more parameter types that defines the method. Note that this is only needed to separate overloaded methods. @return A mock object of type <T>. """ return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); }
java
public static synchronized <T> T createStrictPartialMock(Class<T> type, String methodNameToMock, Class<?> firstArgumentType, Class<?>... additionalArgumentTypes) { return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); }
[ "public", "static", "synchronized", "<", "T", ">", "T", "createStrictPartialMock", "(", "Class", "<", "T", ">", "type", ",", "String", "methodNameToMock", ",", "Class", "<", "?", ">", "firstArgumentType", ",", "Class", "<", "?", ">", "...", "additionalArgume...
Strictly mock a single specific method. Use this to handle overloaded methods. @param <T> The type of the mock. @param type The type that'll be used to create a mock instance. @param methodNameToMock The name of the method to mock @param firstArgumentType The type of the first parameter of the method to mock @param additionalArgumentTypes Optionally more parameter types that defines the method. Note that this is only needed to separate overloaded methods. @return A mock object of type <T>.
[ "Strictly", "mock", "a", "single", "specific", "method", ".", "Use", "this", "to", "handle", "overloaded", "methods", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L485-L489