repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java
FileSystemView.checkDeletable
private void checkDeletable(File file, DeleteMode mode, Path path) throws IOException { if (file.isRootDirectory()) { throw new FileSystemException(path.toString(), null, "can't delete root directory"); } if (file.isDirectory()) { if (mode == DeleteMode.NON_DIRECTORY_ONLY) { throw new FileSystemException(path.toString(), null, "can't delete: is a directory"); } checkEmpty(((Directory) file), path); } else if (mode == DeleteMode.DIRECTORY_ONLY) { throw new FileSystemException(path.toString(), null, "can't delete: is not a directory"); } if (file == workingDirectory && !path.isAbsolute()) { // this is weird, but on Unix at least, the file system seems to be happy to delete the // working directory if you give the absolute path to it but fail if you use a relative path // that resolves to the working directory (e.g. "" or ".") throw new FileSystemException(path.toString(), null, "invalid argument"); } }
java
private void checkDeletable(File file, DeleteMode mode, Path path) throws IOException { if (file.isRootDirectory()) { throw new FileSystemException(path.toString(), null, "can't delete root directory"); } if (file.isDirectory()) { if (mode == DeleteMode.NON_DIRECTORY_ONLY) { throw new FileSystemException(path.toString(), null, "can't delete: is a directory"); } checkEmpty(((Directory) file), path); } else if (mode == DeleteMode.DIRECTORY_ONLY) { throw new FileSystemException(path.toString(), null, "can't delete: is not a directory"); } if (file == workingDirectory && !path.isAbsolute()) { // this is weird, but on Unix at least, the file system seems to be happy to delete the // working directory if you give the absolute path to it but fail if you use a relative path // that resolves to the working directory (e.g. "" or ".") throw new FileSystemException(path.toString(), null, "invalid argument"); } }
[ "private", "void", "checkDeletable", "(", "File", "file", ",", "DeleteMode", "mode", ",", "Path", "path", ")", "throws", "IOException", "{", "if", "(", "file", ".", "isRootDirectory", "(", ")", ")", "{", "throw", "new", "FileSystemException", "(", "path", ...
Checks that the given file can be deleted, throwing an exception if it can't.
[ "Checks", "that", "the", "given", "file", "can", "be", "deleted", "throwing", "an", "exception", "if", "it", "can", "t", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java#L467-L488
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java
CQLTranslator.appendSet
private boolean appendSet(StringBuilder builder, Object value) { boolean isPresent = false; if (value instanceof Collection) { Collection collection = ((Collection) value); isPresent = true; builder.append(Constants.OPEN_CURLY_BRACKET); for (Object o : collection) { // Allowing null values. appendValue(builder, o != null ? o.getClass() : null, o, false); builder.append(Constants.COMMA); } if (!collection.isEmpty()) { builder.deleteCharAt(builder.length() - 1); } builder.append(Constants.CLOSE_CURLY_BRACKET); } else { appendValue(builder, value.getClass(), value, false); } return isPresent; }
java
private boolean appendSet(StringBuilder builder, Object value) { boolean isPresent = false; if (value instanceof Collection) { Collection collection = ((Collection) value); isPresent = true; builder.append(Constants.OPEN_CURLY_BRACKET); for (Object o : collection) { // Allowing null values. appendValue(builder, o != null ? o.getClass() : null, o, false); builder.append(Constants.COMMA); } if (!collection.isEmpty()) { builder.deleteCharAt(builder.length() - 1); } builder.append(Constants.CLOSE_CURLY_BRACKET); } else { appendValue(builder, value.getClass(), value, false); } return isPresent; }
[ "private", "boolean", "appendSet", "(", "StringBuilder", "builder", ",", "Object", "value", ")", "{", "boolean", "isPresent", "=", "false", ";", "if", "(", "value", "instanceof", "Collection", ")", "{", "Collection", "collection", "=", "(", "(", "Collection", ...
Appends a object of type {@link java.util.Map} @param builder the builder @param value the value @return true, if successful
[ "Appends", "a", "object", "of", "type", "{", "@link", "java", ".", "util", ".", "Map", "}" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java#L1174-L1199
tntim96/JSCover
src/main/java/jscover/util/IoUtils.java
IoUtils.loadFromClassPath
public String loadFromClassPath(String dataFile) { InputStream is = null; try { // is = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataFile); is = IoUtils.class.getResourceAsStream(dataFile); return toString(is); } catch (Throwable e) { throw new RuntimeException(String.format("Problem loading resource: '%s'" , dataFile), e); } finally { closeQuietly(is); } }
java
public String loadFromClassPath(String dataFile) { InputStream is = null; try { // is = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataFile); is = IoUtils.class.getResourceAsStream(dataFile); return toString(is); } catch (Throwable e) { throw new RuntimeException(String.format("Problem loading resource: '%s'" , dataFile), e); } finally { closeQuietly(is); } }
[ "public", "String", "loadFromClassPath", "(", "String", "dataFile", ")", "{", "InputStream", "is", "=", "null", ";", "try", "{", "// is = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataFile);\r", "is", "=", "IoUtils", ".", "class", ".", ...
/* public List<String> readLines(String source) { ByteArrayInputStream bais = new ByteArrayInputStream(source.getBytes(charSet)); return readLines(new BufferedReader(new InputStreamReader(bais, charSet))); } private List<String> readLines(BufferedReader br) { List<String> result = new ArrayList<String>(); try { for (String line; (line = br.readLine()) != null; ) { result.add(line); } return result; } catch (IOException e) { throw new RuntimeException(e); } finally { closeQuietly(br); } }
[ "/", "*", "public", "List<String", ">", "readLines", "(", "String", "source", ")", "{", "ByteArrayInputStream", "bais", "=", "new", "ByteArrayInputStream", "(", "source", ".", "getBytes", "(", "charSet", "))", ";", "return", "readLines", "(", "new", "BufferedR...
train
https://github.com/tntim96/JSCover/blob/87808b3aa38726b369496331d28ec4111dc5143e/src/main/java/jscover/util/IoUtils.java#L463-L474
jetty-project/jetty-npn
npn-boot/src/main/java/sun/security/ssl/Handshaker.java
Handshaker.throwSSLException
static void throwSSLException(String msg, Throwable cause) throws SSLException { SSLException e = new SSLException(msg); e.initCause(cause); throw e; }
java
static void throwSSLException(String msg, Throwable cause) throws SSLException { SSLException e = new SSLException(msg); e.initCause(cause); throw e; }
[ "static", "void", "throwSSLException", "(", "String", "msg", ",", "Throwable", "cause", ")", "throws", "SSLException", "{", "SSLException", "e", "=", "new", "SSLException", "(", "msg", ")", ";", "e", ".", "initCause", "(", "cause", ")", ";", "throw", "e", ...
Throw an SSLException with the specified message and cause. Shorthand until a new SSLException constructor is added. This method never returns.
[ "Throw", "an", "SSLException", "with", "the", "specified", "message", "and", "cause", ".", "Shorthand", "until", "a", "new", "SSLException", "constructor", "is", "added", ".", "This", "method", "never", "returns", "." ]
train
https://github.com/jetty-project/jetty-npn/blob/a26a7a5eabeeb57a63c6ee08fcf9b8cec1fa6c0d/npn-boot/src/main/java/sun/security/ssl/Handshaker.java#L1270-L1275
CloudSlang/cs-actions
cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java
DateTimeUtils.getJodaOrJavaDate
public static DateTime getJodaOrJavaDate(final DateTimeFormatter dateFormatter, final String date) throws Exception { if (DateTimeUtils.isDateValid(date, dateFormatter.getLocale())) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, dateFormatter.getLocale()); Calendar dateCalendar = GregorianCalendar.getInstance(); dateCalendar.setTime(dateFormat.parse(date)); return new DateTime(dateCalendar.getTime()); } return new DateTime(date); }
java
public static DateTime getJodaOrJavaDate(final DateTimeFormatter dateFormatter, final String date) throws Exception { if (DateTimeUtils.isDateValid(date, dateFormatter.getLocale())) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, dateFormatter.getLocale()); Calendar dateCalendar = GregorianCalendar.getInstance(); dateCalendar.setTime(dateFormat.parse(date)); return new DateTime(dateCalendar.getTime()); } return new DateTime(date); }
[ "public", "static", "DateTime", "getJodaOrJavaDate", "(", "final", "DateTimeFormatter", "dateFormatter", ",", "final", "String", "date", ")", "throws", "Exception", "{", "if", "(", "DateTimeUtils", ".", "isDateValid", "(", "date", ",", "dateFormatter", ".", "getLo...
Returns a LocalDateTime depending on how the date passes as argument is formatted. @param date date passed as argument @return the DateTime if it could parse it
[ "Returns", "a", "LocalDateTime", "depending", "on", "how", "the", "date", "passes", "as", "argument", "is", "formatted", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/utils/DateTimeUtils.java#L78-L89
Netflix/conductor
core/src/main/java/com/netflix/conductor/core/orchestration/ExecutionDAOFacade.java
ExecutionDAOFacade.updateTask
public void updateTask(Task task) { try { executionDAO.updateTask(task); indexDAO.indexTask(task); } catch (Exception e) { String errorMsg = String.format("Error updating task: %s in workflow: %s", task.getTaskId(), task.getWorkflowInstanceId()); LOGGER.error(errorMsg, e); throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, errorMsg, e); } }
java
public void updateTask(Task task) { try { executionDAO.updateTask(task); indexDAO.indexTask(task); } catch (Exception e) { String errorMsg = String.format("Error updating task: %s in workflow: %s", task.getTaskId(), task.getWorkflowInstanceId()); LOGGER.error(errorMsg, e); throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, errorMsg, e); } }
[ "public", "void", "updateTask", "(", "Task", "task", ")", "{", "try", "{", "executionDAO", ".", "updateTask", "(", "task", ")", ";", "indexDAO", ".", "indexTask", "(", "task", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "errorMsg...
Sets the update time for the task. Sets the end time for the task (if task is in terminal state and end time is not set). Updates the task in the {@link ExecutionDAO} first, then stores it in the {@link IndexDAO}. @param task the task to be updated in the data store @throws ApplicationException if the dao operations fail
[ "Sets", "the", "update", "time", "for", "the", "task", ".", "Sets", "the", "end", "time", "for", "the", "task", "(", "if", "task", "is", "in", "terminal", "state", "and", "end", "time", "is", "not", "set", ")", ".", "Updates", "the", "task", "in", ...
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/core/src/main/java/com/netflix/conductor/core/orchestration/ExecutionDAOFacade.java#L232-L241
powermock/powermock
powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java
HotSpotVirtualMachine.loadAgentPath
@Override public void loadAgentPath(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException { loadAgentLibrary(agentLibrary, true, options); }
java
@Override public void loadAgentPath(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException { loadAgentLibrary(agentLibrary, true, options); }
[ "@", "Override", "public", "void", "loadAgentPath", "(", "String", "agentLibrary", ",", "String", "options", ")", "throws", "AgentLoadException", ",", "AgentInitializationException", ",", "IOException", "{", "loadAgentLibrary", "(", "agentLibrary", ",", "true", ",", ...
/* Load agent - absolute path of library provided to target VM
[ "/", "*", "Load", "agent", "-", "absolute", "path", "of", "library", "provided", "to", "target", "VM" ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java#L85-L90
alkacon/opencms-core
src/org/opencms/ade/detailpage/CmsDetailPageConfigurationWriter.java
CmsDetailPageConfigurationWriter.updateAndSave
public void updateAndSave(List<CmsDetailPageInfo> infos, CmsUUID newId) throws CmsException { if (m_resource != null) { getDocument(); removeOldValues(); writeDetailPageInfos(infos, newId); m_document.setAutoCorrectionEnabled(true); m_document.correctXmlStructure(m_cms); byte[] content = m_document.marshal(); m_file.setContents(content); m_cms.writeFile(m_file); } }
java
public void updateAndSave(List<CmsDetailPageInfo> infos, CmsUUID newId) throws CmsException { if (m_resource != null) { getDocument(); removeOldValues(); writeDetailPageInfos(infos, newId); m_document.setAutoCorrectionEnabled(true); m_document.correctXmlStructure(m_cms); byte[] content = m_document.marshal(); m_file.setContents(content); m_cms.writeFile(m_file); } }
[ "public", "void", "updateAndSave", "(", "List", "<", "CmsDetailPageInfo", ">", "infos", ",", "CmsUUID", "newId", ")", "throws", "CmsException", "{", "if", "(", "m_resource", "!=", "null", ")", "{", "getDocument", "(", ")", ";", "removeOldValues", "(", ")", ...
Writes the new detail page information to the configuration file.<p> @param infos the new detail page information @param newId the id to use for new pages @throws CmsException if something goes wrong
[ "Writes", "the", "new", "detail", "page", "information", "to", "the", "configuration", "file", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/detailpage/CmsDetailPageConfigurationWriter.java#L93-L105
signalapp/curve25519-java
common/src/main/java/org/whispersystems/curve25519/Curve25519.java
Curve25519.verifySignature
public boolean verifySignature(byte[] publicKey, byte[] message, byte[] signature) { if (publicKey == null || publicKey.length != 32) { throw new IllegalArgumentException("Invalid public key!"); } if (message == null || signature == null || signature.length != 64) { return false; } return provider.verifySignature(publicKey, message, signature); }
java
public boolean verifySignature(byte[] publicKey, byte[] message, byte[] signature) { if (publicKey == null || publicKey.length != 32) { throw new IllegalArgumentException("Invalid public key!"); } if (message == null || signature == null || signature.length != 64) { return false; } return provider.verifySignature(publicKey, message, signature); }
[ "public", "boolean", "verifySignature", "(", "byte", "[", "]", "publicKey", ",", "byte", "[", "]", "message", ",", "byte", "[", "]", "signature", ")", "{", "if", "(", "publicKey", "==", "null", "||", "publicKey", ".", "length", "!=", "32", ")", "{", ...
Verify a Curve25519 signature. @param publicKey The Curve25519 public key the signature belongs to. @param message The message that was signed. @param signature The signature to verify. @return true if valid, false if not.
[ "Verify", "a", "Curve25519", "signature", "." ]
train
https://github.com/signalapp/curve25519-java/blob/70fae57d6dccff7e78a46203c534314b07dfdd98/common/src/main/java/org/whispersystems/curve25519/Curve25519.java#L108-L118
windup/windup
config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationFilter.java
AbstractIterationFilter.checkVariableName
protected void checkVariableName(GraphRewrite event, EvaluationContext context) { if (getInputVariablesName() == null) { setInputVariablesName(Iteration.getPayloadVariableName(event, context)); } }
java
protected void checkVariableName(GraphRewrite event, EvaluationContext context) { if (getInputVariablesName() == null) { setInputVariablesName(Iteration.getPayloadVariableName(event, context)); } }
[ "protected", "void", "checkVariableName", "(", "GraphRewrite", "event", ",", "EvaluationContext", "context", ")", "{", "if", "(", "getInputVariablesName", "(", ")", "==", "null", ")", "{", "setInputVariablesName", "(", "Iteration", ".", "getPayloadVariableName", "("...
Check the variable name and if not set, set it with the singleton variable being on the top of the stack.
[ "Check", "the", "variable", "name", "and", "if", "not", "set", "set", "it", "with", "the", "singleton", "variable", "being", "on", "the", "top", "of", "the", "stack", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/operation/iteration/AbstractIterationFilter.java#L43-L49
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addBetween
public void addBetween(Object attribute, Object value1, Object value2) { // PAW // addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias())); addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getUserAlias(attribute))); }
java
public void addBetween(Object attribute, Object value1, Object value2) { // PAW // addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias())); addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getUserAlias(attribute))); }
[ "public", "void", "addBetween", "(", "Object", "attribute", ",", "Object", "value1", ",", "Object", "value2", ")", "{", "// PAW\r", "// addSelectionCriteria(ValueCriteria.buildBeweenCriteria(attribute, value1, value2, getAlias()));\r", "addSelectionCriteria", "(", "ValueCriteria"...
Adds BETWEEN criteria, customer_id between 1 and 10 @param attribute The field name to be used @param value1 The lower boundary @param value2 The upper boundary
[ "Adds", "BETWEEN", "criteria", "customer_id", "between", "1", "and", "10" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L735-L740
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/KDTree.java
KDTree.kNearestNeighbours
public Instances kNearestNeighbours(Instance target, int k) throws Exception { checkMissing(target); MyHeap heap = new MyHeap(k); findNearestNeighbours(target, m_Root, k, heap, 0.0); Instances neighbours = new Instances(m_Instances, (heap.size() + heap .noOfKthNearest())); m_DistanceList = new double[heap.size() + heap.noOfKthNearest()]; int[] indices = new int[heap.size() + heap.noOfKthNearest()]; int i = indices.length - 1; MyHeapElement h; while (heap.noOfKthNearest() > 0) { h = heap.getKthNearest(); indices[i] = h.index; m_DistanceList[i] = h.distance; i--; } while (heap.size() > 0) { h = heap.get(); indices[i] = h.index; m_DistanceList[i] = h.distance; i--; } m_DistanceFunction.postProcessDistances(m_DistanceList); for (int idx = 0; idx < indices.length; idx++) { neighbours.add(m_Instances.instance(indices[idx])); } return neighbours; }
java
public Instances kNearestNeighbours(Instance target, int k) throws Exception { checkMissing(target); MyHeap heap = new MyHeap(k); findNearestNeighbours(target, m_Root, k, heap, 0.0); Instances neighbours = new Instances(m_Instances, (heap.size() + heap .noOfKthNearest())); m_DistanceList = new double[heap.size() + heap.noOfKthNearest()]; int[] indices = new int[heap.size() + heap.noOfKthNearest()]; int i = indices.length - 1; MyHeapElement h; while (heap.noOfKthNearest() > 0) { h = heap.getKthNearest(); indices[i] = h.index; m_DistanceList[i] = h.distance; i--; } while (heap.size() > 0) { h = heap.get(); indices[i] = h.index; m_DistanceList[i] = h.distance; i--; } m_DistanceFunction.postProcessDistances(m_DistanceList); for (int idx = 0; idx < indices.length; idx++) { neighbours.add(m_Instances.instance(indices[idx])); } return neighbours; }
[ "public", "Instances", "kNearestNeighbours", "(", "Instance", "target", ",", "int", "k", ")", "throws", "Exception", "{", "checkMissing", "(", "target", ")", ";", "MyHeap", "heap", "=", "new", "MyHeap", "(", "k", ")", ";", "findNearestNeighbours", "(", "targ...
Returns the k nearest neighbours of the supplied instance. &gt;k neighbours are returned if there are more than one neighbours at the kth boundary. @param target The instance to find the nearest neighbours for. @param k The number of neighbours to find. @return The k nearest neighbours (or &gt;k if more there are than one neighbours at the kth boundary). @throws Exception if the nearest neighbour could not be found.
[ "Returns", "the", "k", "nearest", "neighbours", "of", "the", "supplied", "instance", ".", "&gt", ";", "k", "neighbours", "are", "returned", "if", "there", "are", "more", "than", "one", "neighbours", "at", "the", "kth", "boundary", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/KDTree.java#L328-L359
facebookarchive/hadoop-20
src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerCore.java
ServerCore.getClientsForNotification
@Override public Set<Long> getClientsForNotification(NamespaceNotification n) { String eventPath = NotifierUtils.getBasePath(n); if (LOG.isDebugEnabled()) { LOG.debug("getClientsForNotification called for " + NotifierUtils.asString(n) + ". Searching at path " + eventPath); } List<String> ancestors = NotifierUtils.getAllAncestors(eventPath); Set<Long> clients = new HashSet<Long>(); synchronized (subscriptions) { for (String path : ancestors) { Set<Long> clientsOnPath = subscriptions.get(new NamespaceEventKey(path, n.type)); if (clientsOnPath != null) { clients.addAll(clientsOnPath); } } } return clients; }
java
@Override public Set<Long> getClientsForNotification(NamespaceNotification n) { String eventPath = NotifierUtils.getBasePath(n); if (LOG.isDebugEnabled()) { LOG.debug("getClientsForNotification called for " + NotifierUtils.asString(n) + ". Searching at path " + eventPath); } List<String> ancestors = NotifierUtils.getAllAncestors(eventPath); Set<Long> clients = new HashSet<Long>(); synchronized (subscriptions) { for (String path : ancestors) { Set<Long> clientsOnPath = subscriptions.get(new NamespaceEventKey(path, n.type)); if (clientsOnPath != null) { clients.addAll(clientsOnPath); } } } return clients; }
[ "@", "Override", "public", "Set", "<", "Long", ">", "getClientsForNotification", "(", "NamespaceNotification", "n", ")", "{", "String", "eventPath", "=", "NotifierUtils", ".", "getBasePath", "(", "n", ")", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", "...
Used to get the set of clients for which a notification should be sent. While iterating over this set, you should use synchronized() on it to avoid data inconsistency (or ordering problems). @param n the notification for which we want to get the set of clients @return the set of clients or null if there are no clients subscribed for this notification
[ "Used", "to", "get", "the", "set", "of", "clients", "for", "which", "a", "notification", "should", "be", "sent", ".", "While", "iterating", "over", "this", "set", "you", "should", "use", "synchronized", "()", "on", "it", "to", "avoid", "data", "inconsisten...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerCore.java#L506-L524
Azure/azure-sdk-for-java
datamigration/resource-manager/v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/implementation/FilesInner.java
FilesInner.readAsync
public Observable<FileStorageInfoInner> readAsync(String groupName, String serviceName, String projectName, String fileName) { return readWithServiceResponseAsync(groupName, serviceName, projectName, fileName).map(new Func1<ServiceResponse<FileStorageInfoInner>, FileStorageInfoInner>() { @Override public FileStorageInfoInner call(ServiceResponse<FileStorageInfoInner> response) { return response.body(); } }); }
java
public Observable<FileStorageInfoInner> readAsync(String groupName, String serviceName, String projectName, String fileName) { return readWithServiceResponseAsync(groupName, serviceName, projectName, fileName).map(new Func1<ServiceResponse<FileStorageInfoInner>, FileStorageInfoInner>() { @Override public FileStorageInfoInner call(ServiceResponse<FileStorageInfoInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "FileStorageInfoInner", ">", "readAsync", "(", "String", "groupName", ",", "String", "serviceName", ",", "String", "projectName", ",", "String", "fileName", ")", "{", "return", "readWithServiceResponseAsync", "(", "groupName", ",", "serv...
Request storage information for downloading the file content. This method is used for requesting storage information using which contents of the file can be downloaded. @param groupName Name of the resource group @param serviceName Name of the service @param projectName Name of the project @param fileName Name of the File @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the FileStorageInfoInner object
[ "Request", "storage", "information", "for", "downloading", "the", "file", "content", ".", "This", "method", "is", "used", "for", "requesting", "storage", "information", "using", "which", "contents", "of", "the", "file", "can", "be", "downloaded", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/implementation/FilesInner.java#L713-L720
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApiClient.java
GitLabApiClient.getWithAccepts
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, URL url, String accepts) { return (invocation(url, queryParams, accepts).get()); }
java
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, URL url, String accepts) { return (invocation(url, queryParams, accepts).get()); }
[ "protected", "Response", "getWithAccepts", "(", "MultivaluedMap", "<", "String", ",", "String", ">", "queryParams", ",", "URL", "url", ",", "String", "accepts", ")", "{", "return", "(", "invocation", "(", "url", ",", "queryParams", ",", "accepts", ")", ".", ...
Perform an HTTP GET call with the specified query parameters and URL, returning a ClientResponse instance with the data returned from the endpoint. @param queryParams multivalue map of request parameters @param url the fully formed path to the GitLab API endpoint @param accepts if non-empty will set the Accepts header to this value @return a ClientResponse instance with the data returned from the endpoint
[ "Perform", "an", "HTTP", "GET", "call", "with", "the", "specified", "query", "parameters", "and", "URL", "returning", "a", "ClientResponse", "instance", "with", "the", "data", "returned", "from", "the", "endpoint", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiClient.java#L413-L415
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/parser/lexparser/EnglishTreebankParserParams.java
EnglishTreebankParserParams.treeReaderFactory
public TreeReaderFactory treeReaderFactory() { return new TreeReaderFactory() { public TreeReader newTreeReader(Reader in) { return new PennTreeReader(in, new LabeledScoredTreeFactory(), new NPTmpRetainingTreeNormalizer(englishTrain.splitTMP, englishTrain.splitSGapped == 5, englishTrain.leaveItAll, englishTrain.splitNPADV >= 1, headFinder())); } }; }
java
public TreeReaderFactory treeReaderFactory() { return new TreeReaderFactory() { public TreeReader newTreeReader(Reader in) { return new PennTreeReader(in, new LabeledScoredTreeFactory(), new NPTmpRetainingTreeNormalizer(englishTrain.splitTMP, englishTrain.splitSGapped == 5, englishTrain.leaveItAll, englishTrain.splitNPADV >= 1, headFinder())); } }; }
[ "public", "TreeReaderFactory", "treeReaderFactory", "(", ")", "{", "return", "new", "TreeReaderFactory", "(", ")", "{", "public", "TreeReader", "newTreeReader", "(", "Reader", "in", ")", "{", "return", "new", "PennTreeReader", "(", "in", ",", "new", "LabeledScor...
Makes appropriate TreeReaderFactory with all options specified
[ "Makes", "appropriate", "TreeReaderFactory", "with", "all", "options", "specified" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/parser/lexparser/EnglishTreebankParserParams.java#L172-L178
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java
WalletProtobufSerializer.writeWallet
public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, this.walletWriteBufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }
java
public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, this.walletWriteBufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }
[ "public", "void", "writeWallet", "(", "Wallet", "wallet", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "Protos", ".", "Wallet", "walletProto", "=", "walletToProto", "(", "wallet", ")", ";", "final", "CodedOutputStream", "codedOutput", "=", "...
Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p> Equivalent to {@code walletToProto(wallet).writeTo(output);}
[ "Formats", "the", "given", "wallet", "(", "transactions", "and", "keys", ")", "to", "the", "given", "output", "stream", "in", "protocol", "buffer", "format", ".", "<p", ">" ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java#L152-L157
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getMatch
public Future<MatchDetail> getMatch(long matchId, boolean includeTimeline) { return new ApiFuture<>(() -> handler.getMatch(matchId, includeTimeline)); }
java
public Future<MatchDetail> getMatch(long matchId, boolean includeTimeline) { return new ApiFuture<>(() -> handler.getMatch(matchId, includeTimeline)); }
[ "public", "Future", "<", "MatchDetail", ">", "getMatch", "(", "long", "matchId", ",", "boolean", "includeTimeline", ")", "{", "return", "new", "ApiFuture", "<>", "(", "(", ")", "->", "handler", ".", "getMatch", "(", "matchId", ",", "includeTimeline", ")", ...
Retrieves the specified match. @param matchId The id of the match. @param includeTimeline Whether or not the event timeline should be retrieved. @return The match details. @see <a href="https://developer.riotgames.com/api/methods#!/806/2848">Official API Documentation</a>
[ "Retrieves", "the", "specified", "match", "." ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L976-L978
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java
DiagnosticsInner.listHostingEnvironmentDetectorResponsesWithServiceResponseAsync
public Observable<ServiceResponse<Page<DetectorResponseInner>>> listHostingEnvironmentDetectorResponsesWithServiceResponseAsync(final String resourceGroupName, final String name) { return listHostingEnvironmentDetectorResponsesSinglePageAsync(resourceGroupName, name) .concatMap(new Func1<ServiceResponse<Page<DetectorResponseInner>>, Observable<ServiceResponse<Page<DetectorResponseInner>>>>() { @Override public Observable<ServiceResponse<Page<DetectorResponseInner>>> call(ServiceResponse<Page<DetectorResponseInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listHostingEnvironmentDetectorResponsesNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<DetectorResponseInner>>> listHostingEnvironmentDetectorResponsesWithServiceResponseAsync(final String resourceGroupName, final String name) { return listHostingEnvironmentDetectorResponsesSinglePageAsync(resourceGroupName, name) .concatMap(new Func1<ServiceResponse<Page<DetectorResponseInner>>, Observable<ServiceResponse<Page<DetectorResponseInner>>>>() { @Override public Observable<ServiceResponse<Page<DetectorResponseInner>>> call(ServiceResponse<Page<DetectorResponseInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listHostingEnvironmentDetectorResponsesNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "DetectorResponseInner", ">", ">", ">", "listHostingEnvironmentDetectorResponsesWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ")", "{", "return", ...
List Hosting Environment Detector Responses. List Hosting Environment Detector Responses. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Site Name @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;DetectorResponseInner&gt; object
[ "List", "Hosting", "Environment", "Detector", "Responses", ".", "List", "Hosting", "Environment", "Detector", "Responses", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java#L267-L279
elki-project/elki
addons/uncertain/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/uncertain/UKMeans.java
UKMeans.assignToNearestCluster
protected boolean assignToNearestCluster(Relation<DiscreteUncertainObject> relation, List<double[]> means, List<? extends ModifiableDBIDs> clusters, WritableIntegerDataStore assignment, double[] varsum) { assert (k == means.size()); boolean changed = false; Arrays.fill(varsum, 0.); for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { double mindist = Double.POSITIVE_INFINITY; DiscreteUncertainObject fv = relation.get(iditer); int minIndex = 0; for(int i = 0; i < k; i++) { double dist = getExpectedRepDistance(DoubleVector.wrap(means.get(i)), fv); if(dist < mindist) { minIndex = i; mindist = dist; } } varsum[minIndex] += mindist; changed |= updateAssignment(iditer, clusters, assignment, minIndex); } return changed; }
java
protected boolean assignToNearestCluster(Relation<DiscreteUncertainObject> relation, List<double[]> means, List<? extends ModifiableDBIDs> clusters, WritableIntegerDataStore assignment, double[] varsum) { assert (k == means.size()); boolean changed = false; Arrays.fill(varsum, 0.); for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { double mindist = Double.POSITIVE_INFINITY; DiscreteUncertainObject fv = relation.get(iditer); int minIndex = 0; for(int i = 0; i < k; i++) { double dist = getExpectedRepDistance(DoubleVector.wrap(means.get(i)), fv); if(dist < mindist) { minIndex = i; mindist = dist; } } varsum[minIndex] += mindist; changed |= updateAssignment(iditer, clusters, assignment, minIndex); } return changed; }
[ "protected", "boolean", "assignToNearestCluster", "(", "Relation", "<", "DiscreteUncertainObject", ">", "relation", ",", "List", "<", "double", "[", "]", ">", "means", ",", "List", "<", "?", "extends", "ModifiableDBIDs", ">", "clusters", ",", "WritableIntegerDataS...
Returns a list of clusters. The k<sup>th</sup> cluster contains the ids of those FeatureVectors, that are nearest to the k<sup>th</sup> mean. @param relation the database to cluster @param means a list of k means @param clusters cluster assignment @param assignment Current cluster assignment @param varsum Variance sum output @return true when the object was reassigned
[ "Returns", "a", "list", "of", "clusters", ".", "The", "k<sup", ">", "th<", "/", "sup", ">", "cluster", "contains", "the", "ids", "of", "those", "FeatureVectors", "that", "are", "nearest", "to", "the", "k<sup", ">", "th<", "/", "sup", ">", "mean", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/uncertain/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/uncertain/UKMeans.java#L193-L212
dadoonet/fscrawler
elasticsearch-client/elasticsearch-client-v5/src/main/java/fr/pilato/elasticsearch/crawler/fs/client/v5/ElasticsearchClientV5.java
ElasticsearchClientV5.deleteByQuery
public void deleteByQuery(String index, String type) throws IOException { logger.debug("deleteByQuery [{}]/[{}]", index, type); String deleteByQuery = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " }\n" + "}"; HttpEntity entity = EntityBuilder.create().setText(deleteByQuery).setContentType(ContentType.APPLICATION_JSON).build(); Response restResponse = lowLevelClient.performRequest("POST", "/" + index + "/" + type + "/_delete_by_query", Collections.emptyMap(), entity); Map<String, Object> response = asMap(restResponse); logger.debug("reindex response: {}", response); }
java
public void deleteByQuery(String index, String type) throws IOException { logger.debug("deleteByQuery [{}]/[{}]", index, type); String deleteByQuery = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " }\n" + "}"; HttpEntity entity = EntityBuilder.create().setText(deleteByQuery).setContentType(ContentType.APPLICATION_JSON).build(); Response restResponse = lowLevelClient.performRequest("POST", "/" + index + "/" + type + "/_delete_by_query", Collections.emptyMap(), entity); Map<String, Object> response = asMap(restResponse); logger.debug("reindex response: {}", response); }
[ "public", "void", "deleteByQuery", "(", "String", "index", ",", "String", "type", ")", "throws", "IOException", "{", "logger", ".", "debug", "(", "\"deleteByQuery [{}]/[{}]\"", ",", "index", ",", "type", ")", ";", "String", "deleteByQuery", "=", "\"{\\n\"", "+...
Fully removes a type from an index (removes data) @param index index name @param type type @throws IOException In case of error
[ "Fully", "removes", "a", "type", "from", "an", "index", "(", "removes", "data", ")" ]
train
https://github.com/dadoonet/fscrawler/blob/cca00a14e21ef9986aa30e19b160463aed6bf921/elasticsearch-client/elasticsearch-client-v5/src/main/java/fr/pilato/elasticsearch/crawler/fs/client/v5/ElasticsearchClientV5.java#L348-L361
google/closure-compiler
src/com/google/javascript/jscomp/RewriteAsyncIteration.java
RewriteAsyncIteration.convertAsyncGenerator
private void convertAsyncGenerator(NodeTraversal t, Node originalFunction) { checkNotNull(originalFunction); checkState(originalFunction.isAsyncGeneratorFunction()); Node asyncGeneratorWrapperRef = astFactory.createAsyncGeneratorWrapperReference(originalFunction.getJSType(), t.getScope()); Node innerFunction = astFactory.createEmptyAsyncGeneratorWrapperArgument(asyncGeneratorWrapperRef.getJSType()); Node innerBlock = originalFunction.getLastChild(); originalFunction.removeChild(innerBlock); innerFunction.replaceChild(innerFunction.getLastChild(), innerBlock); // Body should be: // return new $jscomp.AsyncGeneratorWrapper((new function with original block here)()); Node outerBlock = astFactory.createBlock( astFactory.createReturn( astFactory.createNewNode( asyncGeneratorWrapperRef, astFactory.createCall(innerFunction)))); originalFunction.addChildToBack(outerBlock); originalFunction.setIsAsyncFunction(false); originalFunction.setIsGeneratorFunction(false); originalFunction.useSourceInfoIfMissingFromForTree(originalFunction); // Both the inner and original functions should be marked as changed. compiler.reportChangeToChangeScope(originalFunction); compiler.reportChangeToChangeScope(innerFunction); }
java
private void convertAsyncGenerator(NodeTraversal t, Node originalFunction) { checkNotNull(originalFunction); checkState(originalFunction.isAsyncGeneratorFunction()); Node asyncGeneratorWrapperRef = astFactory.createAsyncGeneratorWrapperReference(originalFunction.getJSType(), t.getScope()); Node innerFunction = astFactory.createEmptyAsyncGeneratorWrapperArgument(asyncGeneratorWrapperRef.getJSType()); Node innerBlock = originalFunction.getLastChild(); originalFunction.removeChild(innerBlock); innerFunction.replaceChild(innerFunction.getLastChild(), innerBlock); // Body should be: // return new $jscomp.AsyncGeneratorWrapper((new function with original block here)()); Node outerBlock = astFactory.createBlock( astFactory.createReturn( astFactory.createNewNode( asyncGeneratorWrapperRef, astFactory.createCall(innerFunction)))); originalFunction.addChildToBack(outerBlock); originalFunction.setIsAsyncFunction(false); originalFunction.setIsGeneratorFunction(false); originalFunction.useSourceInfoIfMissingFromForTree(originalFunction); // Both the inner and original functions should be marked as changed. compiler.reportChangeToChangeScope(originalFunction); compiler.reportChangeToChangeScope(innerFunction); }
[ "private", "void", "convertAsyncGenerator", "(", "NodeTraversal", "t", ",", "Node", "originalFunction", ")", "{", "checkNotNull", "(", "originalFunction", ")", ";", "checkState", "(", "originalFunction", ".", "isAsyncGeneratorFunction", "(", ")", ")", ";", "Node", ...
Moves the body of an async generator function into a nested generator function and removes the async and generator props from the original function. <pre>{@code async function* foo() { bar(); } }</pre> <p>becomes <pre>{@code function foo() { return new $jscomp.AsyncGeneratorWrapper((function*(){ bar(); })()) } }</pre> @param originalFunction the original AsyncGeneratorFunction Node to be converted.
[ "Moves", "the", "body", "of", "an", "async", "generator", "function", "into", "a", "nested", "generator", "function", "and", "removes", "the", "async", "and", "generator", "props", "from", "the", "original", "function", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewriteAsyncIteration.java#L370-L398
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java
FileSystemView.isSameFile
public boolean isSameFile(JimfsPath path, FileSystemView view2, JimfsPath path2) throws IOException { if (!isSameFileSystem(view2)) { return false; } store.readLock().lock(); try { File file = lookUp(path, Options.FOLLOW_LINKS).fileOrNull(); File file2 = view2.lookUp(path2, Options.FOLLOW_LINKS).fileOrNull(); return file != null && Objects.equals(file, file2); } finally { store.readLock().unlock(); } }
java
public boolean isSameFile(JimfsPath path, FileSystemView view2, JimfsPath path2) throws IOException { if (!isSameFileSystem(view2)) { return false; } store.readLock().lock(); try { File file = lookUp(path, Options.FOLLOW_LINKS).fileOrNull(); File file2 = view2.lookUp(path2, Options.FOLLOW_LINKS).fileOrNull(); return file != null && Objects.equals(file, file2); } finally { store.readLock().unlock(); } }
[ "public", "boolean", "isSameFile", "(", "JimfsPath", "path", ",", "FileSystemView", "view2", ",", "JimfsPath", "path2", ")", "throws", "IOException", "{", "if", "(", "!", "isSameFileSystem", "(", "view2", ")", ")", "{", "return", "false", ";", "}", "store", ...
Returns whether or not the two given paths locate the same file. The second path is located using the given view rather than this file view.
[ "Returns", "whether", "or", "not", "the", "two", "given", "paths", "locate", "the", "same", "file", ".", "The", "second", "path", "is", "located", "using", "the", "given", "view", "rather", "than", "this", "file", "view", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/FileSystemView.java#L175-L189
Azure/azure-sdk-for-java
recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/FeatureSupportsInner.java
FeatureSupportsInner.validateAsync
public Observable<AzureVMResourceFeatureSupportResponseInner> validateAsync(String azureRegion, FeatureSupportRequest parameters) { return validateWithServiceResponseAsync(azureRegion, parameters).map(new Func1<ServiceResponse<AzureVMResourceFeatureSupportResponseInner>, AzureVMResourceFeatureSupportResponseInner>() { @Override public AzureVMResourceFeatureSupportResponseInner call(ServiceResponse<AzureVMResourceFeatureSupportResponseInner> response) { return response.body(); } }); }
java
public Observable<AzureVMResourceFeatureSupportResponseInner> validateAsync(String azureRegion, FeatureSupportRequest parameters) { return validateWithServiceResponseAsync(azureRegion, parameters).map(new Func1<ServiceResponse<AzureVMResourceFeatureSupportResponseInner>, AzureVMResourceFeatureSupportResponseInner>() { @Override public AzureVMResourceFeatureSupportResponseInner call(ServiceResponse<AzureVMResourceFeatureSupportResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AzureVMResourceFeatureSupportResponseInner", ">", "validateAsync", "(", "String", "azureRegion", ",", "FeatureSupportRequest", "parameters", ")", "{", "return", "validateWithServiceResponseAsync", "(", "azureRegion", ",", "parameters", ")", "."...
It will validate if given feature with resource properties is supported in service. @param azureRegion Azure region to hit Api @param parameters Feature support request object @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AzureVMResourceFeatureSupportResponseInner object
[ "It", "will", "validate", "if", "given", "feature", "with", "resource", "properties", "is", "supported", "in", "service", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/FeatureSupportsInner.java#L98-L105
playn/playn
core/src/playn/core/Image.java
Image.createTexture
public Texture createTexture (Texture.Config config) { if (!isLoaded()) throw new IllegalStateException( "Cannot create texture from unready image: " + this); int texWidth = config.toTexWidth(pixelWidth()); int texHeight = config.toTexHeight(pixelHeight()); if (texWidth <= 0 || texHeight <= 0) throw new IllegalArgumentException( "Invalid texture size: " + texWidth + "x" + texHeight + " from: " + this); Texture tex = new Texture(gfx, gfx.createTexture(config), config, texWidth, texHeight, scale(), width(), height()); tex.update(this); // this will handle non-POT source image conversion return tex; }
java
public Texture createTexture (Texture.Config config) { if (!isLoaded()) throw new IllegalStateException( "Cannot create texture from unready image: " + this); int texWidth = config.toTexWidth(pixelWidth()); int texHeight = config.toTexHeight(pixelHeight()); if (texWidth <= 0 || texHeight <= 0) throw new IllegalArgumentException( "Invalid texture size: " + texWidth + "x" + texHeight + " from: " + this); Texture tex = new Texture(gfx, gfx.createTexture(config), config, texWidth, texHeight, scale(), width(), height()); tex.update(this); // this will handle non-POT source image conversion return tex; }
[ "public", "Texture", "createTexture", "(", "Texture", ".", "Config", "config", ")", "{", "if", "(", "!", "isLoaded", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot create texture from unready image: \"", "+", "this", ")", ";", "int", "tex...
Creates a texture with this image's bitmap data using {@code config}. NOTE: this creates a new texture with every call. This is generally only needed if you plan to create multiple textures from the same bitmap, with different configurations. Otherwise just use {@link #texture} to create the image's "default" texture which will be shared by all callers.
[ "Creates", "a", "texture", "with", "this", "image", "s", "bitmap", "data", "using", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Image.java#L169-L182
alkacon/opencms-core
src/org/opencms/relations/CmsCategoryService.java
CmsCategoryService.repairRelations
public void repairRelations(CmsObject cms, CmsResource resource) throws CmsException { internalReadResourceCategories(cms, resource, true); }
java
public void repairRelations(CmsObject cms, CmsResource resource) throws CmsException { internalReadResourceCategories(cms, resource, true); }
[ "public", "void", "repairRelations", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "internalReadResourceCategories", "(", "cms", ",", "resource", ",", "true", ")", ";", "}" ]
Repairs broken category relations.<p> This could be caused by renaming/moving a category folder, or changing the category repositories base folder name.<p> Also repairs problems when creating/deleting conflicting category folders across several repositories.<p> The resource has to be previously locked.<p> @param cms the cms context @param resource the resource to repair @throws CmsException if something goes wrong
[ "Repairs", "broken", "category", "relations", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategoryService.java#L727-L730
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/StringUtils.java
StringUtils.makeAsciiTableCell
private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) { String result = obj.toString(); if (padLeft > 0) { result = padLeft(result, padLeft); } if (padRight > 0) { result = pad(result, padRight); } if (tsv) { result = result + '\t'; } return result; }
java
private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) { String result = obj.toString(); if (padLeft > 0) { result = padLeft(result, padLeft); } if (padRight > 0) { result = pad(result, padRight); } if (tsv) { result = result + '\t'; } return result; }
[ "private", "static", "String", "makeAsciiTableCell", "(", "Object", "obj", ",", "int", "padLeft", ",", "int", "padRight", ",", "boolean", "tsv", ")", "{", "String", "result", "=", "obj", ".", "toString", "(", ")", ";", "if", "(", "padLeft", ">", "0", "...
The cell String is the string representation of the object. If padLeft is greater than 0, it is padded. Ditto right
[ "The", "cell", "String", "is", "the", "string", "representation", "of", "the", "object", ".", "If", "padLeft", "is", "greater", "than", "0", "it", "is", "padded", ".", "Ditto", "right" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/StringUtils.java#L1501-L1513
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/thrift/DBConn.java
DBConn.reconnect
private void reconnect(Exception reconnectEx) { // Log the exception as a warning. m_logger.warn("Reconnecting to Cassandra due to error", reconnectEx); // Reconnect up to the configured number of times, waiting a little between each attempt. boolean bSuccess = false; for (int attempt = 1; !bSuccess; attempt++) { try { close(); m_dbService.connectDBConn(this); m_logger.debug("Reconnect successful"); bSuccess = true; } catch (Exception ex) { // Abort if all retries failed. if (attempt >= m_max_reconnect_attempts) { m_logger.error("All reconnect attempts failed; abandoning reconnect", ex); throw new DBNotAvailableException("All reconnect attempts failed", ex); } m_logger.warn("Reconnect attempt #" + attempt + " failed", ex); try { Thread.sleep(m_retry_wait_millis * attempt); } catch (InterruptedException e) { // Ignore } } } }
java
private void reconnect(Exception reconnectEx) { // Log the exception as a warning. m_logger.warn("Reconnecting to Cassandra due to error", reconnectEx); // Reconnect up to the configured number of times, waiting a little between each attempt. boolean bSuccess = false; for (int attempt = 1; !bSuccess; attempt++) { try { close(); m_dbService.connectDBConn(this); m_logger.debug("Reconnect successful"); bSuccess = true; } catch (Exception ex) { // Abort if all retries failed. if (attempt >= m_max_reconnect_attempts) { m_logger.error("All reconnect attempts failed; abandoning reconnect", ex); throw new DBNotAvailableException("All reconnect attempts failed", ex); } m_logger.warn("Reconnect attempt #" + attempt + " failed", ex); try { Thread.sleep(m_retry_wait_millis * attempt); } catch (InterruptedException e) { // Ignore } } } }
[ "private", "void", "reconnect", "(", "Exception", "reconnectEx", ")", "{", "// Log the exception as a warning.\r", "m_logger", ".", "warn", "(", "\"Reconnecting to Cassandra due to error\"", ",", "reconnectEx", ")", ";", "// Reconnect up to the configured number of times, waiting...
an DBNotAvailableException and leave the Thrift connection null.
[ "an", "DBNotAvailableException", "and", "leave", "the", "Thrift", "connection", "null", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/thrift/DBConn.java#L518-L544
aws/aws-sdk-java
aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/internal/Utils.java
Utils.assertNotNull
public static <T> T assertNotNull(T argument, String msg) { if (argument == null) throw new IllegalArgumentException(msg); return argument; }
java
public static <T> T assertNotNull(T argument, String msg) { if (argument == null) throw new IllegalArgumentException(msg); return argument; }
[ "public", "static", "<", "T", ">", "T", "assertNotNull", "(", "T", "argument", ",", "String", "msg", ")", "{", "if", "(", "argument", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "msg", ")", ";", "return", "argument", ";", "}" ]
Throws IllegalArgumentException with the specified error message if the input is null, otherwise return the input as is.
[ "Throws", "IllegalArgumentException", "with", "the", "specified", "error", "message", "if", "the", "input", "is", "null", "otherwise", "return", "the", "input", "as", "is", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/internal/Utils.java#L253-L256
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/Note.java
Note.createResponse
public Note createResponse(String name, String content, boolean personal, Map<String, Object> attributes) { return getInstance().create().note(this, name, content, personal, attributes); }
java
public Note createResponse(String name, String content, boolean personal, Map<String, Object> attributes) { return getInstance().create().note(this, name, content, personal, attributes); }
[ "public", "Note", "createResponse", "(", "String", "name", ",", "String", "content", ",", "boolean", "personal", ",", "Map", "<", "String", ",", "Object", ">", "attributes", ")", "{", "return", "getInstance", "(", ")", ".", "create", "(", ")", ".", "note...
Create a response to this note. @param name The name of the note @param content The content of the note @param personal True if the note is only visible to the currently logged in user @param attributes additional attributes for response to this note. @return a new note
[ "Create", "a", "response", "to", "this", "note", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/Note.java#L135-L137
nguyenq/tess4j
src/main/java/net/sourceforge/tess4j/util/PdfBoxUtilities.java
PdfBoxUtilities.splitPdf
public static void splitPdf(File inputPdfFile, File outputPdfFile, int firstPage, int lastPage) { PDDocument document = null; try { document = PDDocument.load(inputPdfFile); Splitter splitter = new Splitter(); splitter.setStartPage(firstPage); splitter.setEndPage(lastPage); splitter.setSplitAtPage(lastPage - firstPage + 1); List<PDDocument> documents = splitter.split(document); if (documents.size() == 1) { PDDocument outputPdf = documents.get(0); outputPdf.save(outputPdfFile); outputPdf.close(); } else { logger.error("Splitter returned " + documents.size() + " documents rather than expected of 1"); } } catch (IOException ioe) { logger.error("Exception splitting PDF => " + ioe); } finally { if (document != null) { try { document.close(); } catch (Exception e) { } } } }
java
public static void splitPdf(File inputPdfFile, File outputPdfFile, int firstPage, int lastPage) { PDDocument document = null; try { document = PDDocument.load(inputPdfFile); Splitter splitter = new Splitter(); splitter.setStartPage(firstPage); splitter.setEndPage(lastPage); splitter.setSplitAtPage(lastPage - firstPage + 1); List<PDDocument> documents = splitter.split(document); if (documents.size() == 1) { PDDocument outputPdf = documents.get(0); outputPdf.save(outputPdfFile); outputPdf.close(); } else { logger.error("Splitter returned " + documents.size() + " documents rather than expected of 1"); } } catch (IOException ioe) { logger.error("Exception splitting PDF => " + ioe); } finally { if (document != null) { try { document.close(); } catch (Exception e) { } } } }
[ "public", "static", "void", "splitPdf", "(", "File", "inputPdfFile", ",", "File", "outputPdfFile", ",", "int", "firstPage", ",", "int", "lastPage", ")", "{", "PDDocument", "document", "=", "null", ";", "try", "{", "document", "=", "PDDocument", ".", "load", ...
Splits PDF. @param inputPdfFile input file @param outputPdfFile output file @param firstPage begin page @param lastPage end page
[ "Splits", "PDF", "." ]
train
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/PdfBoxUtilities.java#L142-L171
killbill/killbill
util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java
InternalCallContextFactory.createInternalCallContext
public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final CallContext context) { // The callcontext may come from a user API - for security, check we're not doing cross-tenants operations //final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType); //final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext); //Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject), // "tenant of the pointed object (%s) and the callcontext (%s) don't match!", tenantRecordIdFromObject, tenantRecordIdFromContext); final Long tenantRecordId = getTenantRecordIdSafe(context); final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context); return createInternalCallContext(tenantRecordId, accountRecordId, context.getUserName(), context.getCallOrigin(), context.getUserType(), context.getUserToken(), context.getReasonCode(), context.getComments(), context.getCreatedDate(), context.getUpdatedDate()); }
java
public InternalCallContext createInternalCallContext(final UUID objectId, final ObjectType objectType, final CallContext context) { // The callcontext may come from a user API - for security, check we're not doing cross-tenants operations //final Long tenantRecordIdFromObject = retrieveTenantRecordIdFromObject(objectId, objectType); //final Long tenantRecordIdFromContext = getTenantRecordIdSafe(callcontext); //Preconditions.checkState(tenantRecordIdFromContext.equals(tenantRecordIdFromObject), // "tenant of the pointed object (%s) and the callcontext (%s) don't match!", tenantRecordIdFromObject, tenantRecordIdFromContext); final Long tenantRecordId = getTenantRecordIdSafe(context); final Long accountRecordId = getAccountRecordIdSafe(objectId, objectType, context); return createInternalCallContext(tenantRecordId, accountRecordId, context.getUserName(), context.getCallOrigin(), context.getUserType(), context.getUserToken(), context.getReasonCode(), context.getComments(), context.getCreatedDate(), context.getUpdatedDate()); }
[ "public", "InternalCallContext", "createInternalCallContext", "(", "final", "UUID", "objectId", ",", "final", "ObjectType", "objectType", ",", "final", "CallContext", "context", ")", "{", "// The callcontext may come from a user API - for security, check we're not doing cross-tenan...
Create an internal call callcontext from a call callcontext, and retrieving the account_record_id from another table @param objectId the id of the row in the table pointed by object type where to look for account_record_id @param objectType the object type pointed by this objectId @param context original call callcontext @return internal call callcontext from callcontext, with a non null account_record_id (if found)
[ "Create", "an", "internal", "call", "callcontext", "from", "a", "call", "callcontext", "and", "retrieving", "the", "account_record_id", "from", "another", "table" ]
train
https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/util/src/main/java/org/killbill/billing/util/callcontext/InternalCallContextFactory.java#L194-L213
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java
ContentSpecProcessor.doesParentMatch
protected boolean doesParentMatch(final CSNodeWrapper parent, final CSNodeWrapper entityParent) { if (parent != null && entityParent != null) { if (parent.getId() != null && parent.getId().equals(entityParent.getId())) { return true; } else if (parent.getId() == null && entityParent.getId() == null && parent == entityParent) { return true; } else { return false; } } else if (parent == null && entityParent == null) { return true; } else { return false; } }
java
protected boolean doesParentMatch(final CSNodeWrapper parent, final CSNodeWrapper entityParent) { if (parent != null && entityParent != null) { if (parent.getId() != null && parent.getId().equals(entityParent.getId())) { return true; } else if (parent.getId() == null && entityParent.getId() == null && parent == entityParent) { return true; } else { return false; } } else if (parent == null && entityParent == null) { return true; } else { return false; } }
[ "protected", "boolean", "doesParentMatch", "(", "final", "CSNodeWrapper", "parent", ",", "final", "CSNodeWrapper", "entityParent", ")", "{", "if", "(", "parent", "!=", "null", "&&", "entityParent", "!=", "null", ")", "{", "if", "(", "parent", ".", "getId", "...
Checks to see if two parent nodes match @param parent The current parent being used for processing. @param entityParent The processed entities parent. @return True if the two match, otherwise false.
[ "Checks", "to", "see", "if", "two", "parent", "nodes", "match" ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java#L1570-L1584
ag-gipp/MathMLTools
mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java
MathMLConverter.scanFormulaNode
Content scanFormulaNode(Element formulaNode) throws Exception { // first off, try scanning for a semantic split, this indicates multiple semantics Boolean containsSemantic = XMLHelper.getElementB(formulaNode, xPath.compile("//m:semantics")) != null; // check if there is an annotationNode and if so check which semantics are present Element annotationNode = (Element) XMLHelper.getElementB(formulaNode, xPath.compile("//m:annotation-xml")); Boolean containsCMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Content"); Boolean containsPMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Presentation"); // if apply are present, the content semantics is used somewhere NonWhitespaceNodeList applyNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:apply"))); containsCMML |= applyNodes.getLength() > 0; // if mrow nodes are present, the presentation semantic is used somewhere NonWhitespaceNodeList mrowNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:mrow"))); containsPMML |= mrowNodes.getLength() > 0; // TODO the containCMML and -PMML can be more specific, e.g. check if identifiers of each semantics is present if (containsSemantic) { // if semantic separator is present plus one opposite semantic, we assume a LaTeXML produced content return containsCMML || containsPMML ? Content.mathml : Content.unknown; } else { if (containsCMML && containsPMML) { // both semantics without semantic separator suggests broken syntax return Content.unknown; } else if (containsCMML) { return Content.cmml; } else if (containsPMML) { return Content.pmml; } } // next, try to identify latex Element child = (Element) XMLHelper.getElementB(formulaNode, "./*[1]"); // if there is no child node, we currently anticipate some form of latex formula if (child == null && StringUtils.isNotEmpty(formulaNode.getTextContent())) { return Content.latex; } // found nothing comprehensible return Content.unknown; }
java
Content scanFormulaNode(Element formulaNode) throws Exception { // first off, try scanning for a semantic split, this indicates multiple semantics Boolean containsSemantic = XMLHelper.getElementB(formulaNode, xPath.compile("//m:semantics")) != null; // check if there is an annotationNode and if so check which semantics are present Element annotationNode = (Element) XMLHelper.getElementB(formulaNode, xPath.compile("//m:annotation-xml")); Boolean containsCMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Content"); Boolean containsPMML = annotationNode != null && annotationNode.getAttribute("encoding").equals("MathML-Presentation"); // if apply are present, the content semantics is used somewhere NonWhitespaceNodeList applyNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:apply"))); containsCMML |= applyNodes.getLength() > 0; // if mrow nodes are present, the presentation semantic is used somewhere NonWhitespaceNodeList mrowNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(formulaNode, xPath.compile("//m:mrow"))); containsPMML |= mrowNodes.getLength() > 0; // TODO the containCMML and -PMML can be more specific, e.g. check if identifiers of each semantics is present if (containsSemantic) { // if semantic separator is present plus one opposite semantic, we assume a LaTeXML produced content return containsCMML || containsPMML ? Content.mathml : Content.unknown; } else { if (containsCMML && containsPMML) { // both semantics without semantic separator suggests broken syntax return Content.unknown; } else if (containsCMML) { return Content.cmml; } else if (containsPMML) { return Content.pmml; } } // next, try to identify latex Element child = (Element) XMLHelper.getElementB(formulaNode, "./*[1]"); // if there is no child node, we currently anticipate some form of latex formula if (child == null && StringUtils.isNotEmpty(formulaNode.getTextContent())) { return Content.latex; } // found nothing comprehensible return Content.unknown; }
[ "Content", "scanFormulaNode", "(", "Element", "formulaNode", ")", "throws", "Exception", "{", "// first off, try scanning for a semantic split, this indicates multiple semantics", "Boolean", "containsSemantic", "=", "XMLHelper", ".", "getElementB", "(", "formulaNode", ",", "xPa...
Tries to scan and interpret a formula node and guess its content format. @param formulaNode formula to be inspected @return sse {@link Content} format @throws Exception parsing error
[ "Tries", "to", "scan", "and", "interpret", "a", "formula", "node", "and", "guess", "its", "content", "format", "." ]
train
https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L230-L271
mikepenz/Materialize
library/src/main/java/com/mikepenz/materialize/holder/ImageHolder.java
ImageHolder.applyTo
public boolean applyTo(ImageView imageView, String tag) { if (mUri != null) { imageView.setImageURI(mUri); /* if ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme())) { DrawerImageLoader.getInstance().setImage(imageView, mUri, tag); } else { } */ } else if (mIcon != null) { imageView.setImageDrawable(mIcon); } else if (mBitmap != null) { imageView.setImageBitmap(mBitmap); } else if (mIconRes != -1) { imageView.setImageResource(mIconRes); } else { imageView.setImageBitmap(null); return false; } return true; }
java
public boolean applyTo(ImageView imageView, String tag) { if (mUri != null) { imageView.setImageURI(mUri); /* if ("http".equals(mUri.getScheme()) || "https".equals(mUri.getScheme())) { DrawerImageLoader.getInstance().setImage(imageView, mUri, tag); } else { } */ } else if (mIcon != null) { imageView.setImageDrawable(mIcon); } else if (mBitmap != null) { imageView.setImageBitmap(mBitmap); } else if (mIconRes != -1) { imageView.setImageResource(mIconRes); } else { imageView.setImageBitmap(null); return false; } return true; }
[ "public", "boolean", "applyTo", "(", "ImageView", "imageView", ",", "String", "tag", ")", "{", "if", "(", "mUri", "!=", "null", ")", "{", "imageView", ".", "setImageURI", "(", "mUri", ")", ";", "/*\n if (\"http\".equals(mUri.getScheme()) || \"https\".equa...
sets an existing image to the imageView @param imageView @param tag used to identify imageViews and define different placeholders @return true if an image was set
[ "sets", "an", "existing", "image", "to", "the", "imageView" ]
train
https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/holder/ImageHolder.java#L97-L118
TheHortonMachine/hortonmachine
extras/sideprojects/gpextras/src/main/java/org/hortonmachine/gpextras/tiles/MapsforgeTilesGenerator.java
MapsforgeTilesGenerator.getTile4TileCoordinate
public <T> T getTile4TileCoordinate( final int tx, final int ty, int zoom, Class<T> adaptee ) throws IOException { //System.out.println("https://tile.openstreetmap.org/" + zoom + "/" + tx + "/" + ty + ".png"); Tile tile = new Tile(tx, ty, (byte) zoom, tileSize); RendererJob mapGeneratorJob = new RendererJob(tile, mapDataStore, renderTheme, displayModel, scaleFactor, false, false); TileBitmap tb = renderer.executeJob(mapGeneratorJob); if (!(tileCache instanceof InMemoryTileCache)) { tileCache.put(mapGeneratorJob, tb); } if (tb instanceof AwtTileBitmap) { AwtTileBitmap bmp = (AwtTileBitmap) tb; if (bmp != null) { BufferedImage bitmap = AwtGraphicFactory.getBitmap(bmp); if (adaptee.isAssignableFrom(BufferedImage.class)) { return adaptee.cast(bitmap); } else if (adaptee.isAssignableFrom(byte[].class)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bitmap, "png", baos); baos.flush(); byte[] imageInByte = baos.toByteArray(); baos.close(); return adaptee.cast(imageInByte); } } } throw new RuntimeException("Can't handle tilebitmap of type -> " + tb.getClass()); }
java
public <T> T getTile4TileCoordinate( final int tx, final int ty, int zoom, Class<T> adaptee ) throws IOException { //System.out.println("https://tile.openstreetmap.org/" + zoom + "/" + tx + "/" + ty + ".png"); Tile tile = new Tile(tx, ty, (byte) zoom, tileSize); RendererJob mapGeneratorJob = new RendererJob(tile, mapDataStore, renderTheme, displayModel, scaleFactor, false, false); TileBitmap tb = renderer.executeJob(mapGeneratorJob); if (!(tileCache instanceof InMemoryTileCache)) { tileCache.put(mapGeneratorJob, tb); } if (tb instanceof AwtTileBitmap) { AwtTileBitmap bmp = (AwtTileBitmap) tb; if (bmp != null) { BufferedImage bitmap = AwtGraphicFactory.getBitmap(bmp); if (adaptee.isAssignableFrom(BufferedImage.class)) { return adaptee.cast(bitmap); } else if (adaptee.isAssignableFrom(byte[].class)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bitmap, "png", baos); baos.flush(); byte[] imageInByte = baos.toByteArray(); baos.close(); return adaptee.cast(imageInByte); } } } throw new RuntimeException("Can't handle tilebitmap of type -> " + tb.getClass()); }
[ "public", "<", "T", ">", "T", "getTile4TileCoordinate", "(", "final", "int", "tx", ",", "final", "int", "ty", ",", "int", "zoom", ",", "Class", "<", "T", ">", "adaptee", ")", "throws", "IOException", "{", "//System.out.println(\"https://tile.openstreetmap.org/\"...
Get tile data for a given tile schema coordinate. @param tx the x tile index. @param ty the y tile index. @param zoom the zoomlevel @param adaptee the class to adapt to. @return the generated data. @throws IOException
[ "Get", "tile", "data", "for", "a", "given", "tile", "schema", "coordinate", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/extras/sideprojects/gpextras/src/main/java/org/hortonmachine/gpextras/tiles/MapsforgeTilesGenerator.java#L169-L196
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java
MailUtil.sendHtml
public static void sendHtml(String to, String subject, String content, File... files) { send(to, subject, content, true, files); }
java
public static void sendHtml(String to, String subject, String content, File... files) { send(to, subject, content, true, files); }
[ "public", "static", "void", "sendHtml", "(", "String", "to", ",", "String", "subject", ",", "String", "content", ",", "File", "...", "files", ")", "{", "send", "(", "to", ",", "subject", ",", "content", ",", "true", ",", "files", ")", ";", "}" ]
使用配置文件中设置的账户发送HTML邮件,发送给单个或多个收件人<br> 多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔 @param to 收件人 @param subject 标题 @param content 正文 @param files 附件列表 @since 3.2.0
[ "使用配置文件中设置的账户发送HTML邮件,发送给单个或多个收件人<br", ">", "多个收件人可以使用逗号“", "”分隔,也可以通过分号“", ";", "”分隔" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java#L42-L44
bushidowallet/bushido-java-service
bushido-service-lib/src/main/java/com/bccapi/bitlib/StandardTransactionBuilder.java
StandardTransactionBuilder.createUnsignedTransaction
public UnsignedTransaction createUnsignedTransaction(List<UnspentTransactionOutput> unspent, Address changeAddress, long fee, PublicKeyRing keyRing, NetworkParameters network) throws InsufficientFundsException { // Make a copy so we can mutate the list unspent = new LinkedList<UnspentTransactionOutput>(unspent); List<UnspentTransactionOutput> funding = new LinkedList<UnspentTransactionOutput>(); long outputSum = outputSum(); long toSend = fee + outputSum; long found = 0; while (found < toSend) { UnspentTransactionOutput output = extractOldest(unspent); if (output == null) { // We do not have enough funds throw new InsufficientFundsException(outputSum, fee); } found += output.value; funding.add(output); } // We have our funding, calculate change long change = found - toSend; // Get a copy of all outputs List<TransactionOutput> outputs = new LinkedList<TransactionOutput>(_outputs); if (change > 0) { // We have more funds than needed, add an output to our change address outputs.add(createOutput(changeAddress, change)); } return new UnsignedTransaction(outputs, funding, keyRing, network); }
java
public UnsignedTransaction createUnsignedTransaction(List<UnspentTransactionOutput> unspent, Address changeAddress, long fee, PublicKeyRing keyRing, NetworkParameters network) throws InsufficientFundsException { // Make a copy so we can mutate the list unspent = new LinkedList<UnspentTransactionOutput>(unspent); List<UnspentTransactionOutput> funding = new LinkedList<UnspentTransactionOutput>(); long outputSum = outputSum(); long toSend = fee + outputSum; long found = 0; while (found < toSend) { UnspentTransactionOutput output = extractOldest(unspent); if (output == null) { // We do not have enough funds throw new InsufficientFundsException(outputSum, fee); } found += output.value; funding.add(output); } // We have our funding, calculate change long change = found - toSend; // Get a copy of all outputs List<TransactionOutput> outputs = new LinkedList<TransactionOutput>(_outputs); if (change > 0) { // We have more funds than needed, add an output to our change address outputs.add(createOutput(changeAddress, change)); } return new UnsignedTransaction(outputs, funding, keyRing, network); }
[ "public", "UnsignedTransaction", "createUnsignedTransaction", "(", "List", "<", "UnspentTransactionOutput", ">", "unspent", ",", "Address", "changeAddress", ",", "long", "fee", ",", "PublicKeyRing", "keyRing", ",", "NetworkParameters", "network", ")", "throws", "Insuffi...
Create an unsigned transaction with a specific miner fee. Note that specifying a miner fee that is too low may result in hanging transactions that never confirm. @param unspent The list of unspent transaction outputs that can be used as funding @param changeAddress The address to send any change to @param fee The miner fee to pay. Specifying zero may result in hanging transactions. @param keyRing The public key ring matching the unspent outputs @param network The network we are working on @return An unsigned transaction or null if not enough funds were available @throws InsufficientFundsException
[ "Create", "an", "unsigned", "transaction", "with", "a", "specific", "miner", "fee", ".", "Note", "that", "specifying", "a", "miner", "fee", "that", "is", "too", "low", "may", "result", "in", "hanging", "transactions", "that", "never", "confirm", "." ]
train
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-service-lib/src/main/java/com/bccapi/bitlib/StandardTransactionBuilder.java#L256-L285
landawn/AbacusUtil
src/com/landawn/abacus/util/HBaseExecutor.java
HBaseExecutor.exists
boolean exists(final String tableName, final Object rowKey) throws UncheckedIOException { return exists(tableName, AnyGet.of(rowKey)); }
java
boolean exists(final String tableName, final Object rowKey) throws UncheckedIOException { return exists(tableName, AnyGet.of(rowKey)); }
[ "boolean", "exists", "(", "final", "String", "tableName", ",", "final", "Object", "rowKey", ")", "throws", "UncheckedIOException", "{", "return", "exists", "(", "tableName", ",", "AnyGet", ".", "of", "(", "rowKey", ")", ")", ";", "}" ]
And it may cause error because the "Object" is ambiguous to any type.
[ "And", "it", "may", "cause", "error", "because", "the", "Object", "is", "ambiguous", "to", "any", "type", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/HBaseExecutor.java#L726-L728
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java
MultiLayerNetwork.rnnTimeStep
public INDArray rnnTimeStep(INDArray input, MemoryWorkspace outputWorkspace ) { try { boolean inputIs2d = input.rank() == 2; INDArray out = outputOfLayerDetached(false, FwdPassType.RNN_TIMESTEP, layers.length - 1, input, null, null, outputWorkspace); if (inputIs2d && out.rank() == 3 && layers[layers.length - 1].type() == Type.RECURRENT) { //Return 2d output with shape [miniBatchSize,nOut] // instead of 3d output with shape [miniBatchSize,nOut,1] return out.tensorAlongDimension(0, 1, 0); } return out; } catch (OutOfMemoryError e){ CrashReportingUtil.writeMemoryCrashDump(this, e); throw e; } }
java
public INDArray rnnTimeStep(INDArray input, MemoryWorkspace outputWorkspace ) { try { boolean inputIs2d = input.rank() == 2; INDArray out = outputOfLayerDetached(false, FwdPassType.RNN_TIMESTEP, layers.length - 1, input, null, null, outputWorkspace); if (inputIs2d && out.rank() == 3 && layers[layers.length - 1].type() == Type.RECURRENT) { //Return 2d output with shape [miniBatchSize,nOut] // instead of 3d output with shape [miniBatchSize,nOut,1] return out.tensorAlongDimension(0, 1, 0); } return out; } catch (OutOfMemoryError e){ CrashReportingUtil.writeMemoryCrashDump(this, e); throw e; } }
[ "public", "INDArray", "rnnTimeStep", "(", "INDArray", "input", ",", "MemoryWorkspace", "outputWorkspace", ")", "{", "try", "{", "boolean", "inputIs2d", "=", "input", ".", "rank", "(", ")", "==", "2", ";", "INDArray", "out", "=", "outputOfLayerDetached", "(", ...
See {@link #rnnTimeStep(INDArray)} for details<br> If no memory workspace is provided, the output will be detached (not in any workspace).<br> If a memory workspace is provided, the output activation array (i.e., the INDArray returned by this method) will be placed in the specified workspace. This workspace must be opened by the user before calling this method - and the user is responsible for (a) closing this workspace, and (b) ensuring the output array is not used out of scope (i.e., not used after closing the workspace to which it belongs - as this is likely to cause either an exception when used, or a crash). @param input Input activations @param outputWorkspace Output workspace. May be null @return The output/activations from the network (either detached or in the specified workspace if provided)
[ "See", "{", "@link", "#rnnTimeStep", "(", "INDArray", ")", "}", "for", "details<br", ">", "If", "no", "memory", "workspace", "is", "provided", "the", "output", "will", "be", "detached", "(", "not", "in", "any", "workspace", ")", ".", "<br", ">", "If", ...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java#L3062-L3076
aalmiray/Json-lib
src/main/java/net/sf/json/JsonConfig.java
JsonConfig.registerPropertyExclusion
public void registerPropertyExclusion( Class target, String propertyName ) { if( target != null && propertyName != null ) { Set set = (Set) exclusionMap.get( target ); if( set == null ){ set = new HashSet(); exclusionMap.put( target, set ); } if( !set.contains( propertyName )){ set.add(propertyName ); } } }
java
public void registerPropertyExclusion( Class target, String propertyName ) { if( target != null && propertyName != null ) { Set set = (Set) exclusionMap.get( target ); if( set == null ){ set = new HashSet(); exclusionMap.put( target, set ); } if( !set.contains( propertyName )){ set.add(propertyName ); } } }
[ "public", "void", "registerPropertyExclusion", "(", "Class", "target", ",", "String", "propertyName", ")", "{", "if", "(", "target", "!=", "null", "&&", "propertyName", "!=", "null", ")", "{", "Set", "set", "=", "(", "Set", ")", "exclusionMap", ".", "get",...
Registers a exclusion for a target class.<br> [Java -&gt; JSON] @param target the class to use as key @param propertyName the property to be excluded
[ "Registers", "a", "exclusion", "for", "a", "target", "class", ".", "<br", ">", "[", "Java", "-", "&gt", ";", "JSON", "]" ]
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JsonConfig.java#L866-L877
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/style/stylers/Image.java
Image.addToCanvas
public void addToCanvas(float[] tf, com.itextpdf.text.Image img, PdfContentByte canvas) throws DocumentException { if (tf == null) { canvas.addImage(img); } else { canvas.addImage(img, img.getWidth() * tf[TRANSFORMMATRIX.SCALEX.getIndex()], tf[TRANSFORMMATRIX.SHEARX.getIndex()], tf[TRANSFORMMATRIX.SHEARY.getIndex()], img.getHeight() * tf[TRANSFORMMATRIX.SCALEY.getIndex()], img.getAbsoluteX() + tf[TRANSFORMMATRIX.TRANSLATEX.getIndex()], img.getAbsoluteY() + tf[TRANSFORMMATRIX.TRANSLATEY.getIndex()]); } if (getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.DEBUG) && !isDrawShadow()) { if (tf == null) { DebugHelper.debugAnnotation( new Rectangle(img.getAbsoluteX(), img.getAbsoluteY(), img.getAbsoluteX() + img.getWidth(), img.getAbsoluteY() + img.getHeight()), getStyleClass(), getWriter()); } else { DebugHelper.debugAnnotation( new Rectangle( img.getAbsoluteX() + tf[TRANSFORMMATRIX.TRANSLATEX.getIndex()], img.getAbsoluteY() + tf[TRANSFORMMATRIX.TRANSLATEY.getIndex()], img.getAbsoluteX() + tf[TRANSFORMMATRIX.TRANSLATEX.getIndex()] + img.getWidth() * tf[TRANSFORMMATRIX.SCALEX.getIndex()], img.getAbsoluteY() + tf[TRANSFORMMATRIX.TRANSLATEY.getIndex()] + img.getHeight() * tf[TRANSFORMMATRIX.SCALEY.getIndex()] ), getStyleClass(), getWriter()); } } }
java
public void addToCanvas(float[] tf, com.itextpdf.text.Image img, PdfContentByte canvas) throws DocumentException { if (tf == null) { canvas.addImage(img); } else { canvas.addImage(img, img.getWidth() * tf[TRANSFORMMATRIX.SCALEX.getIndex()], tf[TRANSFORMMATRIX.SHEARX.getIndex()], tf[TRANSFORMMATRIX.SHEARY.getIndex()], img.getHeight() * tf[TRANSFORMMATRIX.SCALEY.getIndex()], img.getAbsoluteX() + tf[TRANSFORMMATRIX.TRANSLATEX.getIndex()], img.getAbsoluteY() + tf[TRANSFORMMATRIX.TRANSLATEY.getIndex()]); } if (getSettings().getBooleanProperty(Boolean.FALSE, ReportConstants.DEBUG) && !isDrawShadow()) { if (tf == null) { DebugHelper.debugAnnotation( new Rectangle(img.getAbsoluteX(), img.getAbsoluteY(), img.getAbsoluteX() + img.getWidth(), img.getAbsoluteY() + img.getHeight()), getStyleClass(), getWriter()); } else { DebugHelper.debugAnnotation( new Rectangle( img.getAbsoluteX() + tf[TRANSFORMMATRIX.TRANSLATEX.getIndex()], img.getAbsoluteY() + tf[TRANSFORMMATRIX.TRANSLATEY.getIndex()], img.getAbsoluteX() + tf[TRANSFORMMATRIX.TRANSLATEX.getIndex()] + img.getWidth() * tf[TRANSFORMMATRIX.SCALEX.getIndex()], img.getAbsoluteY() + tf[TRANSFORMMATRIX.TRANSLATEY.getIndex()] + img.getHeight() * tf[TRANSFORMMATRIX.SCALEY.getIndex()] ), getStyleClass(), getWriter()); } } }
[ "public", "void", "addToCanvas", "(", "float", "[", "]", "tf", ",", "com", ".", "itextpdf", ".", "text", ".", "Image", "img", ",", "PdfContentByte", "canvas", ")", "throws", "DocumentException", "{", "if", "(", "tf", "==", "null", ")", "{", "canvas", "...
Adds an image to a canvas applying the transform if it is not null. Calls {@link DebugHelper#debugAnnotation(com.itextpdf.text.Rectangle, java.lang.String, com.itextpdf.text.pdf.PdfWriter) }. @param tf may be null, the transform matrix to apply to the image @param img @param canvas @throws DocumentException
[ "Adds", "an", "image", "to", "a", "canvas", "applying", "the", "transform", "if", "it", "is", "not", "null", ".", "Calls", "{", "@link", "DebugHelper#debugAnnotation", "(", "com", ".", "itextpdf", ".", "text", ".", "Rectangle", "java", ".", "lang", ".", ...
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/stylers/Image.java#L134-L160
segmentio/analytics-android
analytics/src/main/java/com/segment/analytics/ValueMap.java
ValueMap.getEnum
public <T extends Enum<T>> T getEnum(Class<T> enumType, String key) { if (enumType == null) { throw new IllegalArgumentException("enumType may not be null"); } Object value = get(key); if (enumType.isInstance(value)) { //noinspection unchecked return (T) value; } else if (value instanceof String) { String stringValue = (String) value; return Enum.valueOf(enumType, stringValue); } return null; }
java
public <T extends Enum<T>> T getEnum(Class<T> enumType, String key) { if (enumType == null) { throw new IllegalArgumentException("enumType may not be null"); } Object value = get(key); if (enumType.isInstance(value)) { //noinspection unchecked return (T) value; } else if (value instanceof String) { String stringValue = (String) value; return Enum.valueOf(enumType, stringValue); } return null; }
[ "public", "<", "T", "extends", "Enum", "<", "T", ">", ">", "T", "getEnum", "(", "Class", "<", "T", ">", "enumType", ",", "String", "key", ")", "{", "if", "(", "enumType", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"enu...
Returns the value mapped by {@code key} if it exists and is a enum or can be coerced to an enum. Returns null otherwise.
[ "Returns", "the", "value", "mapped", "by", "{" ]
train
https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/ValueMap.java#L292-L305
medallia/Word2VecJava
src/main/java/com/medallia/word2vec/util/ProfilingTimer.java
ProfilingTimer.createSubtasksAndSerialization
public static ProfilingTimer createSubtasksAndSerialization(ByteArrayOutputStream serializationOutput, final String processName, final Object... args) { return create(null, false, serializationOutput, processName, args); }
java
public static ProfilingTimer createSubtasksAndSerialization(ByteArrayOutputStream serializationOutput, final String processName, final Object... args) { return create(null, false, serializationOutput, processName, args); }
[ "public", "static", "ProfilingTimer", "createSubtasksAndSerialization", "(", "ByteArrayOutputStream", "serializationOutput", ",", "final", "String", "processName", ",", "final", "Object", "...", "args", ")", "{", "return", "create", "(", "null", ",", "false", ",", "...
Same as {@link #create(Log, String, Object...)} but includes subtasks, and instead of writing to a log, it outputs the tree in serialized form
[ "Same", "as", "{" ]
train
https://github.com/medallia/Word2VecJava/blob/eb31fbb99ac6bbab82d7f807b3e2240edca50eb7/src/main/java/com/medallia/word2vec/util/ProfilingTimer.java#L182-L184
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java
DockerFileBuilder.write
public File write(File destDir) throws IOException { File target = new File(destDir,"Dockerfile"); FileUtils.fileWrite(target, content()); return target; }
java
public File write(File destDir) throws IOException { File target = new File(destDir,"Dockerfile"); FileUtils.fileWrite(target, content()); return target; }
[ "public", "File", "write", "(", "File", "destDir", ")", "throws", "IOException", "{", "File", "target", "=", "new", "File", "(", "destDir", ",", "\"Dockerfile\"", ")", ";", "FileUtils", ".", "fileWrite", "(", "target", ",", "content", "(", ")", ")", ";",...
Create a DockerFile in the given directory @param destDir directory where to store the dockerfile @return the full path to the docker file @throws IOException if writing fails
[ "Create", "a", "DockerFile", "in", "the", "given", "directory" ]
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java#L83-L87
OpenLiberty/open-liberty
dev/com.ibm.ws.jca.cm/src/com/ibm/ejs/j2c/ConnectionManagerServiceImpl.java
ConnectionManagerServiceImpl.createPoolManager
private void createPoolManager(AbstractConnectionFactoryService svc) throws ResourceException { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(this, tc, "createPoolManager", svc, properties); J2CGlobalConfigProperties gConfigProps = processServerPoolManagerProperties(svc, properties); pm = new PoolManager(svc, null, // dsProps=null misses out on nondeferredreaper, but we don't have that anyways gConfigProps, raClassLoader); if (bndCtx == null) bndCtx = priv.getBundleContext(FrameworkUtil.getBundle(getClass())); try { pmMBean = new PoolManagerMBeanImpl(pm, svc.getFeatureVersion()); pmMBean.register(bndCtx); } catch (MalformedObjectNameException e) { pmMBean = null; throw new ResourceException(e); } if (trace && tc.isEntryEnabled()) Tr.exit(this, tc, "createPoolManager", this); }
java
private void createPoolManager(AbstractConnectionFactoryService svc) throws ResourceException { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(this, tc, "createPoolManager", svc, properties); J2CGlobalConfigProperties gConfigProps = processServerPoolManagerProperties(svc, properties); pm = new PoolManager(svc, null, // dsProps=null misses out on nondeferredreaper, but we don't have that anyways gConfigProps, raClassLoader); if (bndCtx == null) bndCtx = priv.getBundleContext(FrameworkUtil.getBundle(getClass())); try { pmMBean = new PoolManagerMBeanImpl(pm, svc.getFeatureVersion()); pmMBean.register(bndCtx); } catch (MalformedObjectNameException e) { pmMBean = null; throw new ResourceException(e); } if (trace && tc.isEntryEnabled()) Tr.exit(this, tc, "createPoolManager", this); }
[ "private", "void", "createPoolManager", "(", "AbstractConnectionFactoryService", "svc", ")", "throws", "ResourceException", "{", "final", "boolean", "trace", "=", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", ";", "if", "(", "trace", "&&", "tc", ".", "is...
Create and initialize the connection manager/pool configuration based on the connection factory configuration. Precondition: invoker must have the write lock for this connection manager service. @param svc the connection factory service @throws ResourceException if an error occurs
[ "Create", "and", "initialize", "the", "connection", "manager", "/", "pool", "configuration", "based", "on", "the", "connection", "factory", "configuration", ".", "Precondition", ":", "invoker", "must", "have", "the", "write", "lock", "for", "this", "connection", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca.cm/src/com/ibm/ejs/j2c/ConnectionManagerServiceImpl.java#L184-L207
jMetal/jMetal
jmetal-core/src/main/java/org/uma/jmetal/util/SolutionListUtils.java
SolutionListUtils.removeSolutionsFromList
public static <S> void removeSolutionsFromList(List<S> solutionList, int numberOfSolutionsToRemove) { if (solutionList.size() < numberOfSolutionsToRemove) { throw new JMetalException("The list size (" + solutionList.size() + ") is lower than " + "the number of solutions to remove (" + numberOfSolutionsToRemove + ")"); } for (int i = 0; i < numberOfSolutionsToRemove; i++) { solutionList.remove(0); } }
java
public static <S> void removeSolutionsFromList(List<S> solutionList, int numberOfSolutionsToRemove) { if (solutionList.size() < numberOfSolutionsToRemove) { throw new JMetalException("The list size (" + solutionList.size() + ") is lower than " + "the number of solutions to remove (" + numberOfSolutionsToRemove + ")"); } for (int i = 0; i < numberOfSolutionsToRemove; i++) { solutionList.remove(0); } }
[ "public", "static", "<", "S", ">", "void", "removeSolutionsFromList", "(", "List", "<", "S", ">", "solutionList", ",", "int", "numberOfSolutionsToRemove", ")", "{", "if", "(", "solutionList", ".", "size", "(", ")", "<", "numberOfSolutionsToRemove", ")", "{", ...
Removes a number of solutions from a list @param solutionList The list of solutions @param numberOfSolutionsToRemove
[ "Removes", "a", "number", "of", "solutions", "from", "a", "list" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/util/SolutionListUtils.java#L329-L338
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/space/AbstractEventSpace.java
AbstractEventSpace.ensureEventSource
protected void ensureEventSource(UUID eventSource, Event event) { if (event.getSource() == null) { if (eventSource != null) { event.setSource(new Address(getSpaceID(), eventSource)); } else { throw new AssertionError("Every event must have a source"); //$NON-NLS-1$ } } }
java
protected void ensureEventSource(UUID eventSource, Event event) { if (event.getSource() == null) { if (eventSource != null) { event.setSource(new Address(getSpaceID(), eventSource)); } else { throw new AssertionError("Every event must have a source"); //$NON-NLS-1$ } } }
[ "protected", "void", "ensureEventSource", "(", "UUID", "eventSource", ",", "Event", "event", ")", "{", "if", "(", "event", ".", "getSource", "(", ")", "==", "null", ")", "{", "if", "(", "eventSource", "!=", "null", ")", "{", "event", ".", "setSource", ...
Ensure that the given event has a source. @param eventSource the source of the event. @param event the event to emit. @since 2.0.6.0
[ "Ensure", "that", "the", "given", "event", "has", "a", "source", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/space/AbstractEventSpace.java#L154-L162
bmwcarit/joynr
java/javaapi/src/main/java/io/joynr/provider/AbstractSubscriptionPublisher.java
AbstractSubscriptionPublisher.registerAttributeListener
@Override public void registerAttributeListener(String attributeName, AttributeListener attributeListener) { attributeListeners.putIfAbsent(attributeName, new ArrayList<AttributeListener>()); List<AttributeListener> listeners = attributeListeners.get(attributeName); synchronized (listeners) { listeners.add(attributeListener); } }
java
@Override public void registerAttributeListener(String attributeName, AttributeListener attributeListener) { attributeListeners.putIfAbsent(attributeName, new ArrayList<AttributeListener>()); List<AttributeListener> listeners = attributeListeners.get(attributeName); synchronized (listeners) { listeners.add(attributeListener); } }
[ "@", "Override", "public", "void", "registerAttributeListener", "(", "String", "attributeName", ",", "AttributeListener", "attributeListener", ")", "{", "attributeListeners", ".", "putIfAbsent", "(", "attributeName", ",", "new", "ArrayList", "<", "AttributeListener", ">...
Registers an attribute listener that gets notified in case the attribute changes. This is used for on change subscriptions. @param attributeName the attribute name as defined in the Franca model to subscribe to. @param attributeListener the listener to add.
[ "Registers", "an", "attribute", "listener", "that", "gets", "notified", "in", "case", "the", "attribute", "changes", ".", "This", "is", "used", "for", "on", "change", "subscriptions", "." ]
train
https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/javaapi/src/main/java/io/joynr/provider/AbstractSubscriptionPublisher.java#L127-L134
cdk/cdk
tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricTetrahedralEncoderFactory.java
GeometricTetrahedralEncoderFactory.geometric3D
private static GeometricParity geometric3D(int i, int[] adjacent, IAtomContainer container) { IAtom atom = container.getAtom(i); Point3d[] coordinates = new Point3d[4]; // set the forth ligand to centre as default (overwritten if // we have 4 neighbors) if (atom.getPoint3d() != null) coordinates[3] = atom.getPoint3d(); else return null; // for each neighboring atom check if we have 3D coordinates for (int j = 0; j < adjacent.length; j++) { IAtom neighbor = container.getAtom(adjacent[j]); if (neighbor.getPoint3d() != null) coordinates[j] = neighbor.getPoint3d(); else return null; // skip to next atom } // add new 3D stereo encoder return new Tetrahedral3DParity(coordinates); }
java
private static GeometricParity geometric3D(int i, int[] adjacent, IAtomContainer container) { IAtom atom = container.getAtom(i); Point3d[] coordinates = new Point3d[4]; // set the forth ligand to centre as default (overwritten if // we have 4 neighbors) if (atom.getPoint3d() != null) coordinates[3] = atom.getPoint3d(); else return null; // for each neighboring atom check if we have 3D coordinates for (int j = 0; j < adjacent.length; j++) { IAtom neighbor = container.getAtom(adjacent[j]); if (neighbor.getPoint3d() != null) coordinates[j] = neighbor.getPoint3d(); else return null; // skip to next atom } // add new 3D stereo encoder return new Tetrahedral3DParity(coordinates); }
[ "private", "static", "GeometricParity", "geometric3D", "(", "int", "i", ",", "int", "[", "]", "adjacent", ",", "IAtomContainer", "container", ")", "{", "IAtom", "atom", "=", "container", ".", "getAtom", "(", "i", ")", ";", "Point3d", "[", "]", "coordinates...
Create the geometric part of an encoder of 3D configurations @param i the central atom (index) @param adjacent adjacent atoms (indices) @param container container @return geometric parity encoder (or null)
[ "Create", "the", "geometric", "part", "of", "an", "encoder", "of", "3D", "configurations" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricTetrahedralEncoderFactory.java#L185-L210
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/StatementManager.java
StatementManager.getUpdateStatement
public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection()); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Could not build statement ask for", e); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
java
public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException { try { return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection()); } catch (SQLException e) { throw new PersistenceBrokerSQLException("Could not build statement ask for", e); } catch (LookupException e) { throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e); } }
[ "public", "PreparedStatement", "getUpdateStatement", "(", "ClassDescriptor", "cds", ")", "throws", "PersistenceBrokerSQLException", ",", "PersistenceBrokerException", "{", "try", "{", "return", "cds", ".", "getStatementsForClass", "(", "m_conMan", ")", ".", "getUpdateStmt...
return a prepared Update Statement fitting to the given ClassDescriptor
[ "return", "a", "prepared", "Update", "Statement", "fitting", "to", "the", "given", "ClassDescriptor" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/StatementManager.java#L639-L653
fcrepo4/fcrepo4
fcrepo-auth-webac/src/main/java/org/fcrepo/auth/webac/WebACFilter.java
WebACFilter.getHasMemberFromResource
private URI getHasMemberFromResource(final HttpServletRequest request, final FedoraResource resource) { return resource.getTriples(translator(request), of(PROPERTIES)) .filter(triple -> triple.getPredicate().equals(MEMBERSHIP_RESOURCE.asNode()) && triple.getObject() .isURI()) .map(Triple::getObject).map(Node::getURI) .findFirst().map(URI::create).orElse(null); }
java
private URI getHasMemberFromResource(final HttpServletRequest request, final FedoraResource resource) { return resource.getTriples(translator(request), of(PROPERTIES)) .filter(triple -> triple.getPredicate().equals(MEMBERSHIP_RESOURCE.asNode()) && triple.getObject() .isURI()) .map(Triple::getObject).map(Node::getURI) .findFirst().map(URI::create).orElse(null); }
[ "private", "URI", "getHasMemberFromResource", "(", "final", "HttpServletRequest", "request", ",", "final", "FedoraResource", "resource", ")", "{", "return", "resource", ".", "getTriples", "(", "translator", "(", "request", ")", ",", "of", "(", "PROPERTIES", ")", ...
Get ldp:membershipResource from an existing resource @param request the request @param resource the FedoraResource @return URI of the ldp:membershipResource triple or null if not found.
[ "Get", "ldp", ":", "membershipResource", "from", "an", "existing", "resource" ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-auth-webac/src/main/java/org/fcrepo/auth/webac/WebACFilter.java#L693-L699
zaproxy/zaproxy
src/org/apache/commons/httpclient/HttpMethodBase.java
HttpMethodBase.putAllCookiesInASingleHeader
private void putAllCookiesInASingleHeader(String host, CookieSpec matcher, Cookie[] cookies) { LOG.trace("enter putAllCookiesInASingleHeader(String host, CookieSpec matcher, Cookie[] cookies)" ); //use a map to make sure we only have one cookie per name HashMap<String, Cookie> mergedCookies = new HashMap<String, Cookie>(); Header[] cookieLineHeaders = getRequestHeaderGroup().getHeaders(HttpHeader.COOKIE); for (Header cookieLineHeader : cookieLineHeaders) { List<Cookie> cookiesHeader = parseCookieHeader(host, cookieLineHeader.getValue()); for (Cookie cookieHeader: cookiesHeader){ mergedCookies.put(cookieHeader.getName(),cookieHeader); } // clean the header getRequestHeaderGroup().removeHeader(cookieLineHeader); } //add the cookies coming from the state for (Cookie cookie : cookies) { mergedCookies.put(cookie.getName(),cookie); } cookies = mergedCookies.values().toArray(new Cookie[mergedCookies.size()]); String s = matcher.formatCookies(cookies); getRequestHeaderGroup() .addHeader(new Header(HttpHeader.COOKIE, s, true)); }
java
private void putAllCookiesInASingleHeader(String host, CookieSpec matcher, Cookie[] cookies) { LOG.trace("enter putAllCookiesInASingleHeader(String host, CookieSpec matcher, Cookie[] cookies)" ); //use a map to make sure we only have one cookie per name HashMap<String, Cookie> mergedCookies = new HashMap<String, Cookie>(); Header[] cookieLineHeaders = getRequestHeaderGroup().getHeaders(HttpHeader.COOKIE); for (Header cookieLineHeader : cookieLineHeaders) { List<Cookie> cookiesHeader = parseCookieHeader(host, cookieLineHeader.getValue()); for (Cookie cookieHeader: cookiesHeader){ mergedCookies.put(cookieHeader.getName(),cookieHeader); } // clean the header getRequestHeaderGroup().removeHeader(cookieLineHeader); } //add the cookies coming from the state for (Cookie cookie : cookies) { mergedCookies.put(cookie.getName(),cookie); } cookies = mergedCookies.values().toArray(new Cookie[mergedCookies.size()]); String s = matcher.formatCookies(cookies); getRequestHeaderGroup() .addHeader(new Header(HttpHeader.COOKIE, s, true)); }
[ "private", "void", "putAllCookiesInASingleHeader", "(", "String", "host", ",", "CookieSpec", "matcher", ",", "Cookie", "[", "]", "cookies", ")", "{", "LOG", ".", "trace", "(", "\"enter putAllCookiesInASingleHeader(String host, CookieSpec matcher, Cookie[] cookies)\"", ")", ...
Put all the cookies in a single header line. Merge the cookies already present in the request with the cookies coming from the state. @param host the host used with this cookies @param matcher the {@link CookieSpec matcher} used in this context @param cookies associated with the {@link HttpState state}
[ "Put", "all", "the", "cookies", "in", "a", "single", "header", "line", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/apache/commons/httpclient/HttpMethodBase.java#L1390-L1414
resilience4j/resilience4j
resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/CircuitBreakerMetrics.java
CircuitBreakerMetrics.ofIterable
public static CircuitBreakerMetrics ofIterable(String prefix, Iterable<CircuitBreaker> circuitBreakers) { return new CircuitBreakerMetrics(circuitBreakers, prefix); }
java
public static CircuitBreakerMetrics ofIterable(String prefix, Iterable<CircuitBreaker> circuitBreakers) { return new CircuitBreakerMetrics(circuitBreakers, prefix); }
[ "public", "static", "CircuitBreakerMetrics", "ofIterable", "(", "String", "prefix", ",", "Iterable", "<", "CircuitBreaker", ">", "circuitBreakers", ")", "{", "return", "new", "CircuitBreakerMetrics", "(", "circuitBreakers", ",", "prefix", ")", ";", "}" ]
Creates a new instance CircuitBreakerMetrics {@link CircuitBreakerMetrics} with an {@link Iterable} of circuit breakers as a source. @param prefix The prefix. @param circuitBreakers the circuit @return The CircuitBreakerMetrics {@link CircuitBreakerMetrics}.
[ "Creates", "a", "new", "instance", "CircuitBreakerMetrics", "{", "@link", "CircuitBreakerMetrics", "}", "with", "an", "{", "@link", "Iterable", "}", "of", "circuit", "breakers", "as", "a", "source", "." ]
train
https://github.com/resilience4j/resilience4j/blob/fa843d30f531c00f0c3dc218b65a7f2bb51af336/resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/CircuitBreakerMetrics.java#L77-L79
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/utility/Exceptions.java
Exceptions.RuntimeAssertion
public static RuntimeAssertion RuntimeAssertion(Throwable cause, String pattern, Object... parameters) { return strip(new RuntimeAssertion(String.format(pattern, parameters), cause)); }
java
public static RuntimeAssertion RuntimeAssertion(Throwable cause, String pattern, Object... parameters) { return strip(new RuntimeAssertion(String.format(pattern, parameters), cause)); }
[ "public", "static", "RuntimeAssertion", "RuntimeAssertion", "(", "Throwable", "cause", ",", "String", "pattern", ",", "Object", "...", "parameters", ")", "{", "return", "strip", "(", "new", "RuntimeAssertion", "(", "String", ".", "format", "(", "pattern", ",", ...
Generate a {@link RuntimeAssertion} @param cause Existing {@link Throwable} to wrap in a new {@code IllegalArgumentException} @param pattern {@link String#format(String, Object...) String.format()} pattern @param parameters {@code String.format()} parameters @return A new {@code IllegalArgumentException}
[ "Generate", "a", "{", "@link", "RuntimeAssertion", "}" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/utility/Exceptions.java#L89-L93
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.installationTemplate_templateName_partitionScheme_schemeName_hardwareRaid_POST
public void installationTemplate_templateName_partitionScheme_schemeName_hardwareRaid_POST(String templateName, String schemeName, String[] disks, OvhTemplateOsHardwareRaidEnum mode, String name, Long step) throws IOException { String qPath = "/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/hardwareRaid"; StringBuilder sb = path(qPath, templateName, schemeName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "disks", disks); addBody(o, "mode", mode); addBody(o, "name", name); addBody(o, "step", step); exec(qPath, "POST", sb.toString(), o); }
java
public void installationTemplate_templateName_partitionScheme_schemeName_hardwareRaid_POST(String templateName, String schemeName, String[] disks, OvhTemplateOsHardwareRaidEnum mode, String name, Long step) throws IOException { String qPath = "/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/hardwareRaid"; StringBuilder sb = path(qPath, templateName, schemeName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "disks", disks); addBody(o, "mode", mode); addBody(o, "name", name); addBody(o, "step", step); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "installationTemplate_templateName_partitionScheme_schemeName_hardwareRaid_POST", "(", "String", "templateName", ",", "String", "schemeName", ",", "String", "[", "]", "disks", ",", "OvhTemplateOsHardwareRaidEnum", "mode", ",", "String", "name", ",", "Long"...
Add an hardware RAID in this partitioning scheme REST: POST /me/installationTemplate/{templateName}/partitionScheme/{schemeName}/hardwareRaid @param step [required] Specifies the creation order of the hardware RAID @param disks [required] Disk list. Syntax is cX:dY for disks and [cX:dY, cX:dY] for groups. With X and Y resp. the controler id and the disk id. @param mode [required] RAID mode @param name [required] Hardware RAID name @param templateName [required] This template name @param schemeName [required] name of this partitioning scheme
[ "Add", "an", "hardware", "RAID", "in", "this", "partitioning", "scheme" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L3569-L3578
citrusframework/citrus
modules/citrus-selenium/src/main/java/com/consol/citrus/selenium/endpoint/SeleniumBrowser.java
SeleniumBrowser.storeFile
public String storeFile(Resource file) { try { File newFile = new File(temporaryStorage.toFile(), file.getFilename()); log.info("Store file " + file + " to " + newFile); FileUtils.copyFile(file.getFile(), newFile); return newFile.getCanonicalPath(); } catch (IOException e) { throw new CitrusRuntimeException("Failed to store file: " + file, e); } }
java
public String storeFile(Resource file) { try { File newFile = new File(temporaryStorage.toFile(), file.getFilename()); log.info("Store file " + file + " to " + newFile); FileUtils.copyFile(file.getFile(), newFile); return newFile.getCanonicalPath(); } catch (IOException e) { throw new CitrusRuntimeException("Failed to store file: " + file, e); } }
[ "public", "String", "storeFile", "(", "Resource", "file", ")", "{", "try", "{", "File", "newFile", "=", "new", "File", "(", "temporaryStorage", ".", "toFile", "(", ")", ",", "file", ".", "getFilename", "(", ")", ")", ";", "log", ".", "info", "(", "\"...
Deploy resource object from resource folder and return path of deployed file @param file Resource to deploy to temporary storage @return String containing the filename to which the file is uploaded to.
[ "Deploy", "resource", "object", "from", "resource", "folder", "and", "return", "path", "of", "deployed", "file" ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-selenium/src/main/java/com/consol/citrus/selenium/endpoint/SeleniumBrowser.java#L161-L173
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java
BytecodeUtils.doIsAssignableFrom
private static boolean doIsAssignableFrom(Type left, Type right, boolean failOpen) { if (left.equals(right)) { return true; } if (left.getSort() != right.getSort()) { return false; } if (left.getSort() != Type.OBJECT) { return false; // all other sorts require exact equality (even arrays) } // for object types we really need to know type hierarchy information to test for whether // right is assignable to left. Optional<Class<?>> leftClass = objectTypeToClassCache.getUnchecked(left); Optional<Class<?>> rightClass = objectTypeToClassCache.getUnchecked(right); if (!leftClass.isPresent() || !rightClass.isPresent()) { // This means one of the types being compared is a generated object. So we can't easily check // it. Just delegate responsibility to the verifier. return failOpen; } return leftClass.get().isAssignableFrom(rightClass.get()); }
java
private static boolean doIsAssignableFrom(Type left, Type right, boolean failOpen) { if (left.equals(right)) { return true; } if (left.getSort() != right.getSort()) { return false; } if (left.getSort() != Type.OBJECT) { return false; // all other sorts require exact equality (even arrays) } // for object types we really need to know type hierarchy information to test for whether // right is assignable to left. Optional<Class<?>> leftClass = objectTypeToClassCache.getUnchecked(left); Optional<Class<?>> rightClass = objectTypeToClassCache.getUnchecked(right); if (!leftClass.isPresent() || !rightClass.isPresent()) { // This means one of the types being compared is a generated object. So we can't easily check // it. Just delegate responsibility to the verifier. return failOpen; } return leftClass.get().isAssignableFrom(rightClass.get()); }
[ "private", "static", "boolean", "doIsAssignableFrom", "(", "Type", "left", ",", "Type", "right", ",", "boolean", "failOpen", ")", "{", "if", "(", "left", ".", "equals", "(", "right", ")", ")", "{", "return", "true", ";", "}", "if", "(", "left", ".", ...
Checks if {@code left} is assignable from {@code right}, however if we don't have information about one of the types then this returns {@code failOpen}.
[ "Checks", "if", "{" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/BytecodeUtils.java#L192-L212
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerInputBuffer.java
DerInputBuffer.getUTCTime
public Date getUTCTime(int len) throws IOException { if (len > available()) throw new IOException("short read of DER UTC Time"); if (len < 11 || len > 17) throw new IOException("DER UTC Time length error"); return getTime(len, false); }
java
public Date getUTCTime(int len) throws IOException { if (len > available()) throw new IOException("short read of DER UTC Time"); if (len < 11 || len > 17) throw new IOException("DER UTC Time length error"); return getTime(len, false); }
[ "public", "Date", "getUTCTime", "(", "int", "len", ")", "throws", "IOException", "{", "if", "(", "len", ">", "available", "(", ")", ")", "throw", "new", "IOException", "(", "\"short read of DER UTC Time\"", ")", ";", "if", "(", "len", "<", "11", "||", "l...
Returns the UTC Time value that takes up the specified number of bytes in this buffer. @param len the number of bytes to use
[ "Returns", "the", "UTC", "Time", "value", "that", "takes", "up", "the", "specified", "number", "of", "bytes", "in", "this", "buffer", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerInputBuffer.java#L261-L269
apiman/apiman
common/es/src/main/java/io/apiman/common/es/util/ESUtils.java
ESUtils.queryWithEscapedArgs
public static String queryWithEscapedArgs(String query, String... args) { Object[] sanitisedArgs = Arrays.stream(args) .parallel() .map(ESUtils::escape) .toArray(); return replaceQMark(query, sanitisedArgs); }
java
public static String queryWithEscapedArgs(String query, String... args) { Object[] sanitisedArgs = Arrays.stream(args) .parallel() .map(ESUtils::escape) .toArray(); return replaceQMark(query, sanitisedArgs); }
[ "public", "static", "String", "queryWithEscapedArgs", "(", "String", "query", ",", "String", "...", "args", ")", "{", "Object", "[", "]", "sanitisedArgs", "=", "Arrays", ".", "stream", "(", "args", ")", ".", "parallel", "(", ")", ".", "map", "(", "ESUtil...
An ES query with escaped arguments: <p> Use the SQL convention of ? (e.g. "foo": ?, "bar": ?). <p> A {@link Number} instance will be unquoted, all other types will be quoted. @param query ES query @param args the corresponding positional arguments {0} ... {n-1} @return query with escaped variables substituted in
[ "An", "ES", "query", "with", "escaped", "arguments", ":", "<p", ">", "Use", "the", "SQL", "convention", "of", "?", "(", "e", ".", "g", ".", "foo", ":", "?", "bar", ":", "?", ")", ".", "<p", ">", "A", "{", "@link", "Number", "}", "instance", "wi...
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/es/src/main/java/io/apiman/common/es/util/ESUtils.java#L55-L61
alkacon/opencms-core
src/org/opencms/workplace/comparison/CmsHistoryListUtil.java
CmsHistoryListUtil.getHistoryLink
public static String getHistoryLink(CmsObject cms, CmsUUID structureId, String version) { String resourcePath; CmsResource resource; try { resource = cms.readResource(structureId, CmsResourceFilter.ALL); resourcePath = resource.getRootPath(); } catch (CmsException e) { throw new CmsRuntimeException(e.getMessageContainer(), e); } StringBuffer link = new StringBuffer(); link.append(CmsHistoryResourceHandler.HISTORY_HANDLER); link.append(resourcePath); link.append('?'); link.append(CmsHistoryResourceHandler.PARAM_VERSION); link.append('='); link.append(CmsHistoryListUtil.getVersion("" + version)); return link.toString(); }
java
public static String getHistoryLink(CmsObject cms, CmsUUID structureId, String version) { String resourcePath; CmsResource resource; try { resource = cms.readResource(structureId, CmsResourceFilter.ALL); resourcePath = resource.getRootPath(); } catch (CmsException e) { throw new CmsRuntimeException(e.getMessageContainer(), e); } StringBuffer link = new StringBuffer(); link.append(CmsHistoryResourceHandler.HISTORY_HANDLER); link.append(resourcePath); link.append('?'); link.append(CmsHistoryResourceHandler.PARAM_VERSION); link.append('='); link.append(CmsHistoryListUtil.getVersion("" + version)); return link.toString(); }
[ "public", "static", "String", "getHistoryLink", "(", "CmsObject", "cms", ",", "CmsUUID", "structureId", ",", "String", "version", ")", "{", "String", "resourcePath", ";", "CmsResource", "resource", ";", "try", "{", "resource", "=", "cms", ".", "readResource", ...
Returns the link to an historical file.<p> @param cms the cms context @param structureId the structure id of the file @param version the version number of the file @return the link to an historical file
[ "Returns", "the", "link", "to", "an", "historical", "file", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/comparison/CmsHistoryListUtil.java#L85-L103
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringParser.java
StringParser.parseByte
public static byte parseByte (@Nullable final Object aObject, @Nonnegative final int nRadix, final byte nDefault) { if (aObject == null) return nDefault; if (aObject instanceof Number) return ((Number) aObject).byteValue (); return parseByte (aObject.toString (), nRadix, nDefault); }
java
public static byte parseByte (@Nullable final Object aObject, @Nonnegative final int nRadix, final byte nDefault) { if (aObject == null) return nDefault; if (aObject instanceof Number) return ((Number) aObject).byteValue (); return parseByte (aObject.toString (), nRadix, nDefault); }
[ "public", "static", "byte", "parseByte", "(", "@", "Nullable", "final", "Object", "aObject", ",", "@", "Nonnegative", "final", "int", "nRadix", ",", "final", "byte", "nDefault", ")", "{", "if", "(", "aObject", "==", "null", ")", "return", "nDefault", ";", ...
Parse the given {@link Object} as byte with the specified radix. @param aObject The Object to parse. May be <code>null</code>. @param nRadix The radix to use. Must be &ge; {@link Character#MIN_RADIX} and &le; {@link Character#MAX_RADIX}. @param nDefault The default value to be returned if the passed object could not be converted to a valid value. @return The default value if the string does not represent a valid value.
[ "Parse", "the", "given", "{", "@link", "Object", "}", "as", "byte", "with", "the", "specified", "radix", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L277-L284
networknt/light-4j
utility/src/main/java/com/networknt/utility/RegExUtils.java
RegExUtils.removePattern
public static String removePattern(final String text, final String regex) { return replacePattern(text, regex, StringUtils.EMPTY); }
java
public static String removePattern(final String text, final String regex) { return replacePattern(text, regex, StringUtils.EMPTY); }
[ "public", "static", "String", "removePattern", "(", "final", "String", "text", ",", "final", "String", "regex", ")", "{", "return", "replacePattern", "(", "text", ",", "regex", ",", "StringUtils", ".", "EMPTY", ")", ";", "}" ]
<p>Removes each substring of the source String that matches the given regular expression using the DOTALL option.</p> This call is a {@code null} safe equivalent to: <ul> <li>{@code text.replaceAll(&quot;(?s)&quot; + regex, StringUtils.EMPTY)}</li> <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(StringUtils.EMPTY)}</li> </ul> <p>A {@code null} reference passed to this method is a no-op.</p> <pre> StringUtils.removePattern(null, *) = null StringUtils.removePattern("any", (String) null) = "any" StringUtils.removePattern("A&lt;__&gt;\n&lt;__&gt;B", "&lt;.*&gt;") = "AB" StringUtils.removePattern("ABCabc123", "[a-z]") = "ABC123" </pre> @param text the source string @param regex the regular expression to which this string is to be matched @return The resulting {@code String} @see #replacePattern(String, String, String) @see String#replaceAll(String, String) @see Pattern#DOTALL
[ "<p", ">", "Removes", "each", "substring", "of", "the", "source", "String", "that", "matches", "the", "given", "regular", "expression", "using", "the", "DOTALL", "option", ".", "<", "/", "p", ">" ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/RegExUtils.java#L218-L220
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/termofuse/TermOfUsePanel.java
TermOfUsePanel.newLegalReferencesPanel
protected Component newLegalReferencesPanel(final String id, final IModel<HeaderContentListModelBean> model) { return new LegalReferencesPanel(id, Model.of(model.getObject())); }
java
protected Component newLegalReferencesPanel(final String id, final IModel<HeaderContentListModelBean> model) { return new LegalReferencesPanel(id, Model.of(model.getObject())); }
[ "protected", "Component", "newLegalReferencesPanel", "(", "final", "String", "id", ",", "final", "IModel", "<", "HeaderContentListModelBean", ">", "model", ")", "{", "return", "new", "LegalReferencesPanel", "(", "id", ",", "Model", ".", "of", "(", "model", ".", ...
Factory method for creating the new {@link Component} for the legal references. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Component} for the legal references. @param id the id @param model the model @return the new {@link Component} for the legal references
[ "Factory", "method", "for", "creating", "the", "new", "{", "@link", "Component", "}", "for", "the", "legal", "references", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "derived", "classes", "and", "can", "be", "overridde...
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/termofuse/TermOfUsePanel.java#L295-L299
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlWriter.java
HtmlWriter.addStyles
public void addStyles(HtmlStyle style, StringBuilder vars) { vars.append("var ").append(style).append(" = \"").append(style) .append("\";").append(DocletConstants.NL); }
java
public void addStyles(HtmlStyle style, StringBuilder vars) { vars.append("var ").append(style).append(" = \"").append(style) .append("\";").append(DocletConstants.NL); }
[ "public", "void", "addStyles", "(", "HtmlStyle", "style", ",", "StringBuilder", "vars", ")", "{", "vars", ".", "append", "(", "\"var \"", ")", ".", "append", "(", "style", ")", ".", "append", "(", "\" = \\\"\"", ")", ".", "append", "(", "style", ")", "...
Adds javascript style variables to the document. @param style style to be added as a javascript variable @param vars variable string to which the style variable will be added
[ "Adds", "javascript", "style", "variables", "to", "the", "document", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlWriter.java#L381-L384
mgm-tp/jfunk
jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
WebDriverTool.openNewWindow
public String openNewWindow(final String url, final long timeoutSeconds) { String oldHandle = openNewWindow(timeoutSeconds); get(url); return oldHandle; }
java
public String openNewWindow(final String url, final long timeoutSeconds) { String oldHandle = openNewWindow(timeoutSeconds); get(url); return oldHandle; }
[ "public", "String", "openNewWindow", "(", "final", "String", "url", ",", "final", "long", "timeoutSeconds", ")", "{", "String", "oldHandle", "=", "openNewWindow", "(", "timeoutSeconds", ")", ";", "get", "(", "url", ")", ";", "return", "oldHandle", ";", "}" ]
Opens a new window, switches to it, and loads the given URL in the new window. @param url the url to open @param timeoutSeconds the timeout in seconds to wait for the new window to open @return the handle of the window that opened the new window
[ "Opens", "a", "new", "window", "switches", "to", "it", "and", "loads", "the", "given", "URL", "in", "the", "new", "window", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java#L791-L795
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/EntityListenersMetadata.java
EntityListenersMetadata.put
public void put(CallbackType callbackType, CallbackMetadata callbackMetadata) { if (callbacks == null) { callbacks = new EnumMap<>(CallbackType.class); } List<CallbackMetadata> callbackMetadataList = callbacks.get(callbackType); if (callbackMetadataList == null) { callbackMetadataList = new ArrayList<>(); callbacks.put(callbackType, callbackMetadataList); } callbackMetadataList.add(callbackMetadata); }
java
public void put(CallbackType callbackType, CallbackMetadata callbackMetadata) { if (callbacks == null) { callbacks = new EnumMap<>(CallbackType.class); } List<CallbackMetadata> callbackMetadataList = callbacks.get(callbackType); if (callbackMetadataList == null) { callbackMetadataList = new ArrayList<>(); callbacks.put(callbackType, callbackMetadataList); } callbackMetadataList.add(callbackMetadata); }
[ "public", "void", "put", "(", "CallbackType", "callbackType", ",", "CallbackMetadata", "callbackMetadata", ")", "{", "if", "(", "callbacks", "==", "null", ")", "{", "callbacks", "=", "new", "EnumMap", "<>", "(", "CallbackType", ".", "class", ")", ";", "}", ...
Adds the given CallbackEventMetadata. @param callbackType the callback type @param callbackMetadata the metadata of the callback
[ "Adds", "the", "given", "CallbackEventMetadata", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/EntityListenersMetadata.java#L122-L132
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AttributeConstraintRule.java
AttributeConstraintRule.validateFuture
private boolean validateFuture(Object validationObject, Annotation annotate) { if (checkNullObject(validationObject)) { return true; } int res = 0; if (validationObject.getClass().isAssignableFrom(java.util.Date.class)) { Date today = new Date(); Date futureDate = (Date) validationObject; res = futureDate.compareTo(today); } else if (validationObject.getClass().isAssignableFrom(java.util.Calendar.class)) { Calendar cal = Calendar.getInstance(); Calendar futureDate = (Calendar) validationObject; res = futureDate.compareTo(cal); } // else // { // //ruleExceptionHandler(((Future) annotate).message()); // throw new RuleValidationException(((Future) // annotate).message()); // } if (res <= 0) { throwValidationException(((Future) annotate).message()); } return true; }
java
private boolean validateFuture(Object validationObject, Annotation annotate) { if (checkNullObject(validationObject)) { return true; } int res = 0; if (validationObject.getClass().isAssignableFrom(java.util.Date.class)) { Date today = new Date(); Date futureDate = (Date) validationObject; res = futureDate.compareTo(today); } else if (validationObject.getClass().isAssignableFrom(java.util.Calendar.class)) { Calendar cal = Calendar.getInstance(); Calendar futureDate = (Calendar) validationObject; res = futureDate.compareTo(cal); } // else // { // //ruleExceptionHandler(((Future) annotate).message()); // throw new RuleValidationException(((Future) // annotate).message()); // } if (res <= 0) { throwValidationException(((Future) annotate).message()); } return true; }
[ "private", "boolean", "validateFuture", "(", "Object", "validationObject", ",", "Annotation", "annotate", ")", "{", "if", "(", "checkNullObject", "(", "validationObject", ")", ")", "{", "return", "true", ";", "}", "int", "res", "=", "0", ";", "if", "(", "v...
Checks whether a given date is that in future or not @param validationObject @param annotate @return
[ "Checks", "whether", "a", "given", "date", "is", "that", "in", "future", "or", "not" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AttributeConstraintRule.java#L316-L352
amzn/ion-java
src/com/amazon/ion/impl/lite/IonLoaderLite.java
IonLoaderLite.load_helper
private IonDatagramLite load_helper(IonReader reader) throws IOException { IonDatagramLite datagram = new IonDatagramLite(_system, _catalog); IonWriter writer = _Private_IonWriterFactory.makeWriter(datagram); writer.writeValues(reader); return datagram; }
java
private IonDatagramLite load_helper(IonReader reader) throws IOException { IonDatagramLite datagram = new IonDatagramLite(_system, _catalog); IonWriter writer = _Private_IonWriterFactory.makeWriter(datagram); writer.writeValues(reader); return datagram; }
[ "private", "IonDatagramLite", "load_helper", "(", "IonReader", "reader", ")", "throws", "IOException", "{", "IonDatagramLite", "datagram", "=", "new", "IonDatagramLite", "(", "_system", ",", "_catalog", ")", ";", "IonWriter", "writer", "=", "_Private_IonWriterFactory"...
This doesn't wrap IOException because some callers need to propagate it. @return a new datagram; not null.
[ "This", "doesn", "t", "wrap", "IOException", "because", "some", "callers", "need", "to", "propagate", "it", "." ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/lite/IonLoaderLite.java#L76-L83
greatman/craftconomy3
src/main/java/com/greatmancode/craftconomy3/account/Account.java
Account.getBalance
public double getBalance(String world, String currencyName) { double balance = Double.MIN_NORMAL; if (!Common.getInstance().getWorldGroupManager().worldGroupExist(world)) { world = Common.getInstance().getWorldGroupManager().getWorldGroupName(world); } Currency currency = Common.getInstance().getCurrencyManager().getCurrency(currencyName); if (currency != null) { if (!hasInfiniteMoney()) { balance = Common.getInstance().getStorageHandler().getStorageEngine().getBalance(this, currency, world); } else { balance = Double.MAX_VALUE; } } return format(balance); }
java
public double getBalance(String world, String currencyName) { double balance = Double.MIN_NORMAL; if (!Common.getInstance().getWorldGroupManager().worldGroupExist(world)) { world = Common.getInstance().getWorldGroupManager().getWorldGroupName(world); } Currency currency = Common.getInstance().getCurrencyManager().getCurrency(currencyName); if (currency != null) { if (!hasInfiniteMoney()) { balance = Common.getInstance().getStorageHandler().getStorageEngine().getBalance(this, currency, world); } else { balance = Double.MAX_VALUE; } } return format(balance); }
[ "public", "double", "getBalance", "(", "String", "world", ",", "String", "currencyName", ")", "{", "double", "balance", "=", "Double", ".", "MIN_NORMAL", ";", "if", "(", "!", "Common", ".", "getInstance", "(", ")", ".", "getWorldGroupManager", "(", ")", "....
Get's the player balance. Sends double.MIN_NORMAL in case of a error @param world The world / world group to search in @param currencyName The currency Name @return The balance. If the account has infinite money. Double.MAX_VALUE is returned.
[ "Get", "s", "the", "player", "balance", ".", "Sends", "double", ".", "MIN_NORMAL", "in", "case", "of", "a", "error" ]
train
https://github.com/greatman/craftconomy3/blob/51b1b3de7d039e20c7418d1e70b8c4b02b8cf840/src/main/java/com/greatmancode/craftconomy3/account/Account.java#L121-L135
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/matrix/TransformStatistics.java
TransformStatistics.extractStatistics
public static MatrixStatistics extractStatistics( File inputMatrixFile, Format format) { return extractStatistics(inputMatrixFile, format, false, false); }
java
public static MatrixStatistics extractStatistics( File inputMatrixFile, Format format) { return extractStatistics(inputMatrixFile, format, false, false); }
[ "public", "static", "MatrixStatistics", "extractStatistics", "(", "File", "inputMatrixFile", ",", "Format", "format", ")", "{", "return", "extractStatistics", "(", "inputMatrixFile", ",", "format", ",", "false", ",", "false", ")", ";", "}" ]
Extracts the full row, column, and matrix summations based on entries in the given {@link Matrix} file. @param inputMatrixFfile a {@link Matrix} file to sum over @param format the matrix {@link Format} of {@code inputMatrixFile} @return a {@link MatrixStatistics} instance containing the summations
[ "Extracts", "the", "full", "row", "column", "and", "matrix", "summations", "based", "on", "entries", "in", "the", "given", "{", "@link", "Matrix", "}", "file", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/matrix/TransformStatistics.java#L124-L127
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/ObjectField.java
ObjectField.setupDefaultView
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { return null; }
java
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { return null; }
[ "public", "ScreenComponent", "setupDefaultView", "(", "ScreenLoc", "itsLocation", ",", "ComponentParent", "targetScreen", ",", "Convert", "converter", ",", "int", "iDisplayFieldDesc", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", ...
Set up the default screen control for this field. You should override this method depending of the concrete display type. @param itsLocation Location of this component on screen (ie., GridBagConstraint). @param targetScreen Where to place this component (ie., Parent screen or GridBagLayout). @param converter The converter to set the screenfield to. @param iDisplayFieldDesc Display the label? (optional). @return Return the component or ScreenField that is created for this field.
[ "Set", "up", "the", "default", "screen", "control", "for", "this", "field", ".", "You", "should", "override", "this", "method", "depending", "of", "the", "concrete", "display", "type", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/ObjectField.java#L105-L108
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.createCompositeEntityRoleAsync
public Observable<UUID> createCompositeEntityRoleAsync(UUID appId, String versionId, UUID cEntityId, CreateCompositeEntityRoleOptionalParameter createCompositeEntityRoleOptionalParameter) { return createCompositeEntityRoleWithServiceResponseAsync(appId, versionId, cEntityId, createCompositeEntityRoleOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
java
public Observable<UUID> createCompositeEntityRoleAsync(UUID appId, String versionId, UUID cEntityId, CreateCompositeEntityRoleOptionalParameter createCompositeEntityRoleOptionalParameter) { return createCompositeEntityRoleWithServiceResponseAsync(appId, versionId, cEntityId, createCompositeEntityRoleOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
[ "public", "Observable", "<", "UUID", ">", "createCompositeEntityRoleAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "cEntityId", ",", "CreateCompositeEntityRoleOptionalParameter", "createCompositeEntityRoleOptionalParameter", ")", "{", "return", "crea...
Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param cEntityId The composite entity extractor ID. @param createCompositeEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object
[ "Create", "an", "entity", "role", "for", "an", "entity", "in", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L8901-L8908
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/cache/JMapperCache.java
JMapperCache.getMapper
public static <D,S> IJMapper<D, S> getMapper(final Class<D> destination,final Class<S> source,final JMapperAPI api) { return getMapper(destination,source,api.toXStream().toString()); }
java
public static <D,S> IJMapper<D, S> getMapper(final Class<D> destination,final Class<S> source,final JMapperAPI api) { return getMapper(destination,source,api.toXStream().toString()); }
[ "public", "static", "<", "D", ",", "S", ">", "IJMapper", "<", "D", ",", "S", ">", "getMapper", "(", "final", "Class", "<", "D", ">", "destination", ",", "final", "Class", "<", "S", ">", "source", ",", "final", "JMapperAPI", "api", ")", "{", "return...
Returns an instance of JMapper from cache if exists, in alternative a new instance. <br>Taking configuration by API. @param destination the Destination Class @param source the Source Class @param api JMapperAPI configuration @param <D> Destination class @param <S> Source Class @return the mapper instance
[ "Returns", "an", "instance", "of", "JMapper", "from", "cache", "if", "exists", "in", "alternative", "a", "new", "instance", ".", "<br", ">", "Taking", "configuration", "by", "API", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/cache/JMapperCache.java#L88-L90
apache/groovy
src/main/java/org/codehaus/groovy/syntax/Types.java
Types.lookup
public static int lookup(String text, int filter) { int type = UNKNOWN; if (LOOKUP.containsKey(text)) { type = LOOKUP.get(text); if (filter != UNKNOWN && !ofType(type, filter)) { type = UNKNOWN; } } return type; }
java
public static int lookup(String text, int filter) { int type = UNKNOWN; if (LOOKUP.containsKey(text)) { type = LOOKUP.get(text); if (filter != UNKNOWN && !ofType(type, filter)) { type = UNKNOWN; } } return type; }
[ "public", "static", "int", "lookup", "(", "String", "text", ",", "int", "filter", ")", "{", "int", "type", "=", "UNKNOWN", ";", "if", "(", "LOOKUP", ".", "containsKey", "(", "text", ")", ")", "{", "type", "=", "LOOKUP", ".", "get", "(", "text", ")"...
Returns the type for the specified symbol/keyword text. Returns UNKNOWN if the text isn't found. You can filter finds on a type.
[ "Returns", "the", "type", "for", "the", "specified", "symbol", "/", "keyword", "text", ".", "Returns", "UNKNOWN", "if", "the", "text", "isn", "t", "found", ".", "You", "can", "filter", "finds", "on", "a", "type", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/syntax/Types.java#L1052-L1063
Headline/CleverBotAPI-Java
src/main/java/com/michaelwflaherty/cleverbotapi/CleverBotQuery.java
CleverBotQuery.formatRequest
private static String formatRequest(String url, String key, String phrase, String conversationID) { String formattedPhrase = phrase.replaceAll("\\s+", "+"); return String.format("%s%s&input=%s&wrapper=Headline22JavaAPI%s", url, key, formattedPhrase, ((conversationID.equals("")) ? "" : ("&cs=" + conversationID))); }
java
private static String formatRequest(String url, String key, String phrase, String conversationID) { String formattedPhrase = phrase.replaceAll("\\s+", "+"); return String.format("%s%s&input=%s&wrapper=Headline22JavaAPI%s", url, key, formattedPhrase, ((conversationID.equals("")) ? "" : ("&cs=" + conversationID))); }
[ "private", "static", "String", "formatRequest", "(", "String", "url", ",", "String", "key", ",", "String", "phrase", ",", "String", "conversationID", ")", "{", "String", "formattedPhrase", "=", "phrase", ".", "replaceAll", "(", "\"\\\\s+\"", ",", "\"+\"", ")",...
URL request formater @param url starting url to connect to @param key API key (cleverbot.com/api) @param phrase input to be sent to CleverBot servers @param conversationID unique conversation identifer @return String object containing properly formatted URL
[ "URL", "request", "formater" ]
train
https://github.com/Headline/CleverBotAPI-Java/blob/fe6818362eec687cdfeb7ee8deb4d2ee19611676/src/main/java/com/michaelwflaherty/cleverbotapi/CleverBotQuery.java#L206-L210
AltBeacon/android-beacon-library
lib/src/main/java/org/altbeacon/beacon/Identifier.java
Identifier.fromLong
public static Identifier fromLong(long longValue, int desiredByteLength) { if (desiredByteLength < 0) { throw new IllegalArgumentException("Identifier length must be > 0."); } byte[] newValue = new byte[desiredByteLength]; for (int i = desiredByteLength-1; i >= 0; i--) { newValue[i] = (byte) (longValue & 0xff); longValue = longValue >> 8; } return new Identifier(newValue); }
java
public static Identifier fromLong(long longValue, int desiredByteLength) { if (desiredByteLength < 0) { throw new IllegalArgumentException("Identifier length must be > 0."); } byte[] newValue = new byte[desiredByteLength]; for (int i = desiredByteLength-1; i >= 0; i--) { newValue[i] = (byte) (longValue & 0xff); longValue = longValue >> 8; } return new Identifier(newValue); }
[ "public", "static", "Identifier", "fromLong", "(", "long", "longValue", ",", "int", "desiredByteLength", ")", "{", "if", "(", "desiredByteLength", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Identifier length must be > 0.\"", ")", ";", ...
Creates an Identifer backed by an array of length desiredByteLength @param longValue a long to put into the identifier @param desiredByteLength how many bytes to make the identifier @return
[ "Creates", "an", "Identifer", "backed", "by", "an", "array", "of", "length", "desiredByteLength" ]
train
https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/Identifier.java#L130-L140
seedstack/shed
src/main/java/org/seedstack/shed/exception/BaseException.java
BaseException.createNew
public static <E extends BaseException> E createNew(Class<E> exceptionType, ErrorCode errorCode) { try { Constructor<E> constructor = exceptionType.getDeclaredConstructor(ErrorCode.class); constructor.setAccessible(true); return constructor.newInstance(errorCode); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new IllegalArgumentException(exceptionType.getCanonicalName() + " must implement a constructor with ErrorCode as parameter", e); } }
java
public static <E extends BaseException> E createNew(Class<E> exceptionType, ErrorCode errorCode) { try { Constructor<E> constructor = exceptionType.getDeclaredConstructor(ErrorCode.class); constructor.setAccessible(true); return constructor.newInstance(errorCode); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new IllegalArgumentException(exceptionType.getCanonicalName() + " must implement a constructor with ErrorCode as parameter", e); } }
[ "public", "static", "<", "E", "extends", "BaseException", ">", "E", "createNew", "(", "Class", "<", "E", ">", "exceptionType", ",", "ErrorCode", "errorCode", ")", "{", "try", "{", "Constructor", "<", "E", ">", "constructor", "=", "exceptionType", ".", "get...
Create a new subclass of BaseException from an {@link ErrorCode}. @param exceptionType the subclass of BaseException to create. @param errorCode the error code to set. @param <E> the subtype. @return the created BaseException.
[ "Create", "a", "new", "subclass", "of", "BaseException", "from", "an", "{", "@link", "ErrorCode", "}", "." ]
train
https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/exception/BaseException.java#L101-L111
astrapi69/jaulp-wicket
jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/request/mapper/HighScoreRequestMapper.java
HighScoreRequestMapper.initializeRequestMappers
private Collection<RequestMapperBean> initializeRequestMappers(final Request request) { final Set<RequestMapperBean> mapperBeans = new TreeSet<>(getComparator()); for (final IRequestMapper requestMapper : this.requestMappers) { mapperBeans.add( new RequestMapperBean(requestMapper, requestMapper.getCompatibilityScore(request))); } return mapperBeans; }
java
private Collection<RequestMapperBean> initializeRequestMappers(final Request request) { final Set<RequestMapperBean> mapperBeans = new TreeSet<>(getComparator()); for (final IRequestMapper requestMapper : this.requestMappers) { mapperBeans.add( new RequestMapperBean(requestMapper, requestMapper.getCompatibilityScore(request))); } return mapperBeans; }
[ "private", "Collection", "<", "RequestMapperBean", ">", "initializeRequestMappers", "(", "final", "Request", "request", ")", "{", "final", "Set", "<", "RequestMapperBean", ">", "mapperBeans", "=", "new", "TreeSet", "<>", "(", "getComparator", "(", ")", ")", ";",...
Initialize request mappers. @param request the request @return the collection
[ "Initialize", "request", "mappers", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/request/mapper/HighScoreRequestMapper.java#L116-L125
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java
ResourceLoader.getConfigBufferedReader
public static BufferedReader getConfigBufferedReader(final String resource, final String encoding) throws IOException { return new BufferedReader(getConfigInputStreamReader(resource, encoding)); }
java
public static BufferedReader getConfigBufferedReader(final String resource, final String encoding) throws IOException { return new BufferedReader(getConfigInputStreamReader(resource, encoding)); }
[ "public", "static", "BufferedReader", "getConfigBufferedReader", "(", "final", "String", "resource", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "return", "new", "BufferedReader", "(", "getConfigInputStreamReader", "(", "resource", ",", "enc...
Loads a resource as {@link BufferedReader} relative {@link #getConfigDir()}. @param resource The resource to be loaded. @param encoding The encoding to use @return The reader
[ "Loads", "a", "resource", "as", "{", "@link", "BufferedReader", "}", "relative", "{", "@link", "#getConfigDir", "()", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java#L129-L131
Stratio/bdt
src/main/java/com/stratio/qa/specs/DatabaseSpec.java
DatabaseSpec.insertData
@Given("^I insert in keyspace '(.+?)' and table '(.+?)' with:$") public void insertData(String keyspace, String table, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getPickleRows().get(0).getCells().size(); Map<String, Object> fields = new HashMap<String, Object>(); for (int e = 1; e < datatable.getPickleRows().size(); e++) { for (int i = 0; i < attrLength; i++) { fields.put(datatable.getPickleRows().get(0).getCells().get(i).getValue(), datatable.getPickleRows().get(e).getCells().get(i).getValue()); } commonspec.getCassandraClient().insertData(keyspace + "." + table, fields); } } catch (Exception e) { commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } }
java
@Given("^I insert in keyspace '(.+?)' and table '(.+?)' with:$") public void insertData(String keyspace, String table, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getPickleRows().get(0).getCells().size(); Map<String, Object> fields = new HashMap<String, Object>(); for (int e = 1; e < datatable.getPickleRows().size(); e++) { for (int i = 0; i < attrLength; i++) { fields.put(datatable.getPickleRows().get(0).getCells().get(i).getValue(), datatable.getPickleRows().get(e).getCells().get(i).getValue()); } commonspec.getCassandraClient().insertData(keyspace + "." + table, fields); } } catch (Exception e) { commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } }
[ "@", "Given", "(", "\"^I insert in keyspace '(.+?)' and table '(.+?)' with:$\"", ")", "public", "void", "insertData", "(", "String", "keyspace", ",", "String", "table", ",", "DataTable", "datatable", ")", "{", "try", "{", "commonspec", ".", "getCassandraClient", "(", ...
Insert Data @param table Cassandra table @param datatable datatable used for parsing elements @param keyspace Cassandra keyspace
[ "Insert", "Data" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L193-L212
code4everything/util
src/main/java/com/zhazhapan/util/FileExecutor.java
FileExecutor.copyDirectories
public static void copyDirectories(String[] directories, String[] destinationDirectories) throws IOException { copyDirectories(getFiles(directories), getFiles(destinationDirectories)); }
java
public static void copyDirectories(String[] directories, String[] destinationDirectories) throws IOException { copyDirectories(getFiles(directories), getFiles(destinationDirectories)); }
[ "public", "static", "void", "copyDirectories", "(", "String", "[", "]", "directories", ",", "String", "[", "]", "destinationDirectories", ")", "throws", "IOException", "{", "copyDirectories", "(", "getFiles", "(", "directories", ")", ",", "getFiles", "(", "desti...
批量复制文件夹 @param directories 文件夹路径数组 @param destinationDirectories 目标文件夹路径数组,与文件夹一一对应 @throws IOException 异常
[ "批量复制文件夹" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L409-L411
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/StringFunctions.java
StringFunctions.ltrim
public static Expression ltrim(Expression expression, String characters) { return x("LTRIM(" + expression.toString() + ", \"" + characters + "\")"); }
java
public static Expression ltrim(Expression expression, String characters) { return x("LTRIM(" + expression.toString() + ", \"" + characters + "\")"); }
[ "public", "static", "Expression", "ltrim", "(", "Expression", "expression", ",", "String", "characters", ")", "{", "return", "x", "(", "\"LTRIM(\"", "+", "expression", ".", "toString", "(", ")", "+", "\", \\\"\"", "+", "characters", "+", "\"\\\")\"", ")", ";...
Returned expression results in the string with all leading chars removed (any char in the characters string).
[ "Returned", "expression", "results", "in", "the", "string", "with", "all", "leading", "chars", "removed", "(", "any", "char", "in", "the", "characters", "string", ")", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/StringFunctions.java#L130-L132
cdk/cdk
app/depict/src/main/java/org/openscience/cdk/depict/Depiction.java
Depiction.writeTo
public final void writeTo(String fmt, String path) throws IOException { writeTo(fmt, new File(replaceTildeWithHomeDir(ensureSuffix(path, fmt)))); }
java
public final void writeTo(String fmt, String path) throws IOException { writeTo(fmt, new File(replaceTildeWithHomeDir(ensureSuffix(path, fmt)))); }
[ "public", "final", "void", "writeTo", "(", "String", "fmt", ",", "String", "path", ")", "throws", "IOException", "{", "writeTo", "(", "fmt", ",", "new", "File", "(", "replaceTildeWithHomeDir", "(", "ensureSuffix", "(", "path", ",", "fmt", ")", ")", ")", ...
Write the depiction to the provided file path. @param fmt format @param path output destination path @throws IOException depiction could not be written, low level IO problem @see #listFormats()
[ "Write", "the", "depiction", "to", "the", "provided", "file", "path", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/app/depict/src/main/java/org/openscience/cdk/depict/Depiction.java#L280-L282
michael-rapp/AndroidPreferenceActivity
example/src/main/java/de/mrapp/android/preference/activity/example/MainActivity.java
MainActivity.createDynamicPreferenceButtonListener
private OnClickListener createDynamicPreferenceButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { Intent intent = new Intent(MainActivity.this, DynamicSettingsActivity.class); startActivity(intent); } }; }
java
private OnClickListener createDynamicPreferenceButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { Intent intent = new Intent(MainActivity.this, DynamicSettingsActivity.class); startActivity(intent); } }; }
[ "private", "OnClickListener", "createDynamicPreferenceButtonListener", "(", ")", "{", "return", "new", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "final", "View", "v", ")", "{", "Intent", "intent", "=", "new", "Intent", ...
Creates and returns a listener, which allows to show a {@link PreferenceActivity}, whose headers can be added or removed dynamically at runtime. @return The listener, which has been created, as an instance of the type {@link OnClickListener}
[ "Creates", "and", "returns", "a", "listener", "which", "allows", "to", "show", "a", "{", "@link", "PreferenceActivity", "}", "whose", "headers", "can", "be", "added", "or", "removed", "dynamically", "at", "runtime", "." ]
train
https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/example/src/main/java/de/mrapp/android/preference/activity/example/MainActivity.java#L127-L137
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java
TileBoundingBoxUtils.getTileGrid
public static TileGrid getTileGrid(BoundingBox webMercatorBoundingBox, int zoom) { int tilesPerSide = tilesPerSide(zoom); double tileSize = tileSize(tilesPerSide); int minX = (int) ((webMercatorBoundingBox.getMinLongitude() + ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) / tileSize); double tempMaxX = (webMercatorBoundingBox.getMaxLongitude() + ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) / tileSize; int maxX = (int) (tempMaxX - ProjectionConstants.WEB_MERCATOR_PRECISION); maxX = Math.min(maxX, tilesPerSide - 1); int minY = (int) (((webMercatorBoundingBox.getMaxLatitude() - ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) * -1) / tileSize); double tempMaxY = ((webMercatorBoundingBox.getMinLatitude() - ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) * -1) / tileSize; int maxY = (int) (tempMaxY - ProjectionConstants.WEB_MERCATOR_PRECISION); maxY = Math.min(maxY, tilesPerSide - 1); TileGrid grid = new TileGrid(minX, minY, maxX, maxY); return grid; }
java
public static TileGrid getTileGrid(BoundingBox webMercatorBoundingBox, int zoom) { int tilesPerSide = tilesPerSide(zoom); double tileSize = tileSize(tilesPerSide); int minX = (int) ((webMercatorBoundingBox.getMinLongitude() + ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) / tileSize); double tempMaxX = (webMercatorBoundingBox.getMaxLongitude() + ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) / tileSize; int maxX = (int) (tempMaxX - ProjectionConstants.WEB_MERCATOR_PRECISION); maxX = Math.min(maxX, tilesPerSide - 1); int minY = (int) (((webMercatorBoundingBox.getMaxLatitude() - ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) * -1) / tileSize); double tempMaxY = ((webMercatorBoundingBox.getMinLatitude() - ProjectionConstants.WEB_MERCATOR_HALF_WORLD_WIDTH) * -1) / tileSize; int maxY = (int) (tempMaxY - ProjectionConstants.WEB_MERCATOR_PRECISION); maxY = Math.min(maxY, tilesPerSide - 1); TileGrid grid = new TileGrid(minX, minY, maxX, maxY); return grid; }
[ "public", "static", "TileGrid", "getTileGrid", "(", "BoundingBox", "webMercatorBoundingBox", ",", "int", "zoom", ")", "{", "int", "tilesPerSide", "=", "tilesPerSide", "(", "zoom", ")", ";", "double", "tileSize", "=", "tileSize", "(", "tilesPerSide", ")", ";", ...
Get the tile grid that includes the entire tile bounding box @param webMercatorBoundingBox web mercator bounding box @param zoom zoom level @return tile grid
[ "Get", "the", "tile", "grid", "that", "includes", "the", "entire", "tile", "bounding", "box" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java#L594-L615
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/color/ColorYuv.java
ColorYuv.rgbToYuv
public static <T extends ImageGray<T>> void rgbToYuv(Planar<T> rgb , Planar<T> yuv) { yuv.reshape(rgb.width,rgb.height,3); if( rgb.getBandType() == GrayF32.class ) { if (BoofConcurrency.USE_CONCURRENT) { ImplColorYuv_MT.rgbToYuv_F32((Planar<GrayF32>) rgb, (Planar<GrayF32>) yuv); } else { ImplColorYuv.rgbToYuv_F32((Planar<GrayF32>) rgb, (Planar<GrayF32>) yuv); } } else { throw new IllegalArgumentException("Unsupported band type "+rgb.getBandType().getSimpleName()); } }
java
public static <T extends ImageGray<T>> void rgbToYuv(Planar<T> rgb , Planar<T> yuv) { yuv.reshape(rgb.width,rgb.height,3); if( rgb.getBandType() == GrayF32.class ) { if (BoofConcurrency.USE_CONCURRENT) { ImplColorYuv_MT.rgbToYuv_F32((Planar<GrayF32>) rgb, (Planar<GrayF32>) yuv); } else { ImplColorYuv.rgbToYuv_F32((Planar<GrayF32>) rgb, (Planar<GrayF32>) yuv); } } else { throw new IllegalArgumentException("Unsupported band type "+rgb.getBandType().getSimpleName()); } }
[ "public", "static", "<", "T", "extends", "ImageGray", "<", "T", ">", ">", "void", "rgbToYuv", "(", "Planar", "<", "T", ">", "rgb", ",", "Planar", "<", "T", ">", "yuv", ")", "{", "yuv", ".", "reshape", "(", "rgb", ".", "width", ",", "rgb", ".", ...
Convert a 3-channel {@link Planar} image from RGB into YUV. If integer then YCbCr and not YUV. NOTE: Input and output image can be the same instance. @param rgb (Input) RGB encoded image @param yuv (Output) YUV encoded image
[ "Convert", "a", "3", "-", "channel", "{", "@link", "Planar", "}", "image", "from", "RGB", "into", "YUV", ".", "If", "integer", "then", "YCbCr", "and", "not", "YUV", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/color/ColorYuv.java#L176-L189
belaban/JGroups
src/org/jgroups/protocols/pbcast/Merger.java
Merger.handleMergeRequest
public void handleMergeRequest(Address sender, MergeId merge_id, Collection<? extends Address> mbrs) { try { _handleMergeRequest(sender, merge_id, mbrs); } catch(Throwable t) { log.error("%s: failure handling the merge request: %s", gms.local_addr, t.getMessage()); cancelMerge(merge_id); sendMergeRejectedResponse(sender, merge_id); } }
java
public void handleMergeRequest(Address sender, MergeId merge_id, Collection<? extends Address> mbrs) { try { _handleMergeRequest(sender, merge_id, mbrs); } catch(Throwable t) { log.error("%s: failure handling the merge request: %s", gms.local_addr, t.getMessage()); cancelMerge(merge_id); sendMergeRejectedResponse(sender, merge_id); } }
[ "public", "void", "handleMergeRequest", "(", "Address", "sender", ",", "MergeId", "merge_id", ",", "Collection", "<", "?", "extends", "Address", ">", "mbrs", ")", "{", "try", "{", "_handleMergeRequest", "(", "sender", ",", "merge_id", ",", "mbrs", ")", ";", ...
Get the view and digest and send back both (MergeData) in the form of a MERGE_RSP to the sender. If a merge is already in progress, send back a MergeData with the merge_rejected field set to true. @param sender The address of the merge leader @param merge_id The merge ID @param mbrs The set of members from which we expect responses. Guaranteed to be non-null
[ "Get", "the", "view", "and", "digest", "and", "send", "back", "both", "(", "MergeData", ")", "in", "the", "form", "of", "a", "MERGE_RSP", "to", "the", "sender", ".", "If", "a", "merge", "is", "already", "in", "progress", "send", "back", "a", "MergeData...
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/pbcast/Merger.java#L111-L120
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/HighTideShell.java
HighTideShell.showConfig
private int showConfig(String cmd, String argv[], int startindex) throws IOException { int exitCode = 0; PolicyInfo[] all = hightidenode.getAllPolicies(); for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } return exitCode; }
java
private int showConfig(String cmd, String argv[], int startindex) throws IOException { int exitCode = 0; PolicyInfo[] all = hightidenode.getAllPolicies(); for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } return exitCode; }
[ "private", "int", "showConfig", "(", "String", "cmd", ",", "String", "argv", "[", "]", ",", "int", "startindex", ")", "throws", "IOException", "{", "int", "exitCode", "=", "0", ";", "PolicyInfo", "[", "]", "all", "=", "hightidenode", ".", "getAllPolicies",...
Apply operation specified by 'cmd' on all parameters starting from argv[startindex].
[ "Apply", "operation", "specified", "by", "cmd", "on", "all", "parameters", "starting", "from", "argv", "[", "startindex", "]", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/HighTideShell.java#L241-L248
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java
CommerceSubscriptionEntryPersistenceImpl.findAll
@Override public List<CommerceSubscriptionEntry> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CommerceSubscriptionEntry> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CommerceSubscriptionEntry", ">", "findAll", "(", ")", "{", "return", "findAll", "(", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the commerce subscription entries. @return the commerce subscription entries
[ "Returns", "all", "the", "commerce", "subscription", "entries", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java#L4125-L4128
hibernate/hibernate-ogm
mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java
MongoDBDialect.insertDocument
private Document insertDocument(EntityKeyMetadata entityKeyMetadata, Tuple tuple, TupleContext tupleContext ) { Document dbObject = objectForInsert( tuple, ( (MongoDBTupleSnapshot) tuple.getSnapshot() ).getDbObject() ); getCollection( entityKeyMetadata.getTable(), tupleContext.getTupleTypeContext().getOptionsContext() ).insertOne( dbObject ); return dbObject; }
java
private Document insertDocument(EntityKeyMetadata entityKeyMetadata, Tuple tuple, TupleContext tupleContext ) { Document dbObject = objectForInsert( tuple, ( (MongoDBTupleSnapshot) tuple.getSnapshot() ).getDbObject() ); getCollection( entityKeyMetadata.getTable(), tupleContext.getTupleTypeContext().getOptionsContext() ).insertOne( dbObject ); return dbObject; }
[ "private", "Document", "insertDocument", "(", "EntityKeyMetadata", "entityKeyMetadata", ",", "Tuple", "tuple", ",", "TupleContext", "tupleContext", ")", "{", "Document", "dbObject", "=", "objectForInsert", "(", "tuple", ",", "(", "(", "MongoDBTupleSnapshot", ")", "t...
/* InsertOne the tuple and return an object containing the id in the field ID_FIELDNAME
[ "/", "*", "InsertOne", "the", "tuple", "and", "return", "an", "object", "containing", "the", "id", "in", "the", "field", "ID_FIELDNAME" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java#L545-L549
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/DistributionSetSelectComboBox.java
DistributionSetSelectComboBox.buildFilter
@Override protected Filter buildFilter(final String filterString, final FilteringMode filteringMode) { if (filterStringIsNotChanged(filterString)) { return null; } final Filter filter = super.buildFilter(filterString, filteringMode); refreshContainerIfFilterStringBecomesEmpty(filterString); lastFilterString = filterString; return filter; }
java
@Override protected Filter buildFilter(final String filterString, final FilteringMode filteringMode) { if (filterStringIsNotChanged(filterString)) { return null; } final Filter filter = super.buildFilter(filterString, filteringMode); refreshContainerIfFilterStringBecomesEmpty(filterString); lastFilterString = filterString; return filter; }
[ "@", "Override", "protected", "Filter", "buildFilter", "(", "final", "String", "filterString", ",", "final", "FilteringMode", "filteringMode", ")", "{", "if", "(", "filterStringIsNotChanged", "(", "filterString", ")", ")", "{", "return", "null", ";", "}", "final...
Overriden not to update the filter when the filterstring (value of combobox input) was not changed. Otherwise, it would lead to additional database requests during combobox page change while scrolling instead of retreiving items from container cache. @param filterString value of combobox input @param filteringMode the filtering mode (starts_with, contains) @return SimpleStringFilter to transfer filterstring in container
[ "Overriden", "not", "to", "update", "the", "filter", "when", "the", "filterstring", "(", "value", "of", "combobox", "input", ")", "was", "not", "changed", ".", "Otherwise", "it", "would", "lead", "to", "additional", "database", "requests", "during", "combobox"...
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/DistributionSetSelectComboBox.java#L277-L289
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/TypeCache.java
TypeCache.findOrInsert
public Class<?> findOrInsert(ClassLoader classLoader, T key, Callable<Class<?>> lazy, Object monitor) { Class<?> type = find(classLoader, key); if (type != null) { return type; } else { synchronized (monitor) { return findOrInsert(classLoader, key, lazy); } } }
java
public Class<?> findOrInsert(ClassLoader classLoader, T key, Callable<Class<?>> lazy, Object monitor) { Class<?> type = find(classLoader, key); if (type != null) { return type; } else { synchronized (monitor) { return findOrInsert(classLoader, key, lazy); } } }
[ "public", "Class", "<", "?", ">", "findOrInsert", "(", "ClassLoader", "classLoader", ",", "T", "key", ",", "Callable", "<", "Class", "<", "?", ">", ">", "lazy", ",", "Object", "monitor", ")", "{", "Class", "<", "?", ">", "type", "=", "find", "(", "...
Finds an existing type or inserts a new one if the previous type was not found. @param classLoader The class loader for which this type is stored. @param key The key for the type in question. @param lazy A lazy creator for the type to insert of no previous type was stored in the cache. @param monitor A monitor to lock before creating the lazy type. @return The lazily created type or a previously submitted type for the same class loader and key combination.
[ "Finds", "an", "existing", "type", "or", "inserts", "a", "new", "one", "if", "the", "previous", "type", "was", "not", "found", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/TypeCache.java#L168-L177
shrinkwrap/descriptors
metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/xslt/XsltTransformer.java
XsltTransformer.applyParameters
private static void applyParameters(final Transformer transformer, final Map<String, String> parameters) { final Set<String> keys = parameters.keySet(); for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) { final String key = iterator.next(); transformer.setParameter(key, parameters.get(key)); } }
java
private static void applyParameters(final Transformer transformer, final Map<String, String> parameters) { final Set<String> keys = parameters.keySet(); for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) { final String key = iterator.next(); transformer.setParameter(key, parameters.get(key)); } }
[ "private", "static", "void", "applyParameters", "(", "final", "Transformer", "transformer", ",", "final", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "final", "Set", "<", "String", ">", "keys", "=", "parameters", ".", "keySet", "(", "...
Applies all key/value pairs as defined by the given <code>Map</code> to the given <code>Transformer</code> instance. @param transformer @param parameters
[ "Applies", "all", "key", "/", "value", "pairs", "as", "defined", "by", "the", "given", "<code", ">", "Map<", "/", "code", ">", "to", "the", "given", "<code", ">", "Transformer<", "/", "code", ">", "instance", "." ]
train
https://github.com/shrinkwrap/descriptors/blob/023ba080e6396b9f4dd8275dc4e5c0ebb6b5e6ba/metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/xslt/XsltTransformer.java#L109-L115
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java
PageInBrowserStats.getWindowLastLoadTime
public long getWindowLastLoadTime(final String intervalName, final TimeUnit unit) { return unit.transformMillis(windowLastLoadTime.getValueAsLong(intervalName)); }
java
public long getWindowLastLoadTime(final String intervalName, final TimeUnit unit) { return unit.transformMillis(windowLastLoadTime.getValueAsLong(intervalName)); }
[ "public", "long", "getWindowLastLoadTime", "(", "final", "String", "intervalName", ",", "final", "TimeUnit", "unit", ")", "{", "return", "unit", ".", "transformMillis", "(", "windowLastLoadTime", ".", "getValueAsLong", "(", "intervalName", ")", ")", ";", "}" ]
Returns web page last load time for given interval and {@link TimeUnit}. @param intervalName name of the interval @param unit {@link TimeUnit} @return web page last load time
[ "Returns", "web", "page", "last", "load", "time", "for", "given", "interval", "and", "{", "@link", "TimeUnit", "}", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java#L199-L201
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java
ByteBuffer.circularByteBufferInitializer
private void circularByteBufferInitializer(int bufferCapacity, int bufferSize, int readPosition, int writePosition) { if (bufferCapacity < 2) { throw new IllegalArgumentException("Buffer capacity must be greater than 2 !"); } if ((bufferSize < 0) || (bufferSize > bufferCapacity)) { throw new IllegalArgumentException("Buffer size must be a value between 0 and "+bufferCapacity+" !"); } if ((readPosition < 0) || (readPosition > bufferSize)) { throw new IllegalArgumentException("Buffer read position must be a value between 0 and "+bufferSize+" !"); } if ((writePosition < 0) || (writePosition > bufferSize)) { throw new IllegalArgumentException("Buffer write position must be a value between 0 and "+bufferSize+" !"); } this.buffer = new byte[bufferCapacity]; this.currentBufferSize = bufferSize; this.currentReadPosition = readPosition; this.currentWritePosition = writePosition; }
java
private void circularByteBufferInitializer(int bufferCapacity, int bufferSize, int readPosition, int writePosition) { if (bufferCapacity < 2) { throw new IllegalArgumentException("Buffer capacity must be greater than 2 !"); } if ((bufferSize < 0) || (bufferSize > bufferCapacity)) { throw new IllegalArgumentException("Buffer size must be a value between 0 and "+bufferCapacity+" !"); } if ((readPosition < 0) || (readPosition > bufferSize)) { throw new IllegalArgumentException("Buffer read position must be a value between 0 and "+bufferSize+" !"); } if ((writePosition < 0) || (writePosition > bufferSize)) { throw new IllegalArgumentException("Buffer write position must be a value between 0 and "+bufferSize+" !"); } this.buffer = new byte[bufferCapacity]; this.currentBufferSize = bufferSize; this.currentReadPosition = readPosition; this.currentWritePosition = writePosition; }
[ "private", "void", "circularByteBufferInitializer", "(", "int", "bufferCapacity", ",", "int", "bufferSize", ",", "int", "readPosition", ",", "int", "writePosition", ")", "{", "if", "(", "bufferCapacity", "<", "2", ")", "{", "throw", "new", "IllegalArgumentExceptio...
Intializes the new CircularByteBuffer with all parameters that characterize a CircularByteBuffer. @param bufferCapacity the buffer capacity. Must be >= 2. @param bufferSize the buffer initial size. Must be in [0, bufferCapacity]. @param readPosition the buffer initial read position. Must be in [0, bufferSize] @param writePosition the buffer initial write position. Must be in [0, bufferSize]
[ "Intializes", "the", "new", "CircularByteBuffer", "with", "all", "parameters", "that", "characterize", "a", "CircularByteBuffer", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java#L243-L260
mboudreau/Alternator
src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBReflector.java
DynamoDBReflector.parseBoolean
private boolean parseBoolean(String s) { if ( "1".equals(s) ) { return true; } else if ( "0".equals(s) ) { return false; } else { throw new IllegalArgumentException("Expected 1 or 0 for boolean value, was " + s); } }
java
private boolean parseBoolean(String s) { if ( "1".equals(s) ) { return true; } else if ( "0".equals(s) ) { return false; } else { throw new IllegalArgumentException("Expected 1 or 0 for boolean value, was " + s); } }
[ "private", "boolean", "parseBoolean", "(", "String", "s", ")", "{", "if", "(", "\"1\"", ".", "equals", "(", "s", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "\"0\"", ".", "equals", "(", "s", ")", ")", "{", "return", "false", ";"...
Attempts to parse the string given as a boolean and return its value. Throws an exception if the value is anything other than 0 or 1.
[ "Attempts", "to", "parse", "the", "string", "given", "as", "a", "boolean", "and", "return", "its", "value", ".", "Throws", "an", "exception", "if", "the", "value", "is", "anything", "other", "than", "0", "or", "1", "." ]
train
https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBReflector.java#L811-L819
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java
JenkinsServer.createJob
public JenkinsServer createJob(FolderJob folder, String jobName, String jobXml, Boolean crumbFlag) throws IOException { client.post_xml(UrlUtils.toBaseUrl(folder) + "createItem?name=" + EncodingUtils.formParameter(jobName), jobXml, crumbFlag); return this; }
java
public JenkinsServer createJob(FolderJob folder, String jobName, String jobXml, Boolean crumbFlag) throws IOException { client.post_xml(UrlUtils.toBaseUrl(folder) + "createItem?name=" + EncodingUtils.formParameter(jobName), jobXml, crumbFlag); return this; }
[ "public", "JenkinsServer", "createJob", "(", "FolderJob", "folder", ",", "String", "jobName", ",", "String", "jobXml", ",", "Boolean", "crumbFlag", ")", "throws", "IOException", "{", "client", ".", "post_xml", "(", "UrlUtils", ".", "toBaseUrl", "(", "folder", ...
Create a job on the server using the provided xml and in the provided folder @param folder {@link FolderJob} @param jobName name of the job to be created. @param jobXml the <code>config.xml</code> which should be used to create the job. @param crumbFlag <code>true</code> to add <b>crumbIssuer</b> <code>false</code> otherwise. @throws IOException in case of an error.
[ "Create", "a", "job", "on", "the", "server", "using", "the", "provided", "xml", "and", "in", "the", "provided", "folder" ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L388-L392
groupon/monsoon
processors/wavefront/src/main/java/com/groupon/lex/metrics/processors/wavefront/WavefrontStrings.java
WavefrontStrings.wavefrontLine
public static Optional<String> wavefrontLine(DateTime ts, GroupName group, MetricName metric, MetricValue metric_value) { return wavefrontValue(metric_value) .map(value -> { final Map<String, String> tag_map = tags(group.getTags()); final String source = extractTagSource(tag_map); // Modifies tag_map. return wavefrontLine(ts, group.getPath(), metric, value, source, tag_map); }); }
java
public static Optional<String> wavefrontLine(DateTime ts, GroupName group, MetricName metric, MetricValue metric_value) { return wavefrontValue(metric_value) .map(value -> { final Map<String, String> tag_map = tags(group.getTags()); final String source = extractTagSource(tag_map); // Modifies tag_map. return wavefrontLine(ts, group.getPath(), metric, value, source, tag_map); }); }
[ "public", "static", "Optional", "<", "String", ">", "wavefrontLine", "(", "DateTime", "ts", ",", "GroupName", "group", ",", "MetricName", "metric", ",", "MetricValue", "metric_value", ")", "{", "return", "wavefrontValue", "(", "metric_value", ")", ".", "map", ...
Convert a metric to a wavefront string. Empty metrics and histograms do not emit a value. Note: the line is not terminated with a newline.
[ "Convert", "a", "metric", "to", "a", "wavefront", "string", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/processors/wavefront/src/main/java/com/groupon/lex/metrics/processors/wavefront/WavefrontStrings.java#L200-L207
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/misc/FDBigInteger.java
FDBigInteger.mult
private FDBigInteger mult(FDBigInteger other) { if (this.nWords == 0) { return this; } if (this.size() == 1) { return other.mult(data[0]); } if (other.nWords == 0) { return other; } if (other.size() == 1) { return this.mult(other.data[0]); } int[] r = new int[nWords + other.nWords]; mult(this.data, this.nWords, other.data, other.nWords, r); return new FDBigInteger(r, this.offset + other.offset); }
java
private FDBigInteger mult(FDBigInteger other) { if (this.nWords == 0) { return this; } if (this.size() == 1) { return other.mult(data[0]); } if (other.nWords == 0) { return other; } if (other.size() == 1) { return this.mult(other.data[0]); } int[] r = new int[nWords + other.nWords]; mult(this.data, this.nWords, other.data, other.nWords, r); return new FDBigInteger(r, this.offset + other.offset); }
[ "private", "FDBigInteger", "mult", "(", "FDBigInteger", "other", ")", "{", "if", "(", "this", ".", "nWords", "==", "0", ")", "{", "return", "this", ";", "}", "if", "(", "this", ".", "size", "(", ")", "==", "1", ")", "{", "return", "other", ".", "...
/*@ @ requires this.value() == 0; @ assignable \nothing; @ ensures \result == this; @ @ also @ @ requires this.value() != 0 && other.value() == 0; @ assignable \nothing; @ ensures \result == other; @ @ also @ @ requires this.value() != 0 && other.value() != 0; @ assignable \nothing; @ ensures \result.value() == \old(this.value() * other.value()); @
[ "/", "*" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/misc/FDBigInteger.java#L1153-L1169