repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobResult.java
JobResult.toJobExecutionResult
public JobExecutionResult toJobExecutionResult(ClassLoader classLoader) throws JobExecutionException, IOException, ClassNotFoundException { if (applicationStatus == ApplicationStatus.SUCCEEDED) { return new JobExecutionResult( jobId, netRuntime, AccumulatorHelper.deserializeAccumulators( accumulatorResults, classLoader)); } else { final Throwable cause; if (serializedThrowable == null) { cause = null; } else { cause = serializedThrowable.deserializeError(classLoader); } final JobExecutionException exception; if (applicationStatus == ApplicationStatus.FAILED) { exception = new JobExecutionException(jobId, "Job execution failed.", cause); } else if (applicationStatus == ApplicationStatus.CANCELED) { exception = new JobCancellationException(jobId, "Job was cancelled.", cause); } else { exception = new JobExecutionException(jobId, "Job completed with illegal application status: " + applicationStatus + '.', cause); } throw exception; } }
java
public JobExecutionResult toJobExecutionResult(ClassLoader classLoader) throws JobExecutionException, IOException, ClassNotFoundException { if (applicationStatus == ApplicationStatus.SUCCEEDED) { return new JobExecutionResult( jobId, netRuntime, AccumulatorHelper.deserializeAccumulators( accumulatorResults, classLoader)); } else { final Throwable cause; if (serializedThrowable == null) { cause = null; } else { cause = serializedThrowable.deserializeError(classLoader); } final JobExecutionException exception; if (applicationStatus == ApplicationStatus.FAILED) { exception = new JobExecutionException(jobId, "Job execution failed.", cause); } else if (applicationStatus == ApplicationStatus.CANCELED) { exception = new JobCancellationException(jobId, "Job was cancelled.", cause); } else { exception = new JobExecutionException(jobId, "Job completed with illegal application status: " + applicationStatus + '.', cause); } throw exception; } }
[ "public", "JobExecutionResult", "toJobExecutionResult", "(", "ClassLoader", "classLoader", ")", "throws", "JobExecutionException", ",", "IOException", ",", "ClassNotFoundException", "{", "if", "(", "applicationStatus", "==", "ApplicationStatus", ".", "SUCCEEDED", ")", "{"...
Converts the {@link JobResult} to a {@link JobExecutionResult}. @param classLoader to use for deserialization @return JobExecutionResult @throws JobCancellationException if the job was cancelled @throws JobExecutionException if the job execution did not succeed @throws IOException if the accumulator could not be deserialized @throws ClassNotFoundException if the accumulator could not deserialized
[ "Converts", "the", "{", "@link", "JobResult", "}", "to", "a", "{", "@link", "JobExecutionResult", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobResult.java#L126-L155
OpenHFT/Chronicle-Map
src/main/java/net/openhft/chronicle/hash/impl/util/math/Gamma.java
Gamma.regularizedGammaQ
public static double regularizedGammaQ(final double a, double x, double epsilon, int maxIterations) { double ret; if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) { ret = Double.NaN; } else if (x == 0.0) { ret = 1.0; } else if (x < a + 1.0) { // use regularizedGammaP because it should converge faster in this // case. ret = 1.0 - regularizedGammaP(a, x, epsilon, maxIterations); } else { // create continued fraction ContinuedFraction cf = new ContinuedFraction() { @Override protected double getA(int n, double x) { return ((2.0 * n) + 1.0) - a + x; } @Override protected double getB(int n, double x) { return n * (a - n); } }; ret = 1.0 / cf.evaluate(x, epsilon, maxIterations); ret = Math.exp(-x + (a * Math.log(x)) - logGamma(a)) * ret; } return ret; }
java
public static double regularizedGammaQ(final double a, double x, double epsilon, int maxIterations) { double ret; if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) { ret = Double.NaN; } else if (x == 0.0) { ret = 1.0; } else if (x < a + 1.0) { // use regularizedGammaP because it should converge faster in this // case. ret = 1.0 - regularizedGammaP(a, x, epsilon, maxIterations); } else { // create continued fraction ContinuedFraction cf = new ContinuedFraction() { @Override protected double getA(int n, double x) { return ((2.0 * n) + 1.0) - a + x; } @Override protected double getB(int n, double x) { return n * (a - n); } }; ret = 1.0 / cf.evaluate(x, epsilon, maxIterations); ret = Math.exp(-x + (a * Math.log(x)) - logGamma(a)) * ret; } return ret; }
[ "public", "static", "double", "regularizedGammaQ", "(", "final", "double", "a", ",", "double", "x", ",", "double", "epsilon", ",", "int", "maxIterations", ")", "{", "double", "ret", ";", "if", "(", "Double", ".", "isNaN", "(", "a", ")", "||", "Double", ...
Returns the regularized gamma function Q(a, x) = 1 - P(a, x). <p> The implementation of this method is based on: <ul> <li> <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> Regularized Gamma Function</a>, equation (1). </li> <li> <a href="http://functions.wolfram.com/GammaBetaErf/GammaRegularized/10/0003/"> Regularized incomplete gamma function: Continued fraction representations (formula 06.08.10.0003)</a> </li> </ul> @param a the a parameter. @param x the value. @param epsilon When the absolute value of the nth item in the series is less than epsilon the approximation ceases to calculate further elements in the series. @param maxIterations Maximum number of "iterations" to complete. @return the regularized gamma function P(a, x) @throws IllegalStateException if the algorithm fails to converge.
[ "Returns", "the", "regularized", "gamma", "function", "Q", "(", "a", "x", ")", "=", "1", "-", "P", "(", "a", "x", ")", ".", "<p", ">", "The", "implementation", "of", "this", "method", "is", "based", "on", ":", "<ul", ">", "<li", ">", "<a", "href"...
train
https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/impl/util/math/Gamma.java#L418-L452
katjahahn/PortEx
src/main/java/com/github/katjahahn/tools/Overlay.java
Overlay.getDump
public byte[] getDump() throws IOException { byte[] dump = new byte[(int) getSize()]; try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { raf.seek(offset); raf.readFully(dump); } return dump; }
java
public byte[] getDump() throws IOException { byte[] dump = new byte[(int) getSize()]; try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { raf.seek(offset); raf.readFully(dump); } return dump; }
[ "public", "byte", "[", "]", "getDump", "(", ")", "throws", "IOException", "{", "byte", "[", "]", "dump", "=", "new", "byte", "[", "(", "int", ")", "getSize", "(", ")", "]", ";", "try", "(", "RandomAccessFile", "raf", "=", "new", "RandomAccessFile", "...
Loads all bytes of the overlay into an array and returns them. @return array containing the overlay bytes @throws IOException
[ "Loads", "all", "bytes", "of", "the", "overlay", "into", "an", "array", "and", "returns", "them", "." ]
train
https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/tools/Overlay.java#L170-L177
DiUS/pact-jvm
pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java
PactDslJsonArray.arrayMinMaxLike
public static PactDslJsonBody arrayMinMaxLike(int minSize, int maxSize, int numberExamples) { if (numberExamples < minSize) { throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d", numberExamples, minSize)); } else if (numberExamples > maxSize) { throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d", numberExamples, maxSize)); } PactDslJsonArray parent = new PactDslJsonArray("", "", null, true); parent.setNumberExamples(numberExamples); parent.matchers.addRule("", parent.matchMinMax(minSize, maxSize)); return new PactDslJsonBody(".", "", parent); }
java
public static PactDslJsonBody arrayMinMaxLike(int minSize, int maxSize, int numberExamples) { if (numberExamples < minSize) { throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d", numberExamples, minSize)); } else if (numberExamples > maxSize) { throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d", numberExamples, maxSize)); } PactDslJsonArray parent = new PactDslJsonArray("", "", null, true); parent.setNumberExamples(numberExamples); parent.matchers.addRule("", parent.matchMinMax(minSize, maxSize)); return new PactDslJsonBody(".", "", parent); }
[ "public", "static", "PactDslJsonBody", "arrayMinMaxLike", "(", "int", "minSize", ",", "int", "maxSize", ",", "int", "numberExamples", ")", "{", "if", "(", "numberExamples", "<", "minSize", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".",...
Array with a minimum and maximum size where each item must match the following example @param minSize minimum size @param maxSize maximum size @param numberExamples Number of examples to generate
[ "Array", "with", "a", "minimum", "and", "maximum", "size", "where", "each", "item", "must", "match", "the", "following", "example" ]
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L878-L890
khennig/lazy-datacontroller
lazy-datacontroller-pfadapter/src/main/java/com/tri/ui/model/adapter/PrimeFacesLazyAdapter.java
PrimeFacesLazyAdapter.handleFilters
boolean handleFilters(Map<String, Object> filters) { Validate.notNull(filters, "Filters required"); boolean changed = false; // clear non active filters and remove them from lastFilters for (Object filterKey : CollectionUtils.subtract(lastFilters.keySet(), filters.keySet())) { BeanProperty.clearBeanProperty(adaptee, (String) filterKey); lastFilters.remove(filterKey); changed = true; } // set changed active filters for (Entry<String, Object> entry : filters.entrySet()) { if (!lastFilters.containsKey(entry.getKey()) || !entry.getValue() .equals(lastFilters.get(entry.getKey()))) { BeanProperty.setBeanProperty(adaptee, entry.getKey(), entry.getValue()); lastFilters.put(entry.getKey(), entry.getValue()); changed = true; } } return changed; }
java
boolean handleFilters(Map<String, Object> filters) { Validate.notNull(filters, "Filters required"); boolean changed = false; // clear non active filters and remove them from lastFilters for (Object filterKey : CollectionUtils.subtract(lastFilters.keySet(), filters.keySet())) { BeanProperty.clearBeanProperty(adaptee, (String) filterKey); lastFilters.remove(filterKey); changed = true; } // set changed active filters for (Entry<String, Object> entry : filters.entrySet()) { if (!lastFilters.containsKey(entry.getKey()) || !entry.getValue() .equals(lastFilters.get(entry.getKey()))) { BeanProperty.setBeanProperty(adaptee, entry.getKey(), entry.getValue()); lastFilters.put(entry.getKey(), entry.getValue()); changed = true; } } return changed; }
[ "boolean", "handleFilters", "(", "Map", "<", "String", ",", "Object", ">", "filters", ")", "{", "Validate", ".", "notNull", "(", "filters", ",", "\"Filters required\"", ")", ";", "boolean", "changed", "=", "false", ";", "// clear non active filters and remove them...
Clears previously passed filters, sets new filters on adaptee. @param filters @return true if filters have changed to last call
[ "Clears", "previously", "passed", "filters", "sets", "new", "filters", "on", "adaptee", "." ]
train
https://github.com/khennig/lazy-datacontroller/blob/a72a5fc6ced43d0e06fc839d68bd58cede10ab56/lazy-datacontroller-pfadapter/src/main/java/com/tri/ui/model/adapter/PrimeFacesLazyAdapter.java#L183-L208
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bcc/BccClient.java
BccClient.listZones
public ListZonesResponse listZones(AbstractBceRequest request) { InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, ZONE); return invokeHttpClient(internalRequest, ListZonesResponse.class); }
java
public ListZonesResponse listZones(AbstractBceRequest request) { InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, ZONE); return invokeHttpClient(internalRequest, ListZonesResponse.class); }
[ "public", "ListZonesResponse", "listZones", "(", "AbstractBceRequest", "request", ")", "{", "InternalRequest", "internalRequest", "=", "this", ".", "createRequest", "(", "request", ",", "HttpMethodName", ".", "GET", ",", "ZONE", ")", ";", "return", "invokeHttpClient...
listing zones within current region @param request use withRequestCredentials @return The response with list of zones
[ "listing", "zones", "within", "current", "region" ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L1621-L1624
knowm/XChange
xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java
CexIOAdapters.adaptOrderBook
public static OrderBook adaptOrderBook(CexIODepth depth, CurrencyPair currencyPair) { List<LimitOrder> asks = createOrders(currencyPair, OrderType.ASK, depth.getAsks()); List<LimitOrder> bids = createOrders(currencyPair, OrderType.BID, depth.getBids()); Date date = new Date(depth.getTimestamp() * 1000); return new OrderBook(date, asks, bids); }
java
public static OrderBook adaptOrderBook(CexIODepth depth, CurrencyPair currencyPair) { List<LimitOrder> asks = createOrders(currencyPair, OrderType.ASK, depth.getAsks()); List<LimitOrder> bids = createOrders(currencyPair, OrderType.BID, depth.getBids()); Date date = new Date(depth.getTimestamp() * 1000); return new OrderBook(date, asks, bids); }
[ "public", "static", "OrderBook", "adaptOrderBook", "(", "CexIODepth", "depth", ",", "CurrencyPair", "currencyPair", ")", "{", "List", "<", "LimitOrder", ">", "asks", "=", "createOrders", "(", "currencyPair", ",", "OrderType", ".", "ASK", ",", "depth", ".", "ge...
Adapts Cex.IO Depth to OrderBook Object @param depth Cex.IO order book @param currencyPair The currency pair (e.g. BTC/USD) @return The XChange OrderBook
[ "Adapts", "Cex", ".", "IO", "Depth", "to", "OrderBook", "Object" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-cexio/src/main/java/org/knowm/xchange/cexio/CexIOAdapters.java#L126-L132
brianwhu/xillium
data/src/main/java/org/xillium/data/persistence/Persistence.java
Persistence.executeSelect
public <T> T executeSelect(String name, DataObject object, ResultSetWorker<T> worker) throws Exception { ParametricQuery statement = (ParametricQuery)_statements.get(name); if (statement != null) { return statement.executeSelect(DataSourceUtils.getConnection(_dataSource), object, worker); } else { throw new RuntimeException("ParametricQuery '" + name + "' not found"); } }
java
public <T> T executeSelect(String name, DataObject object, ResultSetWorker<T> worker) throws Exception { ParametricQuery statement = (ParametricQuery)_statements.get(name); if (statement != null) { return statement.executeSelect(DataSourceUtils.getConnection(_dataSource), object, worker); } else { throw new RuntimeException("ParametricQuery '" + name + "' not found"); } }
[ "public", "<", "T", ">", "T", "executeSelect", "(", "String", "name", ",", "DataObject", "object", ",", "ResultSetWorker", "<", "T", ">", "worker", ")", "throws", "Exception", "{", "ParametricQuery", "statement", "=", "(", "ParametricQuery", ")", "_statements"...
Executes a SELECT statement and passes the result set to the ResultSetWorker.
[ "Executes", "a", "SELECT", "statement", "and", "passes", "the", "result", "set", "to", "the", "ResultSetWorker", "." ]
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/data/src/main/java/org/xillium/data/persistence/Persistence.java#L183-L190
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/stats/StatsInterface.java
StatsInterface.getPhotoReferrers
public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException { return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, "photo_id", photoId, date, perPage, page); }
java
public ReferrerList getPhotoReferrers(Date date, String domain, String photoId, int perPage, int page) throws FlickrException { return getReferrers(METHOD_GET_PHOTO_REFERRERS, domain, "photo_id", photoId, date, perPage, page); }
[ "public", "ReferrerList", "getPhotoReferrers", "(", "Date", "date", ",", "String", "domain", ",", "String", "photoId", ",", "int", "perPage", ",", "int", "page", ")", "throws", "FlickrException", "{", "return", "getReferrers", "(", "METHOD_GET_PHOTO_REFERRERS", ",...
Get a list of referrers from a given domain to a photo. @param date (Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will automatically be rounded down to the start of the day. @param domain (Required) The domain to return referrers for. This should be a hostname (eg: "flickr.com") with no protocol or pathname. @param photoId (Optional) The id of the photo to get stats for. If not provided, stats for all photos will be returned. @param perPage (Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100. @param page (Optional) The page of results to return. If this argument is omitted, it defaults to 1. @see "http://www.flickr.com/services/api/flickr.stats.getPhotoReferrers.html"
[ "Get", "a", "list", "of", "referrers", "from", "a", "given", "domain", "to", "a", "photo", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/stats/StatsInterface.java#L188-L190
infinispan/infinispan
query/src/main/java/org/infinispan/query/indexmanager/AbstractUpdateCommand.java
AbstractUpdateCommand.setCacheManager
@Override public void setCacheManager(EmbeddedCacheManager cm) { String name = cacheName.toString(); if (cm.cacheExists(name)) { Cache cache = cm.getCache(name); searchFactory = ComponentRegistryUtils.getSearchIntegrator(cache); queryInterceptor = ComponentRegistryUtils.getQueryInterceptor(cache); } else { throw new CacheException("Cache named '" + name + "' does not exist on this CacheManager, or was not started"); } }
java
@Override public void setCacheManager(EmbeddedCacheManager cm) { String name = cacheName.toString(); if (cm.cacheExists(name)) { Cache cache = cm.getCache(name); searchFactory = ComponentRegistryUtils.getSearchIntegrator(cache); queryInterceptor = ComponentRegistryUtils.getQueryInterceptor(cache); } else { throw new CacheException("Cache named '" + name + "' does not exist on this CacheManager, or was not started"); } }
[ "@", "Override", "public", "void", "setCacheManager", "(", "EmbeddedCacheManager", "cm", ")", "{", "String", "name", "=", "cacheName", ".", "toString", "(", ")", ";", "if", "(", "cm", ".", "cacheExists", "(", "name", ")", ")", "{", "Cache", "cache", "=",...
This is invoked only on the receiving node, before {@link #perform(org.infinispan.context.InvocationContext)}.
[ "This", "is", "invoked", "only", "on", "the", "receiving", "node", "before", "{" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/indexmanager/AbstractUpdateCommand.java#L71-L81
j256/simplejmx
src/main/java/com/j256/simplejmx/client/JmxClient.java
JmxClient.invokeOperation
public Object invokeOperation(ObjectName objectName, String operName, Object... params) throws Exception { String[] paramTypes = lookupParamTypes(objectName, operName, params); return invokeOperation(objectName, operName, paramTypes, params); }
java
public Object invokeOperation(ObjectName objectName, String operName, Object... params) throws Exception { String[] paramTypes = lookupParamTypes(objectName, operName, params); return invokeOperation(objectName, operName, paramTypes, params); }
[ "public", "Object", "invokeOperation", "(", "ObjectName", "objectName", ",", "String", "operName", ",", "Object", "...", "params", ")", "throws", "Exception", "{", "String", "[", "]", "paramTypes", "=", "lookupParamTypes", "(", "objectName", ",", "operName", ","...
Invoke a JMX method as an array of objects. @return The value returned by the method or null if none.
[ "Invoke", "a", "JMX", "method", "as", "an", "array", "of", "objects", "." ]
train
https://github.com/j256/simplejmx/blob/1a04f52512dfa0a711ba0cc7023c604dbc82a352/src/main/java/com/j256/simplejmx/client/JmxClient.java#L458-L461
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java
VirtualNetworksInner.beginUpdateTagsAsync
public Observable<VirtualNetworkInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkName, tags).map(new Func1<ServiceResponse<VirtualNetworkInner>, VirtualNetworkInner>() { @Override public VirtualNetworkInner call(ServiceResponse<VirtualNetworkInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkName, tags).map(new Func1<ServiceResponse<VirtualNetworkInner>, VirtualNetworkInner>() { @Override public VirtualNetworkInner call(ServiceResponse<VirtualNetworkInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync"...
Updates a virtual network tags. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkInner object
[ "Updates", "a", "virtual", "network", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java#L874-L881
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java
Messenger.forwardContent
@ObjectiveCName("forwardContentContentWithPeer:withContent:") public void forwardContent(Peer peer, AbsContent content) { modules.getMessagesModule().forwardContent(peer, content); }
java
@ObjectiveCName("forwardContentContentWithPeer:withContent:") public void forwardContent(Peer peer, AbsContent content) { modules.getMessagesModule().forwardContent(peer, content); }
[ "@", "ObjectiveCName", "(", "\"forwardContentContentWithPeer:withContent:\"", ")", "public", "void", "forwardContent", "(", "Peer", "peer", ",", "AbsContent", "content", ")", "{", "modules", ".", "getMessagesModule", "(", ")", ".", "forwardContent", "(", "peer", ","...
Send DocumentContent - used for forwarding @param peer destination peer @param content content to forward
[ "Send", "DocumentContent", "-", "used", "for", "forwarding" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L969-L972
uber/rides-java-sdk
uber-rides/src/main/java/com/uber/sdk/rides/client/error/ErrorParser.java
ErrorParser.parseError
@Nullable public static ApiError parseError(@Nonnull Response<?> response) { if (response.isSuccessful()) { return null; } try { return parseError(response.errorBody().string(), response.code(), response.message()); } catch (IOException e) { return new ApiError(null, response.code(), "Unknown Error"); } }
java
@Nullable public static ApiError parseError(@Nonnull Response<?> response) { if (response.isSuccessful()) { return null; } try { return parseError(response.errorBody().string(), response.code(), response.message()); } catch (IOException e) { return new ApiError(null, response.code(), "Unknown Error"); } }
[ "@", "Nullable", "public", "static", "ApiError", "parseError", "(", "@", "Nonnull", "Response", "<", "?", ">", "response", ")", "{", "if", "(", "response", ".", "isSuccessful", "(", ")", ")", "{", "return", "null", ";", "}", "try", "{", "return", "pars...
Parses a {@link Response} into an {@link ApiError}. @param response the {@link Response} to parse. @return an {@link ApiError} if parsable, or {@code null} if the response is not in error.
[ "Parses", "a", "{", "@link", "Response", "}", "into", "an", "{", "@link", "ApiError", "}", "." ]
train
https://github.com/uber/rides-java-sdk/blob/6c75570ab7884f8ecafaad312ef471dd33f64c42/uber-rides/src/main/java/com/uber/sdk/rides/client/error/ErrorParser.java#L47-L58
twitter/scalding
scalding-parquet-scrooge/src/main/java/com/twitter/scalding/parquet/scrooge/ScroogeReadSupport.java
ScroogeReadSupport.getSchemaForRead
public static MessageType getSchemaForRead(MessageType fileMessageType, MessageType projectedMessageType) { assertGroupsAreCompatible(fileMessageType, projectedMessageType); return projectedMessageType; }
java
public static MessageType getSchemaForRead(MessageType fileMessageType, MessageType projectedMessageType) { assertGroupsAreCompatible(fileMessageType, projectedMessageType); return projectedMessageType; }
[ "public", "static", "MessageType", "getSchemaForRead", "(", "MessageType", "fileMessageType", ",", "MessageType", "projectedMessageType", ")", "{", "assertGroupsAreCompatible", "(", "fileMessageType", ",", "projectedMessageType", ")", ";", "return", "projectedMessageType", ...
Updated method from ReadSupport which checks if the projection's compatible instead of a stricter check to see if the file's schema contains the projection @param fileMessageType @param projectedMessageType @return
[ "Updated", "method", "from", "ReadSupport", "which", "checks", "if", "the", "projection", "s", "compatible", "instead", "of", "a", "stricter", "check", "to", "see", "if", "the", "file", "s", "schema", "contains", "the", "projection" ]
train
https://github.com/twitter/scalding/blob/428b5507279655676e507d52c669c3cbc7812dc0/scalding-parquet-scrooge/src/main/java/com/twitter/scalding/parquet/scrooge/ScroogeReadSupport.java#L133-L136
fcrepo4-labs/fcrepo4-client
fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/HttpHelper.java
HttpHelper.queryString
private static String queryString( final Map<String, List<String>> params ) { final StringBuilder builder = new StringBuilder(); if (params != null && params.size() > 0) { for (final Iterator<String> it = params.keySet().iterator(); it.hasNext(); ) { final String key = it.next(); final List<String> values = params.get(key); for (final String value : values) { try { builder.append(key + "=" + URLEncoder.encode(value, "UTF-8") + "&"); } catch (final UnsupportedEncodingException e) { builder.append(key + "=" + value + "&"); } } } return builder.length() > 0 ? "?" + builder.substring(0, builder.length() - 1) : ""; } return ""; }
java
private static String queryString( final Map<String, List<String>> params ) { final StringBuilder builder = new StringBuilder(); if (params != null && params.size() > 0) { for (final Iterator<String> it = params.keySet().iterator(); it.hasNext(); ) { final String key = it.next(); final List<String> values = params.get(key); for (final String value : values) { try { builder.append(key + "=" + URLEncoder.encode(value, "UTF-8") + "&"); } catch (final UnsupportedEncodingException e) { builder.append(key + "=" + value + "&"); } } } return builder.length() > 0 ? "?" + builder.substring(0, builder.length() - 1) : ""; } return ""; }
[ "private", "static", "String", "queryString", "(", "final", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "params", ")", "{", "final", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "params", "!=", "null"...
Encode URL parameters as a query string. @param params Query parameters
[ "Encode", "URL", "parameters", "as", "a", "query", "string", "." ]
train
https://github.com/fcrepo4-labs/fcrepo4-client/blob/21eaf27200c5b2542095f6ebb9dd8ec865b95bbd/fcrepo-client-impl/src/main/java/org/fcrepo/client/utils/HttpHelper.java#L190-L207
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java
IoUtil.readLines
public static <T extends Collection<String>> T readLines(InputStream in, Charset charset, T collection) throws IORuntimeException { return readLines(getReader(in, charset), collection); }
java
public static <T extends Collection<String>> T readLines(InputStream in, Charset charset, T collection) throws IORuntimeException { return readLines(getReader(in, charset), collection); }
[ "public", "static", "<", "T", "extends", "Collection", "<", "String", ">", ">", "T", "readLines", "(", "InputStream", "in", ",", "Charset", "charset", ",", "T", "collection", ")", "throws", "IORuntimeException", "{", "return", "readLines", "(", "getReader", ...
从流中读取内容 @param <T> 集合类型 @param in 输入流 @param charset 字符集 @param collection 返回集合 @return 内容 @throws IORuntimeException IO异常
[ "从流中读取内容" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L658-L660
baratine/baratine
framework/src/main/java/com/caucho/v5/vfs/ClasspathPath.java
ClasspathPath.fsWalk
public PathImpl fsWalk(String userPath, Map<String,Object> attributes, String path) { return new ClasspathPath(_root, userPath, path); }
java
public PathImpl fsWalk(String userPath, Map<String,Object> attributes, String path) { return new ClasspathPath(_root, userPath, path); }
[ "public", "PathImpl", "fsWalk", "(", "String", "userPath", ",", "Map", "<", "String", ",", "Object", ">", "attributes", ",", "String", "path", ")", "{", "return", "new", "ClasspathPath", "(", "_root", ",", "userPath", ",", "path", ")", ";", "}" ]
Lookup the actual path relative to the filesystem root. @param userPath the user's path to lookup() @param attributes the user's attributes to lookup() @param path the normalized path @return the selected path
[ "Lookup", "the", "actual", "path", "relative", "to", "the", "filesystem", "root", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/vfs/ClasspathPath.java#L76-L81
jboss/jboss-common-beans
src/main/java/org/jboss/common/beans/property/LongEditor.java
LongEditor.setAsText
@Override public void setAsText(final String text) { if (BeanUtils.isNull(text)) { setValue(null); return; } try { Object newValue = Long.valueOf(text); setValue(newValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse long.", e); } }
java
@Override public void setAsText(final String text) { if (BeanUtils.isNull(text)) { setValue(null); return; } try { Object newValue = Long.valueOf(text); setValue(newValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse long.", e); } }
[ "@", "Override", "public", "void", "setAsText", "(", "final", "String", "text", ")", "{", "if", "(", "BeanUtils", ".", "isNull", "(", "text", ")", ")", "{", "setValue", "(", "null", ")", ";", "return", ";", "}", "try", "{", "Object", "newValue", "=",...
Map the argument text into and Integer using Integer.valueOf.
[ "Map", "the", "argument", "text", "into", "and", "Integer", "using", "Integer", ".", "valueOf", "." ]
train
https://github.com/jboss/jboss-common-beans/blob/ffb48b1719762534bf92d762eadf91d1815f6748/src/main/java/org/jboss/common/beans/property/LongEditor.java#L38-L50
dadoonet/fscrawler
framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java
FsCrawlerUtil.copyDirs
public static void copyDirs(Path source, Path target, CopyOption... options) throws IOException { if (Files.notExists(target)) { Files.createDirectory(target); } logger.debug(" --> Copying resources from [{}]", source); if (Files.notExists(source)) { throw new RuntimeException(source + " doesn't seem to exist."); } Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new InternalFileVisitor(source, target, options)); logger.debug(" --> Resources ready in [{}]", target); }
java
public static void copyDirs(Path source, Path target, CopyOption... options) throws IOException { if (Files.notExists(target)) { Files.createDirectory(target); } logger.debug(" --> Copying resources from [{}]", source); if (Files.notExists(source)) { throw new RuntimeException(source + " doesn't seem to exist."); } Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new InternalFileVisitor(source, target, options)); logger.debug(" --> Resources ready in [{}]", target); }
[ "public", "static", "void", "copyDirs", "(", "Path", "source", ",", "Path", "target", ",", "CopyOption", "...", "options", ")", "throws", "IOException", "{", "if", "(", "Files", ".", "notExists", "(", "target", ")", ")", "{", "Files", ".", "createDirectory...
Copy files from a source to a target under a _default sub directory. @param source The source dir @param target The target dir @param options Potential options @throws IOException If copying does not work
[ "Copy", "files", "from", "a", "source", "to", "a", "target", "under", "a", "_default", "sub", "directory", "." ]
train
https://github.com/dadoonet/fscrawler/blob/cca00a14e21ef9986aa30e19b160463aed6bf921/framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java#L488-L502
Azure/azure-sdk-for-java
cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java
DatabaseAccountsInner.beginOnlineRegion
public void beginOnlineRegion(String resourceGroupName, String accountName, String region) { beginOnlineRegionWithServiceResponseAsync(resourceGroupName, accountName, region).toBlocking().single().body(); }
java
public void beginOnlineRegion(String resourceGroupName, String accountName, String region) { beginOnlineRegionWithServiceResponseAsync(resourceGroupName, accountName, region).toBlocking().single().body(); }
[ "public", "void", "beginOnlineRegion", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "region", ")", "{", "beginOnlineRegionWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "region", ")", ".", "toBlocking", ...
Online the specified region for the specified Azure Cosmos DB database account. @param resourceGroupName Name of an Azure resource group. @param accountName Cosmos DB database account name. @param region Cosmos DB region, with spaces between words and each word capitalized. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Online", "the", "specified", "region", "for", "the", "specified", "Azure", "Cosmos", "DB", "database", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1533-L1535
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/text/IteratorFactory.java
IteratorFactory.tokenizeOrderedWithReplacement
public static Iterator<String> tokenizeOrderedWithReplacement( BufferedReader reader) { Iterator<String> baseIterator = tokenizeOrdered(reader); return (replacementMap == null) ? baseIterator : new WordReplacementIterator(baseIterator, replacementMap); }
java
public static Iterator<String> tokenizeOrderedWithReplacement( BufferedReader reader) { Iterator<String> baseIterator = tokenizeOrdered(reader); return (replacementMap == null) ? baseIterator : new WordReplacementIterator(baseIterator, replacementMap); }
[ "public", "static", "Iterator", "<", "String", ">", "tokenizeOrderedWithReplacement", "(", "BufferedReader", "reader", ")", "{", "Iterator", "<", "String", ">", "baseIterator", "=", "tokenizeOrdered", "(", "reader", ")", ";", "return", "(", "replacementMap", "==",...
Wraps an iterator returned by {@link #tokenizeOrdered(String) tokenizeOrdered} to also include term replacement of tokens. Terms will be replaced based on a mapping provided through the system configuration. @param reader A reader whose contents are to be tokenized. @return An iterator over all the tokens in the reader where any tokens removed due to filtering have been replaced with the {@code IteratorFactory.EMPTY_TOKEN} value, and tokens may be replaced based on system configuration.
[ "Wraps", "an", "iterator", "returned", "by", "{", "@link", "#tokenizeOrdered", "(", "String", ")", "tokenizeOrdered", "}", "to", "also", "include", "term", "replacement", "of", "tokens", ".", "Terms", "will", "be", "replaced", "based", "on", "a", "mapping", ...
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/text/IteratorFactory.java#L403-L409
wisdom-framework/wisdom-jcr
wisdom-modeshape-web-jcr-rest/src/main/java/org/modeshape/web/jcr/rest/handler/RestNodeTypeHandlerImpl.java
RestNodeTypeHandlerImpl.getNodeType
@Override public RestNodeType getNodeType(Request request, String repositoryName, String workspaceName, String nodeTypeName) throws RepositoryException { Session session = getSession(request, repositoryName, workspaceName); NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager(); NodeType nodeType = nodeTypeManager.getNodeType(nodeTypeName); return new RestNodeType(nodeType, RestHelper.repositoryUrl(request)); }
java
@Override public RestNodeType getNodeType(Request request, String repositoryName, String workspaceName, String nodeTypeName) throws RepositoryException { Session session = getSession(request, repositoryName, workspaceName); NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager(); NodeType nodeType = nodeTypeManager.getNodeType(nodeTypeName); return new RestNodeType(nodeType, RestHelper.repositoryUrl(request)); }
[ "@", "Override", "public", "RestNodeType", "getNodeType", "(", "Request", "request", ",", "String", "repositoryName", ",", "String", "workspaceName", ",", "String", "nodeTypeName", ")", "throws", "RepositoryException", "{", "Session", "session", "=", "getSession", "...
Retrieves the {@link RestNodeType rest node type representation} of the {@link javax.jcr.nodetype.NodeType} with the given name. @param request a non-null {@link org.wisdom.api.http.Request} @param repositoryName a non-null, URL encoded {@link String} representing the name of a repository @param workspaceName a non-null, URL encoded {@link String} representing the name of a workspace @param nodeTypeName a non-null, URL encoded {@link String} representing the name of type @return a {@link RestNodeType} instance. @throws javax.jcr.RepositoryException if any JCR related operation fails, including if the node type cannot be found.
[ "Retrieves", "the", "{", "@link", "RestNodeType", "rest", "node", "type", "representation", "}", "of", "the", "{", "@link", "javax", ".", "jcr", ".", "nodetype", ".", "NodeType", "}", "with", "the", "given", "name", "." ]
train
https://github.com/wisdom-framework/wisdom-jcr/blob/2711383dde2239a19b90c226b3fd2aecab5715e4/wisdom-modeshape-web-jcr-rest/src/main/java/org/modeshape/web/jcr/rest/handler/RestNodeTypeHandlerImpl.java#L83-L92
spring-projects/spring-boot
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java
GitInfoContributor.postProcessContent
@Override protected void postProcessContent(Map<String, Object> content) { replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime()); replaceValue(getNestedMap(content, "build"), "time", getProperties().getInstant("build.time")); }
java
@Override protected void postProcessContent(Map<String, Object> content) { replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime()); replaceValue(getNestedMap(content, "build"), "time", getProperties().getInstant("build.time")); }
[ "@", "Override", "protected", "void", "postProcessContent", "(", "Map", "<", "String", ",", "Object", ">", "content", ")", "{", "replaceValue", "(", "getNestedMap", "(", "content", ",", "\"commit\"", ")", ",", "\"time\"", ",", "getProperties", "(", ")", ".",...
Post-process the content to expose. By default, well known keys representing dates are converted to {@link Instant} instances. @param content the content to expose
[ "Post", "-", "process", "the", "content", "to", "expose", ".", "By", "default", "well", "known", "keys", "representing", "dates", "are", "converted", "to", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/GitInfoContributor.java#L65-L71
apache/flink
flink-core/src/main/java/org/apache/flink/configuration/Configuration.java
Configuration.addAll
public void addAll(Configuration other, String prefix) { final StringBuilder bld = new StringBuilder(); bld.append(prefix); final int pl = bld.length(); synchronized (this.confData) { synchronized (other.confData) { for (Map.Entry<String, Object> entry : other.confData.entrySet()) { bld.setLength(pl); bld.append(entry.getKey()); this.confData.put(bld.toString(), entry.getValue()); } } } }
java
public void addAll(Configuration other, String prefix) { final StringBuilder bld = new StringBuilder(); bld.append(prefix); final int pl = bld.length(); synchronized (this.confData) { synchronized (other.confData) { for (Map.Entry<String, Object> entry : other.confData.entrySet()) { bld.setLength(pl); bld.append(entry.getKey()); this.confData.put(bld.toString(), entry.getValue()); } } } }
[ "public", "void", "addAll", "(", "Configuration", "other", ",", "String", "prefix", ")", "{", "final", "StringBuilder", "bld", "=", "new", "StringBuilder", "(", ")", ";", "bld", ".", "append", "(", "prefix", ")", ";", "final", "int", "pl", "=", "bld", ...
Adds all entries from the given configuration into this configuration. The keys are prepended with the given prefix. @param other The configuration whose entries are added to this configuration. @param prefix The prefix to prepend.
[ "Adds", "all", "entries", "from", "the", "given", "configuration", "into", "this", "configuration", ".", "The", "keys", "are", "prepended", "with", "the", "given", "prefix", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L683-L697
cubedtear/aritzh
aritzh-core/src/main/java/io/github/aritzhack/aritzh/util/IOUtil.java
IOUtil.chooseFolder
public static File chooseFolder(String title, File currentDir) { if (currentDir == null) currentDir = new File("."); JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(currentDir); fileChooser.setDialogTitle(title); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setMultiSelectionEnabled(false); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } return null; }
java
public static File chooseFolder(String title, File currentDir) { if (currentDir == null) currentDir = new File("."); JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(currentDir); fileChooser.setDialogTitle(title); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setMultiSelectionEnabled(false); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } return null; }
[ "public", "static", "File", "chooseFolder", "(", "String", "title", ",", "File", "currentDir", ")", "{", "if", "(", "currentDir", "==", "null", ")", "currentDir", "=", "new", "File", "(", "\".\"", ")", ";", "JFileChooser", "fileChooser", "=", "new", "JFile...
Open a {@link javax.swing.JFileChooser} which can only select folders, and return the selected folder, or null if closed or cancelled. @param title The title of the file-chooser window. @param currentDir The root directory. If null, {@code new File(".")} will be used. @return The chosen folder, or null if none was chosen.
[ "Open", "a", "{", "@link", "javax", ".", "swing", ".", "JFileChooser", "}", "which", "can", "only", "select", "folders", "and", "return", "the", "selected", "folder", "or", "null", "if", "closed", "or", "cancelled", "." ]
train
https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/util/IOUtil.java#L113-L125
E7du/jfinal-ext3
src/main/java/com/jfinal/ext/kit/PageViewKit.java
PageViewKit.getPageView
public static String getPageView(String dir, String viewPath, String pageName, String fileExtension){ if (!dir.endsWith("/")) { dir = dir + "/"; } if (!viewPath.endsWith("/")) { viewPath = viewPath + "/"; } return dir+viewPath+pageName+fileExtension; }
java
public static String getPageView(String dir, String viewPath, String pageName, String fileExtension){ if (!dir.endsWith("/")) { dir = dir + "/"; } if (!viewPath.endsWith("/")) { viewPath = viewPath + "/"; } return dir+viewPath+pageName+fileExtension; }
[ "public", "static", "String", "getPageView", "(", "String", "dir", ",", "String", "viewPath", ",", "String", "pageName", ",", "String", "fileExtension", ")", "{", "if", "(", "!", "dir", ".", "endsWith", "(", "\"/\"", ")", ")", "{", "dir", "=", "dir", "...
获取页面 @param dir 所在目录 @param viewPath view路径 @param pageName view名字 @param fileExtension view后缀 @return
[ "获取页面" ]
train
https://github.com/E7du/jfinal-ext3/blob/8ffcbd150fd50c72852bb778bd427b5eb19254dc/src/main/java/com/jfinal/ext/kit/PageViewKit.java#L215-L223
wildfly/wildfly-core
domain-management/src/main/java/org/jboss/as/domain/management/security/PropertiesFileLoader.java
PropertiesFileLoader.addLineContent
protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException { content.add(line); }
java
protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException { content.add(line); }
[ "protected", "void", "addLineContent", "(", "BufferedReader", "bufferedFileReader", ",", "List", "<", "String", ">", "content", ",", "String", "line", ")", "throws", "IOException", "{", "content", ".", "add", "(", "line", ")", ";", "}" ]
Add the line to the content @param bufferedFileReader The file reader @param content The content of the file @param line The current read line @throws IOException
[ "Add", "the", "line", "to", "the", "content" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/domain-management/src/main/java/org/jboss/as/domain/management/security/PropertiesFileLoader.java#L301-L303
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelFrameworkImpl.java
ChannelFrameworkImpl.setChannelState
private synchronized void setChannelState(String channelName, RuntimeState state) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setChannelState channelName=" + channelName + ", state=" + state.ordinal); } if (null != channelName) { ChannelContainer channelContainer = this.channelRunningMap.get(channelName); if (null != channelContainer) { channelContainer.setState(state); } } }
java
private synchronized void setChannelState(String channelName, RuntimeState state) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setChannelState channelName=" + channelName + ", state=" + state.ordinal); } if (null != channelName) { ChannelContainer channelContainer = this.channelRunningMap.get(channelName); if (null != channelContainer) { channelContainer.setState(state); } } }
[ "private", "synchronized", "void", "setChannelState", "(", "String", "channelName", ",", "RuntimeState", "state", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "...
Set the channel state of a given channel. @param channelName @param state
[ "Set", "the", "channel", "state", "of", "a", "given", "channel", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/ChannelFrameworkImpl.java#L4097-L4107
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/RuntimeExceptionsFactory.java
RuntimeExceptionsFactory.newIllegalArgumentException
public static IllegalArgumentException newIllegalArgumentException(String message, Object... args) { return newIllegalArgumentException(null, message, args); }
java
public static IllegalArgumentException newIllegalArgumentException(String message, Object... args) { return newIllegalArgumentException(null, message, args); }
[ "public", "static", "IllegalArgumentException", "newIllegalArgumentException", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "newIllegalArgumentException", "(", "null", ",", "message", ",", "args", ")", ";", "}" ]
Constructs and initializes a new {@link IllegalArgumentException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link IllegalArgumentException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link IllegalArgumentException} with the given {@link String message}. @see #newIllegalArgumentException(Throwable, String, Object...) @see java.lang.IllegalArgumentException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "IllegalArgumentException", "}", "with", "the", "given", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/RuntimeExceptionsFactory.java#L48-L50
wdtinc/mapbox-vector-tile-java
src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/MvtReader.java
MvtReader.loadMvt
public static JtsMvt loadMvt(File file, GeometryFactory geomFactory, ITagConverter tagConverter) throws IOException { return loadMvt(file, geomFactory, tagConverter, RING_CLASSIFIER_V2_1); }
java
public static JtsMvt loadMvt(File file, GeometryFactory geomFactory, ITagConverter tagConverter) throws IOException { return loadMvt(file, geomFactory, tagConverter, RING_CLASSIFIER_V2_1); }
[ "public", "static", "JtsMvt", "loadMvt", "(", "File", "file", ",", "GeometryFactory", "geomFactory", ",", "ITagConverter", "tagConverter", ")", "throws", "IOException", "{", "return", "loadMvt", "(", "file", ",", "geomFactory", ",", "tagConverter", ",", "RING_CLAS...
Convenience method for loading MVT from file. See {@link #loadMvt(InputStream, GeometryFactory, ITagConverter, RingClassifier)}. Uses {@link #RING_CLASSIFIER_V2_1} for forming Polygons and MultiPolygons. @param file path to the MVT @param geomFactory allows for JTS geometry creation @param tagConverter converts MVT feature tags to JTS user data object @return JTS MVT with geometry in MVT coordinates @throws IOException failure reading MVT from path @see #loadMvt(InputStream, GeometryFactory, ITagConverter, RingClassifier) @see Geometry @see Geometry#getUserData() @see RingClassifier
[ "Convenience", "method", "for", "loading", "MVT", "from", "file", ".", "See", "{", "@link", "#loadMvt", "(", "InputStream", "GeometryFactory", "ITagConverter", "RingClassifier", ")", "}", ".", "Uses", "{", "@link", "#RING_CLASSIFIER_V2_1", "}", "for", "forming", ...
train
https://github.com/wdtinc/mapbox-vector-tile-java/blob/e5e3df3fc2260709e289f972a1348c0a1ea30339/src/main/java/com/wdtinc/mapbox_vector_tile/adapt/jts/MvtReader.java#L47-L51
gallandarakhneorg/afc
maven/maventools/src/main/java/org/arakhne/maven/AbstractArakhneMojo.java
AbstractArakhneMojo.resolveArtifact
public final Artifact resolveArtifact(String groupId, String artifactId, String version) throws MojoExecutionException { return resolveArtifact(createArtifact(groupId, artifactId, version)); }
java
public final Artifact resolveArtifact(String groupId, String artifactId, String version) throws MojoExecutionException { return resolveArtifact(createArtifact(groupId, artifactId, version)); }
[ "public", "final", "Artifact", "resolveArtifact", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "version", ")", "throws", "MojoExecutionException", "{", "return", "resolveArtifact", "(", "createArtifact", "(", "groupId", ",", "artifactId", ",...
Retreive the extended artifact definition of the given artifact id. @param groupId is the identifier of the group. @param artifactId is the identifier of the artifact. @param version is the version of the artifact to retreive. @return the artifact definition. @throws MojoExecutionException on error.
[ "Retreive", "the", "extended", "artifact", "definition", "of", "the", "given", "artifact", "id", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/maven/maventools/src/main/java/org/arakhne/maven/AbstractArakhneMojo.java#L643-L645
square/pagerduty-incidents
src/main/java/com/squareup/pagerduty/incidents/Util.java
Util.checkStringArgument
static String checkStringArgument(String s, String name) { checkNotNull(s, name); checkArgument(!s.trim().isEmpty(), "'" + name + "' must not be blank. Was: '" + s + "'"); return s; }
java
static String checkStringArgument(String s, String name) { checkNotNull(s, name); checkArgument(!s.trim().isEmpty(), "'" + name + "' must not be blank. Was: '" + s + "'"); return s; }
[ "static", "String", "checkStringArgument", "(", "String", "s", ",", "String", "name", ")", "{", "checkNotNull", "(", "s", ",", "name", ")", ";", "checkArgument", "(", "!", "s", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ",", "\"'\"", "+", "name...
Reject {@code null}, empty, and blank strings with a good exception type and message.
[ "Reject", "{" ]
train
https://github.com/square/pagerduty-incidents/blob/81f29c2bd5b08c8a2f0d2abd2083f23d150fc8dd/src/main/java/com/squareup/pagerduty/incidents/Util.java#L24-L28
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/internal/InternalUtils.java
InternalUtils.setForwardedFormBean
public static void setForwardedFormBean( ServletRequest request, ActionForm form ) { if ( form == null ) { request.removeAttribute( FORWARDED_FORMBEAN_ATTR ); } else { request.setAttribute( FORWARDED_FORMBEAN_ATTR, form ); } }
java
public static void setForwardedFormBean( ServletRequest request, ActionForm form ) { if ( form == null ) { request.removeAttribute( FORWARDED_FORMBEAN_ATTR ); } else { request.setAttribute( FORWARDED_FORMBEAN_ATTR, form ); } }
[ "public", "static", "void", "setForwardedFormBean", "(", "ServletRequest", "request", ",", "ActionForm", "form", ")", "{", "if", "(", "form", "==", "null", ")", "{", "request", ".", "removeAttribute", "(", "FORWARDED_FORMBEAN_ATTR", ")", ";", "}", "else", "{",...
Set the forwarded form. This overrides the auto-generated form created by processActionForm and populated by processPopulate (in PageFlowRequestProcessor).
[ "Set", "the", "forwarded", "form", ".", "This", "overrides", "the", "auto", "-", "generated", "form", "created", "by", "processActionForm", "and", "populated", "by", "processPopulate", "(", "in", "PageFlowRequestProcessor", ")", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/internal/InternalUtils.java#L1022-L1032
crawljax/crawljax
plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/OutputBuilder.java
OutputBuilder.persistDom
void persistDom(String name, @Nullable String dom) { try { Files.write(Strings.nullToEmpty(dom), new File(doms, name + ".html"), Charsets.UTF_8); } catch (IOException e) { LOG.warn("Could not save dom state for {}", name); LOG.debug("Could not save dom state", e); } }
java
void persistDom(String name, @Nullable String dom) { try { Files.write(Strings.nullToEmpty(dom), new File(doms, name + ".html"), Charsets.UTF_8); } catch (IOException e) { LOG.warn("Could not save dom state for {}", name); LOG.debug("Could not save dom state", e); } }
[ "void", "persistDom", "(", "String", "name", ",", "@", "Nullable", "String", "dom", ")", "{", "try", "{", "Files", ".", "write", "(", "Strings", ".", "nullToEmpty", "(", "dom", ")", ",", "new", "File", "(", "doms", ",", "name", "+", "\".html\"", ")",...
Save the dom to disk. @param name statename @param dom the DOM as string
[ "Save", "the", "dom", "to", "disk", "." ]
train
https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/OutputBuilder.java#L262-L269
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/proxy/ObjectProxy.java
ObjectProxy.executeMethod
public static Object executeMethod(Object aObject, String methodName, Object[] aArguments) throws Exception { Class<?>[] parameterTypes = null; ArrayList<Object> parameterTypeArrayList = null; if(aArguments != null && aArguments.length >0) { //get array of inputs parameterTypeArrayList = new ArrayList<Object>(aArguments.length); for (int i = 0; i < aArguments.length; i++) { if(aArguments[i] == null) { //TODO: throw new RequiredException("argument["+i+"]"); parameterTypeArrayList.add(Object.class); } else { parameterTypeArrayList.add(aArguments[i].getClass()); } } parameterTypes = (Class[])parameterTypeArrayList.toArray(new Class[parameterTypeArrayList.size()]); } //find method Method method = null; method = aObject.getClass().getDeclaredMethod(methodName, parameterTypes); try { return method.invoke(aObject, aArguments); } catch (Exception e) { throw new SystemException("methodName="+methodName+" object="+aObject.getClass().getName()+" parameters="+parameterTypeArrayList+" EXCEPTION="+Debugger.stackTrace(e)); } }
java
public static Object executeMethod(Object aObject, String methodName, Object[] aArguments) throws Exception { Class<?>[] parameterTypes = null; ArrayList<Object> parameterTypeArrayList = null; if(aArguments != null && aArguments.length >0) { //get array of inputs parameterTypeArrayList = new ArrayList<Object>(aArguments.length); for (int i = 0; i < aArguments.length; i++) { if(aArguments[i] == null) { //TODO: throw new RequiredException("argument["+i+"]"); parameterTypeArrayList.add(Object.class); } else { parameterTypeArrayList.add(aArguments[i].getClass()); } } parameterTypes = (Class[])parameterTypeArrayList.toArray(new Class[parameterTypeArrayList.size()]); } //find method Method method = null; method = aObject.getClass().getDeclaredMethod(methodName, parameterTypes); try { return method.invoke(aObject, aArguments); } catch (Exception e) { throw new SystemException("methodName="+methodName+" object="+aObject.getClass().getName()+" parameters="+parameterTypeArrayList+" EXCEPTION="+Debugger.stackTrace(e)); } }
[ "public", "static", "Object", "executeMethod", "(", "Object", "aObject", ",", "String", "methodName", ",", "Object", "[", "]", "aArguments", ")", "throws", "Exception", "{", "Class", "<", "?", ">", "[", "]", "parameterTypes", "=", "null", ";", "ArrayList", ...
Note that this methods does not support auto boxing of primitive types @param aObject the object @param methodName the method @param aArguments the input argument @return the object return values @throws Exception
[ "Note", "that", "this", "methods", "does", "not", "support", "auto", "boxing", "of", "primitive", "types" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/proxy/ObjectProxy.java#L42-L90
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/internal/mysql/MySQLProtocol.java
MySQLProtocol.cancelCurrentQuery
public void cancelCurrentQuery() throws QueryException { Protocol copiedProtocol = new MySQLProtocol(host, port, database, username, password, info); queryWasCancelled = true; copiedProtocol.executeQuery(new DrizzleQuery("KILL QUERY " + serverThreadId)); copiedProtocol.close(); }
java
public void cancelCurrentQuery() throws QueryException { Protocol copiedProtocol = new MySQLProtocol(host, port, database, username, password, info); queryWasCancelled = true; copiedProtocol.executeQuery(new DrizzleQuery("KILL QUERY " + serverThreadId)); copiedProtocol.close(); }
[ "public", "void", "cancelCurrentQuery", "(", ")", "throws", "QueryException", "{", "Protocol", "copiedProtocol", "=", "new", "MySQLProtocol", "(", "host", ",", "port", ",", "database", ",", "username", ",", "password", ",", "info", ")", ";", "queryWasCancelled",...
cancels the current query - clones the current protocol and executes a query using the new connection <p/> thread safe @throws QueryException
[ "cancels", "the", "current", "query", "-", "clones", "the", "current", "protocol", "and", "executes", "a", "query", "using", "the", "new", "connection", "<p", "/", ">", "thread", "safe" ]
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/internal/mysql/MySQLProtocol.java#L624-L629
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ScriptContext.java
ScriptContext.chooseFile
@Cmd public File chooseFile(final String fileKey) { log.debug("Opening file chooser dialog"); JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR)); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setPreferredSize(new Dimension(600, 326)); int fileChooserResult = fileChooser.showOpenDialog(null); if (fileChooserResult == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String filename = file.toString(); log.info("Assigning file path '{}' to property '{}'", filename, fileKey); config.put(fileKey, filename); return file; } log.error("No file or directory was chosen, execution will abort"); throw new IllegalArgumentException("No file or directory was chosen"); }
java
@Cmd public File chooseFile(final String fileKey) { log.debug("Opening file chooser dialog"); JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR)); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setPreferredSize(new Dimension(600, 326)); int fileChooserResult = fileChooser.showOpenDialog(null); if (fileChooserResult == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String filename = file.toString(); log.info("Assigning file path '{}' to property '{}'", filename, fileKey); config.put(fileKey, filename); return file; } log.error("No file or directory was chosen, execution will abort"); throw new IllegalArgumentException("No file or directory was chosen"); }
[ "@", "Cmd", "public", "File", "chooseFile", "(", "final", "String", "fileKey", ")", "{", "log", ".", "debug", "(", "\"Opening file chooser dialog\"", ")", ";", "JFileChooser", "fileChooser", "=", "new", "JFileChooser", "(", "System", ".", "getProperty", "(", "...
Opens a file chooser dialog which can then be used to choose a file or directory and assign the path of the chosen object to a variable. The name of the variable must be passed as a parameter. @param fileKey the key the selected file path is stored under in the configuration @return the chosen file
[ "Opens", "a", "file", "chooser", "dialog", "which", "can", "then", "be", "used", "to", "choose", "a", "file", "or", "directory", "and", "assign", "the", "path", "of", "the", "chosen", "object", "to", "a", "variable", ".", "The", "name", "of", "the", "v...
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ScriptContext.java#L196-L214
spring-projects/spring-boot
spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/json-shade/java/org/springframework/boot/configurationprocessor/json/JSONObject.java
JSONObject.optString
public String optString(String name, String fallback) { Object object = opt(name); String result = JSON.toString(object); return result != null ? result : fallback; }
java
public String optString(String name, String fallback) { Object object = opt(name); String result = JSON.toString(object); return result != null ? result : fallback; }
[ "public", "String", "optString", "(", "String", "name", ",", "String", "fallback", ")", "{", "Object", "object", "=", "opt", "(", "name", ")", ";", "String", "result", "=", "JSON", ".", "toString", "(", "object", ")", ";", "return", "result", "!=", "nu...
Returns the value mapped by {@code name} if it exists, coercing it if necessary. Returns {@code fallback} if no such mapping exists. @param name the name of the property @param fallback a fallback value @return the value or {@code fallback}
[ "Returns", "the", "value", "mapped", "by", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/json-shade/java/org/springframework/boot/configurationprocessor/json/JSONObject.java#L586-L590
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/MutableDictionary.java
MutableDictionary.setInt
@NonNull @Override public MutableDictionary setInt(@NonNull String key, int value) { return setValue(key, value); }
java
@NonNull @Override public MutableDictionary setInt(@NonNull String key, int value) { return setValue(key, value); }
[ "@", "NonNull", "@", "Override", "public", "MutableDictionary", "setInt", "(", "@", "NonNull", "String", "key", ",", "int", "value", ")", "{", "return", "setValue", "(", "key", ",", "value", ")", ";", "}" ]
Set an int value for the given key. @param key The key @param value The int value. @return The self object.
[ "Set", "an", "int", "value", "for", "the", "given", "key", "." ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableDictionary.java#L143-L147
moparisthebest/beehive
beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParameterChecker.java
ParameterChecker.checkReflectionParameters
public static void checkReflectionParameters(SqlFragmentContainer statement, MethodDeclaration methodDecl) { ArrayList<ParameterDeclaration> params = new ArrayList<ParameterDeclaration>(methodDecl.getParameters()); HashMap<String, ParameterDeclaration> paramMap = new HashMap<String, ParameterDeclaration>(); // don't run these checks if this is a compiled class file (method names replaced with arg0, arg1, etc) if (params.size() > 0 && params.get(0).getSimpleName().equals("arg0")) { return; } for (int i = 0; i < params.size(); i++) { paramMap.put(params.get(i).getSimpleName(), params.get(i)); } doCheck(statement, paramMap, methodDecl); }
java
public static void checkReflectionParameters(SqlFragmentContainer statement, MethodDeclaration methodDecl) { ArrayList<ParameterDeclaration> params = new ArrayList<ParameterDeclaration>(methodDecl.getParameters()); HashMap<String, ParameterDeclaration> paramMap = new HashMap<String, ParameterDeclaration>(); // don't run these checks if this is a compiled class file (method names replaced with arg0, arg1, etc) if (params.size() > 0 && params.get(0).getSimpleName().equals("arg0")) { return; } for (int i = 0; i < params.size(); i++) { paramMap.put(params.get(i).getSimpleName(), params.get(i)); } doCheck(statement, paramMap, methodDecl); }
[ "public", "static", "void", "checkReflectionParameters", "(", "SqlFragmentContainer", "statement", ",", "MethodDeclaration", "methodDecl", ")", "{", "ArrayList", "<", "ParameterDeclaration", ">", "params", "=", "new", "ArrayList", "<", "ParameterDeclaration", ">", "(", ...
Verify that all reflection parameters in the statement element can be mapped to method parameters. @param statement The parsed statement element. @param methodDecl The method declaration which was annotated.
[ "Verify", "that", "all", "reflection", "parameters", "in", "the", "statement", "element", "can", "be", "mapped", "to", "method", "parameters", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ParameterChecker.java#L50-L66
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/text/codepoint/CodepointHelper.java
CodepointHelper.verify
public static void verify (final AbstractCodepointIterator aIter, final IntPredicate aFilter) { final CodepointIteratorRestricted rci = aIter.restrict (aFilter, false); while (rci.hasNext ()) rci.next (); }
java
public static void verify (final AbstractCodepointIterator aIter, final IntPredicate aFilter) { final CodepointIteratorRestricted rci = aIter.restrict (aFilter, false); while (rci.hasNext ()) rci.next (); }
[ "public", "static", "void", "verify", "(", "final", "AbstractCodepointIterator", "aIter", ",", "final", "IntPredicate", "aFilter", ")", "{", "final", "CodepointIteratorRestricted", "rci", "=", "aIter", ".", "restrict", "(", "aFilter", ",", "false", ")", ";", "wh...
Verifies a sequence of codepoints using the specified filter @param aIter Codepointer iterator @param aFilter filter
[ "Verifies", "a", "sequence", "of", "codepoints", "using", "the", "specified", "filter" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/text/codepoint/CodepointHelper.java#L747-L752
samskivert/samskivert
src/main/java/com/samskivert/servlet/util/ParameterUtil.java
ParameterUtil.requireDateParameter
public static Date requireDateParameter ( HttpServletRequest req, String name, String invalidDataMessage) throws DataValidationException { return parseDateParameter(getParameter(req, name, false), invalidDataMessage); }
java
public static Date requireDateParameter ( HttpServletRequest req, String name, String invalidDataMessage) throws DataValidationException { return parseDateParameter(getParameter(req, name, false), invalidDataMessage); }
[ "public", "static", "Date", "requireDateParameter", "(", "HttpServletRequest", "req", ",", "String", "name", ",", "String", "invalidDataMessage", ")", "throws", "DataValidationException", "{", "return", "parseDateParameter", "(", "getParameter", "(", "req", ",", "name...
Fetches the supplied parameter from the request and converts it to a date. The value of the parameter should be a date formatted like so: 2001-12-25. If the parameter does not exist or is not a well-formed date, a data validation exception is thrown with the supplied message.
[ "Fetches", "the", "supplied", "parameter", "from", "the", "request", "and", "converts", "it", "to", "a", "date", ".", "The", "value", "of", "the", "parameter", "should", "be", "a", "date", "formatted", "like", "so", ":", "2001", "-", "12", "-", "25", "...
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/util/ParameterUtil.java#L237-L242
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/UriEscaper.java
UriEscaper.escapeFragment
public static String escapeFragment(final String fragment, final boolean strict) { return (strict ? STRICT_ESCAPER : ESCAPER).escapeFragment(fragment); }
java
public static String escapeFragment(final String fragment, final boolean strict) { return (strict ? STRICT_ESCAPER : ESCAPER).escapeFragment(fragment); }
[ "public", "static", "String", "escapeFragment", "(", "final", "String", "fragment", ",", "final", "boolean", "strict", ")", "{", "return", "(", "strict", "?", "STRICT_ESCAPER", ":", "ESCAPER", ")", ".", "escapeFragment", "(", "fragment", ")", ";", "}" ]
Escapes a string as a URI query @param fragment the path to escape @param strict whether or not to do strict escaping @return the escaped string
[ "Escapes", "a", "string", "as", "a", "URI", "query" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/UriEscaper.java#L271-L273
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/CommsLightTrace.java
CommsLightTrace.traceException
public static void traceException(TraceComponent callersTrace, Throwable ex) { if (light_tc.isDebugEnabled() || callersTrace.isDebugEnabled()) { // Find XA completion code if one exists, as this isn't in a normal dump String xaErrStr = null; if (ex instanceof XAException) { XAException xaex = (XAException)ex; xaErrStr = "XAExceptionErrorCode: " + xaex.errorCode; } // Trace using the correct trace group if (light_tc.isDebugEnabled()) { if (xaErrStr != null) SibTr.debug(light_tc, xaErrStr); SibTr.exception(light_tc, ex); } else { if (xaErrStr != null) SibTr.debug(callersTrace, xaErrStr); SibTr.exception(callersTrace, ex); } } }
java
public static void traceException(TraceComponent callersTrace, Throwable ex) { if (light_tc.isDebugEnabled() || callersTrace.isDebugEnabled()) { // Find XA completion code if one exists, as this isn't in a normal dump String xaErrStr = null; if (ex instanceof XAException) { XAException xaex = (XAException)ex; xaErrStr = "XAExceptionErrorCode: " + xaex.errorCode; } // Trace using the correct trace group if (light_tc.isDebugEnabled()) { if (xaErrStr != null) SibTr.debug(light_tc, xaErrStr); SibTr.exception(light_tc, ex); } else { if (xaErrStr != null) SibTr.debug(callersTrace, xaErrStr); SibTr.exception(callersTrace, ex); } } }
[ "public", "static", "void", "traceException", "(", "TraceComponent", "callersTrace", ",", "Throwable", "ex", ")", "{", "if", "(", "light_tc", ".", "isDebugEnabled", "(", ")", "||", "callersTrace", ".", "isDebugEnabled", "(", ")", ")", "{", "// Find XA completion...
Trace an exception. @param callersTrace The trace component of the caller @param ex The exception
[ "Trace", "an", "exception", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/CommsLightTrace.java#L157-L178
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/dense/DescribeDenseHogFastAlg.java
DescribeDenseHogFastAlg.computeDescriptor
void computeDescriptor(int row, int col) { // set location to top-left pixel locations.grow().set(col* pixelsPerCell,row* pixelsPerCell); TupleDesc_F64 d = descriptions.grow(); int indexDesc = 0; for (int i = 0; i < cellsPerBlockY; i++) { for (int j = 0; j < cellsPerBlockX; j++) { Cell c = cells[(row+i)*cellCols + (col+j)]; for (int k = 0; k < c.histogram.length; k++) { d.value[indexDesc++] = c.histogram[k]; } } } // Apply SIFT style L2-Hys normalization DescribeSiftCommon.normalizeDescriptor(d,0.2); }
java
void computeDescriptor(int row, int col) { // set location to top-left pixel locations.grow().set(col* pixelsPerCell,row* pixelsPerCell); TupleDesc_F64 d = descriptions.grow(); int indexDesc = 0; for (int i = 0; i < cellsPerBlockY; i++) { for (int j = 0; j < cellsPerBlockX; j++) { Cell c = cells[(row+i)*cellCols + (col+j)]; for (int k = 0; k < c.histogram.length; k++) { d.value[indexDesc++] = c.histogram[k]; } } } // Apply SIFT style L2-Hys normalization DescribeSiftCommon.normalizeDescriptor(d,0.2); }
[ "void", "computeDescriptor", "(", "int", "row", ",", "int", "col", ")", "{", "// set location to top-left pixel", "locations", ".", "grow", "(", ")", ".", "set", "(", "col", "*", "pixelsPerCell", ",", "row", "*", "pixelsPerCell", ")", ";", "TupleDesc_F64", "...
Compute the descriptor from the specified cells. (row,col) to (row+w,col+w) @param row Lower extent of cell rows @param col Lower extent of cell columns
[ "Compute", "the", "descriptor", "from", "the", "specified", "cells", ".", "(", "row", "col", ")", "to", "(", "row", "+", "w", "col", "+", "w", ")" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/dense/DescribeDenseHogFastAlg.java#L150-L169
iwgang/SimplifySpan
library/src/main/java/cn/iwgang/simplifyspan/SimplifySpanBuild.java
SimplifySpanBuild.appendMultiClickableToFirst
public SimplifySpanBuild appendMultiClickableToFirst(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) { processMultiClickableSpecialUnit(true, specialClickableUnit, specialUnitOrStrings); return this; }
java
public SimplifySpanBuild appendMultiClickableToFirst(SpecialClickableUnit specialClickableUnit, Object... specialUnitOrStrings) { processMultiClickableSpecialUnit(true, specialClickableUnit, specialUnitOrStrings); return this; }
[ "public", "SimplifySpanBuild", "appendMultiClickableToFirst", "(", "SpecialClickableUnit", "specialClickableUnit", ",", "Object", "...", "specialUnitOrStrings", ")", "{", "processMultiClickableSpecialUnit", "(", "true", ",", "specialClickableUnit", ",", "specialUnitOrStrings", ...
append multi clickable SpecialUnit or String to first (Behind the existing BeforeContent) @param specialClickableUnit SpecialClickableUnit @param specialUnitOrStrings Unit Or String @return
[ "append", "multi", "clickable", "SpecialUnit", "or", "String", "to", "first", "(", "Behind", "the", "existing", "BeforeContent", ")" ]
train
https://github.com/iwgang/SimplifySpan/blob/34e917cd5497215c8abc07b3d8df187949967283/library/src/main/java/cn/iwgang/simplifyspan/SimplifySpanBuild.java#L252-L255
zxing/zxing
core/src/main/java/com/google/zxing/qrcode/detector/FinderPattern.java
FinderPattern.combineEstimate
FinderPattern combineEstimate(float i, float j, float newModuleSize) { int combinedCount = count + 1; float combinedX = (count * getX() + j) / combinedCount; float combinedY = (count * getY() + i) / combinedCount; float combinedModuleSize = (count * estimatedModuleSize + newModuleSize) / combinedCount; return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount); }
java
FinderPattern combineEstimate(float i, float j, float newModuleSize) { int combinedCount = count + 1; float combinedX = (count * getX() + j) / combinedCount; float combinedY = (count * getY() + i) / combinedCount; float combinedModuleSize = (count * estimatedModuleSize + newModuleSize) / combinedCount; return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount); }
[ "FinderPattern", "combineEstimate", "(", "float", "i", ",", "float", "j", ",", "float", "newModuleSize", ")", "{", "int", "combinedCount", "=", "count", "+", "1", ";", "float", "combinedX", "=", "(", "count", "*", "getX", "(", ")", "+", "j", ")", "/", ...
Combines this object's current estimate of a finder pattern position and module size with a new estimate. It returns a new {@code FinderPattern} containing a weighted average based on count.
[ "Combines", "this", "object", "s", "current", "estimate", "of", "a", "finder", "pattern", "position", "and", "module", "size", "with", "a", "new", "estimate", ".", "It", "returns", "a", "new", "{" ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/qrcode/detector/FinderPattern.java#L74-L80
ben-manes/caffeine
simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/WindowTinyLfuPolicy.java
WindowTinyLfuPolicy.policies
public static Set<Policy> policies(Config config) { WindowTinyLfuSettings settings = new WindowTinyLfuSettings(config); return settings.percentMain().stream() .map(percentMain -> new WindowTinyLfuPolicy(percentMain, settings)) .collect(toSet()); }
java
public static Set<Policy> policies(Config config) { WindowTinyLfuSettings settings = new WindowTinyLfuSettings(config); return settings.percentMain().stream() .map(percentMain -> new WindowTinyLfuPolicy(percentMain, settings)) .collect(toSet()); }
[ "public", "static", "Set", "<", "Policy", ">", "policies", "(", "Config", "config", ")", "{", "WindowTinyLfuSettings", "settings", "=", "new", "WindowTinyLfuSettings", "(", "config", ")", ";", "return", "settings", ".", "percentMain", "(", ")", ".", "stream", ...
Returns all variations of this policy based on the configuration parameters.
[ "Returns", "all", "variations", "of", "this", "policy", "based", "on", "the", "configuration", "parameters", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/WindowTinyLfuPolicy.java#L84-L89
alkacon/opencms-core
src/org/opencms/module/CmsModuleManager.java
CmsModuleManager.updateModule
public synchronized void updateModule(CmsObject cms, CmsModule module) throws CmsRoleViolationException, CmsConfigurationException { // check for module manager role permissions OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); CmsModule oldModule = m_modules.get(module.getName()); if (oldModule == null) { // module is not currently configured, no update possible throw new CmsConfigurationException(Messages.get().container(Messages.ERR_OLD_MOD_ERR_1, module.getName())); } if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_MOD_UPDATE_1, module.getName())); } // indicate that the version number was recently updated module.getVersion().setUpdated(true); // initialize (freeze) the module module.initialize(cms); // replace old version of module with new version m_modules.put(module.getName(), module); try { I_CmsModuleAction moduleAction = oldModule.getActionInstance(); // handle module action instance if initialized if (moduleAction != null) { moduleAction.moduleUpdate(module); // set the old action instance // the new action instance will be used after a system restart module.setActionInstance(moduleAction); } } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_INSTANCE_UPDATE_ERR_1, module.getName()), t); } // initialize the export points initModuleExportPoints(); // update the configuration updateModuleConfiguration(); // reinit the workplace CSS URIs if (!module.getParameters().isEmpty()) { OpenCms.getWorkplaceAppManager().initWorkplaceCssUris(this); } }
java
public synchronized void updateModule(CmsObject cms, CmsModule module) throws CmsRoleViolationException, CmsConfigurationException { // check for module manager role permissions OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); CmsModule oldModule = m_modules.get(module.getName()); if (oldModule == null) { // module is not currently configured, no update possible throw new CmsConfigurationException(Messages.get().container(Messages.ERR_OLD_MOD_ERR_1, module.getName())); } if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_MOD_UPDATE_1, module.getName())); } // indicate that the version number was recently updated module.getVersion().setUpdated(true); // initialize (freeze) the module module.initialize(cms); // replace old version of module with new version m_modules.put(module.getName(), module); try { I_CmsModuleAction moduleAction = oldModule.getActionInstance(); // handle module action instance if initialized if (moduleAction != null) { moduleAction.moduleUpdate(module); // set the old action instance // the new action instance will be used after a system restart module.setActionInstance(moduleAction); } } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_INSTANCE_UPDATE_ERR_1, module.getName()), t); } // initialize the export points initModuleExportPoints(); // update the configuration updateModuleConfiguration(); // reinit the workplace CSS URIs if (!module.getParameters().isEmpty()) { OpenCms.getWorkplaceAppManager().initWorkplaceCssUris(this); } }
[ "public", "synchronized", "void", "updateModule", "(", "CmsObject", "cms", ",", "CmsModule", "module", ")", "throws", "CmsRoleViolationException", ",", "CmsConfigurationException", "{", "// check for module manager role permissions", "OpenCms", ".", "getRoleManager", "(", "...
Updates a already configured module with new values.<p> @param cms must be initialized with "Admin" permissions @param module the module to update @throws CmsRoleViolationException if the required module manager role permissions are not available @throws CmsConfigurationException if a module with this name is not available for updating
[ "Updates", "a", "already", "configured", "module", "with", "new", "values", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleManager.java#L985-L1034
jhy/jsoup
src/main/java/org/jsoup/parser/Tag.java
Tag.valueOf
public static Tag valueOf(String tagName, ParseSettings settings) { Validate.notNull(tagName); Tag tag = tags.get(tagName); if (tag == null) { tagName = settings.normalizeTag(tagName); Validate.notEmpty(tagName); tag = tags.get(tagName); if (tag == null) { // not defined: create default; go anywhere, do anything! (incl be inside a <p>) tag = new Tag(tagName); tag.isBlock = false; } } return tag; }
java
public static Tag valueOf(String tagName, ParseSettings settings) { Validate.notNull(tagName); Tag tag = tags.get(tagName); if (tag == null) { tagName = settings.normalizeTag(tagName); Validate.notEmpty(tagName); tag = tags.get(tagName); if (tag == null) { // not defined: create default; go anywhere, do anything! (incl be inside a <p>) tag = new Tag(tagName); tag.isBlock = false; } } return tag; }
[ "public", "static", "Tag", "valueOf", "(", "String", "tagName", ",", "ParseSettings", "settings", ")", "{", "Validate", ".", "notNull", "(", "tagName", ")", ";", "Tag", "tag", "=", "tags", ".", "get", "(", "tagName", ")", ";", "if", "(", "tag", "==", ...
Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. <p> Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). </p> @param tagName Name of tag, e.g. "p". Case insensitive. @param settings used to control tag name sensitivity @return The tag, either defined or new generic.
[ "Get", "a", "Tag", "by", "name", ".", "If", "not", "previously", "defined", "(", "unknown", ")", "returns", "a", "new", "generic", "tag", "that", "can", "do", "anything", ".", "<p", ">", "Pre", "-", "defined", "tags", "(", "P", "DIV", "etc", ")", "...
train
https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/parser/Tag.java#L60-L76
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowControlContainerFactory.java
PageFlowControlContainerFactory.getSessionVar
private static Object getSessionVar(HttpServletRequest request, ServletContext servletContext, String name) { StorageHandler sh = Handlers.get( servletContext ).getStorageHandler(); HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request ); RequestContext rc = new RequestContext( unwrappedRequest, null ); String attrName = ScopedServletUtils.getScopedSessionAttrName(name, unwrappedRequest); return sh.getAttribute( rc, attrName ); }
java
private static Object getSessionVar(HttpServletRequest request, ServletContext servletContext, String name) { StorageHandler sh = Handlers.get( servletContext ).getStorageHandler(); HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request ); RequestContext rc = new RequestContext( unwrappedRequest, null ); String attrName = ScopedServletUtils.getScopedSessionAttrName(name, unwrappedRequest); return sh.getAttribute( rc, attrName ); }
[ "private", "static", "Object", "getSessionVar", "(", "HttpServletRequest", "request", ",", "ServletContext", "servletContext", ",", "String", "name", ")", "{", "StorageHandler", "sh", "=", "Handlers", ".", "get", "(", "servletContext", ")", ".", "getStorageHandler",...
This is a generic routine that will retrieve a value from the Session through the StorageHandler. @param request @param servletContext @param name The name of the value to be retrieved @return The requested value from the session
[ "This", "is", "a", "generic", "routine", "that", "will", "retrieve", "a", "value", "from", "the", "Session", "through", "the", "StorageHandler", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowControlContainerFactory.java#L59-L67
BellaDati/belladati-sdk-api
src/main/java/com/belladati/sdk/dataset/data/OverwritePolicy.java
OverwritePolicy.byAttributes
public static OverwritePolicy byAttributes(String firstAttribute, String... otherAttributes) { List<String> attributes = new ArrayList<String>(); attributes.add(firstAttribute); attributes.addAll(Arrays.asList(otherAttributes)); return new AttributeOverwritePolicy(attributes); }
java
public static OverwritePolicy byAttributes(String firstAttribute, String... otherAttributes) { List<String> attributes = new ArrayList<String>(); attributes.add(firstAttribute); attributes.addAll(Arrays.asList(otherAttributes)); return new AttributeOverwritePolicy(attributes); }
[ "public", "static", "OverwritePolicy", "byAttributes", "(", "String", "firstAttribute", ",", "String", "...", "otherAttributes", ")", "{", "List", "<", "String", ">", "attributes", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "attributes", ".", ...
Returns an {@link OverwritePolicy} that deletes records that are identical in the specified attributes with a record being imported. As a result, no two records can exist in the data set that have the same values for all of those attributes at once. <br> At least one attribute needs to be specified. <p> Empty attribute values in existing data are treated as matching anything. Existing records that match an imported record on all non-empty attributes are deleted. @param firstAttribute first attribute @param otherAttributes additional, optional attributes @return a policy deleting non-unique data by selected attributes
[ "Returns", "an", "{", "@link", "OverwritePolicy", "}", "that", "deletes", "records", "that", "are", "identical", "in", "the", "specified", "attributes", "with", "a", "record", "being", "imported", ".", "As", "a", "result", "no", "two", "records", "can", "exi...
train
https://github.com/BellaDati/belladati-sdk-api/blob/ec45a42048d8255838ad0200aa6784a8e8a121c1/src/main/java/com/belladati/sdk/dataset/data/OverwritePolicy.java#L89-L94
magott/spring-social-yammer
spring-social-yammer/src/main/java/org/springframework/social/yammer/api/impl/GroupTemplate.java
GroupTemplate.updateGroup
public void updateGroup(long groupId, String name, boolean isPrivate) { LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.set("name",name); params.set("private", String.valueOf(isPrivate)); restTemplate.put(buildUri("groups/"+groupId), params); }
java
public void updateGroup(long groupId, String name, boolean isPrivate) { LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.set("name",name); params.set("private", String.valueOf(isPrivate)); restTemplate.put(buildUri("groups/"+groupId), params); }
[ "public", "void", "updateGroup", "(", "long", "groupId", ",", "String", "name", ",", "boolean", "isPrivate", ")", "{", "LinkedMultiValueMap", "<", "String", ",", "String", ">", "params", "=", "new", "LinkedMultiValueMap", "<", "String", ",", "String", ">", "...
Method returns 401 from Yammer, so it isn't visible in GroupOperations yet @param groupId @param name @param isPrivate
[ "Method", "returns", "401", "from", "Yammer", "so", "it", "isn", "t", "visible", "in", "GroupOperations", "yet" ]
train
https://github.com/magott/spring-social-yammer/blob/a39dab7c33e40bfaa26c15b6336823edf57452c3/spring-social-yammer/src/main/java/org/springframework/social/yammer/api/impl/GroupTemplate.java#L71-L76
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/IndexWriter.java
IndexWriter.generateBucketUpdate
private void generateBucketUpdate(TableBucket bucket, long bucketOffset, UpdateInstructions update) { assert bucketOffset >= 0; update.withAttribute(new AttributeUpdate(bucket.getHash(), AttributeUpdateType.Replace, bucketOffset)); if (!bucket.exists()) { update.bucketAdded(); } }
java
private void generateBucketUpdate(TableBucket bucket, long bucketOffset, UpdateInstructions update) { assert bucketOffset >= 0; update.withAttribute(new AttributeUpdate(bucket.getHash(), AttributeUpdateType.Replace, bucketOffset)); if (!bucket.exists()) { update.bucketAdded(); } }
[ "private", "void", "generateBucketUpdate", "(", "TableBucket", "bucket", ",", "long", "bucketOffset", ",", "UpdateInstructions", "update", ")", "{", "assert", "bucketOffset", ">=", "0", ";", "update", ".", "withAttribute", "(", "new", "AttributeUpdate", "(", "buck...
Generates one or more {@link AttributeUpdate}s that will create or update the necessary Table Buckets entries in the Segment's Extended Attributes. @param bucket The Bucket to create or update. @param bucketOffset The Bucket's new offset. @param update A {@link UpdateInstructions} object to collect updates into.
[ "Generates", "one", "or", "more", "{", "@link", "AttributeUpdate", "}", "s", "that", "will", "create", "or", "update", "the", "necessary", "Table", "Buckets", "entries", "in", "the", "Segment", "s", "Extended", "Attributes", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/IndexWriter.java#L196-L202
onelogin/onelogin-java-sdk
src/main/java/com/onelogin/sdk/conn/Client.java
Client.getSAMLAssertionVerifying
public SAMLEndpointResponse getSAMLAssertionVerifying(String appId, String devideId, String stateToken, String otpToken) throws OAuthSystemException, OAuthProblemException, URISyntaxException { return getSAMLAssertionVerifying(appId, devideId, stateToken, otpToken, null); }
java
public SAMLEndpointResponse getSAMLAssertionVerifying(String appId, String devideId, String stateToken, String otpToken) throws OAuthSystemException, OAuthProblemException, URISyntaxException { return getSAMLAssertionVerifying(appId, devideId, stateToken, otpToken, null); }
[ "public", "SAMLEndpointResponse", "getSAMLAssertionVerifying", "(", "String", "appId", ",", "String", "devideId", ",", "String", "stateToken", ",", "String", "otpToken", ")", "throws", "OAuthSystemException", ",", "OAuthProblemException", ",", "URISyntaxException", "{", ...
Verifies a one-time password (OTP) value provided for a second factor when multi-factor authentication (MFA) is required for SAML authentication. @param appId App ID of the app for which you want to generate a SAML token @param devideId Provide the MFA device_id you are submitting for verification. @param stateToken Provide the state_token associated with the MFA device_id you are submitting for verification. @param otpToken Provide the OTP value for the MFA factor you are submitting for verification. @return SAMLEndpointResponse @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see com.onelogin.sdk.model.SAMLEndpointResponse @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/saml-assertions/verify-factor">Verify Factor documentation</a>
[ "Verifies", "a", "one", "-", "time", "password", "(", "OTP", ")", "value", "provided", "for", "a", "second", "factor", "when", "multi", "-", "factor", "authentication", "(", "MFA", ")", "is", "required", "for", "SAML", "authentication", "." ]
train
https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L2578-L2580
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/BatchOperation.java
BatchOperation.addReportQuery
public void addReportQuery(String reportQuery, String bId) { BatchItemRequest batchItemRequest = new BatchItemRequest(); batchItemRequest.setBId(bId); batchItemRequest.setReportQuery(reportQuery); batchItemRequests.add(batchItemRequest); bIds.add(bId); }
java
public void addReportQuery(String reportQuery, String bId) { BatchItemRequest batchItemRequest = new BatchItemRequest(); batchItemRequest.setBId(bId); batchItemRequest.setReportQuery(reportQuery); batchItemRequests.add(batchItemRequest); bIds.add(bId); }
[ "public", "void", "addReportQuery", "(", "String", "reportQuery", ",", "String", "bId", ")", "{", "BatchItemRequest", "batchItemRequest", "=", "new", "BatchItemRequest", "(", ")", ";", "batchItemRequest", ".", "setBId", "(", "bId", ")", ";", "batchItemRequest", ...
Method to add the report query batch operation to batchItemRequest @param reportQuery @param bId
[ "Method", "to", "add", "the", "report", "query", "batch", "operation", "to", "batchItemRequest" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/BatchOperation.java#L169-L177
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/ElasticSearchSchemaService.java
ElasticSearchSchemaService.toEntity
private <T> T toEntity(String content, TypeReference<T> type) { try { return _mapper.readValue(content, type); } catch (IOException ex) { throw new SystemException(ex); } }
java
private <T> T toEntity(String content, TypeReference<T> type) { try { return _mapper.readValue(content, type); } catch (IOException ex) { throw new SystemException(ex); } }
[ "private", "<", "T", ">", "T", "toEntity", "(", "String", "content", ",", "TypeReference", "<", "T", ">", "type", ")", "{", "try", "{", "return", "_mapper", ".", "readValue", "(", "content", ",", "type", ")", ";", "}", "catch", "(", "IOException", "e...
/* Helper method to convert JSON String representation to the corresponding Java entity.
[ "/", "*", "Helper", "method", "to", "convert", "JSON", "String", "representation", "to", "the", "corresponding", "Java", "entity", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/ElasticSearchSchemaService.java#L1372-L1378
killme2008/xmemcached
src/main/java/net/rubyeye/xmemcached/aws/AWSUtils.java
AWSUtils.parseConfiguration
public static ClusterConfigration parseConfiguration(String line) { String[] lines = line.trim().split("(?:\\r?\\n)"); if (lines.length < 2) { throw new IllegalArgumentException("Incorrect config response:" + line); } String configversion = lines[0]; String nodeListStr = lines[1]; if (!ByteUtils.isNumber(configversion)) { throw new IllegalArgumentException( "Invalid configversion: " + configversion + ", it should be a number."); } String[] nodeStrs = nodeListStr.split("(?:\\s)+"); int version = Integer.parseInt(configversion); List<CacheNode> nodeList = new ArrayList<CacheNode>(nodeStrs.length); for (String nodeStr : nodeStrs) { if (nodeStr.equals("")) { continue; } int firstDelimiter = nodeStr.indexOf(DELIMITER); int secondDelimiter = nodeStr.lastIndexOf(DELIMITER); if (firstDelimiter < 1 || firstDelimiter == secondDelimiter) { throw new IllegalArgumentException( "Invalid server ''" + nodeStr + "'' in response: " + line); } String hostName = nodeStr.substring(0, firstDelimiter).trim(); String ipAddress = nodeStr.substring(firstDelimiter + 1, secondDelimiter).trim(); String portNum = nodeStr.substring(secondDelimiter + 1).trim(); int port = Integer.parseInt(portNum); nodeList.add(new CacheNode(hostName, ipAddress, port)); } return new ClusterConfigration(version, nodeList); }
java
public static ClusterConfigration parseConfiguration(String line) { String[] lines = line.trim().split("(?:\\r?\\n)"); if (lines.length < 2) { throw new IllegalArgumentException("Incorrect config response:" + line); } String configversion = lines[0]; String nodeListStr = lines[1]; if (!ByteUtils.isNumber(configversion)) { throw new IllegalArgumentException( "Invalid configversion: " + configversion + ", it should be a number."); } String[] nodeStrs = nodeListStr.split("(?:\\s)+"); int version = Integer.parseInt(configversion); List<CacheNode> nodeList = new ArrayList<CacheNode>(nodeStrs.length); for (String nodeStr : nodeStrs) { if (nodeStr.equals("")) { continue; } int firstDelimiter = nodeStr.indexOf(DELIMITER); int secondDelimiter = nodeStr.lastIndexOf(DELIMITER); if (firstDelimiter < 1 || firstDelimiter == secondDelimiter) { throw new IllegalArgumentException( "Invalid server ''" + nodeStr + "'' in response: " + line); } String hostName = nodeStr.substring(0, firstDelimiter).trim(); String ipAddress = nodeStr.substring(firstDelimiter + 1, secondDelimiter).trim(); String portNum = nodeStr.substring(secondDelimiter + 1).trim(); int port = Integer.parseInt(portNum); nodeList.add(new CacheNode(hostName, ipAddress, port)); } return new ClusterConfigration(version, nodeList); }
[ "public", "static", "ClusterConfigration", "parseConfiguration", "(", "String", "line", ")", "{", "String", "[", "]", "lines", "=", "line", ".", "trim", "(", ")", ".", "split", "(", "\"(?:\\\\r?\\\\n)\"", ")", ";", "if", "(", "lines", ".", "length", "<", ...
Parse response string to ClusterConfiguration instance. @param line @return
[ "Parse", "response", "string", "to", "ClusterConfiguration", "instance", "." ]
train
https://github.com/killme2008/xmemcached/blob/66150915938813b3e3413de1d7b43b6ff9b1478d/src/main/java/net/rubyeye/xmemcached/aws/AWSUtils.java#L23-L57
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Normalizer.java
Normalizer.isNormalized
@Deprecated public static boolean isNormalized(String str, Mode mode, int options) { return mode.getNormalizer2(options).isNormalized(str); }
java
@Deprecated public static boolean isNormalized(String str, Mode mode, int options) { return mode.getNormalizer2(options).isNormalized(str); }
[ "@", "Deprecated", "public", "static", "boolean", "isNormalized", "(", "String", "str", ",", "Mode", "mode", ",", "int", "options", ")", "{", "return", "mode", ".", "getNormalizer2", "(", "options", ")", ".", "isNormalized", "(", "str", ")", ";", "}" ]
Test if a string is in a given normalization form. This is semantically equivalent to source.equals(normalize(source, mode)). Unlike quickCheck(), this function returns a definitive result, never a "maybe". For NFD, NFKD, and FCD, both functions work exactly the same. For NFC and NFKC where quickCheck may return "maybe", this function will perform further tests to arrive at a true/false result. @param str the input string to be checked to see if it is normalized @param mode the normalization mode @param options Options for use with exclusion set and tailored Normalization The only option that is currently recognized is UNICODE_3_2 @see #isNormalized @deprecated ICU 56 Use {@link Normalizer2} instead. @hide original deprecated declaration
[ "Test", "if", "a", "string", "is", "in", "a", "given", "normalization", "form", ".", "This", "is", "semantically", "equivalent", "to", "source", ".", "equals", "(", "normalize", "(", "source", "mode", "))", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Normalizer.java#L1110-L1113
aws/aws-sdk-java
aws-java-sdk-logs/src/main/java/com/amazonaws/services/logs/model/GetLogRecordResult.java
GetLogRecordResult.withLogRecord
public GetLogRecordResult withLogRecord(java.util.Map<String, String> logRecord) { setLogRecord(logRecord); return this; }
java
public GetLogRecordResult withLogRecord(java.util.Map<String, String> logRecord) { setLogRecord(logRecord); return this; }
[ "public", "GetLogRecordResult", "withLogRecord", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "logRecord", ")", "{", "setLogRecord", "(", "logRecord", ")", ";", "return", "this", ";", "}" ]
<p> The requested log event, as a JSON string. </p> @param logRecord The requested log event, as a JSON string. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "requested", "log", "event", "as", "a", "JSON", "string", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-logs/src/main/java/com/amazonaws/services/logs/model/GetLogRecordResult.java#L71-L74
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RepositoryFileApi.java
RepositoryFileApi.updateFile
public RepositoryFile updateFile(Object projectIdOrPath, RepositoryFile file, String branchName, String commitMessage) throws GitLabApiException { Form formData = createForm(file, branchName, commitMessage); Response response; if (isApiVersion(ApiVersion.V3)) { response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files"); } else { response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(file.getFilePath())); } return (response.readEntity(RepositoryFile.class)); }
java
public RepositoryFile updateFile(Object projectIdOrPath, RepositoryFile file, String branchName, String commitMessage) throws GitLabApiException { Form formData = createForm(file, branchName, commitMessage); Response response; if (isApiVersion(ApiVersion.V3)) { response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files"); } else { response = put(Response.Status.OK, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(file.getFilePath())); } return (response.readEntity(RepositoryFile.class)); }
[ "public", "RepositoryFile", "updateFile", "(", "Object", "projectIdOrPath", ",", "RepositoryFile", "file", ",", "String", "branchName", ",", "String", "commitMessage", ")", "throws", "GitLabApiException", "{", "Form", "formData", "=", "createForm", "(", "file", ",",...
Update existing file in repository <pre><code>GitLab Endpoint: PUT /projects/:id/repository/files</code></pre> file_path (required) - Full path to new file. Ex. lib/class.rb branch_name (required) - The name of branch encoding (optional) - 'text' or 'base64'. Text is default. content (required) - File content commit_message (required) - Commit message @param projectIdOrPath the id, path of the project, or a Project instance holding the project ID or path @param file a ReposityoryFile instance with info for the file to update @param branchName the name of branch @param commitMessage the commit message @return a RepositoryFile instance with the updated file info @throws GitLabApiException if any exception occurs
[ "Update", "existing", "file", "in", "repository" ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryFileApi.java#L263-L276
knowm/XChange
xchange-coinbase/src/main/java/org/knowm/xchange/coinbase/service/CoinbaseAccountServiceRaw.java
CoinbaseAccountServiceRaw.generateCoinbaseReceiveAddress
public CoinbaseAddress generateCoinbaseReceiveAddress(String callbackUrl, final String label) throws IOException { final CoinbaseAddressCallback callbackUrlParam = new CoinbaseAddressCallback(callbackUrl, label); final CoinbaseAddress generateReceiveAddress = coinbase.generateReceiveAddress( callbackUrlParam, exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); return handleResponse(generateReceiveAddress); }
java
public CoinbaseAddress generateCoinbaseReceiveAddress(String callbackUrl, final String label) throws IOException { final CoinbaseAddressCallback callbackUrlParam = new CoinbaseAddressCallback(callbackUrl, label); final CoinbaseAddress generateReceiveAddress = coinbase.generateReceiveAddress( callbackUrlParam, exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); return handleResponse(generateReceiveAddress); }
[ "public", "CoinbaseAddress", "generateCoinbaseReceiveAddress", "(", "String", "callbackUrl", ",", "final", "String", "label", ")", "throws", "IOException", "{", "final", "CoinbaseAddressCallback", "callbackUrlParam", "=", "new", "CoinbaseAddressCallback", "(", "callbackUrl"...
Authenticated resource that generates a new Bitcoin receive address for the user. @param callbackUrl Optional Callback URL to receive instant payment notifications whenever funds arrive to this address. @param label Optional text label for the address which can be used to filter against when calling {@link #getCoinbaseAddresses}. @return The user’s newly generated and current {@code CoinbaseAddress}. @throws IOException @see <a href="https://coinbase.com/api/doc/1.0/accounts/generate_receive_address.html">coinbase.com/api/doc/1.0/accounts/generate_receive_address .html</a>
[ "Authenticated", "resource", "that", "generates", "a", "new", "Bitcoin", "receive", "address", "for", "the", "user", "." ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-coinbase/src/main/java/org/knowm/xchange/coinbase/service/CoinbaseAccountServiceRaw.java#L209-L222
micronaut-projects/micronaut-core
core/src/main/java/io/micronaut/core/reflect/ReflectionUtils.java
ReflectionUtils.getRequiredMethod
public static Method getRequiredMethod(Class type, String name, Class... argumentTypes) { try { return type.getDeclaredMethod(name, argumentTypes); } catch (NoSuchMethodException e) { return findMethod(type, name, argumentTypes) .orElseThrow(() -> newNoSuchMethodError(type, name, argumentTypes)); } }
java
public static Method getRequiredMethod(Class type, String name, Class... argumentTypes) { try { return type.getDeclaredMethod(name, argumentTypes); } catch (NoSuchMethodException e) { return findMethod(type, name, argumentTypes) .orElseThrow(() -> newNoSuchMethodError(type, name, argumentTypes)); } }
[ "public", "static", "Method", "getRequiredMethod", "(", "Class", "type", ",", "String", "name", ",", "Class", "...", "argumentTypes", ")", "{", "try", "{", "return", "type", ".", "getDeclaredMethod", "(", "name", ",", "argumentTypes", ")", ";", "}", "catch",...
Finds a method on the given type for the given name. @param type The type @param name The name @param argumentTypes The argument types @return An {@link Optional} contains the method or empty
[ "Finds", "a", "method", "on", "the", "given", "type", "for", "the", "given", "name", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/reflect/ReflectionUtils.java#L236-L243
jamesagnew/hapi-fhir
hapi-fhir-narrativegenerator/src/main/java/ca/uhn/fhir/narrative/template/Template.java
Template.parse
public static Template parse(String input) { return new Template(input, Tag.getTags(), Filter.getFilters()); }
java
public static Template parse(String input) { return new Template(input, Tag.getTags(), Filter.getFilters()); }
[ "public", "static", "Template", "parse", "(", "String", "input", ")", "{", "return", "new", "Template", "(", "input", ",", "Tag", ".", "getTags", "(", ")", ",", "Filter", ".", "getFilters", "(", ")", ")", ";", "}" ]
Returns a new Template instance from a given input string. @param input the input string holding the Liquid source. @return a new Template instance from a given input string.
[ "Returns", "a", "new", "Template", "instance", "from", "a", "given", "input", "string", "." ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-narrativegenerator/src/main/java/ca/uhn/fhir/narrative/template/Template.java#L123-L125
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.answerCallbackQuery
public boolean answerCallbackQuery(String callbackQueryId, CallbackQueryResponse callbackQueryResponse) { if(callbackQueryId != null && callbackQueryResponse.getText() != null) { HttpResponse<String> response; JSONObject jsonResponse; try { MultipartBody requests = Unirest.post(getBotAPIUrl() + "answerCallbackQuery") .field("callback_query_id", callbackQueryId, "application/json; charset=utf8;") .field("text", callbackQueryResponse.getText(), "application/json; charset=utf8;") .field("show_alert", callbackQueryResponse.isShowAlert()) .field("cache_time", callbackQueryResponse.getCacheTime()) .field("url", callbackQueryResponse.getURL() != null ? callbackQueryResponse.getURL().toExternalForm() : null, "application/json; charset=utf8;"); response = requests.asString(); jsonResponse = Utils.processResponse(response); if (jsonResponse != null) { if (jsonResponse.getBoolean("result")) return true; } } catch (UnirestException e) { e.printStackTrace(); } } return false; }
java
public boolean answerCallbackQuery(String callbackQueryId, CallbackQueryResponse callbackQueryResponse) { if(callbackQueryId != null && callbackQueryResponse.getText() != null) { HttpResponse<String> response; JSONObject jsonResponse; try { MultipartBody requests = Unirest.post(getBotAPIUrl() + "answerCallbackQuery") .field("callback_query_id", callbackQueryId, "application/json; charset=utf8;") .field("text", callbackQueryResponse.getText(), "application/json; charset=utf8;") .field("show_alert", callbackQueryResponse.isShowAlert()) .field("cache_time", callbackQueryResponse.getCacheTime()) .field("url", callbackQueryResponse.getURL() != null ? callbackQueryResponse.getURL().toExternalForm() : null, "application/json; charset=utf8;"); response = requests.asString(); jsonResponse = Utils.processResponse(response); if (jsonResponse != null) { if (jsonResponse.getBoolean("result")) return true; } } catch (UnirestException e) { e.printStackTrace(); } } return false; }
[ "public", "boolean", "answerCallbackQuery", "(", "String", "callbackQueryId", ",", "CallbackQueryResponse", "callbackQueryResponse", ")", "{", "if", "(", "callbackQueryId", "!=", "null", "&&", "callbackQueryResponse", ".", "getText", "(", ")", "!=", "null", ")", "{"...
This allows you to respond to a callback query with some text as a response. This will either show up as an alert or as a toast on the telegram client @param callbackQueryId The ID of the callback query you are responding to @param callbackQueryResponse The response that you would like to send in reply to this callback query @return True if the response was sent successfully, otherwise False
[ "This", "allows", "you", "to", "respond", "to", "a", "callback", "query", "with", "some", "text", "as", "a", "response", ".", "This", "will", "either", "show", "up", "as", "an", "alert", "or", "as", "a", "toast", "on", "the", "telegram", "client" ]
train
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L995-L1024
grpc/grpc-java
netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java
ProtocolNegotiators.serverTls
public static ProtocolNegotiator serverTls(final SslContext sslContext) { Preconditions.checkNotNull(sslContext, "sslContext"); return new ProtocolNegotiator() { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler handler) { return new ServerTlsHandler(sslContext, handler); } @Override public void close() {} @Override public AsciiString scheme() { return Utils.HTTPS; } }; }
java
public static ProtocolNegotiator serverTls(final SslContext sslContext) { Preconditions.checkNotNull(sslContext, "sslContext"); return new ProtocolNegotiator() { @Override public ChannelHandler newHandler(GrpcHttp2ConnectionHandler handler) { return new ServerTlsHandler(sslContext, handler); } @Override public void close() {} @Override public AsciiString scheme() { return Utils.HTTPS; } }; }
[ "public", "static", "ProtocolNegotiator", "serverTls", "(", "final", "SslContext", "sslContext", ")", "{", "Preconditions", ".", "checkNotNull", "(", "sslContext", ",", "\"sslContext\"", ")", ";", "return", "new", "ProtocolNegotiator", "(", ")", "{", "@", "Overrid...
Create a server TLS handler for HTTP/2 capable of using ALPN/NPN.
[ "Create", "a", "server", "TLS", "handler", "for", "HTTP", "/", "2", "capable", "of", "using", "ALPN", "/", "NPN", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java#L118-L135
jaxio/celerio
celerio-engine/src/main/java/com/jaxio/celerio/factory/RelationCollisionUtil.java
RelationCollisionUtil.getOneToManyIntermediateNamer
public Namer getOneToManyIntermediateNamer(Namer fromEntityNamer, ColumnConfig pointsOnToEntity, Namer toEntityNamer) { // new configuration Namer result = getOneToManyNamerFromConf(pointsOnToEntity.getOneToManyConfig(), toEntityNamer); // fallback if (result == null) { // NOTE: we use the many to many fallback as it is totally complient with intermediate m2o fallback expectations. result = getManyToManyNamerFallBack(fromEntityNamer, pointsOnToEntity, toEntityNamer); } return result; }
java
public Namer getOneToManyIntermediateNamer(Namer fromEntityNamer, ColumnConfig pointsOnToEntity, Namer toEntityNamer) { // new configuration Namer result = getOneToManyNamerFromConf(pointsOnToEntity.getOneToManyConfig(), toEntityNamer); // fallback if (result == null) { // NOTE: we use the many to many fallback as it is totally complient with intermediate m2o fallback expectations. result = getManyToManyNamerFallBack(fromEntityNamer, pointsOnToEntity, toEntityNamer); } return result; }
[ "public", "Namer", "getOneToManyIntermediateNamer", "(", "Namer", "fromEntityNamer", ",", "ColumnConfig", "pointsOnToEntity", ",", "Namer", "toEntityNamer", ")", "{", "// new configuration", "Namer", "result", "=", "getOneToManyNamerFromConf", "(", "pointsOnToEntity", ".", ...
Compute the appropriate namer for the Java field @ManyToOne (with intermediate table)
[ "Compute", "the", "appropriate", "namer", "for", "the", "Java", "field" ]
train
https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/factory/RelationCollisionUtil.java#L122-L133
Wolfgang-Schuetzelhofer/jcypher
src/main/java/iot/jcypher/util/Util.java
Util.printQueries
public static void printQueries(List<JcQuery> queries, QueryToObserve toObserve, Format format) { boolean titlePrinted = false; ContentToObserve tob = QueriesPrintObserver.contentToObserve(toObserve); if (tob == ContentToObserve.CYPHER || tob == ContentToObserve.CYPHER_JSON) { titlePrinted = true; QueriesPrintObserver.printStream.println("#QUERIES: " + toObserve.getTitle() + " --------------------"); // map to Cypher QueriesPrintObserver.printStream.println("#CYPHER --------------------"); for(int i = 0; i < queries.size(); i++) { String cypher = iot.jcypher.util.Util.toCypher(queries.get(i), format); QueriesPrintObserver.printStream.println("#--------------------"); QueriesPrintObserver.printStream.println(cypher); } QueriesPrintObserver.printStream.println(""); } if (tob == ContentToObserve.JSON || tob == ContentToObserve.CYPHER_JSON) { // map to JSON if (!titlePrinted) QueriesPrintObserver.printStream.println("#QUERIES: " + toObserve.getTitle() + " --------------------"); String json = iot.jcypher.util.Util.toJSON(queries, format); QueriesPrintObserver.printStream.println("#JSON --------------------"); QueriesPrintObserver.printStream.println(json); QueriesPrintObserver.printStream.println(""); } }
java
public static void printQueries(List<JcQuery> queries, QueryToObserve toObserve, Format format) { boolean titlePrinted = false; ContentToObserve tob = QueriesPrintObserver.contentToObserve(toObserve); if (tob == ContentToObserve.CYPHER || tob == ContentToObserve.CYPHER_JSON) { titlePrinted = true; QueriesPrintObserver.printStream.println("#QUERIES: " + toObserve.getTitle() + " --------------------"); // map to Cypher QueriesPrintObserver.printStream.println("#CYPHER --------------------"); for(int i = 0; i < queries.size(); i++) { String cypher = iot.jcypher.util.Util.toCypher(queries.get(i), format); QueriesPrintObserver.printStream.println("#--------------------"); QueriesPrintObserver.printStream.println(cypher); } QueriesPrintObserver.printStream.println(""); } if (tob == ContentToObserve.JSON || tob == ContentToObserve.CYPHER_JSON) { // map to JSON if (!titlePrinted) QueriesPrintObserver.printStream.println("#QUERIES: " + toObserve.getTitle() + " --------------------"); String json = iot.jcypher.util.Util.toJSON(queries, format); QueriesPrintObserver.printStream.println("#JSON --------------------"); QueriesPrintObserver.printStream.println(json); QueriesPrintObserver.printStream.println(""); } }
[ "public", "static", "void", "printQueries", "(", "List", "<", "JcQuery", ">", "queries", ",", "QueryToObserve", "toObserve", ",", "Format", "format", ")", "{", "boolean", "titlePrinted", "=", "false", ";", "ContentToObserve", "tob", "=", "QueriesPrintObserver", ...
map to CYPHER statements and map to JSON, print the mapping results to the output streams configured in QueriesPrintObserver @param queries @param toObserve @param format
[ "map", "to", "CYPHER", "statements", "and", "map", "to", "JSON", "print", "the", "mapping", "results", "to", "the", "output", "streams", "configured", "in", "QueriesPrintObserver" ]
train
https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/util/Util.java#L104-L129
google/closure-templates
java/src/com/google/template/soy/internal/i18n/BidiFormatter.java
BidiFormatter.markAfter
public String markAfter(@Nullable Dir dir, String str, boolean isHtml) { if (dir == null) { dir = estimateDirection(str, isHtml); } // BidiUtils.getExitDir() is called only if needed (short-circuit). if (contextDir == Dir.LTR && (dir == Dir.RTL || BidiUtils.getExitDir(str, isHtml) == Dir.RTL)) { return BidiUtils.Format.LRM_STRING; } if (contextDir == Dir.RTL && (dir == Dir.LTR || BidiUtils.getExitDir(str, isHtml) == Dir.LTR)) { return BidiUtils.Format.RLM_STRING; } return ""; }
java
public String markAfter(@Nullable Dir dir, String str, boolean isHtml) { if (dir == null) { dir = estimateDirection(str, isHtml); } // BidiUtils.getExitDir() is called only if needed (short-circuit). if (contextDir == Dir.LTR && (dir == Dir.RTL || BidiUtils.getExitDir(str, isHtml) == Dir.RTL)) { return BidiUtils.Format.LRM_STRING; } if (contextDir == Dir.RTL && (dir == Dir.LTR || BidiUtils.getExitDir(str, isHtml) == Dir.LTR)) { return BidiUtils.Format.RLM_STRING; } return ""; }
[ "public", "String", "markAfter", "(", "@", "Nullable", "Dir", "dir", ",", "String", "str", ",", "boolean", "isHtml", ")", "{", "if", "(", "dir", "==", "null", ")", "{", "dir", "=", "estimateDirection", "(", "str", ",", "isHtml", ")", ";", "}", "// Bi...
Returns a Unicode bidi mark matching the context directionality (LRM or RLM) if either the overall or the exit directionality of a given string is opposite to the context directionality. Putting this after the string (including its directionality declaration wrapping) prevents it from "sticking" to other opposite-directionality text or a number appearing after it inline with only neutral content in between. Otherwise returns the empty string. While the exit directionality is determined by scanning the end of the string, the overall directionality is given explicitly in {@code dir}. @param str String after which the mark may need to appear @param dir {@code str}'s overall directionality. If null, i.e. unknown, it is estimated. @param isHtml Whether {@code str} is HTML / HTML-escaped @return LRM for RTL text in LTR context; RLM for LTR text in RTL context; else, the empty string.
[ "Returns", "a", "Unicode", "bidi", "mark", "matching", "the", "context", "directionality", "(", "LRM", "or", "RLM", ")", "if", "either", "the", "overall", "or", "the", "exit", "directionality", "of", "a", "given", "string", "is", "opposite", "to", "the", "...
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/i18n/BidiFormatter.java#L223-L235
wnameless/rubycollect4j
src/main/java/net/sf/rubycollect4j/RubyIO.java
RubyIO.foreach
public static void foreach(String path, Consumer<? super String> block) { Ruby.Enumerator.of(new EachLineIterable(new File(path))).each(block); }
java
public static void foreach(String path, Consumer<? super String> block) { Ruby.Enumerator.of(new EachLineIterable(new File(path))).each(block); }
[ "public", "static", "void", "foreach", "(", "String", "path", ",", "Consumer", "<", "?", "super", "String", ">", "block", ")", "{", "Ruby", ".", "Enumerator", ".", "of", "(", "new", "EachLineIterable", "(", "new", "File", "(", "path", ")", ")", ")", ...
Iterates a file line by line. @param path of a File @param block to process each line
[ "Iterates", "a", "file", "line", "by", "line", "." ]
train
https://github.com/wnameless/rubycollect4j/blob/b8b8d8eccaca2254a3d09b91745882fb7a0d5add/src/main/java/net/sf/rubycollect4j/RubyIO.java#L297-L299
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UsersApi.java
UsersApi.supervisorRemoteMediaOperation
public ApiSuccessResponse supervisorRemoteMediaOperation(String dbid, String mediatype, String operationName, SupervisorPlaceData1 supervisorPlaceData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = supervisorRemoteMediaOperationWithHttpInfo(dbid, mediatype, operationName, supervisorPlaceData); return resp.getData(); }
java
public ApiSuccessResponse supervisorRemoteMediaOperation(String dbid, String mediatype, String operationName, SupervisorPlaceData1 supervisorPlaceData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = supervisorRemoteMediaOperationWithHttpInfo(dbid, mediatype, operationName, supervisorPlaceData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "supervisorRemoteMediaOperation", "(", "String", "dbid", ",", "String", "mediatype", ",", "String", "operationName", ",", "SupervisorPlaceData1", "supervisorPlaceData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessRespon...
Change the state of the agent specified by the dbid to operationName. Change the state of the agent specified by the dbid to operationName. @param dbid The dbid of the agent. (required) @param mediatype The media channel. (required) @param operationName Name of state to change to (required) @param supervisorPlaceData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Change", "the", "state", "of", "the", "agent", "specified", "by", "the", "dbid", "to", "operationName", ".", "Change", "the", "state", "of", "the", "agent", "specified", "by", "the", "dbid", "to", "operationName", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UsersApi.java#L305-L308
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/index/service/ClusteringKeySorter.java
ClusteringKeySorter.compareValues
@Override public int compareValues(BytesRef val1, BytesRef val2) { if (val1 == null) { if (val2 == null) { return 0; } return -1; } else if (val2 == null) { return 1; } CellName bb1 = clusteringKeyMapper.clusteringKey(val1); CellName bb2 = clusteringKeyMapper.clusteringKey(val2); CellNameType type = clusteringKeyMapper.getType(); return type.compare(bb1, bb2); }
java
@Override public int compareValues(BytesRef val1, BytesRef val2) { if (val1 == null) { if (val2 == null) { return 0; } return -1; } else if (val2 == null) { return 1; } CellName bb1 = clusteringKeyMapper.clusteringKey(val1); CellName bb2 = clusteringKeyMapper.clusteringKey(val2); CellNameType type = clusteringKeyMapper.getType(); return type.compare(bb1, bb2); }
[ "@", "Override", "public", "int", "compareValues", "(", "BytesRef", "val1", ",", "BytesRef", "val2", ")", "{", "if", "(", "val1", "==", "null", ")", "{", "if", "(", "val2", "==", "null", ")", "{", "return", "0", ";", "}", "return", "-", "1", ";", ...
Compares its two field value arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. @param val1 The first field value to be compared. @param val2 The second field value to be compared. @return A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
[ "Compares", "its", "two", "field", "value", "arguments", "for", "order", ".", "Returns", "a", "negative", "integer", "zero", "or", "a", "positive", "integer", "as", "the", "first", "argument", "is", "less", "than", "equal", "to", "or", "greater", "than", "...
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/ClusteringKeySorter.java#L55-L69
nats-io/java-nats-streaming
src/main/java/io/nats/streaming/Message.java
Message.setData
public void setData(byte[] data, int offset, int length) { if (immutable) { throw new IllegalStateException(ERR_MSG_IMMUTABLE); } this.data = new byte[length]; System.arraycopy(data, offset, this.data, 0, length); }
java
public void setData(byte[] data, int offset, int length) { if (immutable) { throw new IllegalStateException(ERR_MSG_IMMUTABLE); } this.data = new byte[length]; System.arraycopy(data, offset, this.data, 0, length); }
[ "public", "void", "setData", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "length", ")", "{", "if", "(", "immutable", ")", "{", "throw", "new", "IllegalStateException", "(", "ERR_MSG_IMMUTABLE", ")", ";", "}", "this", ".", "data", "...
Sets the message payload data. @param data the payload data @param offset the beginning offset to copy from @param length the length to copy
[ "Sets", "the", "message", "payload", "data", "." ]
train
https://github.com/nats-io/java-nats-streaming/blob/72f964e9093622875d7f1c85ce60820e028863e7/src/main/java/io/nats/streaming/Message.java#L162-L168
mistraltechnologies/smog
src/main/java/com/mistraltech/smog/core/util/PropertyDescriptorLocator.java
PropertyDescriptorLocator.getPropertyDescriptor
public PropertyDescriptor getPropertyDescriptor(String propertyName) { final PropertyDescriptor propertyDescriptor = findPropertyDescriptor(propertyName); if (propertyDescriptor == null) { throw new PropertyNotFoundException(beanClass, propertyName); } return propertyDescriptor; }
java
public PropertyDescriptor getPropertyDescriptor(String propertyName) { final PropertyDescriptor propertyDescriptor = findPropertyDescriptor(propertyName); if (propertyDescriptor == null) { throw new PropertyNotFoundException(beanClass, propertyName); } return propertyDescriptor; }
[ "public", "PropertyDescriptor", "getPropertyDescriptor", "(", "String", "propertyName", ")", "{", "final", "PropertyDescriptor", "propertyDescriptor", "=", "findPropertyDescriptor", "(", "propertyName", ")", ";", "if", "(", "propertyDescriptor", "==", "null", ")", "{", ...
Get the property descriptor for the named property. Throws an exception if the property does not exist. @param propertyName property name @return the PropertyDescriptor for the named property @throws PropertyNotFoundException if the named property does not exist on the bean @see #findPropertyDescriptor(String)
[ "Get", "the", "property", "descriptor", "for", "the", "named", "property", ".", "Throws", "an", "exception", "if", "the", "property", "does", "not", "exist", "." ]
train
https://github.com/mistraltechnologies/smog/blob/bd561520f79476b96467f554daa59e51875ce027/src/main/java/com/mistraltech/smog/core/util/PropertyDescriptorLocator.java#L44-L53
mabe02/lanterna
src/main/java/com/googlecode/lanterna/terminal/ansi/StreamBasedTerminal.java
StreamBasedTerminal.waitForCursorPositionReport
synchronized TerminalPosition waitForCursorPositionReport() throws IOException { long startTime = System.currentTimeMillis(); TerminalPosition cursorPosition = lastReportedCursorPosition; while(cursorPosition == null) { if(System.currentTimeMillis() - startTime > 5000) { //throw new IllegalStateException("Terminal didn't send any position report for 5 seconds, please file a bug with a reproduce!"); return null; } KeyStroke keyStroke = readInput(false, false); if(keyStroke != null) { keyQueue.add(keyStroke); } else { try { Thread.sleep(1); } catch(InterruptedException ignored) {} } cursorPosition = lastReportedCursorPosition; } return cursorPosition; }
java
synchronized TerminalPosition waitForCursorPositionReport() throws IOException { long startTime = System.currentTimeMillis(); TerminalPosition cursorPosition = lastReportedCursorPosition; while(cursorPosition == null) { if(System.currentTimeMillis() - startTime > 5000) { //throw new IllegalStateException("Terminal didn't send any position report for 5 seconds, please file a bug with a reproduce!"); return null; } KeyStroke keyStroke = readInput(false, false); if(keyStroke != null) { keyQueue.add(keyStroke); } else { try { Thread.sleep(1); } catch(InterruptedException ignored) {} } cursorPosition = lastReportedCursorPosition; } return cursorPosition; }
[ "synchronized", "TerminalPosition", "waitForCursorPositionReport", "(", ")", "throws", "IOException", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "TerminalPosition", "cursorPosition", "=", "lastReportedCursorPosition", ";", "while", ...
Waits for up to 5 seconds for a terminal cursor position report to appear in the input stream. If the timeout expires, it will return null. You should have sent the cursor position query already before calling this method. @return Current position of the cursor, or null if the terminal didn't report it in time. @throws IOException If there was an I/O error
[ "Waits", "for", "up", "to", "5", "seconds", "for", "a", "terminal", "cursor", "position", "report", "to", "appear", "in", "the", "input", "stream", ".", "If", "the", "timeout", "expires", "it", "will", "return", "null", ".", "You", "should", "have", "sen...
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/terminal/ansi/StreamBasedTerminal.java#L167-L185
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/BinaryLogRecordSerializerImpl.java
BinaryLogRecordSerializerImpl.writeString
private static void writeString(String str, DataOutput writer) throws IOException { if (str == null) { writer.writeInt(0); } else { int blocks = str.length() >> 15; writer.writeInt(blocks+1); int end = 0; for (int i=0; i<blocks; i++) { int start = end; end = (i+1)<<15; writer.writeUTF(str.substring(start, end)); } writer.writeUTF(str.substring(end)); } }
java
private static void writeString(String str, DataOutput writer) throws IOException { if (str == null) { writer.writeInt(0); } else { int blocks = str.length() >> 15; writer.writeInt(blocks+1); int end = 0; for (int i=0; i<blocks; i++) { int start = end; end = (i+1)<<15; writer.writeUTF(str.substring(start, end)); } writer.writeUTF(str.substring(end)); } }
[ "private", "static", "void", "writeString", "(", "String", "str", ",", "DataOutput", "writer", ")", "throws", "IOException", "{", "if", "(", "str", "==", "null", ")", "{", "writer", ".", "writeInt", "(", "0", ")", ";", "}", "else", "{", "int", "blocks"...
/* Serialize string. Need to take care of <code>null</code> value since {@link DataOutput#writeUTF(String)} does not handle it.
[ "/", "*", "Serialize", "string", ".", "Need", "to", "take", "care", "of", "<code", ">", "null<", "/", "code", ">", "value", "since", "{" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/BinaryLogRecordSerializerImpl.java#L599-L613
shrinkwrap/shrinkwrap
impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarHeader.java
TarHeader.getFileNameBytes
public static int getFileNameBytes(String newName, byte[] outbuf) throws InvalidHeaderException { if (newName.length() > 100) { // Locate a pathname "break" prior to the maximum name length... int index = newName.indexOf("/", newName.length() - 100); if (index == -1) { throw new InvalidHeaderException("file name is greater than 100 characters, " + newName); } // Get the "suffix subpath" of the name. String name = newName.substring(index + 1); // Get the "prefix subpath", or "prefix", of the name. String prefix = newName.substring(0, index); if (prefix.length() > TarHeader.PREFIXLEN) { throw new InvalidHeaderException("file prefix is greater than 155 characters"); } TarHeader.getNameBytes(new StringBuffer(name), outbuf, TarHeader.NAMEOFFSET, TarHeader.NAMELEN); TarHeader.getNameBytes(new StringBuffer(prefix), outbuf, TarHeader.PREFIXOFFSET, TarHeader.PREFIXLEN); } else { TarHeader.getNameBytes(new StringBuffer(newName), outbuf, TarHeader.NAMEOFFSET, TarHeader.NAMELEN); } // The offset, regardless of the format, is now the end of the // original name field. // return TarHeader.NAMELEN; }
java
public static int getFileNameBytes(String newName, byte[] outbuf) throws InvalidHeaderException { if (newName.length() > 100) { // Locate a pathname "break" prior to the maximum name length... int index = newName.indexOf("/", newName.length() - 100); if (index == -1) { throw new InvalidHeaderException("file name is greater than 100 characters, " + newName); } // Get the "suffix subpath" of the name. String name = newName.substring(index + 1); // Get the "prefix subpath", or "prefix", of the name. String prefix = newName.substring(0, index); if (prefix.length() > TarHeader.PREFIXLEN) { throw new InvalidHeaderException("file prefix is greater than 155 characters"); } TarHeader.getNameBytes(new StringBuffer(name), outbuf, TarHeader.NAMEOFFSET, TarHeader.NAMELEN); TarHeader.getNameBytes(new StringBuffer(prefix), outbuf, TarHeader.PREFIXOFFSET, TarHeader.PREFIXLEN); } else { TarHeader.getNameBytes(new StringBuffer(newName), outbuf, TarHeader.NAMEOFFSET, TarHeader.NAMELEN); } // The offset, regardless of the format, is now the end of the // original name field. // return TarHeader.NAMELEN; }
[ "public", "static", "int", "getFileNameBytes", "(", "String", "newName", ",", "byte", "[", "]", "outbuf", ")", "throws", "InvalidHeaderException", "{", "if", "(", "newName", ".", "length", "(", ")", ">", "100", ")", "{", "// Locate a pathname \"break\" prior to ...
This method, like getNameBytes(), is intended to place a name into a TarHeader's buffer. However, this method is sophisticated enough to recognize long names (name.length() > NAMELEN). In these cases, the method will break the name into a prefix and suffix and place the name in the header in 'ustar' format. It is up to the TarEntry to manage the "entry header format". This method assumes the name is valid for the type of archive being generated. @param outbuf The buffer containing the entry header to modify. @param newName The new name to place into the header buffer. @return The current offset in the tar header (always TarHeader.NAMELEN). @throws InvalidHeaderException If the name will not fit in the header.
[ "This", "method", "like", "getNameBytes", "()", "is", "intended", "to", "place", "a", "name", "into", "a", "TarHeader", "s", "buffer", ".", "However", "this", "method", "is", "sophisticated", "enough", "to", "recognize", "long", "names", "(", "name", ".", ...
train
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarHeader.java#L359-L387
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaJobTracker.java
CoronaJobTracker.processBadResource
public void processBadResource(int grant, boolean abandonHost) { synchronized (lockObject) { Set<String> excludedHosts = null; TaskInProgress tip = requestToTipMap.get(grant); if (!job.canLaunchJobCleanupTask() && (!tip.isRunnable() || (tip.isRunning() && !(speculatedMaps.contains(tip) || speculatedReduces.contains(tip))))) { // The task is not runnable anymore. Job is done/killed/failed or the // task has finished and this is a speculative resource // Or the task is running and this is a speculative resource // but the speculation is no longer needed resourceTracker.releaseResource(grant); return; } if (abandonHost) { ResourceGrant resource = resourceTracker.getGrant(grant); String hostToExlcude = resource.getAddress().getHost(); taskToContextMap.get(tip).excludedHosts.add(hostToExlcude); excludedHosts = taskToContextMap.get(tip).excludedHosts; } ResourceRequest newReq = resourceTracker.releaseAndRequestResource(grant, excludedHosts); requestToTipMap.put(newReq.getId(), tip); TaskContext context = taskToContextMap.get(tip); if (context == null) { context = new TaskContext(newReq); } else { context.resourceRequests.add(newReq); } taskToContextMap.put(tip, context); } }
java
public void processBadResource(int grant, boolean abandonHost) { synchronized (lockObject) { Set<String> excludedHosts = null; TaskInProgress tip = requestToTipMap.get(grant); if (!job.canLaunchJobCleanupTask() && (!tip.isRunnable() || (tip.isRunning() && !(speculatedMaps.contains(tip) || speculatedReduces.contains(tip))))) { // The task is not runnable anymore. Job is done/killed/failed or the // task has finished and this is a speculative resource // Or the task is running and this is a speculative resource // but the speculation is no longer needed resourceTracker.releaseResource(grant); return; } if (abandonHost) { ResourceGrant resource = resourceTracker.getGrant(grant); String hostToExlcude = resource.getAddress().getHost(); taskToContextMap.get(tip).excludedHosts.add(hostToExlcude); excludedHosts = taskToContextMap.get(tip).excludedHosts; } ResourceRequest newReq = resourceTracker.releaseAndRequestResource(grant, excludedHosts); requestToTipMap.put(newReq.getId(), tip); TaskContext context = taskToContextMap.get(tip); if (context == null) { context = new TaskContext(newReq); } else { context.resourceRequests.add(newReq); } taskToContextMap.put(tip, context); } }
[ "public", "void", "processBadResource", "(", "int", "grant", ",", "boolean", "abandonHost", ")", "{", "synchronized", "(", "lockObject", ")", "{", "Set", "<", "String", ">", "excludedHosts", "=", "null", ";", "TaskInProgress", "tip", "=", "requestToTipMap", "....
Return this grant and request a different one. This can happen because the task has failed, was killed or the job tracker decided that the resource is bad @param grant The grant identifier. @param abandonHost - if true then this host will be excluded from the list of possibilities for this request
[ "Return", "this", "grant", "and", "request", "a", "different", "one", ".", "This", "can", "happen", "because", "the", "task", "has", "failed", "was", "killed", "or", "the", "job", "tracker", "decided", "that", "the", "resource", "is", "bad" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaJobTracker.java#L1599-L1632
Netflix/astyanax
astyanax-queue/src/main/java/com/netflix/astyanax/recipes/queue/ShardedDistributedMessageQueue.java
ShardedDistributedMessageQueue.getShardKey
private String getShardKey(long messageTime, int modShard) { long timePartition; if (metadata.getPartitionDuration() != null) timePartition = (messageTime / metadata.getPartitionDuration()) % metadata.getPartitionCount(); else timePartition = 0; return getName() + ":" + timePartition + ":" + modShard; }
java
private String getShardKey(long messageTime, int modShard) { long timePartition; if (metadata.getPartitionDuration() != null) timePartition = (messageTime / metadata.getPartitionDuration()) % metadata.getPartitionCount(); else timePartition = 0; return getName() + ":" + timePartition + ":" + modShard; }
[ "private", "String", "getShardKey", "(", "long", "messageTime", ",", "int", "modShard", ")", "{", "long", "timePartition", ";", "if", "(", "metadata", ".", "getPartitionDuration", "(", ")", "!=", "null", ")", "timePartition", "=", "(", "messageTime", "/", "m...
Return the shard for this timestamp @param messageTime @param modShard @return
[ "Return", "the", "shard", "for", "this", "timestamp" ]
train
https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-queue/src/main/java/com/netflix/astyanax/recipes/queue/ShardedDistributedMessageQueue.java#L430-L437
Bandwidth/java-bandwidth
src/main/java/com/bandwidth/sdk/model/Call.java
Call.get
public static Call get(final BandwidthClient client, final String callId) throws Exception { final String callsUri = client.getUserResourceInstanceUri(BandwidthConstants.CALLS_URI_PATH, callId); final JSONObject jsonObject = toJSONObject(client.get(callsUri, null)); return new Call(client, jsonObject); }
java
public static Call get(final BandwidthClient client, final String callId) throws Exception { final String callsUri = client.getUserResourceInstanceUri(BandwidthConstants.CALLS_URI_PATH, callId); final JSONObject jsonObject = toJSONObject(client.get(callsUri, null)); return new Call(client, jsonObject); }
[ "public", "static", "Call", "get", "(", "final", "BandwidthClient", "client", ",", "final", "String", "callId", ")", "throws", "Exception", "{", "final", "String", "callsUri", "=", "client", ".", "getUserResourceInstanceUri", "(", "BandwidthConstants", ".", "CALLS...
Convenience factory method for Call, returns a Call object given an id @param client the client @param callId the call id @return the call @throws Exception error.
[ "Convenience", "factory", "method", "for", "Call", "returns", "a", "Call", "object", "given", "an", "id" ]
train
https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Call.java#L44-L51
Netflix/conductor
grpc-client/src/main/java/com/netflix/conductor/client/grpc/WorkflowClient.java
WorkflowClient.terminateWorkflow
public void terminateWorkflow(String workflowId, String reason) { Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.terminateWorkflow(WorkflowServicePb.TerminateWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .setReason(reason) .build() ); }
java
public void terminateWorkflow(String workflowId, String reason) { Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.terminateWorkflow(WorkflowServicePb.TerminateWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .setReason(reason) .build() ); }
[ "public", "void", "terminateWorkflow", "(", "String", "workflowId", ",", "String", "reason", ")", "{", "Preconditions", ".", "checkArgument", "(", "StringUtils", ".", "isNotBlank", "(", "workflowId", ")", ",", "\"workflow id cannot be blank\"", ")", ";", "stub", "...
Terminates the execution of the given workflow instance @param workflowId the id of the workflow to be terminated @param reason the reason to be logged and displayed
[ "Terminates", "the", "execution", "of", "the", "given", "workflow", "instance" ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/grpc-client/src/main/java/com/netflix/conductor/client/grpc/WorkflowClient.java#L267-L274
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java
PageFlowUtils.removeSharedFlow
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request, ServletContext servletContext ) { StorageHandler sh = Handlers.get( servletContext ).getStorageHandler(); HttpServletRequest unwrappedRequest = unwrapMultipart( request ); RequestContext rc = new RequestContext( unwrappedRequest, null ); String attrName = ScopedServletUtils.getScopedSessionAttrName(InternalConstants.SHARED_FLOW_ATTR_PREFIX + sharedFlowClassName, request); sh.removeAttribute(rc, attrName); }
java
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request, ServletContext servletContext ) { StorageHandler sh = Handlers.get( servletContext ).getStorageHandler(); HttpServletRequest unwrappedRequest = unwrapMultipart( request ); RequestContext rc = new RequestContext( unwrappedRequest, null ); String attrName = ScopedServletUtils.getScopedSessionAttrName(InternalConstants.SHARED_FLOW_ATTR_PREFIX + sharedFlowClassName, request); sh.removeAttribute(rc, attrName); }
[ "public", "static", "void", "removeSharedFlow", "(", "String", "sharedFlowClassName", ",", "HttpServletRequest", "request", ",", "ServletContext", "servletContext", ")", "{", "StorageHandler", "sh", "=", "Handlers", ".", "get", "(", "servletContext", ")", ".", "getS...
Destroy the current {@link SharedFlowController} of the given class name. @param sharedFlowClassName the class name of the current SharedFlowController to destroy. @param request the current HttpServletRequest.
[ "Destroy", "the", "current", "{" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java#L406-L415
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java
TopologyBuilder.setBolt
public BoltDeclarer setBolt(String id, IControlBolt bolt, Number parallelism_hint) { return setBolt(id, new ControlBoltExecutor(bolt), parallelism_hint); }
java
public BoltDeclarer setBolt(String id, IControlBolt bolt, Number parallelism_hint) { return setBolt(id, new ControlBoltExecutor(bolt), parallelism_hint); }
[ "public", "BoltDeclarer", "setBolt", "(", "String", "id", ",", "IControlBolt", "bolt", ",", "Number", "parallelism_hint", ")", "{", "return", "setBolt", "(", "id", ",", "new", "ControlBoltExecutor", "(", "bolt", ")", ",", "parallelism_hint", ")", ";", "}" ]
Define a new bolt in this topology. This defines a control bolt, which is a simpler to use but more restricted kind of bolt. Control bolts are intended for making sending control message more simply @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the control bolt @param parallelism_hint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster. @return use the returned object to declare the inputs to this component
[ "Define", "a", "new", "bolt", "in", "this", "topology", ".", "This", "defines", "a", "control", "bolt", "which", "is", "a", "simpler", "to", "use", "but", "more", "restricted", "kind", "of", "bolt", ".", "Control", "bolts", "are", "intended", "for", "mak...
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/topology/TopologyBuilder.java#L350-L352
banq/jdonframework
src/main/java/com/jdon/util/UtilDateTime.java
UtilDateTime.toSqlDate
public static java.sql.Date toSqlDate(String monthStr, String dayStr, String yearStr) { java.util.Date newDate = toDate(monthStr, dayStr, yearStr, "0", "0", "0"); if (newDate != null) return new java.sql.Date(newDate.getTime()); else return null; }
java
public static java.sql.Date toSqlDate(String monthStr, String dayStr, String yearStr) { java.util.Date newDate = toDate(monthStr, dayStr, yearStr, "0", "0", "0"); if (newDate != null) return new java.sql.Date(newDate.getTime()); else return null; }
[ "public", "static", "java", ".", "sql", ".", "Date", "toSqlDate", "(", "String", "monthStr", ",", "String", "dayStr", ",", "String", "yearStr", ")", "{", "java", ".", "util", ".", "Date", "newDate", "=", "toDate", "(", "monthStr", ",", "dayStr", ",", "...
Makes a java.sql.Date from separate Strings for month, day, year @param monthStr The month String @param dayStr The day String @param yearStr The year String @return A java.sql.Date made from separate Strings for month, day, year
[ "Makes", "a", "java", ".", "sql", ".", "Date", "from", "separate", "Strings", "for", "month", "day", "year" ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/UtilDateTime.java#L117-L124
Azure/azure-sdk-for-java
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/FirewallRulesInner.java
FirewallRulesInner.listByRedisResourceWithServiceResponseAsync
public Observable<ServiceResponse<Page<RedisFirewallRuleInner>>> listByRedisResourceWithServiceResponseAsync(final String resourceGroupName, final String cacheName) { return listByRedisResourceSinglePageAsync(resourceGroupName, cacheName) .concatMap(new Func1<ServiceResponse<Page<RedisFirewallRuleInner>>, Observable<ServiceResponse<Page<RedisFirewallRuleInner>>>>() { @Override public Observable<ServiceResponse<Page<RedisFirewallRuleInner>>> call(ServiceResponse<Page<RedisFirewallRuleInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByRedisResourceNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<RedisFirewallRuleInner>>> listByRedisResourceWithServiceResponseAsync(final String resourceGroupName, final String cacheName) { return listByRedisResourceSinglePageAsync(resourceGroupName, cacheName) .concatMap(new Func1<ServiceResponse<Page<RedisFirewallRuleInner>>, Observable<ServiceResponse<Page<RedisFirewallRuleInner>>>>() { @Override public Observable<ServiceResponse<Page<RedisFirewallRuleInner>>> call(ServiceResponse<Page<RedisFirewallRuleInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByRedisResourceNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RedisFirewallRuleInner", ">", ">", ">", "listByRedisResourceWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "cacheName", ")", "{", "return", "listByRedisRe...
Gets all firewall rules in the specified redis cache. @param resourceGroupName The name of the resource group. @param cacheName The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RedisFirewallRuleInner&gt; object
[ "Gets", "all", "firewall", "rules", "in", "the", "specified", "redis", "cache", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/FirewallRulesInner.java#L154-L166
isisaddons-legacy/isis-module-security
dom/src/main/java/org/isisaddons/module/security/dom/permission/ApplicationPermissionRepository.java
ApplicationPermissionRepository.findByUserAndPermissionValue
@Programmatic public ApplicationPermission findByUserAndPermissionValue(final String username, final ApplicationPermissionValue permissionValue) { // obtain all permissions for this user, map by its value, and // put into query cache (so that this method can be safely called in a tight loop) final Map<ApplicationPermissionValue, List<ApplicationPermission>> permissions = queryResultsCache.execute(new Callable<Map<ApplicationPermissionValue, List<ApplicationPermission>>>() { @Override public Map<ApplicationPermissionValue, List<ApplicationPermission>> call() throws Exception { final List<ApplicationPermission> applicationPermissions = findByUser(username); final ImmutableListMultimap<ApplicationPermissionValue, ApplicationPermission> index = Multimaps .index(applicationPermissions, ApplicationPermission.Functions.AS_VALUE); return Multimaps.asMap(index); } // note: it is correct that only username (and not permissionValue) is the key // (we are obtaining all the perms for this user) }, ApplicationPermissionRepository.class, "findByUserAndPermissionValue", username); // now simply return the permission from the required value (if it exists) final List<ApplicationPermission> applicationPermissions = permissions.get(permissionValue); return applicationPermissions != null && !applicationPermissions.isEmpty() ? applicationPermissions.get(0) : null; }
java
@Programmatic public ApplicationPermission findByUserAndPermissionValue(final String username, final ApplicationPermissionValue permissionValue) { // obtain all permissions for this user, map by its value, and // put into query cache (so that this method can be safely called in a tight loop) final Map<ApplicationPermissionValue, List<ApplicationPermission>> permissions = queryResultsCache.execute(new Callable<Map<ApplicationPermissionValue, List<ApplicationPermission>>>() { @Override public Map<ApplicationPermissionValue, List<ApplicationPermission>> call() throws Exception { final List<ApplicationPermission> applicationPermissions = findByUser(username); final ImmutableListMultimap<ApplicationPermissionValue, ApplicationPermission> index = Multimaps .index(applicationPermissions, ApplicationPermission.Functions.AS_VALUE); return Multimaps.asMap(index); } // note: it is correct that only username (and not permissionValue) is the key // (we are obtaining all the perms for this user) }, ApplicationPermissionRepository.class, "findByUserAndPermissionValue", username); // now simply return the permission from the required value (if it exists) final List<ApplicationPermission> applicationPermissions = permissions.get(permissionValue); return applicationPermissions != null && !applicationPermissions.isEmpty() ? applicationPermissions.get(0) : null; }
[ "@", "Programmatic", "public", "ApplicationPermission", "findByUserAndPermissionValue", "(", "final", "String", "username", ",", "final", "ApplicationPermissionValue", "permissionValue", ")", "{", "// obtain all permissions for this user, map by its value, and", "// put into query ca...
Uses the {@link QueryResultsCache} in order to support multiple lookups from <code>org.isisaddons.module.security.app.user.UserPermissionViewModel</code>.
[ "Uses", "the", "{" ]
train
https://github.com/isisaddons-legacy/isis-module-security/blob/a9deb1b003ba01e44c859085bd078be8df0c1863/dom/src/main/java/org/isisaddons/module/security/dom/permission/ApplicationPermissionRepository.java#L103-L130
google/closure-compiler
src/com/google/javascript/jscomp/JSError.java
JSError.make
public static JSError make(DiagnosticType type, String... arguments) { return new JSError(null, null, -1, -1, type, null, arguments); }
java
public static JSError make(DiagnosticType type, String... arguments) { return new JSError(null, null, -1, -1, type, null, arguments); }
[ "public", "static", "JSError", "make", "(", "DiagnosticType", "type", ",", "String", "...", "arguments", ")", "{", "return", "new", "JSError", "(", "null", ",", "null", ",", "-", "1", ",", "-", "1", ",", "type", ",", "null", ",", "arguments", ")", ";...
Creates a JSError with no source information @param type The DiagnosticType @param arguments Arguments to be incorporated into the message
[ "Creates", "a", "JSError", "with", "no", "source", "information" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JSError.java#L68-L70
primefaces-extensions/core
src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java
SheetRenderer.encodeData
protected void encodeData(final FacesContext context, final Sheet sheet, final WidgetBuilder wb) throws IOException { final JavascriptVarBuilder jsData = new JavascriptVarBuilder(null, false); final JavascriptVarBuilder jsRowKeys = new JavascriptVarBuilder(null, false); final JavascriptVarBuilder jsStyle = new JavascriptVarBuilder(null, true); final JavascriptVarBuilder jsRowStyle = new JavascriptVarBuilder(null, false); final JavascriptVarBuilder jsReadOnly = new JavascriptVarBuilder(null, true); final JavascriptVarBuilder jsRowHeaders = new JavascriptVarBuilder(null, false); final boolean isCustomHeader = sheet.getRowHeaderValueExpression() != null; final List<Object> values = sheet.getSortedValues(); int row = 0; for (final Object value : values) { context.getExternalContext().getRequestMap().put(sheet.getVar(), value); final String rowKey = sheet.getRowKeyValueAsString(context); jsRowKeys.appendArrayValue(rowKey, true); encodeRow(context, rowKey, jsData, jsRowStyle, jsStyle, jsReadOnly, sheet, row); // In case of custom row header evaluate the value expression for every row to // set the header if (sheet.isShowRowHeaders() && isCustomHeader) { final String rowHeader = sheet.getRowHeaderValueAsString(context); jsRowHeaders.appendArrayValue(rowHeader, true); } row++; } sheet.setRowVar(context, null); wb.nativeAttr("data", jsData.closeVar().toString()); wb.nativeAttr("styles", jsStyle.closeVar().toString()); wb.nativeAttr("rowStyles", jsRowStyle.closeVar().toString()); wb.nativeAttr("readOnlyCells", jsReadOnly.closeVar().toString()); wb.nativeAttr("rowKeys", jsRowKeys.closeVar().toString()); // add the row header as a native attribute if (!isCustomHeader) { wb.nativeAttr("rowHeaders", sheet.isShowRowHeaders().toString()); } else { wb.nativeAttr("rowHeaders", jsRowHeaders.closeVar().toString()); } }
java
protected void encodeData(final FacesContext context, final Sheet sheet, final WidgetBuilder wb) throws IOException { final JavascriptVarBuilder jsData = new JavascriptVarBuilder(null, false); final JavascriptVarBuilder jsRowKeys = new JavascriptVarBuilder(null, false); final JavascriptVarBuilder jsStyle = new JavascriptVarBuilder(null, true); final JavascriptVarBuilder jsRowStyle = new JavascriptVarBuilder(null, false); final JavascriptVarBuilder jsReadOnly = new JavascriptVarBuilder(null, true); final JavascriptVarBuilder jsRowHeaders = new JavascriptVarBuilder(null, false); final boolean isCustomHeader = sheet.getRowHeaderValueExpression() != null; final List<Object> values = sheet.getSortedValues(); int row = 0; for (final Object value : values) { context.getExternalContext().getRequestMap().put(sheet.getVar(), value); final String rowKey = sheet.getRowKeyValueAsString(context); jsRowKeys.appendArrayValue(rowKey, true); encodeRow(context, rowKey, jsData, jsRowStyle, jsStyle, jsReadOnly, sheet, row); // In case of custom row header evaluate the value expression for every row to // set the header if (sheet.isShowRowHeaders() && isCustomHeader) { final String rowHeader = sheet.getRowHeaderValueAsString(context); jsRowHeaders.appendArrayValue(rowHeader, true); } row++; } sheet.setRowVar(context, null); wb.nativeAttr("data", jsData.closeVar().toString()); wb.nativeAttr("styles", jsStyle.closeVar().toString()); wb.nativeAttr("rowStyles", jsRowStyle.closeVar().toString()); wb.nativeAttr("readOnlyCells", jsReadOnly.closeVar().toString()); wb.nativeAttr("rowKeys", jsRowKeys.closeVar().toString()); // add the row header as a native attribute if (!isCustomHeader) { wb.nativeAttr("rowHeaders", sheet.isShowRowHeaders().toString()); } else { wb.nativeAttr("rowHeaders", jsRowHeaders.closeVar().toString()); } }
[ "protected", "void", "encodeData", "(", "final", "FacesContext", "context", ",", "final", "Sheet", "sheet", ",", "final", "WidgetBuilder", "wb", ")", "throws", "IOException", "{", "final", "JavascriptVarBuilder", "jsData", "=", "new", "JavascriptVarBuilder", "(", ...
Encode the row data. Builds row data, style data and read only object. @param context @param sheet @param wb @throws IOException
[ "Encode", "the", "row", "data", ".", "Builds", "row", "data", "style", "data", "and", "read", "only", "object", "." ]
train
https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java#L426-L470
xvik/dropwizard-guicey
src/main/java/ru/vyarus/dropwizard/guice/module/installer/util/JerseyBinding.java
JerseyBinding.bindSpecificComponent
public static void bindSpecificComponent(final AbstractBinder binder, final Injector injector, final Class<?> type, final Class<?> specificType, final boolean hkManaged, final boolean singleton) { // resolve generics of specific type final GenericsContext context = GenericsResolver.resolve(type).type(specificType); final List<Type> genericTypes = context.genericTypes(); final Type[] generics = genericTypes.toArray(new Type[0]); final Type bindingType = generics.length > 0 ? new ParameterizedTypeImpl(specificType, generics) : specificType; if (hkManaged) { optionalSingleton( binder.bind(type).to(type).to(bindingType), singleton); } else { optionalSingleton( binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type).to(bindingType), singleton); } }
java
public static void bindSpecificComponent(final AbstractBinder binder, final Injector injector, final Class<?> type, final Class<?> specificType, final boolean hkManaged, final boolean singleton) { // resolve generics of specific type final GenericsContext context = GenericsResolver.resolve(type).type(specificType); final List<Type> genericTypes = context.genericTypes(); final Type[] generics = genericTypes.toArray(new Type[0]); final Type bindingType = generics.length > 0 ? new ParameterizedTypeImpl(specificType, generics) : specificType; if (hkManaged) { optionalSingleton( binder.bind(type).to(type).to(bindingType), singleton); } else { optionalSingleton( binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type).to(bindingType), singleton); } }
[ "public", "static", "void", "bindSpecificComponent", "(", "final", "AbstractBinder", "binder", ",", "final", "Injector", "injector", ",", "final", "Class", "<", "?", ">", "type", ",", "final", "Class", "<", "?", ">", "specificType", ",", "final", "boolean", ...
Binds jersey specific component (component implements jersey interface or extends class). Specific binding is required for types directly supported by jersey (e.g. ExceptionMapper). Such types must be bound to target interface directly, otherwise jersey would not be able to resolve them. <p> If type is {@link HK2Managed}, binds directly. Otherwise, use guice "bridge" factory to lazily bind type.</p> @param binder HK2 binder @param injector guice injector @param type type which implements specific jersey interface or extends class @param specificType specific jersey type (interface or abstract class) @param hkManaged true if bean must be managed by HK2, false to bind guice managed instance @param singleton true to force singleton scope
[ "Binds", "jersey", "specific", "component", "(", "component", "implements", "jersey", "interface", "or", "extends", "class", ")", ".", "Specific", "binding", "is", "required", "for", "types", "directly", "supported", "by", "jersey", "(", "e", ".", "g", ".", ...
train
https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/module/installer/util/JerseyBinding.java#L142-L163
fcrepo4/fcrepo4
fcrepo-http-api/src/main/java/org/fcrepo/http/api/ExternalContentHandler.java
ExternalContentHandler.fetchExternalContent
public InputStream fetchExternalContent() { final URI uri = link.getUri(); final String scheme = uri.getScheme(); LOGGER.debug("scheme is {}", scheme); if (scheme != null) { try { if (scheme.equals("file")) { return new FileInputStream(uri.getPath()); } else if (scheme.equals("http") || scheme.equals("https")) { return uri.toURL().openStream(); } } catch (final IOException e) { throw new ExternalContentAccessException("Failed to read external content from " + uri, e); } } return null; }
java
public InputStream fetchExternalContent() { final URI uri = link.getUri(); final String scheme = uri.getScheme(); LOGGER.debug("scheme is {}", scheme); if (scheme != null) { try { if (scheme.equals("file")) { return new FileInputStream(uri.getPath()); } else if (scheme.equals("http") || scheme.equals("https")) { return uri.toURL().openStream(); } } catch (final IOException e) { throw new ExternalContentAccessException("Failed to read external content from " + uri, e); } } return null; }
[ "public", "InputStream", "fetchExternalContent", "(", ")", "{", "final", "URI", "uri", "=", "link", ".", "getUri", "(", ")", ";", "final", "String", "scheme", "=", "uri", ".", "getScheme", "(", ")", ";", "LOGGER", ".", "debug", "(", "\"scheme is {}\"", "...
Fetch the external content @return InputStream containing the external content
[ "Fetch", "the", "external", "content" ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-api/src/main/java/org/fcrepo/http/api/ExternalContentHandler.java#L140-L157
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Messages.java
Messages.getBundle
public static <T> T getBundle(Class<T> type) { return getBundle(type, Locale.getDefault()); }
java
public static <T> T getBundle(Class<T> type) { return getBundle(type, Locale.getDefault()); }
[ "public", "static", "<", "T", ">", "T", "getBundle", "(", "Class", "<", "T", ">", "type", ")", "{", "return", "getBundle", "(", "type", ",", "Locale", ".", "getDefault", "(", ")", ")", ";", "}" ]
Get a message bundle of the given type. Equivalent to <code>{@link #getBundle(Class, java.util.Locale) getBundle}(type, Locale.getDefault())</code>. @param type the bundle type class @param <T> the bundle type @return the bundle
[ "Get", "a", "message", "bundle", "of", "the", "given", "type", ".", "Equivalent", "to", "<code", ">", "{", "@link", "#getBundle", "(", "Class", "java", ".", "util", ".", "Locale", ")", "getBundle", "}", "(", "type", "Locale", ".", "getDefault", "()", "...
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Messages.java#L45-L47
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/jaxbref/JAXBResourceFactory.java
JAXBResourceFactory.get
public <T> T get(Class<T> clazz, final String name) { JAXBNamedResourceFactory<T> cached = cachedReferences.get(name); if (cached == null) { cached = new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz); cachedReferences.put(name, cached); } return cached.get(); }
java
public <T> T get(Class<T> clazz, final String name) { JAXBNamedResourceFactory<T> cached = cachedReferences.get(name); if (cached == null) { cached = new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz); cachedReferences.put(name, cached); } return cached.get(); }
[ "public", "<", "T", ">", "T", "get", "(", "Class", "<", "T", ">", "clazz", ",", "final", "String", "name", ")", "{", "JAXBNamedResourceFactory", "<", "T", ">", "cached", "=", "cachedReferences", ".", "get", "(", "name", ")", ";", "if", "(", "cached",...
Resolve the JAXB resource, permitting caching behind the scenes @param clazz the jaxb resource to read @param name the name of the property @param <T> @return
[ "Resolve", "the", "JAXB", "resource", "permitting", "caching", "behind", "the", "scenes" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/jaxbref/JAXBResourceFactory.java#L39-L50
thelinmichael/spotify-web-api-java
src/main/java/com/wrapper/spotify/SpotifyApi.java
SpotifyApi.changePlaylistsDetails
@Deprecated public ChangePlaylistsDetailsRequest.Builder changePlaylistsDetails(String user_id, String playlist_id) { return new ChangePlaylistsDetailsRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .user_id(user_id) .playlist_id(playlist_id); }
java
@Deprecated public ChangePlaylistsDetailsRequest.Builder changePlaylistsDetails(String user_id, String playlist_id) { return new ChangePlaylistsDetailsRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port) .user_id(user_id) .playlist_id(playlist_id); }
[ "@", "Deprecated", "public", "ChangePlaylistsDetailsRequest", ".", "Builder", "changePlaylistsDetails", "(", "String", "user_id", ",", "String", "playlist_id", ")", "{", "return", "new", "ChangePlaylistsDetailsRequest", ".", "Builder", "(", "accessToken", ")", ".", "s...
Update a playlists properties. @deprecated Playlist IDs are unique for themselves. This parameter is thus no longer used. (https://developer.spotify.com/community/news/2018/06/12/changes-to-playlist-uris/) @param user_id The owners username. @param playlist_id The playlists ID. @return A {@link ChangePlaylistsDetailsRequest.Builder}. @see <a href="https://developer.spotify.com/web-api/user-guide/#spotify-uris-and-ids">Spotify: URLs &amp; IDs</a>
[ "Update", "a", "playlists", "properties", "." ]
train
https://github.com/thelinmichael/spotify-web-api-java/blob/c06b8512344c0310d0c1df362fa267879021da2e/src/main/java/com/wrapper/spotify/SpotifyApi.java#L1129-L1135
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/LineString.java
LineString.fromLngLats
public static LineString fromLngLats(@NonNull List<Point> points, @Nullable BoundingBox bbox) { return new LineString(TYPE, bbox, points); }
java
public static LineString fromLngLats(@NonNull List<Point> points, @Nullable BoundingBox bbox) { return new LineString(TYPE, bbox, points); }
[ "public", "static", "LineString", "fromLngLats", "(", "@", "NonNull", "List", "<", "Point", ">", "points", ",", "@", "Nullable", "BoundingBox", "bbox", ")", "{", "return", "new", "LineString", "(", "TYPE", ",", "bbox", ",", "points", ")", ";", "}" ]
Create a new instance of this class by defining a list of {@link Point}s which follow the correct specifications described in the Point documentation. Note that there should not be any duplicate points inside the list and the points combined should create a LineString with a distance greater than 0. <p> Note that if less than 2 points are passed in, a runtime exception will occur. </p> @param points a list of {@link Point}s which make up the LineString geometry @param bbox optionally include a bbox definition as a double array @return a new instance of this class defined by the values passed inside this static factory method @since 3.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "by", "defining", "a", "list", "of", "{", "@link", "Point", "}", "s", "which", "follow", "the", "correct", "specifications", "described", "in", "the", "Point", "documentation", ".", "Note", "that", "...
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/LineString.java#L127-L129
graknlabs/grakn
server/src/server/kb/structure/AbstractElement.java
AbstractElement.propertyImmutable
public <X> void propertyImmutable(P property, X newValue, @Nullable X foundValue, Function<X, Object> converter) { Objects.requireNonNull(property); if (foundValue == null) { property(property, converter.apply(newValue)); } else if (!foundValue.equals(newValue)) { throw TransactionException.immutableProperty(foundValue, newValue, property); } }
java
public <X> void propertyImmutable(P property, X newValue, @Nullable X foundValue, Function<X, Object> converter) { Objects.requireNonNull(property); if (foundValue == null) { property(property, converter.apply(newValue)); } else if (!foundValue.equals(newValue)) { throw TransactionException.immutableProperty(foundValue, newValue, property); } }
[ "public", "<", "X", ">", "void", "propertyImmutable", "(", "P", "property", ",", "X", "newValue", ",", "@", "Nullable", "X", "foundValue", ",", "Function", "<", "X", ",", "Object", ">", "converter", ")", "{", "Objects", ".", "requireNonNull", "(", "prope...
Sets a property which cannot be mutated @param property The key of the immutable property to mutate @param newValue The new value to put on the property (if the property is not set) @param foundValue The current value of the property @param converter Helper method to ensure data is persisted in the correct format
[ "Sets", "a", "property", "which", "cannot", "be", "mutated" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/structure/AbstractElement.java#L153-L162
lucee/Lucee
core/src/main/java/lucee/runtime/reflection/Reflector.java
Reflector.getField
public static Object getField(Object obj, String prop) throws PageException { try { return getFieldsIgnoreCase(obj.getClass(), prop)[0].get(obj); } catch (Throwable e) { ExceptionUtil.rethrowIfNecessary(e); throw Caster.toPageException(e); } }
java
public static Object getField(Object obj, String prop) throws PageException { try { return getFieldsIgnoreCase(obj.getClass(), prop)[0].get(obj); } catch (Throwable e) { ExceptionUtil.rethrowIfNecessary(e); throw Caster.toPageException(e); } }
[ "public", "static", "Object", "getField", "(", "Object", "obj", ",", "String", "prop", ")", "throws", "PageException", "{", "try", "{", "return", "getFieldsIgnoreCase", "(", "obj", ".", "getClass", "(", ")", ",", "prop", ")", "[", "0", "]", ".", "get", ...
to get a visible Field of a object @param obj Object to invoke @param prop property to call @return property value @throws PageException
[ "to", "get", "a", "visible", "Field", "of", "a", "object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/reflection/Reflector.java#L1119-L1127
OpenBEL/openbel-framework
org.openbel.framework.common/src/main/java/org/openbel/framework/common/model/NamespaceGroup.java
NamespaceGroup.getAllNamespaces
public List<Namespace> getAllNamespaces() { List<Namespace> ret = new ArrayList<Namespace>(); if (namespaces != null) { ret.addAll(namespaces); } if (defaultResourceLocation != null) { String prefix = DEFAULT_NAMESPACE_PREFIX; String drl = defaultResourceLocation; final Namespace defaultNS = new Namespace(prefix, drl); ret.add(defaultNS); } return ret; }
java
public List<Namespace> getAllNamespaces() { List<Namespace> ret = new ArrayList<Namespace>(); if (namespaces != null) { ret.addAll(namespaces); } if (defaultResourceLocation != null) { String prefix = DEFAULT_NAMESPACE_PREFIX; String drl = defaultResourceLocation; final Namespace defaultNS = new Namespace(prefix, drl); ret.add(defaultNS); } return ret; }
[ "public", "List", "<", "Namespace", ">", "getAllNamespaces", "(", ")", "{", "List", "<", "Namespace", ">", "ret", "=", "new", "ArrayList", "<", "Namespace", ">", "(", ")", ";", "if", "(", "namespaces", "!=", "null", ")", "{", "ret", ".", "addAll", "(...
Returns all the group's namespaces. <p> This is equivalent to {@link #getNamespaces()} with the addition of the namespace representing the {@link #getDefaultResourceLocation() default resource location}, if present. </p> @return {@link List} of {@link Namespace namespaces}; which may be empty @see #getNamespaces()
[ "Returns", "all", "the", "group", "s", "namespaces", ".", "<p", ">", "This", "is", "equivalent", "to", "{", "@link", "#getNamespaces", "()", "}", "with", "the", "addition", "of", "the", "namespace", "representing", "the", "{", "@link", "#getDefaultResourceLoca...
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/model/NamespaceGroup.java#L117-L129
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/SampleCount.java
SampleCount.subtractPrecise
public SampleCount subtractPrecise(SampleCount that) throws ResamplingException { final long thatSamples = that.getSamplesPrecise(this.rate); if (thatSamples != 0) { return new SampleCount(this.samples - thatSamples, this.rate); } else { return this; } }
java
public SampleCount subtractPrecise(SampleCount that) throws ResamplingException { final long thatSamples = that.getSamplesPrecise(this.rate); if (thatSamples != 0) { return new SampleCount(this.samples - thatSamples, this.rate); } else { return this; } }
[ "public", "SampleCount", "subtractPrecise", "(", "SampleCount", "that", ")", "throws", "ResamplingException", "{", "final", "long", "thatSamples", "=", "that", ".", "getSamplesPrecise", "(", "this", ".", "rate", ")", ";", "if", "(", "thatSamples", "!=", "0", "...
@param that the sample count to subtract @return @throws ResamplingException if the delta cannot be expressed without losing accuracy
[ "@param", "that", "the", "sample", "count", "to", "subtract" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/SampleCount.java#L87-L99
RestComm/Restcomm-Connect
restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/ua/UserAgentManager.java
UserAgentManager.isWebRTC
private boolean isWebRTC(String transport, String userAgent) { return "ws".equalsIgnoreCase(transport) || "wss".equalsIgnoreCase(transport) || userAgent.toLowerCase().contains("restcomm"); }
java
private boolean isWebRTC(String transport, String userAgent) { return "ws".equalsIgnoreCase(transport) || "wss".equalsIgnoreCase(transport) || userAgent.toLowerCase().contains("restcomm"); }
[ "private", "boolean", "isWebRTC", "(", "String", "transport", ",", "String", "userAgent", ")", "{", "return", "\"ws\"", ".", "equalsIgnoreCase", "(", "transport", ")", "||", "\"wss\"", ".", "equalsIgnoreCase", "(", "transport", ")", "||", "userAgent", ".", "to...
Checks whether the client is WebRTC or not. <p> A client is considered WebRTC if one of the following statements is true:<br> 1. The chosen transport is WebSockets (transport=ws).<br> 2. The chosen transport is WebSockets Secured (transport=wss).<br> 3. The User-Agent corresponds to one of TeleStax mobile clients. </p> @param transport @param userAgent @return
[ "Checks", "whether", "the", "client", "is", "WebRTC", "or", "not", "." ]
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/ua/UserAgentManager.java#L746-L748