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
micronaut-projects/micronaut-core
session/src/main/java/io/micronaut/session/http/SessionForRequest.java
SessionForRequest.findOrCreate
public static Session findOrCreate(HttpRequest<?> request, SessionStore sessionStore) { """ Finds a session or creates a new one and stores it in the request attributes. @param request The Http Request @param sessionStore The session store to create the session if not found @return A session if found in the request attributes or a new session stored in the request attributes. """ return find(request).orElseGet(() -> create(sessionStore, request)); }
java
public static Session findOrCreate(HttpRequest<?> request, SessionStore sessionStore) { return find(request).orElseGet(() -> create(sessionStore, request)); }
[ "public", "static", "Session", "findOrCreate", "(", "HttpRequest", "<", "?", ">", "request", ",", "SessionStore", "sessionStore", ")", "{", "return", "find", "(", "request", ")", ".", "orElseGet", "(", "(", ")", "->", "create", "(", "sessionStore", ",", "request", ")", ")", ";", "}" ]
Finds a session or creates a new one and stores it in the request attributes. @param request The Http Request @param sessionStore The session store to create the session if not found @return A session if found in the request attributes or a new session stored in the request attributes.
[ "Finds", "a", "session", "or", "creates", "a", "new", "one", "and", "stores", "it", "in", "the", "request", "attributes", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/session/src/main/java/io/micronaut/session/http/SessionForRequest.java#L62-L64
mikepenz/Materialize
library/src/main/java/com/mikepenz/materialize/holder/ColorHolder.java
ColorHolder.applyToOr
public void applyToOr(TextView textView, ColorStateList colorDefault) { """ a small helper to set the text color to a textView null save @param textView @param colorDefault """ if (mColorInt != 0) { textView.setTextColor(mColorInt); } else if (mColorRes != -1) { textView.setTextColor(ContextCompat.getColor(textView.getContext(), mColorRes)); } else if (colorDefault != null) { textView.setTextColor(colorDefault); } }
java
public void applyToOr(TextView textView, ColorStateList colorDefault) { if (mColorInt != 0) { textView.setTextColor(mColorInt); } else if (mColorRes != -1) { textView.setTextColor(ContextCompat.getColor(textView.getContext(), mColorRes)); } else if (colorDefault != null) { textView.setTextColor(colorDefault); } }
[ "public", "void", "applyToOr", "(", "TextView", "textView", ",", "ColorStateList", "colorDefault", ")", "{", "if", "(", "mColorInt", "!=", "0", ")", "{", "textView", ".", "setTextColor", "(", "mColorInt", ")", ";", "}", "else", "if", "(", "mColorRes", "!=", "-", "1", ")", "{", "textView", ".", "setTextColor", "(", "ContextCompat", ".", "getColor", "(", "textView", ".", "getContext", "(", ")", ",", "mColorRes", ")", ")", ";", "}", "else", "if", "(", "colorDefault", "!=", "null", ")", "{", "textView", ".", "setTextColor", "(", "colorDefault", ")", ";", "}", "}" ]
a small helper to set the text color to a textView null save @param textView @param colorDefault
[ "a", "small", "helper", "to", "set", "the", "text", "color", "to", "a", "textView", "null", "save" ]
train
https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/holder/ColorHolder.java#L89-L97
hector-client/hector
core/src/main/java/me/prettyprint/hector/api/factory/HFactory.java
HFactory.getOrCreateCluster
public static Cluster getOrCreateCluster(String clusterName, String hostIp) { """ Method tries to create a Cluster instance for an existing Cassandra cluster. If another class already called getOrCreateCluster, the factory returns the cached instance. If the instance doesn't exist in memory, a new ThriftCluster is created and cached. Example usage for a default installation of Cassandra. String clusterName = "Test Cluster"; String host = "localhost:9160"; Cluster cluster = HFactory.getOrCreateCluster(clusterName, host); Note the host should be the hostname and port number. It is preferable to use the hostname instead of the IP address. @param clusterName The cluster name. This is an identifying string for the cluster, e.g. "production" or "test" etc. Clusters will be created on demand per each unique clusterName key. @param hostIp host:ip format string @return """ return getOrCreateCluster(clusterName, new CassandraHostConfigurator(hostIp)); }
java
public static Cluster getOrCreateCluster(String clusterName, String hostIp) { return getOrCreateCluster(clusterName, new CassandraHostConfigurator(hostIp)); }
[ "public", "static", "Cluster", "getOrCreateCluster", "(", "String", "clusterName", ",", "String", "hostIp", ")", "{", "return", "getOrCreateCluster", "(", "clusterName", ",", "new", "CassandraHostConfigurator", "(", "hostIp", ")", ")", ";", "}" ]
Method tries to create a Cluster instance for an existing Cassandra cluster. If another class already called getOrCreateCluster, the factory returns the cached instance. If the instance doesn't exist in memory, a new ThriftCluster is created and cached. Example usage for a default installation of Cassandra. String clusterName = "Test Cluster"; String host = "localhost:9160"; Cluster cluster = HFactory.getOrCreateCluster(clusterName, host); Note the host should be the hostname and port number. It is preferable to use the hostname instead of the IP address. @param clusterName The cluster name. This is an identifying string for the cluster, e.g. "production" or "test" etc. Clusters will be created on demand per each unique clusterName key. @param hostIp host:ip format string @return
[ "Method", "tries", "to", "create", "a", "Cluster", "instance", "for", "an", "existing", "Cassandra", "cluster", ".", "If", "another", "class", "already", "called", "getOrCreateCluster", "the", "factory", "returns", "the", "cached", "instance", ".", "If", "the", "instance", "doesn", "t", "exist", "in", "memory", "a", "new", "ThriftCluster", "is", "created", "and", "cached", "." ]
train
https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/core/src/main/java/me/prettyprint/hector/api/factory/HFactory.java#L132-L135
Talend/tesb-rt-se
sam/sam-agent/src/main/java/org/talend/esb/sam/agent/lifecycle/AbstractListenerImpl.java
AbstractListenerImpl.createEvent
private Event createEvent(Endpoint endpoint, EventTypeEnum type) { """ Creates the event for endpoint with specific type. @param endpoint the endpoint @param type the type @return the event """ Event event = new Event(); MessageInfo messageInfo = new MessageInfo(); Originator originator = new Originator(); event.setMessageInfo(messageInfo); event.setOriginator(originator); Date date = new Date(); event.setTimestamp(date); event.setEventType(type); messageInfo.setPortType( endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString()); String transportType = null; if (endpoint.getBinding() instanceof SoapBinding) { SoapBinding soapBinding = (SoapBinding)endpoint.getBinding(); if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) { SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo(); transportType = soapBindingInfo.getTransportURI(); } } messageInfo.setTransportType((transportType != null) ? transportType : "Unknown transport type"); originator.setProcessId(Converter.getPID()); try { InetAddress inetAddress = InetAddress.getLocalHost(); originator.setIp(inetAddress.getHostAddress()); originator.setHostname(inetAddress.getHostName()); } catch (UnknownHostException e) { originator.setHostname("Unknown hostname"); originator.setIp("Unknown ip address"); } String address = endpoint.getEndpointInfo().getAddress(); event.getCustomInfo().put("address", address); return event; }
java
private Event createEvent(Endpoint endpoint, EventTypeEnum type) { Event event = new Event(); MessageInfo messageInfo = new MessageInfo(); Originator originator = new Originator(); event.setMessageInfo(messageInfo); event.setOriginator(originator); Date date = new Date(); event.setTimestamp(date); event.setEventType(type); messageInfo.setPortType( endpoint.getBinding().getBindingInfo().getService().getInterface().getName().toString()); String transportType = null; if (endpoint.getBinding() instanceof SoapBinding) { SoapBinding soapBinding = (SoapBinding)endpoint.getBinding(); if (soapBinding.getBindingInfo() instanceof SoapBindingInfo) { SoapBindingInfo soapBindingInfo = (SoapBindingInfo)soapBinding.getBindingInfo(); transportType = soapBindingInfo.getTransportURI(); } } messageInfo.setTransportType((transportType != null) ? transportType : "Unknown transport type"); originator.setProcessId(Converter.getPID()); try { InetAddress inetAddress = InetAddress.getLocalHost(); originator.setIp(inetAddress.getHostAddress()); originator.setHostname(inetAddress.getHostName()); } catch (UnknownHostException e) { originator.setHostname("Unknown hostname"); originator.setIp("Unknown ip address"); } String address = endpoint.getEndpointInfo().getAddress(); event.getCustomInfo().put("address", address); return event; }
[ "private", "Event", "createEvent", "(", "Endpoint", "endpoint", ",", "EventTypeEnum", "type", ")", "{", "Event", "event", "=", "new", "Event", "(", ")", ";", "MessageInfo", "messageInfo", "=", "new", "MessageInfo", "(", ")", ";", "Originator", "originator", "=", "new", "Originator", "(", ")", ";", "event", ".", "setMessageInfo", "(", "messageInfo", ")", ";", "event", ".", "setOriginator", "(", "originator", ")", ";", "Date", "date", "=", "new", "Date", "(", ")", ";", "event", ".", "setTimestamp", "(", "date", ")", ";", "event", ".", "setEventType", "(", "type", ")", ";", "messageInfo", ".", "setPortType", "(", "endpoint", ".", "getBinding", "(", ")", ".", "getBindingInfo", "(", ")", ".", "getService", "(", ")", ".", "getInterface", "(", ")", ".", "getName", "(", ")", ".", "toString", "(", ")", ")", ";", "String", "transportType", "=", "null", ";", "if", "(", "endpoint", ".", "getBinding", "(", ")", "instanceof", "SoapBinding", ")", "{", "SoapBinding", "soapBinding", "=", "(", "SoapBinding", ")", "endpoint", ".", "getBinding", "(", ")", ";", "if", "(", "soapBinding", ".", "getBindingInfo", "(", ")", "instanceof", "SoapBindingInfo", ")", "{", "SoapBindingInfo", "soapBindingInfo", "=", "(", "SoapBindingInfo", ")", "soapBinding", ".", "getBindingInfo", "(", ")", ";", "transportType", "=", "soapBindingInfo", ".", "getTransportURI", "(", ")", ";", "}", "}", "messageInfo", ".", "setTransportType", "(", "(", "transportType", "!=", "null", ")", "?", "transportType", ":", "\"Unknown transport type\"", ")", ";", "originator", ".", "setProcessId", "(", "Converter", ".", "getPID", "(", ")", ")", ";", "try", "{", "InetAddress", "inetAddress", "=", "InetAddress", ".", "getLocalHost", "(", ")", ";", "originator", ".", "setIp", "(", "inetAddress", ".", "getHostAddress", "(", ")", ")", ";", "originator", ".", "setHostname", "(", "inetAddress", ".", "getHostName", "(", ")", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "originator", ".", "setHostname", "(", "\"Unknown hostname\"", ")", ";", "originator", ".", "setIp", "(", "\"Unknown ip address\"", ")", ";", "}", "String", "address", "=", "endpoint", ".", "getEndpointInfo", "(", ")", ".", "getAddress", "(", ")", ";", "event", ".", "getCustomInfo", "(", ")", ".", "put", "(", "\"address\"", ",", "address", ")", ";", "return", "event", ";", "}" ]
Creates the event for endpoint with specific type. @param endpoint the endpoint @param type the type @return the event
[ "Creates", "the", "event", "for", "endpoint", "with", "specific", "type", "." ]
train
https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/sam/sam-agent/src/main/java/org/talend/esb/sam/agent/lifecycle/AbstractListenerImpl.java#L126-L165
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.allOf
@SafeVarargs public static <T extends Tree> Matcher<T> allOf(final Matcher<? super T>... matchers) { """ Compose several matchers together, such that the composite matches an AST node iff all the given matchers do. """ return new Matcher<T>() { @Override public boolean matches(T t, VisitorState state) { for (Matcher<? super T> matcher : matchers) { if (!matcher.matches(t, state)) { return false; } } return true; } }; }
java
@SafeVarargs public static <T extends Tree> Matcher<T> allOf(final Matcher<? super T>... matchers) { return new Matcher<T>() { @Override public boolean matches(T t, VisitorState state) { for (Matcher<? super T> matcher : matchers) { if (!matcher.matches(t, state)) { return false; } } return true; } }; }
[ "@", "SafeVarargs", "public", "static", "<", "T", "extends", "Tree", ">", "Matcher", "<", "T", ">", "allOf", "(", "final", "Matcher", "<", "?", "super", "T", ">", "...", "matchers", ")", "{", "return", "new", "Matcher", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "T", "t", ",", "VisitorState", "state", ")", "{", "for", "(", "Matcher", "<", "?", "super", "T", ">", "matcher", ":", "matchers", ")", "{", "if", "(", "!", "matcher", ".", "matches", "(", "t", ",", "state", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "}", ";", "}" ]
Compose several matchers together, such that the composite matches an AST node iff all the given matchers do.
[ "Compose", "several", "matchers", "together", "such", "that", "the", "composite", "matches", "an", "AST", "node", "iff", "all", "the", "given", "matchers", "do", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L131-L144
spotify/helios
helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java
ZooKeeperMasterModel.getJobHistory
@Override public List<TaskStatusEvent> getJobHistory(final JobId jobId) throws JobDoesNotExistException { """ Given a jobId, returns the N most recent events in its history in the cluster. """ return getJobHistory(jobId, null); }
java
@Override public List<TaskStatusEvent> getJobHistory(final JobId jobId) throws JobDoesNotExistException { return getJobHistory(jobId, null); }
[ "@", "Override", "public", "List", "<", "TaskStatusEvent", ">", "getJobHistory", "(", "final", "JobId", "jobId", ")", "throws", "JobDoesNotExistException", "{", "return", "getJobHistory", "(", "jobId", ",", "null", ")", ";", "}" ]
Given a jobId, returns the N most recent events in its history in the cluster.
[ "Given", "a", "jobId", "returns", "the", "N", "most", "recent", "events", "in", "its", "history", "in", "the", "cluster", "." ]
train
https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java#L284-L287
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/util/ResourceTable.java
ResourceTable.copyRecord
public void copyRecord(Record recAlt, Record recMain) { """ Copy the fields from the (main) source to the (mirrored) destination record. This is done before any write or set. @param recAlt Destination record @param recMain Source record """ // Already done in preCopyRecord(), just make sure the primary key is the same this.copyKeys(recAlt, recMain, DBConstants.MAIN_KEY_AREA); }
java
public void copyRecord(Record recAlt, Record recMain) { // Already done in preCopyRecord(), just make sure the primary key is the same this.copyKeys(recAlt, recMain, DBConstants.MAIN_KEY_AREA); }
[ "public", "void", "copyRecord", "(", "Record", "recAlt", ",", "Record", "recMain", ")", "{", "// Already done in preCopyRecord(), just make sure the primary key is the same", "this", ".", "copyKeys", "(", "recAlt", ",", "recMain", ",", "DBConstants", ".", "MAIN_KEY_AREA", ")", ";", "}" ]
Copy the fields from the (main) source to the (mirrored) destination record. This is done before any write or set. @param recAlt Destination record @param recMain Source record
[ "Copy", "the", "fields", "from", "the", "(", "main", ")", "source", "to", "the", "(", "mirrored", ")", "destination", "record", ".", "This", "is", "done", "before", "any", "write", "or", "set", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/util/ResourceTable.java#L118-L122
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/store/ServiceBuilder.java
ServiceBuilder.newInMemoryBuilder
@VisibleForTesting public static ServiceBuilder newInMemoryBuilder(ServiceBuilderConfig builderConfig, ExecutorBuilder executorBuilder) { """ Creates a new instance of the ServiceBuilder class which is contained in memory. Any data added to this service will be lost when the object is garbage collected or the process terminates. @param builderConfig The ServiceBuilderConfig to use. @param executorBuilder A Function that, given a thread count and a pool name, creates a ScheduledExecutorService with the given number of threads that have the given name as prefix. @return The new instance of the ServiceBuilder. """ ServiceConfig serviceConfig = builderConfig.getConfig(ServiceConfig::builder); ServiceBuilder builder; if (serviceConfig.isReadOnlySegmentStore()) { // Only components required for ReadOnly SegmentStore. builder = new ReadOnlyServiceBuilder(builderConfig, serviceConfig, executorBuilder); } else { // Components that are required for general SegmentStore. builder = new ServiceBuilder(builderConfig, serviceConfig, executorBuilder) .withCacheFactory(setup -> new InMemoryCacheFactory()); } // Components that are required for all types of SegmentStore. return builder .withDataLogFactory(setup -> new InMemoryDurableDataLogFactory(setup.getCoreExecutor())) .withContainerManager(setup -> new LocalSegmentContainerManager( setup.getContainerRegistry(), setup.getSegmentToContainerMapper())) .withStorageFactory(setup -> new InMemoryStorageFactory(setup.getStorageExecutor())) .withStreamSegmentStore(setup -> new StreamSegmentService(setup.getContainerRegistry(), setup.getSegmentToContainerMapper())); }
java
@VisibleForTesting public static ServiceBuilder newInMemoryBuilder(ServiceBuilderConfig builderConfig, ExecutorBuilder executorBuilder) { ServiceConfig serviceConfig = builderConfig.getConfig(ServiceConfig::builder); ServiceBuilder builder; if (serviceConfig.isReadOnlySegmentStore()) { // Only components required for ReadOnly SegmentStore. builder = new ReadOnlyServiceBuilder(builderConfig, serviceConfig, executorBuilder); } else { // Components that are required for general SegmentStore. builder = new ServiceBuilder(builderConfig, serviceConfig, executorBuilder) .withCacheFactory(setup -> new InMemoryCacheFactory()); } // Components that are required for all types of SegmentStore. return builder .withDataLogFactory(setup -> new InMemoryDurableDataLogFactory(setup.getCoreExecutor())) .withContainerManager(setup -> new LocalSegmentContainerManager( setup.getContainerRegistry(), setup.getSegmentToContainerMapper())) .withStorageFactory(setup -> new InMemoryStorageFactory(setup.getStorageExecutor())) .withStreamSegmentStore(setup -> new StreamSegmentService(setup.getContainerRegistry(), setup.getSegmentToContainerMapper())); }
[ "@", "VisibleForTesting", "public", "static", "ServiceBuilder", "newInMemoryBuilder", "(", "ServiceBuilderConfig", "builderConfig", ",", "ExecutorBuilder", "executorBuilder", ")", "{", "ServiceConfig", "serviceConfig", "=", "builderConfig", ".", "getConfig", "(", "ServiceConfig", "::", "builder", ")", ";", "ServiceBuilder", "builder", ";", "if", "(", "serviceConfig", ".", "isReadOnlySegmentStore", "(", ")", ")", "{", "// Only components required for ReadOnly SegmentStore.", "builder", "=", "new", "ReadOnlyServiceBuilder", "(", "builderConfig", ",", "serviceConfig", ",", "executorBuilder", ")", ";", "}", "else", "{", "// Components that are required for general SegmentStore.", "builder", "=", "new", "ServiceBuilder", "(", "builderConfig", ",", "serviceConfig", ",", "executorBuilder", ")", ".", "withCacheFactory", "(", "setup", "->", "new", "InMemoryCacheFactory", "(", ")", ")", ";", "}", "// Components that are required for all types of SegmentStore.", "return", "builder", ".", "withDataLogFactory", "(", "setup", "->", "new", "InMemoryDurableDataLogFactory", "(", "setup", ".", "getCoreExecutor", "(", ")", ")", ")", ".", "withContainerManager", "(", "setup", "->", "new", "LocalSegmentContainerManager", "(", "setup", ".", "getContainerRegistry", "(", ")", ",", "setup", ".", "getSegmentToContainerMapper", "(", ")", ")", ")", ".", "withStorageFactory", "(", "setup", "->", "new", "InMemoryStorageFactory", "(", "setup", ".", "getStorageExecutor", "(", ")", ")", ")", ".", "withStreamSegmentStore", "(", "setup", "->", "new", "StreamSegmentService", "(", "setup", ".", "getContainerRegistry", "(", ")", ",", "setup", ".", "getSegmentToContainerMapper", "(", ")", ")", ")", ";", "}" ]
Creates a new instance of the ServiceBuilder class which is contained in memory. Any data added to this service will be lost when the object is garbage collected or the process terminates. @param builderConfig The ServiceBuilderConfig to use. @param executorBuilder A Function that, given a thread count and a pool name, creates a ScheduledExecutorService with the given number of threads that have the given name as prefix. @return The new instance of the ServiceBuilder.
[ "Creates", "a", "new", "instance", "of", "the", "ServiceBuilder", "class", "which", "is", "contained", "in", "memory", ".", "Any", "data", "added", "to", "this", "service", "will", "be", "lost", "when", "the", "object", "is", "garbage", "collected", "or", "the", "process", "terminates", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/store/ServiceBuilder.java#L386-L408
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/Hud.java
Hud.generateSubMenu
private void generateSubMenu(final Collection<ActionRef> parents, final ActionRef action, Featurable menu) { """ Generate sub menu creation if menu contains sub menu. @param parents The parents menu. @param action The current action. @param menu The current menu to check. """ menu.getFeature(Actionable.class).setAction(() -> { clearMenus(); createMenus(parents, action.getRefs()); }); }
java
private void generateSubMenu(final Collection<ActionRef> parents, final ActionRef action, Featurable menu) { menu.getFeature(Actionable.class).setAction(() -> { clearMenus(); createMenus(parents, action.getRefs()); }); }
[ "private", "void", "generateSubMenu", "(", "final", "Collection", "<", "ActionRef", ">", "parents", ",", "final", "ActionRef", "action", ",", "Featurable", "menu", ")", "{", "menu", ".", "getFeature", "(", "Actionable", ".", "class", ")", ".", "setAction", "(", "(", ")", "->", "{", "clearMenus", "(", ")", ";", "createMenus", "(", "parents", ",", "action", ".", "getRefs", "(", ")", ")", ";", "}", ")", ";", "}" ]
Generate sub menu creation if menu contains sub menu. @param parents The parents menu. @param action The current action. @param menu The current menu to check.
[ "Generate", "sub", "menu", "creation", "if", "menu", "contains", "sub", "menu", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/collidable/selector/Hud.java#L235-L242
atomix/copycat
server/src/main/java/io/atomix/copycat/server/storage/compaction/MajorCompactionTask.java
MajorCompactionTask.mergeReleasedEntries
private void mergeReleasedEntries(Segment segment, OffsetPredicate predicate, Segment compactSegment) { """ Updates the new compact segment with entries that were released in the given segment during compaction. """ for (long i = segment.firstIndex(); i <= segment.lastIndex(); i++) { long offset = segment.offset(i); if (offset != -1 && !predicate.test(offset)) { compactSegment.release(i); } } }
java
private void mergeReleasedEntries(Segment segment, OffsetPredicate predicate, Segment compactSegment) { for (long i = segment.firstIndex(); i <= segment.lastIndex(); i++) { long offset = segment.offset(i); if (offset != -1 && !predicate.test(offset)) { compactSegment.release(i); } } }
[ "private", "void", "mergeReleasedEntries", "(", "Segment", "segment", ",", "OffsetPredicate", "predicate", ",", "Segment", "compactSegment", ")", "{", "for", "(", "long", "i", "=", "segment", ".", "firstIndex", "(", ")", ";", "i", "<=", "segment", ".", "lastIndex", "(", ")", ";", "i", "++", ")", "{", "long", "offset", "=", "segment", ".", "offset", "(", "i", ")", ";", "if", "(", "offset", "!=", "-", "1", "&&", "!", "predicate", ".", "test", "(", "offset", ")", ")", "{", "compactSegment", ".", "release", "(", "i", ")", ";", "}", "}", "}" ]
Updates the new compact segment with entries that were released in the given segment during compaction.
[ "Updates", "the", "new", "compact", "segment", "with", "entries", "that", "were", "released", "in", "the", "given", "segment", "during", "compaction", "." ]
train
https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/storage/compaction/MajorCompactionTask.java#L306-L313
nguillaumin/slick2d-maven
slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/TTFSubSetFile.java
TTFSubSetFile.getLongCheckSum
private long getLongCheckSum(int start, int size) { """ Get the checksum as a long @param start The start value @param size The size of the values to checksum @return The long checksum """ // All the tables here are aligned on four byte boundaries // Add remainder to size if it's not a multiple of 4 int remainder = size % 4; if (remainder != 0) { size += remainder; } long sum = 0; for (int i = 0; i < size; i += 4) { int l = (output[start + i] << 24); l += (output[start + i + 1] << 16); l += (output[start + i + 2] << 16); l += (output[start + i + 3] << 16); sum += l; if (sum > 0xffffffff) { sum = sum - 0xffffffff; } } return sum; }
java
private long getLongCheckSum(int start, int size) { // All the tables here are aligned on four byte boundaries // Add remainder to size if it's not a multiple of 4 int remainder = size % 4; if (remainder != 0) { size += remainder; } long sum = 0; for (int i = 0; i < size; i += 4) { int l = (output[start + i] << 24); l += (output[start + i + 1] << 16); l += (output[start + i + 2] << 16); l += (output[start + i + 3] << 16); sum += l; if (sum > 0xffffffff) { sum = sum - 0xffffffff; } } return sum; }
[ "private", "long", "getLongCheckSum", "(", "int", "start", ",", "int", "size", ")", "{", "// All the tables here are aligned on four byte boundaries", "// Add remainder to size if it's not a multiple of 4", "int", "remainder", "=", "size", "%", "4", ";", "if", "(", "remainder", "!=", "0", ")", "{", "size", "+=", "remainder", ";", "}", "long", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "+=", "4", ")", "{", "int", "l", "=", "(", "output", "[", "start", "+", "i", "]", "<<", "24", ")", ";", "l", "+=", "(", "output", "[", "start", "+", "i", "+", "1", "]", "<<", "16", ")", ";", "l", "+=", "(", "output", "[", "start", "+", "i", "+", "2", "]", "<<", "16", ")", ";", "l", "+=", "(", "output", "[", "start", "+", "i", "+", "3", "]", "<<", "16", ")", ";", "sum", "+=", "l", ";", "if", "(", "sum", ">", "0xffffffff", ")", "{", "sum", "=", "sum", "-", "0xffffffff", ";", "}", "}", "return", "sum", ";", "}" ]
Get the checksum as a long @param start The start value @param size The size of the values to checksum @return The long checksum
[ "Get", "the", "checksum", "as", "a", "long" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/TTFSubSetFile.java#L956-L978
line/armeria
core/src/main/java/com/linecorp/armeria/server/auth/HttpAuthService.java
HttpAuthService.newDecorator
@SafeVarargs public static Function<Service<HttpRequest, HttpResponse>, HttpAuthService> newDecorator(Authorizer<HttpRequest>... authorizers) { """ Creates a new HTTP authorization {@link Service} decorator using the specified {@link Authorizer}s. @param authorizers the array of {@link Authorizer}s. """ return newDecorator(ImmutableList.copyOf(requireNonNull(authorizers, "authorizers"))); }
java
@SafeVarargs public static Function<Service<HttpRequest, HttpResponse>, HttpAuthService> newDecorator(Authorizer<HttpRequest>... authorizers) { return newDecorator(ImmutableList.copyOf(requireNonNull(authorizers, "authorizers"))); }
[ "@", "SafeVarargs", "public", "static", "Function", "<", "Service", "<", "HttpRequest", ",", "HttpResponse", ">", ",", "HttpAuthService", ">", "newDecorator", "(", "Authorizer", "<", "HttpRequest", ">", "...", "authorizers", ")", "{", "return", "newDecorator", "(", "ImmutableList", ".", "copyOf", "(", "requireNonNull", "(", "authorizers", ",", "\"authorizers\"", ")", ")", ")", ";", "}" ]
Creates a new HTTP authorization {@link Service} decorator using the specified {@link Authorizer}s. @param authorizers the array of {@link Authorizer}s.
[ "Creates", "a", "new", "HTTP", "authorization", "{", "@link", "Service", "}", "decorator", "using", "the", "specified", "{", "@link", "Authorizer", "}", "s", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/auth/HttpAuthService.java#L61-L65
rey5137/material
material/src/main/java/com/rey/material/app/Dialog.java
Dialog.contentMargin
public Dialog contentMargin(int left, int top, int right, int bottom) { """ Set the margin between content view and Dialog border. @param left The left margin size in pixels. @param top The top margin size in pixels. @param right The right margin size in pixels. @param bottom The bottom margin size in pixels. @return The Dialog for chaining methods. """ mCardView.setContentMargin(left, top, right, bottom); return this; }
java
public Dialog contentMargin(int left, int top, int right, int bottom){ mCardView.setContentMargin(left, top, right, bottom); return this; }
[ "public", "Dialog", "contentMargin", "(", "int", "left", ",", "int", "top", ",", "int", "right", ",", "int", "bottom", ")", "{", "mCardView", ".", "setContentMargin", "(", "left", ",", "top", ",", "right", ",", "bottom", ")", ";", "return", "this", ";", "}" ]
Set the margin between content view and Dialog border. @param left The left margin size in pixels. @param top The top margin size in pixels. @param right The right margin size in pixels. @param bottom The bottom margin size in pixels. @return The Dialog for chaining methods.
[ "Set", "the", "margin", "between", "content", "view", "and", "Dialog", "border", "." ]
train
https://github.com/rey5137/material/blob/1bbcac2686a0023ef7720d3fe455bb116d115af8/material/src/main/java/com/rey/material/app/Dialog.java#L986-L989
UrielCh/ovh-java-sdk
ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java
ApiOvhCdndedicated.serviceName_domains_domain_backends_ip_GET
public OvhBackend serviceName_domains_domain_backends_ip_GET(String serviceName, String domain, String ip) throws IOException { """ Get this object properties REST: GET /cdn/dedicated/{serviceName}/domains/{domain}/backends/{ip} @param serviceName [required] The internal name of your CDN offer @param domain [required] Domain of this object @param ip [required] """ String qPath = "/cdn/dedicated/{serviceName}/domains/{domain}/backends/{ip}"; StringBuilder sb = path(qPath, serviceName, domain, ip); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhBackend.class); }
java
public OvhBackend serviceName_domains_domain_backends_ip_GET(String serviceName, String domain, String ip) throws IOException { String qPath = "/cdn/dedicated/{serviceName}/domains/{domain}/backends/{ip}"; StringBuilder sb = path(qPath, serviceName, domain, ip); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhBackend.class); }
[ "public", "OvhBackend", "serviceName_domains_domain_backends_ip_GET", "(", "String", "serviceName", ",", "String", "domain", ",", "String", "ip", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cdn/dedicated/{serviceName}/domains/{domain}/backends/{ip}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "domain", ",", "ip", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhBackend", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /cdn/dedicated/{serviceName}/domains/{domain}/backends/{ip} @param serviceName [required] The internal name of your CDN offer @param domain [required] Domain of this object @param ip [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java#L144-L149
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/TermStatementUpdate.java
TermStatementUpdate.processDescriptions
protected void processDescriptions(List<MonolingualTextValue> descriptions) { """ Adds descriptions to the item. @param descriptions the descriptions to add """ for(MonolingualTextValue description : descriptions) { NameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode()); // only mark the description as added if the value we are writing is different from the current one if (currentValue == null || !currentValue.value.equals(description)) { newDescriptions.put(description.getLanguageCode(), new NameWithUpdate(description, true)); } } }
java
protected void processDescriptions(List<MonolingualTextValue> descriptions) { for(MonolingualTextValue description : descriptions) { NameWithUpdate currentValue = newDescriptions.get(description.getLanguageCode()); // only mark the description as added if the value we are writing is different from the current one if (currentValue == null || !currentValue.value.equals(description)) { newDescriptions.put(description.getLanguageCode(), new NameWithUpdate(description, true)); } } }
[ "protected", "void", "processDescriptions", "(", "List", "<", "MonolingualTextValue", ">", "descriptions", ")", "{", "for", "(", "MonolingualTextValue", "description", ":", "descriptions", ")", "{", "NameWithUpdate", "currentValue", "=", "newDescriptions", ".", "get", "(", "description", ".", "getLanguageCode", "(", ")", ")", ";", "// only mark the description as added if the value we are writing is different from the current one", "if", "(", "currentValue", "==", "null", "||", "!", "currentValue", ".", "value", ".", "equals", "(", "description", ")", ")", "{", "newDescriptions", ".", "put", "(", "description", ".", "getLanguageCode", "(", ")", ",", "new", "NameWithUpdate", "(", "description", ",", "true", ")", ")", ";", "}", "}", "}" ]
Adds descriptions to the item. @param descriptions the descriptions to add
[ "Adds", "descriptions", "to", "the", "item", "." ]
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/TermStatementUpdate.java#L232-L241
OpenLiberty/open-liberty
dev/com.ibm.ws.security.utility/src/com/ibm/ws/security/utility/tasks/CreateSSLCertificateTask.java
CreateSSLCertificateTask.createConfigFileIfNeeded
protected String createConfigFileIfNeeded(String serverDir, String[] commandLine, String xmlSnippet) { """ This method acts like a filter for xml snippets. If the user provides the {@link #ARG_OPT_CREATE_CONFIG_FILE} option, then we will write it to a file and provide an include snippet. Otherwise, we just return the provided xml snippet. @param serverDir Path to the root of the server. e.g. /path/to/wlp/usr/servers/myServer/ @param commandLine The command-line arguments. @param xmlSnippet The xml configuration the task produced. @return An include snippet or the given xmlSnippet. """ String utilityName = this.scriptName; String taskName = this.getTaskName(); final String MAGICAL_SENTINEL = "@!$#%$#%32543265k425k4/3nj5k43n?m2|5k4\\n5k2345"; /* * getArgumentValue() can return 3 possible values. * null - The ARG_OPT_CREATE_CONFIG_FILE option was provided, but no value was associated with it. * MAGICAL_SENTINEL - The ARG_OPT_CREATE_CONFIG_FILE option was not in the command-line at all. * ??? - The value associated with ARG_OPT_CREATE_CONFIG_FILE is ???. */ String targetFilepath = getArgumentValue(ARG_CREATE_CONFIG_FILE, commandLine, MAGICAL_SENTINEL); if (targetFilepath == MAGICAL_SENTINEL) { // the config file is not needed return xmlSnippet; } // note that generateConfigFileName() will handle the case where targetFilepath == null File outputFile = generateConfigFileName(utilityName, taskName, serverDir, targetFilepath); String xmlTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NL + "<server description=\"This file was generated by the ''{0} {1}'' command on {2,date,yyyy-MM-dd HH:mm:ss z}.\">" + NL + "{3}" + NL + "</server>" + NL; String xmlData = MessageFormat.format(xmlTemplate, utilityName, taskName, Calendar.getInstance().getTime(), xmlSnippet); fileUtility.createParentDirectory(stdout, outputFile); fileUtility.writeToFile(stderr, xmlData, outputFile); String includeSnippet = " <include location=\"" + outputFile.getAbsolutePath() + "\" />" + NL; return includeSnippet; }
java
protected String createConfigFileIfNeeded(String serverDir, String[] commandLine, String xmlSnippet) { String utilityName = this.scriptName; String taskName = this.getTaskName(); final String MAGICAL_SENTINEL = "@!$#%$#%32543265k425k4/3nj5k43n?m2|5k4\\n5k2345"; /* * getArgumentValue() can return 3 possible values. * null - The ARG_OPT_CREATE_CONFIG_FILE option was provided, but no value was associated with it. * MAGICAL_SENTINEL - The ARG_OPT_CREATE_CONFIG_FILE option was not in the command-line at all. * ??? - The value associated with ARG_OPT_CREATE_CONFIG_FILE is ???. */ String targetFilepath = getArgumentValue(ARG_CREATE_CONFIG_FILE, commandLine, MAGICAL_SENTINEL); if (targetFilepath == MAGICAL_SENTINEL) { // the config file is not needed return xmlSnippet; } // note that generateConfigFileName() will handle the case where targetFilepath == null File outputFile = generateConfigFileName(utilityName, taskName, serverDir, targetFilepath); String xmlTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NL + "<server description=\"This file was generated by the ''{0} {1}'' command on {2,date,yyyy-MM-dd HH:mm:ss z}.\">" + NL + "{3}" + NL + "</server>" + NL; String xmlData = MessageFormat.format(xmlTemplate, utilityName, taskName, Calendar.getInstance().getTime(), xmlSnippet); fileUtility.createParentDirectory(stdout, outputFile); fileUtility.writeToFile(stderr, xmlData, outputFile); String includeSnippet = " <include location=\"" + outputFile.getAbsolutePath() + "\" />" + NL; return includeSnippet; }
[ "protected", "String", "createConfigFileIfNeeded", "(", "String", "serverDir", ",", "String", "[", "]", "commandLine", ",", "String", "xmlSnippet", ")", "{", "String", "utilityName", "=", "this", ".", "scriptName", ";", "String", "taskName", "=", "this", ".", "getTaskName", "(", ")", ";", "final", "String", "MAGICAL_SENTINEL", "=", "\"@!$#%$#%32543265k425k4/3nj5k43n?m2|5k4\\\\n5k2345\"", ";", "/*\n * getArgumentValue() can return 3 possible values.\n * null - The ARG_OPT_CREATE_CONFIG_FILE option was provided, but no value was associated with it.\n * MAGICAL_SENTINEL - The ARG_OPT_CREATE_CONFIG_FILE option was not in the command-line at all.\n * ??? - The value associated with ARG_OPT_CREATE_CONFIG_FILE is ???.\n */", "String", "targetFilepath", "=", "getArgumentValue", "(", "ARG_CREATE_CONFIG_FILE", ",", "commandLine", ",", "MAGICAL_SENTINEL", ")", ";", "if", "(", "targetFilepath", "==", "MAGICAL_SENTINEL", ")", "{", "// the config file is not needed", "return", "xmlSnippet", ";", "}", "// note that generateConfigFileName() will handle the case where targetFilepath == null", "File", "outputFile", "=", "generateConfigFileName", "(", "utilityName", ",", "taskName", ",", "serverDir", ",", "targetFilepath", ")", ";", "String", "xmlTemplate", "=", "\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\"", "+", "NL", "+", "\"<server description=\\\"This file was generated by the ''{0} {1}'' command on {2,date,yyyy-MM-dd HH:mm:ss z}.\\\">\"", "+", "NL", "+", "\"{3}\"", "+", "NL", "+", "\"</server>\"", "+", "NL", ";", "String", "xmlData", "=", "MessageFormat", ".", "format", "(", "xmlTemplate", ",", "utilityName", ",", "taskName", ",", "Calendar", ".", "getInstance", "(", ")", ".", "getTime", "(", ")", ",", "xmlSnippet", ")", ";", "fileUtility", ".", "createParentDirectory", "(", "stdout", ",", "outputFile", ")", ";", "fileUtility", ".", "writeToFile", "(", "stderr", ",", "xmlData", ",", "outputFile", ")", ";", "String", "includeSnippet", "=", "\" <include location=\\\"\"", "+", "outputFile", ".", "getAbsolutePath", "(", ")", "+", "\"\\\" />\"", "+", "NL", ";", "return", "includeSnippet", ";", "}" ]
This method acts like a filter for xml snippets. If the user provides the {@link #ARG_OPT_CREATE_CONFIG_FILE} option, then we will write it to a file and provide an include snippet. Otherwise, we just return the provided xml snippet. @param serverDir Path to the root of the server. e.g. /path/to/wlp/usr/servers/myServer/ @param commandLine The command-line arguments. @param xmlSnippet The xml configuration the task produced. @return An include snippet or the given xmlSnippet.
[ "This", "method", "acts", "like", "a", "filter", "for", "xml", "snippets", ".", "If", "the", "user", "provides", "the", "{", "@link", "#ARG_OPT_CREATE_CONFIG_FILE", "}", "option", "then", "we", "will", "write", "it", "to", "a", "file", "and", "provide", "an", "include", "snippet", ".", "Otherwise", "we", "just", "return", "the", "provided", "xml", "snippet", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.utility/src/com/ibm/ws/security/utility/tasks/CreateSSLCertificateTask.java#L264-L299
passwordmaker/java-passwordmaker-lib
src/main/java/org/daveware/passwordmaker/Database.java
Database.setGlobalSetting
public void setGlobalSetting(String name, String value) { """ Sets a firefox global setting. This allows any name and should be avoided. It is used by the RDF reader. @param name The name of the setting. @param value The value. """ String oldValue; // Avoid redundant setting if (globalSettings.containsKey(name)) { oldValue = globalSettings.get(name); if (value.compareTo(oldValue) == 0) return; } globalSettings.put(name, value); setDirty(true); }
java
public void setGlobalSetting(String name, String value) { String oldValue; // Avoid redundant setting if (globalSettings.containsKey(name)) { oldValue = globalSettings.get(name); if (value.compareTo(oldValue) == 0) return; } globalSettings.put(name, value); setDirty(true); }
[ "public", "void", "setGlobalSetting", "(", "String", "name", ",", "String", "value", ")", "{", "String", "oldValue", ";", "// Avoid redundant setting", "if", "(", "globalSettings", ".", "containsKey", "(", "name", ")", ")", "{", "oldValue", "=", "globalSettings", ".", "get", "(", "name", ")", ";", "if", "(", "value", ".", "compareTo", "(", "oldValue", ")", "==", "0", ")", "return", ";", "}", "globalSettings", ".", "put", "(", "name", ",", "value", ")", ";", "setDirty", "(", "true", ")", ";", "}" ]
Sets a firefox global setting. This allows any name and should be avoided. It is used by the RDF reader. @param name The name of the setting. @param value The value.
[ "Sets", "a", "firefox", "global", "setting", ".", "This", "allows", "any", "name", "and", "should", "be", "avoided", ".", "It", "is", "used", "by", "the", "RDF", "reader", "." ]
train
https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L170-L181
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Observable.java
Observable.fromCallable
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromCallable(Callable<? extends T> supplier) { """ Returns an Observable that, when an observer subscribes to it, invokes a function you specify and then emits the value returned from that function. <p> <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromCallable.png" alt=""> <p> This allows you to defer the execution of the function you specify until an observer subscribes to the ObservableSource. That is to say, it makes the function "lazy." <dl> <dt><b>Scheduler:</b></dt> <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> <dt><b>Error handling:</b></dt> <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is delivered to the downstream via {@link Observer#onError(Throwable)}, except when the downstream has disposed this {@code Observable} source. In this latter case, the {@code Throwable} is delivered to the global error handler via {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. </dd> </dl> @param supplier a function, the execution of which should be deferred; {@code fromCallable} will invoke this function only when an observer subscribes to the ObservableSource that {@code fromCallable} returns @param <T> the type of the item emitted by the ObservableSource @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given function @see #defer(Callable) @since 2.0 """ ObjectHelper.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new ObservableFromCallable<T>(supplier)); }
java
@CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public static <T> Observable<T> fromCallable(Callable<? extends T> supplier) { ObjectHelper.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new ObservableFromCallable<T>(supplier)); }
[ "@", "CheckReturnValue", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "static", "<", "T", ">", "Observable", "<", "T", ">", "fromCallable", "(", "Callable", "<", "?", "extends", "T", ">", "supplier", ")", "{", "ObjectHelper", ".", "requireNonNull", "(", "supplier", ",", "\"supplier is null\"", ")", ";", "return", "RxJavaPlugins", ".", "onAssembly", "(", "new", "ObservableFromCallable", "<", "T", ">", "(", "supplier", ")", ")", ";", "}" ]
Returns an Observable that, when an observer subscribes to it, invokes a function you specify and then emits the value returned from that function. <p> <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromCallable.png" alt=""> <p> This allows you to defer the execution of the function you specify until an observer subscribes to the ObservableSource. That is to say, it makes the function "lazy." <dl> <dt><b>Scheduler:</b></dt> <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> <dt><b>Error handling:</b></dt> <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is delivered to the downstream via {@link Observer#onError(Throwable)}, except when the downstream has disposed this {@code Observable} source. In this latter case, the {@code Throwable} is delivered to the global error handler via {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}. </dd> </dl> @param supplier a function, the execution of which should be deferred; {@code fromCallable} will invoke this function only when an observer subscribes to the ObservableSource that {@code fromCallable} returns @param <T> the type of the item emitted by the ObservableSource @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given function @see #defer(Callable) @since 2.0
[ "Returns", "an", "Observable", "that", "when", "an", "observer", "subscribes", "to", "it", "invokes", "a", "function", "you", "specify", "and", "then", "emits", "the", "value", "returned", "from", "that", "function", ".", "<p", ">", "<img", "width", "=", "640", "height", "=", "310", "src", "=", "https", ":", "//", "raw", ".", "github", ".", "com", "/", "wiki", "/", "ReactiveX", "/", "RxJava", "/", "images", "/", "rx", "-", "operators", "/", "fromCallable", ".", "png", "alt", "=", ">", "<p", ">", "This", "allows", "you", "to", "defer", "the", "execution", "of", "the", "function", "you", "specify", "until", "an", "observer", "subscribes", "to", "the", "ObservableSource", ".", "That", "is", "to", "say", "it", "makes", "the", "function", "lazy", ".", "<dl", ">", "<dt", ">", "<b", ">", "Scheduler", ":", "<", "/", "b", ">", "<", "/", "dt", ">", "<dd", ">", "{" ]
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Observable.java#L1777-L1782
vkostyukov/la4j
src/main/java/org/la4j/Vector.java
Vector.fromMap
public static Vector fromMap(Map<Integer, ? extends Number> map, int length) { """ Creates new {@link org.la4j.vector.SparseVector} from {@code list} """ return SparseVector.fromMap(map, length); }
java
public static Vector fromMap(Map<Integer, ? extends Number> map, int length) { return SparseVector.fromMap(map, length); }
[ "public", "static", "Vector", "fromMap", "(", "Map", "<", "Integer", ",", "?", "extends", "Number", ">", "map", ",", "int", "length", ")", "{", "return", "SparseVector", ".", "fromMap", "(", "map", ",", "length", ")", ";", "}" ]
Creates new {@link org.la4j.vector.SparseVector} from {@code list}
[ "Creates", "new", "{" ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Vector.java#L214-L216
WASdev/ci.maven
liberty-maven-plugin/src/main/java/net/wasdev/wlp/maven/plugins/utils/MavenProjectUtil.java
MavenProjectUtil.getPluginConfiguration
public static String getPluginConfiguration(MavenProject proj, String pluginGroupId, String pluginArtifactId, String key) { """ Get a configuration value from a plugin @param proj @param pluginGroupId @param pluginArtifactId @param key @return """ Xpp3Dom dom = proj.getGoalConfiguration(pluginGroupId, pluginArtifactId, null, null); if (dom != null) { Xpp3Dom val = dom.getChild(key); if (val != null) { return val.getValue(); } } return null; }
java
public static String getPluginConfiguration(MavenProject proj, String pluginGroupId, String pluginArtifactId, String key) { Xpp3Dom dom = proj.getGoalConfiguration(pluginGroupId, pluginArtifactId, null, null); if (dom != null) { Xpp3Dom val = dom.getChild(key); if (val != null) { return val.getValue(); } } return null; }
[ "public", "static", "String", "getPluginConfiguration", "(", "MavenProject", "proj", ",", "String", "pluginGroupId", ",", "String", "pluginArtifactId", ",", "String", "key", ")", "{", "Xpp3Dom", "dom", "=", "proj", ".", "getGoalConfiguration", "(", "pluginGroupId", ",", "pluginArtifactId", ",", "null", ",", "null", ")", ";", "if", "(", "dom", "!=", "null", ")", "{", "Xpp3Dom", "val", "=", "dom", ".", "getChild", "(", "key", ")", ";", "if", "(", "val", "!=", "null", ")", "{", "return", "val", ".", "getValue", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Get a configuration value from a plugin @param proj @param pluginGroupId @param pluginArtifactId @param key @return
[ "Get", "a", "configuration", "value", "from", "a", "plugin" ]
train
https://github.com/WASdev/ci.maven/blob/4fcf2d314299a4c02e2c740e4fc99a4f6aba6918/liberty-maven-plugin/src/main/java/net/wasdev/wlp/maven/plugins/utils/MavenProjectUtil.java#L39-L48
spockframework/spock
spock-core/src/main/java/spock/lang/Specification.java
Specification.notThrown
public void notThrown(Class<? extends Throwable> type) { """ Specifies that no exception of the given type should be thrown, failing with a {@link UnallowedExceptionThrownError} otherwise. @param type the exception type that should not be thrown """ Throwable thrown = getSpecificationContext().getThrownException(); if (thrown == null) return; if (type.isAssignableFrom(thrown.getClass())) { throw new UnallowedExceptionThrownError(type, thrown); } ExceptionUtil.sneakyThrow(thrown); }
java
public void notThrown(Class<? extends Throwable> type) { Throwable thrown = getSpecificationContext().getThrownException(); if (thrown == null) return; if (type.isAssignableFrom(thrown.getClass())) { throw new UnallowedExceptionThrownError(type, thrown); } ExceptionUtil.sneakyThrow(thrown); }
[ "public", "void", "notThrown", "(", "Class", "<", "?", "extends", "Throwable", ">", "type", ")", "{", "Throwable", "thrown", "=", "getSpecificationContext", "(", ")", ".", "getThrownException", "(", ")", ";", "if", "(", "thrown", "==", "null", ")", "return", ";", "if", "(", "type", ".", "isAssignableFrom", "(", "thrown", ".", "getClass", "(", ")", ")", ")", "{", "throw", "new", "UnallowedExceptionThrownError", "(", "type", ",", "thrown", ")", ";", "}", "ExceptionUtil", ".", "sneakyThrow", "(", "thrown", ")", ";", "}" ]
Specifies that no exception of the given type should be thrown, failing with a {@link UnallowedExceptionThrownError} otherwise. @param type the exception type that should not be thrown
[ "Specifies", "that", "no", "exception", "of", "the", "given", "type", "should", "be", "thrown", "failing", "with", "a", "{", "@link", "UnallowedExceptionThrownError", "}", "otherwise", "." ]
train
https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/spock/lang/Specification.java#L102-L109
andrehertwig/admintool
admin-tools-core/src/main/java/de/chandre/admintool/core/controller/AbstractAdminController.java
AbstractAdminController.resolveLocale
protected void resolveLocale(Locale language, HttpServletRequest request, HttpServletResponse response) { """ manually resolve of locale ... to request. useful for path variables @param language @param request @param response """ final LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); localeResolver.setLocale(request, response, language); }
java
protected void resolveLocale(Locale language, HttpServletRequest request, HttpServletResponse response){ final LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); localeResolver.setLocale(request, response, language); }
[ "protected", "void", "resolveLocale", "(", "Locale", "language", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "{", "final", "LocaleResolver", "localeResolver", "=", "RequestContextUtils", ".", "getLocaleResolver", "(", "request", ")", ";", "localeResolver", ".", "setLocale", "(", "request", ",", "response", ",", "language", ")", ";", "}" ]
manually resolve of locale ... to request. useful for path variables @param language @param request @param response
[ "manually", "resolve", "of", "locale", "...", "to", "request", ".", "useful", "for", "path", "variables" ]
train
https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-core/src/main/java/de/chandre/admintool/core/controller/AbstractAdminController.java#L149-L152
deeplearning4j/deeplearning4j
datavec/datavec-spark/src/main/java/org/datavec/spark/storage/SparkStorageUtils.java
SparkStorageUtils.saveSequenceFileSequences
public static void saveSequenceFileSequences(String path, JavaRDD<List<List<Writable>>> rdd) { """ Save a {@code JavaRDD<List<List<Writable>>>} to a Hadoop {@link org.apache.hadoop.io.SequenceFile}. Each record is given a unique (but noncontiguous) {@link LongWritable} key, and values are stored as {@link SequenceRecordWritable} instances. <p> Use {@link #restoreSequenceFileSequences(String, JavaSparkContext)} to restore values saved with this method. @param path Path to save the sequence file @param rdd RDD to save @see #saveSequenceFile(String, JavaRDD) @see #saveMapFileSequences(String, JavaRDD) """ saveSequenceFileSequences(path, rdd, null); }
java
public static void saveSequenceFileSequences(String path, JavaRDD<List<List<Writable>>> rdd) { saveSequenceFileSequences(path, rdd, null); }
[ "public", "static", "void", "saveSequenceFileSequences", "(", "String", "path", ",", "JavaRDD", "<", "List", "<", "List", "<", "Writable", ">", ">", ">", "rdd", ")", "{", "saveSequenceFileSequences", "(", "path", ",", "rdd", ",", "null", ")", ";", "}" ]
Save a {@code JavaRDD<List<List<Writable>>>} to a Hadoop {@link org.apache.hadoop.io.SequenceFile}. Each record is given a unique (but noncontiguous) {@link LongWritable} key, and values are stored as {@link SequenceRecordWritable} instances. <p> Use {@link #restoreSequenceFileSequences(String, JavaSparkContext)} to restore values saved with this method. @param path Path to save the sequence file @param rdd RDD to save @see #saveSequenceFile(String, JavaRDD) @see #saveMapFileSequences(String, JavaRDD)
[ "Save", "a", "{", "@code", "JavaRDD<List<List<Writable", ">>>", "}", "to", "a", "Hadoop", "{", "@link", "org", ".", "apache", ".", "hadoop", ".", "io", ".", "SequenceFile", "}", ".", "Each", "record", "is", "given", "a", "unique", "(", "but", "noncontiguous", ")", "{", "@link", "LongWritable", "}", "key", "and", "values", "are", "stored", "as", "{", "@link", "SequenceRecordWritable", "}", "instances", ".", "<p", ">", "Use", "{", "@link", "#restoreSequenceFileSequences", "(", "String", "JavaSparkContext", ")", "}", "to", "restore", "values", "saved", "with", "this", "method", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/storage/SparkStorageUtils.java#L127-L129
gitblit/fathom
fathom-core/src/main/java/fathom/utils/RequireUtil.java
RequireUtil.allowClass
public static boolean allowClass(Settings settings, Class<?> aClass) { """ Determines if this class may be used in the current runtime environment. Fathom settings are considered as well as runtime modes. @param settings @param aClass @return true if the class may be used """ // Settings-based class exclusions/inclusions if (aClass.isAnnotationPresent(RequireSettings.class)) { // multiple keys required RequireSetting[] requireSettings = aClass.getAnnotation(RequireSettings.class).value(); StringJoiner joiner = new StringJoiner(", "); Arrays.asList(requireSettings).forEach((require) -> { if (!settings.hasSetting(require.value())) { joiner.add(require.value()); } }); String requiredSettings = joiner.toString(); if (!requiredSettings.isEmpty()) { log.warn("skipping {}, it requires the following {} mode settings: {}", aClass.getName(), settings.getMode(), requiredSettings); return false; } }
java
public static boolean allowClass(Settings settings, Class<?> aClass) { // Settings-based class exclusions/inclusions if (aClass.isAnnotationPresent(RequireSettings.class)) { // multiple keys required RequireSetting[] requireSettings = aClass.getAnnotation(RequireSettings.class).value(); StringJoiner joiner = new StringJoiner(", "); Arrays.asList(requireSettings).forEach((require) -> { if (!settings.hasSetting(require.value())) { joiner.add(require.value()); } }); String requiredSettings = joiner.toString(); if (!requiredSettings.isEmpty()) { log.warn("skipping {}, it requires the following {} mode settings: {}", aClass.getName(), settings.getMode(), requiredSettings); return false; } }
[ "public", "static", "boolean", "allowClass", "(", "Settings", "settings", ",", "Class", "<", "?", ">", "aClass", ")", "{", "// Settings-based class exclusions/inclusions", "if", "(", "aClass", ".", "isAnnotationPresent", "(", "RequireSettings", ".", "class", ")", ")", "{", "// multiple keys required", "RequireSetting", "[", "]", "requireSettings", "=", "aClass", ".", "getAnnotation", "(", "RequireSettings", ".", "class", ")", ".", "value", "(", ")", ";", "StringJoiner", "joiner", "=", "new", "StringJoiner", "(", "\", \"", ")", ";", "Arrays", ".", "asList", "(", "requireSettings", ")", ".", "forEach", "(", "(", "require", ")", "-", ">", "{", "if", "(", "!", "settings", ".", "hasSetting", "(", "require", ".", "value", "(", ")", ")", ")", "{", "joiner", ".", "add", "(", "require", ".", "value", "(", ")", ")", ";", "}", "}", ")", ";", "String", "requiredSettings", "=", "joiner", ".", "toString", "(", ")", ";", "if", "(", "!", "requiredSettings", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "warn", "(", "\"skipping {}, it requires the following {} mode settings: {}\"", ",", "aClass", ".", "getName", "(", ")", ",", "settings", ".", "getMode", "(", ")", ",", "requiredSettings", ")", ";", "return", "false", ";", "}", "}" ]
Determines if this class may be used in the current runtime environment. Fathom settings are considered as well as runtime modes. @param settings @param aClass @return true if the class may be used
[ "Determines", "if", "this", "class", "may", "be", "used", "in", "the", "current", "runtime", "environment", ".", "Fathom", "settings", "are", "considered", "as", "well", "as", "runtime", "modes", "." ]
train
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/utils/RequireUtil.java#L74-L93
orhanobut/wasp
wasp/src/main/java/com/orhanobut/wasp/NetworkHandler.java
NetworkHandler.getMethodsRecursive
private static void getMethodsRecursive(Class<?> service, List<Method> methods) { """ Fills {@code proxiedMethods} with the methods of {@code interfaces} and the interfaces they extend. May contain duplicates. """ Collections.addAll(methods, service.getDeclaredMethods()); }
java
private static void getMethodsRecursive(Class<?> service, List<Method> methods) { Collections.addAll(methods, service.getDeclaredMethods()); }
[ "private", "static", "void", "getMethodsRecursive", "(", "Class", "<", "?", ">", "service", ",", "List", "<", "Method", ">", "methods", ")", "{", "Collections", ".", "addAll", "(", "methods", ",", "service", ".", "getDeclaredMethods", "(", ")", ")", ";", "}" ]
Fills {@code proxiedMethods} with the methods of {@code interfaces} and the interfaces they extend. May contain duplicates.
[ "Fills", "{" ]
train
https://github.com/orhanobut/wasp/blob/295d8747aa7e410b185a620a6b87239816a38c11/wasp/src/main/java/com/orhanobut/wasp/NetworkHandler.java#L65-L67
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ConfigValidator.java
ConfigValidator.generateConflictMap
protected Map<String, ConfigElementList> generateConflictMap(List<? extends ConfigElement> list) { """ Look for conflicts between single-valued attributes. No metatype registry entry is available. @param elements The configuration elements to test. @return A table of conflicts between the configuration elements. """ return generateConflictMap(null, list); }
java
protected Map<String, ConfigElementList> generateConflictMap(List<? extends ConfigElement> list) { return generateConflictMap(null, list); }
[ "protected", "Map", "<", "String", ",", "ConfigElementList", ">", "generateConflictMap", "(", "List", "<", "?", "extends", "ConfigElement", ">", "list", ")", "{", "return", "generateConflictMap", "(", "null", ",", "list", ")", ";", "}" ]
Look for conflicts between single-valued attributes. No metatype registry entry is available. @param elements The configuration elements to test. @return A table of conflicts between the configuration elements.
[ "Look", "for", "conflicts", "between", "single", "-", "valued", "attributes", ".", "No", "metatype", "registry", "entry", "is", "available", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/ConfigValidator.java#L229-L231
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java
MarshallUtil.unmarshallIntCollection
public static <T extends Collection<Integer>> T unmarshallIntCollection(ObjectInput in, CollectionBuilder<Integer, T> builder) throws IOException { """ Unmarshalls a collection of integers. @param in the {@link ObjectInput} to read from. @param builder the {@link CollectionBuilder} to build the collection of integer. @param <T> the concrete type of the collection. @return the collection. @throws IOException if an error occurs. """ final int size = unmarshallSize(in); if (size == NULL_VALUE) { return null; } T collection = Objects.requireNonNull(builder, "CollectionBuilder must be non-null").build(size); for (int i = 0; i < size; ++i) { collection.add(in.readInt()); } return collection; }
java
public static <T extends Collection<Integer>> T unmarshallIntCollection(ObjectInput in, CollectionBuilder<Integer, T> builder) throws IOException { final int size = unmarshallSize(in); if (size == NULL_VALUE) { return null; } T collection = Objects.requireNonNull(builder, "CollectionBuilder must be non-null").build(size); for (int i = 0; i < size; ++i) { collection.add(in.readInt()); } return collection; }
[ "public", "static", "<", "T", "extends", "Collection", "<", "Integer", ">", ">", "T", "unmarshallIntCollection", "(", "ObjectInput", "in", ",", "CollectionBuilder", "<", "Integer", ",", "T", ">", "builder", ")", "throws", "IOException", "{", "final", "int", "size", "=", "unmarshallSize", "(", "in", ")", ";", "if", "(", "size", "==", "NULL_VALUE", ")", "{", "return", "null", ";", "}", "T", "collection", "=", "Objects", ".", "requireNonNull", "(", "builder", ",", "\"CollectionBuilder must be non-null\"", ")", ".", "build", "(", "size", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "++", "i", ")", "{", "collection", ".", "add", "(", "in", ".", "readInt", "(", ")", ")", ";", "}", "return", "collection", ";", "}" ]
Unmarshalls a collection of integers. @param in the {@link ObjectInput} to read from. @param builder the {@link CollectionBuilder} to build the collection of integer. @param <T> the concrete type of the collection. @return the collection. @throws IOException if an error occurs.
[ "Unmarshalls", "a", "collection", "of", "integers", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java#L489-L499
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/layer/CacheEntry.java
CacheEntry.setData
public void setData(byte[] bytes, byte[] sourceMap) { """ Sets the contents of the cache entry with source map info. @param bytes The layer content @param sourceMap The source map for the layer """ this.sourceMap = sourceMap; sourceMapSize = sourceMap != null ? sourceMap.length : 0; setBytes(bytes); }
java
public void setData(byte[] bytes, byte[] sourceMap) { this.sourceMap = sourceMap; sourceMapSize = sourceMap != null ? sourceMap.length : 0; setBytes(bytes); }
[ "public", "void", "setData", "(", "byte", "[", "]", "bytes", ",", "byte", "[", "]", "sourceMap", ")", "{", "this", ".", "sourceMap", "=", "sourceMap", ";", "sourceMapSize", "=", "sourceMap", "!=", "null", "?", "sourceMap", ".", "length", ":", "0", ";", "setBytes", "(", "bytes", ")", ";", "}" ]
Sets the contents of the cache entry with source map info. @param bytes The layer content @param sourceMap The source map for the layer
[ "Sets", "the", "contents", "of", "the", "cache", "entry", "with", "source", "map", "info", "." ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/layer/CacheEntry.java#L182-L186
realtime-framework/RealtimeMessaging-Android
library/src/main/java/ibt/ortc/extensibility/OrtcClient.java
OrtcClient.subscribeWithNotifications
public void subscribeWithNotifications(String channel, boolean subscribeOnReconnect, String gcmRegistrationId, OnMessage onMessage) { """ Subscribe the specified channel in order to receive messages in that channel with a support of Google Cloud Messaging. (use this method only when you are sure what are you doing) @param channel Channel to be subscribed @param subscribeOnReconnect Indicates if the channel should be subscribe if the event on reconnected is fired @param gcmRegistrationId Device id obtained from GCM during registration @param onMessage Event handler that will be called when a message will be received on the subscribed channel """ this.registrationId = gcmRegistrationId; _subscribeWithNotifications(channel, subscribeOnReconnect, onMessage, true); }
java
public void subscribeWithNotifications(String channel, boolean subscribeOnReconnect, String gcmRegistrationId, OnMessage onMessage){ this.registrationId = gcmRegistrationId; _subscribeWithNotifications(channel, subscribeOnReconnect, onMessage, true); }
[ "public", "void", "subscribeWithNotifications", "(", "String", "channel", ",", "boolean", "subscribeOnReconnect", ",", "String", "gcmRegistrationId", ",", "OnMessage", "onMessage", ")", "{", "this", ".", "registrationId", "=", "gcmRegistrationId", ";", "_subscribeWithNotifications", "(", "channel", ",", "subscribeOnReconnect", ",", "onMessage", ",", "true", ")", ";", "}" ]
Subscribe the specified channel in order to receive messages in that channel with a support of Google Cloud Messaging. (use this method only when you are sure what are you doing) @param channel Channel to be subscribed @param subscribeOnReconnect Indicates if the channel should be subscribe if the event on reconnected is fired @param gcmRegistrationId Device id obtained from GCM during registration @param onMessage Event handler that will be called when a message will be received on the subscribed channel
[ "Subscribe", "the", "specified", "channel", "in", "order", "to", "receive", "messages", "in", "that", "channel", "with", "a", "support", "of", "Google", "Cloud", "Messaging", ".", "(", "use", "this", "method", "only", "when", "you", "are", "sure", "what", "are", "you", "doing", ")" ]
train
https://github.com/realtime-framework/RealtimeMessaging-Android/blob/f0d87b92ed7c591bcfe2b9cf45b947865570e061/library/src/main/java/ibt/ortc/extensibility/OrtcClient.java#L929-L932
apereo/cas
support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java
SamlUtils.readCertificate
public static X509Certificate readCertificate(final Resource resource) { """ Read certificate x 509 certificate. @param resource the resource @return the x 509 certificate """ try (val in = resource.getInputStream()) { return CertUtil.readCertificate(in); } catch (final Exception e) { throw new IllegalArgumentException("Error reading certificate " + resource, e); } }
java
public static X509Certificate readCertificate(final Resource resource) { try (val in = resource.getInputStream()) { return CertUtil.readCertificate(in); } catch (final Exception e) { throw new IllegalArgumentException("Error reading certificate " + resource, e); } }
[ "public", "static", "X509Certificate", "readCertificate", "(", "final", "Resource", "resource", ")", "{", "try", "(", "val", "in", "=", "resource", ".", "getInputStream", "(", ")", ")", "{", "return", "CertUtil", ".", "readCertificate", "(", "in", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Error reading certificate \"", "+", "resource", ",", "e", ")", ";", "}", "}" ]
Read certificate x 509 certificate. @param resource the resource @return the x 509 certificate
[ "Read", "certificate", "x", "509", "certificate", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/SamlUtils.java#L55-L61
EdwardRaff/JSAT
JSAT/src/jsat/linear/RowColumnOps.java
RowColumnOps.addDiag
public static void addDiag(Matrix A, int start, int to, double c) { """ Updates the values along the main diagonal of the matrix by adding a constant to them @param A the matrix to perform the update on @param start the first index of the diagonals to update (inclusive) @param to the last index of the diagonals to update (exclusive) @param c the constant to add to the diagonal """ for(int i = start; i < to; i++) A.increment(i, i, c); }
java
public static void addDiag(Matrix A, int start, int to, double c) { for(int i = start; i < to; i++) A.increment(i, i, c); }
[ "public", "static", "void", "addDiag", "(", "Matrix", "A", ",", "int", "start", ",", "int", "to", ",", "double", "c", ")", "{", "for", "(", "int", "i", "=", "start", ";", "i", "<", "to", ";", "i", "++", ")", "A", ".", "increment", "(", "i", ",", "i", ",", ")", ";", "}" ]
Updates the values along the main diagonal of the matrix by adding a constant to them @param A the matrix to perform the update on @param start the first index of the diagonals to update (inclusive) @param to the last index of the diagonals to update (exclusive) @param c the constant to add to the diagonal
[ "Updates", "the", "values", "along", "the", "main", "diagonal", "of", "the", "matrix", "by", "adding", "a", "constant", "to", "them" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/RowColumnOps.java#L17-L21
apache/incubator-atlas
repository/src/main/java/org/apache/atlas/repository/graph/GraphBackedSearchIndexer.java
GraphBackedSearchIndexer.onAdd
@Override public void onAdd(Collection<? extends IDataType> dataTypes) throws AtlasException { """ This is upon adding a new type to Store. @param dataTypes data type @throws AtlasException """ AtlasGraphManagement management = provider.get().getManagementSystem(); for (IDataType dataType : dataTypes) { if (LOG.isDebugEnabled()) { LOG.debug("Creating indexes for type name={}, definition={}", dataType.getName(), dataType.getClass()); } try { addIndexForType(management, dataType); LOG.info("Index creation for type {} complete", dataType.getName()); } catch (Throwable throwable) { LOG.error("Error creating index for type {}", dataType, throwable); //Rollback indexes if any failure rollback(management); throw new IndexCreationException("Error while creating index for type " + dataType, throwable); } } //Commit indexes commit(management); }
java
@Override public void onAdd(Collection<? extends IDataType> dataTypes) throws AtlasException { AtlasGraphManagement management = provider.get().getManagementSystem(); for (IDataType dataType : dataTypes) { if (LOG.isDebugEnabled()) { LOG.debug("Creating indexes for type name={}, definition={}", dataType.getName(), dataType.getClass()); } try { addIndexForType(management, dataType); LOG.info("Index creation for type {} complete", dataType.getName()); } catch (Throwable throwable) { LOG.error("Error creating index for type {}", dataType, throwable); //Rollback indexes if any failure rollback(management); throw new IndexCreationException("Error while creating index for type " + dataType, throwable); } } //Commit indexes commit(management); }
[ "@", "Override", "public", "void", "onAdd", "(", "Collection", "<", "?", "extends", "IDataType", ">", "dataTypes", ")", "throws", "AtlasException", "{", "AtlasGraphManagement", "management", "=", "provider", ".", "get", "(", ")", ".", "getManagementSystem", "(", ")", ";", "for", "(", "IDataType", "dataType", ":", "dataTypes", ")", "{", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "\"Creating indexes for type name={}, definition={}\"", ",", "dataType", ".", "getName", "(", ")", ",", "dataType", ".", "getClass", "(", ")", ")", ";", "}", "try", "{", "addIndexForType", "(", "management", ",", "dataType", ")", ";", "LOG", ".", "info", "(", "\"Index creation for type {} complete\"", ",", "dataType", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "Throwable", "throwable", ")", "{", "LOG", ".", "error", "(", "\"Error creating index for type {}\"", ",", "dataType", ",", "throwable", ")", ";", "//Rollback indexes if any failure", "rollback", "(", "management", ")", ";", "throw", "new", "IndexCreationException", "(", "\"Error while creating index for type \"", "+", "dataType", ",", "throwable", ")", ";", "}", "}", "//Commit indexes", "commit", "(", "management", ")", ";", "}" ]
This is upon adding a new type to Store. @param dataTypes data type @throws AtlasException
[ "This", "is", "upon", "adding", "a", "new", "type", "to", "Store", "." ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/graph/GraphBackedSearchIndexer.java#L226-L248
k3po/k3po
driver/src/main/java/org/kaazing/k3po/driver/internal/netty/channel/Channels.java
Channels.shutdownInput
public static void shutdownInput(ChannelHandlerContext ctx, ChannelFuture future) { """ Sends a {@code "shutdownInput"} request to the {@link ChannelDownstreamHandler} which is placed in the closest downstream from the handler associated with the specified {@link ChannelHandlerContext}. @param ctx the context @param future the future which will be notified when the shutdownInput operation is done """ ctx.sendDownstream( new DownstreamShutdownInputEvent(ctx.getChannel(), future)); }
java
public static void shutdownInput(ChannelHandlerContext ctx, ChannelFuture future) { ctx.sendDownstream( new DownstreamShutdownInputEvent(ctx.getChannel(), future)); }
[ "public", "static", "void", "shutdownInput", "(", "ChannelHandlerContext", "ctx", ",", "ChannelFuture", "future", ")", "{", "ctx", ".", "sendDownstream", "(", "new", "DownstreamShutdownInputEvent", "(", "ctx", ".", "getChannel", "(", ")", ",", "future", ")", ")", ";", "}" ]
Sends a {@code "shutdownInput"} request to the {@link ChannelDownstreamHandler} which is placed in the closest downstream from the handler associated with the specified {@link ChannelHandlerContext}. @param ctx the context @param future the future which will be notified when the shutdownInput operation is done
[ "Sends", "a", "{", "@code", "shutdownInput", "}", "request", "to", "the", "{", "@link", "ChannelDownstreamHandler", "}", "which", "is", "placed", "in", "the", "closest", "downstream", "from", "the", "handler", "associated", "with", "the", "specified", "{", "@link", "ChannelHandlerContext", "}", "." ]
train
https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/driver/src/main/java/org/kaazing/k3po/driver/internal/netty/channel/Channels.java#L89-L92
dropbox/dropbox-sdk-java
src/main/java/com/dropbox/core/v1/DbxClientV1.java
DbxClientV1.getMetadataWithChildrenIfChanged
public Maybe<DbxEntry./*@Nullable*/WithChildren> getMetadataWithChildrenIfChanged(String path, /*@Nullable*/String previousFolderHash) throws DbxException { """ Same as {@link #getMetadataWithChildrenIfChanged(String, boolean, String)} with {@code includeMediaInfo} set to {@code false}. """ return getMetadataWithChildrenIfChanged(path, false, previousFolderHash); }
java
public Maybe<DbxEntry./*@Nullable*/WithChildren> getMetadataWithChildrenIfChanged(String path, /*@Nullable*/String previousFolderHash) throws DbxException { return getMetadataWithChildrenIfChanged(path, false, previousFolderHash); }
[ "public", "Maybe", "<", "DbxEntry", ".", "/*@Nullable*/", "WithChildren", ">", "getMetadataWithChildrenIfChanged", "(", "String", "path", ",", "/*@Nullable*/", "String", "previousFolderHash", ")", "throws", "DbxException", "{", "return", "getMetadataWithChildrenIfChanged", "(", "path", ",", "false", ",", "previousFolderHash", ")", ";", "}" ]
Same as {@link #getMetadataWithChildrenIfChanged(String, boolean, String)} with {@code includeMediaInfo} set to {@code false}.
[ "Same", "as", "{" ]
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L274-L278
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java
KeyValueHandler.handleGetRequest
private static BinaryMemcacheRequest handleGetRequest(final ChannelHandlerContext ctx, final GetRequest msg) { """ Encodes a {@link GetRequest} into its lower level representation. Depending on the flags set on the {@link GetRequest}, the appropriate opcode gets chosen. Currently, a regular get, as well as "get and touch" and "get and lock" are supported. Latter variants have server-side side-effects but do not differ in response behavior. @param ctx the {@link ChannelHandlerContext} to use for allocation and others. @param msg the incoming message. @return a ready {@link BinaryMemcacheRequest}. """ byte opcode; ByteBuf extras; if (msg.lock()) { opcode = OP_GET_AND_LOCK; extras = ctx.alloc().buffer().writeInt(msg.expiry()); } else if (msg.touch()) { opcode = OP_GET_AND_TOUCH; extras = ctx.alloc().buffer().writeInt(msg.expiry()); } else { opcode = OP_GET; extras = Unpooled.EMPTY_BUFFER; } byte[] key = msg.keyBytes(); short keyLength = (short) key.length; byte extrasLength = (byte) extras.readableBytes(); BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key); request .setOpcode(opcode) .setKeyLength(keyLength) .setExtras(extras) .setExtrasLength(extrasLength) .setTotalBodyLength(keyLength + extrasLength); return request; }
java
private static BinaryMemcacheRequest handleGetRequest(final ChannelHandlerContext ctx, final GetRequest msg) { byte opcode; ByteBuf extras; if (msg.lock()) { opcode = OP_GET_AND_LOCK; extras = ctx.alloc().buffer().writeInt(msg.expiry()); } else if (msg.touch()) { opcode = OP_GET_AND_TOUCH; extras = ctx.alloc().buffer().writeInt(msg.expiry()); } else { opcode = OP_GET; extras = Unpooled.EMPTY_BUFFER; } byte[] key = msg.keyBytes(); short keyLength = (short) key.length; byte extrasLength = (byte) extras.readableBytes(); BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key); request .setOpcode(opcode) .setKeyLength(keyLength) .setExtras(extras) .setExtrasLength(extrasLength) .setTotalBodyLength(keyLength + extrasLength); return request; }
[ "private", "static", "BinaryMemcacheRequest", "handleGetRequest", "(", "final", "ChannelHandlerContext", "ctx", ",", "final", "GetRequest", "msg", ")", "{", "byte", "opcode", ";", "ByteBuf", "extras", ";", "if", "(", "msg", ".", "lock", "(", ")", ")", "{", "opcode", "=", "OP_GET_AND_LOCK", ";", "extras", "=", "ctx", ".", "alloc", "(", ")", ".", "buffer", "(", ")", ".", "writeInt", "(", "msg", ".", "expiry", "(", ")", ")", ";", "}", "else", "if", "(", "msg", ".", "touch", "(", ")", ")", "{", "opcode", "=", "OP_GET_AND_TOUCH", ";", "extras", "=", "ctx", ".", "alloc", "(", ")", ".", "buffer", "(", ")", ".", "writeInt", "(", "msg", ".", "expiry", "(", ")", ")", ";", "}", "else", "{", "opcode", "=", "OP_GET", ";", "extras", "=", "Unpooled", ".", "EMPTY_BUFFER", ";", "}", "byte", "[", "]", "key", "=", "msg", ".", "keyBytes", "(", ")", ";", "short", "keyLength", "=", "(", "short", ")", "key", ".", "length", ";", "byte", "extrasLength", "=", "(", "byte", ")", "extras", ".", "readableBytes", "(", ")", ";", "BinaryMemcacheRequest", "request", "=", "new", "DefaultBinaryMemcacheRequest", "(", "key", ")", ";", "request", ".", "setOpcode", "(", "opcode", ")", ".", "setKeyLength", "(", "keyLength", ")", ".", "setExtras", "(", "extras", ")", ".", "setExtrasLength", "(", "extrasLength", ")", ".", "setTotalBodyLength", "(", "keyLength", "+", "extrasLength", ")", ";", "return", "request", ";", "}" ]
Encodes a {@link GetRequest} into its lower level representation. Depending on the flags set on the {@link GetRequest}, the appropriate opcode gets chosen. Currently, a regular get, as well as "get and touch" and "get and lock" are supported. Latter variants have server-side side-effects but do not differ in response behavior. @param ctx the {@link ChannelHandlerContext} to use for allocation and others. @param msg the incoming message. @return a ready {@link BinaryMemcacheRequest}.
[ "Encodes", "a", "{", "@link", "GetRequest", "}", "into", "its", "lower", "level", "representation", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java#L488-L513
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/input/CmsTriStateCheckBox.java
CmsTriStateCheckBox.setState
public void setState(State state, boolean fireEvent) { """ Sets the state of the check box and optionally fires an event.<p> @param state the new state @param fireEvent true if a ValueChangeEvent should be fired """ boolean changed = m_state != state; m_state = state; if (changed) { updateStyle(); } if (fireEvent) { ValueChangeEvent.fire(this, state); } }
java
public void setState(State state, boolean fireEvent) { boolean changed = m_state != state; m_state = state; if (changed) { updateStyle(); } if (fireEvent) { ValueChangeEvent.fire(this, state); } }
[ "public", "void", "setState", "(", "State", "state", ",", "boolean", "fireEvent", ")", "{", "boolean", "changed", "=", "m_state", "!=", "state", ";", "m_state", "=", "state", ";", "if", "(", "changed", ")", "{", "updateStyle", "(", ")", ";", "}", "if", "(", "fireEvent", ")", "{", "ValueChangeEvent", ".", "fire", "(", "this", ",", "state", ")", ";", "}", "}" ]
Sets the state of the check box and optionally fires an event.<p> @param state the new state @param fireEvent true if a ValueChangeEvent should be fired
[ "Sets", "the", "state", "of", "the", "check", "box", "and", "optionally", "fires", "an", "event", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/CmsTriStateCheckBox.java#L121-L131
kiswanij/jk-util
src/main/java/com/jk/util/UserPreferences.java
UserPreferences.getFloat
public static float getFloat(final String key, final float def) { """ Gets the float. @param key the key @param def the def @return the float @see java.util.prefs.Preferences#getFloat(java.lang.String, float) """ try { return systemRoot.getFloat(fixKey(key), def); } catch (final Exception e) { // just eat the exception to avoid any system // crash on system issues return def; } }
java
public static float getFloat(final String key, final float def) { try { return systemRoot.getFloat(fixKey(key), def); } catch (final Exception e) { // just eat the exception to avoid any system // crash on system issues return def; } }
[ "public", "static", "float", "getFloat", "(", "final", "String", "key", ",", "final", "float", "def", ")", "{", "try", "{", "return", "systemRoot", ".", "getFloat", "(", "fixKey", "(", "key", ")", ",", "def", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "// just eat the exception to avoid any system", "// crash on system issues", "return", "def", ";", "}", "}" ]
Gets the float. @param key the key @param def the def @return the float @see java.util.prefs.Preferences#getFloat(java.lang.String, float)
[ "Gets", "the", "float", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/UserPreferences.java#L108-L116
alkacon/opencms-core
src/org/opencms/file/CmsProperty.java
CmsProperty.setValue
public void setValue(String value, String type) { """ Sets the value of this property as either shared or individual value.<p> If the given type equals {@link CmsProperty#TYPE_SHARED} then the value is set as a shared (resource) value, otherwise it is set as individual (structure) value.<p> @param value the value to set @param type the value type to set """ checkFrozen(); setAutoCreatePropertyDefinition(true); if (TYPE_SHARED.equalsIgnoreCase(type)) { // set the provided value as shared (resource) value setResourceValue(value); } else { // set the provided value as individual (structure) value setStructureValue(value); } }
java
public void setValue(String value, String type) { checkFrozen(); setAutoCreatePropertyDefinition(true); if (TYPE_SHARED.equalsIgnoreCase(type)) { // set the provided value as shared (resource) value setResourceValue(value); } else { // set the provided value as individual (structure) value setStructureValue(value); } }
[ "public", "void", "setValue", "(", "String", "value", ",", "String", "type", ")", "{", "checkFrozen", "(", ")", ";", "setAutoCreatePropertyDefinition", "(", "true", ")", ";", "if", "(", "TYPE_SHARED", ".", "equalsIgnoreCase", "(", "type", ")", ")", "{", "// set the provided value as shared (resource) value", "setResourceValue", "(", "value", ")", ";", "}", "else", "{", "// set the provided value as individual (structure) value", "setStructureValue", "(", "value", ")", ";", "}", "}" ]
Sets the value of this property as either shared or individual value.<p> If the given type equals {@link CmsProperty#TYPE_SHARED} then the value is set as a shared (resource) value, otherwise it is set as individual (structure) value.<p> @param value the value to set @param type the value type to set
[ "Sets", "the", "value", "of", "this", "property", "as", "either", "shared", "or", "individual", "value", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsProperty.java#L1158-L1169
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.readAliasByPath
public CmsAlias readAliasByPath(CmsDbContext dbc, CmsProject project, String siteRoot, String path) throws CmsException { """ Finds the alias with a given path.<p> If no alias is found, null is returned.<p> @param dbc the current database context @param project the current project @param siteRoot the site root @param path the path of the alias @return the alias with the given path @throws CmsException if something goes wrong """ List<CmsAlias> aliases = getVfsDriver(dbc).readAliases(dbc, project, new CmsAliasFilter(siteRoot, path, null)); if (aliases.isEmpty()) { return null; } else { return aliases.get(0); } }
java
public CmsAlias readAliasByPath(CmsDbContext dbc, CmsProject project, String siteRoot, String path) throws CmsException { List<CmsAlias> aliases = getVfsDriver(dbc).readAliases(dbc, project, new CmsAliasFilter(siteRoot, path, null)); if (aliases.isEmpty()) { return null; } else { return aliases.get(0); } }
[ "public", "CmsAlias", "readAliasByPath", "(", "CmsDbContext", "dbc", ",", "CmsProject", "project", ",", "String", "siteRoot", ",", "String", "path", ")", "throws", "CmsException", "{", "List", "<", "CmsAlias", ">", "aliases", "=", "getVfsDriver", "(", "dbc", ")", ".", "readAliases", "(", "dbc", ",", "project", ",", "new", "CmsAliasFilter", "(", "siteRoot", ",", "path", ",", "null", ")", ")", ";", "if", "(", "aliases", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "{", "return", "aliases", ".", "get", "(", "0", ")", ";", "}", "}" ]
Finds the alias with a given path.<p> If no alias is found, null is returned.<p> @param dbc the current database context @param project the current project @param siteRoot the site root @param path the path of the alias @return the alias with the given path @throws CmsException if something goes wrong
[ "Finds", "the", "alias", "with", "a", "given", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L6343-L6352
brettwooldridge/HikariCP
src/main/java/com/zaxxer/hikari/pool/HikariPool.java
HikariPool.closeConnection
void closeConnection(final PoolEntry poolEntry, final String closureReason) { """ Permanently close the real (underlying) connection (eat any exception). @param poolEntry poolEntry having the connection to close @param closureReason reason to close """ if (connectionBag.remove(poolEntry)) { final Connection connection = poolEntry.close(); closeConnectionExecutor.execute(() -> { quietlyCloseConnection(connection, closureReason); if (poolState == POOL_NORMAL) { fillPool(); } }); } }
java
void closeConnection(final PoolEntry poolEntry, final String closureReason) { if (connectionBag.remove(poolEntry)) { final Connection connection = poolEntry.close(); closeConnectionExecutor.execute(() -> { quietlyCloseConnection(connection, closureReason); if (poolState == POOL_NORMAL) { fillPool(); } }); } }
[ "void", "closeConnection", "(", "final", "PoolEntry", "poolEntry", ",", "final", "String", "closureReason", ")", "{", "if", "(", "connectionBag", ".", "remove", "(", "poolEntry", ")", ")", "{", "final", "Connection", "connection", "=", "poolEntry", ".", "close", "(", ")", ";", "closeConnectionExecutor", ".", "execute", "(", "(", ")", "->", "{", "quietlyCloseConnection", "(", "connection", ",", "closureReason", ")", ";", "if", "(", "poolState", "==", "POOL_NORMAL", ")", "{", "fillPool", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Permanently close the real (underlying) connection (eat any exception). @param poolEntry poolEntry having the connection to close @param closureReason reason to close
[ "Permanently", "close", "the", "real", "(", "underlying", ")", "connection", "(", "eat", "any", "exception", ")", "." ]
train
https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/pool/HikariPool.java#L442-L453
hageldave/ImagingKit
ImagingKit_Fourier/src/main/java/hageldave/imagingkit/fourier/ArrayUtils.java
ArrayUtils.shift2D
public static void shift2D(double[] a, int w, int h, int x, int y) { """ Applies a 2D torus shift to the specified row major order array of specified dimensions. The array is interpreted as an image of given width and height (with elements in row major order) and is shifted by x to the right and by y to the bottom. @param a array @param w width @param h height @param x shift in x direction @param y shift in y direction """ assertPositive(w, ()->"specified width is not positive. w="+w); assertPositive(h, ()->"specified height is not positive. h="+h); while(x < 0) x = w+x; while(y < 0) y = h+y; x %=w; y %=h; if(x==0 && y==0){ return; } for(int row = 0; row < h; row++){ int offset = row*w; rotateArray(a, w, offset, x); } rotateArray(a,w*h, 0, y*w); }
java
public static void shift2D(double[] a, int w, int h, int x, int y){ assertPositive(w, ()->"specified width is not positive. w="+w); assertPositive(h, ()->"specified height is not positive. h="+h); while(x < 0) x = w+x; while(y < 0) y = h+y; x %=w; y %=h; if(x==0 && y==0){ return; } for(int row = 0; row < h; row++){ int offset = row*w; rotateArray(a, w, offset, x); } rotateArray(a,w*h, 0, y*w); }
[ "public", "static", "void", "shift2D", "(", "double", "[", "]", "a", ",", "int", "w", ",", "int", "h", ",", "int", "x", ",", "int", "y", ")", "{", "assertPositive", "(", "w", ",", "(", ")", "->", "\"specified width is not positive. w=\"", "+", "w", ")", ";", "assertPositive", "(", "h", ",", "(", ")", "->", "\"specified height is not positive. h=\"", "+", "h", ")", ";", "while", "(", "x", "<", "0", ")", "x", "=", "w", "+", "x", ";", "while", "(", "y", "<", "0", ")", "y", "=", "h", "+", "y", ";", "x", "%=", "w", ";", "y", "%=", "h", ";", "if", "(", "x", "==", "0", "&&", "y", "==", "0", ")", "{", "return", ";", "}", "for", "(", "int", "row", "=", "0", ";", "row", "<", "h", ";", "row", "++", ")", "{", "int", "offset", "=", "row", "*", "w", ";", "rotateArray", "(", "a", ",", "w", ",", "offset", ",", "x", ")", ";", "}", "rotateArray", "(", "a", ",", "w", "*", "h", ",", "0", ",", "y", "*", "w", ")", ";", "}" ]
Applies a 2D torus shift to the specified row major order array of specified dimensions. The array is interpreted as an image of given width and height (with elements in row major order) and is shifted by x to the right and by y to the bottom. @param a array @param w width @param h height @param x shift in x direction @param y shift in y direction
[ "Applies", "a", "2D", "torus", "shift", "to", "the", "specified", "row", "major", "order", "array", "of", "specified", "dimensions", ".", "The", "array", "is", "interpreted", "as", "an", "image", "of", "given", "width", "and", "height", "(", "with", "elements", "in", "row", "major", "order", ")", "and", "is", "shifted", "by", "x", "to", "the", "right", "and", "by", "y", "to", "the", "bottom", "." ]
train
https://github.com/hageldave/ImagingKit/blob/3837c7d550a12cf4dc5718b644ced94b97f52668/ImagingKit_Fourier/src/main/java/hageldave/imagingkit/fourier/ArrayUtils.java#L41-L56
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.setStyle
public static boolean setStyle(MarkerOptions markerOptions, StyleRow style) { """ Set the style into the marker options @param markerOptions marker options @param style style row @return true if style was set into the marker options """ boolean styleSet = false; if (style != null) { Color color = style.getColorOrDefault(); float hue = color.getHue(); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue)); styleSet = true; } return styleSet; }
java
public static boolean setStyle(MarkerOptions markerOptions, StyleRow style) { boolean styleSet = false; if (style != null) { Color color = style.getColorOrDefault(); float hue = color.getHue(); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue)); styleSet = true; } return styleSet; }
[ "public", "static", "boolean", "setStyle", "(", "MarkerOptions", "markerOptions", ",", "StyleRow", "style", ")", "{", "boolean", "styleSet", "=", "false", ";", "if", "(", "style", "!=", "null", ")", "{", "Color", "color", "=", "style", ".", "getColorOrDefault", "(", ")", ";", "float", "hue", "=", "color", ".", "getHue", "(", ")", ";", "markerOptions", ".", "icon", "(", "BitmapDescriptorFactory", ".", "defaultMarker", "(", "hue", ")", ")", ";", "styleSet", "=", "true", ";", "}", "return", "styleSet", ";", "}" ]
Set the style into the marker options @param markerOptions marker options @param style style row @return true if style was set into the marker options
[ "Set", "the", "style", "into", "the", "marker", "options" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L328-L340
osglworks/java-tool
src/main/java/org/osgl/util/E.java
E.invalidRangeIf
public static void invalidRangeIf(boolean tester, String msg, Object... args) { """ Throws out an {@link InvalidRangeException} with error message specified when `tester` is `true`. @param tester when `true` then throw out the exception @param msg the error message format pattern. @param args the error message format arguments. """ if (tester) { throw invalidRange(msg, args); } }
java
public static void invalidRangeIf(boolean tester, String msg, Object... args) { if (tester) { throw invalidRange(msg, args); } }
[ "public", "static", "void", "invalidRangeIf", "(", "boolean", "tester", ",", "String", "msg", ",", "Object", "...", "args", ")", "{", "if", "(", "tester", ")", "{", "throw", "invalidRange", "(", "msg", ",", "args", ")", ";", "}", "}" ]
Throws out an {@link InvalidRangeException} with error message specified when `tester` is `true`. @param tester when `true` then throw out the exception @param msg the error message format pattern. @param args the error message format arguments.
[ "Throws", "out", "an", "{", "@link", "InvalidRangeException", "}", "with", "error", "message", "specified", "when", "tester", "is", "true", "." ]
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L481-L485
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AlpineQueryManager.java
AlpineQueryManager.removeUserFromTeam
public boolean removeUserFromTeam(final UserPrincipal user, final Team team) { """ Removes the association of a UserPrincipal to a Team. @param user The user to unbind @param team The team to unbind @return true if operation was successful, false if not. This is not an indication of team disassociation, an unsuccessful return value may be due to the team or user not existing, or a binding that may not exist. @since 1.0.0 """ final List<Team> teams = user.getTeams(); if (teams == null) { return false; } boolean found = false; for (final Team t: teams) { if (team.getUuid().equals(t.getUuid())) { found = true; } } if (found) { pm.currentTransaction().begin(); teams.remove(team); user.setTeams(teams); pm.currentTransaction().commit(); return true; } return false; }
java
public boolean removeUserFromTeam(final UserPrincipal user, final Team team) { final List<Team> teams = user.getTeams(); if (teams == null) { return false; } boolean found = false; for (final Team t: teams) { if (team.getUuid().equals(t.getUuid())) { found = true; } } if (found) { pm.currentTransaction().begin(); teams.remove(team); user.setTeams(teams); pm.currentTransaction().commit(); return true; } return false; }
[ "public", "boolean", "removeUserFromTeam", "(", "final", "UserPrincipal", "user", ",", "final", "Team", "team", ")", "{", "final", "List", "<", "Team", ">", "teams", "=", "user", ".", "getTeams", "(", ")", ";", "if", "(", "teams", "==", "null", ")", "{", "return", "false", ";", "}", "boolean", "found", "=", "false", ";", "for", "(", "final", "Team", "t", ":", "teams", ")", "{", "if", "(", "team", ".", "getUuid", "(", ")", ".", "equals", "(", "t", ".", "getUuid", "(", ")", ")", ")", "{", "found", "=", "true", ";", "}", "}", "if", "(", "found", ")", "{", "pm", ".", "currentTransaction", "(", ")", ".", "begin", "(", ")", ";", "teams", ".", "remove", "(", "team", ")", ";", "user", ".", "setTeams", "(", "teams", ")", ";", "pm", ".", "currentTransaction", "(", ")", ".", "commit", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Removes the association of a UserPrincipal to a Team. @param user The user to unbind @param team The team to unbind @return true if operation was successful, false if not. This is not an indication of team disassociation, an unsuccessful return value may be due to the team or user not existing, or a binding that may not exist. @since 1.0.0
[ "Removes", "the", "association", "of", "a", "UserPrincipal", "to", "a", "Team", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AlpineQueryManager.java#L422-L441
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java
AbstractSelectCodeGenerator.generateSubQueries
protected void generateSubQueries(Builder methodBuilder, SQLiteModelMethod method) { """ generate code for sub queries @param methodBuilder @param method """ SQLiteEntity entity = method.getEntity(); for (Triple<String, String, SQLiteModelMethod> item : method.childrenSelects) { TypeName entityTypeName = TypeUtility.typeName(entity.getElement()); String setter; if (entity.isImmutablePojo()) { String idGetter = ImmutableUtility.IMMUTABLE_PREFIX + entity.getPrimaryKey().getName(); setter = ImmutableUtility.IMMUTABLE_PREFIX + entity.findRelationByParentProperty(item.value0).value0.getName() + "=" + String.format("this.daoFactory.get%s().%s(%s)", item.value2.getParent().getName(), item.value2.getName(), idGetter); } else { String idGetter = PropertyUtility.getter("resultBean", entityTypeName, entity.getPrimaryKey()); setter = PropertyUtility.setter(entityTypeName, "resultBean", entity.findRelationByParentProperty(item.value0).value0, String.format("this.daoFactory.get%s().%s(%s)", item.value2.getParent().getName(), item.value2.getName(), idGetter)); } methodBuilder.addComment("sub query: $L", setter); methodBuilder.addStatement("$L", setter); } }
java
protected void generateSubQueries(Builder methodBuilder, SQLiteModelMethod method) { SQLiteEntity entity = method.getEntity(); for (Triple<String, String, SQLiteModelMethod> item : method.childrenSelects) { TypeName entityTypeName = TypeUtility.typeName(entity.getElement()); String setter; if (entity.isImmutablePojo()) { String idGetter = ImmutableUtility.IMMUTABLE_PREFIX + entity.getPrimaryKey().getName(); setter = ImmutableUtility.IMMUTABLE_PREFIX + entity.findRelationByParentProperty(item.value0).value0.getName() + "=" + String.format("this.daoFactory.get%s().%s(%s)", item.value2.getParent().getName(), item.value2.getName(), idGetter); } else { String idGetter = PropertyUtility.getter("resultBean", entityTypeName, entity.getPrimaryKey()); setter = PropertyUtility.setter(entityTypeName, "resultBean", entity.findRelationByParentProperty(item.value0).value0, String.format("this.daoFactory.get%s().%s(%s)", item.value2.getParent().getName(), item.value2.getName(), idGetter)); } methodBuilder.addComment("sub query: $L", setter); methodBuilder.addStatement("$L", setter); } }
[ "protected", "void", "generateSubQueries", "(", "Builder", "methodBuilder", ",", "SQLiteModelMethod", "method", ")", "{", "SQLiteEntity", "entity", "=", "method", ".", "getEntity", "(", ")", ";", "for", "(", "Triple", "<", "String", ",", "String", ",", "SQLiteModelMethod", ">", "item", ":", "method", ".", "childrenSelects", ")", "{", "TypeName", "entityTypeName", "=", "TypeUtility", ".", "typeName", "(", "entity", ".", "getElement", "(", ")", ")", ";", "String", "setter", ";", "if", "(", "entity", ".", "isImmutablePojo", "(", ")", ")", "{", "String", "idGetter", "=", "ImmutableUtility", ".", "IMMUTABLE_PREFIX", "+", "entity", ".", "getPrimaryKey", "(", ")", ".", "getName", "(", ")", ";", "setter", "=", "ImmutableUtility", ".", "IMMUTABLE_PREFIX", "+", "entity", ".", "findRelationByParentProperty", "(", "item", ".", "value0", ")", ".", "value0", ".", "getName", "(", ")", "+", "\"=\"", "+", "String", ".", "format", "(", "\"this.daoFactory.get%s().%s(%s)\"", ",", "item", ".", "value2", ".", "getParent", "(", ")", ".", "getName", "(", ")", ",", "item", ".", "value2", ".", "getName", "(", ")", ",", "idGetter", ")", ";", "}", "else", "{", "String", "idGetter", "=", "PropertyUtility", ".", "getter", "(", "\"resultBean\"", ",", "entityTypeName", ",", "entity", ".", "getPrimaryKey", "(", ")", ")", ";", "setter", "=", "PropertyUtility", ".", "setter", "(", "entityTypeName", ",", "\"resultBean\"", ",", "entity", ".", "findRelationByParentProperty", "(", "item", ".", "value0", ")", ".", "value0", ",", "String", ".", "format", "(", "\"this.daoFactory.get%s().%s(%s)\"", ",", "item", ".", "value2", ".", "getParent", "(", ")", ".", "getName", "(", ")", ",", "item", ".", "value2", ".", "getName", "(", ")", ",", "idGetter", ")", ")", ";", "}", "methodBuilder", ".", "addComment", "(", "\"sub query: $L\"", ",", "setter", ")", ";", "methodBuilder", ".", "addStatement", "(", "\"$L\"", ",", "setter", ")", ";", "}", "}" ]
generate code for sub queries @param methodBuilder @param method
[ "generate", "code", "for", "sub", "queries" ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java#L89-L110
jpaoletti/java-presentation-manager
modules/jpm-core/src/main/java/jpaoletti/jpm/core/Highlights.java
Highlights.getHighlights
public List<Highlight> getHighlights(Entity entity, Field field, Object instance) { """ Return all the highlights that matches the given instance in the given field of the given entity @param entity The entity @param field The field @param instance The instance @return The highlight """ if (field == null) { return getHighlights(entity, instance); } final List<Highlight> result = new ArrayList<Highlight>(); for (Highlight highlight : highlights) { if (!highlight.getScope().equals(INSTANCE)) { if (match(instance, field, highlight)) { result.add(highlight); } } } return result; }
java
public List<Highlight> getHighlights(Entity entity, Field field, Object instance) { if (field == null) { return getHighlights(entity, instance); } final List<Highlight> result = new ArrayList<Highlight>(); for (Highlight highlight : highlights) { if (!highlight.getScope().equals(INSTANCE)) { if (match(instance, field, highlight)) { result.add(highlight); } } } return result; }
[ "public", "List", "<", "Highlight", ">", "getHighlights", "(", "Entity", "entity", ",", "Field", "field", ",", "Object", "instance", ")", "{", "if", "(", "field", "==", "null", ")", "{", "return", "getHighlights", "(", "entity", ",", "instance", ")", ";", "}", "final", "List", "<", "Highlight", ">", "result", "=", "new", "ArrayList", "<", "Highlight", ">", "(", ")", ";", "for", "(", "Highlight", "highlight", ":", "highlights", ")", "{", "if", "(", "!", "highlight", ".", "getScope", "(", ")", ".", "equals", "(", "INSTANCE", ")", ")", "{", "if", "(", "match", "(", "instance", ",", "field", ",", "highlight", ")", ")", "{", "result", ".", "add", "(", "highlight", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Return all the highlights that matches the given instance in the given field of the given entity @param entity The entity @param field The field @param instance The instance @return The highlight
[ "Return", "all", "the", "highlights", "that", "matches", "the", "given", "instance", "in", "the", "given", "field", "of", "the", "given", "entity" ]
train
https://github.com/jpaoletti/java-presentation-manager/blob/d5aab55638383695db244744b4bfe27c5200e04f/modules/jpm-core/src/main/java/jpaoletti/jpm/core/Highlights.java#L58-L71
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.Chessboard
public static double Chessboard(IntPoint p, IntPoint q) { """ Gets the Chessboard distance between two points. @param p IntPoint with X and Y axis coordinates. @param q IntPoint with X and Y axis coordinates. @return The Chessboard distance between x and y. """ return Chessboard(p.x, p.y, q.x, q.y); }
java
public static double Chessboard(IntPoint p, IntPoint q) { return Chessboard(p.x, p.y, q.x, q.y); }
[ "public", "static", "double", "Chessboard", "(", "IntPoint", "p", ",", "IntPoint", "q", ")", "{", "return", "Chessboard", "(", "p", ".", "x", ",", "p", ".", "y", ",", "q", ".", "x", ",", "q", ".", "y", ")", ";", "}" ]
Gets the Chessboard distance between two points. @param p IntPoint with X and Y axis coordinates. @param q IntPoint with X and Y axis coordinates. @return The Chessboard distance between x and y.
[ "Gets", "the", "Chessboard", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L254-L256
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldAdjustRegion.java
TldAdjustRegion.adjustRectangle
protected void adjustRectangle( Rectangle2D_F64 rect , ScaleTranslate2D motion ) { """ Estimate motion of points inside the rectangle and updates the rectangle using the found motion. """ rect.p0.x = rect.p0.x*motion.scale + motion.transX; rect.p0.y = rect.p0.y*motion.scale + motion.transY; rect.p1.x = rect.p1.x*motion.scale + motion.transX; rect.p1.y = rect.p1.y*motion.scale + motion.transY; }
java
protected void adjustRectangle( Rectangle2D_F64 rect , ScaleTranslate2D motion ) { rect.p0.x = rect.p0.x*motion.scale + motion.transX; rect.p0.y = rect.p0.y*motion.scale + motion.transY; rect.p1.x = rect.p1.x*motion.scale + motion.transX; rect.p1.y = rect.p1.y*motion.scale + motion.transY; }
[ "protected", "void", "adjustRectangle", "(", "Rectangle2D_F64", "rect", ",", "ScaleTranslate2D", "motion", ")", "{", "rect", ".", "p0", ".", "x", "=", "rect", ".", "p0", ".", "x", "*", "motion", ".", "scale", "+", "motion", ".", "transX", ";", "rect", ".", "p0", ".", "y", "=", "rect", ".", "p0", ".", "y", "*", "motion", ".", "scale", "+", "motion", ".", "transY", ";", "rect", ".", "p1", ".", "x", "=", "rect", ".", "p1", ".", "x", "*", "motion", ".", "scale", "+", "motion", ".", "transX", ";", "rect", ".", "p1", ".", "y", "=", "rect", ".", "p1", ".", "y", "*", "motion", ".", "scale", "+", "motion", ".", "transY", ";", "}" ]
Estimate motion of points inside the rectangle and updates the rectangle using the found motion.
[ "Estimate", "motion", "of", "points", "inside", "the", "rectangle", "and", "updates", "the", "rectangle", "using", "the", "found", "motion", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldAdjustRegion.java#L93-L98
joniles/mpxj
src/main/java/net/sf/mpxj/ResourceAssignment.java
ResourceAssignment.setCost
public void setCost(int index, Number value) { """ Set a cost value. @param index cost index (1-10) @param value cost value """ set(selectField(AssignmentFieldLists.CUSTOM_COST, index), value); }
java
public void setCost(int index, Number value) { set(selectField(AssignmentFieldLists.CUSTOM_COST, index), value); }
[ "public", "void", "setCost", "(", "int", "index", ",", "Number", "value", ")", "{", "set", "(", "selectField", "(", "AssignmentFieldLists", ".", "CUSTOM_COST", ",", "index", ")", ",", "value", ")", ";", "}" ]
Set a cost value. @param index cost index (1-10) @param value cost value
[ "Set", "a", "cost", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ResourceAssignment.java#L1650-L1653
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/model/TorqueModelDef.java
TorqueModelDef.containsCollectionAndMapsToDifferentTable
private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef) { """ Checks whether the given class maps to a different table but also has the given collection. @param origCollDef The original collection to search for @param origTableDef The original table @param classDef The class descriptor to test @return <code>true</code> if the class maps to a different table and has the collection """ if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) && !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE))) { CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName()); if ((curCollDef != null) && !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false)) { return true; } } return false; }
java
private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef) { if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) && !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE))) { CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName()); if ((curCollDef != null) && !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false)) { return true; } } return false; }
[ "private", "boolean", "containsCollectionAndMapsToDifferentTable", "(", "CollectionDescriptorDef", "origCollDef", ",", "TableDef", "origTableDef", ",", "ClassDescriptorDef", "classDef", ")", "{", "if", "(", "classDef", ".", "getBooleanProperty", "(", "PropertyHelper", ".", "OJB_PROPERTY_GENERATE_TABLE_INFO", ",", "true", ")", "&&", "!", "origTableDef", ".", "getName", "(", ")", ".", "equals", "(", "classDef", ".", "getProperty", "(", "PropertyHelper", ".", "OJB_PROPERTY_TABLE", ")", ")", ")", "{", "CollectionDescriptorDef", "curCollDef", "=", "classDef", ".", "getCollection", "(", "origCollDef", ".", "getName", "(", ")", ")", ";", "if", "(", "(", "curCollDef", "!=", "null", ")", "&&", "!", "curCollDef", ".", "getBooleanProperty", "(", "PropertyHelper", ".", "OJB_PROPERTY_IGNORE", ",", "false", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether the given class maps to a different table but also has the given collection. @param origCollDef The original collection to search for @param origTableDef The original table @param classDef The class descriptor to test @return <code>true</code> if the class maps to a different table and has the collection
[ "Checks", "whether", "the", "given", "class", "maps", "to", "a", "different", "table", "but", "also", "has", "the", "given", "collection", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/model/TorqueModelDef.java#L359-L373
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/MediaManagementApi.java
MediaManagementApi.releaseSnapshot
public ApiSuccessResponse releaseSnapshot(String snapshotId, ReleaseSnapshotBody releaseSnapshotBody) throws ApiException { """ Release the snapshot Release the snapshot specified. @param snapshotId Id of the snapshot (required) @param releaseSnapshotBody (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = releaseSnapshotWithHttpInfo(snapshotId, releaseSnapshotBody); return resp.getData(); }
java
public ApiSuccessResponse releaseSnapshot(String snapshotId, ReleaseSnapshotBody releaseSnapshotBody) throws ApiException { ApiResponse<ApiSuccessResponse> resp = releaseSnapshotWithHttpInfo(snapshotId, releaseSnapshotBody); return resp.getData(); }
[ "public", "ApiSuccessResponse", "releaseSnapshot", "(", "String", "snapshotId", ",", "ReleaseSnapshotBody", "releaseSnapshotBody", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "releaseSnapshotWithHttpInfo", "(", "snapshotId", ",", "releaseSnapshotBody", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Release the snapshot Release the snapshot specified. @param snapshotId Id of the snapshot (required) @param releaseSnapshotBody (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Release", "the", "snapshot", "Release", "the", "snapshot", "specified", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaManagementApi.java#L1126-L1129
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setVisibility
public static void setVisibility(EfficientCacheView cacheView, int viewId, int visibility) { """ Equivalent to calling View.setVisibility @param cacheView The cache of views to get the view from @param viewId The id of the view whose visibility should change @param visibility The new visibility for the view """ View view = cacheView.findViewByIdEfficient(viewId); if (view != null) { view.setVisibility(visibility); } }
java
public static void setVisibility(EfficientCacheView cacheView, int viewId, int visibility) { View view = cacheView.findViewByIdEfficient(viewId); if (view != null) { view.setVisibility(visibility); } }
[ "public", "static", "void", "setVisibility", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "int", "visibility", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "!=", "null", ")", "{", "view", ".", "setVisibility", "(", "visibility", ")", ";", "}", "}" ]
Equivalent to calling View.setVisibility @param cacheView The cache of views to get the view from @param viewId The id of the view whose visibility should change @param visibility The new visibility for the view
[ "Equivalent", "to", "calling", "View", ".", "setVisibility" ]
train
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L24-L29
rythmengine/rythmengine
src/main/java/org/rythmengine/RythmEngine.java
RythmEngine.getTemplate
@SuppressWarnings("unchecked") public ITemplate getTemplate(File file, Object... args) { """ Get an new template instance by template source {@link java.io.File file} and an array of arguments. <p/> <p>When the args array contains only one element and is of {@link java.util.Map} type the the render args are passed to template {@link ITemplate#__setRenderArgs(java.util.Map) by name}, otherwise they passes to template instance by position</p> @param file the template source file @param args the render args. See {@link #getTemplate(String, Object...)} @return template instance """ boolean typeInferenceEnabled = conf().typeInferenceEnabled(); if (typeInferenceEnabled) { ParamTypeInferencer.registerParams(this, args); } String key = S.str(resourceManager().get(file).getKey()); if (typeInferenceEnabled) { key += ParamTypeInferencer.uuid(); } TemplateClass tc = classes().getByTemplate(key); ITemplate t; if (null == tc) { tc = new TemplateClass(file, this); t = tc.asTemplate(this); if (null == t) return null; _templates.put(tc.getKey(), t); //classes().add(key, tc); } else { t = tc.asTemplate(this); } setRenderArgs(t, args); return t; }
java
@SuppressWarnings("unchecked") public ITemplate getTemplate(File file, Object... args) { boolean typeInferenceEnabled = conf().typeInferenceEnabled(); if (typeInferenceEnabled) { ParamTypeInferencer.registerParams(this, args); } String key = S.str(resourceManager().get(file).getKey()); if (typeInferenceEnabled) { key += ParamTypeInferencer.uuid(); } TemplateClass tc = classes().getByTemplate(key); ITemplate t; if (null == tc) { tc = new TemplateClass(file, this); t = tc.asTemplate(this); if (null == t) return null; _templates.put(tc.getKey(), t); //classes().add(key, tc); } else { t = tc.asTemplate(this); } setRenderArgs(t, args); return t; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "ITemplate", "getTemplate", "(", "File", "file", ",", "Object", "...", "args", ")", "{", "boolean", "typeInferenceEnabled", "=", "conf", "(", ")", ".", "typeInferenceEnabled", "(", ")", ";", "if", "(", "typeInferenceEnabled", ")", "{", "ParamTypeInferencer", ".", "registerParams", "(", "this", ",", "args", ")", ";", "}", "String", "key", "=", "S", ".", "str", "(", "resourceManager", "(", ")", ".", "get", "(", "file", ")", ".", "getKey", "(", ")", ")", ";", "if", "(", "typeInferenceEnabled", ")", "{", "key", "+=", "ParamTypeInferencer", ".", "uuid", "(", ")", ";", "}", "TemplateClass", "tc", "=", "classes", "(", ")", ".", "getByTemplate", "(", "key", ")", ";", "ITemplate", "t", ";", "if", "(", "null", "==", "tc", ")", "{", "tc", "=", "new", "TemplateClass", "(", "file", ",", "this", ")", ";", "t", "=", "tc", ".", "asTemplate", "(", "this", ")", ";", "if", "(", "null", "==", "t", ")", "return", "null", ";", "_templates", ".", "put", "(", "tc", ".", "getKey", "(", ")", ",", "t", ")", ";", "//classes().add(key, tc);", "}", "else", "{", "t", "=", "tc", ".", "asTemplate", "(", "this", ")", ";", "}", "setRenderArgs", "(", "t", ",", "args", ")", ";", "return", "t", ";", "}" ]
Get an new template instance by template source {@link java.io.File file} and an array of arguments. <p/> <p>When the args array contains only one element and is of {@link java.util.Map} type the the render args are passed to template {@link ITemplate#__setRenderArgs(java.util.Map) by name}, otherwise they passes to template instance by position</p> @param file the template source file @param args the render args. See {@link #getTemplate(String, Object...)} @return template instance
[ "Get", "an", "new", "template", "instance", "by", "template", "source", "{", "@link", "java", ".", "io", ".", "File", "file", "}", "and", "an", "array", "of", "arguments", ".", "<p", "/", ">", "<p", ">", "When", "the", "args", "array", "contains", "only", "one", "element", "and", "is", "of", "{", "@link", "java", ".", "util", ".", "Map", "}", "type", "the", "the", "render", "args", "are", "passed", "to", "template", "{", "@link", "ITemplate#__setRenderArgs", "(", "java", ".", "util", ".", "Map", ")", "by", "name", "}", "otherwise", "they", "passes", "to", "template", "instance", "by", "position<", "/", "p", ">" ]
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/RythmEngine.java#L952-L976
Bandwidth/java-bandwidth
src/main/java/com/bandwidth/sdk/model/Conference.java
Conference.getConference
public static Conference getConference(final String id) throws Exception { """ Retrieves the conference information. @param id conference id @return conference information. @throws IOException unexpected error. """ final BandwidthClient client = BandwidthClient.getInstance(); return getConference(client, id); }
java
public static Conference getConference(final String id) throws Exception { final BandwidthClient client = BandwidthClient.getInstance(); return getConference(client, id); }
[ "public", "static", "Conference", "getConference", "(", "final", "String", "id", ")", "throws", "Exception", "{", "final", "BandwidthClient", "client", "=", "BandwidthClient", ".", "getInstance", "(", ")", ";", "return", "getConference", "(", "client", ",", "id", ")", ";", "}" ]
Retrieves the conference information. @param id conference id @return conference information. @throws IOException unexpected error.
[ "Retrieves", "the", "conference", "information", "." ]
train
https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Conference.java#L28-L32
bazaarvoice/emodb
common/client/src/main/java/com/bazaarvoice/emodb/client/EntityHelper.java
EntityHelper.getEntity
public static <T> T getEntity(InputStream in, Class<T> clazz) { """ Reads the entity input stream and deserializes the JSON content to the given class. """ if (clazz == InputStream.class) { //noinspection unchecked return (T) clazz; } try { return JsonHelper.readJson(in, clazz); } catch (IOException e) { throw Throwables.propagate(e); } }
java
public static <T> T getEntity(InputStream in, Class<T> clazz) { if (clazz == InputStream.class) { //noinspection unchecked return (T) clazz; } try { return JsonHelper.readJson(in, clazz); } catch (IOException e) { throw Throwables.propagate(e); } }
[ "public", "static", "<", "T", ">", "T", "getEntity", "(", "InputStream", "in", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "clazz", "==", "InputStream", ".", "class", ")", "{", "//noinspection unchecked", "return", "(", "T", ")", "clazz", ";", "}", "try", "{", "return", "JsonHelper", ".", "readJson", "(", "in", ",", "clazz", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Reads the entity input stream and deserializes the JSON content to the given class.
[ "Reads", "the", "entity", "input", "stream", "and", "deserializes", "the", "JSON", "content", "to", "the", "given", "class", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/client/src/main/java/com/bazaarvoice/emodb/client/EntityHelper.java#L23-L34
jbundle/jbundle
app/program/db/src/main/java/org/jbundle/app/program/db/AnalysisLog.java
AnalysisLog.logAddRecord
public void logAddRecord(Rec record, int iSystemID) { """ Log that this record has been added. Call this from the end of record.init @param record the record that is being added. """ try { this.getTable().setProperty(DBParams.SUPRESSREMOTEDBMESSAGES, DBConstants.TRUE); this.getTable().getDatabase().setProperty(DBParams.MESSAGES_TO_REMOTE, DBConstants.FALSE); this.addNew(); this.getField(AnalysisLog.SYSTEM_ID).setValue(iSystemID); this.getField(AnalysisLog.OBJECT_ID).setValue(Debug.getObjectID(record, false)); this.getField(AnalysisLog.CLASS_NAME).setString(Debug.getClassName(record)); this.getField(AnalysisLog.DATABASE_NAME).setString(record.getDatabaseName()); ((DateTimeField)this.getField(AnalysisLog.INIT_TIME)).setValue(DateTimeField.currentTime()); this.getField(AnalysisLog.RECORD_OWNER).setString(Debug.getClassName(((Record)record).getRecordOwner())); this.getField(AnalysisLog.STACK_TRACE).setString(Debug.getStackTrace()); this.add(); } catch (DBException ex) { ex.printStackTrace(); } }
java
public void logAddRecord(Rec record, int iSystemID) { try { this.getTable().setProperty(DBParams.SUPRESSREMOTEDBMESSAGES, DBConstants.TRUE); this.getTable().getDatabase().setProperty(DBParams.MESSAGES_TO_REMOTE, DBConstants.FALSE); this.addNew(); this.getField(AnalysisLog.SYSTEM_ID).setValue(iSystemID); this.getField(AnalysisLog.OBJECT_ID).setValue(Debug.getObjectID(record, false)); this.getField(AnalysisLog.CLASS_NAME).setString(Debug.getClassName(record)); this.getField(AnalysisLog.DATABASE_NAME).setString(record.getDatabaseName()); ((DateTimeField)this.getField(AnalysisLog.INIT_TIME)).setValue(DateTimeField.currentTime()); this.getField(AnalysisLog.RECORD_OWNER).setString(Debug.getClassName(((Record)record).getRecordOwner())); this.getField(AnalysisLog.STACK_TRACE).setString(Debug.getStackTrace()); this.add(); } catch (DBException ex) { ex.printStackTrace(); } }
[ "public", "void", "logAddRecord", "(", "Rec", "record", ",", "int", "iSystemID", ")", "{", "try", "{", "this", ".", "getTable", "(", ")", ".", "setProperty", "(", "DBParams", ".", "SUPRESSREMOTEDBMESSAGES", ",", "DBConstants", ".", "TRUE", ")", ";", "this", ".", "getTable", "(", ")", ".", "getDatabase", "(", ")", ".", "setProperty", "(", "DBParams", ".", "MESSAGES_TO_REMOTE", ",", "DBConstants", ".", "FALSE", ")", ";", "this", ".", "addNew", "(", ")", ";", "this", ".", "getField", "(", "AnalysisLog", ".", "SYSTEM_ID", ")", ".", "setValue", "(", "iSystemID", ")", ";", "this", ".", "getField", "(", "AnalysisLog", ".", "OBJECT_ID", ")", ".", "setValue", "(", "Debug", ".", "getObjectID", "(", "record", ",", "false", ")", ")", ";", "this", ".", "getField", "(", "AnalysisLog", ".", "CLASS_NAME", ")", ".", "setString", "(", "Debug", ".", "getClassName", "(", "record", ")", ")", ";", "this", ".", "getField", "(", "AnalysisLog", ".", "DATABASE_NAME", ")", ".", "setString", "(", "record", ".", "getDatabaseName", "(", ")", ")", ";", "(", "(", "DateTimeField", ")", "this", ".", "getField", "(", "AnalysisLog", ".", "INIT_TIME", ")", ")", ".", "setValue", "(", "DateTimeField", ".", "currentTime", "(", ")", ")", ";", "this", ".", "getField", "(", "AnalysisLog", ".", "RECORD_OWNER", ")", ".", "setString", "(", "Debug", ".", "getClassName", "(", "(", "(", "Record", ")", "record", ")", ".", "getRecordOwner", "(", ")", ")", ")", ";", "this", ".", "getField", "(", "AnalysisLog", ".", "STACK_TRACE", ")", ".", "setString", "(", "Debug", ".", "getStackTrace", "(", ")", ")", ";", "this", ".", "add", "(", ")", ";", "}", "catch", "(", "DBException", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Log that this record has been added. Call this from the end of record.init @param record the record that is being added.
[ "Log", "that", "this", "record", "has", "been", "added", ".", "Call", "this", "from", "the", "end", "of", "record", ".", "init" ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/db/src/main/java/org/jbundle/app/program/db/AnalysisLog.java#L143-L161
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/map/AbstractMap.java
AbstractMap.setUp
protected void setUp(int initialCapacity, double minLoadFactor, double maxLoadFactor) { """ Initializes the receiver. You will almost certainly need to override this method in subclasses to initialize the hash table. @param initialCapacity the initial capacity of the receiver. @param minLoadFactor the minLoadFactor of the receiver. @param maxLoadFactor the maxLoadFactor of the receiver. @throws IllegalArgumentException if <tt>initialCapacity < 0 || (minLoadFactor < 0.0 || minLoadFactor >= 1.0) || (maxLoadFactor <= 0.0 || maxLoadFactor >= 1.0) || (minLoadFactor >= maxLoadFactor)</tt>. """ if (initialCapacity < 0) throw new IllegalArgumentException("Initial Capacity must not be less than zero: "+ initialCapacity); if (minLoadFactor < 0.0 || minLoadFactor >= 1.0) throw new IllegalArgumentException("Illegal minLoadFactor: "+ minLoadFactor); if (maxLoadFactor <= 0.0 || maxLoadFactor >= 1.0) throw new IllegalArgumentException("Illegal maxLoadFactor: "+ maxLoadFactor); if (minLoadFactor >= maxLoadFactor) throw new IllegalArgumentException("Illegal minLoadFactor: "+ minLoadFactor+" and maxLoadFactor: "+ maxLoadFactor); }
java
protected void setUp(int initialCapacity, double minLoadFactor, double maxLoadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Initial Capacity must not be less than zero: "+ initialCapacity); if (minLoadFactor < 0.0 || minLoadFactor >= 1.0) throw new IllegalArgumentException("Illegal minLoadFactor: "+ minLoadFactor); if (maxLoadFactor <= 0.0 || maxLoadFactor >= 1.0) throw new IllegalArgumentException("Illegal maxLoadFactor: "+ maxLoadFactor); if (minLoadFactor >= maxLoadFactor) throw new IllegalArgumentException("Illegal minLoadFactor: "+ minLoadFactor+" and maxLoadFactor: "+ maxLoadFactor); }
[ "protected", "void", "setUp", "(", "int", "initialCapacity", ",", "double", "minLoadFactor", ",", "double", "maxLoadFactor", ")", "{", "if", "(", "initialCapacity", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Initial Capacity must not be less than zero: \"", "+", "initialCapacity", ")", ";", "if", "(", "minLoadFactor", "<", "0.0", "||", "minLoadFactor", ">=", "1.0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Illegal minLoadFactor: \"", "+", "minLoadFactor", ")", ";", "if", "(", "maxLoadFactor", "<=", "0.0", "||", "maxLoadFactor", ">=", "1.0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Illegal maxLoadFactor: \"", "+", "maxLoadFactor", ")", ";", "if", "(", "minLoadFactor", ">=", "maxLoadFactor", ")", "throw", "new", "IllegalArgumentException", "(", "\"Illegal minLoadFactor: \"", "+", "minLoadFactor", "+", "\" and maxLoadFactor: \"", "+", "maxLoadFactor", ")", ";", "}" ]
Initializes the receiver. You will almost certainly need to override this method in subclasses to initialize the hash table. @param initialCapacity the initial capacity of the receiver. @param minLoadFactor the minLoadFactor of the receiver. @param maxLoadFactor the maxLoadFactor of the receiver. @throws IllegalArgumentException if <tt>initialCapacity < 0 || (minLoadFactor < 0.0 || minLoadFactor >= 1.0) || (maxLoadFactor <= 0.0 || maxLoadFactor >= 1.0) || (minLoadFactor >= maxLoadFactor)</tt>.
[ "Initializes", "the", "receiver", ".", "You", "will", "almost", "certainly", "need", "to", "override", "this", "method", "in", "subclasses", "to", "initialize", "the", "hash", "table", "." ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/map/AbstractMap.java#L137-L146
knowm/XChange
xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java
OrderBook.update
private void update(List<LimitOrder> asks, LimitOrder limitOrder) { """ Replace the amount for limitOrder's price in the provided list. """ int idx = Collections.binarySearch(asks, limitOrder); if (idx >= 0) { asks.remove(idx); asks.add(idx, limitOrder); } else { asks.add(-idx - 1, limitOrder); } }
java
private void update(List<LimitOrder> asks, LimitOrder limitOrder) { int idx = Collections.binarySearch(asks, limitOrder); if (idx >= 0) { asks.remove(idx); asks.add(idx, limitOrder); } else { asks.add(-idx - 1, limitOrder); } }
[ "private", "void", "update", "(", "List", "<", "LimitOrder", ">", "asks", ",", "LimitOrder", "limitOrder", ")", "{", "int", "idx", "=", "Collections", ".", "binarySearch", "(", "asks", ",", "limitOrder", ")", ";", "if", "(", "idx", ">=", "0", ")", "{", "asks", ".", "remove", "(", "idx", ")", ";", "asks", ".", "add", "(", "idx", ",", "limitOrder", ")", ";", "}", "else", "{", "asks", ".", "add", "(", "-", "idx", "-", "1", ",", "limitOrder", ")", ";", "}", "}" ]
Replace the amount for limitOrder's price in the provided list.
[ "Replace", "the", "amount", "for", "limitOrder", "s", "price", "in", "the", "provided", "list", "." ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java#L140-L149
prestodb/presto
presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/Indexer.java
Indexer.getMetricsTableName
public static String getMetricsTableName(String schema, String table) { """ Gets the fully-qualified index metrics table name for the given table. @param schema Schema name @param table Table name @return Qualified index metrics table name """ return schema.equals("default") ? table + "_idx_metrics" : schema + '.' + table + "_idx_metrics"; }
java
public static String getMetricsTableName(String schema, String table) { return schema.equals("default") ? table + "_idx_metrics" : schema + '.' + table + "_idx_metrics"; }
[ "public", "static", "String", "getMetricsTableName", "(", "String", "schema", ",", "String", "table", ")", "{", "return", "schema", ".", "equals", "(", "\"default\"", ")", "?", "table", "+", "\"_idx_metrics\"", ":", "schema", "+", "'", "'", "+", "table", "+", "\"_idx_metrics\"", ";", "}" ]
Gets the fully-qualified index metrics table name for the given table. @param schema Schema name @param table Table name @return Qualified index metrics table name
[ "Gets", "the", "fully", "-", "qualified", "index", "metrics", "table", "name", "for", "the", "given", "table", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/Indexer.java#L454-L458
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Collectors.java
Collectors.toConcurrentMap
public static <T, K, U> Collector<T, ?, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { """ Returns a concurrent {@code Collector} that accumulates elements into a {@code ConcurrentMap} whose keys and values are the result of applying the provided mapping functions to the input elements. <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}), an {@code IllegalStateException} is thrown when the collection operation is performed. If the mapped keys may have duplicates, use {@link #toConcurrentMap(Function, Function, BinaryOperator)} instead. @apiNote It is common for either the key or the value to be the input elements. In this case, the utility method {@link java.util.function.Function#identity()} may be helpful. For example, the following produces a {@code Map} mapping students to their grade point average: <pre>{@code Map<Student, Double> studentToGPA students.stream().collect(toMap(Functions.identity(), student -> computeGPA(student))); }</pre> And the following produces a {@code Map} mapping a unique identifier to students: <pre>{@code Map<String, Student> studentIdToStudent students.stream().collect(toConcurrentMap(Student::getId, Functions.identity()); }</pre> <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and {@link Collector.Characteristics#UNORDERED unordered} Collector. @param <T> the type of the input elements @param <K> the output type of the key mapping function @param <U> the output type of the value mapping function @param keyMapper the mapping function to produce keys @param valueMapper the mapping function to produce values @return a concurrent, unordered {@code Collector} which collects elements into a {@code ConcurrentMap} whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to the input elements @see #toMap(Function, Function) @see #toConcurrentMap(Function, Function, BinaryOperator) @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier) """ return toConcurrentMap(keyMapper, valueMapper, throwingMerger(), ConcurrentHashMap::new); }
java
public static <T, K, U> Collector<T, ?, ConcurrentMap<K,U>> toConcurrentMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { return toConcurrentMap(keyMapper, valueMapper, throwingMerger(), ConcurrentHashMap::new); }
[ "public", "static", "<", "T", ",", "K", ",", "U", ">", "Collector", "<", "T", ",", "?", ",", "ConcurrentMap", "<", "K", ",", "U", ">", ">", "toConcurrentMap", "(", "Function", "<", "?", "super", "T", ",", "?", "extends", "K", ">", "keyMapper", ",", "Function", "<", "?", "super", "T", ",", "?", "extends", "U", ">", "valueMapper", ")", "{", "return", "toConcurrentMap", "(", "keyMapper", ",", "valueMapper", ",", "throwingMerger", "(", ")", ",", "ConcurrentHashMap", "::", "new", ")", ";", "}" ]
Returns a concurrent {@code Collector} that accumulates elements into a {@code ConcurrentMap} whose keys and values are the result of applying the provided mapping functions to the input elements. <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}), an {@code IllegalStateException} is thrown when the collection operation is performed. If the mapped keys may have duplicates, use {@link #toConcurrentMap(Function, Function, BinaryOperator)} instead. @apiNote It is common for either the key or the value to be the input elements. In this case, the utility method {@link java.util.function.Function#identity()} may be helpful. For example, the following produces a {@code Map} mapping students to their grade point average: <pre>{@code Map<Student, Double> studentToGPA students.stream().collect(toMap(Functions.identity(), student -> computeGPA(student))); }</pre> And the following produces a {@code Map} mapping a unique identifier to students: <pre>{@code Map<String, Student> studentIdToStudent students.stream().collect(toConcurrentMap(Student::getId, Functions.identity()); }</pre> <p>This is a {@link Collector.Characteristics#CONCURRENT concurrent} and {@link Collector.Characteristics#UNORDERED unordered} Collector. @param <T> the type of the input elements @param <K> the output type of the key mapping function @param <U> the output type of the value mapping function @param keyMapper the mapping function to produce keys @param valueMapper the mapping function to produce values @return a concurrent, unordered {@code Collector} which collects elements into a {@code ConcurrentMap} whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to the input elements @see #toMap(Function, Function) @see #toConcurrentMap(Function, Function, BinaryOperator) @see #toConcurrentMap(Function, Function, BinaryOperator, Supplier)
[ "Returns", "a", "concurrent", "{", "@code", "Collector", "}", "that", "accumulates", "elements", "into", "a", "{", "@code", "ConcurrentMap", "}", "whose", "keys", "and", "values", "are", "the", "result", "of", "applying", "the", "provided", "mapping", "functions", "to", "the", "input", "elements", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Collectors.java#L1372-L1376
bwkimmel/jdcp
jdcp-worker/src/main/java/ca/eandb/jdcp/worker/FileCachingJobServiceClassLoaderStrategy.java
FileCachingJobServiceClassLoaderStrategy.getCacheEntryFile
private File getCacheEntryFile(String name, byte[] digest, boolean createDirectory) { """ Gets the <code>File</code> in which to store the given class definition. @param name The fully qualified name of the class. @param digest The MD5 digest of the class definition. @param createDirectory A value indicating whether the directory containing the file should be created if it does not yet exist. @return The <code>File</code> to use for storing the cached class definition. """ File entryDirectory = new File(directory, name.replace('.', '/')); if (createDirectory && !entryDirectory.isDirectory()) { entryDirectory.mkdirs(); } return new File(entryDirectory, StringUtil.toHex(digest)); }
java
private File getCacheEntryFile(String name, byte[] digest, boolean createDirectory) { File entryDirectory = new File(directory, name.replace('.', '/')); if (createDirectory && !entryDirectory.isDirectory()) { entryDirectory.mkdirs(); } return new File(entryDirectory, StringUtil.toHex(digest)); }
[ "private", "File", "getCacheEntryFile", "(", "String", "name", ",", "byte", "[", "]", "digest", ",", "boolean", "createDirectory", ")", "{", "File", "entryDirectory", "=", "new", "File", "(", "directory", ",", "name", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ")", ";", "if", "(", "createDirectory", "&&", "!", "entryDirectory", ".", "isDirectory", "(", ")", ")", "{", "entryDirectory", ".", "mkdirs", "(", ")", ";", "}", "return", "new", "File", "(", "entryDirectory", ",", "StringUtil", ".", "toHex", "(", "digest", ")", ")", ";", "}" ]
Gets the <code>File</code> in which to store the given class definition. @param name The fully qualified name of the class. @param digest The MD5 digest of the class definition. @param createDirectory A value indicating whether the directory containing the file should be created if it does not yet exist. @return The <code>File</code> to use for storing the cached class definition.
[ "Gets", "the", "<code", ">", "File<", "/", "code", ">", "in", "which", "to", "store", "the", "given", "class", "definition", "." ]
train
https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-worker/src/main/java/ca/eandb/jdcp/worker/FileCachingJobServiceClassLoaderStrategy.java#L125-L131
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Metric.java
Metric.averageExistingDatapoints
public void averageExistingDatapoints(Map<Long, Double> datapoints) { """ If current set already has a value at that timestamp then replace the latest average value for that timestamp at coinciding cutoff boundary, else adds the new data points to the current set. @param datapoints The set of data points to add. If null or empty, no operation is performed. """ if (datapoints != null) { for(Entry<Long, Double> entry : datapoints.entrySet()){ _datapoints.put(entry.getKey(), entry.getValue()); } } }
java
public void averageExistingDatapoints(Map<Long, Double> datapoints) { if (datapoints != null) { for(Entry<Long, Double> entry : datapoints.entrySet()){ _datapoints.put(entry.getKey(), entry.getValue()); } } }
[ "public", "void", "averageExistingDatapoints", "(", "Map", "<", "Long", ",", "Double", ">", "datapoints", ")", "{", "if", "(", "datapoints", "!=", "null", ")", "{", "for", "(", "Entry", "<", "Long", ",", "Double", ">", "entry", ":", "datapoints", ".", "entrySet", "(", ")", ")", "{", "_datapoints", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
If current set already has a value at that timestamp then replace the latest average value for that timestamp at coinciding cutoff boundary, else adds the new data points to the current set. @param datapoints The set of data points to add. If null or empty, no operation is performed.
[ "If", "current", "set", "already", "has", "a", "value", "at", "that", "timestamp", "then", "replace", "the", "latest", "average", "value", "for", "that", "timestamp", "at", "coinciding", "cutoff", "boundary", "else", "adds", "the", "new", "data", "points", "to", "the", "current", "set", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Metric.java#L248-L255
aws/aws-sdk-java
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/UpdateServiceActionRequest.java
UpdateServiceActionRequest.withDefinition
public UpdateServiceActionRequest withDefinition(java.util.Map<String, String> definition) { """ <p> A map that defines the self-service action. </p> @param definition A map that defines the self-service action. @return Returns a reference to this object so that method calls can be chained together. """ setDefinition(definition); return this; }
java
public UpdateServiceActionRequest withDefinition(java.util.Map<String, String> definition) { setDefinition(definition); return this; }
[ "public", "UpdateServiceActionRequest", "withDefinition", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "definition", ")", "{", "setDefinition", "(", "definition", ")", ";", "return", "this", ";", "}" ]
<p> A map that defines the self-service action. </p> @param definition A map that defines the self-service action. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "that", "defines", "the", "self", "-", "service", "action", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/UpdateServiceActionRequest.java#L191-L194
cubedtear/aritzh
aritzh-core/src/main/java/io/github/aritzhack/aritzh/config/Configuration.java
Configuration.loadConfig
public static Configuration loadConfig(Path configFile, boolean compressSpaces) { """ Loads the configuration path, specifying if spaces should be compressed or not ({@code currentLine.replaceAll("\\s+", " ")}) If the config path did not exist, it will be created @param configFile Path to read the configuration from @param compressSpaces If true subsequent whitespaces will be replaced with a single one (defaults to {@code false}) @return A new configuration object, already parsed, from {@code configFile} """ if (Files.notExists(configFile)) { return Configuration.newConfig(OneOrOther.<File, Path>ofOther(configFile)); } Configuration config = new Configuration(OneOrOther.<File, Path>ofOther(configFile), compressSpaces); try (BufferedReader reader = Files.newBufferedReader(configFile, Charset.defaultCharset())) { loadConfig(config, reader, compressSpaces); } catch (IOException e) { e.printStackTrace(); } return config; }
java
public static Configuration loadConfig(Path configFile, boolean compressSpaces) { if (Files.notExists(configFile)) { return Configuration.newConfig(OneOrOther.<File, Path>ofOther(configFile)); } Configuration config = new Configuration(OneOrOther.<File, Path>ofOther(configFile), compressSpaces); try (BufferedReader reader = Files.newBufferedReader(configFile, Charset.defaultCharset())) { loadConfig(config, reader, compressSpaces); } catch (IOException e) { e.printStackTrace(); } return config; }
[ "public", "static", "Configuration", "loadConfig", "(", "Path", "configFile", ",", "boolean", "compressSpaces", ")", "{", "if", "(", "Files", ".", "notExists", "(", "configFile", ")", ")", "{", "return", "Configuration", ".", "newConfig", "(", "OneOrOther", ".", "<", "File", ",", "Path", ">", "ofOther", "(", "configFile", ")", ")", ";", "}", "Configuration", "config", "=", "new", "Configuration", "(", "OneOrOther", ".", "<", "File", ",", "Path", ">", "ofOther", "(", "configFile", ")", ",", "compressSpaces", ")", ";", "try", "(", "BufferedReader", "reader", "=", "Files", ".", "newBufferedReader", "(", "configFile", ",", "Charset", ".", "defaultCharset", "(", ")", ")", ")", "{", "loadConfig", "(", "config", ",", "reader", ",", "compressSpaces", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "config", ";", "}" ]
Loads the configuration path, specifying if spaces should be compressed or not ({@code currentLine.replaceAll("\\s+", " ")}) If the config path did not exist, it will be created @param configFile Path to read the configuration from @param compressSpaces If true subsequent whitespaces will be replaced with a single one (defaults to {@code false}) @return A new configuration object, already parsed, from {@code configFile}
[ "Loads", "the", "configuration", "path", "specifying", "if", "spaces", "should", "be", "compressed", "or", "not", "(", "{", "@code", "currentLine", ".", "replaceAll", "(", "\\\\", "s", "+", ")", "}", ")", "If", "the", "config", "path", "did", "not", "exist", "it", "will", "be", "created" ]
train
https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/config/Configuration.java#L151-L164
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/EnumBindTransform.java
EnumBindTransform.generateSerializeOnJackson
@Override public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { """ /* (non-Javadoc) @see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateSerializeOnJackson(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty) """ if (property.isNullable()) { methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); } if (property.isProperty()) { methodBuilder.addStatement("fieldCount++"); } if (property.isInCollection()) { methodBuilder.addStatement("$L.writeString($L.$L())", serializerName, getter(beanName, beanClass, property), METHOD_TO_CONVERT); } else { methodBuilder.addStatement("$L.writeStringField($S, $L.$L())", serializerName, property.label, getter(beanName, beanClass, property), METHOD_TO_CONVERT); } if (property.isNullable()) { methodBuilder.endControlFlow(); } }
java
@Override public void generateSerializeOnJackson(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { if (property.isNullable()) { methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); } if (property.isProperty()) { methodBuilder.addStatement("fieldCount++"); } if (property.isInCollection()) { methodBuilder.addStatement("$L.writeString($L.$L())", serializerName, getter(beanName, beanClass, property), METHOD_TO_CONVERT); } else { methodBuilder.addStatement("$L.writeStringField($S, $L.$L())", serializerName, property.label, getter(beanName, beanClass, property), METHOD_TO_CONVERT); } if (property.isNullable()) { methodBuilder.endControlFlow(); } }
[ "@", "Override", "public", "void", "generateSerializeOnJackson", "(", "BindTypeContext", "context", ",", "MethodSpec", ".", "Builder", "methodBuilder", ",", "String", "serializerName", ",", "TypeName", "beanClass", ",", "String", "beanName", ",", "BindProperty", "property", ")", "{", "if", "(", "property", ".", "isNullable", "(", ")", ")", "{", "methodBuilder", ".", "beginControlFlow", "(", "\"if ($L!=null) \"", ",", "getter", "(", "beanName", ",", "beanClass", ",", "property", ")", ")", ";", "}", "if", "(", "property", ".", "isProperty", "(", ")", ")", "{", "methodBuilder", ".", "addStatement", "(", "\"fieldCount++\"", ")", ";", "}", "if", "(", "property", ".", "isInCollection", "(", ")", ")", "{", "methodBuilder", ".", "addStatement", "(", "\"$L.writeString($L.$L())\"", ",", "serializerName", ",", "getter", "(", "beanName", ",", "beanClass", ",", "property", ")", ",", "METHOD_TO_CONVERT", ")", ";", "}", "else", "{", "methodBuilder", ".", "addStatement", "(", "\"$L.writeStringField($S, $L.$L())\"", ",", "serializerName", ",", "property", ".", "label", ",", "getter", "(", "beanName", ",", "beanClass", ",", "property", ")", ",", "METHOD_TO_CONVERT", ")", ";", "}", "if", "(", "property", ".", "isNullable", "(", ")", ")", "{", "methodBuilder", ".", "endControlFlow", "(", ")", ";", "}", "}" ]
/* (non-Javadoc) @see com.abubusoft.kripton.processor.bind.transform.BindTransform#generateSerializeOnJackson(com.abubusoft.kripton.processor.bind.BindTypeContext, com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.bind.model.BindProperty)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/EnumBindTransform.java#L100-L119
sarxos/v4l4j
src/main/java/au/edu/jcu/v4l4j/VideoDevice.java
VideoDevice.initDeviceInfo
private void initDeviceInfo() throws V4L4JException { """ This method initialises this VideoDevice with the information obtained from the {@link DeviceInfo}. This method must be called before any other methods. @throws V4L4JException if the device can not be initialised """ //initialise deviceInfo deviceInfo = new DeviceInfo(v4l4jObject, deviceFile); ImageFormatList l = deviceInfo.getFormatList(); supportJPEG = l.getJPEGEncodableFormats().size()==0?false:true; supportRGB24 = l.getRGBEncodableFormats().size()==0?false:true; supportBGR24 = l.getBGREncodableFormats().size()==0?false:true; supportYUV420 = l.getYUVEncodableFormats().size()==0?false:true; supportYVU420 = l.getYVUEncodableFormats().size()==0?false:true; //initialise TunerList Vector<Tuner> v= new Vector<Tuner>(); doGetTunerActions(v4l4jObject); for(InputInfo i:deviceInfo.getInputs()){ try { v.add(new Tuner(v4l4jObject,i.getTunerInfo())); } catch (NoTunerException e) {} //no tuner for this input } if(v.size()!=0) tuners = new TunerList(v); }
java
private void initDeviceInfo() throws V4L4JException{ //initialise deviceInfo deviceInfo = new DeviceInfo(v4l4jObject, deviceFile); ImageFormatList l = deviceInfo.getFormatList(); supportJPEG = l.getJPEGEncodableFormats().size()==0?false:true; supportRGB24 = l.getRGBEncodableFormats().size()==0?false:true; supportBGR24 = l.getBGREncodableFormats().size()==0?false:true; supportYUV420 = l.getYUVEncodableFormats().size()==0?false:true; supportYVU420 = l.getYVUEncodableFormats().size()==0?false:true; //initialise TunerList Vector<Tuner> v= new Vector<Tuner>(); doGetTunerActions(v4l4jObject); for(InputInfo i:deviceInfo.getInputs()){ try { v.add(new Tuner(v4l4jObject,i.getTunerInfo())); } catch (NoTunerException e) {} //no tuner for this input } if(v.size()!=0) tuners = new TunerList(v); }
[ "private", "void", "initDeviceInfo", "(", ")", "throws", "V4L4JException", "{", "//initialise deviceInfo", "deviceInfo", "=", "new", "DeviceInfo", "(", "v4l4jObject", ",", "deviceFile", ")", ";", "ImageFormatList", "l", "=", "deviceInfo", ".", "getFormatList", "(", ")", ";", "supportJPEG", "=", "l", ".", "getJPEGEncodableFormats", "(", ")", ".", "size", "(", ")", "==", "0", "?", "false", ":", "true", ";", "supportRGB24", "=", "l", ".", "getRGBEncodableFormats", "(", ")", ".", "size", "(", ")", "==", "0", "?", "false", ":", "true", ";", "supportBGR24", "=", "l", ".", "getBGREncodableFormats", "(", ")", ".", "size", "(", ")", "==", "0", "?", "false", ":", "true", ";", "supportYUV420", "=", "l", ".", "getYUVEncodableFormats", "(", ")", ".", "size", "(", ")", "==", "0", "?", "false", ":", "true", ";", "supportYVU420", "=", "l", ".", "getYVUEncodableFormats", "(", ")", ".", "size", "(", ")", "==", "0", "?", "false", ":", "true", ";", "//initialise TunerList", "Vector", "<", "Tuner", ">", "v", "=", "new", "Vector", "<", "Tuner", ">", "(", ")", ";", "doGetTunerActions", "(", "v4l4jObject", ")", ";", "for", "(", "InputInfo", "i", ":", "deviceInfo", ".", "getInputs", "(", ")", ")", "{", "try", "{", "v", ".", "add", "(", "new", "Tuner", "(", "v4l4jObject", ",", "i", ".", "getTunerInfo", "(", ")", ")", ")", ";", "}", "catch", "(", "NoTunerException", "e", ")", "{", "}", "//no tuner for this input", "}", "if", "(", "v", ".", "size", "(", ")", "!=", "0", ")", "tuners", "=", "new", "TunerList", "(", "v", ")", ";", "}" ]
This method initialises this VideoDevice with the information obtained from the {@link DeviceInfo}. This method must be called before any other methods. @throws V4L4JException if the device can not be initialised
[ "This", "method", "initialises", "this", "VideoDevice", "with", "the", "information", "obtained", "from", "the", "{" ]
train
https://github.com/sarxos/v4l4j/blob/4fc0eec2c3a1a4260593f6ac03b7a8013e3804c9/src/main/java/au/edu/jcu/v4l4j/VideoDevice.java#L296-L318
sagiegurari/fax4j
src/main/java/org/fax4j/util/IOHelper.java
IOHelper.createReader
public static Reader createReader(InputStream inputStream,String encoding) { """ This function creates and returns a new reader for the provided input stream. @param inputStream The input stream @param encoding The encoding used by the reader (null for default system encoding) @return The reader """ //get encoding String updatedEncoding=IOHelper.getEncodingToUse(encoding); //create reader Reader reader=null; try { reader=new InputStreamReader(inputStream,updatedEncoding); } catch(UnsupportedEncodingException exception) { throw new FaxException("Unable to create reader, unsupported encoding: "+encoding,exception); } return reader; }
java
public static Reader createReader(InputStream inputStream,String encoding) { //get encoding String updatedEncoding=IOHelper.getEncodingToUse(encoding); //create reader Reader reader=null; try { reader=new InputStreamReader(inputStream,updatedEncoding); } catch(UnsupportedEncodingException exception) { throw new FaxException("Unable to create reader, unsupported encoding: "+encoding,exception); } return reader; }
[ "public", "static", "Reader", "createReader", "(", "InputStream", "inputStream", ",", "String", "encoding", ")", "{", "//get encoding", "String", "updatedEncoding", "=", "IOHelper", ".", "getEncodingToUse", "(", "encoding", ")", ";", "//create reader", "Reader", "reader", "=", "null", ";", "try", "{", "reader", "=", "new", "InputStreamReader", "(", "inputStream", ",", "updatedEncoding", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "exception", ")", "{", "throw", "new", "FaxException", "(", "\"Unable to create reader, unsupported encoding: \"", "+", "encoding", ",", "exception", ")", ";", "}", "return", "reader", ";", "}" ]
This function creates and returns a new reader for the provided input stream. @param inputStream The input stream @param encoding The encoding used by the reader (null for default system encoding) @return The reader
[ "This", "function", "creates", "and", "returns", "a", "new", "reader", "for", "the", "provided", "input", "stream", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/util/IOHelper.java#L235-L252
overturetool/overture
ide/debug/src/main/java/org/overture/ide/debug/ui/launchconfigurations/VdmLaunchShortcut.java
VdmLaunchShortcut.chooseType
protected INode chooseType(INode[] types, String title) { """ Prompts the user to select a type from the given types. @param types the types to choose from @param title the selection dialog title @return the selected type or <code>null</code> if none. """ try { DebugTypeSelectionDialog mmsd = new DebugTypeSelectionDialog(VdmDebugPlugin.getActiveWorkbenchShell(), types, title, project); if (mmsd.open() == Window.OK) { return (INode) mmsd.getResult()[0]; } } catch (Exception e) { e.printStackTrace(); } return null; }
java
protected INode chooseType(INode[] types, String title) { try { DebugTypeSelectionDialog mmsd = new DebugTypeSelectionDialog(VdmDebugPlugin.getActiveWorkbenchShell(), types, title, project); if (mmsd.open() == Window.OK) { return (INode) mmsd.getResult()[0]; } } catch (Exception e) { e.printStackTrace(); } return null; }
[ "protected", "INode", "chooseType", "(", "INode", "[", "]", "types", ",", "String", "title", ")", "{", "try", "{", "DebugTypeSelectionDialog", "mmsd", "=", "new", "DebugTypeSelectionDialog", "(", "VdmDebugPlugin", ".", "getActiveWorkbenchShell", "(", ")", ",", "types", ",", "title", ",", "project", ")", ";", "if", "(", "mmsd", ".", "open", "(", ")", "==", "Window", ".", "OK", ")", "{", "return", "(", "INode", ")", "mmsd", ".", "getResult", "(", ")", "[", "0", "]", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "null", ";", "}" ]
Prompts the user to select a type from the given types. @param types the types to choose from @param title the selection dialog title @return the selected type or <code>null</code> if none.
[ "Prompts", "the", "user", "to", "select", "a", "type", "from", "the", "given", "types", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/ui/launchconfigurations/VdmLaunchShortcut.java#L193-L208
UrielCh/ovh-java-sdk
ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java
ApiOvhVps.serviceName_disks_id_PUT
public void serviceName_disks_id_PUT(String serviceName, Long id, OvhDisk body) throws IOException { """ Alter this object properties REST: PUT /vps/{serviceName}/disks/{id} @param body [required] New object properties @param serviceName [required] The internal name of your VPS offer @param id [required] Id of the object """ String qPath = "/vps/{serviceName}/disks/{id}"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_disks_id_PUT(String serviceName, Long id, OvhDisk body) throws IOException { String qPath = "/vps/{serviceName}/disks/{id}"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_disks_id_PUT", "(", "String", "serviceName", ",", "Long", "id", ",", "OvhDisk", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/vps/{serviceName}/disks/{id}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "id", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /vps/{serviceName}/disks/{id} @param body [required] New object properties @param serviceName [required] The internal name of your VPS offer @param id [required] Id of the object
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vps/src/main/java/net/minidev/ovh/api/ApiOvhVps.java#L894-L898
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Duration.java
Duration.ofSeconds
public static Duration ofSeconds(long seconds, long nanoAdjustment) { """ Obtains a {@code Duration} representing a number of seconds and an adjustment in nanoseconds. <p> This method allows an arbitrary number of nanoseconds to be passed in. The factory will alter the values of the second and nanosecond in order to ensure that the stored nanosecond is in the range 0 to 999,999,999. For example, the following will result in the exactly the same duration: <pre> Duration.ofSeconds(3, 1); Duration.ofSeconds(4, -999_999_999); Duration.ofSeconds(2, 1000_000_001); </pre> @param seconds the number of seconds, positive or negative @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative @return a {@code Duration}, not null @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration} """ long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); return create(secs, nos); }
java
public static Duration ofSeconds(long seconds, long nanoAdjustment) { long secs = Math.addExact(seconds, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); int nos = (int) Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); return create(secs, nos); }
[ "public", "static", "Duration", "ofSeconds", "(", "long", "seconds", ",", "long", "nanoAdjustment", ")", "{", "long", "secs", "=", "Math", ".", "addExact", "(", "seconds", ",", "Math", ".", "floorDiv", "(", "nanoAdjustment", ",", "NANOS_PER_SECOND", ")", ")", ";", "int", "nos", "=", "(", "int", ")", "Math", ".", "floorMod", "(", "nanoAdjustment", ",", "NANOS_PER_SECOND", ")", ";", "return", "create", "(", "secs", ",", "nos", ")", ";", "}" ]
Obtains a {@code Duration} representing a number of seconds and an adjustment in nanoseconds. <p> This method allows an arbitrary number of nanoseconds to be passed in. The factory will alter the values of the second and nanosecond in order to ensure that the stored nanosecond is in the range 0 to 999,999,999. For example, the following will result in the exactly the same duration: <pre> Duration.ofSeconds(3, 1); Duration.ofSeconds(4, -999_999_999); Duration.ofSeconds(2, 1000_000_001); </pre> @param seconds the number of seconds, positive or negative @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative @return a {@code Duration}, not null @throws ArithmeticException if the adjustment causes the seconds to exceed the capacity of {@code Duration}
[ "Obtains", "a", "{", "@code", "Duration", "}", "representing", "a", "number", "of", "seconds", "and", "an", "adjustment", "in", "nanoseconds", ".", "<p", ">", "This", "method", "allows", "an", "arbitrary", "number", "of", "nanoseconds", "to", "be", "passed", "in", ".", "The", "factory", "will", "alter", "the", "values", "of", "the", "second", "and", "nanosecond", "in", "order", "to", "ensure", "that", "the", "stored", "nanosecond", "is", "in", "the", "range", "0", "to", "999", "999", "999", ".", "For", "example", "the", "following", "will", "result", "in", "the", "exactly", "the", "same", "duration", ":", "<pre", ">", "Duration", ".", "ofSeconds", "(", "3", "1", ")", ";", "Duration", ".", "ofSeconds", "(", "4", "-", "999_999_999", ")", ";", "Duration", ".", "ofSeconds", "(", "2", "1000_000_001", ")", ";", "<", "/", "pre", ">" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Duration.java#L238-L242
hal/elemento
core/src/main/java/org/jboss/gwt/elemento/core/Elements.java
Elements.failSafeRemove
public static boolean failSafeRemove(Node parent, Element child) { """ Removes the child from parent if both parent and child are not null and parent contains child. @return {@code true} if the the element has been removed from its parent, {@code false} otherwise. """ //noinspection SimplifiableIfStatement if (parent != null && child != null && parent.contains(child)) { return parent.removeChild(child) != null; } return false; }
java
public static boolean failSafeRemove(Node parent, Element child) { //noinspection SimplifiableIfStatement if (parent != null && child != null && parent.contains(child)) { return parent.removeChild(child) != null; } return false; }
[ "public", "static", "boolean", "failSafeRemove", "(", "Node", "parent", ",", "Element", "child", ")", "{", "//noinspection SimplifiableIfStatement", "if", "(", "parent", "!=", "null", "&&", "child", "!=", "null", "&&", "parent", ".", "contains", "(", "child", ")", ")", "{", "return", "parent", ".", "removeChild", "(", "child", ")", "!=", "null", ";", "}", "return", "false", ";", "}" ]
Removes the child from parent if both parent and child are not null and parent contains child. @return {@code true} if the the element has been removed from its parent, {@code false} otherwise.
[ "Removes", "the", "child", "from", "parent", "if", "both", "parent", "and", "child", "are", "not", "null", "and", "parent", "contains", "child", "." ]
train
https://github.com/hal/elemento/blob/26da2d5a1fe2ec55b779737dbaeda25a942eee61/core/src/main/java/org/jboss/gwt/elemento/core/Elements.java#L727-L733
agapsys/embedded-servlet-container
src/main/java/com/agapsys/jee/ServletContainer.java
ServletContainer.registerServlet
public final SC registerServlet(Class<? extends HttpServlet> servletClass) { """ Registers a servlet. @param servletClass servlet class to be registered. This class must be annotated with {@linkplain WebServlet}. @return this. """ WebServlet webServlet = servletClass.getAnnotation(WebServlet.class); if (webServlet == null) throw new IllegalArgumentException(String.format("Missing annotation '%s' for class '%s'", WebFilter.class.getName(), servletClass.getName())); String[] urlPatterns = webServlet.value(); if (urlPatterns.length == 0) urlPatterns = webServlet.urlPatterns(); if (urlPatterns.length == 0) throw new IllegalArgumentException(String.format("Missing pattern mapping for '%s'", servletClass.getName())); for (String urlPattern : urlPatterns) { registerServlet(servletClass, urlPattern); } return (SC) this; }
java
public final SC registerServlet(Class<? extends HttpServlet> servletClass) { WebServlet webServlet = servletClass.getAnnotation(WebServlet.class); if (webServlet == null) throw new IllegalArgumentException(String.format("Missing annotation '%s' for class '%s'", WebFilter.class.getName(), servletClass.getName())); String[] urlPatterns = webServlet.value(); if (urlPatterns.length == 0) urlPatterns = webServlet.urlPatterns(); if (urlPatterns.length == 0) throw new IllegalArgumentException(String.format("Missing pattern mapping for '%s'", servletClass.getName())); for (String urlPattern : urlPatterns) { registerServlet(servletClass, urlPattern); } return (SC) this; }
[ "public", "final", "SC", "registerServlet", "(", "Class", "<", "?", "extends", "HttpServlet", ">", "servletClass", ")", "{", "WebServlet", "webServlet", "=", "servletClass", ".", "getAnnotation", "(", "WebServlet", ".", "class", ")", ";", "if", "(", "webServlet", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Missing annotation '%s' for class '%s'\"", ",", "WebFilter", ".", "class", ".", "getName", "(", ")", ",", "servletClass", ".", "getName", "(", ")", ")", ")", ";", "String", "[", "]", "urlPatterns", "=", "webServlet", ".", "value", "(", ")", ";", "if", "(", "urlPatterns", ".", "length", "==", "0", ")", "urlPatterns", "=", "webServlet", ".", "urlPatterns", "(", ")", ";", "if", "(", "urlPatterns", ".", "length", "==", "0", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Missing pattern mapping for '%s'\"", ",", "servletClass", ".", "getName", "(", ")", ")", ")", ";", "for", "(", "String", "urlPattern", ":", "urlPatterns", ")", "{", "registerServlet", "(", "servletClass", ",", "urlPattern", ")", ";", "}", "return", "(", "SC", ")", "this", ";", "}" ]
Registers a servlet. @param servletClass servlet class to be registered. This class must be annotated with {@linkplain WebServlet}. @return this.
[ "Registers", "a", "servlet", "." ]
train
https://github.com/agapsys/embedded-servlet-container/blob/28314a2600ad8550ed2c901d8e35d86583c26bb0/src/main/java/com/agapsys/jee/ServletContainer.java#L360-L380
forge/core
ui/api/src/main/java/org/jboss/forge/addon/ui/util/InputComponents.java
InputComponents.hasValue
public static boolean hasValue(InputComponent<?, ?> input) { """ Returns if there is a value set for this {@link InputComponent} """ boolean ret; Object value = InputComponents.getValueFor(input); if (value == null) { ret = false; } else if (value instanceof String && value.toString().isEmpty()) { ret = false; } else if (!input.getValueType().isInstance(value) && value instanceof Iterable && !((Iterable) value).iterator().hasNext()) { ret = false; } else { ret = true; } return ret; }
java
public static boolean hasValue(InputComponent<?, ?> input) { boolean ret; Object value = InputComponents.getValueFor(input); if (value == null) { ret = false; } else if (value instanceof String && value.toString().isEmpty()) { ret = false; } else if (!input.getValueType().isInstance(value) && value instanceof Iterable && !((Iterable) value).iterator().hasNext()) { ret = false; } else { ret = true; } return ret; }
[ "public", "static", "boolean", "hasValue", "(", "InputComponent", "<", "?", ",", "?", ">", "input", ")", "{", "boolean", "ret", ";", "Object", "value", "=", "InputComponents", ".", "getValueFor", "(", "input", ")", ";", "if", "(", "value", "==", "null", ")", "{", "ret", "=", "false", ";", "}", "else", "if", "(", "value", "instanceof", "String", "&&", "value", ".", "toString", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "ret", "=", "false", ";", "}", "else", "if", "(", "!", "input", ".", "getValueType", "(", ")", ".", "isInstance", "(", "value", ")", "&&", "value", "instanceof", "Iterable", "&&", "!", "(", "(", "Iterable", ")", "value", ")", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", ")", "{", "ret", "=", "false", ";", "}", "else", "{", "ret", "=", "true", ";", "}", "return", "ret", ";", "}" ]
Returns if there is a value set for this {@link InputComponent}
[ "Returns", "if", "there", "is", "a", "value", "set", "for", "this", "{" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/ui/api/src/main/java/org/jboss/forge/addon/ui/util/InputComponents.java#L295-L317
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java
PoolsImpl.disableAutoScale
public void disableAutoScale(String poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions) { """ Disables automatic scaling for a pool. @param poolId The ID of the pool on which to disable automatic scaling. @param poolDisableAutoScaleOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ disableAutoScaleWithServiceResponseAsync(poolId, poolDisableAutoScaleOptions).toBlocking().single().body(); }
java
public void disableAutoScale(String poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions) { disableAutoScaleWithServiceResponseAsync(poolId, poolDisableAutoScaleOptions).toBlocking().single().body(); }
[ "public", "void", "disableAutoScale", "(", "String", "poolId", ",", "PoolDisableAutoScaleOptions", "poolDisableAutoScaleOptions", ")", "{", "disableAutoScaleWithServiceResponseAsync", "(", "poolId", ",", "poolDisableAutoScaleOptions", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Disables automatic scaling for a pool. @param poolId The ID of the pool on which to disable automatic scaling. @param poolDisableAutoScaleOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Disables", "automatic", "scaling", "for", "a", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L2158-L2160
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/RolesInner.java
RolesInner.beginCreateOrUpdate
public RoleInner beginCreateOrUpdate(String deviceName, String name, String resourceGroupName, RoleInner role) { """ Create or update a role. @param deviceName The device name. @param name The role name. @param resourceGroupName The resource group name. @param role The role properties. @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 RoleInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, role).toBlocking().single().body(); }
java
public RoleInner beginCreateOrUpdate(String deviceName, String name, String resourceGroupName, RoleInner role) { return beginCreateOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, role).toBlocking().single().body(); }
[ "public", "RoleInner", "beginCreateOrUpdate", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ",", "RoleInner", "role", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "deviceName", ",", "name", ",", "resourceGroupName", ",", "role", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update a role. @param deviceName The device name. @param name The role name. @param resourceGroupName The resource group name. @param role The role properties. @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 RoleInner object if successful.
[ "Create", "or", "update", "a", "role", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/RolesInner.java#L406-L408
haifengl/smile
math/src/main/java/smile/math/Random.java
Random.nextDoubles
public void nextDoubles(double[] d, double lo, double hi) { """ Generate n uniform random numbers in the range [lo, hi) @param lo lower limit of range @param hi upper limit of range @param d array of random numbers to be generated """ real.nextDoubles(d); double l = hi - lo; int n = d.length; for (int i = 0; i < n; i++) { d[i] = lo + l * d[i]; } }
java
public void nextDoubles(double[] d, double lo, double hi) { real.nextDoubles(d); double l = hi - lo; int n = d.length; for (int i = 0; i < n; i++) { d[i] = lo + l * d[i]; } }
[ "public", "void", "nextDoubles", "(", "double", "[", "]", "d", ",", "double", "lo", ",", "double", "hi", ")", "{", "real", ".", "nextDoubles", "(", "d", ")", ";", "double", "l", "=", "hi", "-", "lo", ";", "int", "n", "=", "d", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "d", "[", "i", "]", "=", "lo", "+", "l", "*", "d", "[", "i", "]", ";", "}", "}" ]
Generate n uniform random numbers in the range [lo, hi) @param lo lower limit of range @param hi upper limit of range @param d array of random numbers to be generated
[ "Generate", "n", "uniform", "random", "numbers", "in", "the", "range", "[", "lo", "hi", ")" ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/Random.java#L81-L89
treelogic-swe/aws-mock
src/main/java/com/tlswe/awsmock/ec2/control/MockEC2QueryHandler.java
MockEC2QueryHandler.createSubnet
private CreateSubnetResponseType createSubnet(final String vpcId, final String cidrBlock) { """ Handles "createSubnet" request to create Subnet and returns response with a subnet. @param vpcId vpc Id for subnet. @param cidrBlock VPC cidr block. @return a CreateSubnetResponseType with our new Subnet """ CreateSubnetResponseType ret = new CreateSubnetResponseType(); ret.setRequestId(UUID.randomUUID().toString()); MockSubnet mockSubnet = mockSubnetController.createSubnet(cidrBlock, vpcId); SubnetType subnetType = new SubnetType(); subnetType.setVpcId(mockSubnet.getVpcId()); subnetType.setSubnetId(mockSubnet.getSubnetId()); ret.setSubnet(subnetType); return ret; }
java
private CreateSubnetResponseType createSubnet(final String vpcId, final String cidrBlock) { CreateSubnetResponseType ret = new CreateSubnetResponseType(); ret.setRequestId(UUID.randomUUID().toString()); MockSubnet mockSubnet = mockSubnetController.createSubnet(cidrBlock, vpcId); SubnetType subnetType = new SubnetType(); subnetType.setVpcId(mockSubnet.getVpcId()); subnetType.setSubnetId(mockSubnet.getSubnetId()); ret.setSubnet(subnetType); return ret; }
[ "private", "CreateSubnetResponseType", "createSubnet", "(", "final", "String", "vpcId", ",", "final", "String", "cidrBlock", ")", "{", "CreateSubnetResponseType", "ret", "=", "new", "CreateSubnetResponseType", "(", ")", ";", "ret", ".", "setRequestId", "(", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ")", ";", "MockSubnet", "mockSubnet", "=", "mockSubnetController", ".", "createSubnet", "(", "cidrBlock", ",", "vpcId", ")", ";", "SubnetType", "subnetType", "=", "new", "SubnetType", "(", ")", ";", "subnetType", ".", "setVpcId", "(", "mockSubnet", ".", "getVpcId", "(", ")", ")", ";", "subnetType", ".", "setSubnetId", "(", "mockSubnet", ".", "getSubnetId", "(", ")", ")", ";", "ret", ".", "setSubnet", "(", "subnetType", ")", ";", "return", "ret", ";", "}" ]
Handles "createSubnet" request to create Subnet and returns response with a subnet. @param vpcId vpc Id for subnet. @param cidrBlock VPC cidr block. @return a CreateSubnetResponseType with our new Subnet
[ "Handles", "createSubnet", "request", "to", "create", "Subnet", "and", "returns", "response", "with", "a", "subnet", "." ]
train
https://github.com/treelogic-swe/aws-mock/blob/1d1058c0ebbd0615efa28695481e36ae3ffc58a0/src/main/java/com/tlswe/awsmock/ec2/control/MockEC2QueryHandler.java#L1474-L1485
molgenis/molgenis
molgenis-core-ui/src/main/java/org/molgenis/core/ui/MolgenisInterceptor.java
MolgenisInterceptor.getEnvironmentAttributes
private Map<String, String> getEnvironmentAttributes() { """ Make sure Spring does not add the attributes as query parameters to the url when doing a redirect. You can do this by introducing an object instead of a string key value pair. <p>See <a href="https://github.com/molgenis/molgenis/issues/6515">https://github.com/molgenis/molgenis/issues/6515</a> @return environmentAttributeMap """ Map<String, String> environmentAttributes = new HashMap<>(); environmentAttributes.put(ATTRIBUTE_ENVIRONMENT_TYPE, environment); return environmentAttributes; }
java
private Map<String, String> getEnvironmentAttributes() { Map<String, String> environmentAttributes = new HashMap<>(); environmentAttributes.put(ATTRIBUTE_ENVIRONMENT_TYPE, environment); return environmentAttributes; }
[ "private", "Map", "<", "String", ",", "String", ">", "getEnvironmentAttributes", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "environmentAttributes", "=", "new", "HashMap", "<>", "(", ")", ";", "environmentAttributes", ".", "put", "(", "ATTRIBUTE_ENVIRONMENT_TYPE", ",", "environment", ")", ";", "return", "environmentAttributes", ";", "}" ]
Make sure Spring does not add the attributes as query parameters to the url when doing a redirect. You can do this by introducing an object instead of a string key value pair. <p>See <a href="https://github.com/molgenis/molgenis/issues/6515">https://github.com/molgenis/molgenis/issues/6515</a> @return environmentAttributeMap
[ "Make", "sure", "Spring", "does", "not", "add", "the", "attributes", "as", "query", "parameters", "to", "the", "url", "when", "doing", "a", "redirect", ".", "You", "can", "do", "this", "by", "introducing", "an", "object", "instead", "of", "a", "string", "key", "value", "pair", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-core-ui/src/main/java/org/molgenis/core/ui/MolgenisInterceptor.java#L92-L96
beanshell/beanshell
src/main/java/bsh/Primitive.java
Primitive.castToType
public Primitive castToType( Class<?> toType, int operation ) throws UtilEvalError { """ Cast this bsh.Primitive value to a new bsh.Primitive value This is usually a numeric type cast. Other cases include: A boolean can be cast to boolen null can be cast to any object type and remains null Attempting to cast a void causes an exception @param toType is the java object or primitive TYPE class """ return castPrimitive( toType, getType()/*fromType*/, this/*fromValue*/, false/*checkOnly*/, operation ); }
java
public Primitive castToType( Class<?> toType, int operation ) throws UtilEvalError { return castPrimitive( toType, getType()/*fromType*/, this/*fromValue*/, false/*checkOnly*/, operation ); }
[ "public", "Primitive", "castToType", "(", "Class", "<", "?", ">", "toType", ",", "int", "operation", ")", "throws", "UtilEvalError", "{", "return", "castPrimitive", "(", "toType", ",", "getType", "(", ")", "/*fromType*/", ",", "this", "/*fromValue*/", ",", "false", "/*checkOnly*/", ",", "operation", ")", ";", "}" ]
Cast this bsh.Primitive value to a new bsh.Primitive value This is usually a numeric type cast. Other cases include: A boolean can be cast to boolen null can be cast to any object type and remains null Attempting to cast a void causes an exception @param toType is the java object or primitive TYPE class
[ "Cast", "this", "bsh", ".", "Primitive", "value", "to", "a", "new", "bsh", ".", "Primitive", "value", "This", "is", "usually", "a", "numeric", "type", "cast", ".", "Other", "cases", "include", ":", "A", "boolean", "can", "be", "cast", "to", "boolen", "null", "can", "be", "cast", "to", "any", "object", "type", "and", "remains", "null", "Attempting", "to", "cast", "a", "void", "causes", "an", "exception" ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Primitive.java#L422-L428
glyptodon/guacamole-client
extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/sharing/ConnectionSharingService.java
ConnectionSharingService.retrieveSharedConnectionUser
public SharedAuthenticatedUser retrieveSharedConnectionUser( AuthenticationProvider authProvider, Credentials credentials) { """ Returns a SharedAuthenticatedUser if the given credentials contain a valid share key. The returned user will be associated with the single shared connection to which they have been granted temporary access. If the share key is invalid, or no share key is contained within the given credentials, null is returned. @param authProvider The AuthenticationProvider on behalf of which the user is being retrieved. @param credentials The credentials which are expected to contain the share key. @return A SharedAuthenticatedUser with access to a single shared connection, if the share key within the given credentials is valid, or null if the share key is invalid or absent. """ // Validate the share key String shareKey = getShareKey(credentials); if (shareKey == null || connectionMap.get(shareKey) == null) return null; // Return temporary in-memory user return new SharedAuthenticatedUser(authProvider, credentials, shareKey); }
java
public SharedAuthenticatedUser retrieveSharedConnectionUser( AuthenticationProvider authProvider, Credentials credentials) { // Validate the share key String shareKey = getShareKey(credentials); if (shareKey == null || connectionMap.get(shareKey) == null) return null; // Return temporary in-memory user return new SharedAuthenticatedUser(authProvider, credentials, shareKey); }
[ "public", "SharedAuthenticatedUser", "retrieveSharedConnectionUser", "(", "AuthenticationProvider", "authProvider", ",", "Credentials", "credentials", ")", "{", "// Validate the share key", "String", "shareKey", "=", "getShareKey", "(", "credentials", ")", ";", "if", "(", "shareKey", "==", "null", "||", "connectionMap", ".", "get", "(", "shareKey", ")", "==", "null", ")", "return", "null", ";", "// Return temporary in-memory user", "return", "new", "SharedAuthenticatedUser", "(", "authProvider", ",", "credentials", ",", "shareKey", ")", ";", "}" ]
Returns a SharedAuthenticatedUser if the given credentials contain a valid share key. The returned user will be associated with the single shared connection to which they have been granted temporary access. If the share key is invalid, or no share key is contained within the given credentials, null is returned. @param authProvider The AuthenticationProvider on behalf of which the user is being retrieved. @param credentials The credentials which are expected to contain the share key. @return A SharedAuthenticatedUser with access to a single shared connection, if the share key within the given credentials is valid, or null if the share key is invalid or absent.
[ "Returns", "a", "SharedAuthenticatedUser", "if", "the", "given", "credentials", "contain", "a", "valid", "share", "key", ".", "The", "returned", "user", "will", "be", "associated", "with", "the", "single", "shared", "connection", "to", "which", "they", "have", "been", "granted", "temporary", "access", ".", "If", "the", "share", "key", "is", "invalid", "or", "no", "share", "key", "is", "contained", "within", "the", "given", "credentials", "null", "is", "returned", "." ]
train
https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/sharing/ConnectionSharingService.java#L172-L183
apache/incubator-druid
indexing-service/src/main/java/org/apache/druid/indexing/seekablestream/SeekableStreamIndexTaskRunner.java
SeekableStreamIndexTaskRunner.authorizationCheck
private Access authorizationCheck(final HttpServletRequest req, Action action) { """ Authorizes action to be performed on this task's datasource @return authorization result """ return IndexTaskUtils.datasourceAuthorizationCheck(req, action, task.getDataSource(), authorizerMapper); }
java
private Access authorizationCheck(final HttpServletRequest req, Action action) { return IndexTaskUtils.datasourceAuthorizationCheck(req, action, task.getDataSource(), authorizerMapper); }
[ "private", "Access", "authorizationCheck", "(", "final", "HttpServletRequest", "req", ",", "Action", "action", ")", "{", "return", "IndexTaskUtils", ".", "datasourceAuthorizationCheck", "(", "req", ",", "action", ",", "task", ".", "getDataSource", "(", ")", ",", "authorizerMapper", ")", ";", "}" ]
Authorizes action to be performed on this task's datasource @return authorization result
[ "Authorizes", "action", "to", "be", "performed", "on", "this", "task", "s", "datasource" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/indexing-service/src/main/java/org/apache/druid/indexing/seekablestream/SeekableStreamIndexTaskRunner.java#L1312-L1315
BlueBrain/bluima
modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/tokenize/TokenizerME.java
TokenizerME.tokenizePos
public Span[] tokenizePos(String d) { """ Tokenizes the string. @param d The string to be tokenized. @return A span array containing individual tokens as elements. """ Span[] tokens = split(d); newTokens.clear(); tokProbs.clear(); for (int i = 0, il = tokens.length; i < il; i++) { Span s = tokens[i]; String tok = d.substring(s.getStart(), s.getEnd()); // Can't tokenize single characters if (tok.length() < 2) { newTokens.add(s); tokProbs.add(ONE); } else if (useAlphaNumericOptimization() && alphaNumeric.matcher(tok).matches()) { newTokens.add(s); tokProbs.add(ONE); } else { int start = s.getStart(); int end = s.getEnd(); final int origStart = s.getStart(); double tokenProb = 1.0; for (int j = origStart + 1; j < end; j++) { double[] probs = model.eval(cg.getContext(new ObjectIntPair(tok, j - origStart))); String best = model.getBestOutcome(probs); //System.err.println("TokenizerME: "+tok.substring(0,j-origStart)+"^"+tok.substring(j-origStart)+" "+best+" "+probs[model.getIndex(best)]); tokenProb *= probs[model.getIndex(best)]; if (best.equals(TokContextGenerator.SPLIT)) { newTokens.add(new Span(start, j)); tokProbs.add(new Double(tokenProb)); start = j; tokenProb = 1.0; } } newTokens.add(new Span(start, end)); tokProbs.add(new Double(tokenProb)); } } Span[] spans = new Span[newTokens.size()]; newTokens.toArray(spans); return spans; }
java
public Span[] tokenizePos(String d) { Span[] tokens = split(d); newTokens.clear(); tokProbs.clear(); for (int i = 0, il = tokens.length; i < il; i++) { Span s = tokens[i]; String tok = d.substring(s.getStart(), s.getEnd()); // Can't tokenize single characters if (tok.length() < 2) { newTokens.add(s); tokProbs.add(ONE); } else if (useAlphaNumericOptimization() && alphaNumeric.matcher(tok).matches()) { newTokens.add(s); tokProbs.add(ONE); } else { int start = s.getStart(); int end = s.getEnd(); final int origStart = s.getStart(); double tokenProb = 1.0; for (int j = origStart + 1; j < end; j++) { double[] probs = model.eval(cg.getContext(new ObjectIntPair(tok, j - origStart))); String best = model.getBestOutcome(probs); //System.err.println("TokenizerME: "+tok.substring(0,j-origStart)+"^"+tok.substring(j-origStart)+" "+best+" "+probs[model.getIndex(best)]); tokenProb *= probs[model.getIndex(best)]; if (best.equals(TokContextGenerator.SPLIT)) { newTokens.add(new Span(start, j)); tokProbs.add(new Double(tokenProb)); start = j; tokenProb = 1.0; } } newTokens.add(new Span(start, end)); tokProbs.add(new Double(tokenProb)); } } Span[] spans = new Span[newTokens.size()]; newTokens.toArray(spans); return spans; }
[ "public", "Span", "[", "]", "tokenizePos", "(", "String", "d", ")", "{", "Span", "[", "]", "tokens", "=", "split", "(", "d", ")", ";", "newTokens", ".", "clear", "(", ")", ";", "tokProbs", ".", "clear", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "il", "=", "tokens", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "{", "Span", "s", "=", "tokens", "[", "i", "]", ";", "String", "tok", "=", "d", ".", "substring", "(", "s", ".", "getStart", "(", ")", ",", "s", ".", "getEnd", "(", ")", ")", ";", "// Can't tokenize single characters", "if", "(", "tok", ".", "length", "(", ")", "<", "2", ")", "{", "newTokens", ".", "add", "(", "s", ")", ";", "tokProbs", ".", "add", "(", "ONE", ")", ";", "}", "else", "if", "(", "useAlphaNumericOptimization", "(", ")", "&&", "alphaNumeric", ".", "matcher", "(", "tok", ")", ".", "matches", "(", ")", ")", "{", "newTokens", ".", "add", "(", "s", ")", ";", "tokProbs", ".", "add", "(", "ONE", ")", ";", "}", "else", "{", "int", "start", "=", "s", ".", "getStart", "(", ")", ";", "int", "end", "=", "s", ".", "getEnd", "(", ")", ";", "final", "int", "origStart", "=", "s", ".", "getStart", "(", ")", ";", "double", "tokenProb", "=", "1.0", ";", "for", "(", "int", "j", "=", "origStart", "+", "1", ";", "j", "<", "end", ";", "j", "++", ")", "{", "double", "[", "]", "probs", "=", "model", ".", "eval", "(", "cg", ".", "getContext", "(", "new", "ObjectIntPair", "(", "tok", ",", "j", "-", "origStart", ")", ")", ")", ";", "String", "best", "=", "model", ".", "getBestOutcome", "(", "probs", ")", ";", "//System.err.println(\"TokenizerME: \"+tok.substring(0,j-origStart)+\"^\"+tok.substring(j-origStart)+\" \"+best+\" \"+probs[model.getIndex(best)]);", "tokenProb", "*=", "probs", "[", "model", ".", "getIndex", "(", "best", ")", "]", ";", "if", "(", "best", ".", "equals", "(", "TokContextGenerator", ".", "SPLIT", ")", ")", "{", "newTokens", ".", "add", "(", "new", "Span", "(", "start", ",", "j", ")", ")", ";", "tokProbs", ".", "add", "(", "new", "Double", "(", "tokenProb", ")", ")", ";", "start", "=", "j", ";", "tokenProb", "=", "1.0", ";", "}", "}", "newTokens", ".", "add", "(", "new", "Span", "(", "start", ",", "end", ")", ")", ";", "tokProbs", ".", "add", "(", "new", "Double", "(", "tokenProb", ")", ")", ";", "}", "}", "Span", "[", "]", "spans", "=", "new", "Span", "[", "newTokens", ".", "size", "(", ")", "]", ";", "newTokens", ".", "toArray", "(", "spans", ")", ";", "return", "spans", ";", "}" ]
Tokenizes the string. @param d The string to be tokenized. @return A span array containing individual tokens as elements.
[ "Tokenizes", "the", "string", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/tokenize/TokenizerME.java#L108-L150
yanzhenjie/AndServer
api/src/main/java/com/yanzhenjie/andserver/framework/website/FileBrowser.java
FileBrowser.findPathResource
private File findPathResource(@NonNull String httpPath) { """ Find the path specified resource. @param httpPath path. @return return if the file is found. """ if ("/".equals(httpPath)) { File root = new File(mRootPath); return root.exists() ? root : null; } else { File sourceFile = new File(mRootPath, httpPath); if (sourceFile.exists()) { return sourceFile; } } return null; }
java
private File findPathResource(@NonNull String httpPath) { if ("/".equals(httpPath)) { File root = new File(mRootPath); return root.exists() ? root : null; } else { File sourceFile = new File(mRootPath, httpPath); if (sourceFile.exists()) { return sourceFile; } } return null; }
[ "private", "File", "findPathResource", "(", "@", "NonNull", "String", "httpPath", ")", "{", "if", "(", "\"/\"", ".", "equals", "(", "httpPath", ")", ")", "{", "File", "root", "=", "new", "File", "(", "mRootPath", ")", ";", "return", "root", ".", "exists", "(", ")", "?", "root", ":", "null", ";", "}", "else", "{", "File", "sourceFile", "=", "new", "File", "(", "mRootPath", ",", "httpPath", ")", ";", "if", "(", "sourceFile", ".", "exists", "(", ")", ")", "{", "return", "sourceFile", ";", "}", "}", "return", "null", ";", "}" ]
Find the path specified resource. @param httpPath path. @return return if the file is found.
[ "Find", "the", "path", "specified", "resource", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/framework/website/FileBrowser.java#L66-L77
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/KeyPointsCircleHexagonalGrid.java
KeyPointsCircleHexagonalGrid.addTangents
private boolean addTangents(Grid grid, int rowA, int colA, int rowB, int colB) { """ Computes tangent points to the two ellipses specified by the grid coordinates """ EllipseRotated_F64 a = grid.get(rowA,colA); EllipseRotated_F64 b = grid.get(rowB,colB); if( a == null || b == null ) { return false; } if( !tangentFinder.process(a,b, A0, A1, A2, A3, B0, B1, B2, B3) ) { return false; } Tangents ta = tangents.get(grid.getIndexOfHexEllipse(rowA,colA)); Tangents tb = tangents.get(grid.getIndexOfHexEllipse(rowB,colB)); // add tangent points from the two lines which do not cross the center line ta.grow().set(A0); ta.grow().set(A3); tb.grow().set(B0); tb.grow().set(B3); return true; }
java
private boolean addTangents(Grid grid, int rowA, int colA, int rowB, int colB) { EllipseRotated_F64 a = grid.get(rowA,colA); EllipseRotated_F64 b = grid.get(rowB,colB); if( a == null || b == null ) { return false; } if( !tangentFinder.process(a,b, A0, A1, A2, A3, B0, B1, B2, B3) ) { return false; } Tangents ta = tangents.get(grid.getIndexOfHexEllipse(rowA,colA)); Tangents tb = tangents.get(grid.getIndexOfHexEllipse(rowB,colB)); // add tangent points from the two lines which do not cross the center line ta.grow().set(A0); ta.grow().set(A3); tb.grow().set(B0); tb.grow().set(B3); return true; }
[ "private", "boolean", "addTangents", "(", "Grid", "grid", ",", "int", "rowA", ",", "int", "colA", ",", "int", "rowB", ",", "int", "colB", ")", "{", "EllipseRotated_F64", "a", "=", "grid", ".", "get", "(", "rowA", ",", "colA", ")", ";", "EllipseRotated_F64", "b", "=", "grid", ".", "get", "(", "rowB", ",", "colB", ")", ";", "if", "(", "a", "==", "null", "||", "b", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "tangentFinder", ".", "process", "(", "a", ",", "b", ",", "A0", ",", "A1", ",", "A2", ",", "A3", ",", "B0", ",", "B1", ",", "B2", ",", "B3", ")", ")", "{", "return", "false", ";", "}", "Tangents", "ta", "=", "tangents", ".", "get", "(", "grid", ".", "getIndexOfHexEllipse", "(", "rowA", ",", "colA", ")", ")", ";", "Tangents", "tb", "=", "tangents", ".", "get", "(", "grid", ".", "getIndexOfHexEllipse", "(", "rowB", ",", "colB", ")", ")", ";", "// add tangent points from the two lines which do not cross the center line", "ta", ".", "grow", "(", ")", ".", "set", "(", "A0", ")", ";", "ta", ".", "grow", "(", ")", ".", "set", "(", "A3", ")", ";", "tb", ".", "grow", "(", ")", ".", "set", "(", "B0", ")", ";", "tb", ".", "grow", "(", ")", ".", "set", "(", "B3", ")", ";", "return", "true", ";", "}" ]
Computes tangent points to the two ellipses specified by the grid coordinates
[ "Computes", "tangent", "points", "to", "the", "two", "ellipses", "specified", "by", "the", "grid", "coordinates" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/KeyPointsCircleHexagonalGrid.java#L162-L183
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/format/validate/ParsedAddressGrouping.java
ParsedAddressGrouping.getNetworkSegmentIndex
public static int getNetworkSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) { """ Returns the index of the segment containing the last byte within the network prefix When networkPrefixLength is zero (so there are no segments containing bytes within the network prefix), returns -1 @param networkPrefixLength @param byteLength @return """ if(bytesPerSegment > 1) { if(bytesPerSegment == 2) { return (networkPrefixLength - 1) >> 4;//note this is intentionally a signed shift and not >>> so that networkPrefixLength of 0 returns -1 } return (networkPrefixLength - 1) / bitsPerSegment; } return (networkPrefixLength - 1) >> 3; }
java
public static int getNetworkSegmentIndex(int networkPrefixLength, int bytesPerSegment, int bitsPerSegment) { if(bytesPerSegment > 1) { if(bytesPerSegment == 2) { return (networkPrefixLength - 1) >> 4;//note this is intentionally a signed shift and not >>> so that networkPrefixLength of 0 returns -1 } return (networkPrefixLength - 1) / bitsPerSegment; } return (networkPrefixLength - 1) >> 3; }
[ "public", "static", "int", "getNetworkSegmentIndex", "(", "int", "networkPrefixLength", ",", "int", "bytesPerSegment", ",", "int", "bitsPerSegment", ")", "{", "if", "(", "bytesPerSegment", ">", "1", ")", "{", "if", "(", "bytesPerSegment", "==", "2", ")", "{", "return", "(", "networkPrefixLength", "-", "1", ")", ">>", "4", ";", "//note this is intentionally a signed shift and not >>> so that networkPrefixLength of 0 returns -1", "}", "return", "(", "networkPrefixLength", "-", "1", ")", "/", "bitsPerSegment", ";", "}", "return", "(", "networkPrefixLength", "-", "1", ")", ">>", "3", ";", "}" ]
Returns the index of the segment containing the last byte within the network prefix When networkPrefixLength is zero (so there are no segments containing bytes within the network prefix), returns -1 @param networkPrefixLength @param byteLength @return
[ "Returns", "the", "index", "of", "the", "segment", "containing", "the", "last", "byte", "within", "the", "network", "prefix", "When", "networkPrefixLength", "is", "zero", "(", "so", "there", "are", "no", "segments", "containing", "bytes", "within", "the", "network", "prefix", ")", "returns", "-", "1" ]
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/format/validate/ParsedAddressGrouping.java#L34-L42
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.isMethodCall
public static boolean isMethodCall(Statement stmt, String methodObject, String methodName, int numArguments) { """ Return true only if the Statement represents a method call for the specified method object (receiver), method name, and with the specified number of arguments. @param stmt - the AST Statement @param methodObject - the name of the method object (receiver) @param methodName - the name of the method being called @param numArguments - the number of arguments passed into the method @return true only if the Statement is a method call matching the specified criteria """ if (stmt instanceof ExpressionStatement) { Expression expression = ((ExpressionStatement) stmt).getExpression(); if (expression instanceof MethodCallExpression) { return isMethodCall(expression, methodObject, methodName, numArguments); } } return false; }
java
public static boolean isMethodCall(Statement stmt, String methodObject, String methodName, int numArguments) { if (stmt instanceof ExpressionStatement) { Expression expression = ((ExpressionStatement) stmt).getExpression(); if (expression instanceof MethodCallExpression) { return isMethodCall(expression, methodObject, methodName, numArguments); } } return false; }
[ "public", "static", "boolean", "isMethodCall", "(", "Statement", "stmt", ",", "String", "methodObject", ",", "String", "methodName", ",", "int", "numArguments", ")", "{", "if", "(", "stmt", "instanceof", "ExpressionStatement", ")", "{", "Expression", "expression", "=", "(", "(", "ExpressionStatement", ")", "stmt", ")", ".", "getExpression", "(", ")", ";", "if", "(", "expression", "instanceof", "MethodCallExpression", ")", "{", "return", "isMethodCall", "(", "expression", ",", "methodObject", ",", "methodName", ",", "numArguments", ")", ";", "}", "}", "return", "false", ";", "}" ]
Return true only if the Statement represents a method call for the specified method object (receiver), method name, and with the specified number of arguments. @param stmt - the AST Statement @param methodObject - the name of the method object (receiver) @param methodName - the name of the method being called @param numArguments - the number of arguments passed into the method @return true only if the Statement is a method call matching the specified criteria
[ "Return", "true", "only", "if", "the", "Statement", "represents", "a", "method", "call", "for", "the", "specified", "method", "object", "(", "receiver", ")", "method", "name", "and", "with", "the", "specified", "number", "of", "arguments", "." ]
train
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L292-L300
google/gson
gson/src/main/java/com/google/gson/Gson.java
Gson.fromJson
@SuppressWarnings("unchecked") public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException { """ Reads the next JSON value from {@code reader} and convert it to an object of type {@code typeOfT}. Returns {@code null}, if the {@code reader} is at EOF. Since Type is not parameterized by T, this method is type unsafe and should be used carefully @throws JsonIOException if there was a problem writing to the Reader @throws JsonSyntaxException if json is not a valid representation for an object of type """ boolean isEmpty = true; boolean oldLenient = reader.isLenient(); reader.setLenient(true); try { reader.peek(); isEmpty = false; TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT); TypeAdapter<T> typeAdapter = getAdapter(typeToken); T object = typeAdapter.read(reader); return object; } catch (EOFException e) { /* * For compatibility with JSON 1.5 and earlier, we return null for empty * documents instead of throwing. */ if (isEmpty) { return null; } throw new JsonSyntaxException(e); } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IOException e) { // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException throw new JsonSyntaxException(e); } catch (AssertionError e) { AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage()); error.initCause(e); throw error; } finally { reader.setLenient(oldLenient); } }
java
@SuppressWarnings("unchecked") public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException { boolean isEmpty = true; boolean oldLenient = reader.isLenient(); reader.setLenient(true); try { reader.peek(); isEmpty = false; TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT); TypeAdapter<T> typeAdapter = getAdapter(typeToken); T object = typeAdapter.read(reader); return object; } catch (EOFException e) { /* * For compatibility with JSON 1.5 and earlier, we return null for empty * documents instead of throwing. */ if (isEmpty) { return null; } throw new JsonSyntaxException(e); } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IOException e) { // TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException throw new JsonSyntaxException(e); } catch (AssertionError e) { AssertionError error = new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage()); error.initCause(e); throw error; } finally { reader.setLenient(oldLenient); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "fromJson", "(", "JsonReader", "reader", ",", "Type", "typeOfT", ")", "throws", "JsonIOException", ",", "JsonSyntaxException", "{", "boolean", "isEmpty", "=", "true", ";", "boolean", "oldLenient", "=", "reader", ".", "isLenient", "(", ")", ";", "reader", ".", "setLenient", "(", "true", ")", ";", "try", "{", "reader", ".", "peek", "(", ")", ";", "isEmpty", "=", "false", ";", "TypeToken", "<", "T", ">", "typeToken", "=", "(", "TypeToken", "<", "T", ">", ")", "TypeToken", ".", "get", "(", "typeOfT", ")", ";", "TypeAdapter", "<", "T", ">", "typeAdapter", "=", "getAdapter", "(", "typeToken", ")", ";", "T", "object", "=", "typeAdapter", ".", "read", "(", "reader", ")", ";", "return", "object", ";", "}", "catch", "(", "EOFException", "e", ")", "{", "/*\n * For compatibility with JSON 1.5 and earlier, we return null for empty\n * documents instead of throwing.\n */", "if", "(", "isEmpty", ")", "{", "return", "null", ";", "}", "throw", "new", "JsonSyntaxException", "(", "e", ")", ";", "}", "catch", "(", "IllegalStateException", "e", ")", "{", "throw", "new", "JsonSyntaxException", "(", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException", "throw", "new", "JsonSyntaxException", "(", "e", ")", ";", "}", "catch", "(", "AssertionError", "e", ")", "{", "AssertionError", "error", "=", "new", "AssertionError", "(", "\"AssertionError (GSON \"", "+", "GsonBuildConfig", ".", "VERSION", "+", "\"): \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "error", ".", "initCause", "(", "e", ")", ";", "throw", "error", ";", "}", "finally", "{", "reader", ".", "setLenient", "(", "oldLenient", ")", ";", "}", "}" ]
Reads the next JSON value from {@code reader} and convert it to an object of type {@code typeOfT}. Returns {@code null}, if the {@code reader} is at EOF. Since Type is not parameterized by T, this method is type unsafe and should be used carefully @throws JsonIOException if there was a problem writing to the Reader @throws JsonSyntaxException if json is not a valid representation for an object of type
[ "Reads", "the", "next", "JSON", "value", "from", "{", "@code", "reader", "}", "and", "convert", "it", "to", "an", "object", "of", "type", "{", "@code", "typeOfT", "}", ".", "Returns", "{", "@code", "null", "}", "if", "the", "{", "@code", "reader", "}", "is", "at", "EOF", ".", "Since", "Type", "is", "not", "parameterized", "by", "T", "this", "method", "is", "type", "unsafe", "and", "should", "be", "used", "carefully" ]
train
https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/Gson.java#L922-L955
liferay/com-liferay-commerce
commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java
CommerceDiscountRelPersistenceImpl.countByCN_CPK
@Override public int countByCN_CPK(long classNameId, long classPK) { """ Returns the number of commerce discount rels where classNameId = &#63; and classPK = &#63;. @param classNameId the class name ID @param classPK the class pk @return the number of matching commerce discount rels """ FinderPath finderPath = FINDER_PATH_COUNT_BY_CN_CPK; Object[] finderArgs = new Object[] { classNameId, classPK }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_COMMERCEDISCOUNTREL_WHERE); query.append(_FINDER_COLUMN_CN_CPK_CLASSNAMEID_2); query.append(_FINDER_COLUMN_CN_CPK_CLASSPK_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(classNameId); qPos.add(classPK); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
java
@Override public int countByCN_CPK(long classNameId, long classPK) { FinderPath finderPath = FINDER_PATH_COUNT_BY_CN_CPK; Object[] finderArgs = new Object[] { classNameId, classPK }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_COMMERCEDISCOUNTREL_WHERE); query.append(_FINDER_COLUMN_CN_CPK_CLASSNAMEID_2); query.append(_FINDER_COLUMN_CN_CPK_CLASSPK_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(classNameId); qPos.add(classPK); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
[ "@", "Override", "public", "int", "countByCN_CPK", "(", "long", "classNameId", ",", "long", "classPK", ")", "{", "FinderPath", "finderPath", "=", "FINDER_PATH_COUNT_BY_CN_CPK", ";", "Object", "[", "]", "finderArgs", "=", "new", "Object", "[", "]", "{", "classNameId", ",", "classPK", "}", ";", "Long", "count", "=", "(", "Long", ")", "finderCache", ".", "getResult", "(", "finderPath", ",", "finderArgs", ",", "this", ")", ";", "if", "(", "count", "==", "null", ")", "{", "StringBundler", "query", "=", "new", "StringBundler", "(", "3", ")", ";", "query", ".", "append", "(", "_SQL_COUNT_COMMERCEDISCOUNTREL_WHERE", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_CN_CPK_CLASSNAMEID_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_CN_CPK_CLASSPK_2", ")", ";", "String", "sql", "=", "query", ".", "toString", "(", ")", ";", "Session", "session", "=", "null", ";", "try", "{", "session", "=", "openSession", "(", ")", ";", "Query", "q", "=", "session", ".", "createQuery", "(", "sql", ")", ";", "QueryPos", "qPos", "=", "QueryPos", ".", "getInstance", "(", "q", ")", ";", "qPos", ".", "add", "(", "classNameId", ")", ";", "qPos", ".", "add", "(", "classPK", ")", ";", "count", "=", "(", "Long", ")", "q", ".", "uniqueResult", "(", ")", ";", "finderCache", ".", "putResult", "(", "finderPath", ",", "finderArgs", ",", "count", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "finderCache", ".", "removeResult", "(", "finderPath", ",", "finderArgs", ")", ";", "throw", "processException", "(", "e", ")", ";", "}", "finally", "{", "closeSession", "(", "session", ")", ";", "}", "}", "return", "count", ".", "intValue", "(", ")", ";", "}" ]
Returns the number of commerce discount rels where classNameId = &#63; and classPK = &#63;. @param classNameId the class name ID @param classPK the class pk @return the number of matching commerce discount rels
[ "Returns", "the", "number", "of", "commerce", "discount", "rels", "where", "classNameId", "=", "&#63", ";", "and", "classPK", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java#L1673-L1720
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/ZooKeeperUtils.java
ZooKeeperUtils.createLeaderRetrievalService
public static ZooKeeperLeaderRetrievalService createLeaderRetrievalService( final CuratorFramework client, final Configuration configuration, final String pathSuffix) { """ Creates a {@link ZooKeeperLeaderRetrievalService} instance. @param client The {@link CuratorFramework} ZooKeeper client to use @param configuration {@link Configuration} object containing the configuration values @param pathSuffix The path suffix which we want to append @return {@link ZooKeeperLeaderRetrievalService} instance. @throws Exception """ String leaderPath = configuration.getString( HighAvailabilityOptions.HA_ZOOKEEPER_LEADER_PATH) + pathSuffix; return new ZooKeeperLeaderRetrievalService(client, leaderPath); }
java
public static ZooKeeperLeaderRetrievalService createLeaderRetrievalService( final CuratorFramework client, final Configuration configuration, final String pathSuffix) { String leaderPath = configuration.getString( HighAvailabilityOptions.HA_ZOOKEEPER_LEADER_PATH) + pathSuffix; return new ZooKeeperLeaderRetrievalService(client, leaderPath); }
[ "public", "static", "ZooKeeperLeaderRetrievalService", "createLeaderRetrievalService", "(", "final", "CuratorFramework", "client", ",", "final", "Configuration", "configuration", ",", "final", "String", "pathSuffix", ")", "{", "String", "leaderPath", "=", "configuration", ".", "getString", "(", "HighAvailabilityOptions", ".", "HA_ZOOKEEPER_LEADER_PATH", ")", "+", "pathSuffix", ";", "return", "new", "ZooKeeperLeaderRetrievalService", "(", "client", ",", "leaderPath", ")", ";", "}" ]
Creates a {@link ZooKeeperLeaderRetrievalService} instance. @param client The {@link CuratorFramework} ZooKeeper client to use @param configuration {@link Configuration} object containing the configuration values @param pathSuffix The path suffix which we want to append @return {@link ZooKeeperLeaderRetrievalService} instance. @throws Exception
[ "Creates", "a", "{", "@link", "ZooKeeperLeaderRetrievalService", "}", "instance", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/util/ZooKeeperUtils.java#L185-L193
Azure/azure-sdk-for-java
common/azure-common-mgmt/src/main/java/com/azure/common/mgmt/AzureProxy.java
AzureProxy.createDefaultPipeline
public static HttpPipeline createDefaultPipeline(Class<?> swaggerInterface, AsyncServiceClientCredentials credentials) { """ Create the default HttpPipeline. @param swaggerInterface The interface that the pipeline will use to generate a user-agent string. @param credentials The credentials to use to apply authentication to the pipeline. @return the default HttpPipeline. """ return createDefaultPipeline(swaggerInterface, new AsyncCredentialsPolicy(credentials)); }
java
public static HttpPipeline createDefaultPipeline(Class<?> swaggerInterface, AsyncServiceClientCredentials credentials) { return createDefaultPipeline(swaggerInterface, new AsyncCredentialsPolicy(credentials)); }
[ "public", "static", "HttpPipeline", "createDefaultPipeline", "(", "Class", "<", "?", ">", "swaggerInterface", ",", "AsyncServiceClientCredentials", "credentials", ")", "{", "return", "createDefaultPipeline", "(", "swaggerInterface", ",", "new", "AsyncCredentialsPolicy", "(", "credentials", ")", ")", ";", "}" ]
Create the default HttpPipeline. @param swaggerInterface The interface that the pipeline will use to generate a user-agent string. @param credentials The credentials to use to apply authentication to the pipeline. @return the default HttpPipeline.
[ "Create", "the", "default", "HttpPipeline", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common-mgmt/src/main/java/com/azure/common/mgmt/AzureProxy.java#L180-L182
VoltDB/voltdb
src/frontend/org/voltdb/types/GeographyValue.java
GeographyValue.diagnoseLoop
private static <T> void diagnoseLoop(List<T> loop, String excpMsgPrf) throws IllegalArgumentException { """ A helper function to validate the loop structure If loop is invalid, it generates IllegalArgumentException exception """ if (loop == null) { throw new IllegalArgumentException(excpMsgPrf + "a polygon must contain at least one ring " + "(with each ring at least 4 points, including repeated closing vertex)"); } // 4 vertices = 3 unique vertices for polygon + 1 end point which is same as start point if (loop.size() < 4) { throw new IllegalArgumentException(excpMsgPrf + "a polygon ring must contain at least 4 points " + "(including repeated closing vertex)"); } // check if the end points of the loop are equal if (loop.get(0).equals(loop.get(loop.size() - 1)) == false) { throw new IllegalArgumentException(excpMsgPrf + "closing points of ring are not equal: \"" + loop.get(0).toString() + "\" != \"" + loop.get(loop.size()-1).toString() + "\""); } }
java
private static <T> void diagnoseLoop(List<T> loop, String excpMsgPrf) throws IllegalArgumentException { if (loop == null) { throw new IllegalArgumentException(excpMsgPrf + "a polygon must contain at least one ring " + "(with each ring at least 4 points, including repeated closing vertex)"); } // 4 vertices = 3 unique vertices for polygon + 1 end point which is same as start point if (loop.size() < 4) { throw new IllegalArgumentException(excpMsgPrf + "a polygon ring must contain at least 4 points " + "(including repeated closing vertex)"); } // check if the end points of the loop are equal if (loop.get(0).equals(loop.get(loop.size() - 1)) == false) { throw new IllegalArgumentException(excpMsgPrf + "closing points of ring are not equal: \"" + loop.get(0).toString() + "\" != \"" + loop.get(loop.size()-1).toString() + "\""); } }
[ "private", "static", "<", "T", ">", "void", "diagnoseLoop", "(", "List", "<", "T", ">", "loop", ",", "String", "excpMsgPrf", ")", "throws", "IllegalArgumentException", "{", "if", "(", "loop", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "excpMsgPrf", "+", "\"a polygon must contain at least one ring \"", "+", "\"(with each ring at least 4 points, including repeated closing vertex)\"", ")", ";", "}", "// 4 vertices = 3 unique vertices for polygon + 1 end point which is same as start point", "if", "(", "loop", ".", "size", "(", ")", "<", "4", ")", "{", "throw", "new", "IllegalArgumentException", "(", "excpMsgPrf", "+", "\"a polygon ring must contain at least 4 points \"", "+", "\"(including repeated closing vertex)\"", ")", ";", "}", "// check if the end points of the loop are equal", "if", "(", "loop", ".", "get", "(", "0", ")", ".", "equals", "(", "loop", ".", "get", "(", "loop", ".", "size", "(", ")", "-", "1", ")", ")", "==", "false", ")", "{", "throw", "new", "IllegalArgumentException", "(", "excpMsgPrf", "+", "\"closing points of ring are not equal: \\\"\"", "+", "loop", ".", "get", "(", "0", ")", ".", "toString", "(", ")", "+", "\"\\\" != \\\"\"", "+", "loop", ".", "get", "(", "loop", ".", "size", "(", ")", "-", "1", ")", ".", "toString", "(", ")", "+", "\"\\\"\"", ")", ";", "}", "}" ]
A helper function to validate the loop structure If loop is invalid, it generates IllegalArgumentException exception
[ "A", "helper", "function", "to", "validate", "the", "loop", "structure", "If", "loop", "is", "invalid", "it", "generates", "IllegalArgumentException", "exception" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/types/GeographyValue.java#L636-L657
landawn/AbacusUtil
src/com/landawn/abacus/util/Maps.java
Maps.removeEntries
public static boolean removeEntries(final Map<?, ?> map, final Map<?, ?> entriesToRemove) { """ The the entries from the specified <code>Map</code> @param map @param entriesToRemove @return <code>true</code> if any key/value was removed, otherwise <code>false</code>. """ if (N.isNullOrEmpty(map) || N.isNullOrEmpty(entriesToRemove)) { return false; } final int originalSize = map.size(); for (Map.Entry<?, ?> entry : entriesToRemove.entrySet()) { if (N.equals(map.get(entry.getKey()), entry.getValue())) { map.remove(entry.getKey()); } } return map.size() < originalSize; }
java
public static boolean removeEntries(final Map<?, ?> map, final Map<?, ?> entriesToRemove) { if (N.isNullOrEmpty(map) || N.isNullOrEmpty(entriesToRemove)) { return false; } final int originalSize = map.size(); for (Map.Entry<?, ?> entry : entriesToRemove.entrySet()) { if (N.equals(map.get(entry.getKey()), entry.getValue())) { map.remove(entry.getKey()); } } return map.size() < originalSize; }
[ "public", "static", "boolean", "removeEntries", "(", "final", "Map", "<", "?", ",", "?", ">", "map", ",", "final", "Map", "<", "?", ",", "?", ">", "entriesToRemove", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "map", ")", "||", "N", ".", "isNullOrEmpty", "(", "entriesToRemove", ")", ")", "{", "return", "false", ";", "}", "final", "int", "originalSize", "=", "map", ".", "size", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "?", ",", "?", ">", "entry", ":", "entriesToRemove", ".", "entrySet", "(", ")", ")", "{", "if", "(", "N", ".", "equals", "(", "map", ".", "get", "(", "entry", ".", "getKey", "(", ")", ")", ",", "entry", ".", "getValue", "(", ")", ")", ")", "{", "map", ".", "remove", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "return", "map", ".", "size", "(", ")", "<", "originalSize", ";", "}" ]
The the entries from the specified <code>Map</code> @param map @param entriesToRemove @return <code>true</code> if any key/value was removed, otherwise <code>false</code>.
[ "The", "the", "entries", "from", "the", "specified", "<code", ">", "Map<", "/", "code", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Maps.java#L575-L589
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_easyPabx_serviceName_hunting_tones_toneUpload_POST
public OvhTask billingAccount_easyPabx_serviceName_hunting_tones_toneUpload_POST(String billingAccount, String serviceName, String documentId, OvhTonesTypeEnum type, String url) throws IOException { """ Upload new tone file REST: POST /telephony/{billingAccount}/easyPabx/{serviceName}/hunting/tones/toneUpload @param url [required] URL of the file you want to import (instead of /me/document ID) @param documentId [required] ID of the /me/document file you want to import @param type [required] @param billingAccount [required] The name of your billingAccount @param serviceName [required] """ String qPath = "/telephony/{billingAccount}/easyPabx/{serviceName}/hunting/tones/toneUpload"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "documentId", documentId); addBody(o, "type", type); addBody(o, "url", url); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask billingAccount_easyPabx_serviceName_hunting_tones_toneUpload_POST(String billingAccount, String serviceName, String documentId, OvhTonesTypeEnum type, String url) throws IOException { String qPath = "/telephony/{billingAccount}/easyPabx/{serviceName}/hunting/tones/toneUpload"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "documentId", documentId); addBody(o, "type", type); addBody(o, "url", url); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "billingAccount_easyPabx_serviceName_hunting_tones_toneUpload_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "documentId", ",", "OvhTonesTypeEnum", "type", ",", "String", "url", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/easyPabx/{serviceName}/hunting/tones/toneUpload\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"documentId\"", ",", "documentId", ")", ";", "addBody", "(", "o", ",", "\"type\"", ",", "type", ")", ";", "addBody", "(", "o", ",", "\"url\"", ",", "url", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Upload new tone file REST: POST /telephony/{billingAccount}/easyPabx/{serviceName}/hunting/tones/toneUpload @param url [required] URL of the file you want to import (instead of /me/document ID) @param documentId [required] ID of the /me/document file you want to import @param type [required] @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Upload", "new", "tone", "file" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3616-L3625
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsChtype.java
CmsChtype.actionChtype
public void actionChtype() throws JspException { """ Uploads the specified file and replaces the VFS file.<p> @throws JspException if inclusion of error dialog fails """ int plainId; try { plainId = OpenCms.getResourceManager().getResourceType( CmsResourceTypePlain.getStaticTypeName()).getTypeId(); } catch (CmsLoaderException e) { // this should really never happen plainId = CmsResourceTypePlain.getStaticTypeId(); } try { int newType = plainId; try { // get new resource type id from request newType = Integer.parseInt(getParamSelectedType()); } catch (NumberFormatException nf) { throw new CmsException(Messages.get().container(Messages.ERR_GET_RESTYPE_1, getParamSelectedType())); } // check the resource lock state checkLock(getParamResource()); // change the resource type getCms().chtype(getParamResource(), newType); // close the dialog window actionCloseDialog(); } catch (Throwable e) { // error changing resource type, show error dialog includeErrorpage(this, e); } }
java
public void actionChtype() throws JspException { int plainId; try { plainId = OpenCms.getResourceManager().getResourceType( CmsResourceTypePlain.getStaticTypeName()).getTypeId(); } catch (CmsLoaderException e) { // this should really never happen plainId = CmsResourceTypePlain.getStaticTypeId(); } try { int newType = plainId; try { // get new resource type id from request newType = Integer.parseInt(getParamSelectedType()); } catch (NumberFormatException nf) { throw new CmsException(Messages.get().container(Messages.ERR_GET_RESTYPE_1, getParamSelectedType())); } // check the resource lock state checkLock(getParamResource()); // change the resource type getCms().chtype(getParamResource(), newType); // close the dialog window actionCloseDialog(); } catch (Throwable e) { // error changing resource type, show error dialog includeErrorpage(this, e); } }
[ "public", "void", "actionChtype", "(", ")", "throws", "JspException", "{", "int", "plainId", ";", "try", "{", "plainId", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "CmsResourceTypePlain", ".", "getStaticTypeName", "(", ")", ")", ".", "getTypeId", "(", ")", ";", "}", "catch", "(", "CmsLoaderException", "e", ")", "{", "// this should really never happen", "plainId", "=", "CmsResourceTypePlain", ".", "getStaticTypeId", "(", ")", ";", "}", "try", "{", "int", "newType", "=", "plainId", ";", "try", "{", "// get new resource type id from request", "newType", "=", "Integer", ".", "parseInt", "(", "getParamSelectedType", "(", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "nf", ")", "{", "throw", "new", "CmsException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_GET_RESTYPE_1", ",", "getParamSelectedType", "(", ")", ")", ")", ";", "}", "// check the resource lock state", "checkLock", "(", "getParamResource", "(", ")", ")", ";", "// change the resource type", "getCms", "(", ")", ".", "chtype", "(", "getParamResource", "(", ")", ",", "newType", ")", ";", "// close the dialog window", "actionCloseDialog", "(", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "// error changing resource type, show error dialog", "includeErrorpage", "(", "this", ",", "e", ")", ";", "}", "}" ]
Uploads the specified file and replaces the VFS file.<p> @throws JspException if inclusion of error dialog fails
[ "Uploads", "the", "specified", "file", "and", "replaces", "the", "VFS", "file", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsChtype.java#L126-L154
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/tools/manipulator/AtomContainerManipulator.java
AtomContainerManipulator.countExplicitHydrogens
public static int countExplicitHydrogens(IAtomContainer atomContainer, IAtom atom) { """ Count explicit hydrogens. @param atomContainer the atom container to consider @return The number of explicit hydrogens on the given IAtom. @throws IllegalArgumentException if either the container or atom were null """ if (atomContainer == null || atom == null) throw new IllegalArgumentException("null container or atom provided"); int hCount = 0; for (IAtom connected : atomContainer.getConnectedAtomsList(atom)) { if (Elements.HYDROGEN.getSymbol().equals(connected.getSymbol())) { hCount++; } } return hCount; }
java
public static int countExplicitHydrogens(IAtomContainer atomContainer, IAtom atom) { if (atomContainer == null || atom == null) throw new IllegalArgumentException("null container or atom provided"); int hCount = 0; for (IAtom connected : atomContainer.getConnectedAtomsList(atom)) { if (Elements.HYDROGEN.getSymbol().equals(connected.getSymbol())) { hCount++; } } return hCount; }
[ "public", "static", "int", "countExplicitHydrogens", "(", "IAtomContainer", "atomContainer", ",", "IAtom", "atom", ")", "{", "if", "(", "atomContainer", "==", "null", "||", "atom", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"null container or atom provided\"", ")", ";", "int", "hCount", "=", "0", ";", "for", "(", "IAtom", "connected", ":", "atomContainer", ".", "getConnectedAtomsList", "(", "atom", ")", ")", "{", "if", "(", "Elements", ".", "HYDROGEN", ".", "getSymbol", "(", ")", ".", "equals", "(", "connected", ".", "getSymbol", "(", ")", ")", ")", "{", "hCount", "++", ";", "}", "}", "return", "hCount", ";", "}" ]
Count explicit hydrogens. @param atomContainer the atom container to consider @return The number of explicit hydrogens on the given IAtom. @throws IllegalArgumentException if either the container or atom were null
[ "Count", "explicit", "hydrogens", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/tools/manipulator/AtomContainerManipulator.java#L587-L597
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/geo/GeoInterface.java
GeoInterface.setLocation
public void setLocation(String photoId, GeoData location) throws FlickrException { """ Sets the geo data (latitude and longitude and, optionally, the accuracy level) for a photo. Before users may assign location data to a photo they must define who, by default, may view that information. Users can edit this preference at <a href="http://www.flickr.com/account/geo/privacy/">flickr</a>. If a user has not set this preference, the API method will return an error. This method requires authentication with 'write' permission. @param photoId The id of the photo to cet permissions for. @param location geo data with optional accuracy (1-16), accuracy 0 to use the default. @throws FlickrException """ Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_LOCATION); parameters.put("photo_id", photoId); parameters.put("lat", String.valueOf(location.getLatitude())); parameters.put("lon", String.valueOf(location.getLongitude())); int accuracy = location.getAccuracy(); if (accuracy > 0) { parameters.put("accuracy", String.valueOf(location.getAccuracy())); } // Note: This method requires an HTTP POST request. Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); // This method has no specific response - It returns an empty sucess response // if it completes without error. if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void setLocation(String photoId, GeoData location) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_LOCATION); parameters.put("photo_id", photoId); parameters.put("lat", String.valueOf(location.getLatitude())); parameters.put("lon", String.valueOf(location.getLongitude())); int accuracy = location.getAccuracy(); if (accuracy > 0) { parameters.put("accuracy", String.valueOf(location.getAccuracy())); } // Note: This method requires an HTTP POST request. Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); // This method has no specific response - It returns an empty sucess response // if it completes without error. if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "setLocation", "(", "String", "photoId", ",", "GeoData", "location", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_SET_LOCATION", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "parameters", ".", "put", "(", "\"lat\"", ",", "String", ".", "valueOf", "(", "location", ".", "getLatitude", "(", ")", ")", ")", ";", "parameters", ".", "put", "(", "\"lon\"", ",", "String", ".", "valueOf", "(", "location", ".", "getLongitude", "(", ")", ")", ")", ";", "int", "accuracy", "=", "location", ".", "getAccuracy", "(", ")", ";", "if", "(", "accuracy", ">", "0", ")", "{", "parameters", ".", "put", "(", "\"accuracy\"", ",", "String", ".", "valueOf", "(", "location", ".", "getAccuracy", "(", ")", ")", ")", ";", "}", "// Note: This method requires an HTTP POST request.\r", "Response", "response", "=", "transport", ".", "post", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "// This method has no specific response - It returns an empty sucess response\r", "// if it completes without error.\r", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Sets the geo data (latitude and longitude and, optionally, the accuracy level) for a photo. Before users may assign location data to a photo they must define who, by default, may view that information. Users can edit this preference at <a href="http://www.flickr.com/account/geo/privacy/">flickr</a>. If a user has not set this preference, the API method will return an error. This method requires authentication with 'write' permission. @param photoId The id of the photo to cet permissions for. @param location geo data with optional accuracy (1-16), accuracy 0 to use the default. @throws FlickrException
[ "Sets", "the", "geo", "data", "(", "latitude", "and", "longitude", "and", "optionally", "the", "accuracy", "level", ")", "for", "a", "photo", ".", "Before", "users", "may", "assign", "location", "data", "to", "a", "photo", "they", "must", "define", "who", "by", "default", "may", "view", "that", "information", ".", "Users", "can", "edit", "this", "preference", "at", "<a", "href", "=", "http", ":", "//", "www", ".", "flickr", ".", "com", "/", "account", "/", "geo", "/", "privacy", "/", ">", "flickr<", "/", "a", ">", ".", "If", "a", "user", "has", "not", "set", "this", "preference", "the", "API", "method", "will", "return", "an", "error", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/geo/GeoInterface.java#L162-L181
UrielCh/ovh-java-sdk
ovh-java-sdk-vrack/src/main/java/net/minidev/ovh/api/ApiOvhVrack.java
ApiOvhVrack.serviceName_ipLoadbalancing_ipLoadbalancing_GET
public OvhIplb serviceName_ipLoadbalancing_ipLoadbalancing_GET(String serviceName, String ipLoadbalancing) throws IOException { """ Get this object properties REST: GET /vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing} @param serviceName [required] The internal name of your vrack @param ipLoadbalancing [required] Your ipLoadbalancing API beta """ String qPath = "/vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing}"; StringBuilder sb = path(qPath, serviceName, ipLoadbalancing); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhIplb.class); }
java
public OvhIplb serviceName_ipLoadbalancing_ipLoadbalancing_GET(String serviceName, String ipLoadbalancing) throws IOException { String qPath = "/vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing}"; StringBuilder sb = path(qPath, serviceName, ipLoadbalancing); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhIplb.class); }
[ "public", "OvhIplb", "serviceName_ipLoadbalancing_ipLoadbalancing_GET", "(", "String", "serviceName", ",", "String", "ipLoadbalancing", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "ipLoadbalancing", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhIplb", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /vrack/{serviceName}/ipLoadbalancing/{ipLoadbalancing} @param serviceName [required] The internal name of your vrack @param ipLoadbalancing [required] Your ipLoadbalancing API beta
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vrack/src/main/java/net/minidev/ovh/api/ApiOvhVrack.java#L60-L65
eclipse/xtext-core
org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IndentationAwareCompletionPrefixProvider.java
IndentationAwareCompletionPrefixProvider.getInputToParse
@Override public String getInputToParse(String completeInput, int offset, int completionOffset) { """ Returns the input to parse including the whitespace left to the cursor position since it may be relevant to the list of proposals for whitespace sensitive languages. """ int fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset)); return super.getInputToParse(completeInput, fixedOffset, completionOffset); }
java
@Override public String getInputToParse(String completeInput, int offset, int completionOffset) { int fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset)); return super.getInputToParse(completeInput, fixedOffset, completionOffset); }
[ "@", "Override", "public", "String", "getInputToParse", "(", "String", "completeInput", ",", "int", "offset", ",", "int", "completionOffset", ")", "{", "int", "fixedOffset", "=", "getOffsetIncludingWhitespace", "(", "completeInput", ",", "offset", ",", "Math", ".", "min", "(", "completeInput", ".", "length", "(", ")", ",", "completionOffset", ")", ")", ";", "return", "super", ".", "getInputToParse", "(", "completeInput", ",", "fixedOffset", ",", "completionOffset", ")", ";", "}" ]
Returns the input to parse including the whitespace left to the cursor position since it may be relevant to the list of proposals for whitespace sensitive languages.
[ "Returns", "the", "input", "to", "parse", "including", "the", "whitespace", "left", "to", "the", "cursor", "position", "since", "it", "may", "be", "relevant", "to", "the", "list", "of", "proposals", "for", "whitespace", "sensitive", "languages", "." ]
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IndentationAwareCompletionPrefixProvider.java#L41-L45
sebastiangraf/jSCSI
bundles/target/src/main/java/org/jscsi/target/storage/RandomAccessStorageModule.java
RandomAccessStorageModule.open
public static synchronized final IStorageModule open (final File file, final long storageLength, final boolean create, Class<? extends IStorageModule> kind) throws IOException { """ This is the build method for creating instances of {@link RandomAccessStorageModule}. If there is no file to be found at the specified <code>filePath</code>, then a {@link FileNotFoundException} will be thrown. @param file a path leading to the file serving as storage medium @param storageLength length of storage (if not already existing) @param create should the storage be created @return a new instance of {@link RandomAccessStorageModule} @throws IOException """ long sizeInBlocks; sizeInBlocks = storageLength / VIRTUAL_BLOCK_SIZE; if (create && !kind.equals(JCloudsStorageModule.class)) { createStorageVolume(file, storageLength); } // throws exc. if !file.exists() @SuppressWarnings ("unchecked") Constructor<? extends IStorageModule> cons = (Constructor<? extends IStorageModule>) kind.getConstructors()[0]; try { IStorageModule mod = cons.newInstance(sizeInBlocks, file); return mod; } catch (InvocationTargetException | IllegalAccessException | InstantiationException exc) { throw new IOException(exc); } }
java
public static synchronized final IStorageModule open (final File file, final long storageLength, final boolean create, Class<? extends IStorageModule> kind) throws IOException { long sizeInBlocks; sizeInBlocks = storageLength / VIRTUAL_BLOCK_SIZE; if (create && !kind.equals(JCloudsStorageModule.class)) { createStorageVolume(file, storageLength); } // throws exc. if !file.exists() @SuppressWarnings ("unchecked") Constructor<? extends IStorageModule> cons = (Constructor<? extends IStorageModule>) kind.getConstructors()[0]; try { IStorageModule mod = cons.newInstance(sizeInBlocks, file); return mod; } catch (InvocationTargetException | IllegalAccessException | InstantiationException exc) { throw new IOException(exc); } }
[ "public", "static", "synchronized", "final", "IStorageModule", "open", "(", "final", "File", "file", ",", "final", "long", "storageLength", ",", "final", "boolean", "create", ",", "Class", "<", "?", "extends", "IStorageModule", ">", "kind", ")", "throws", "IOException", "{", "long", "sizeInBlocks", ";", "sizeInBlocks", "=", "storageLength", "/", "VIRTUAL_BLOCK_SIZE", ";", "if", "(", "create", "&&", "!", "kind", ".", "equals", "(", "JCloudsStorageModule", ".", "class", ")", ")", "{", "createStorageVolume", "(", "file", ",", "storageLength", ")", ";", "}", "// throws exc. if !file.exists()\r", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Constructor", "<", "?", "extends", "IStorageModule", ">", "cons", "=", "(", "Constructor", "<", "?", "extends", "IStorageModule", ">", ")", "kind", ".", "getConstructors", "(", ")", "[", "0", "]", ";", "try", "{", "IStorageModule", "mod", "=", "cons", ".", "newInstance", "(", "sizeInBlocks", ",", "file", ")", ";", "return", "mod", ";", "}", "catch", "(", "InvocationTargetException", "|", "IllegalAccessException", "|", "InstantiationException", "exc", ")", "{", "throw", "new", "IOException", "(", "exc", ")", ";", "}", "}" ]
This is the build method for creating instances of {@link RandomAccessStorageModule}. If there is no file to be found at the specified <code>filePath</code>, then a {@link FileNotFoundException} will be thrown. @param file a path leading to the file serving as storage medium @param storageLength length of storage (if not already existing) @param create should the storage be created @return a new instance of {@link RandomAccessStorageModule} @throws IOException
[ "This", "is", "the", "build", "method", "for", "creating", "instances", "of", "{", "@link", "RandomAccessStorageModule", "}", ".", "If", "there", "is", "no", "file", "to", "be", "found", "at", "the", "specified", "<code", ">", "filePath<", "/", "code", ">", "then", "a", "{", "@link", "FileNotFoundException", "}", "will", "be", "thrown", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/storage/RandomAccessStorageModule.java#L128-L143
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/storage/types/BasicDigitalObject.java
BasicDigitalObject.getRels
private Set<RelationshipTuple> getRels(String relsDatastreamName) { """ Given a relationships datastream name, return the relationships contained in that datastream """ List<Datastream> relsDatastreamVersions = m_datastreams.get(relsDatastreamName); if (relsDatastreamVersions == null || relsDatastreamVersions.size() == 0) { return new HashSet<RelationshipTuple>(); } Datastream latestRels = relsDatastreamVersions.get(0); for (Datastream v : relsDatastreamVersions) { if (v.DSCreateDT == null){ latestRels = v; break; } if (v.DSCreateDT.getTime() > latestRels.DSCreateDT.getTime()) { latestRels = v; } } try { return RDFRelationshipReader.readRelationships(latestRels); } catch (ServerException e) { throw new RuntimeException("Error reading object relationships in " + relsDatastreamName, e); } }
java
private Set<RelationshipTuple> getRels(String relsDatastreamName) { List<Datastream> relsDatastreamVersions = m_datastreams.get(relsDatastreamName); if (relsDatastreamVersions == null || relsDatastreamVersions.size() == 0) { return new HashSet<RelationshipTuple>(); } Datastream latestRels = relsDatastreamVersions.get(0); for (Datastream v : relsDatastreamVersions) { if (v.DSCreateDT == null){ latestRels = v; break; } if (v.DSCreateDT.getTime() > latestRels.DSCreateDT.getTime()) { latestRels = v; } } try { return RDFRelationshipReader.readRelationships(latestRels); } catch (ServerException e) { throw new RuntimeException("Error reading object relationships in " + relsDatastreamName, e); } }
[ "private", "Set", "<", "RelationshipTuple", ">", "getRels", "(", "String", "relsDatastreamName", ")", "{", "List", "<", "Datastream", ">", "relsDatastreamVersions", "=", "m_datastreams", ".", "get", "(", "relsDatastreamName", ")", ";", "if", "(", "relsDatastreamVersions", "==", "null", "||", "relsDatastreamVersions", ".", "size", "(", ")", "==", "0", ")", "{", "return", "new", "HashSet", "<", "RelationshipTuple", ">", "(", ")", ";", "}", "Datastream", "latestRels", "=", "relsDatastreamVersions", ".", "get", "(", "0", ")", ";", "for", "(", "Datastream", "v", ":", "relsDatastreamVersions", ")", "{", "if", "(", "v", ".", "DSCreateDT", "==", "null", ")", "{", "latestRels", "=", "v", ";", "break", ";", "}", "if", "(", "v", ".", "DSCreateDT", ".", "getTime", "(", ")", ">", "latestRels", ".", "DSCreateDT", ".", "getTime", "(", ")", ")", "{", "latestRels", "=", "v", ";", "}", "}", "try", "{", "return", "RDFRelationshipReader", ".", "readRelationships", "(", "latestRels", ")", ";", "}", "catch", "(", "ServerException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error reading object relationships in \"", "+", "relsDatastreamName", ",", "e", ")", ";", "}", "}" ]
Given a relationships datastream name, return the relationships contained in that datastream
[ "Given", "a", "relationships", "datastream", "name", "return", "the", "relationships", "contained", "in", "that", "datastream" ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/storage/types/BasicDigitalObject.java#L494-L518