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
davidmoten/rxjava-extras
src/main/java/com/github/davidmoten/rx/Transformers.java
Transformers.toListUntil
public static final <T> Transformer<T, List<T>> toListUntil(Func1<? super T, Boolean> predicate, int capacityHint) { return bufferUntil(predicate, capacityHint); }
java
public static final <T> Transformer<T, List<T>> toListUntil(Func1<? super T, Boolean> predicate, int capacityHint) { return bufferUntil(predicate, capacityHint); }
[ "public", "static", "final", "<", "T", ">", "Transformer", "<", "T", ",", "List", "<", "T", ">", ">", "toListUntil", "(", "Func1", "<", "?", "super", "T", ",", "Boolean", ">", "predicate", ",", "int", "capacityHint", ")", "{", "return", "bufferUntil", ...
Buffers the elements into continuous, non-overlapping Lists where the boundary is determined by a predicate receiving each item, after being buffered, and returns true to indicate a new buffer should start. <p> The operator won't return an empty first or last buffer. <dl> <dt><b>Backpressure Support:</b></dt> <dd>This operator supports backpressure.</dd> <dt><b>Scheduler:</b></dt> <dd>This operator does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param <T> the input value type @param predicate the Func1 that receives each item, after being buffered, and should return true to indicate a new buffer has to start. @param capacityHint the expected number of items in each buffer @return the new Observable instance @see #bufferWhile(Func1) @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number)
[ "Buffers", "the", "elements", "into", "continuous", "non", "-", "overlapping", "Lists", "where", "the", "boundary", "is", "determined", "by", "a", "predicate", "receiving", "each", "item", "after", "being", "buffered", "and", "returns", "true", "to", "indicate",...
train
https://github.com/davidmoten/rxjava-extras/blob/a91d2ba7d454843250e0b0fce36084f9fb02a551/src/main/java/com/github/davidmoten/rx/Transformers.java#L1148-L1151
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ConstantStringInfo.java
ConstantStringInfo.make
static ConstantStringInfo make(ConstantPool cp, String str) { ConstantInfo ci = new ConstantStringInfo(cp, str); return (ConstantStringInfo)cp.addConstant(ci); }
java
static ConstantStringInfo make(ConstantPool cp, String str) { ConstantInfo ci = new ConstantStringInfo(cp, str); return (ConstantStringInfo)cp.addConstant(ci); }
[ "static", "ConstantStringInfo", "make", "(", "ConstantPool", "cp", ",", "String", "str", ")", "{", "ConstantInfo", "ci", "=", "new", "ConstantStringInfo", "(", "cp", ",", "str", ")", ";", "return", "(", "ConstantStringInfo", ")", "cp", ".", "addConstant", "(...
Will return either a new ConstantStringInfo object or one already in the constant pool. If it is a new ConstantStringInfo, it will be inserted into the pool.
[ "Will", "return", "either", "a", "new", "ConstantStringInfo", "object", "or", "one", "already", "in", "the", "constant", "pool", ".", "If", "it", "is", "a", "new", "ConstantStringInfo", "it", "will", "be", "inserted", "into", "the", "pool", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantStringInfo.java#L37-L40
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/deps/DepTreeNode.java
DepTreeNode.setDependencies
public void setDependencies(String[] defineDependencies, String[] requireDependencies, String[] dependentFeatures, long lastModifiedFile, long lastModifiedDep) { this.defineDependencies = defineDependencies; this.requireDependencies = requireDependencies; this.dependentFeatures = dependentFeatures; this.lastModified = lastModifiedFile; this.lastModifiedDep = lastModifiedDep; }
java
public void setDependencies(String[] defineDependencies, String[] requireDependencies, String[] dependentFeatures, long lastModifiedFile, long lastModifiedDep) { this.defineDependencies = defineDependencies; this.requireDependencies = requireDependencies; this.dependentFeatures = dependentFeatures; this.lastModified = lastModifiedFile; this.lastModifiedDep = lastModifiedDep; }
[ "public", "void", "setDependencies", "(", "String", "[", "]", "defineDependencies", ",", "String", "[", "]", "requireDependencies", ",", "String", "[", "]", "dependentFeatures", ",", "long", "lastModifiedFile", ",", "long", "lastModifiedDep", ")", "{", "this", "...
Specifies the dependency list of modules for the module named by this node, along with the last modified date of the javascript file that the dependency list was obtained from. @param defineDependencies The define() dependency list of module names @param requireDependencies The require() dependency list of module names @param dependentFeatures The dependent features for the module @param lastModifiedFile The last modified date of the javascript source file @param lastModifiedDep The last modified date of the dependency list. See {@link #lastModifiedDep()}
[ "Specifies", "the", "dependency", "list", "of", "modules", "for", "the", "module", "named", "by", "this", "node", "along", "with", "the", "last", "modified", "date", "of", "the", "javascript", "file", "that", "the", "dependency", "list", "was", "obtained", "...
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/deps/DepTreeNode.java#L446-L452
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/DeepCopy.java
DeepCopy.simpleDeepCopy
public static Object simpleDeepCopy( Object object ) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); oos.close(); bos.close(); byte [] byteData = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); return new ObjectInputStream(bais).readObject(); } catch ( IOException ioe ) { throw new RuntimeException( "DeepCopy IOException", ioe ); } catch ( ClassNotFoundException cnf ) { throw new RuntimeException( "DeepCopy ClassNotFoundException", cnf ); } }
java
public static Object simpleDeepCopy( Object object ) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); oos.close(); bos.close(); byte [] byteData = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); return new ObjectInputStream(bais).readObject(); } catch ( IOException ioe ) { throw new RuntimeException( "DeepCopy IOException", ioe ); } catch ( ClassNotFoundException cnf ) { throw new RuntimeException( "DeepCopy ClassNotFoundException", cnf ); } }
[ "public", "static", "Object", "simpleDeepCopy", "(", "Object", "object", ")", "{", "try", "{", "ByteArrayOutputStream", "bos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "bos", ")", ";"...
Simple deep copy, that leverages Java Serialization. Supplied object is serialized to an in memory buffer (byte array), and then a new object is reconstituted from that byte array. This is meant for copying small objects or object graphs, and will probably do nasty things if asked to copy a large graph. @param object object to deep copy @return deep copy of the object
[ "Simple", "deep", "copy", "that", "leverages", "Java", "Serialization", ".", "Supplied", "object", "is", "serialized", "to", "an", "in", "memory", "buffer", "(", "byte", "array", ")", "and", "then", "a", "new", "object", "is", "reconstituted", "from", "that"...
train
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/DeepCopy.java#L37-L58
b3log/latke
latke-core/src/main/java/org/b3log/latke/ioc/SingletonContext.java
SingletonContext.destroyReference
private <T> void destroyReference(final Bean<T> bean, final T beanInstance) { bean.destroy(beanInstance); }
java
private <T> void destroyReference(final Bean<T> bean, final T beanInstance) { bean.destroy(beanInstance); }
[ "private", "<", "T", ">", "void", "destroyReference", "(", "final", "Bean", "<", "T", ">", "bean", ",", "final", "T", "beanInstance", ")", "{", "bean", ".", "destroy", "(", "beanInstance", ")", ";", "}" ]
Destroys the specified bean's instance. @param <T> the type of contextual @param bean the specified bean @param beanInstance the specified bean's instance
[ "Destroys", "the", "specified", "bean", "s", "instance", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/SingletonContext.java#L104-L106
googleapis/google-oauth-java-client
google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/TokenResponseException.java
TokenResponseException.from
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) { HttpResponseException.Builder builder = new HttpResponseException.Builder( response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); // details Preconditions.checkNotNull(jsonFactory); TokenErrorResponse details = null; String detailString = null; String contentType = response.getContentType(); try { if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) { details = new JsonObjectParser(jsonFactory).parseAndClose( response.getContent(), response.getContentCharset(), TokenErrorResponse.class); detailString = details.toPrettyString(); } else { detailString = response.parseAsString(); } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } // message StringBuilder message = HttpResponseException.computeMessageBuffer(response); if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); return new TokenResponseException(builder, details); }
java
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) { HttpResponseException.Builder builder = new HttpResponseException.Builder( response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); // details Preconditions.checkNotNull(jsonFactory); TokenErrorResponse details = null; String detailString = null; String contentType = response.getContentType(); try { if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) { details = new JsonObjectParser(jsonFactory).parseAndClose( response.getContent(), response.getContentCharset(), TokenErrorResponse.class); detailString = details.toPrettyString(); } else { detailString = response.parseAsString(); } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } // message StringBuilder message = HttpResponseException.computeMessageBuffer(response); if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); return new TokenResponseException(builder, details); }
[ "public", "static", "TokenResponseException", "from", "(", "JsonFactory", "jsonFactory", ",", "HttpResponse", "response", ")", "{", "HttpResponseException", ".", "Builder", "builder", "=", "new", "HttpResponseException", ".", "Builder", "(", "response", ".", "getStatu...
Returns a new instance of {@link TokenResponseException}. <p> If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be inspected using {@link #getDetails()}. Otherwise, the full response content is read and included in the exception message. </p> @param jsonFactory JSON factory @param response HTTP response @return new instance of {@link TokenErrorResponse}
[ "Returns", "a", "new", "instance", "of", "{", "@link", "TokenResponseException", "}", "." ]
train
https://github.com/googleapis/google-oauth-java-client/blob/7a829f8fd4d216c7d5882a82b9b58930fb375592/google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/TokenResponseException.java#L77-L106
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.removeEntries
public static void removeEntries(File zip, String[] paths, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and removing paths " + Arrays.asList(paths) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); copyEntries(zip, out, new HashSet<String>(Arrays.asList(paths))); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } }
java
public static void removeEntries(File zip, String[] paths, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and removing paths " + Arrays.asList(paths) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); copyEntries(zip, out, new HashSet<String>(Arrays.asList(paths))); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } }
[ "public", "static", "void", "removeEntries", "(", "File", "zip", ",", "String", "[", "]", "paths", ",", "File", "destZip", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Copying '\"", "+", "zip", "...
Copies an existing ZIP file and removes entries with given paths. @param zip an existing ZIP file (only read) @param paths paths of the entries to remove @param destZip new ZIP file created. @since 1.7
[ "Copies", "an", "existing", "ZIP", "file", "and", "removes", "entries", "with", "given", "paths", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2303-L2319
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/SslTlsUtil.java
SslTlsUtil.initializeKeyManagers
public static KeyManager[] initializeKeyManagers(File _keyStoreFile, String _keyStorePassword, String _keyPassword) throws IOException { if (_keyStoreFile == null) { return null; } String keyStorePwd = StringUtil.defaultIfBlank(_keyStorePassword, System.getProperty("javax.net.ssl.keyStorePassword")); if (StringUtil.isBlank(keyStorePwd)) { keyStorePwd = "changeit"; } String keyPwd = StringUtil.defaultIfBlank(_keyPassword, System.getProperty("javax.net.ssl.keyStorePassword")); if (StringUtil.isBlank(keyPwd)) { keyPwd = "changeit"; } String storeType = getStoreTypeByFileName(_keyStoreFile); LOGGER.debug("Creating key store of type '" + storeType + "' from file '" + _keyStoreFile + "'"); try { KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(storeType); try (FileInputStream fis = new FileInputStream(_keyStoreFile)) { keyStore.load(fis, keyStorePwd.toCharArray()); } keyMgrFactory.init(keyStore, keyPwd.toCharArray()); return keyMgrFactory.getKeyManagers(); } catch (Exception _ex) { throw new IOException("Error while setting up keyStore", _ex); } }
java
public static KeyManager[] initializeKeyManagers(File _keyStoreFile, String _keyStorePassword, String _keyPassword) throws IOException { if (_keyStoreFile == null) { return null; } String keyStorePwd = StringUtil.defaultIfBlank(_keyStorePassword, System.getProperty("javax.net.ssl.keyStorePassword")); if (StringUtil.isBlank(keyStorePwd)) { keyStorePwd = "changeit"; } String keyPwd = StringUtil.defaultIfBlank(_keyPassword, System.getProperty("javax.net.ssl.keyStorePassword")); if (StringUtil.isBlank(keyPwd)) { keyPwd = "changeit"; } String storeType = getStoreTypeByFileName(_keyStoreFile); LOGGER.debug("Creating key store of type '" + storeType + "' from file '" + _keyStoreFile + "'"); try { KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(storeType); try (FileInputStream fis = new FileInputStream(_keyStoreFile)) { keyStore.load(fis, keyStorePwd.toCharArray()); } keyMgrFactory.init(keyStore, keyPwd.toCharArray()); return keyMgrFactory.getKeyManagers(); } catch (Exception _ex) { throw new IOException("Error while setting up keyStore", _ex); } }
[ "public", "static", "KeyManager", "[", "]", "initializeKeyManagers", "(", "File", "_keyStoreFile", ",", "String", "_keyStorePassword", ",", "String", "_keyPassword", ")", "throws", "IOException", "{", "if", "(", "_keyStoreFile", "==", "null", ")", "{", "return", ...
Initialization of keyStoreManager used to provide access to the configured keyStore. @param _keyStoreFile key store file @param _keyStorePassword key store password @param _keyPassword key password @return KeyManager array or null @throws IOException on error
[ "Initialization", "of", "keyStoreManager", "used", "to", "provide", "access", "to", "the", "configured", "keyStore", "." ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/SslTlsUtil.java#L91-L123
Hygieia/Hygieia
collectors/performance/appdynamics/src/main/java/com/capitalone/dashboard/collector/DefaultAppdynamicsClient.java
DefaultAppdynamicsClient.joinURL
public static String joinURL(String base, String... paths) throws MalformedURLException { StringBuilder result = new StringBuilder(base); for (String path : paths) { String p = path.replaceFirst("^(\\/)+", ""); if (result.lastIndexOf("/") != result.length() - 1) { result.append('/'); } result.append(p); } return result.toString(); }
java
public static String joinURL(String base, String... paths) throws MalformedURLException { StringBuilder result = new StringBuilder(base); for (String path : paths) { String p = path.replaceFirst("^(\\/)+", ""); if (result.lastIndexOf("/") != result.length() - 1) { result.append('/'); } result.append(p); } return result.toString(); }
[ "public", "static", "String", "joinURL", "(", "String", "base", ",", "String", "...", "paths", ")", "throws", "MalformedURLException", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "base", ")", ";", "for", "(", "String", "path", ":", "pat...
join a base url to another path or paths - this will handle trailing or non-trailing /'s
[ "join", "a", "base", "url", "to", "another", "path", "or", "paths", "-", "this", "will", "handle", "trailing", "or", "non", "-", "trailing", "/", "s" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/performance/appdynamics/src/main/java/com/capitalone/dashboard/collector/DefaultAppdynamicsClient.java#L67-L77
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java
PackageSummaryBuilder.buildEnumSummary
public void buildEnumSummary(XMLNode node, Content summaryContentTree) { String enumTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Enum_Summary"), configuration.getText("doclet.enums")); List<String> enumTableHeader = Arrays.asList(configuration.getText("doclet.Enum"), configuration.getText("doclet.Description")); SortedSet<TypeElement> elist = utils.isSpecified(packageElement) ? utils.getTypeElementsAsSortedSet(utils.getEnums(packageElement)) : configuration.typeElementCatalog.enums(packageElement); SortedSet<TypeElement> enums = utils.filterOutPrivateClasses(elist, configuration.javafx); if (!enums.isEmpty()) { packageWriter.addClassesSummary(enums, configuration.getText("doclet.Enum_Summary"), enumTableSummary, enumTableHeader, summaryContentTree); } }
java
public void buildEnumSummary(XMLNode node, Content summaryContentTree) { String enumTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Enum_Summary"), configuration.getText("doclet.enums")); List<String> enumTableHeader = Arrays.asList(configuration.getText("doclet.Enum"), configuration.getText("doclet.Description")); SortedSet<TypeElement> elist = utils.isSpecified(packageElement) ? utils.getTypeElementsAsSortedSet(utils.getEnums(packageElement)) : configuration.typeElementCatalog.enums(packageElement); SortedSet<TypeElement> enums = utils.filterOutPrivateClasses(elist, configuration.javafx); if (!enums.isEmpty()) { packageWriter.addClassesSummary(enums, configuration.getText("doclet.Enum_Summary"), enumTableSummary, enumTableHeader, summaryContentTree); } }
[ "public", "void", "buildEnumSummary", "(", "XMLNode", "node", ",", "Content", "summaryContentTree", ")", "{", "String", "enumTableSummary", "=", "configuration", ".", "getText", "(", "\"doclet.Member_Table_Summary\"", ",", "configuration", ".", "getText", "(", "\"docl...
Build the summary for the enums in this package. @param node the XML element that specifies which components to document @param summaryContentTree the summary tree to which the enum summary will be added
[ "Build", "the", "summary", "for", "the", "enums", "in", "this", "package", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java#L227-L243
joniles/mpxj
src/main/java/net/sf/mpxj/ResourceAssignment.java
ResourceAssignment.splitCostEnd
private TimephasedCost splitCostEnd(ProjectCalendar calendar, double totalAmount, Date finish) { TimephasedCost cost = new TimephasedCost(); cost.setStart(calendar.getStartDate(finish, Duration.getInstance(1, TimeUnit.DAYS))); cost.setFinish(finish); cost.setAmountPerDay(Double.valueOf(totalAmount)); cost.setTotalAmount(Double.valueOf(totalAmount)); return cost; }
java
private TimephasedCost splitCostEnd(ProjectCalendar calendar, double totalAmount, Date finish) { TimephasedCost cost = new TimephasedCost(); cost.setStart(calendar.getStartDate(finish, Duration.getInstance(1, TimeUnit.DAYS))); cost.setFinish(finish); cost.setAmountPerDay(Double.valueOf(totalAmount)); cost.setTotalAmount(Double.valueOf(totalAmount)); return cost; }
[ "private", "TimephasedCost", "splitCostEnd", "(", "ProjectCalendar", "calendar", ",", "double", "totalAmount", ",", "Date", "finish", ")", "{", "TimephasedCost", "cost", "=", "new", "TimephasedCost", "(", ")", ";", "cost", ".", "setStart", "(", "calendar", ".", ...
Used for Cost type Resources. Generates a TimphasedCost block for the total amount on the finish date. This is useful for Cost resources that have an AccrueAt value of End. @param calendar calendar used by this assignment @param totalAmount cost amount for this block @param finish finish date of the timephased cost block @return timephased cost
[ "Used", "for", "Cost", "type", "Resources", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ResourceAssignment.java#L986-L995
jbossws/jbossws-cxf
modules/client/src/main/java/org/jboss/wsf/stack/cxf/client/configuration/JBossWSBusFactory.java
JBossWSBusFactory.getClassLoaderDefaultBus
public static Bus getClassLoaderDefaultBus(final ClassLoader classloader, final ClientBusSelector clientBusSelector) { Bus classLoaderBus; synchronized (classLoaderBusses) { classLoaderBus = classLoaderBusses.get(classloader); if (classLoaderBus == null) { classLoaderBus = clientBusSelector.createNewBus(); //register a listener for cleaning up the bus from the classloader association in the JBossWSBusFactory BusLifeCycleListener listener = new ClassLoaderDefaultBusLifeCycleListener(classLoaderBus); classLoaderBus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(listener); classLoaderBusses.put(classloader, classLoaderBus); } } return classLoaderBus; }
java
public static Bus getClassLoaderDefaultBus(final ClassLoader classloader, final ClientBusSelector clientBusSelector) { Bus classLoaderBus; synchronized (classLoaderBusses) { classLoaderBus = classLoaderBusses.get(classloader); if (classLoaderBus == null) { classLoaderBus = clientBusSelector.createNewBus(); //register a listener for cleaning up the bus from the classloader association in the JBossWSBusFactory BusLifeCycleListener listener = new ClassLoaderDefaultBusLifeCycleListener(classLoaderBus); classLoaderBus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(listener); classLoaderBusses.put(classloader, classLoaderBus); } } return classLoaderBus; }
[ "public", "static", "Bus", "getClassLoaderDefaultBus", "(", "final", "ClassLoader", "classloader", ",", "final", "ClientBusSelector", "clientBusSelector", ")", "{", "Bus", "classLoaderBus", ";", "synchronized", "(", "classLoaderBusses", ")", "{", "classLoaderBus", "=", ...
Gets the default bus for the given classloader; if a new Bus is needed, the creation is delegated to the specified ClientBusSelector instance. @param classloader @param clientBusSelector @return
[ "Gets", "the", "default", "bus", "for", "the", "given", "classloader", ";", "if", "a", "new", "Bus", "is", "needed", "the", "creation", "is", "delegated", "to", "the", "specified", "ClientBusSelector", "instance", "." ]
train
https://github.com/jbossws/jbossws-cxf/blob/e1d5df3664cbc2482ebc83cafd355a4d60d12150/modules/client/src/main/java/org/jboss/wsf/stack/cxf/client/configuration/JBossWSBusFactory.java#L114-L127
eyp/serfj
src/main/java/net/sf/serfj/ServletHelper.java
ServletHelper.invokeAction
private Object invokeAction(Object clazz, Method method, UrlInfo urlInfo, Object... args) throws IllegalAccessException, InvocationTargetException { if (this.isRequestMethodServed(method, urlInfo.getRequestMethod())) { return method.invoke(clazz, args); } else { throw new IllegalArgumentException("Method " + urlInfo.getController() + "." + urlInfo.getAction() + " doesn't accept requests by " + urlInfo.getRequestMethod() + " HTTP_METHOD"); } }
java
private Object invokeAction(Object clazz, Method method, UrlInfo urlInfo, Object... args) throws IllegalAccessException, InvocationTargetException { if (this.isRequestMethodServed(method, urlInfo.getRequestMethod())) { return method.invoke(clazz, args); } else { throw new IllegalArgumentException("Method " + urlInfo.getController() + "." + urlInfo.getAction() + " doesn't accept requests by " + urlInfo.getRequestMethod() + " HTTP_METHOD"); } }
[ "private", "Object", "invokeAction", "(", "Object", "clazz", ",", "Method", "method", ",", "UrlInfo", "urlInfo", ",", "Object", "...", "args", ")", "throws", "IllegalAccessException", ",", "InvocationTargetException", "{", "if", "(", "this", ".", "isRequestMethodS...
Invokes a method checking previously if that method accepts requests using a particular HTTP_METHOD. @param clazz A class. @param method A method to invoke. @param urlInfo URL information extracted by the framework. @param args Arguments for the method which will be invoked. @return the object returned by the method onvoked, or null. @throws IllegalArgumentException if the HTTP_METHOD that comes in the request is not accepted by class's method.
[ "Invokes", "a", "method", "checking", "previously", "if", "that", "method", "accepts", "requests", "using", "a", "particular", "HTTP_METHOD", "." ]
train
https://github.com/eyp/serfj/blob/e617592af6f24e59ea58443f2785c44aa2312189/src/main/java/net/sf/serfj/ServletHelper.java#L264-L270
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/bic/ExternalContextAccessSkill.java
ExternalContextAccessSkill.fireContextJoined
protected final void fireContextJoined(UUID futureContext, UUID futureContextDefaultSpaceID) { getBehaviorsSkill().wake(new ContextJoined(futureContext, futureContextDefaultSpaceID)); }
java
protected final void fireContextJoined(UUID futureContext, UUID futureContextDefaultSpaceID) { getBehaviorsSkill().wake(new ContextJoined(futureContext, futureContextDefaultSpaceID)); }
[ "protected", "final", "void", "fireContextJoined", "(", "UUID", "futureContext", ",", "UUID", "futureContextDefaultSpaceID", ")", "{", "getBehaviorsSkill", "(", ")", ".", "wake", "(", "new", "ContextJoined", "(", "futureContext", ",", "futureContextDefaultSpaceID", ")...
Fires an {@link ContextJoined} event into the Inner Context default space of the owner agent to notify behaviors/members that a new context has been joined. @param futureContext ID of the newly joined context @param futureContextDefaultSpaceID ID of the default space of the newly joined context
[ "Fires", "an", "{", "@link", "ContextJoined", "}", "event", "into", "the", "Inner", "Context", "default", "space", "of", "the", "owner", "agent", "to", "notify", "behaviors", "/", "members", "that", "a", "new", "context", "has", "been", "joined", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/bic/ExternalContextAccessSkill.java#L191-L193
amlinv/amq-topo-utils
src/main/java/com/amlinv/activemq/topo/discovery/MBeanDestinationDiscoverer.java
MBeanDestinationDiscoverer.onFoundDestination
protected void onFoundDestination (String destName) { if ( ( destName != null ) && ( ! destName.isEmpty() ) ) { DestinationState destState = this.registry.putIfAbsent(destName, new DestinationState(destName, this.brokerId)); // // If it was already there, mark it as seen now by the broker. // if ( destState != null ) { destState.putBrokerInfo(this.brokerId, true); } } }
java
protected void onFoundDestination (String destName) { if ( ( destName != null ) && ( ! destName.isEmpty() ) ) { DestinationState destState = this.registry.putIfAbsent(destName, new DestinationState(destName, this.brokerId)); // // If it was already there, mark it as seen now by the broker. // if ( destState != null ) { destState.putBrokerInfo(this.brokerId, true); } } }
[ "protected", "void", "onFoundDestination", "(", "String", "destName", ")", "{", "if", "(", "(", "destName", "!=", "null", ")", "&&", "(", "!", "destName", ".", "isEmpty", "(", ")", ")", ")", "{", "DestinationState", "destState", "=", "this", ".", "regist...
For the destination represented by the named mbean, add the destination to the registry. @param destName name of the destination.
[ "For", "the", "destination", "represented", "by", "the", "named", "mbean", "add", "the", "destination", "to", "the", "registry", "." ]
train
https://github.com/amlinv/amq-topo-utils/blob/4d82d5735d59f9c95e149362a09ea4d27d9ac4ac/src/main/java/com/amlinv/activemq/topo/discovery/MBeanDestinationDiscoverer.java#L168-L180
vincentk/joptimizer
src/main/java/com/joptimizer/optimizers/BasicPhaseIPDM.java
BasicPhaseIPDM.findOneRoot
private DoubleMatrix1D findOneRoot(DoubleMatrix2D A, DoubleMatrix1D b) throws Exception{ return originalProblem.findEqFeasiblePoint(A, b); }
java
private DoubleMatrix1D findOneRoot(DoubleMatrix2D A, DoubleMatrix1D b) throws Exception{ return originalProblem.findEqFeasiblePoint(A, b); }
[ "private", "DoubleMatrix1D", "findOneRoot", "(", "DoubleMatrix2D", "A", ",", "DoubleMatrix1D", "b", ")", "throws", "Exception", "{", "return", "originalProblem", ".", "findEqFeasiblePoint", "(", "A", ",", "b", ")", ";", "}" ]
Just looking for one out of all the possible solutions. @see "Convex Optimization, C.5 p. 681".
[ "Just", "looking", "for", "one", "out", "of", "all", "the", "possible", "solutions", "." ]
train
https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/optimizers/BasicPhaseIPDM.java#L226-L228
j-a-w-r/jawr-main-repo
jawr-dwr2.x/jawr-dwr2.x-webapp-sample/src/main/java/org/getahead/dwrdemo/livehelp/LiveHelp.java
LiveHelp.notifyTyping
public void notifyTyping(String id, String value) { Util utilAll = new Util(getUsersToAffect()); utilAll.setValue(id, Security.replaceXmlCharacters(value)); }
java
public void notifyTyping(String id, String value) { Util utilAll = new Util(getUsersToAffect()); utilAll.setValue(id, Security.replaceXmlCharacters(value)); }
[ "public", "void", "notifyTyping", "(", "String", "id", ",", "String", "value", ")", "{", "Util", "utilAll", "=", "new", "Util", "(", "getUsersToAffect", "(", ")", ")", ";", "utilAll", ".", "setValue", "(", "id", ",", "Security", ".", "replaceXmlCharacters"...
Something has changed @param id The id of the field that changed @param value The new value
[ "Something", "has", "changed" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-dwr2.x/jawr-dwr2.x-webapp-sample/src/main/java/org/getahead/dwrdemo/livehelp/LiveHelp.java#L38-L43
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_command.java
ns_command.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_command_responses result = (ns_command_responses) service.get_payload_formatter().string_to_resource(ns_command_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_command_response_array); } ns_command[] result_ns_command = new ns_command[result.ns_command_response_array.length]; for(int i = 0; i < result.ns_command_response_array.length; i++) { result_ns_command[i] = result.ns_command_response_array[i].ns_command[0]; } return result_ns_command; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_command_responses result = (ns_command_responses) service.get_payload_formatter().string_to_resource(ns_command_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_command_response_array); } ns_command[] result_ns_command = new ns_command[result.ns_command_response_array.length]; for(int i = 0; i < result.ns_command_response_array.length; i++) { result_ns_command[i] = result.ns_command_response_array[i].ns_command[0]; } return result_ns_command; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ns_command_responses", "result", "=", "(", "ns_command_responses", ")", "service", ".", "get_payload_formatte...
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_command.java#L122-L139
opencb/biodata
biodata-formats/src/main/java/org/opencb/biodata/formats/sequence/fastq/io/FastaQReader.java
FastaQReader.checkQualitySize
private void checkQualitySize(String id, String sequence, String quality) throws FileFormatException { if (sequence.length() != quality.length()) { throw new FileFormatException("Quality and Sequence lenghts are different in Fasta " + id); } }
java
private void checkQualitySize(String id, String sequence, String quality) throws FileFormatException { if (sequence.length() != quality.length()) { throw new FileFormatException("Quality and Sequence lenghts are different in Fasta " + id); } }
[ "private", "void", "checkQualitySize", "(", "String", "id", ",", "String", "sequence", ",", "String", "quality", ")", "throws", "FileFormatException", "{", "if", "(", "sequence", ".", "length", "(", ")", "!=", "quality", ".", "length", "(", ")", ")", "{", ...
Check that the sequence and quality strings have the same length @param id - FastQ id @param sequence - FastQ sequence string @param quality - FastQ quality string @throws FileFormatException - If the sequence and quality strings have different lengths
[ "Check", "that", "the", "sequence", "and", "quality", "strings", "have", "the", "same", "length" ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-formats/src/main/java/org/opencb/biodata/formats/sequence/fastq/io/FastaQReader.java#L220-L224
Activiti/Activiti
activiti-engine/src/main/java/org/activiti/engine/impl/util/json/JSONObject.java
JSONObject.optString
public String optString(String key, String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; }
java
public String optString(String key, String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; }
[ "public", "String", "optString", "(", "String", "key", ",", "String", "defaultValue", ")", "{", "Object", "o", "=", "opt", "(", "key", ")", ";", "return", "o", "!=", "null", "?", "o", ".", "toString", "(", ")", ":", "defaultValue", ";", "}" ]
Get an optional string associated with a key. It returns the defaultValue if there is no such key. @param key A key string. @param defaultValue The default. @return A string which is the value.
[ "Get", "an", "optional", "string", "associated", "with", "a", "key", ".", "It", "returns", "the", "defaultValue", "if", "there", "is", "no", "such", "key", "." ]
train
https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/util/json/JSONObject.java#L815-L818
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/quota/PathPatternUtils.java
PathPatternUtils.acceptName
public static boolean acceptName(String pattern, String absPath) { absPath = normalizePath(absPath); pattern = adopt2JavaPattern(pattern); return absPath.matches(pattern); }
java
public static boolean acceptName(String pattern, String absPath) { absPath = normalizePath(absPath); pattern = adopt2JavaPattern(pattern); return absPath.matches(pattern); }
[ "public", "static", "boolean", "acceptName", "(", "String", "pattern", ",", "String", "absPath", ")", "{", "absPath", "=", "normalizePath", "(", "absPath", ")", ";", "pattern", "=", "adopt2JavaPattern", "(", "pattern", ")", ";", "return", "absPath", ".", "ma...
Returns <code>true</code> if a specified path is matched by pattern and has the same depth in term of JCR path. @param pattern pattern for node path @param absPath node absolute path @return a <code>boolean</code>.
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "a", "specified", "path", "is", "matched", "by", "pattern", "and", "has", "the", "same", "depth", "in", "term", "of", "JCR", "path", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/quota/PathPatternUtils.java#L66-L72
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/accounts/A_CmsOrgUnitDialog.java
A_CmsOrgUnitDialog.setResourcesInBean
public void setResourcesInBean(CmsOrgUnitBean orgUnitBean, List<CmsResource> resources) { List<String> resourceNames = new ArrayList<String>(); Iterator<CmsResource> itResources = resources.iterator(); while (itResources.hasNext()) { CmsResource resource = itResources.next(); resourceNames.add(getCms().getSitePath(resource)); } orgUnitBean.setResources(resourceNames); }
java
public void setResourcesInBean(CmsOrgUnitBean orgUnitBean, List<CmsResource> resources) { List<String> resourceNames = new ArrayList<String>(); Iterator<CmsResource> itResources = resources.iterator(); while (itResources.hasNext()) { CmsResource resource = itResources.next(); resourceNames.add(getCms().getSitePath(resource)); } orgUnitBean.setResources(resourceNames); }
[ "public", "void", "setResourcesInBean", "(", "CmsOrgUnitBean", "orgUnitBean", ",", "List", "<", "CmsResource", ">", "resources", ")", "{", "List", "<", "String", ">", "resourceNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "Iterator", "<...
Sets the resources for the given orgUnitBean.<p> @param orgUnitBean the <code>CmsOrgUnitBean</code> object @param resources the list of resources
[ "Sets", "the", "resources", "for", "the", "given", "orgUnitBean", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/accounts/A_CmsOrgUnitDialog.java#L120-L129
OpenLiberty/open-liberty
dev/com.ibm.ws.concurrent.persistent/src/com/ibm/ws/concurrent/persistent/internal/InvokerTask.java
InvokerTask.serializeResult
@FFDCIgnore(Throwable.class) @Sensitive private byte[] serializeResult(Object result, ClassLoader loader) throws IOException { try { return persistentExecutor.serialize(result); } catch (Throwable x) { return persistentExecutor.serialize(new TaskFailure(x, loader, persistentExecutor, TaskFailure.NONSER_RESULT, result.getClass().getName())); } }
java
@FFDCIgnore(Throwable.class) @Sensitive private byte[] serializeResult(Object result, ClassLoader loader) throws IOException { try { return persistentExecutor.serialize(result); } catch (Throwable x) { return persistentExecutor.serialize(new TaskFailure(x, loader, persistentExecutor, TaskFailure.NONSER_RESULT, result.getClass().getName())); } }
[ "@", "FFDCIgnore", "(", "Throwable", ".", "class", ")", "@", "Sensitive", "private", "byte", "[", "]", "serializeResult", "(", "Object", "result", ",", "ClassLoader", "loader", ")", "throws", "IOException", "{", "try", "{", "return", "persistentExecutor", ".",...
Utility method that serializes a task result, or the failure that occurred when attempting to serialize the task result. @param result non-null task result @param loader class loader that can deserialize the task and result. @return serialized bytes
[ "Utility", "method", "that", "serializes", "a", "task", "result", "or", "the", "failure", "that", "occurred", "when", "attempting", "to", "serialize", "the", "task", "result", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.persistent/src/com/ibm/ws/concurrent/persistent/internal/InvokerTask.java#L605-L613
jenkinsci/jenkins
core/src/main/java/jenkins/util/Timer.java
Timer.get
@Nonnull public static synchronized ScheduledExecutorService get() { if (executorService == null) { // corePoolSize is set to 10, but will only be created if needed. // ScheduledThreadPoolExecutor "acts as a fixed-sized pool using corePoolSize threads" // TODO consider also wrapping in ContextResettingExecutorService executorService = new ImpersonatingScheduledExecutorService(new ErrorLoggingScheduledThreadPoolExecutor(10, new NamingThreadFactory(new ClassLoaderSanityThreadFactory(new DaemonThreadFactory()), "jenkins.util.Timer")), ACL.SYSTEM); } return executorService; }
java
@Nonnull public static synchronized ScheduledExecutorService get() { if (executorService == null) { // corePoolSize is set to 10, but will only be created if needed. // ScheduledThreadPoolExecutor "acts as a fixed-sized pool using corePoolSize threads" // TODO consider also wrapping in ContextResettingExecutorService executorService = new ImpersonatingScheduledExecutorService(new ErrorLoggingScheduledThreadPoolExecutor(10, new NamingThreadFactory(new ClassLoaderSanityThreadFactory(new DaemonThreadFactory()), "jenkins.util.Timer")), ACL.SYSTEM); } return executorService; }
[ "@", "Nonnull", "public", "static", "synchronized", "ScheduledExecutorService", "get", "(", ")", "{", "if", "(", "executorService", "==", "null", ")", "{", "// corePoolSize is set to 10, but will only be created if needed.", "// ScheduledThreadPoolExecutor \"acts as a fixed-sized...
Returns the scheduled executor service used by all timed tasks in Jenkins. @return the single {@link ScheduledExecutorService}.
[ "Returns", "the", "scheduled", "executor", "service", "used", "by", "all", "timed", "tasks", "in", "Jenkins", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/Timer.java#L41-L50
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java
ByteBuffer.toHexString
public String toHexString(int offset, int length) { // is offset, length valid for the current size() of our internal byte[] checkOffsetLength(size(), offset, length); // if length is 0, return an empty string if (length == 0 || size() == 0) { return ""; } StringBuilder s = new StringBuilder(length * 2); int end = offset + length; for (int i = offset; i < end; i++) { HexUtil.appendHexString(s, getUnchecked(i)); } return s.toString(); }
java
public String toHexString(int offset, int length) { // is offset, length valid for the current size() of our internal byte[] checkOffsetLength(size(), offset, length); // if length is 0, return an empty string if (length == 0 || size() == 0) { return ""; } StringBuilder s = new StringBuilder(length * 2); int end = offset + length; for (int i = offset; i < end; i++) { HexUtil.appendHexString(s, getUnchecked(i)); } return s.toString(); }
[ "public", "String", "toHexString", "(", "int", "offset", ",", "int", "length", ")", "{", "// is offset, length valid for the current size() of our internal byte[]", "checkOffsetLength", "(", "size", "(", ")", ",", "offset", ",", "length", ")", ";", "// if length is 0, r...
Return a hexidecimal String representation of the current buffer with each byte displayed in a 2 character hexidecimal format. Useful for debugging. Convert a ByteBuffer to a String with a hexidecimal format. @param offset @param length @return The string in hex representation
[ "Return", "a", "hexidecimal", "String", "representation", "of", "the", "current", "buffer", "with", "each", "byte", "displayed", "in", "a", "2", "character", "hexidecimal", "format", ".", "Useful", "for", "debugging", ".", "Convert", "a", "ByteBuffer", "to", "...
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteBuffer.java#L1092-L1108
livetribe/livetribe-slp
core/src/main/java/org/livetribe/slp/settings/Editors.java
Editors.convertFromString
public static <T> T convertFromString(String text, Class<T> typeClass) { Class<? extends PropertyEditor> editorClass = null; synchronized (editors) { editorClass = editors.get(typeClass); } if (editorClass != null) { PropertyEditor editor = newPropertyEditor(editorClass); if (editor != null) { try { return (T)convertFromString(editor, text); } catch (IllegalArgumentException x) { // Fallback to the default editors } } } PropertyEditor editor = PropertyEditorManager.findEditor(typeClass); if (editor != null) return (T)convertFromString(editor, text); return null; }
java
public static <T> T convertFromString(String text, Class<T> typeClass) { Class<? extends PropertyEditor> editorClass = null; synchronized (editors) { editorClass = editors.get(typeClass); } if (editorClass != null) { PropertyEditor editor = newPropertyEditor(editorClass); if (editor != null) { try { return (T)convertFromString(editor, text); } catch (IllegalArgumentException x) { // Fallback to the default editors } } } PropertyEditor editor = PropertyEditorManager.findEditor(typeClass); if (editor != null) return (T)convertFromString(editor, text); return null; }
[ "public", "static", "<", "T", ">", "T", "convertFromString", "(", "String", "text", ",", "Class", "<", "T", ">", "typeClass", ")", "{", "Class", "<", "?", "extends", "PropertyEditor", ">", "editorClass", "=", "null", ";", "synchronized", "(", "editors", ...
Converts the given text string to an object of the given type class. <br /> If no editor is registered for the given type class, or if it fails the conversion, the default property editor from {@link PropertyEditorManager} is tried. @param text the text string to convert into an object @param typeClass the class of the object to return @return an object of the given type class converted from the given text string
[ "Converts", "the", "given", "text", "string", "to", "an", "object", "of", "the", "given", "type", "class", ".", "<br", "/", ">", "If", "no", "editor", "is", "registered", "for", "the", "given", "type", "class", "or", "if", "it", "fails", "the", "conver...
train
https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/settings/Editors.java#L60-L87
algolia/instantsearch-android
ui/src/main/java/com/algolia/instantsearch/ui/helpers/InstantSearch.java
InstantSearch.registerSearchView
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public void registerSearchView(@NonNull final Activity activity, @NonNull final SearchView searchView) { registerSearchView(activity, new SearchViewFacade(searchView)); }
java
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public void registerSearchView(@NonNull final Activity activity, @NonNull final SearchView searchView) { registerSearchView(activity, new SearchViewFacade(searchView)); }
[ "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "// For library users", "public", "void", "registerSearchView", "(", "@", "NonNull", "final", "Activity", "activity", ",", "@", "NonNull", "final", "SearchView", "searchView", ")", ...
Registers a {@link SearchView} to trigger search requests on text change, replacing the current one if any. @param activity The searchable activity, see {@link android.app.SearchableInfo}. @param searchView a SearchView whose query text will be used.
[ "Registers", "a", "{", "@link", "SearchView", "}", "to", "trigger", "search", "requests", "on", "text", "change", "replacing", "the", "current", "one", "if", "any", "." ]
train
https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/ui/src/main/java/com/algolia/instantsearch/ui/helpers/InstantSearch.java#L203-L206
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
AbstractQueuedSynchronizer.tryAcquireNanos
public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout); }
java
public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout); }
[ "public", "final", "boolean", "tryAcquireNanos", "(", "int", "arg", ",", "long", "nanosTimeout", ")", "throws", "InterruptedException", "{", "if", "(", "Thread", ".", "interrupted", "(", ")", ")", "throw", "new", "InterruptedException", "(", ")", ";", "return"...
Attempts to acquire in exclusive mode, aborting if interrupted, and failing if the given timeout elapses. Implemented by first checking interrupt status, then invoking at least once {@link #tryAcquire}, returning on success. Otherwise, the thread is queued, possibly repeatedly blocking and unblocking, invoking {@link #tryAcquire} until success or the thread is interrupted or the timeout elapses. This method can be used to implement method {@link Lock#tryLock(long, TimeUnit)}. @param arg the acquire argument. This value is conveyed to {@link #tryAcquire} but is otherwise uninterpreted and can represent anything you like. @param nanosTimeout the maximum number of nanoseconds to wait @return {@code true} if acquired; {@code false} if timed out @throws InterruptedException if the current thread is interrupted
[ "Attempts", "to", "acquire", "in", "exclusive", "mode", "aborting", "if", "interrupted", "and", "failing", "if", "the", "given", "timeout", "elapses", ".", "Implemented", "by", "first", "checking", "interrupt", "status", "then", "invoking", "at", "least", "once"...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java#L1270-L1276
VoltDB/voltdb
src/frontend/org/voltcore/messaging/SocketJoiner.java
SocketJoiner.requestHostId
private RequestHostIdResponse requestHostId ( MessagingChannel messagingChannel, Set<String> activeVersions) throws Exception { VersionChecker versionChecker = m_acceptor.getVersionChecker(); activeVersions.add(versionChecker.getVersionString()); JSONObject jsObj = new JSONObject(); jsObj.put(TYPE, ConnectionType.REQUEST_HOSTID.name()); // put the version compatibility status in the json jsObj.put(VERSION_STRING, versionChecker.getVersionString()); // Advertise the port we are going to listen on based on config jsObj.put(PORT, m_internalPort); // If config specified an internal interface use that. // Otherwise the leader will echo back what we connected on if (!m_internalInterface.isEmpty()) { jsObj.put(ADDRESS, m_internalInterface); } // communicate configuration and node state jsObj = m_acceptor.decorate(jsObj, Optional.empty()); jsObj.put(MAY_EXCHANGE_TS, true); byte jsBytes[] = jsObj.toString(4).getBytes(StandardCharsets.UTF_8); ByteBuffer requestHostIdBuffer = ByteBuffer.allocate(4 + jsBytes.length); requestHostIdBuffer.putInt(jsBytes.length); requestHostIdBuffer.put(jsBytes).flip(); messagingChannel.writeMessage(requestHostIdBuffer); // read the json response from socketjoiner with version info and validate it JSONObject leaderInfo = processJSONResponse(messagingChannel, activeVersions, true); // read the json response sent by HostMessenger with HostID JSONObject jsonObj = readJSONObjFromWire(messagingChannel); return new RequestHostIdResponse(leaderInfo, jsonObj); }
java
private RequestHostIdResponse requestHostId ( MessagingChannel messagingChannel, Set<String> activeVersions) throws Exception { VersionChecker versionChecker = m_acceptor.getVersionChecker(); activeVersions.add(versionChecker.getVersionString()); JSONObject jsObj = new JSONObject(); jsObj.put(TYPE, ConnectionType.REQUEST_HOSTID.name()); // put the version compatibility status in the json jsObj.put(VERSION_STRING, versionChecker.getVersionString()); // Advertise the port we are going to listen on based on config jsObj.put(PORT, m_internalPort); // If config specified an internal interface use that. // Otherwise the leader will echo back what we connected on if (!m_internalInterface.isEmpty()) { jsObj.put(ADDRESS, m_internalInterface); } // communicate configuration and node state jsObj = m_acceptor.decorate(jsObj, Optional.empty()); jsObj.put(MAY_EXCHANGE_TS, true); byte jsBytes[] = jsObj.toString(4).getBytes(StandardCharsets.UTF_8); ByteBuffer requestHostIdBuffer = ByteBuffer.allocate(4 + jsBytes.length); requestHostIdBuffer.putInt(jsBytes.length); requestHostIdBuffer.put(jsBytes).flip(); messagingChannel.writeMessage(requestHostIdBuffer); // read the json response from socketjoiner with version info and validate it JSONObject leaderInfo = processJSONResponse(messagingChannel, activeVersions, true); // read the json response sent by HostMessenger with HostID JSONObject jsonObj = readJSONObjFromWire(messagingChannel); return new RequestHostIdResponse(leaderInfo, jsonObj); }
[ "private", "RequestHostIdResponse", "requestHostId", "(", "MessagingChannel", "messagingChannel", ",", "Set", "<", "String", ">", "activeVersions", ")", "throws", "Exception", "{", "VersionChecker", "versionChecker", "=", "m_acceptor", ".", "getVersionChecker", "(", ")"...
Connection handshake to the leader, ask the leader to assign a host Id for current node. @param @return array of two JSON objects, first is leader info, second is the response to our request @throws Exception
[ "Connection", "handshake", "to", "the", "leader", "ask", "the", "leader", "to", "assign", "a", "host", "Id", "for", "current", "node", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/messaging/SocketJoiner.java#L763-L801
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/scene_objects/GVRTextViewSceneObject.java
GVRTextViewSceneObject.setTypeface
public boolean setTypeface(GVRContext gvrContext, String font) { return setTypeface(gvrContext, font, fontStyleTypes.PLAIN); }
java
public boolean setTypeface(GVRContext gvrContext, String font) { return setTypeface(gvrContext, font, fontStyleTypes.PLAIN); }
[ "public", "boolean", "setTypeface", "(", "GVRContext", "gvrContext", ",", "String", "font", ")", "{", "return", "setTypeface", "(", "gvrContext", ",", "font", ",", "fontStyleTypes", ".", "PLAIN", ")", ";", "}" ]
Sets the typeface (font) @param gvrContext @param font a string that matches the font name saved in the assets directory Must include the file ending such as "myFont.ttf" @return
[ "Sets", "the", "typeface", "(", "font", ")", "@param", "gvrContext", "@param", "font", "a", "string", "that", "matches", "the", "font", "name", "saved", "in", "the", "assets", "directory", "Must", "include", "the", "file", "ending", "such", "as", "myFont", ...
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/scene_objects/GVRTextViewSceneObject.java#L463-L465
buschmais/extended-objects
impl/src/main/java/com/buschmais/xo/impl/AbstractInstanceManager.java
AbstractInstanceManager.createInstance
public <T> T createInstance(DatastoreType datastoreType, DynamicType<?> types) { return newInstance(getDatastoreId(datastoreType), datastoreType, types, TransactionalCache.Mode.WRITE); }
java
public <T> T createInstance(DatastoreType datastoreType, DynamicType<?> types) { return newInstance(getDatastoreId(datastoreType), datastoreType, types, TransactionalCache.Mode.WRITE); }
[ "public", "<", "T", ">", "T", "createInstance", "(", "DatastoreType", "datastoreType", ",", "DynamicType", "<", "?", ">", "types", ")", "{", "return", "newInstance", "(", "getDatastoreId", "(", "datastoreType", ")", ",", "datastoreType", ",", "types", ",", "...
Return the proxy instance which corresponds to the given datastore type for writing. @param datastoreType The datastore type. @param types The {@link DynamicType}. @param <T> The instance type. @return The instance.
[ "Return", "the", "proxy", "instance", "which", "corresponds", "to", "the", "given", "datastore", "type", "for", "writing", "." ]
train
https://github.com/buschmais/extended-objects/blob/186431e81f3d8d26c511cfe1143dee59b03c2e7a/impl/src/main/java/com/buschmais/xo/impl/AbstractInstanceManager.java#L71-L73
micronaut-projects/micronaut-core
aop/src/main/java/io/micronaut/aop/chain/InterceptorChain.java
InterceptorChain.resolveAroundInterceptors
@Internal public static Interceptor[] resolveAroundInterceptors(BeanContext beanContext, ExecutableMethod<?, ?> method, Interceptor... interceptors) { instrumentAnnotationMetadata(beanContext, method); return resolveInterceptorsInternal(method, Around.class, interceptors); }
java
@Internal public static Interceptor[] resolveAroundInterceptors(BeanContext beanContext, ExecutableMethod<?, ?> method, Interceptor... interceptors) { instrumentAnnotationMetadata(beanContext, method); return resolveInterceptorsInternal(method, Around.class, interceptors); }
[ "@", "Internal", "public", "static", "Interceptor", "[", "]", "resolveAroundInterceptors", "(", "BeanContext", "beanContext", ",", "ExecutableMethod", "<", "?", ",", "?", ">", "method", ",", "Interceptor", "...", "interceptors", ")", "{", "instrumentAnnotationMetada...
Resolves the {@link Around} interceptors for a method. @param beanContext bean context passed in @param method The method @param interceptors The array of interceptors @return The filtered array of interceptors
[ "Resolves", "the", "{", "@link", "Around", "}", "interceptors", "for", "a", "method", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/aop/src/main/java/io/micronaut/aop/chain/InterceptorChain.java#L170-L174
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsPublishScheduled.java
CmsPublishScheduled.computeProjectName
protected String computeProjectName(String rootPath, Date date) { // create the temporary project, which is deleted after publishing // the publish scheduled date in project name String dateTime = CmsDateUtil.getDateTime(date, DateFormat.SHORT, getLocale()); // the resource name to publish scheduled String projectName = key(Messages.GUI_PUBLISH_SCHEDULED_PROJECT_NAME_2, new Object[] {rootPath, dateTime}); // the HTML encoding for slashes is necessary because of the slashes in english date time format // in project names slahes are not allowed, because these are separators for organizaional units projectName = projectName.replace("/", "&#47;"); return projectName; }
java
protected String computeProjectName(String rootPath, Date date) { // create the temporary project, which is deleted after publishing // the publish scheduled date in project name String dateTime = CmsDateUtil.getDateTime(date, DateFormat.SHORT, getLocale()); // the resource name to publish scheduled String projectName = key(Messages.GUI_PUBLISH_SCHEDULED_PROJECT_NAME_2, new Object[] {rootPath, dateTime}); // the HTML encoding for slashes is necessary because of the slashes in english date time format // in project names slahes are not allowed, because these are separators for organizaional units projectName = projectName.replace("/", "&#47;"); return projectName; }
[ "protected", "String", "computeProjectName", "(", "String", "rootPath", ",", "Date", "date", ")", "{", "// create the temporary project, which is deleted after publishing", "// the publish scheduled date in project name", "String", "dateTime", "=", "CmsDateUtil", ".", "getDateTim...
Creates the publish project's name for a given root path and publish date.<p> @param rootPath the publish resource's root path @param date the publish date @return the publish project name
[ "Creates", "the", "publish", "project", "s", "name", "for", "a", "given", "root", "path", "and", "publish", "date", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPublishScheduled.java#L187-L198
mozilla/rhino
toolsrc/org/mozilla/javascript/tools/debugger/Main.java
Main.mainEmbedded
public static Main mainEmbedded(String title) { ContextFactory factory = ContextFactory.getGlobal(); Global global = new Global(); global.init(factory); return mainEmbedded(factory, global, title); }
java
public static Main mainEmbedded(String title) { ContextFactory factory = ContextFactory.getGlobal(); Global global = new Global(); global.init(factory); return mainEmbedded(factory, global, title); }
[ "public", "static", "Main", "mainEmbedded", "(", "String", "title", ")", "{", "ContextFactory", "factory", "=", "ContextFactory", ".", "getGlobal", "(", ")", ";", "Global", "global", "=", "new", "Global", "(", ")", ";", "global", ".", "init", "(", "factory...
Entry point for embedded applications. This method attaches to the global {@link ContextFactory} with a scope of a newly created {@link Global} object. No I/O redirection is performed as with {@link #main(String[])}.
[ "Entry", "point", "for", "embedded", "applications", ".", "This", "method", "attaches", "to", "the", "global", "{" ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/toolsrc/org/mozilla/javascript/tools/debugger/Main.java#L239-L244
jcustenborder/connect-utils
connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java
ConfigUtils.hostAndPort
public static HostAndPort hostAndPort(AbstractConfig config, String key) { return hostAndPort(config, key, null); }
java
public static HostAndPort hostAndPort(AbstractConfig config, String key) { return hostAndPort(config, key, null); }
[ "public", "static", "HostAndPort", "hostAndPort", "(", "AbstractConfig", "config", ",", "String", "key", ")", "{", "return", "hostAndPort", "(", "config", ",", "key", ",", "null", ")", ";", "}" ]
Method is used to parse a string ConfigDef item to a HostAndPort @param config Config to read from @param key ConfigItem to get the host string from. @return HostAndPort based on the ConfigItem.
[ "Method", "is", "used", "to", "parse", "a", "string", "ConfigDef", "item", "to", "a", "HostAndPort" ]
train
https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java#L169-L171
AzureAD/azure-activedirectory-library-for-java
src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java
AuthenticationContext.acquireTokenByDeviceCode
public Future<AuthenticationResult> acquireTokenByDeviceCode( final DeviceCode deviceCode, final AuthenticationCallback callback) throws AuthenticationException { final ClientAuthentication clientAuth = new ClientAuthenticationPost( ClientAuthenticationMethod.NONE, new ClientID(deviceCode.getClientId())); this.validateDeviceCodeRequestInput(deviceCode, clientAuth, deviceCode.getResource()); final AdalDeviceCodeAuthorizationGrant deviceCodeGrant = new AdalDeviceCodeAuthorizationGrant(deviceCode, deviceCode.getResource()); return this.acquireToken(deviceCodeGrant, clientAuth, callback); }
java
public Future<AuthenticationResult> acquireTokenByDeviceCode( final DeviceCode deviceCode, final AuthenticationCallback callback) throws AuthenticationException { final ClientAuthentication clientAuth = new ClientAuthenticationPost( ClientAuthenticationMethod.NONE, new ClientID(deviceCode.getClientId())); this.validateDeviceCodeRequestInput(deviceCode, clientAuth, deviceCode.getResource()); final AdalDeviceCodeAuthorizationGrant deviceCodeGrant = new AdalDeviceCodeAuthorizationGrant(deviceCode, deviceCode.getResource()); return this.acquireToken(deviceCodeGrant, clientAuth, callback); }
[ "public", "Future", "<", "AuthenticationResult", ">", "acquireTokenByDeviceCode", "(", "final", "DeviceCode", "deviceCode", ",", "final", "AuthenticationCallback", "callback", ")", "throws", "AuthenticationException", "{", "final", "ClientAuthentication", "clientAuth", "=",...
Acquires security token from the authority using an device code previously received. @param deviceCode The device code result received from calling acquireDeviceCode. @param callback optional callback object for non-blocking execution. @return A {@link Future} object representing the {@link AuthenticationResult} of the call. It contains AccessToken, Refresh Token and the Access Token's expiration time. @throws AuthenticationException thrown if authorization is pending or another error occurred. If the errorCode of the exception is AdalErrorCode.AUTHORIZATION_PENDING, the call needs to be retried until the AccessToken is returned. DeviceCode.interval - The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoin
[ "Acquires", "security", "token", "from", "the", "authority", "using", "an", "device", "code", "previously", "received", "." ]
train
https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java#L640-L652
grails/grails-core
grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java
DirectoryWatcher.addWatchDirectory
public void addWatchDirectory(File dir, List<String> fileExtensions) { List<String> fileExtensionsWithoutDot = new ArrayList<String>(fileExtensions.size()); for(String fileExtension : fileExtensions){ fileExtensionsWithoutDot.add(removeStartingDotIfPresent(fileExtension)); } directoryWatcherDelegate.addWatchDirectory(dir, fileExtensions); }
java
public void addWatchDirectory(File dir, List<String> fileExtensions) { List<String> fileExtensionsWithoutDot = new ArrayList<String>(fileExtensions.size()); for(String fileExtension : fileExtensions){ fileExtensionsWithoutDot.add(removeStartingDotIfPresent(fileExtension)); } directoryWatcherDelegate.addWatchDirectory(dir, fileExtensions); }
[ "public", "void", "addWatchDirectory", "(", "File", "dir", ",", "List", "<", "String", ">", "fileExtensions", ")", "{", "List", "<", "String", ">", "fileExtensionsWithoutDot", "=", "new", "ArrayList", "<", "String", ">", "(", "fileExtensions", ".", "size", "...
Adds a directory to watch for the given file and extensions. @param dir The directory @param fileExtensions The extensions
[ "Adds", "a", "directory", "to", "watch", "for", "the", "given", "file", "and", "extensions", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-bootstrap/src/main/groovy/org/grails/io/watch/DirectoryWatcher.java#L124-L130
joniles/mpxj
src/main/java/net/sf/mpxj/asta/AstaReader.java
AstaReader.createTasks
private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows) { for (Row row : rows) { boolean rowIsBar = (row.getInteger("BARID") != null); // // Don't export hammock tasks. // if (rowIsBar && row.getChildRows().isEmpty()) { continue; } Task task = parent.addTask(); // // Do we have a bar, task, or milestone? // if (rowIsBar) { // // If the bar only has one child task, we skip it and add the task directly // if (skipBar(row)) { populateLeaf(row.getString("NAMH"), row.getChildRows().get(0), task); } else { populateBar(row, task); createTasks(task, task.getName(), row.getChildRows()); } } else { populateLeaf(parentName, row, task); } m_eventManager.fireTaskReadEvent(task); } }
java
private void createTasks(ChildTaskContainer parent, String parentName, List<Row> rows) { for (Row row : rows) { boolean rowIsBar = (row.getInteger("BARID") != null); // // Don't export hammock tasks. // if (rowIsBar && row.getChildRows().isEmpty()) { continue; } Task task = parent.addTask(); // // Do we have a bar, task, or milestone? // if (rowIsBar) { // // If the bar only has one child task, we skip it and add the task directly // if (skipBar(row)) { populateLeaf(row.getString("NAMH"), row.getChildRows().get(0), task); } else { populateBar(row, task); createTasks(task, task.getName(), row.getChildRows()); } } else { populateLeaf(parentName, row, task); } m_eventManager.fireTaskReadEvent(task); } }
[ "private", "void", "createTasks", "(", "ChildTaskContainer", "parent", ",", "String", "parentName", ",", "List", "<", "Row", ">", "rows", ")", "{", "for", "(", "Row", "row", ":", "rows", ")", "{", "boolean", "rowIsBar", "=", "(", "row", ".", "getInteger"...
Recursively descend through the hierarchy creating tasks. @param parent parent task @param parentName parent name @param rows rows to add as tasks to this parent
[ "Recursively", "descend", "through", "the", "hierarchy", "creating", "tasks", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/asta/AstaReader.java#L322-L363
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/SessionManagerActor.java
SessionManagerActor.spawnSession
private PeerSession spawnSession(int uid, int ownKeyGroup, int theirKeyGroup, PrivateKey ownIdentity, PublicKey theirIdentity, PrivateKey ownPreKey, PublicKey theirPreKey) { // // Calculating Master Secret // byte[] masterSecret = RatchetMasterSecret.calculateMasterSecret( new RatchetPrivateKey(ownIdentity.getKey()), new RatchetPrivateKey(ownPreKey.getKey()), new RatchetPublicKey(theirIdentity.getPublicKey()), new RatchetPublicKey(theirPreKey.getPublicKey()) ); // // Building Session // PeerSession peerSession = new PeerSession(RandomUtils.nextRid(), uid, ownKeyGroup, theirKeyGroup, ownPreKey.getKeyId(), theirPreKey.getKeyId(), masterSecret ); // // Saving session in sessions storage // PeerSessionsStorage sessionsStorage = peerSessions.getValue(uid); if (sessionsStorage == null) { sessionsStorage = new PeerSessionsStorage(uid, new ArrayList<PeerSession>()); } sessionsStorage = sessionsStorage.addSession(peerSession); peerSessions.addOrUpdateItem(sessionsStorage); return peerSession; }
java
private PeerSession spawnSession(int uid, int ownKeyGroup, int theirKeyGroup, PrivateKey ownIdentity, PublicKey theirIdentity, PrivateKey ownPreKey, PublicKey theirPreKey) { // // Calculating Master Secret // byte[] masterSecret = RatchetMasterSecret.calculateMasterSecret( new RatchetPrivateKey(ownIdentity.getKey()), new RatchetPrivateKey(ownPreKey.getKey()), new RatchetPublicKey(theirIdentity.getPublicKey()), new RatchetPublicKey(theirPreKey.getPublicKey()) ); // // Building Session // PeerSession peerSession = new PeerSession(RandomUtils.nextRid(), uid, ownKeyGroup, theirKeyGroup, ownPreKey.getKeyId(), theirPreKey.getKeyId(), masterSecret ); // // Saving session in sessions storage // PeerSessionsStorage sessionsStorage = peerSessions.getValue(uid); if (sessionsStorage == null) { sessionsStorage = new PeerSessionsStorage(uid, new ArrayList<PeerSession>()); } sessionsStorage = sessionsStorage.addSession(peerSession); peerSessions.addOrUpdateItem(sessionsStorage); return peerSession; }
[ "private", "PeerSession", "spawnSession", "(", "int", "uid", ",", "int", "ownKeyGroup", ",", "int", "theirKeyGroup", ",", "PrivateKey", "ownIdentity", ",", "PublicKey", "theirIdentity", ",", "PrivateKey", "ownPreKey", ",", "PublicKey", "theirPreKey", ")", "{", "//...
Spawn new session @param uid user's id @param ownKeyGroup own key group id @param theirKeyGroup their key group Id @param ownIdentity own identity private key @param theirIdentity their identity public key @param ownPreKey own pre key @param theirPreKey their pre key @return spawned session
[ "Spawn", "new", "session" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/SessionManagerActor.java#L173-L216
authlete/authlete-java-common
src/main/java/com/authlete/common/api/AuthleteApiImpl.java
AuthleteApiImpl.callServiceOwnerPostApi
private <TResponse> TResponse callServiceOwnerPostApi( String path, Map<String, String> queryParams, Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException { return callPostApi(mServiceOwnerCredentials, path, queryParams, requestBody, responseClass); }
java
private <TResponse> TResponse callServiceOwnerPostApi( String path, Map<String, String> queryParams, Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException { return callPostApi(mServiceOwnerCredentials, path, queryParams, requestBody, responseClass); }
[ "private", "<", "TResponse", ">", "TResponse", "callServiceOwnerPostApi", "(", "String", "path", ",", "Map", "<", "String", ",", "String", ">", "queryParams", ",", "Object", "requestBody", ",", "Class", "<", "TResponse", ">", "responseClass", ")", "throws", "A...
Call an API with HTTP POST method and Service Owner credentials.
[ "Call", "an", "API", "with", "HTTP", "POST", "method", "and", "Service", "Owner", "credentials", "." ]
train
https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L315-L320
erlang/otp
lib/jinterface/java_src/com/ericsson/otp/erlang/OtpNode.java
OtpNode.deliverError
void deliverError(final OtpCookedConnection conn, final Exception e) { removeConnection(conn); remoteStatus(conn.name, false, e); }
java
void deliverError(final OtpCookedConnection conn, final Exception e) { removeConnection(conn); remoteStatus(conn.name, false, e); }
[ "void", "deliverError", "(", "final", "OtpCookedConnection", "conn", ",", "final", "Exception", "e", ")", "{", "removeConnection", "(", "conn", ")", ";", "remoteStatus", "(", "conn", ".", "name", ",", "false", ",", "e", ")", ";", "}" ]
/* OtpCookedConnection delivers errors here, we send them on to the handler specified by the application
[ "/", "*", "OtpCookedConnection", "delivers", "errors", "here", "we", "send", "them", "on", "to", "the", "handler", "specified", "by", "the", "application" ]
train
https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/OtpNode.java#L554-L557
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/JMessageClient.java
JMessageClient.getGroupStatistic
public GroupStatListResult getGroupStatistic(String start, int duration) throws APIConnectionException, APIRequestException { return _reportClient.getGroupStatistic(start, duration); }
java
public GroupStatListResult getGroupStatistic(String start, int duration) throws APIConnectionException, APIRequestException { return _reportClient.getGroupStatistic(start, duration); }
[ "public", "GroupStatListResult", "getGroupStatistic", "(", "String", "start", ",", "int", "duration", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "return", "_reportClient", ".", "getGroupStatistic", "(", "start", ",", "duration", ")", ";"...
Get group statistic, time unit only supports DAY now. @param start Format: yyyy-MM-dd @param duration duration must between 0 and 60 @return {@link GroupStatListResult} @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Get", "group", "statistic", "time", "unit", "only", "supports", "DAY", "now", "." ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/JMessageClient.java#L1023-L1026
dmfs/httpurlconnection-executor
src/org/dmfs/httpessentials/httpurlconnection/HttpUrlConnectionExecutor.java
HttpUrlConnectionExecutor.sendRequest
private <T> HttpResponse sendRequest(final URI uri, final HttpRequest<T> request) throws IOException, ProtocolException { final HttpURLConnection connection; try { connection = mConnectionFactory.httpUrlConnection(uri); } catch (IllegalArgumentException e) { throw new ProtocolException("The given URI is not applicable to HTTP requests.", e); } // ensure the expected redirect behavior connection.setInstanceFollowRedirects(false); // set the request method connection.setDoOutput(request.method().supportsRequestPayload()); connection.setRequestMethod(request.method().verb()); // add all headers for (Header<?> header : request.headers()) { connection.setRequestProperty(header.type().name(), header.toString()); } // also set the content-type header if we have any content-type if (request.requestEntity().contentType() != null) { connection.setRequestProperty(HttpHeaders.CONTENT_TYPE.name(), HttpHeaders.CONTENT_TYPE.valueString(request.requestEntity().contentType())); } // send the request entity if applicable if (request.method().supportsRequestPayload()) { OutputStream out = connection.getOutputStream(); try { request.requestEntity().writeContent(out); } finally { out.close(); } } // return the response return new HttpUrlConnectionResponse(uri, connection); }
java
private <T> HttpResponse sendRequest(final URI uri, final HttpRequest<T> request) throws IOException, ProtocolException { final HttpURLConnection connection; try { connection = mConnectionFactory.httpUrlConnection(uri); } catch (IllegalArgumentException e) { throw new ProtocolException("The given URI is not applicable to HTTP requests.", e); } // ensure the expected redirect behavior connection.setInstanceFollowRedirects(false); // set the request method connection.setDoOutput(request.method().supportsRequestPayload()); connection.setRequestMethod(request.method().verb()); // add all headers for (Header<?> header : request.headers()) { connection.setRequestProperty(header.type().name(), header.toString()); } // also set the content-type header if we have any content-type if (request.requestEntity().contentType() != null) { connection.setRequestProperty(HttpHeaders.CONTENT_TYPE.name(), HttpHeaders.CONTENT_TYPE.valueString(request.requestEntity().contentType())); } // send the request entity if applicable if (request.method().supportsRequestPayload()) { OutputStream out = connection.getOutputStream(); try { request.requestEntity().writeContent(out); } finally { out.close(); } } // return the response return new HttpUrlConnectionResponse(uri, connection); }
[ "private", "<", "T", ">", "HttpResponse", "sendRequest", "(", "final", "URI", "uri", ",", "final", "HttpRequest", "<", "T", ">", "request", ")", "throws", "IOException", ",", "ProtocolException", "{", "final", "HttpURLConnection", "connection", ";", "try", "{"...
Sends the request and returns an {@link HttpResponse}. @param uri The URL to connect to. @param request The {@link HttpRequest} to send. @return An {@link HttpResponse}. @throws MalformedURLException @throws IOException @throws ProtocolException
[ "Sends", "the", "request", "and", "returns", "an", "{", "@link", "HttpResponse", "}", "." ]
train
https://github.com/dmfs/httpurlconnection-executor/blob/e5f58c0a500804fdb1ead2f5fd67259e5c23ee93/src/org/dmfs/httpessentials/httpurlconnection/HttpUrlConnectionExecutor.java#L95-L136
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java
CommonDatabaseMetaData.getSchemas
public ResultSet getSchemas(final String catalog, final String schemaPattern) throws SQLException { final String query = "SELECT schema_name table_schem, " + "null table_catalog " + "FROM information_schema.schemata " + (schemaPattern != null ? "WHERE schema_name like '" + schemaPattern + "'" : "") + " ORDER BY table_schem"; final Statement stmt = connection.createStatement(); return stmt.executeQuery(query); }
java
public ResultSet getSchemas(final String catalog, final String schemaPattern) throws SQLException { final String query = "SELECT schema_name table_schem, " + "null table_catalog " + "FROM information_schema.schemata " + (schemaPattern != null ? "WHERE schema_name like '" + schemaPattern + "'" : "") + " ORDER BY table_schem"; final Statement stmt = connection.createStatement(); return stmt.executeQuery(query); }
[ "public", "ResultSet", "getSchemas", "(", "final", "String", "catalog", ",", "final", "String", "schemaPattern", ")", "throws", "SQLException", "{", "final", "String", "query", "=", "\"SELECT schema_name table_schem, \"", "+", "\"null table_catalog \"", "+", "\"FROM inf...
Retrieves the schema names available in this database. The results are ordered by <code>TABLE_CATALOG</code> and <code>TABLE_SCHEM</code>. <p/> <P>The schema columns are: <OL> <LI><B>TABLE_SCHEM</B> String => schema name <LI><B>TABLE_CATALOG</B> String => catalog name (may be <code>null</code>) </OL> @param catalog a catalog name; must match the catalog name as it is stored in the database;"" retrieves those without a catalog; null means catalog name should not be used to narrow down the search. @param schemaPattern a schema name; must match the schema name as it is stored in the database; null means schema name should not be used to narrow down the search. @return a <code>ResultSet</code> object in which each row is a schema description @throws java.sql.SQLException if a database access error occurs @see #getSearchStringEscape @since 1.6
[ "Retrieves", "the", "schema", "names", "available", "in", "this", "database", ".", "The", "results", "are", "ordered", "by", "<code", ">", "TABLE_CATALOG<", "/", "code", ">", "and", "<code", ">", "TABLE_SCHEM<", "/", "code", ">", ".", "<p", "/", ">", "<P...
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java#L2538-L2546
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.isInsideCurrentProject
public boolean isInsideCurrentProject(CmsDbContext dbc, String resourcename) { List<String> projectResources = null; try { projectResources = readProjectResources(dbc, dbc.currentProject()); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.LOG_CHECK_RESOURCE_INSIDE_CURRENT_PROJECT_2, resourcename, dbc.currentProject().getName()), e); } return false; } return CmsProject.isInsideProject(projectResources, resourcename); }
java
public boolean isInsideCurrentProject(CmsDbContext dbc, String resourcename) { List<String> projectResources = null; try { projectResources = readProjectResources(dbc, dbc.currentProject()); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.LOG_CHECK_RESOURCE_INSIDE_CURRENT_PROJECT_2, resourcename, dbc.currentProject().getName()), e); } return false; } return CmsProject.isInsideProject(projectResources, resourcename); }
[ "public", "boolean", "isInsideCurrentProject", "(", "CmsDbContext", "dbc", ",", "String", "resourcename", ")", "{", "List", "<", "String", ">", "projectResources", "=", "null", ";", "try", "{", "projectResources", "=", "readProjectResources", "(", "dbc", ",", "d...
Checks if the specified resource is inside the current project.<p> The project "view" is determined by a set of path prefixes. If the resource starts with any one of this prefixes, it is considered to be "inside" the project.<p> @param dbc the current database context @param resourcename the specified resource name (full path) @return <code>true</code>, if the specified resource is inside the current project
[ "Checks", "if", "the", "specified", "resource", "is", "inside", "the", "current", "project", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L5222-L5239
pac4j/pac4j
pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPRedirectDeflateEncoder.java
Pac4jHTTPRedirectDeflateEncoder.deflateAndBase64Encode
String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException { log.debug("Deflating and Base64 encoding SAML message"); try { String messageStr = SerializeSupport.nodeToString(marshallMessage(message)); log.trace("Output XML message: {}", messageStr); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.DEFLATED, true); DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater); deflaterStream.write(messageStr.getBytes(StandardCharsets.UTF_8)); deflaterStream.finish(); return Base64Support.encode(bytesOut.toByteArray(), Base64Support.UNCHUNKED); } catch (IOException e) { throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e); } }
java
String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException { log.debug("Deflating and Base64 encoding SAML message"); try { String messageStr = SerializeSupport.nodeToString(marshallMessage(message)); log.trace("Output XML message: {}", messageStr); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.DEFLATED, true); DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater); deflaterStream.write(messageStr.getBytes(StandardCharsets.UTF_8)); deflaterStream.finish(); return Base64Support.encode(bytesOut.toByteArray(), Base64Support.UNCHUNKED); } catch (IOException e) { throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e); } }
[ "String", "deflateAndBase64Encode", "(", "SAMLObject", "message", ")", "throws", "MessageEncodingException", "{", "log", ".", "debug", "(", "\"Deflating and Base64 encoding SAML message\"", ")", ";", "try", "{", "String", "messageStr", "=", "SerializeSupport", ".", "nod...
DEFLATE (RFC1951) compresses the given SAML message. @param message SAML message @return DEFLATE compressed message @throws MessageEncodingException thrown if there is a problem compressing the message
[ "DEFLATE", "(", "RFC1951", ")", "compresses", "the", "given", "SAML", "message", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPRedirectDeflateEncoder.java#L121-L137
michael-rapp/AndroidPreferenceActivity
example/src/main/java/de/mrapp/android/preference/activity/example/fragment/BehaviorPreferenceFragment.java
BehaviorPreferenceFragment.createHideNavigationChangeListener
private OnPreferenceChangeListener createHideNavigationChangeListener() { return new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { if (newValue != null) { boolean hideNavigation = (boolean) newValue; ((PreferenceActivity) getActivity()).hideNavigation(hideNavigation); } return true; } }; }
java
private OnPreferenceChangeListener createHideNavigationChangeListener() { return new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { if (newValue != null) { boolean hideNavigation = (boolean) newValue; ((PreferenceActivity) getActivity()).hideNavigation(hideNavigation); } return true; } }; }
[ "private", "OnPreferenceChangeListener", "createHideNavigationChangeListener", "(", ")", "{", "return", "new", "OnPreferenceChangeListener", "(", ")", "{", "@", "Override", "public", "boolean", "onPreferenceChange", "(", "final", "Preference", "preference", ",", "final", ...
Creates a listener, which allows to adapt the behavior of the {@link PreferenceActivity} when the value, which determines, whether the navigation should be hidden, has been changed. @return The listener, which has been created, as an instance of the type {@link OnPreferenceChangeListener}
[ "Creates", "a", "listener", "which", "allows", "to", "adapt", "the", "behavior", "of", "the", "{", "@link", "PreferenceActivity", "}", "when", "the", "value", "which", "determines", "whether", "the", "navigation", "should", "be", "hidden", "has", "been", "chan...
train
https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/example/src/main/java/de/mrapp/android/preference/activity/example/fragment/BehaviorPreferenceFragment.java#L68-L82
OpenLiberty/open-liberty
dev/com.ibm.ws.org.apache.cxf.cxf.core.3.2/src/org/apache/cxf/common/util/ProxyHelper.java
ProxyHelper.getClassLoaderForInterfaces
private ClassLoader getClassLoaderForInterfaces(final ClassLoader loader, final Class<?>[] interfaces) { if (canSeeAllInterfaces(loader, interfaces)) { LOG.log(Level.FINE, "current classloader " + loader + " can see all interface"); return loader; } String sortedNameFromInterfaceArray = getSortedNameFromInterfaceArray(interfaces); ClassLoader cachedLoader = proxyClassLoaderCache.getProxyClassLoader(loader, interfaces); if (canSeeAllInterfaces(cachedLoader, interfaces)) { LOG.log(Level.FINE, "find required loader from ProxyClassLoader cache with key" + sortedNameFromInterfaceArray); return cachedLoader; } else { LOG.log(Level.FINE, "find a loader from ProxyClassLoader cache with interfaces " + sortedNameFromInterfaceArray + " but can't see all interfaces"); for (Class<?> currentInterface : interfaces) { String ifName = currentInterface.getName(); if (!ifName.startsWith("org.apache.cxf") && !ifName.startsWith("java")) { // remove the stale ProxyClassLoader and recreate one proxyClassLoaderCache.removeStaleProxyClassLoader(currentInterface); cachedLoader = proxyClassLoaderCache.getProxyClassLoader(loader, interfaces); } } } return cachedLoader; }
java
private ClassLoader getClassLoaderForInterfaces(final ClassLoader loader, final Class<?>[] interfaces) { if (canSeeAllInterfaces(loader, interfaces)) { LOG.log(Level.FINE, "current classloader " + loader + " can see all interface"); return loader; } String sortedNameFromInterfaceArray = getSortedNameFromInterfaceArray(interfaces); ClassLoader cachedLoader = proxyClassLoaderCache.getProxyClassLoader(loader, interfaces); if (canSeeAllInterfaces(cachedLoader, interfaces)) { LOG.log(Level.FINE, "find required loader from ProxyClassLoader cache with key" + sortedNameFromInterfaceArray); return cachedLoader; } else { LOG.log(Level.FINE, "find a loader from ProxyClassLoader cache with interfaces " + sortedNameFromInterfaceArray + " but can't see all interfaces"); for (Class<?> currentInterface : interfaces) { String ifName = currentInterface.getName(); if (!ifName.startsWith("org.apache.cxf") && !ifName.startsWith("java")) { // remove the stale ProxyClassLoader and recreate one proxyClassLoaderCache.removeStaleProxyClassLoader(currentInterface); cachedLoader = proxyClassLoaderCache.getProxyClassLoader(loader, interfaces); } } } return cachedLoader; }
[ "private", "ClassLoader", "getClassLoaderForInterfaces", "(", "final", "ClassLoader", "loader", ",", "final", "Class", "<", "?", ">", "[", "]", "interfaces", ")", "{", "if", "(", "canSeeAllInterfaces", "(", "loader", ",", "interfaces", ")", ")", "{", "LOG", ...
Return a classloader that can see all the given interfaces If the given loader can see all interfaces then it is used. If not then a combined classloader of all interface classloaders is returned. @param loader use supplied class loader @param interfaces @return classloader that sees all interfaces
[ "Return", "a", "classloader", "that", "can", "see", "all", "the", "given", "interfaces", "If", "the", "given", "loader", "can", "see", "all", "interfaces", "then", "it", "is", "used", ".", "If", "not", "then", "a", "combined", "classloader", "of", "all", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.cxf.cxf.core.3.2/src/org/apache/cxf/common/util/ProxyHelper.java#L61-L89
xwiki/xwiki-rendering
xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/impl/WikiScannerUtil.java
WikiScannerUtil.skipSequence
public static int skipSequence(char[] array, int arrayPos, char[] sequence) { int i; int j; for (i = arrayPos, j = 0; i < array.length && j < sequence.length; i++, j++) { if (array[i] != sequence[j]) { break; } } return j == sequence.length ? i : arrayPos; }
java
public static int skipSequence(char[] array, int arrayPos, char[] sequence) { int i; int j; for (i = arrayPos, j = 0; i < array.length && j < sequence.length; i++, j++) { if (array[i] != sequence[j]) { break; } } return j == sequence.length ? i : arrayPos; }
[ "public", "static", "int", "skipSequence", "(", "char", "[", "]", "array", ",", "int", "arrayPos", ",", "char", "[", "]", "sequence", ")", "{", "int", "i", ";", "int", "j", ";", "for", "(", "i", "=", "arrayPos", ",", "j", "=", "0", ";", "i", "<...
Skips the specified sequence if it starts from the given position in the character array. @param array the array of characters @param arrayPos the position of the first character in the array; starting from this position the sequence should be skipped @param sequence the sequence of characters to skip @return a new value of the character counter
[ "Skips", "the", "specified", "sequence", "if", "it", "starts", "from", "the", "given", "position", "in", "the", "character", "array", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-wikimodel/src/main/java/org/xwiki/rendering/wikimodel/impl/WikiScannerUtil.java#L301-L311
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/categories/sdcard.java
sdcard.renameOrMove
public static boolean renameOrMove(File fileToBeMoved, File destination) { boolean result = fileToBeMoved.renameTo(destination); if (result) { log.d("File " + fileToBeMoved.getPath() + " was succesfully renamed or moved."); } else { log.e("File " + fileToBeMoved.getPath() + " couldn't be renamed or moved."); } return result; }
java
public static boolean renameOrMove(File fileToBeMoved, File destination) { boolean result = fileToBeMoved.renameTo(destination); if (result) { log.d("File " + fileToBeMoved.getPath() + " was succesfully renamed or moved."); } else { log.e("File " + fileToBeMoved.getPath() + " couldn't be renamed or moved."); } return result; }
[ "public", "static", "boolean", "renameOrMove", "(", "File", "fileToBeMoved", ",", "File", "destination", ")", "{", "boolean", "result", "=", "fileToBeMoved", ".", "renameTo", "(", "destination", ")", ";", "if", "(", "result", ")", "{", "log", ".", "d", "("...
Renames or moves a determined {@link File} instance to a destination defined by another {@link File} instance.<br> Differs from the {@link File#renameTo(File)} method in the fact that this method logs if the operation was successful.<br> @see File#renameTo(File) @param fileToBeMoved The file to be renamed or moved. @param destination The {@link File} instance that denotes the new location @return <b>boolean</b> true if the file has been successfully renamed or moved.
[ "Renames", "or", "moves", "a", "determined", "{", "@link", "File", "}", "instance", "to", "a", "destination", "defined", "by", "another", "{", "@link", "File", "}", "instance", ".", "<br", ">", "Differs", "from", "the", "{", "@link", "File#renameTo", "(", ...
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/sdcard.java#L439-L447
xbib/marc
src/main/java/org/xbib/marc/transformer/value/MarcValueTransformers.java
MarcValueTransformers.setMarcValueTransformer
public MarcValueTransformers setMarcValueTransformer(String fieldKey, MarcValueTransformer transformer) { // split into tag + indicator and subfield IDs int pos = fieldKey.lastIndexOf('$'); String tagind = pos > 0 ? fieldKey.substring(0, pos) : fieldKey; String subs = pos > 0 ? fieldKey.substring(pos + 1) : ""; this.marcValueTransformerMap.put(tagind, transformer); // subfield IDs this.subfieldMap.put(tagind, subs); return this; }
java
public MarcValueTransformers setMarcValueTransformer(String fieldKey, MarcValueTransformer transformer) { // split into tag + indicator and subfield IDs int pos = fieldKey.lastIndexOf('$'); String tagind = pos > 0 ? fieldKey.substring(0, pos) : fieldKey; String subs = pos > 0 ? fieldKey.substring(pos + 1) : ""; this.marcValueTransformerMap.put(tagind, transformer); // subfield IDs this.subfieldMap.put(tagind, subs); return this; }
[ "public", "MarcValueTransformers", "setMarcValueTransformer", "(", "String", "fieldKey", ",", "MarcValueTransformer", "transformer", ")", "{", "// split into tag + indicator and subfield IDs", "int", "pos", "=", "fieldKey", ".", "lastIndexOf", "(", "'", "'", ")", ";", ...
Set MARC value transformer for transforming field values. @param fieldKey the MARC field key for the field to be transformed @param transformer the string transformer @return this handler
[ "Set", "MARC", "value", "transformer", "for", "transforming", "field", "values", "." ]
train
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/transformer/value/MarcValueTransformers.java#L45-L54
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java
SerializedFormBuilder.buildFieldDeprecationInfo
public void buildFieldDeprecationInfo(XMLNode node, Content fieldsContentTree) { if (!utils.definesSerializableFields(currentTypeElement)) { fieldWriter.addMemberDeprecatedInfo((VariableElement)currentMember, fieldsContentTree); } }
java
public void buildFieldDeprecationInfo(XMLNode node, Content fieldsContentTree) { if (!utils.definesSerializableFields(currentTypeElement)) { fieldWriter.addMemberDeprecatedInfo((VariableElement)currentMember, fieldsContentTree); } }
[ "public", "void", "buildFieldDeprecationInfo", "(", "XMLNode", "node", ",", "Content", "fieldsContentTree", ")", "{", "if", "(", "!", "utils", ".", "definesSerializableFields", "(", "currentTypeElement", ")", ")", "{", "fieldWriter", ".", "addMemberDeprecatedInfo", ...
Build the field deprecation information. @param node the XML element that specifies which components to document @param fieldsContentTree content tree to which the documentation will be added
[ "Build", "the", "field", "deprecation", "information", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java#L470-L475
jenkinsci/github-plugin
src/main/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredBackrefSource.java
ManuallyEnteredBackrefSource.get
@SuppressWarnings("deprecation") @Override public String get(Run<?, ?> run, TaskListener listener) { try { return new ExpandableMessage(backref).expandAll(run, listener); } catch (Exception e) { LOG.debug("Can't expand backref, returning as is", e); return backref; } }
java
@SuppressWarnings("deprecation") @Override public String get(Run<?, ?> run, TaskListener listener) { try { return new ExpandableMessage(backref).expandAll(run, listener); } catch (Exception e) { LOG.debug("Can't expand backref, returning as is", e); return backref; } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "@", "Override", "public", "String", "get", "(", "Run", "<", "?", ",", "?", ">", "run", ",", "TaskListener", "listener", ")", "{", "try", "{", "return", "new", "ExpandableMessage", "(", "backref", ")", ...
Just returns what user entered. Expands env vars and token macro
[ "Just", "returns", "what", "user", "entered", ".", "Expands", "env", "vars", "and", "token", "macro" ]
train
https://github.com/jenkinsci/github-plugin/blob/4e05b9aeb488af5342c78f78aa3c55114e8d462a/src/main/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredBackrefSource.java#L38-L47
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeUtil.java
SnowflakeUtil.checkErrorAndThrowExceptionSub
static private void checkErrorAndThrowExceptionSub( JsonNode rootNode, boolean raiseReauthenticateError) throws SnowflakeSQLException { // no need to throw exception if success if (rootNode.path("success").asBoolean()) { return; } String errorMessage; String sqlState; int errorCode; String queryId = "unknown"; // if we have sqlstate in data, it's a sql error if (!rootNode.path("data").path("sqlState").isMissingNode()) { sqlState = rootNode.path("data").path("sqlState").asText(); errorCode = rootNode.path("data").path("errorCode").asInt(); queryId = rootNode.path("data").path("queryId").asText(); errorMessage = rootNode.path("message").asText(); } else { sqlState = SqlState.INTERNAL_ERROR; // use internal error sql state // check if there is an error code in the envelope if (!rootNode.path("code").isMissingNode()) { errorCode = rootNode.path("code").asInt(); errorMessage = rootNode.path("message").asText(); } else { errorCode = ErrorCode.INTERNAL_ERROR.getMessageCode(); errorMessage = "no_error_code_from_server"; try { PrintWriter writer = new PrintWriter("output.json", "UTF-8"); writer.print(rootNode.toString()); } catch (Exception ex) { logger.debug("{}", ex); } } } if (raiseReauthenticateError) { switch (errorCode) { case ID_TOKEN_EXPIRED_GS_CODE: case SESSION_NOT_EXIST_GS_CODE: case MASTER_TOKEN_NOTFOUND: case MASTER_EXPIRED_GS_CODE: case MASTER_TOKEN_INVALID_GS_CODE: throw new SnowflakeReauthenticationRequest( queryId, errorMessage, sqlState, errorCode); } } throw new SnowflakeSQLException(queryId, errorMessage, sqlState, errorCode); }
java
static private void checkErrorAndThrowExceptionSub( JsonNode rootNode, boolean raiseReauthenticateError) throws SnowflakeSQLException { // no need to throw exception if success if (rootNode.path("success").asBoolean()) { return; } String errorMessage; String sqlState; int errorCode; String queryId = "unknown"; // if we have sqlstate in data, it's a sql error if (!rootNode.path("data").path("sqlState").isMissingNode()) { sqlState = rootNode.path("data").path("sqlState").asText(); errorCode = rootNode.path("data").path("errorCode").asInt(); queryId = rootNode.path("data").path("queryId").asText(); errorMessage = rootNode.path("message").asText(); } else { sqlState = SqlState.INTERNAL_ERROR; // use internal error sql state // check if there is an error code in the envelope if (!rootNode.path("code").isMissingNode()) { errorCode = rootNode.path("code").asInt(); errorMessage = rootNode.path("message").asText(); } else { errorCode = ErrorCode.INTERNAL_ERROR.getMessageCode(); errorMessage = "no_error_code_from_server"; try { PrintWriter writer = new PrintWriter("output.json", "UTF-8"); writer.print(rootNode.toString()); } catch (Exception ex) { logger.debug("{}", ex); } } } if (raiseReauthenticateError) { switch (errorCode) { case ID_TOKEN_EXPIRED_GS_CODE: case SESSION_NOT_EXIST_GS_CODE: case MASTER_TOKEN_NOTFOUND: case MASTER_EXPIRED_GS_CODE: case MASTER_TOKEN_INVALID_GS_CODE: throw new SnowflakeReauthenticationRequest( queryId, errorMessage, sqlState, errorCode); } } throw new SnowflakeSQLException(queryId, errorMessage, sqlState, errorCode); }
[ "static", "private", "void", "checkErrorAndThrowExceptionSub", "(", "JsonNode", "rootNode", ",", "boolean", "raiseReauthenticateError", ")", "throws", "SnowflakeSQLException", "{", "// no need to throw exception if success", "if", "(", "rootNode", ".", "path", "(", "\"succe...
Check the error in the JSON node and generate an exception based on information extracted from the node. @param rootNode json object contains error information @param raiseReauthenticateError raises SnowflakeReauthenticationRequest if true @throws SnowflakeSQLException the exception get from the error in the json
[ "Check", "the", "error", "in", "the", "JSON", "node", "and", "generate", "an", "exception", "based", "on", "information", "extracted", "from", "the", "node", "." ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeUtil.java#L76-L141
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java
LegacyBehavior.areEqualEventSubscriptions
protected static boolean areEqualEventSubscriptions(EventSubscriptionEntity subscription1, EventSubscriptionEntity subscription2) { return valuesEqual(subscription1.getEventType(), subscription2.getEventType()) && valuesEqual(subscription1.getEventName(), subscription2.getEventName()) && valuesEqual(subscription1.getActivityId(), subscription2.getActivityId()); }
java
protected static boolean areEqualEventSubscriptions(EventSubscriptionEntity subscription1, EventSubscriptionEntity subscription2) { return valuesEqual(subscription1.getEventType(), subscription2.getEventType()) && valuesEqual(subscription1.getEventName(), subscription2.getEventName()) && valuesEqual(subscription1.getActivityId(), subscription2.getActivityId()); }
[ "protected", "static", "boolean", "areEqualEventSubscriptions", "(", "EventSubscriptionEntity", "subscription1", ",", "EventSubscriptionEntity", "subscription2", ")", "{", "return", "valuesEqual", "(", "subscription1", ".", "getEventType", "(", ")", ",", "subscription2", ...
Checks if the parameters are the same apart from the execution id
[ "Checks", "if", "the", "parameters", "are", "the", "same", "apart", "from", "the", "execution", "id" ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java#L450-L455
livetribe/livetribe-slp
core/src/main/java/org/livetribe/slp/settings/Factories.java
Factories.newInstance
public static <T> T newInstance(Settings settings, Key<String> key) throws ServiceLocationException { // Workaround for compiler bug (#6302954) return Factories.<T>newInstance(settings, key, Thread.currentThread().getContextClassLoader()); }
java
public static <T> T newInstance(Settings settings, Key<String> key) throws ServiceLocationException { // Workaround for compiler bug (#6302954) return Factories.<T>newInstance(settings, key, Thread.currentThread().getContextClassLoader()); }
[ "public", "static", "<", "T", ">", "T", "newInstance", "(", "Settings", "settings", ",", "Key", "<", "String", ">", "key", ")", "throws", "ServiceLocationException", "{", "// Workaround for compiler bug (#6302954)", "return", "Factories", ".", "<", "T", ">", "ne...
Creates a new instance of a class whose full qualified name is specified under the given key. <br /> The class will be loaded using the current context ClassLoader. <br /> If the given settings is null, or it does not contain the specified key, the default value of the key is taken from the {@link Defaults defaults}. @param settings the configuration settings that may specify the full qualified name of the class to create, overriding the default value @param key the key under which the full qualified name of the class is specified @return a new instance of the class specified by the given key @throws ServiceLocationException if the instance cannot be created @see #newInstance(Settings, Key, ClassLoader)
[ "Creates", "a", "new", "instance", "of", "a", "class", "whose", "full", "qualified", "name", "is", "specified", "under", "the", "given", "key", ".", "<br", "/", ">", "The", "class", "will", "be", "loaded", "using", "the", "current", "context", "ClassLoader...
train
https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/settings/Factories.java#L43-L47
facebookarchive/hadoop-20
src/tools/org/apache/hadoop/tools/Logalyzer.java
Logalyzer.doArchive
public void doArchive(String logListURI, String archiveDirectory) throws IOException { String destURL = FileSystem.getDefaultUri(fsConfig) + archiveDirectory; DistCp.copy(new JobConf(fsConfig), logListURI, destURL, null, true, false); }
java
public void doArchive(String logListURI, String archiveDirectory) throws IOException { String destURL = FileSystem.getDefaultUri(fsConfig) + archiveDirectory; DistCp.copy(new JobConf(fsConfig), logListURI, destURL, null, true, false); }
[ "public", "void", "doArchive", "(", "String", "logListURI", ",", "String", "archiveDirectory", ")", "throws", "IOException", "{", "String", "destURL", "=", "FileSystem", ".", "getDefaultUri", "(", "fsConfig", ")", "+", "archiveDirectory", ";", "DistCp", ".", "co...
doArchive: Workhorse function to archive log-files. @param logListURI : The uri which will serve list of log-files to archive. @param archiveDirectory : The directory to store archived logfiles. @throws IOException
[ "doArchive", ":", "Workhorse", "function", "to", "archive", "log", "-", "files", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/tools/org/apache/hadoop/tools/Logalyzer.java#L181-L187
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/watcher/ResourceWatcher.java
ResourceWatcher.registerPathMapping
private void registerPathMapping(PathMapping pathMapping, String filePath) throws IOException { if (filePath != null) { Path p = Paths.get(filePath); boolean isDir = Files.isDirectory(p); if (!isDir) { p = p.getParent(); } if (pathMapping.isRecursive()) { registerAll(p, Arrays.asList(pathMapping)); } else { register(p, Arrays.asList(pathMapping)); } } }
java
private void registerPathMapping(PathMapping pathMapping, String filePath) throws IOException { if (filePath != null) { Path p = Paths.get(filePath); boolean isDir = Files.isDirectory(p); if (!isDir) { p = p.getParent(); } if (pathMapping.isRecursive()) { registerAll(p, Arrays.asList(pathMapping)); } else { register(p, Arrays.asList(pathMapping)); } } }
[ "private", "void", "registerPathMapping", "(", "PathMapping", "pathMapping", ",", "String", "filePath", ")", "throws", "IOException", "{", "if", "(", "filePath", "!=", "null", ")", "{", "Path", "p", "=", "Paths", ".", "get", "(", "filePath", ")", ";", "boo...
Register the path mapping @param pathMapping the path mapping @param filePath the file path @throws IOException if an IOException occurs
[ "Register", "the", "path", "mapping" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/watcher/ResourceWatcher.java#L232-L247
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/HttpClientRequestActionBuilder.java
HttpClientRequestActionBuilder.queryParam
public HttpClientRequestActionBuilder queryParam(String name, String value) { httpMessage.queryParam(name, value); return this; }
java
public HttpClientRequestActionBuilder queryParam(String name, String value) { httpMessage.queryParam(name, value); return this; }
[ "public", "HttpClientRequestActionBuilder", "queryParam", "(", "String", "name", ",", "String", "value", ")", "{", "httpMessage", ".", "queryParam", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a query param to the request uri. @param name @param value @return
[ "Adds", "a", "query", "param", "to", "the", "request", "uri", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/HttpClientRequestActionBuilder.java#L144-L147
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/abst/feature/tracker/DetectDescribeAssociateTwoPass.java
DetectDescribeAssociateTwoPass.updateTrackLocation
protected void updateTrackLocation( SetTrackInfo<Desc> info, FastQueue<AssociatedIndex> matches) { info.matches.resize(matches.size); for (int i = 0; i < matches.size; i++) { info.matches.get(i).set(matches.get(i)); } tracksActive.clear(); for( int i = 0; i < info.matches.size; i++ ) { AssociatedIndex indexes = info.matches.data[i]; PointTrack track = info.tracks.get(indexes.src); Point2D_F64 loc = info.locDst.data[indexes.dst]; track.set(loc.x, loc.y); tracksActive.add(track); } }
java
protected void updateTrackLocation( SetTrackInfo<Desc> info, FastQueue<AssociatedIndex> matches) { info.matches.resize(matches.size); for (int i = 0; i < matches.size; i++) { info.matches.get(i).set(matches.get(i)); } tracksActive.clear(); for( int i = 0; i < info.matches.size; i++ ) { AssociatedIndex indexes = info.matches.data[i]; PointTrack track = info.tracks.get(indexes.src); Point2D_F64 loc = info.locDst.data[indexes.dst]; track.set(loc.x, loc.y); tracksActive.add(track); } }
[ "protected", "void", "updateTrackLocation", "(", "SetTrackInfo", "<", "Desc", ">", "info", ",", "FastQueue", "<", "AssociatedIndex", ">", "matches", ")", "{", "info", ".", "matches", ".", "resize", "(", "matches", ".", "size", ")", ";", "for", "(", "int", ...
Update each track's location only and not its description. Update the active list too
[ "Update", "each", "track", "s", "location", "only", "and", "not", "its", "description", ".", "Update", "the", "active", "list", "too" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/abst/feature/tracker/DetectDescribeAssociateTwoPass.java#L139-L153
Impetus/Kundera
src/data-as-object/src/main/java/com/impetus/core/DefaultKunderaEntity.java
DefaultKunderaEntity.setSchemaAndPU
private static void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata) { Table table = clazz.getAnnotation(Table.class); if (table != null) { metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName()); String schemaStr = table.schema(); MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr, em.getEntityManagerFactory().getProperties()); } else { metadata.setTableName(clazz.getSimpleName()); metadata.setSchema((String) em.getEntityManagerFactory().getProperties().get("kundera.keyspace")); } if (metadata.getPersistenceUnit() == null) { metadata.setPersistenceUnit(getPersistenceUnit()); } }
java
private static void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata) { Table table = clazz.getAnnotation(Table.class); if (table != null) { metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName()); String schemaStr = table.schema(); MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr, em.getEntityManagerFactory().getProperties()); } else { metadata.setTableName(clazz.getSimpleName()); metadata.setSchema((String) em.getEntityManagerFactory().getProperties().get("kundera.keyspace")); } if (metadata.getPersistenceUnit() == null) { metadata.setPersistenceUnit(getPersistenceUnit()); } }
[ "private", "static", "void", "setSchemaAndPU", "(", "Class", "<", "?", ">", "clazz", ",", "EntityMetadata", "metadata", ")", "{", "Table", "table", "=", "clazz", ".", "getAnnotation", "(", "Table", ".", "class", ")", ";", "if", "(", "table", "!=", "null"...
Sets the schema and pu. @param clazz the clazz @param metadata the metadata
[ "Sets", "the", "schema", "and", "pu", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/data-as-object/src/main/java/com/impetus/core/DefaultKunderaEntity.java#L120-L141
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java
Aggregations.bigIntegerAvg
public static <Key, Value> Aggregation<Key, BigInteger, BigInteger> bigIntegerAvg() { return new AggregationAdapter(new BigIntegerAvgAggregation<Key, Value>()); }
java
public static <Key, Value> Aggregation<Key, BigInteger, BigInteger> bigIntegerAvg() { return new AggregationAdapter(new BigIntegerAvgAggregation<Key, Value>()); }
[ "public", "static", "<", "Key", ",", "Value", ">", "Aggregation", "<", "Key", ",", "BigInteger", ",", "BigInteger", ">", "bigIntegerAvg", "(", ")", "{", "return", "new", "AggregationAdapter", "(", "new", "BigIntegerAvgAggregation", "<", "Key", ",", "Value", ...
Returns an aggregation to calculate the {@link java.math.BigInteger} average of all supplied values.<br/> This aggregation is similar to: <pre>SELECT AVG(value) FROM x</pre> @param <Key> the input key type @param <Value> the supplied value type @return the average over all supplied values
[ "Returns", "an", "aggregation", "to", "calculate", "the", "{", "@link", "java", ".", "math", ".", "BigInteger", "}", "average", "of", "all", "supplied", "values", ".", "<br", "/", ">", "This", "aggregation", "is", "similar", "to", ":", "<pre", ">", "SELE...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java#L299-L301
google/flatbuffers
java/com/google/flatbuffers/Table.java
Table.__vector_as_bytebuffer
protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) { int o = __offset(vector_offset); if (o == 0) return null; ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); int vectorstart = __vector(o); bb.position(vectorstart); bb.limit(vectorstart + __vector_len(o) * elem_size); return bb; }
java
protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) { int o = __offset(vector_offset); if (o == 0) return null; ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); int vectorstart = __vector(o); bb.position(vectorstart); bb.limit(vectorstart + __vector_len(o) * elem_size); return bb; }
[ "protected", "ByteBuffer", "__vector_as_bytebuffer", "(", "int", "vector_offset", ",", "int", "elem_size", ")", "{", "int", "o", "=", "__offset", "(", "vector_offset", ")", ";", "if", "(", "o", "==", "0", ")", "return", "null", ";", "ByteBuffer", "bb", "="...
Get a whole vector as a ByteBuffer. This is efficient, since it only allocates a new {@link ByteBuffer} object, but does not actually copy the data, it still refers to the same bytes as the original ByteBuffer. Also useful with nested FlatBuffers, etc. @param vector_offset The position of the vector in the byte buffer @param elem_size The size of each element in the array @return The {@link ByteBuffer} for the array
[ "Get", "a", "whole", "vector", "as", "a", "ByteBuffer", "." ]
train
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/java/com/google/flatbuffers/Table.java#L133-L141
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/asm/ModifierAdjustment.java
ModifierAdjustment.withConstructorModifiers
public ModifierAdjustment withConstructorModifiers(ElementMatcher<? super MethodDescription> matcher, ModifierContributor.ForMethod... modifierContributor) { return withConstructorModifiers(matcher, Arrays.asList(modifierContributor)); }
java
public ModifierAdjustment withConstructorModifiers(ElementMatcher<? super MethodDescription> matcher, ModifierContributor.ForMethod... modifierContributor) { return withConstructorModifiers(matcher, Arrays.asList(modifierContributor)); }
[ "public", "ModifierAdjustment", "withConstructorModifiers", "(", "ElementMatcher", "<", "?", "super", "MethodDescription", ">", "matcher", ",", "ModifierContributor", ".", "ForMethod", "...", "modifierContributor", ")", "{", "return", "withConstructorModifiers", "(", "mat...
Adjusts a constructor's modifiers if it fulfills the supplied matcher. @param matcher The matcher that determines if a constructor's modifiers should be adjusted. @param modifierContributor The modifier contributors to enforce. @return A new modifier adjustment that enforces the given modifier contributors and any previous adjustments.
[ "Adjusts", "a", "constructor", "s", "modifiers", "if", "it", "fulfills", "the", "supplied", "matcher", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/asm/ModifierAdjustment.java#L253-L256
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApiForm.java
GitLabApiForm.withParam
public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException { return (withParam(name, level, false)); }
java
public GitLabApiForm withParam(String name, AccessLevel level) throws IllegalArgumentException { return (withParam(name, level, false)); }
[ "public", "GitLabApiForm", "withParam", "(", "String", "name", ",", "AccessLevel", "level", ")", "throws", "IllegalArgumentException", "{", "return", "(", "withParam", "(", "name", ",", "level", ",", "false", ")", ")", ";", "}" ]
Fluent method for adding AccessLevel query and form parameters to a get() or post() call. @param name the name of the field/attribute to add @param level the value of the field/attribute to add @return this GitLabAPiForm instance
[ "Fluent", "method", "for", "adding", "AccessLevel", "query", "and", "form", "parameters", "to", "a", "get", "()", "or", "post", "()", "call", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiForm.java#L81-L83
rometools/rome
rome/src/main/java/com/rometools/rome/io/WireFeedOutput.java
WireFeedOutput.outputW3CDom
public org.w3c.dom.Document outputW3CDom(final WireFeed feed) throws IllegalArgumentException, FeedException { final Document doc = outputJDom(feed); final DOMOutputter outputter = new DOMOutputter(); try { return outputter.output(doc); } catch (final JDOMException jdomEx) { throw new FeedException("Could not create DOM", jdomEx); } }
java
public org.w3c.dom.Document outputW3CDom(final WireFeed feed) throws IllegalArgumentException, FeedException { final Document doc = outputJDom(feed); final DOMOutputter outputter = new DOMOutputter(); try { return outputter.output(doc); } catch (final JDOMException jdomEx) { throw new FeedException("Could not create DOM", jdomEx); } }
[ "public", "org", ".", "w3c", ".", "dom", ".", "Document", "outputW3CDom", "(", "final", "WireFeed", "feed", ")", "throws", "IllegalArgumentException", ",", "FeedException", "{", "final", "Document", "doc", "=", "outputJDom", "(", "feed", ")", ";", "final", "...
Creates a W3C DOM document for the given WireFeed. <p> This method does not use the feed encoding property. <p> NOTE: This method delages to the 'Document WireFeedOutput#outputJDom(WireFeed)'. <p> @param feed Abstract feed to create W3C DOM document from. The type of the WireFeed must match the type given to the FeedOuptut constructor. @return the W3C DOM document for the given WireFeed. @throws IllegalArgumentException thrown if the feed type of the WireFeedOutput and WireFeed don't match. @throws FeedException thrown if the W3C DOM document for the feed could not be created.
[ "Creates", "a", "W3C", "DOM", "document", "for", "the", "given", "WireFeed", ".", "<p", ">", "This", "method", "does", "not", "use", "the", "feed", "encoding", "property", ".", "<p", ">", "NOTE", ":", "This", "method", "delages", "to", "the", "Document",...
train
https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/WireFeedOutput.java#L266-L274
JodaOrg/joda-time
src/main/java/org/joda/time/YearMonthDay.java
YearMonthDay.withMonthOfYear
public YearMonthDay withMonthOfYear(int monthOfYear) { int[] newValues = getValues(); newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear); return new YearMonthDay(this, newValues); }
java
public YearMonthDay withMonthOfYear(int monthOfYear) { int[] newValues = getValues(); newValues = getChronology().monthOfYear().set(this, MONTH_OF_YEAR, newValues, monthOfYear); return new YearMonthDay(this, newValues); }
[ "public", "YearMonthDay", "withMonthOfYear", "(", "int", "monthOfYear", ")", "{", "int", "[", "]", "newValues", "=", "getValues", "(", ")", ";", "newValues", "=", "getChronology", "(", ")", ".", "monthOfYear", "(", ")", ".", "set", "(", "this", ",", "MON...
Returns a copy of this date with the month of year field updated. <p> YearMonthDay is immutable, so there are no set methods. Instead, this method returns a new instance with the value of month of year changed. @param monthOfYear the month of year to set @return a copy of this object with the field set @throws IllegalArgumentException if the value is invalid @since 1.3
[ "Returns", "a", "copy", "of", "this", "date", "with", "the", "month", "of", "year", "field", "updated", ".", "<p", ">", "YearMonthDay", "is", "immutable", "so", "there", "are", "no", "set", "methods", ".", "Instead", "this", "method", "returns", "a", "ne...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/YearMonthDay.java#L860-L864
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/SpanCell.java
SpanCell.renderDataCellContents
protected void renderDataCellContents(AbstractRenderAppender appender, String jspFragmentOutput) { /* render any JavaScript needed to support framework features */ if (_spanState.id != null) { HttpServletRequest request = JspUtil.getRequest(getJspContext()); String script = renderNameAndId(request, _spanState, null); if(script != null) _spanCellModel.setJavascript(script); } DECORATOR.decorate(getJspContext(), appender, _spanCellModel); }
java
protected void renderDataCellContents(AbstractRenderAppender appender, String jspFragmentOutput) { /* render any JavaScript needed to support framework features */ if (_spanState.id != null) { HttpServletRequest request = JspUtil.getRequest(getJspContext()); String script = renderNameAndId(request, _spanState, null); if(script != null) _spanCellModel.setJavascript(script); } DECORATOR.decorate(getJspContext(), appender, _spanCellModel); }
[ "protected", "void", "renderDataCellContents", "(", "AbstractRenderAppender", "appender", ",", "String", "jspFragmentOutput", ")", "{", "/* render any JavaScript needed to support framework features */", "if", "(", "_spanState", ".", "id", "!=", "null", ")", "{", "HttpServl...
Render the cell's contents. This method implements support for executing the span cell's decorator. @param appender the {@link AbstractRenderAppender} used to collect the rendered output @param jspFragmentOutput the String result of having evaluated the span cell's {@link javax.servlet.jsp.tagext.JspFragment}
[ "Render", "the", "cell", "s", "contents", ".", "This", "method", "implements", "support", "for", "executing", "the", "span", "cell", "s", "decorator", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/SpanCell.java#L343-L353
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SignatureConverter.java
SignatureConverter.convertMethodSignature
public static String convertMethodSignature(String className, String methodName, String methodSig, String pkgName) { StringBuilder args = new StringBuilder(); SignatureConverter converter = new SignatureConverter(methodSig); converter.skip(); args.append('('); while (converter.getFirst() != ')') { if (args.length() > 1) { args.append(", "); } args.append(shorten(pkgName, converter.parseNext())); } converter.skip(); args.append(')'); // Ignore return type StringBuilder result = new StringBuilder(); result.append(className); result.append('.'); result.append(methodName); result.append(args.toString()); return result.toString(); }
java
public static String convertMethodSignature(String className, String methodName, String methodSig, String pkgName) { StringBuilder args = new StringBuilder(); SignatureConverter converter = new SignatureConverter(methodSig); converter.skip(); args.append('('); while (converter.getFirst() != ')') { if (args.length() > 1) { args.append(", "); } args.append(shorten(pkgName, converter.parseNext())); } converter.skip(); args.append(')'); // Ignore return type StringBuilder result = new StringBuilder(); result.append(className); result.append('.'); result.append(methodName); result.append(args.toString()); return result.toString(); }
[ "public", "static", "String", "convertMethodSignature", "(", "String", "className", ",", "String", "methodName", ",", "String", "methodSig", ",", "String", "pkgName", ")", "{", "StringBuilder", "args", "=", "new", "StringBuilder", "(", ")", ";", "SignatureConverte...
Convenience method for generating a method signature in human readable form. @param className name of the class containing the method @param methodName the name of the method @param methodSig the signature of the method @param pkgName the name of the package the method is in (used to shorten class names)
[ "Convenience", "method", "for", "generating", "a", "method", "signature", "in", "human", "readable", "form", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SignatureConverter.java#L231-L256
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java
PoolOperations.disableAutoScale
public void disableAutoScale(String poolId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { PoolDisableAutoScaleOptions options = new PoolDisableAutoScaleOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); this.parentBatchClient.protocolLayer().pools().disableAutoScale(poolId, options); }
java
public void disableAutoScale(String poolId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { PoolDisableAutoScaleOptions options = new PoolDisableAutoScaleOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); this.parentBatchClient.protocolLayer().pools().disableAutoScale(poolId, options); }
[ "public", "void", "disableAutoScale", "(", "String", "poolId", ",", "Iterable", "<", "BatchClientBehavior", ">", "additionalBehaviors", ")", "throws", "BatchErrorException", ",", "IOException", "{", "PoolDisableAutoScaleOptions", "options", "=", "new", "PoolDisableAutoSca...
Disables automatic scaling on the specified pool. @param poolId The ID of the pool. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Disables", "automatic", "scaling", "on", "the", "specified", "pool", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/PoolOperations.java#L781-L788
lessthanoptimal/BoofCV
main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure/EstimateSceneCalibrated.java
EstimateSceneCalibrated.triangulationAngle
double triangulationAngle( Point2D_F64 normA , Point2D_F64 normB , Se3_F64 a_to_b ) { // the more parallel a line is worse the triangulation. Get rid of bad ideas early here arrowA.set(normA.x,normA.y,1); arrowB.set(normB.x,normB.y,1); GeometryMath_F64.mult(a_to_b.R,arrowA,arrowA); // put them into the same reference frame return UtilVector3D_F64.acute(arrowA,arrowB); }
java
double triangulationAngle( Point2D_F64 normA , Point2D_F64 normB , Se3_F64 a_to_b ) { // the more parallel a line is worse the triangulation. Get rid of bad ideas early here arrowA.set(normA.x,normA.y,1); arrowB.set(normB.x,normB.y,1); GeometryMath_F64.mult(a_to_b.R,arrowA,arrowA); // put them into the same reference frame return UtilVector3D_F64.acute(arrowA,arrowB); }
[ "double", "triangulationAngle", "(", "Point2D_F64", "normA", ",", "Point2D_F64", "normB", ",", "Se3_F64", "a_to_b", ")", "{", "// the more parallel a line is worse the triangulation. Get rid of bad ideas early here", "arrowA", ".", "set", "(", "normA", ".", "x", ",", "nor...
Computes the acture angle between two vectors. Larger this angle is the better the triangulation of the features 3D location is in general
[ "Computes", "the", "acture", "angle", "between", "two", "vectors", ".", "Larger", "this", "angle", "is", "the", "better", "the", "triangulation", "of", "the", "features", "3D", "location", "is", "in", "general" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure/EstimateSceneCalibrated.java#L641-L648
impossibl/stencil
engine/src/main/java/com/impossibl/stencil/engine/internal/StencilInterpreter.java
StencilInterpreter.findAndRemoveValue
private ExpressionContext findAndRemoveValue(List<NamedValueContext> namedValues, String name) { Iterator<NamedValueContext> namedValueIter = namedValues.iterator(); while (namedValueIter.hasNext()) { NamedValueContext namedValue = namedValueIter.next(); if (name.equals(value(namedValue.name))) { namedValueIter.remove(); return namedValue.expr; } } return null; }
java
private ExpressionContext findAndRemoveValue(List<NamedValueContext> namedValues, String name) { Iterator<NamedValueContext> namedValueIter = namedValues.iterator(); while (namedValueIter.hasNext()) { NamedValueContext namedValue = namedValueIter.next(); if (name.equals(value(namedValue.name))) { namedValueIter.remove(); return namedValue.expr; } } return null; }
[ "private", "ExpressionContext", "findAndRemoveValue", "(", "List", "<", "NamedValueContext", ">", "namedValues", ",", "String", "name", ")", "{", "Iterator", "<", "NamedValueContext", ">", "namedValueIter", "=", "namedValues", ".", "iterator", "(", ")", ";", "whil...
Find and remove named value with specific name @param namedValues List of NamedValues to search @param name Name of value to find @return Expression for value with specified name
[ "Find", "and", "remove", "named", "value", "with", "specific", "name" ]
train
https://github.com/impossibl/stencil/blob/4aac1be605542b4248be95bf8916be4e2f755d1c/engine/src/main/java/com/impossibl/stencil/engine/internal/StencilInterpreter.java#L2784-L2796
abel533/Mapper
core/src/main/java/tk/mybatis/mapper/util/OGNL.java
OGNL.exampleHasAtLeastOneCriteriaCheck
public static boolean exampleHasAtLeastOneCriteriaCheck(Object parameter) { if (parameter != null) { try { if (parameter instanceof Example) { List<Example.Criteria> criteriaList = ((Example) parameter).getOredCriteria(); if (criteriaList != null && criteriaList.size() > 0) { return true; } } else { Method getter = parameter.getClass().getDeclaredMethod("getOredCriteria"); Object list = getter.invoke(parameter); if(list != null && list instanceof List && ((List) list).size() > 0){ return true; } } } catch (Exception e) { throw new MapperException(SAFE_DELETE_ERROR, e); } } throw new MapperException(SAFE_DELETE_EXCEPTION); }
java
public static boolean exampleHasAtLeastOneCriteriaCheck(Object parameter) { if (parameter != null) { try { if (parameter instanceof Example) { List<Example.Criteria> criteriaList = ((Example) parameter).getOredCriteria(); if (criteriaList != null && criteriaList.size() > 0) { return true; } } else { Method getter = parameter.getClass().getDeclaredMethod("getOredCriteria"); Object list = getter.invoke(parameter); if(list != null && list instanceof List && ((List) list).size() > 0){ return true; } } } catch (Exception e) { throw new MapperException(SAFE_DELETE_ERROR, e); } } throw new MapperException(SAFE_DELETE_EXCEPTION); }
[ "public", "static", "boolean", "exampleHasAtLeastOneCriteriaCheck", "(", "Object", "parameter", ")", "{", "if", "(", "parameter", "!=", "null", ")", "{", "try", "{", "if", "(", "parameter", "instanceof", "Example", ")", "{", "List", "<", "Example", ".", "Cri...
检查 paremeter 对象中指定的 fields 是否全是 null,如果是则抛出异常 @param parameter @return
[ "检查", "paremeter", "对象中指定的", "fields", "是否全是", "null,如果是则抛出异常" ]
train
https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/util/OGNL.java#L113-L133
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_boot_bootId_option_option_GET
public OvhNetbootOption serviceName_boot_bootId_option_option_GET(String serviceName, Long bootId, net.minidev.ovh.api.dedicated.server.OvhBootOptionEnum option) throws IOException { String qPath = "/dedicated/server/{serviceName}/boot/{bootId}/option/{option}"; StringBuilder sb = path(qPath, serviceName, bootId, option); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhNetbootOption.class); }
java
public OvhNetbootOption serviceName_boot_bootId_option_option_GET(String serviceName, Long bootId, net.minidev.ovh.api.dedicated.server.OvhBootOptionEnum option) throws IOException { String qPath = "/dedicated/server/{serviceName}/boot/{bootId}/option/{option}"; StringBuilder sb = path(qPath, serviceName, bootId, option); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhNetbootOption.class); }
[ "public", "OvhNetbootOption", "serviceName_boot_bootId_option_option_GET", "(", "String", "serviceName", ",", "Long", "bootId", ",", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "dedicated", ".", "server", ".", "OvhBootOptionEnum", "option", ")", "throws", ...
Get this object properties REST: GET /dedicated/server/{serviceName}/boot/{bootId}/option/{option} @param serviceName [required] The internal name of your dedicated server @param bootId [required] boot id @param option [required] The option of this boot
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1800-L1805
osglworks/java-tool
src/main/java/org/osgl/util/StrBase.java
StrBase.maxLength
public T maxLength(int max) { if (isEmpty()) return _empty(); if (length() < (max - 3)) return me(); return subList(0, max).append("..."); }
java
public T maxLength(int max) { if (isEmpty()) return _empty(); if (length() < (max - 3)) return me(); return subList(0, max).append("..."); }
[ "public", "T", "maxLength", "(", "int", "max", ")", "{", "if", "(", "isEmpty", "(", ")", ")", "return", "_empty", "(", ")", ";", "if", "(", "length", "(", ")", "<", "(", "max", "-", "3", ")", ")", "return", "me", "(", ")", ";", "return", "sub...
<p>Return a string no longer than specified max length. <p>If the string supplied is longer than the specified max length then only it's part that is less than the max length returned, appended with "..." @param max the maximum length of the result @return A StrBase instance that contains at most `max` number of chars of this instance
[ "<p", ">", "Return", "a", "string", "no", "longer", "than", "specified", "max", "length", ".", "<p", ">", "If", "the", "string", "supplied", "is", "longer", "than", "the", "specified", "max", "length", "then", "only", "it", "s", "part", "that", "is", "...
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/StrBase.java#L1297-L1301
Wadpam/guja
guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDOAuth2UserDaoImpl.java
GeneratedDOAuth2UserDaoImpl.queryByDisplayName
public Iterable<DOAuth2User> queryByDisplayName(java.lang.String displayName) { return queryByField(null, DOAuth2UserMapper.Field.DISPLAYNAME.getFieldName(), displayName); }
java
public Iterable<DOAuth2User> queryByDisplayName(java.lang.String displayName) { return queryByField(null, DOAuth2UserMapper.Field.DISPLAYNAME.getFieldName(), displayName); }
[ "public", "Iterable", "<", "DOAuth2User", ">", "queryByDisplayName", "(", "java", ".", "lang", ".", "String", "displayName", ")", "{", "return", "queryByField", "(", "null", ",", "DOAuth2UserMapper", ".", "Field", ".", "DISPLAYNAME", ".", "getFieldName", "(", ...
query-by method for field displayName @param displayName the specified attribute @return an Iterable of DOAuth2Users for the specified displayName
[ "query", "-", "by", "method", "for", "field", "displayName" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDOAuth2UserDaoImpl.java#L88-L90
nominanuda/zen-project
zen-core/src/main/java/com/nominanuda/zen/obj/JsonPath.java
JsonPath.convertLeaves
@SuppressWarnings("unchecked") public <X extends Stru> X convertLeaves(X source, SafeConvertor<Object, Object> convertor) { return Check.notNull(source) instanceof Obj ? (X)convertLeavesInternal((Obj)source, convertor) : (X)convertLeavesInternal((Arr)source, convertor); }
java
@SuppressWarnings("unchecked") public <X extends Stru> X convertLeaves(X source, SafeConvertor<Object, Object> convertor) { return Check.notNull(source) instanceof Obj ? (X)convertLeavesInternal((Obj)source, convertor) : (X)convertLeavesInternal((Arr)source, convertor); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "X", "extends", "Stru", ">", "X", "convertLeaves", "(", "X", "source", ",", "SafeConvertor", "<", "Object", ",", "Object", ">", "convertor", ")", "{", "return", "Check", ".", "notNull", "("...
if convertor#canConvert returns false value is not added to result
[ "if", "convertor#canConvert", "returns", "false", "value", "is", "not", "added", "to", "result" ]
train
https://github.com/nominanuda/zen-project/blob/fe48ae8da198eb7066c2b56bf2ffafe4cdfc451d/zen-core/src/main/java/com/nominanuda/zen/obj/JsonPath.java#L251-L256
TakahikoKawasaki/nv-websocket-client
src/main/java/com/neovisionaries/ws/client/HandshakeReader.java
HandshakeReader.validateExtensions
private void validateExtensions(StatusLine statusLine, Map<String, List<String>> headers) throws WebSocketException { // Get the values of Sec-WebSocket-Extensions. List<String> values = headers.get("Sec-WebSocket-Extensions"); if (values == null || values.size() == 0) { // Nothing to check. return; } List<WebSocketExtension> extensions = new ArrayList<WebSocketExtension>(); for (String value : values) { // Split the value into elements each of which represents an extension. String[] elements = value.split("\\s*,\\s*"); for (String element : elements) { // Parse the string whose format is supposed to be "{name}[; {key}[={value}]*". WebSocketExtension extension = WebSocketExtension.parse(element); if (extension == null) { // The value in 'Sec-WebSocket-Extensions' failed to be parsed. throw new OpeningHandshakeException( WebSocketError.EXTENSION_PARSE_ERROR, "The value in 'Sec-WebSocket-Extensions' failed to be parsed: " + element, statusLine, headers); } // The extension name. String name = extension.getName(); // If the extension is not contained in the original request from this client. if (mWebSocket.getHandshakeBuilder().containsExtension(name) == false) { // The extension contained in the Sec-WebSocket-Extensions header is not supported. throw new OpeningHandshakeException( WebSocketError.UNSUPPORTED_EXTENSION, "The extension contained in the Sec-WebSocket-Extensions header is not supported: " + name, statusLine, headers); } // Let the extension validate itself. extension.validate(); // The extension has been agreed. extensions.add(extension); } } // Check if extensions conflict with each other. validateExtensionCombination(statusLine, headers, extensions); // Agreed extensions. mWebSocket.setAgreedExtensions(extensions); }
java
private void validateExtensions(StatusLine statusLine, Map<String, List<String>> headers) throws WebSocketException { // Get the values of Sec-WebSocket-Extensions. List<String> values = headers.get("Sec-WebSocket-Extensions"); if (values == null || values.size() == 0) { // Nothing to check. return; } List<WebSocketExtension> extensions = new ArrayList<WebSocketExtension>(); for (String value : values) { // Split the value into elements each of which represents an extension. String[] elements = value.split("\\s*,\\s*"); for (String element : elements) { // Parse the string whose format is supposed to be "{name}[; {key}[={value}]*". WebSocketExtension extension = WebSocketExtension.parse(element); if (extension == null) { // The value in 'Sec-WebSocket-Extensions' failed to be parsed. throw new OpeningHandshakeException( WebSocketError.EXTENSION_PARSE_ERROR, "The value in 'Sec-WebSocket-Extensions' failed to be parsed: " + element, statusLine, headers); } // The extension name. String name = extension.getName(); // If the extension is not contained in the original request from this client. if (mWebSocket.getHandshakeBuilder().containsExtension(name) == false) { // The extension contained in the Sec-WebSocket-Extensions header is not supported. throw new OpeningHandshakeException( WebSocketError.UNSUPPORTED_EXTENSION, "The extension contained in the Sec-WebSocket-Extensions header is not supported: " + name, statusLine, headers); } // Let the extension validate itself. extension.validate(); // The extension has been agreed. extensions.add(extension); } } // Check if extensions conflict with each other. validateExtensionCombination(statusLine, headers, extensions); // Agreed extensions. mWebSocket.setAgreedExtensions(extensions); }
[ "private", "void", "validateExtensions", "(", "StatusLine", "statusLine", ",", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "headers", ")", "throws", "WebSocketException", "{", "// Get the values of Sec-WebSocket-Extensions.", "List", "<", "String", "...
Validate the value of {@code Sec-WebSocket-Extensions} header. <blockquote> <p>From RFC 6455, p19.</p> <p><i> If the response includes a {@code Sec-WebSocket-Extensions} header field and this header field indicates the use of an extension that was not present in the client's handshake (the server has indicated an extension not requested by the client), the client MUST Fail the WebSocket Connection. </i></p> </blockquote>
[ "Validate", "the", "value", "of", "{", "@code", "Sec", "-", "WebSocket", "-", "Extensions", "}", "header", "." ]
train
https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/HandshakeReader.java#L468-L526
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/BackportReusePublicIdentifiers.java
BackportReusePublicIdentifiers.reportBug
private void reportBug(Library library) { bugReporter.reportBug(new BugInstance(this, BugType.BRPI_BACKPORT_REUSE_PUBLIC_IDENTIFIERS.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this).addString(library.name())); }
java
private void reportBug(Library library) { bugReporter.reportBug(new BugInstance(this, BugType.BRPI_BACKPORT_REUSE_PUBLIC_IDENTIFIERS.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this).addString(library.name())); }
[ "private", "void", "reportBug", "(", "Library", "library", ")", "{", "bugReporter", ".", "reportBug", "(", "new", "BugInstance", "(", "this", ",", "BugType", ".", "BRPI_BACKPORT_REUSE_PUBLIC_IDENTIFIERS", ".", "name", "(", ")", ",", "NORMAL_PRIORITY", ")", ".", ...
issues a new bug at this location @param library the type of backport library that is in use
[ "issues", "a", "new", "bug", "at", "this", "location" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/BackportReusePublicIdentifiers.java#L130-L133
wdtinc/mapbox-vector-tile-java
src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/JtsAdapter.java
JtsAdapter.equalAsInts2d
private static boolean equalAsInts2d(Coordinate a, Coordinate b) { return ((int)a.getOrdinate(0)) == ((int)b.getOrdinate(0)) && ((int)a.getOrdinate(1)) == ((int)b.getOrdinate(1)); }
java
private static boolean equalAsInts2d(Coordinate a, Coordinate b) { return ((int)a.getOrdinate(0)) == ((int)b.getOrdinate(0)) && ((int)a.getOrdinate(1)) == ((int)b.getOrdinate(1)); }
[ "private", "static", "boolean", "equalAsInts2d", "(", "Coordinate", "a", ",", "Coordinate", "b", ")", "{", "return", "(", "(", "int", ")", "a", ".", "getOrdinate", "(", "0", ")", ")", "==", "(", "(", "int", ")", "b", ".", "getOrdinate", "(", "0", "...
Return true if the values of the two {@link Coordinate} are equal when their first and second ordinates are cast as ints. Ignores 3rd ordinate. @param a first coordinate to compare @param b second coordinate to compare @return true if the values of the two {@link Coordinate} are equal when their first and second ordinates are cast as ints
[ "Return", "true", "if", "the", "values", "of", "the", "two", "{", "@link", "Coordinate", "}", "are", "equal", "when", "their", "first", "and", "second", "ordinates", "are", "cast", "as", "ints", ".", "Ignores", "3rd", "ordinate", "." ]
train
https://github.com/wdtinc/mapbox-vector-tile-java/blob/e5e3df3fc2260709e289f972a1348c0a1ea30339/src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/JtsAdapter.java#L618-L621
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_runtimeAvailableTypes_GET
public ArrayList<OvhTypeEnum> serviceName_runtimeAvailableTypes_GET(String serviceName, String language) throws IOException { String qPath = "/hosting/web/{serviceName}/runtimeAvailableTypes"; StringBuilder sb = path(qPath, serviceName); query(sb, "language", language); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
java
public ArrayList<OvhTypeEnum> serviceName_runtimeAvailableTypes_GET(String serviceName, String language) throws IOException { String qPath = "/hosting/web/{serviceName}/runtimeAvailableTypes"; StringBuilder sb = path(qPath, serviceName); query(sb, "language", language); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
[ "public", "ArrayList", "<", "OvhTypeEnum", ">", "serviceName_runtimeAvailableTypes_GET", "(", "String", "serviceName", ",", "String", "language", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/web/{serviceName}/runtimeAvailableTypes\"", ";", "StringB...
List available runtime configurations available backend types REST: GET /hosting/web/{serviceName}/runtimeAvailableTypes @param language [required] Specific programming language to filter @param serviceName [required] The internal name of your hosting
[ "List", "available", "runtime", "configurations", "available", "backend", "types" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L230-L236
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApiForm.java
GitLabApiForm.withParam
public GitLabApiForm withParam(String name, Date date, boolean required) throws IllegalArgumentException { return (withParam(name, (date == null ? null : ISO8601.toString(date)), required)); }
java
public GitLabApiForm withParam(String name, Date date, boolean required) throws IllegalArgumentException { return (withParam(name, (date == null ? null : ISO8601.toString(date)), required)); }
[ "public", "GitLabApiForm", "withParam", "(", "String", "name", ",", "Date", "date", ",", "boolean", "required", ")", "throws", "IllegalArgumentException", "{", "return", "(", "withParam", "(", "name", ",", "(", "date", "==", "null", "?", "null", ":", "ISO860...
Fluent method for adding Date query and form parameters to a get() or post() call. @param name the name of the field/attribute to add @param date the value of the field/attribute to add @param required the field is required flag @return this GitLabAPiForm instance @throws IllegalArgumentException if a required parameter is null or empty
[ "Fluent", "method", "for", "adding", "Date", "query", "and", "form", "parameters", "to", "a", "get", "()", "or", "post", "()", "call", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiForm.java#L70-L72
baratine/baratine
framework/src/main/java/com/caucho/v5/ramp/jamp/InJamp.java
InJamp.readMessages
public int readMessages(Reader is) throws IOException { //InboxAmp oldInbox = null; try (OutboxAmp outbox = OutboxAmp.currentOrCreate(getManager())) { //OutboxThreadLocal.setCurrent(_outbox); return readMessages(is, outbox); } finally { //OutboxThreadLocal.setCurrent(null); } }
java
public int readMessages(Reader is) throws IOException { //InboxAmp oldInbox = null; try (OutboxAmp outbox = OutboxAmp.currentOrCreate(getManager())) { //OutboxThreadLocal.setCurrent(_outbox); return readMessages(is, outbox); } finally { //OutboxThreadLocal.setCurrent(null); } }
[ "public", "int", "readMessages", "(", "Reader", "is", ")", "throws", "IOException", "{", "//InboxAmp oldInbox = null;", "try", "(", "OutboxAmp", "outbox", "=", "OutboxAmp", ".", "currentOrCreate", "(", "getManager", "(", ")", ")", ")", "{", "//OutboxThreadLocal.se...
Reads the next HMTP packet from the stream, returning false on end of file.
[ "Reads", "the", "next", "HMTP", "packet", "from", "the", "stream", "returning", "false", "on", "end", "of", "file", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/ramp/jamp/InJamp.java#L199-L210
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Flowable.java
Flowable.observeOn
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError, int bufferSize) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new FlowableObserveOn<T>(this, scheduler, delayError, bufferSize)); }
java
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.CUSTOM) public final Flowable<T> observeOn(Scheduler scheduler, boolean delayError, int bufferSize) { ObjectHelper.requireNonNull(scheduler, "scheduler is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new FlowableObserveOn<T>(this, scheduler, delayError, bufferSize)); }
[ "@", "CheckReturnValue", "@", "BackpressureSupport", "(", "BackpressureKind", ".", "FULL", ")", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "CUSTOM", ")", "public", "final", "Flowable", "<", "T", ">", "observeOn", "(", "Scheduler", "scheduler", ",", "...
Modifies a Publisher to perform its emissions and notifications on a specified {@link Scheduler}, asynchronously with a bounded buffer of configurable size and optionally delays onError notifications. <p> <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>This operator honors backpressure from downstream and expects it from the source {@code Publisher}. Violating this expectation will lead to {@code MissingBackpressureException}. This is the most common operator where the exception pops up; look for sources up the chain that don't support backpressure, such as {@code interval}, {@code timer}, {code PublishSubject} or {@code BehaviorSubject} and apply any of the {@code onBackpressureXXX} operators <strong>before</strong> applying {@code observeOn} itself.</dd> <dt><b>Scheduler:</b></dt> <dd>You specify which {@link Scheduler} this operator will use.</dd> </dl> @param scheduler the {@link Scheduler} to notify {@link Subscriber}s on @param delayError indicates if the onError notification may not cut ahead of onNext notification on the other side of the scheduling boundary. If true a sequence ending in onError will be replayed in the same order as was received from upstream @param bufferSize the size of the buffer. @return the source Publisher modified so that its {@link Subscriber}s are notified on the specified {@link Scheduler} @see <a href="http://reactivex.io/documentation/operators/observeon.html">ReactiveX operators documentation: ObserveOn</a> @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> @see #subscribeOn @see #observeOn(Scheduler) @see #observeOn(Scheduler, boolean)
[ "Modifies", "a", "Publisher", "to", "perform", "its", "emissions", "and", "notifications", "on", "a", "specified", "{", "@link", "Scheduler", "}", "asynchronously", "with", "a", "bounded", "buffer", "of", "configurable", "size", "and", "optionally", "delays", "o...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L11292-L11299
Jasig/uPortal
uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/groupadmin/GroupAdministrationHelper.java
GroupAdministrationHelper.createGroup
public void createGroup(GroupForm groupForm, JsonEntityBean parent, IPerson creator) { if (!canCreateMemberGroup(creator, parent.getId())) { throw new RuntimeAuthorizationException( creator, IPermission.CREATE_GROUP_ACTIVITY, groupForm.getKey()); } if (log.isDebugEnabled()) { log.debug( "Creating new group for group form [" + groupForm.toString() + "] and parent [" + parent.toString() + "]"); } // get the entity type of the parent group EntityEnum type = EntityEnum.getEntityEnum(groupForm.getType()); // create a new group with the parent's entity type IEntityGroup group = GroupService.newGroup(type.getClazz()); // find the current version of this group entity group.setCreatorID(creator.getUserName()); group.setName(groupForm.getName()); group.setDescription(groupForm.getDescription()); // add all the group membership information from the group form // to the group for (JsonEntityBean child : groupForm.getMembers()) { EntityEnum childType = EntityEnum.getEntityEnum(child.getEntityTypeAsString()); if (childType.isGroup()) { IEntityGroup member = GroupService.findGroup(child.getId()); group.addChild(member); } else { IGroupMember member = GroupService.getGroupMember(child.getId(), type.getClazz()); group.addChild(member); } } // save the group, updating both its basic information and group membership group.update(); // add this group to the membership list for the specified parent IEntityGroup parentGroup = GroupService.findGroup(parent.getId()); parentGroup.addChild(group); parentGroup.updateMembers(); }
java
public void createGroup(GroupForm groupForm, JsonEntityBean parent, IPerson creator) { if (!canCreateMemberGroup(creator, parent.getId())) { throw new RuntimeAuthorizationException( creator, IPermission.CREATE_GROUP_ACTIVITY, groupForm.getKey()); } if (log.isDebugEnabled()) { log.debug( "Creating new group for group form [" + groupForm.toString() + "] and parent [" + parent.toString() + "]"); } // get the entity type of the parent group EntityEnum type = EntityEnum.getEntityEnum(groupForm.getType()); // create a new group with the parent's entity type IEntityGroup group = GroupService.newGroup(type.getClazz()); // find the current version of this group entity group.setCreatorID(creator.getUserName()); group.setName(groupForm.getName()); group.setDescription(groupForm.getDescription()); // add all the group membership information from the group form // to the group for (JsonEntityBean child : groupForm.getMembers()) { EntityEnum childType = EntityEnum.getEntityEnum(child.getEntityTypeAsString()); if (childType.isGroup()) { IEntityGroup member = GroupService.findGroup(child.getId()); group.addChild(member); } else { IGroupMember member = GroupService.getGroupMember(child.getId(), type.getClazz()); group.addChild(member); } } // save the group, updating both its basic information and group membership group.update(); // add this group to the membership list for the specified parent IEntityGroup parentGroup = GroupService.findGroup(parent.getId()); parentGroup.addChild(group); parentGroup.updateMembers(); }
[ "public", "void", "createGroup", "(", "GroupForm", "groupForm", ",", "JsonEntityBean", "parent", ",", "IPerson", "creator", ")", "{", "if", "(", "!", "canCreateMemberGroup", "(", "creator", ",", "parent", ".", "getId", "(", ")", ")", ")", "{", "throw", "ne...
Create a new group under the specified parent. The new group will automatically be added to the parent group. @param groupForm form object representing the new group @param parent parent group for this new group @param creator the uPortal user creating the new group
[ "Create", "a", "new", "group", "under", "the", "specified", "parent", ".", "The", "new", "group", "will", "automatically", "be", "added", "to", "the", "parent", "group", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/groupadmin/GroupAdministrationHelper.java#L189-L236
sksamuel/scrimage
scrimage-filters/src/main/java/thirdparty/jhlabs/image/Gradient.java
Gradient.setKnotType
public void setKnotType(int n, int type) { knotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type); rebuildGradient(); }
java
public void setKnotType(int n, int type) { knotTypes[n] = (byte)((knotTypes[n] & ~COLOR_MASK) | type); rebuildGradient(); }
[ "public", "void", "setKnotType", "(", "int", "n", ",", "int", "type", ")", "{", "knotTypes", "[", "n", "]", "=", "(", "byte", ")", "(", "(", "knotTypes", "[", "n", "]", "&", "~", "COLOR_MASK", ")", "|", "type", ")", ";", "rebuildGradient", "(", "...
Set a knot type. @param n the knot index @param type the type @see #getKnotType
[ "Set", "a", "knot", "type", "." ]
train
https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/jhlabs/image/Gradient.java#L197-L200
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.removeColumns
public static void removeColumns( DMatrixRMaj A , int col0 , int col1 ) { if( col1 < col0 ) { throw new IllegalArgumentException("col1 must be >= col0"); } else if( col0 >= A.numCols || col1 >= A.numCols ) { throw new IllegalArgumentException("Columns which are to be removed must be in bounds"); } int step = col1-col0+1; int offset = 0; for (int row = 0, idx=0; row < A.numRows; row++) { for (int i = 0; i < col0; i++,idx++) { A.data[idx] = A.data[idx+offset]; } offset += step; for (int i = col1+1; i < A.numCols; i++,idx++) { A.data[idx] = A.data[idx+offset]; } } A.numCols -= step; }
java
public static void removeColumns( DMatrixRMaj A , int col0 , int col1 ) { if( col1 < col0 ) { throw new IllegalArgumentException("col1 must be >= col0"); } else if( col0 >= A.numCols || col1 >= A.numCols ) { throw new IllegalArgumentException("Columns which are to be removed must be in bounds"); } int step = col1-col0+1; int offset = 0; for (int row = 0, idx=0; row < A.numRows; row++) { for (int i = 0; i < col0; i++,idx++) { A.data[idx] = A.data[idx+offset]; } offset += step; for (int i = col1+1; i < A.numCols; i++,idx++) { A.data[idx] = A.data[idx+offset]; } } A.numCols -= step; }
[ "public", "static", "void", "removeColumns", "(", "DMatrixRMaj", "A", ",", "int", "col0", ",", "int", "col1", ")", "{", "if", "(", "col1", "<", "col0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"col1 must be >= col0\"", ")", ";", "}", "e...
Removes columns from the matrix. @param A Matrix. Modified @param col0 First column @param col1 Last column, inclusive.
[ "Removes", "columns", "from", "the", "matrix", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L1368-L1388
JodaOrg/joda-time
src/main/java/org/joda/time/DateTimeZone.java
DateTimeZone.fixedOffsetZone
private static DateTimeZone fixedOffsetZone(String id, int offset) { if (offset == 0) { return DateTimeZone.UTC; } return new FixedDateTimeZone(id, null, offset, offset); }
java
private static DateTimeZone fixedOffsetZone(String id, int offset) { if (offset == 0) { return DateTimeZone.UTC; } return new FixedDateTimeZone(id, null, offset, offset); }
[ "private", "static", "DateTimeZone", "fixedOffsetZone", "(", "String", "id", ",", "int", "offset", ")", "{", "if", "(", "offset", "==", "0", ")", "{", "return", "DateTimeZone", ".", "UTC", ";", "}", "return", "new", "FixedDateTimeZone", "(", "id", ",", "...
Gets the zone using a fixed offset amount. @param id the zone id @param offset the offset in millis @return the zone
[ "Gets", "the", "zone", "using", "a", "fixed", "offset", "amount", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/DateTimeZone.java#L408-L413
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscConfigurationsInner.java
DscConfigurationsInner.getAsync
public Observable<DscConfigurationInner> getAsync(String resourceGroupName, String automationAccountName, String configurationName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, configurationName).map(new Func1<ServiceResponse<DscConfigurationInner>, DscConfigurationInner>() { @Override public DscConfigurationInner call(ServiceResponse<DscConfigurationInner> response) { return response.body(); } }); }
java
public Observable<DscConfigurationInner> getAsync(String resourceGroupName, String automationAccountName, String configurationName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, configurationName).map(new Func1<ServiceResponse<DscConfigurationInner>, DscConfigurationInner>() { @Override public DscConfigurationInner call(ServiceResponse<DscConfigurationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DscConfigurationInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "configurationName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "automa...
Retrieve the configuration identified by configuration name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param configurationName The configuration name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DscConfigurationInner object
[ "Retrieve", "the", "configuration", "identified", "by", "configuration", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscConfigurationsInner.java#L226-L233
primefaces/primefaces
src/main/java/org/primefaces/util/ComponentTraversalUtils.java
ComponentTraversalUtils.firstById
public static void firstById(String id, UIComponent base, char separatorChar, FacesContext context, ContextCallback callback) { // try #findComponent first UIComponent component = base.findComponent(id); // try #invokeOnComponent // it's required to support e.g. a full client id for a component which is placed inside UIData components if (component == null) { // #invokeOnComponent doesn't support the leading seperator char String tempExpression = id; if (tempExpression.charAt(0) == separatorChar) { tempExpression = tempExpression.substring(1); } context.getViewRoot().invokeOnComponent(context, tempExpression, callback); } else { callback.invokeContextCallback(context, component); } }
java
public static void firstById(String id, UIComponent base, char separatorChar, FacesContext context, ContextCallback callback) { // try #findComponent first UIComponent component = base.findComponent(id); // try #invokeOnComponent // it's required to support e.g. a full client id for a component which is placed inside UIData components if (component == null) { // #invokeOnComponent doesn't support the leading seperator char String tempExpression = id; if (tempExpression.charAt(0) == separatorChar) { tempExpression = tempExpression.substring(1); } context.getViewRoot().invokeOnComponent(context, tempExpression, callback); } else { callback.invokeContextCallback(context, component); } }
[ "public", "static", "void", "firstById", "(", "String", "id", ",", "UIComponent", "base", ",", "char", "separatorChar", ",", "FacesContext", "context", ",", "ContextCallback", "callback", ")", "{", "// try #findComponent first", "UIComponent", "component", "=", "bas...
Finds the first component by the given id expression or client id. @param id The id. @param base The base component to start the traversal. @param separatorChar The separatorChar (e.g. :). @param context The FacesContext. @param callback the callback for the found component
[ "Finds", "the", "first", "component", "by", "the", "given", "id", "expression", "or", "client", "id", "." ]
train
https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/util/ComponentTraversalUtils.java#L148-L167
cybazeitalia/emaze-dysfunctional
src/main/java/net/emaze/dysfunctional/Searches.java
Searches.findLast
public static <E> E findLast(E[] array, Predicate<E> predicate) { final Iterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), predicate); return new LastElement<E>().apply(filtered); }
java
public static <E> E findLast(E[] array, Predicate<E> predicate) { final Iterator<E> filtered = new FilteringIterator<E>(new ArrayIterator<E>(array), predicate); return new LastElement<E>().apply(filtered); }
[ "public", "static", "<", "E", ">", "E", "findLast", "(", "E", "[", "]", "array", ",", "Predicate", "<", "E", ">", "predicate", ")", "{", "final", "Iterator", "<", "E", ">", "filtered", "=", "new", "FilteringIterator", "<", "E", ">", "(", "new", "Ar...
Searches the last matching element returning it. @param <E> the element type parameter @param array the array to be searched @param predicate the predicate to be applied to each element @throws IllegalArgumentException if no element matches @return the last element found
[ "Searches", "the", "last", "matching", "element", "returning", "it", "." ]
train
https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Searches.java#L627-L630
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/util/CommonHelper.java
CommonHelper.areEquals
public static boolean areEquals(final String s1, final String s2) { return s1 == null ? s2 == null : s1.equals(s2); }
java
public static boolean areEquals(final String s1, final String s2) { return s1 == null ? s2 == null : s1.equals(s2); }
[ "public", "static", "boolean", "areEquals", "(", "final", "String", "s1", ",", "final", "String", "s2", ")", "{", "return", "s1", "==", "null", "?", "s2", "==", "null", ":", "s1", ".", "equals", "(", "s2", ")", ";", "}" ]
Compare two String to see if they are equals (both null is ok). @param s1 string @param s2 string @return if two String are equals
[ "Compare", "two", "String", "to", "see", "if", "they", "are", "equals", "(", "both", "null", "is", "ok", ")", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/util/CommonHelper.java#L52-L54
groupon/robo-remote
RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/QueryBuilder.java
QueryBuilder.mapField
public QueryBuilder mapField(String query, String field_name) throws Exception { JSONObject op = new JSONObject(); if (query != null) op.put(Constants.REQUEST_QUERY, query); op.put(Constants.REQUEST_FIELD, field_name); JSONArray operations = (JSONArray) request.get(Constants.REQUEST_OPERATIONS); operations.put(op); request.remove(Constants.REQUEST_OPERATIONS); request.put(Constants.REQUEST_OPERATIONS, operations); return this; }
java
public QueryBuilder mapField(String query, String field_name) throws Exception { JSONObject op = new JSONObject(); if (query != null) op.put(Constants.REQUEST_QUERY, query); op.put(Constants.REQUEST_FIELD, field_name); JSONArray operations = (JSONArray) request.get(Constants.REQUEST_OPERATIONS); operations.put(op); request.remove(Constants.REQUEST_OPERATIONS); request.put(Constants.REQUEST_OPERATIONS, operations); return this; }
[ "public", "QueryBuilder", "mapField", "(", "String", "query", ",", "String", "field_name", ")", "throws", "Exception", "{", "JSONObject", "op", "=", "new", "JSONObject", "(", ")", ";", "if", "(", "query", "!=", "null", ")", "op", ".", "put", "(", "Consta...
Used to get the value from a field @param query @param field_name @return @throws Exception
[ "Used", "to", "get", "the", "value", "from", "a", "field" ]
train
https://github.com/groupon/robo-remote/blob/12d242faad50bf90f98657ca9a0c0c3ae1993f07/RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/QueryBuilder.java#L58-L72
Azure/azure-sdk-for-java
applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/APIKeysInner.java
APIKeysInner.deleteAsync
public Observable<ApplicationInsightsComponentAPIKeyInner> deleteAsync(String resourceGroupName, String resourceName, String keyId) { return deleteWithServiceResponseAsync(resourceGroupName, resourceName, keyId).map(new Func1<ServiceResponse<ApplicationInsightsComponentAPIKeyInner>, ApplicationInsightsComponentAPIKeyInner>() { @Override public ApplicationInsightsComponentAPIKeyInner call(ServiceResponse<ApplicationInsightsComponentAPIKeyInner> response) { return response.body(); } }); }
java
public Observable<ApplicationInsightsComponentAPIKeyInner> deleteAsync(String resourceGroupName, String resourceName, String keyId) { return deleteWithServiceResponseAsync(resourceGroupName, resourceName, keyId).map(new Func1<ServiceResponse<ApplicationInsightsComponentAPIKeyInner>, ApplicationInsightsComponentAPIKeyInner>() { @Override public ApplicationInsightsComponentAPIKeyInner call(ServiceResponse<ApplicationInsightsComponentAPIKeyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ApplicationInsightsComponentAPIKeyInner", ">", "deleteAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ",", "String", "keyId", ")", "{", "return", "deleteWithServiceResponseAsync", "(", "resourceGroupName", ",", "res...
Delete an API Key of an Application Insights component. @param resourceGroupName The name of the resource group. @param resourceName The name of the Application Insights component resource. @param keyId The API Key ID. This is unique within a Application Insights component. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ApplicationInsightsComponentAPIKeyInner object
[ "Delete", "an", "API", "Key", "of", "an", "Application", "Insights", "component", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/APIKeysInner.java#L301-L308
mangstadt/biweekly
src/main/java/biweekly/component/VTodo.java
VTodo.addAttendee
public Attendee addAttendee(String email) { Attendee prop = new Attendee(null, email, null); addAttendee(prop); return prop; }
java
public Attendee addAttendee(String email) { Attendee prop = new Attendee(null, email, null); addAttendee(prop); return prop; }
[ "public", "Attendee", "addAttendee", "(", "String", "email", ")", "{", "Attendee", "prop", "=", "new", "Attendee", "(", "null", ",", "email", ",", "null", ")", ";", "addAttendee", "(", "prop", ")", ";", "return", "prop", ";", "}" ]
Adds a person who is involved in the to-do task. @param email the attendee's email address @return the property that was created @see <a href="http://tools.ietf.org/html/rfc5545#page-107">RFC 5545 p.107-9</a> @see <a href="http://tools.ietf.org/html/rfc2445#page-102">RFC 2445 p.102-4</a> @see <a href="http://www.imc.org/pdi/vcal-10.doc">vCal 1.0 p.25-7</a>
[ "Adds", "a", "person", "who", "is", "involved", "in", "the", "to", "-", "do", "task", "." ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/VTodo.java#L1141-L1145
looly/hulu
src/main/java/com/xiaoleilu/hulu/Render.java
Render.renderFile
public static void renderFile(File file, String responseFileName, int bufferSize) { new FileView(file, responseFileName, bufferSize).render(); }
java
public static void renderFile(File file, String responseFileName, int bufferSize) { new FileView(file, responseFileName, bufferSize).render(); }
[ "public", "static", "void", "renderFile", "(", "File", "file", ",", "String", "responseFileName", ",", "int", "bufferSize", ")", "{", "new", "FileView", "(", "file", ",", "responseFileName", ",", "bufferSize", ")", ".", "render", "(", ")", ";", "}" ]
响应文件<br> 文件过大将下载失败 @param file 文件对象 @param responseFileName 响应给客户端的文件名,如果为空则使用编码后的原文件名 @param bufferSize 缓存大小
[ "响应文件<br", ">", "文件过大将下载失败" ]
train
https://github.com/looly/hulu/blob/4072de684e2e2f28ac8a3a44c0d5a690b289ef28/src/main/java/com/xiaoleilu/hulu/Render.java#L175-L178
beanshell/beanshell
src/main/java/bsh/Operators.java
Operators.binaryOperation
public static Object binaryOperation( Object obj1, Object obj2, int kind) throws UtilEvalError { // keep track of the original types Class<?> lhsOrgType = obj1.getClass(); Class<?> rhsOrgType = obj2.getClass(); // Unwrap primitives obj1 = Primitive.unwrap(obj1); obj2 = Primitive.unwrap(obj2); Object[] operands = promotePrimitives(obj1, obj2); Object lhs = operands[0]; Object rhs = operands[1]; if(lhs.getClass() != rhs.getClass()) throw new UtilEvalError("Type mismatch in operator. " + lhs.getClass() + " cannot be used with " + rhs.getClass() ); Object result; try { result = binaryOperationImpl( lhs, rhs, kind ); } catch ( ArithmeticException e ) { throw new UtilTargetError( "Arithemetic Exception in binary op", e); } if(result instanceof Boolean) return ((Boolean)result).booleanValue() ? Primitive.TRUE : Primitive.FALSE; // If both original args were Primitives return a Primitive result // else it was mixed (wrapper/primitive) return the wrapper type // Exception is for boolean result, return the primitive if ( lhsOrgType == Primitive.class && rhsOrgType == Primitive.class ) if ( Types.isFloatingpoint(result) && lhs.getClass() == BigDecimal.class ) return (Primitive) Primitive.wrap(result, result.getClass()); else return Primitive.shrinkWrap( result ); return Primitive.shrinkWrap( result ).getValue(); }
java
public static Object binaryOperation( Object obj1, Object obj2, int kind) throws UtilEvalError { // keep track of the original types Class<?> lhsOrgType = obj1.getClass(); Class<?> rhsOrgType = obj2.getClass(); // Unwrap primitives obj1 = Primitive.unwrap(obj1); obj2 = Primitive.unwrap(obj2); Object[] operands = promotePrimitives(obj1, obj2); Object lhs = operands[0]; Object rhs = operands[1]; if(lhs.getClass() != rhs.getClass()) throw new UtilEvalError("Type mismatch in operator. " + lhs.getClass() + " cannot be used with " + rhs.getClass() ); Object result; try { result = binaryOperationImpl( lhs, rhs, kind ); } catch ( ArithmeticException e ) { throw new UtilTargetError( "Arithemetic Exception in binary op", e); } if(result instanceof Boolean) return ((Boolean)result).booleanValue() ? Primitive.TRUE : Primitive.FALSE; // If both original args were Primitives return a Primitive result // else it was mixed (wrapper/primitive) return the wrapper type // Exception is for boolean result, return the primitive if ( lhsOrgType == Primitive.class && rhsOrgType == Primitive.class ) if ( Types.isFloatingpoint(result) && lhs.getClass() == BigDecimal.class ) return (Primitive) Primitive.wrap(result, result.getClass()); else return Primitive.shrinkWrap( result ); return Primitive.shrinkWrap( result ).getValue(); }
[ "public", "static", "Object", "binaryOperation", "(", "Object", "obj1", ",", "Object", "obj2", ",", "int", "kind", ")", "throws", "UtilEvalError", "{", "// keep track of the original types", "Class", "<", "?", ">", "lhsOrgType", "=", "obj1", ".", "getClass", "("...
Perform a binary operation on two Primitives or wrapper types. If both original args were Primitives return a Primitive result else it was mixed (wrapper/primitive) return the wrapper type. The exception is for boolean operations where we will return the primitive type either way.
[ "Perform", "a", "binary", "operation", "on", "two", "Primitives", "or", "wrapper", "types", ".", "If", "both", "original", "args", "were", "Primitives", "return", "a", "Primitive", "result", "else", "it", "was", "mixed", "(", "wrapper", "/", "primitive", ")"...
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Operators.java#L109-L150
playn/playn
core/src/playn/core/json/JsonObject.java
JsonObject.getInt
public int getInt(String key, int default_) { Object o = get(key); return o instanceof Number ? ((Number) o).intValue() : default_; }
java
public int getInt(String key, int default_) { Object o = get(key); return o instanceof Number ? ((Number) o).intValue() : default_; }
[ "public", "int", "getInt", "(", "String", "key", ",", "int", "default_", ")", "{", "Object", "o", "=", "get", "(", "key", ")", ";", "return", "o", "instanceof", "Number", "?", "(", "(", "Number", ")", "o", ")", ".", "intValue", "(", ")", ":", "de...
Returns the {@link Integer} at the given key, or the default if it does not exist or is the wrong type.
[ "Returns", "the", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonObject.java#L123-L126
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/EventHelper.java
EventHelper.renderFooter
protected void renderFooter(PdfWriter writer, Document document) throws DocumentException, VectorPrintException, InstantiationException, IllegalAccessException { if (!debugHereAfter && !failuresHereAfter) { PdfPTable footerTable = elementProducer.createElement(null, PdfPTable.class, getStylers(PAGEFOOTERTABLEKEY)); footerTable.addCell(createFooterCell(ValueHelper.createDate(new Date()))); String pageText = writer.getPageNumber() + getSettings().getProperty(" of ", UPTO); PdfPCell c = createFooterCell(pageText); c.setHorizontalAlignment(Element.ALIGN_RIGHT); footerTable.addCell(c); footerTable.addCell(createFooterCell(new Chunk())); footerTable.writeSelectedRows(0, -1, document.getPageSize().getLeft() + document.leftMargin(), document.getPageSize().getBottom(document.bottomMargin()), writer.getDirectContentUnder()); footerBottom = document.bottom() - footerTable.getTotalHeight(); } }
java
protected void renderFooter(PdfWriter writer, Document document) throws DocumentException, VectorPrintException, InstantiationException, IllegalAccessException { if (!debugHereAfter && !failuresHereAfter) { PdfPTable footerTable = elementProducer.createElement(null, PdfPTable.class, getStylers(PAGEFOOTERTABLEKEY)); footerTable.addCell(createFooterCell(ValueHelper.createDate(new Date()))); String pageText = writer.getPageNumber() + getSettings().getProperty(" of ", UPTO); PdfPCell c = createFooterCell(pageText); c.setHorizontalAlignment(Element.ALIGN_RIGHT); footerTable.addCell(c); footerTable.addCell(createFooterCell(new Chunk())); footerTable.writeSelectedRows(0, -1, document.getPageSize().getLeft() + document.leftMargin(), document.getPageSize().getBottom(document.bottomMargin()), writer.getDirectContentUnder()); footerBottom = document.bottom() - footerTable.getTotalHeight(); } }
[ "protected", "void", "renderFooter", "(", "PdfWriter", "writer", ",", "Document", "document", ")", "throws", "DocumentException", ",", "VectorPrintException", ",", "InstantiationException", ",", "IllegalAccessException", "{", "if", "(", "!", "debugHereAfter", "&&", "!...
prints a footer table with a line at the top, a date and page numbering, second cell will be right aligned @see #PAGEFOOTERTABLEKEY @see #PAGEFOOTERSTYLEKEY @param writer @param document @throws DocumentException @throws VectorPrintException
[ "prints", "a", "footer", "table", "with", "a", "line", "at", "the", "top", "a", "date", "and", "page", "numbering", "second", "cell", "will", "be", "right", "aligned" ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/EventHelper.java#L354-L371
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getItemList
public Future<ItemList> getItemList(ItemData data, String version, String locale) { return new DummyFuture<>(handler.getItemList(data, version, locale)); }
java
public Future<ItemList> getItemList(ItemData data, String version, String locale) { return new DummyFuture<>(handler.getItemList(data, version, locale)); }
[ "public", "Future", "<", "ItemList", ">", "getItemList", "(", "ItemData", "data", ",", "String", "version", ",", "String", "locale", ")", "{", "return", "new", "DummyFuture", "<>", "(", "handler", ".", "getItemList", "(", "data", ",", "version", ",", "loca...
<p> Get a listing of items in the game </p> This method does not count towards the rate limit and is not affected by the throttle @param version Data dragon version for returned data @param locale Locale code for returned data @param data Additional information to retrieve @return The list of items @see <a href=https://developer.riotgames.com/api/methods#!/649/2166>Official API documentation</a>
[ "<p", ">", "Get", "a", "listing", "of", "items", "in", "the", "game", "<", "/", "p", ">", "This", "method", "does", "not", "count", "towards", "the", "rate", "limit", "and", "is", "not", "affected", "by", "the", "throttle" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L479-L481