repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/theta/UnionImpl.java
UnionImpl.initNewDirectInstance
static UnionImpl initNewDirectInstance( final int lgNomLongs, final long seed, final float p, final ResizeFactor rf, final MemoryRequestServer memReqSvr, final WritableMemory dstMem) { final UpdateSketch gadget = new DirectQuickSelectSketch( lgNomLongs, seed, p, rf, memReqSvr, dstMem, true); //create with UNION family final UnionImpl unionImpl = new UnionImpl(gadget, seed); unionImpl.unionThetaLong_ = gadget.getThetaLong(); unionImpl.unionEmpty_ = gadget.isEmpty(); return unionImpl; }
java
static UnionImpl initNewDirectInstance( final int lgNomLongs, final long seed, final float p, final ResizeFactor rf, final MemoryRequestServer memReqSvr, final WritableMemory dstMem) { final UpdateSketch gadget = new DirectQuickSelectSketch( lgNomLongs, seed, p, rf, memReqSvr, dstMem, true); //create with UNION family final UnionImpl unionImpl = new UnionImpl(gadget, seed); unionImpl.unionThetaLong_ = gadget.getThetaLong(); unionImpl.unionEmpty_ = gadget.isEmpty(); return unionImpl; }
[ "static", "UnionImpl", "initNewDirectInstance", "(", "final", "int", "lgNomLongs", ",", "final", "long", "seed", ",", "final", "float", "p", ",", "final", "ResizeFactor", "rf", ",", "final", "MemoryRequestServer", "memReqSvr", ",", "final", "WritableMemory", "dstM...
Construct a new Direct Union in the off-heap destination Memory. Called by SetOperationBuilder. @param lgNomLongs <a href="{@docRoot}/resources/dictionary.html#lgNomLogs">See lgNomLongs</a>. @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See seed</a> @param p <a href="{@docRoot}/resources/dictionary.html#p">See Sampling Probability, <i>p</i></a> @param rf <a href="{@docRoot}/resources/dictionary.html#resizeFactor">See Resize Factor</a> @param memReqSvr a given instance of a MemoryRequestServer @param dstMem the given Memory object destination. It will be cleared prior to use. @return this class
[ "Construct", "a", "new", "Direct", "Union", "in", "the", "off", "-", "heap", "destination", "Memory", ".", "Called", "by", "SetOperationBuilder", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/UnionImpl.java#L96-L109
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java
Feature.setCurrencyAttribute
public void setCurrencyAttribute(String name, String value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof CurrencyAttribute)) { throw new IllegalStateException("Cannot set currency value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((CurrencyAttribute) attribute).setValue(value); }
java
public void setCurrencyAttribute(String name, String value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof CurrencyAttribute)) { throw new IllegalStateException("Cannot set currency value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((CurrencyAttribute) attribute).setValue(value); }
[ "public", "void", "setCurrencyAttribute", "(", "String", "name", ",", "String", "value", ")", "{", "Attribute", "attribute", "=", "getAttributes", "(", ")", ".", "get", "(", "name", ")", ";", "if", "(", "!", "(", "attribute", "instanceof", "CurrencyAttribute...
Set attribute value of given type. @param name attribute name @param value attribute value
[ "Set", "attribute", "value", "of", "given", "type", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java#L230-L237
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/PublicanPODocBookBuilder.java
PublicanPODocBookBuilder.processPOBugLinks
protected void processPOBugLinks(final POBuildData buildData, final DocBookXMLPreProcessor preProcessor, final String bugLinkUrl, final Map<String, TranslationDetails> translations) { final String originalString = buildData.getConstants().getString("REPORT_A_BUG"); final String translationString = buildData.getTranslationConstants().getString("REPORT_A_BUG"); final String originalLink = preProcessor.createExternalLinkElement(buildData.getDocBookVersion(), originalString, bugLinkUrl); // Check to see if the report a bug text has translations if (originalString.equals(translationString)) { translations.put(originalLink, new TranslationDetails(null, false, "para")); } else { final String translatedLink = preProcessor.createExternalLinkElement(buildData.getDocBookVersion(), translationString, bugLinkUrl); translations.put(originalLink, new TranslationDetails(translatedLink, false, "para")); } }
java
protected void processPOBugLinks(final POBuildData buildData, final DocBookXMLPreProcessor preProcessor, final String bugLinkUrl, final Map<String, TranslationDetails> translations) { final String originalString = buildData.getConstants().getString("REPORT_A_BUG"); final String translationString = buildData.getTranslationConstants().getString("REPORT_A_BUG"); final String originalLink = preProcessor.createExternalLinkElement(buildData.getDocBookVersion(), originalString, bugLinkUrl); // Check to see if the report a bug text has translations if (originalString.equals(translationString)) { translations.put(originalLink, new TranslationDetails(null, false, "para")); } else { final String translatedLink = preProcessor.createExternalLinkElement(buildData.getDocBookVersion(), translationString, bugLinkUrl); translations.put(originalLink, new TranslationDetails(translatedLink, false, "para")); } }
[ "protected", "void", "processPOBugLinks", "(", "final", "POBuildData", "buildData", ",", "final", "DocBookXMLPreProcessor", "preProcessor", ",", "final", "String", "bugLinkUrl", ",", "final", "Map", "<", "String", ",", "TranslationDetails", ">", "translations", ")", ...
Creates the strings for a specific bug link url. @param buildData Information and data structures for the build. @param preProcessor The {@link DocBookXMLPreProcessor} instance to use to create the bug links. @param bugLinkUrl The bug link url. @param translations The mapping of original strings to translation strings, that will be used to build the po/pot files.
[ "Creates", "the", "strings", "for", "a", "specific", "bug", "link", "url", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/PublicanPODocBookBuilder.java#L1294-L1310
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java
PlatformBitmapFactory.createBitmap
public CloseableReference<Bitmap> createBitmap( int width, int height, Bitmap.Config bitmapConfig) { return createBitmap(width, height, bitmapConfig, null); }
java
public CloseableReference<Bitmap> createBitmap( int width, int height, Bitmap.Config bitmapConfig) { return createBitmap(width, height, bitmapConfig, null); }
[ "public", "CloseableReference", "<", "Bitmap", ">", "createBitmap", "(", "int", "width", ",", "int", "height", ",", "Bitmap", ".", "Config", "bitmapConfig", ")", "{", "return", "createBitmap", "(", "width", ",", "height", ",", "bitmapConfig", ",", "null", ")...
Creates a bitmap of the specified width and height. @param width the width of the bitmap @param height the height of the bitmap @param bitmapConfig the Bitmap.Config used to create the Bitmap @return a reference to the bitmap @throws TooManyBitmapsException if the pool is full @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
[ "Creates", "a", "bitmap", "of", "the", "specified", "width", "and", "height", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L37-L42
kiegroup/droolsjbpm-integration
kie-server-parent/kie-server-common/src/main/java/org/kie/server/common/rest/KieServerHttpRequest.java
KieServerHttpRequest.contentType
public KieServerHttpRequest contentType(final String contentType, final String charset ) { if( charset != null && charset.length() > 0 ) { final String separator = "; " + PARAM_CHARSET + '='; return header(CONTENT_TYPE, contentType + separator + charset); } else return header(CONTENT_TYPE, contentType); }
java
public KieServerHttpRequest contentType(final String contentType, final String charset ) { if( charset != null && charset.length() > 0 ) { final String separator = "; " + PARAM_CHARSET + '='; return header(CONTENT_TYPE, contentType + separator + charset); } else return header(CONTENT_TYPE, contentType); }
[ "public", "KieServerHttpRequest", "contentType", "(", "final", "String", "contentType", ",", "final", "String", "charset", ")", "{", "if", "(", "charset", "!=", "null", "&&", "charset", ".", "length", "(", ")", ">", "0", ")", "{", "final", "String", "separ...
Set the 'Content-Type' request header to the given value and charset @param contentType @param charset @return this request
[ "Set", "the", "Content", "-", "Type", "request", "header", "to", "the", "given", "value", "and", "charset" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-common/src/main/java/org/kie/server/common/rest/KieServerHttpRequest.java#L1072-L1078
nmdp-bioinformatics/ngs
reads/src/main/java/org/nmdp/ngs/reads/paired/PairedEndFastqReader.java
PairedEndFastqReader.streamInterleaved
public static void streamInterleaved(final Reader reader, final PairedEndListener listener) throws IOException { streamInterleaved((Readable) reader, listener); }
java
public static void streamInterleaved(final Reader reader, final PairedEndListener listener) throws IOException { streamInterleaved((Readable) reader, listener); }
[ "public", "static", "void", "streamInterleaved", "(", "final", "Reader", "reader", ",", "final", "PairedEndListener", "listener", ")", "throws", "IOException", "{", "streamInterleaved", "(", "(", "Readable", ")", "reader", ",", "listener", ")", ";", "}" ]
Stream the specified interleaved paired end reads. Per the interleaved format, all reads must be sorted and paired. @param reader reader, must not be null @param listener paired end listener, must not be null @throws IOException if an I/O error occurs @deprecated by {@link #streamInterleaved(Readable,PairedEndListener)}, will be removed in version 2.0
[ "Stream", "the", "specified", "interleaved", "paired", "end", "reads", ".", "Per", "the", "interleaved", "format", "all", "reads", "must", "be", "sorted", "and", "paired", "." ]
train
https://github.com/nmdp-bioinformatics/ngs/blob/277627e4311313a80f5dc110b3185b0d7af32bd0/reads/src/main/java/org/nmdp/ngs/reads/paired/PairedEndFastqReader.java#L254-L256
Whiley/WhileyCompiler
src/main/java/wyil/util/AbstractTypedVisitor.java
AbstractTypedVisitor.selectCandidate
public <T extends Type> T selectCandidate(T[] candidates, T actual, Environment environment) { // T candidate = null; for (int i = 0; i != candidates.length; ++i) { T next = candidates[i]; if (subtypeOperator.isSubtype(next, actual, environment)) { if (candidate == null) { candidate = next; } else { candidate = selectCandidate(candidate, next, actual, environment); } } } // return candidate; }
java
public <T extends Type> T selectCandidate(T[] candidates, T actual, Environment environment) { // T candidate = null; for (int i = 0; i != candidates.length; ++i) { T next = candidates[i]; if (subtypeOperator.isSubtype(next, actual, environment)) { if (candidate == null) { candidate = next; } else { candidate = selectCandidate(candidate, next, actual, environment); } } } // return candidate; }
[ "public", "<", "T", "extends", "Type", ">", "T", "selectCandidate", "(", "T", "[", "]", "candidates", ",", "T", "actual", ",", "Environment", "environment", ")", "{", "//", "T", "candidate", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", ...
Given an array of candidate types, select the most precise match for a actual type. If no such candidate exists, return null (which should be impossible for type correct code). @param candidates @param actual @return
[ "Given", "an", "array", "of", "candidate", "types", "select", "the", "most", "precise", "match", "for", "a", "actual", "type", ".", "If", "no", "such", "candidate", "exists", "return", "null", "(", "which", "should", "be", "impossible", "for", "type", "cor...
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/util/AbstractTypedVisitor.java#L1229-L1244
VoltDB/voltdb
src/frontend/org/voltdb/sysprocs/UpdateApplicationBase.java
UpdateApplicationBase.allowPausedModeWork
static protected boolean allowPausedModeWork(boolean internalCall, boolean adminConnection) { return (VoltDB.instance().getMode() != OperationMode.PAUSED || internalCall || adminConnection); }
java
static protected boolean allowPausedModeWork(boolean internalCall, boolean adminConnection) { return (VoltDB.instance().getMode() != OperationMode.PAUSED || internalCall || adminConnection); }
[ "static", "protected", "boolean", "allowPausedModeWork", "(", "boolean", "internalCall", ",", "boolean", "adminConnection", ")", "{", "return", "(", "VoltDB", ".", "instance", "(", ")", ".", "getMode", "(", ")", "!=", "OperationMode", ".", "PAUSED", "||", "int...
Check if something should run based on admin/paused/internal status
[ "Check", "if", "something", "should", "run", "based", "on", "admin", "/", "paused", "/", "internal", "status" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/sysprocs/UpdateApplicationBase.java#L393-L397
jfinal/jfinal
src/main/java/com/jfinal/plugin/activerecord/DbPro.java
DbPro.findFirstByCache
public Record findFirstByCache(String cacheName, Object key, String sql, Object... paras) { ICache cache = config.getCache(); Record result = cache.get(cacheName, key); if (result == null) { result = findFirst(sql, paras); cache.put(cacheName, key, result); } return result; }
java
public Record findFirstByCache(String cacheName, Object key, String sql, Object... paras) { ICache cache = config.getCache(); Record result = cache.get(cacheName, key); if (result == null) { result = findFirst(sql, paras); cache.put(cacheName, key, result); } return result; }
[ "public", "Record", "findFirstByCache", "(", "String", "cacheName", ",", "Object", "key", ",", "String", "sql", ",", "Object", "...", "paras", ")", "{", "ICache", "cache", "=", "config", ".", "getCache", "(", ")", ";", "Record", "result", "=", "cache", "...
Find first record by cache. I recommend add "limit 1" in your sql. @see #findFirst(String, Object...) @param cacheName the cache name @param key the key used to get date from cache @param sql an SQL statement that may contain one or more '?' IN parameter placeholders @param paras the parameters of sql @return the Record object
[ "Find", "first", "record", "by", "cache", ".", "I", "recommend", "add", "limit", "1", "in", "your", "sql", "." ]
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/DbPro.java#L843-L851
UrielCh/ovh-java-sdk
ovh-java-sdk-router/src/main/java/net/minidev/ovh/api/ApiOvhRouter.java
ApiOvhRouter.serviceName_privateLink_peerServiceName_request_manage_POST
public String serviceName_privateLink_peerServiceName_request_manage_POST(String serviceName, String peerServiceName, OvhPrivLinkReqActionEnum action) throws IOException { String qPath = "/router/{serviceName}/privateLink/{peerServiceName}/request/manage"; StringBuilder sb = path(qPath, serviceName, peerServiceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "action", action); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
java
public String serviceName_privateLink_peerServiceName_request_manage_POST(String serviceName, String peerServiceName, OvhPrivLinkReqActionEnum action) throws IOException { String qPath = "/router/{serviceName}/privateLink/{peerServiceName}/request/manage"; StringBuilder sb = path(qPath, serviceName, peerServiceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "action", action); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
[ "public", "String", "serviceName_privateLink_peerServiceName_request_manage_POST", "(", "String", "serviceName", ",", "String", "peerServiceName", ",", "OvhPrivLinkReqActionEnum", "action", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/router/{serviceName}/priv...
Accept, reject or cancel a pending request REST: POST /router/{serviceName}/privateLink/{peerServiceName}/request/manage @param action [required] @param serviceName [required] The internal name of your Router offer @param peerServiceName [required] Service name of the other side of this link
[ "Accept", "reject", "or", "cancel", "a", "pending", "request" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-router/src/main/java/net/minidev/ovh/api/ApiOvhRouter.java#L359-L366
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuGraphInstantiate
public static int cuGraphInstantiate(CUgraphExec phGraphExec, CUgraph hGraph, CUgraphNode phErrorNode, byte logBuffer[], long bufferSize) { return checkResult(cuGraphInstantiateNative(phGraphExec, hGraph, phErrorNode, logBuffer, bufferSize)); }
java
public static int cuGraphInstantiate(CUgraphExec phGraphExec, CUgraph hGraph, CUgraphNode phErrorNode, byte logBuffer[], long bufferSize) { return checkResult(cuGraphInstantiateNative(phGraphExec, hGraph, phErrorNode, logBuffer, bufferSize)); }
[ "public", "static", "int", "cuGraphInstantiate", "(", "CUgraphExec", "phGraphExec", ",", "CUgraph", "hGraph", ",", "CUgraphNode", "phErrorNode", ",", "byte", "logBuffer", "[", "]", ",", "long", "bufferSize", ")", "{", "return", "checkResult", "(", "cuGraphInstanti...
Creates an executable graph from a graph.<br> <br> Instantiates \p hGraph as an executable graph. The graph is validated for any structural constraints or intra-node constraints which were not previously validated. If instantiation is successful, a handle to the instantiated graph is returned in \p graphExec.<br> <br> If there are any errors, diagnostic information may be returned in \p errorNode and \p logBuffer. This is the primary way to inspect instantiation errors. The output will be null terminated unless the diagnostics overflow the buffer. In this case, they will be truncated, and the last byte can be inspected to determine if truncation occurred.<br> @param phGraphExec - Returns instantiated graph @param hGraph - Graph to instantiate @param phErrorNode - In case of an instantiation error, this may be modified to indicate a node contributing to the error @param logBuffer - A character buffer to store diagnostic messages @param bufferSize - Size of the log buffer in bytes @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_VALUE @see JCudaDriver#cuGraphCreate JCudaDriver#cuGraphLaunch JCudaDriver#cuGraphExecDestroy
[ "Creates", "an", "executable", "graph", "from", "a", "graph", ".", "<br", ">", "<br", ">", "Instantiates", "\\", "p", "hGraph", "as", "an", "executable", "graph", ".", "The", "graph", "is", "validated", "for", "any", "structural", "constraints", "or", "int...
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L12946-L12949
paypal/SeLion
dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelDataProviderImpl.java
ExcelDataProviderImpl.getSingleExcelRow
protected Object getSingleExcelRow(Object userObj, String key, boolean isExternalCall) { logger.entering(new Object[] { userObj, key, isExternalCall }); Class<?> cls; try { cls = Class.forName(userObj.getClass().getName()); } catch (ClassNotFoundException e) { throw new DataProviderException("Unable to find class of type + '" + userObj.getClass().getName() + "'", e); } int rowIndex = excelReader.getRowIndex(cls.getSimpleName(), key); if (rowIndex == -1) { throw new DataProviderException("Row with key '" + key + "' is not found"); } Object object = getSingleExcelRow(userObj, rowIndex, isExternalCall); logger.exiting(object); return object; }
java
protected Object getSingleExcelRow(Object userObj, String key, boolean isExternalCall) { logger.entering(new Object[] { userObj, key, isExternalCall }); Class<?> cls; try { cls = Class.forName(userObj.getClass().getName()); } catch (ClassNotFoundException e) { throw new DataProviderException("Unable to find class of type + '" + userObj.getClass().getName() + "'", e); } int rowIndex = excelReader.getRowIndex(cls.getSimpleName(), key); if (rowIndex == -1) { throw new DataProviderException("Row with key '" + key + "' is not found"); } Object object = getSingleExcelRow(userObj, rowIndex, isExternalCall); logger.exiting(object); return object; }
[ "protected", "Object", "getSingleExcelRow", "(", "Object", "userObj", ",", "String", "key", ",", "boolean", "isExternalCall", ")", "{", "logger", ".", "entering", "(", "new", "Object", "[", "]", "{", "userObj", ",", "key", ",", "isExternalCall", "}", ")", ...
This method fetches a specific row from an excel sheet which can be identified using a key and returns the data as an Object which can be cast back into the user's actual data type. @param userObj An Object into which data is to be packed into @param key A string that represents a key to search for in the excel sheet @param isExternalCall A boolean that helps distinguish internally if the call is being made internally or by the user. For external calls the index of the row would need to be bumped up,because the first row is to be ignored always. @return An Object which can be cast into the user's actual data type.
[ "This", "method", "fetches", "a", "specific", "row", "from", "an", "excel", "sheet", "which", "can", "be", "identified", "using", "a", "key", "and", "returns", "the", "data", "as", "an", "Object", "which", "can", "be", "cast", "back", "into", "the", "use...
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelDataProviderImpl.java#L388-L405
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/jetty/Server.java
Server.addWebApplications
public WebApplicationContext[] addWebApplications(String host, String webapps, boolean extract) throws IOException { return addWebApplications(host,webapps,null,extract); }
java
public WebApplicationContext[] addWebApplications(String host, String webapps, boolean extract) throws IOException { return addWebApplications(host,webapps,null,extract); }
[ "public", "WebApplicationContext", "[", "]", "addWebApplications", "(", "String", "host", ",", "String", "webapps", ",", "boolean", "extract", ")", "throws", "IOException", "{", "return", "addWebApplications", "(", "host", ",", "webapps", ",", "null", ",", "extr...
Add Web Applications. Add auto webapplications to the server. The name of the webapp directory or war is used as the context name. If the webapp matches the rootWebApp it is added as the "/" context. @param host Virtual host name or null @param webapps Directory file name or URL to look for auto webapplication. @param extract If true, extract war files @exception IOException
[ "Add", "Web", "Applications", ".", "Add", "auto", "webapplications", "to", "the", "server", ".", "The", "name", "of", "the", "webapp", "directory", "or", "war", "is", "used", "as", "the", "context", "name", ".", "If", "the", "webapp", "matches", "the", "...
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/jetty/Server.java#L308-L314
apereo/cas
support/cas-server-support-validation/src/main/java/org/apereo/cas/web/v2/ProxyController.java
ProxyController.generateErrorView
private ModelAndView generateErrorView(final String code, final Object[] args, final HttpServletRequest request) { val modelAndView = new ModelAndView(this.failureView); modelAndView.addObject("code", StringEscapeUtils.escapeHtml4(code)); val desc = StringEscapeUtils.escapeHtml4(this.context.getMessage(code, args, code, request.getLocale())); modelAndView.addObject("description", desc); return modelAndView; }
java
private ModelAndView generateErrorView(final String code, final Object[] args, final HttpServletRequest request) { val modelAndView = new ModelAndView(this.failureView); modelAndView.addObject("code", StringEscapeUtils.escapeHtml4(code)); val desc = StringEscapeUtils.escapeHtml4(this.context.getMessage(code, args, code, request.getLocale())); modelAndView.addObject("description", desc); return modelAndView; }
[ "private", "ModelAndView", "generateErrorView", "(", "final", "String", "code", ",", "final", "Object", "[", "]", "args", ",", "final", "HttpServletRequest", "request", ")", "{", "val", "modelAndView", "=", "new", "ModelAndView", "(", "this", ".", "failureView",...
Generate error view stuffing the code and description of the error into the model. View name is set to {@link #failureView}. @param code the code @param args the msg args @return the model and view
[ "Generate", "error", "view", "stuffing", "the", "code", "and", "description", "of", "the", "error", "into", "the", "model", ".", "View", "name", "is", "set", "to", "{", "@link", "#failureView", "}", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-validation/src/main/java/org/apereo/cas/web/v2/ProxyController.java#L107-L113
ModeShape/modeshape
connectors/modeshape-connector-cmis/src/main/java/org/modeshape/connector/cmis/CmisConnector.java
CmisConnector.cmisContent
private Document cmisContent( String id ) { DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.CONTENT, id)); org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)session.getObject(id); writer.setPrimaryType(NodeType.NT_RESOURCE); writer.setParent(id); ContentStream contentStream = doc.getContentStream(); if (contentStream != null) { BinaryValue content = new CmisConnectorBinary(contentStream, getSourceName(), id, getMimeTypeDetector()); writer.addProperty(JcrConstants.JCR_DATA, content); writer.addProperty(JcrConstants.JCR_MIME_TYPE, contentStream.getMimeType()); } Property<Object> lastModified = doc.getProperty(PropertyIds.LAST_MODIFICATION_DATE); Property<Object> lastModifiedBy = doc.getProperty(PropertyIds.LAST_MODIFIED_BY); writer.addProperty(JcrLexicon.LAST_MODIFIED, properties.jcrValues(lastModified)); writer.addProperty(JcrLexicon.LAST_MODIFIED_BY, properties.jcrValues(lastModifiedBy)); return writer.document(); }
java
private Document cmisContent( String id ) { DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.CONTENT, id)); org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)session.getObject(id); writer.setPrimaryType(NodeType.NT_RESOURCE); writer.setParent(id); ContentStream contentStream = doc.getContentStream(); if (contentStream != null) { BinaryValue content = new CmisConnectorBinary(contentStream, getSourceName(), id, getMimeTypeDetector()); writer.addProperty(JcrConstants.JCR_DATA, content); writer.addProperty(JcrConstants.JCR_MIME_TYPE, contentStream.getMimeType()); } Property<Object> lastModified = doc.getProperty(PropertyIds.LAST_MODIFICATION_DATE); Property<Object> lastModifiedBy = doc.getProperty(PropertyIds.LAST_MODIFIED_BY); writer.addProperty(JcrLexicon.LAST_MODIFIED, properties.jcrValues(lastModified)); writer.addProperty(JcrLexicon.LAST_MODIFIED_BY, properties.jcrValues(lastModifiedBy)); return writer.document(); }
[ "private", "Document", "cmisContent", "(", "String", "id", ")", "{", "DocumentWriter", "writer", "=", "newDocument", "(", "ObjectId", ".", "toString", "(", "ObjectId", ".", "Type", ".", "CONTENT", ",", "id", ")", ")", ";", "org", ".", "apache", ".", "che...
Converts binary content into JCR node. @param id the id of the CMIS document. @return JCR node representation.
[ "Converts", "binary", "content", "into", "JCR", "node", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/connectors/modeshape-connector-cmis/src/main/java/org/modeshape/connector/cmis/CmisConnector.java#L817-L838
lucee/Lucee
core/src/main/java/lucee/runtime/ComponentImpl.java
ComponentImpl.afterConstructor
public void afterConstructor(PageContext pc, Variables parent) throws ApplicationException { pc.setVariablesScope(parent); this.afterConstructor = true; /* * if(constructorUDFs!=null){ Iterator<Entry<Key, UDF>> it = constructorUDFs.entrySet().iterator(); * Map.Entry<Key, UDF> entry; Key key; UDFPlus udf; PageSource ps; while(it.hasNext()){ * entry=it.next(); key=entry.getKey(); udf=(UDFPlus) entry.getValue(); ps=udf.getPageSource(); * //if(ps!=null && ps.equals(getPageSource()))continue; // TODO can we avoid that udfs from the * component itself are here? registerUDF(key, udf,false,true); } } */ }
java
public void afterConstructor(PageContext pc, Variables parent) throws ApplicationException { pc.setVariablesScope(parent); this.afterConstructor = true; /* * if(constructorUDFs!=null){ Iterator<Entry<Key, UDF>> it = constructorUDFs.entrySet().iterator(); * Map.Entry<Key, UDF> entry; Key key; UDFPlus udf; PageSource ps; while(it.hasNext()){ * entry=it.next(); key=entry.getKey(); udf=(UDFPlus) entry.getValue(); ps=udf.getPageSource(); * //if(ps!=null && ps.equals(getPageSource()))continue; // TODO can we avoid that udfs from the * component itself are here? registerUDF(key, udf,false,true); } } */ }
[ "public", "void", "afterConstructor", "(", "PageContext", "pc", ",", "Variables", "parent", ")", "throws", "ApplicationException", "{", "pc", ".", "setVariablesScope", "(", "parent", ")", ";", "this", ".", "afterConstructor", "=", "true", ";", "/*\n\t * if(constru...
will be called after invoking constructor, only invoked by constructor (component body execution) @param pc @param parent @throws ApplicationException
[ "will", "be", "called", "after", "invoking", "constructor", "only", "invoked", "by", "constructor", "(", "component", "body", "execution", ")" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/ComponentImpl.java#L722-L733
gallandarakhneorg/afc
core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/d/Tuple1d.java
Tuple1d.set
public void set(Segment1D<?, ?> segment, double curviline, double shift) { assert segment != null : AssertMessages.notNullParameter(0); this.segment = new WeakReference<>(segment); this.x = curviline; this.y = shift; }
java
public void set(Segment1D<?, ?> segment, double curviline, double shift) { assert segment != null : AssertMessages.notNullParameter(0); this.segment = new WeakReference<>(segment); this.x = curviline; this.y = shift; }
[ "public", "void", "set", "(", "Segment1D", "<", "?", ",", "?", ">", "segment", ",", "double", "curviline", ",", "double", "shift", ")", "{", "assert", "segment", "!=", "null", ":", "AssertMessages", ".", "notNullParameter", "(", "0", ")", ";", "this", ...
Change the attributes of the tuple. @param segment the segment. @param curviline the curviline coordinate. @param shift the shift distance.
[ "Change", "the", "attributes", "of", "the", "tuple", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/d/Tuple1d.java#L264-L269
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/BandwidthSchedulesInner.java
BandwidthSchedulesInner.listByDataBoxEdgeDeviceAsync
public Observable<Page<BandwidthScheduleInner>> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName) { return listByDataBoxEdgeDeviceWithServiceResponseAsync(deviceName, resourceGroupName) .map(new Func1<ServiceResponse<Page<BandwidthScheduleInner>>, Page<BandwidthScheduleInner>>() { @Override public Page<BandwidthScheduleInner> call(ServiceResponse<Page<BandwidthScheduleInner>> response) { return response.body(); } }); }
java
public Observable<Page<BandwidthScheduleInner>> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName) { return listByDataBoxEdgeDeviceWithServiceResponseAsync(deviceName, resourceGroupName) .map(new Func1<ServiceResponse<Page<BandwidthScheduleInner>>, Page<BandwidthScheduleInner>>() { @Override public Page<BandwidthScheduleInner> call(ServiceResponse<Page<BandwidthScheduleInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "BandwidthScheduleInner", ">", ">", "listByDataBoxEdgeDeviceAsync", "(", "final", "String", "deviceName", ",", "final", "String", "resourceGroupName", ")", "{", "return", "listByDataBoxEdgeDeviceWithServiceResponseAsync", "(", "de...
Gets all the bandwidth schedules for a data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;BandwidthScheduleInner&gt; object
[ "Gets", "all", "the", "bandwidth", "schedules", "for", "a", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/BandwidthSchedulesInner.java#L143-L151
aws/aws-sdk-java
aws-java-sdk-simpledb/src/main/java/com/amazonaws/services/simpledb/util/SimpleDBUtils.java
SimpleDBUtils.encodeZeroPadding
public static String encodeZeroPadding(float number, int maxNumDigits) { String floatString = Float.toString(number); int numBeforeDecimal = floatString.indexOf('.'); numBeforeDecimal = (numBeforeDecimal >= 0 ? numBeforeDecimal : floatString.length()); int numZeroes = maxNumDigits - numBeforeDecimal; StringBuffer strBuffer = new StringBuffer(numZeroes + floatString.length()); for (int i = 0; i < numZeroes; i++) { strBuffer.insert(i, '0'); } strBuffer.append(floatString); return strBuffer.toString(); }
java
public static String encodeZeroPadding(float number, int maxNumDigits) { String floatString = Float.toString(number); int numBeforeDecimal = floatString.indexOf('.'); numBeforeDecimal = (numBeforeDecimal >= 0 ? numBeforeDecimal : floatString.length()); int numZeroes = maxNumDigits - numBeforeDecimal; StringBuffer strBuffer = new StringBuffer(numZeroes + floatString.length()); for (int i = 0; i < numZeroes; i++) { strBuffer.insert(i, '0'); } strBuffer.append(floatString); return strBuffer.toString(); }
[ "public", "static", "String", "encodeZeroPadding", "(", "float", "number", ",", "int", "maxNumDigits", ")", "{", "String", "floatString", "=", "Float", ".", "toString", "(", "number", ")", ";", "int", "numBeforeDecimal", "=", "floatString", ".", "indexOf", "("...
Encodes positive float value into a string by zero-padding number up to the specified number of digits @param number positive float value to be encoded @param maxNumDigits maximum number of digits preceding the decimal point in the largest value in the data set @return string representation of the zero-padded float value
[ "Encodes", "positive", "float", "value", "into", "a", "string", "by", "zero", "-", "padding", "number", "up", "to", "the", "specified", "number", "of", "digits" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-simpledb/src/main/java/com/amazonaws/services/simpledb/util/SimpleDBUtils.java#L86-L97
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/svg/InkscapeLoader.java
InkscapeLoader.loadElement
private void loadElement(Element element, Transform t) throws ParsingException { for (int i = 0; i < processors.size(); i++) { ElementProcessor processor = (ElementProcessor) processors.get(i); if (processor.handles(element)) { processor.process(this, element, diagram, t); } } }
java
private void loadElement(Element element, Transform t) throws ParsingException { for (int i = 0; i < processors.size(); i++) { ElementProcessor processor = (ElementProcessor) processors.get(i); if (processor.handles(element)) { processor.process(this, element, diagram, t); } } }
[ "private", "void", "loadElement", "(", "Element", "element", ",", "Transform", "t", ")", "throws", "ParsingException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "processors", ".", "size", "(", ")", ";", "i", "++", ")", "{", "ElementProcesso...
Load a single element into the diagram @param element The element ot be loaded @param t The transform to apply to the loaded element from the parent @throws ParsingException Indicates a failure to parse the element
[ "Load", "a", "single", "element", "into", "the", "diagram" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/svg/InkscapeLoader.java#L216-L225
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java
StreamSegmentReadIndex.getLengthUntilNextEntry
@GuardedBy("lock") private int getLengthUntilNextEntry(long startOffset, int maxLength) { ReadIndexEntry ceilingEntry = this.indexEntries.getCeiling(startOffset); if (ceilingEntry != null) { maxLength = (int) Math.min(maxLength, ceilingEntry.getStreamSegmentOffset() - startOffset); } return maxLength; }
java
@GuardedBy("lock") private int getLengthUntilNextEntry(long startOffset, int maxLength) { ReadIndexEntry ceilingEntry = this.indexEntries.getCeiling(startOffset); if (ceilingEntry != null) { maxLength = (int) Math.min(maxLength, ceilingEntry.getStreamSegmentOffset() - startOffset); } return maxLength; }
[ "@", "GuardedBy", "(", "\"lock\"", ")", "private", "int", "getLengthUntilNextEntry", "(", "long", "startOffset", ",", "int", "maxLength", ")", "{", "ReadIndexEntry", "ceilingEntry", "=", "this", ".", "indexEntries", ".", "getCeiling", "(", "startOffset", ")", ";...
Returns the length from the given offset until the beginning of the next index entry. If no such entry exists, or if the length is greater than maxLength, then maxLength is returned. @param startOffset The offset to search from. @param maxLength The maximum allowed length. @return The result.
[ "Returns", "the", "length", "from", "the", "given", "offset", "until", "the", "beginning", "of", "the", "next", "index", "entry", ".", "If", "no", "such", "entry", "exists", "or", "if", "the", "length", "is", "greater", "than", "maxLength", "then", "maxLen...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java#L1009-L1017
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethod.java
AptMethod.getDefaultReturnValue
public String getDefaultReturnValue(HashMap<String,TypeMirror> typeBinding) { String returnType = getReturnType(typeBinding); if (_defaultReturnValues.containsKey(returnType)) return _defaultReturnValues.get(returnType); return "null"; }
java
public String getDefaultReturnValue(HashMap<String,TypeMirror> typeBinding) { String returnType = getReturnType(typeBinding); if (_defaultReturnValues.containsKey(returnType)) return _defaultReturnValues.get(returnType); return "null"; }
[ "public", "String", "getDefaultReturnValue", "(", "HashMap", "<", "String", ",", "TypeMirror", ">", "typeBinding", ")", "{", "String", "returnType", "=", "getReturnType", "(", "typeBinding", ")", ";", "if", "(", "_defaultReturnValues", ".", "containsKey", "(", "...
Returns a default return value string for the method, based upon bound return type
[ "Returns", "a", "default", "return", "value", "string", "for", "the", "method", "based", "upon", "bound", "return", "type" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptMethod.java#L324-L330
kaazing/gateway
resource.address/spi/src/main/java/org/kaazing/gateway/resource/address/ResourceAddressFactorySpi.java
ResourceAddressFactorySpi.newResourceAddress0
protected T newResourceAddress0(String original, String location, ResourceOptions options) { final T address = newResourceAddress0(original, location); setOptions(address, location, options, options.getOption(QUALIFIER)); return address; }
java
protected T newResourceAddress0(String original, String location, ResourceOptions options) { final T address = newResourceAddress0(original, location); setOptions(address, location, options, options.getOption(QUALIFIER)); return address; }
[ "protected", "T", "newResourceAddress0", "(", "String", "original", ",", "String", "location", ",", "ResourceOptions", "options", ")", "{", "final", "T", "address", "=", "newResourceAddress0", "(", "original", ",", "location", ")", ";", "setOptions", "(", "addre...
note: extra hook for tcp.bind / udp.bind which changes location
[ "note", ":", "extra", "hook", "for", "tcp", ".", "bind", "/", "udp", ".", "bind", "which", "changes", "location" ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/resource.address/spi/src/main/java/org/kaazing/gateway/resource/address/ResourceAddressFactorySpi.java#L254-L259
UrielCh/ovh-java-sdk
ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java
ApiOvhSms.serviceName_receivers_slotId_DELETE
public void serviceName_receivers_slotId_DELETE(String serviceName, Long slotId) throws IOException { String qPath = "/sms/{serviceName}/receivers/{slotId}"; StringBuilder sb = path(qPath, serviceName, slotId); exec(qPath, "DELETE", sb.toString(), null); }
java
public void serviceName_receivers_slotId_DELETE(String serviceName, Long slotId) throws IOException { String qPath = "/sms/{serviceName}/receivers/{slotId}"; StringBuilder sb = path(qPath, serviceName, slotId); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "serviceName_receivers_slotId_DELETE", "(", "String", "serviceName", ",", "Long", "slotId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/sms/{serviceName}/receivers/{slotId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ...
Delete the document from the slot REST: DELETE /sms/{serviceName}/receivers/{slotId} @param serviceName [required] The internal name of your SMS offer @param slotId [required] Slot number id
[ "Delete", "the", "document", "from", "the", "slot" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L573-L577
OpenLiberty/open-liberty
dev/com.ibm.ws.security.javaeesec_fat/fat/src/com/ibm/ws/security/javaeesec/fat_helper/FATHelper.java
FATHelper.updateConfigDynamically
public static void updateConfigDynamically(LibertyServer server, ServerConfiguration config, boolean waitForAppToStart) throws Exception { resetMarksInLogs(server); server.updateServerConfiguration(config); server.waitForStringInLogUsingMark("CWWKG001[7-8]I"); if (waitForAppToStart) { server.waitForStringInLogUsingMark("CWWKZ0003I"); //CWWKZ0003I: The application **** updated in 0.020 seconds. } }
java
public static void updateConfigDynamically(LibertyServer server, ServerConfiguration config, boolean waitForAppToStart) throws Exception { resetMarksInLogs(server); server.updateServerConfiguration(config); server.waitForStringInLogUsingMark("CWWKG001[7-8]I"); if (waitForAppToStart) { server.waitForStringInLogUsingMark("CWWKZ0003I"); //CWWKZ0003I: The application **** updated in 0.020 seconds. } }
[ "public", "static", "void", "updateConfigDynamically", "(", "LibertyServer", "server", ",", "ServerConfiguration", "config", ",", "boolean", "waitForAppToStart", ")", "throws", "Exception", "{", "resetMarksInLogs", "(", "server", ")", ";", "server", ".", "updateServer...
This method will the reset the log and trace marks for log and trace searches, update the configuration and then wait for the server to re-initialize. Optionally it will then wait for the application to start. @param server The server to update. @param config The configuration to use. @param waitForAppToStart Wait for the application to start. @throws Exception If there was an issue updating the server configuration.
[ "This", "method", "will", "the", "reset", "the", "log", "and", "trace", "marks", "for", "log", "and", "trace", "searches", "update", "the", "configuration", "and", "then", "wait", "for", "the", "server", "to", "re", "-", "initialize", ".", "Optionally", "i...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.javaeesec_fat/fat/src/com/ibm/ws/security/javaeesec/fat_helper/FATHelper.java#L61-L68
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/LinearClassifier.java
LinearClassifier.logProbabilityOf
public Counter<L> logProbabilityOf(Datum<L, F> example) { if(example instanceof RVFDatum<?, ?>)return logProbabilityOfRVFDatum((RVFDatum<L,F>)example); Counter<L> scores = scoresOf(example); Counters.logNormalizeInPlace(scores); return scores; }
java
public Counter<L> logProbabilityOf(Datum<L, F> example) { if(example instanceof RVFDatum<?, ?>)return logProbabilityOfRVFDatum((RVFDatum<L,F>)example); Counter<L> scores = scoresOf(example); Counters.logNormalizeInPlace(scores); return scores; }
[ "public", "Counter", "<", "L", ">", "logProbabilityOf", "(", "Datum", "<", "L", ",", "F", ">", "example", ")", "{", "if", "(", "example", "instanceof", "RVFDatum", "<", "?", ",", "?", ">", ")", "return", "logProbabilityOfRVFDatum", "(", "(", "RVFDatum", ...
Returns a counter mapping from each class name to the log probability of that class for a certain example. Looking at the the sum of e^v for each count v, should be 1.0.
[ "Returns", "a", "counter", "mapping", "from", "each", "class", "name", "to", "the", "log", "probability", "of", "that", "class", "for", "a", "certain", "example", ".", "Looking", "at", "the", "the", "sum", "of", "e^v", "for", "each", "count", "v", "shoul...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LinearClassifier.java#L294-L299
sawano/java-commons
src/main/java/se/sawano/java/commons/lang/validate/Validate.java
Validate.isTrue
public static void isTrue(final boolean expression, final String message, final Object... values) { INSTANCE.isTrue(expression, message, values); }
java
public static void isTrue(final boolean expression, final String message, final Object... values) { INSTANCE.isTrue(expression, message, values); }
[ "public", "static", "void", "isTrue", "(", "final", "boolean", "expression", ",", "final", "String", "message", ",", "final", "Object", "...", "values", ")", "{", "INSTANCE", ".", "isTrue", "(", "expression", ",", "message", ",", "values", ")", ";", "}" ]
<p>Validate that the argument condition is {@code true}; otherwise throwing an exception with the specified message. This method is useful when validating according to an arbitrary boolean expression, such as validating a primitive number or using your own custom validation expression.</p> <pre> Validate.isTrue(i &gt;= min &amp;&amp; i &lt;= max, "The value must be between &#37;d and &#37;d", min, max); Validate.isTrue(myObject.isOk(), "The object is not okay"); </pre> @param expression the boolean expression to check @param message the {@link String#format(String, Object...)} exception message if invalid, not null @param values the optional values for the formatted exception message, null array not recommended @throws IllegalArgumentValidationException if expression is {@code false} @see #isTrue(boolean) @see #isTrue(boolean, String, long) @see #isTrue(boolean, String, double)
[ "<p", ">", "Validate", "that", "the", "argument", "condition", "is", "{", "@code", "true", "}", ";", "otherwise", "throwing", "an", "exception", "with", "the", "specified", "message", ".", "This", "method", "is", "useful", "when", "validating", "according", ...
train
https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L720-L722
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWriteDriver.java
GeoJsonWriteDriver.isSupportedPropertyType
public boolean isSupportedPropertyType(int sqlTypeId, String sqlTypeName) throws SQLException { switch (sqlTypeId) { case Types.BOOLEAN: case Types.DOUBLE: case Types.FLOAT: case Types.INTEGER: case Types.BIGINT: case Types.SMALLINT: case Types.DATE: case Types.VARCHAR: case Types.NCHAR: case Types.CHAR: case Types.ARRAY: case Types.OTHER: case Types.DECIMAL: case Types.REAL: case Types.TINYINT: case Types.NUMERIC: case Types.NULL: return true; default: throw new SQLException("Field type not supported by GeoJSON driver: " + sqlTypeName); } }
java
public boolean isSupportedPropertyType(int sqlTypeId, String sqlTypeName) throws SQLException { switch (sqlTypeId) { case Types.BOOLEAN: case Types.DOUBLE: case Types.FLOAT: case Types.INTEGER: case Types.BIGINT: case Types.SMALLINT: case Types.DATE: case Types.VARCHAR: case Types.NCHAR: case Types.CHAR: case Types.ARRAY: case Types.OTHER: case Types.DECIMAL: case Types.REAL: case Types.TINYINT: case Types.NUMERIC: case Types.NULL: return true; default: throw new SQLException("Field type not supported by GeoJSON driver: " + sqlTypeName); } }
[ "public", "boolean", "isSupportedPropertyType", "(", "int", "sqlTypeId", ",", "String", "sqlTypeName", ")", "throws", "SQLException", "{", "switch", "(", "sqlTypeId", ")", "{", "case", "Types", ".", "BOOLEAN", ":", "case", "Types", ".", "DOUBLE", ":", "case", ...
Return true is the SQL type is supported by the GeoJSON driver. @param sqlTypeId @param sqlTypeName @return @throws SQLException
[ "Return", "true", "is", "the", "SQL", "type", "is", "supported", "by", "the", "GeoJSON", "driver", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWriteDriver.java#L598-L621
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java
QueueContainer.txnRollbackPoll
public boolean txnRollbackPoll(long itemId, boolean backup) { TxQueueItem item = txMap.remove(itemId); if (item == null) { return false; } if (backup) { getBackupMap().put(itemId, item); } else { addTxItemOrdered(item); } cancelEvictionIfExists(); return true; }
java
public boolean txnRollbackPoll(long itemId, boolean backup) { TxQueueItem item = txMap.remove(itemId); if (item == null) { return false; } if (backup) { getBackupMap().put(itemId, item); } else { addTxItemOrdered(item); } cancelEvictionIfExists(); return true; }
[ "public", "boolean", "txnRollbackPoll", "(", "long", "itemId", ",", "boolean", "backup", ")", "{", "TxQueueItem", "item", "=", "txMap", ".", "remove", "(", "itemId", ")", ";", "if", "(", "item", "==", "null", ")", "{", "return", "false", ";", "}", "if"...
Rolls back the effects of the {@link #txnPollReserve(long, String)}. The {@code backup} parameter defines whether this item was stored on a backup queue or a primary queue. It will return the item to the queue or backup map if it wasn't offered as a part of the transaction. Cancels the queue eviction if one is scheduled. @param itemId the ID of the item which was polled in a transaction @param backup if this is the primary or the backup replica for this queue @return if there was any polled item with the {@code itemId} inside a transaction
[ "Rolls", "back", "the", "effects", "of", "the", "{", "@link", "#txnPollReserve", "(", "long", "String", ")", "}", ".", "The", "{", "@code", "backup", "}", "parameter", "defines", "whether", "this", "item", "was", "stored", "on", "a", "backup", "queue", "...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java#L269-L282
dihedron/dihedron-commons
src/main/java/org/dihedron/patterns/http/HttpRequest.java
HttpRequest.withHeader
public HttpRequest withHeader(String header, String value) { if(Strings.isValid(header)) { if(Strings.isValid(value)) { headers.put(header, value); } else { withoutHeader(header); } } return this; }
java
public HttpRequest withHeader(String header, String value) { if(Strings.isValid(header)) { if(Strings.isValid(value)) { headers.put(header, value); } else { withoutHeader(header); } } return this; }
[ "public", "HttpRequest", "withHeader", "(", "String", "header", ",", "String", "value", ")", "{", "if", "(", "Strings", ".", "isValid", "(", "header", ")", ")", "{", "if", "(", "Strings", ".", "isValid", "(", "value", ")", ")", "{", "headers", ".", "...
Sets the value of the given header, replacing whatever was already in there; if the value is null or empty, the header is dropped altogether. @param header the name of the header to set. @param value the new value for the header. @return the object itself, for method chaining.
[ "Sets", "the", "value", "of", "the", "given", "header", "replacing", "whatever", "was", "already", "in", "there", ";", "if", "the", "value", "is", "null", "or", "empty", "the", "header", "is", "dropped", "altogether", "." ]
train
https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/patterns/http/HttpRequest.java#L151-L160
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java
Retryer.exponentialWait
public Retryer<R> exponentialWait(final long multiplier, final long maximumWait) { checkArgument(multiplier > 0L, "multiplier must be > 0 but is %d", multiplier); checkArgument(maximumWait >= 0L, "maximumWait must be >= 0 but is %d", maximumWait); checkArgument(multiplier < maximumWait, "multiplier must be < maximumWait but is %d", multiplier); return withWaitStrategy(new WaitStrategy() { @Override public long computeSleepTime(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) { double exp = Math.pow(2, previousAttemptNumber); long result = Math.round(multiplier * exp); if (result > maximumWait) { result = maximumWait; } return result >= 0L ? result : 0L; } }); }
java
public Retryer<R> exponentialWait(final long multiplier, final long maximumWait) { checkArgument(multiplier > 0L, "multiplier must be > 0 but is %d", multiplier); checkArgument(maximumWait >= 0L, "maximumWait must be >= 0 but is %d", maximumWait); checkArgument(multiplier < maximumWait, "multiplier must be < maximumWait but is %d", multiplier); return withWaitStrategy(new WaitStrategy() { @Override public long computeSleepTime(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) { double exp = Math.pow(2, previousAttemptNumber); long result = Math.round(multiplier * exp); if (result > maximumWait) { result = maximumWait; } return result >= 0L ? result : 0L; } }); }
[ "public", "Retryer", "<", "R", ">", "exponentialWait", "(", "final", "long", "multiplier", ",", "final", "long", "maximumWait", ")", "{", "checkArgument", "(", "multiplier", ">", "0L", ",", "\"multiplier must be > 0 but is %d\"", ",", "multiplier", ")", ";", "ch...
Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt, and in exponentially incrementing amounts after each failed attempt up to the maximumTime. The wait time between the retries can be controlled by the multiplier. nextWaitTime = exponentialIncrement * {@code multiplier}. @param multiplier @param maximumTime the unit of the maximumTime is {@link TimeUnit#MILLISECONDS} @return
[ "Sets", "the", "wait", "strategy", "which", "sleeps", "for", "an", "exponential", "amount", "of", "time", "after", "the", "first", "failed", "attempt", "and", "in", "exponentially", "incrementing", "amounts", "after", "each", "failed", "attempt", "up", "to", "...
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java#L506-L522
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RouterClient.java
RouterClient.insertRouter
@BetaApi public final Operation insertRouter(ProjectRegionName region, Router routerResource) { InsertRouterHttpRequest request = InsertRouterHttpRequest.newBuilder() .setRegion(region == null ? null : region.toString()) .setRouterResource(routerResource) .build(); return insertRouter(request); }
java
@BetaApi public final Operation insertRouter(ProjectRegionName region, Router routerResource) { InsertRouterHttpRequest request = InsertRouterHttpRequest.newBuilder() .setRegion(region == null ? null : region.toString()) .setRouterResource(routerResource) .build(); return insertRouter(request); }
[ "@", "BetaApi", "public", "final", "Operation", "insertRouter", "(", "ProjectRegionName", "region", ",", "Router", "routerResource", ")", "{", "InsertRouterHttpRequest", "request", "=", "InsertRouterHttpRequest", ".", "newBuilder", "(", ")", ".", "setRegion", "(", "...
Creates a Router resource in the specified project and region using the data included in the request. <p>Sample code: <pre><code> try (RouterClient routerClient = RouterClient.create()) { ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]"); Router routerResource = Router.newBuilder().build(); Operation response = routerClient.insertRouter(region, routerResource); } </code></pre> @param region Name of the region for this request. @param routerResource Router resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "Router", "resource", "in", "the", "specified", "project", "and", "region", "using", "the", "data", "included", "in", "the", "request", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RouterClient.java#L747-L756
apache/groovy
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.fullyResolve
protected static GenericsType fullyResolve(GenericsType gt, Map<GenericsTypeName, GenericsType> placeholders) { GenericsType fromMap = placeholders.get(new GenericsTypeName(gt.getName())); if (gt.isPlaceholder() && fromMap != null) { gt = fromMap; } ClassNode type = fullyResolveType(gt.getType(), placeholders); ClassNode lowerBound = gt.getLowerBound(); if (lowerBound != null) lowerBound = fullyResolveType(lowerBound, placeholders); ClassNode[] upperBounds = gt.getUpperBounds(); if (upperBounds != null) { ClassNode[] copy = new ClassNode[upperBounds.length]; for (int i = 0, upperBoundsLength = upperBounds.length; i < upperBoundsLength; i++) { final ClassNode upperBound = upperBounds[i]; copy[i] = fullyResolveType(upperBound, placeholders); } upperBounds = copy; } GenericsType genericsType = new GenericsType(type, upperBounds, lowerBound); genericsType.setWildcard(gt.isWildcard()); return genericsType; }
java
protected static GenericsType fullyResolve(GenericsType gt, Map<GenericsTypeName, GenericsType> placeholders) { GenericsType fromMap = placeholders.get(new GenericsTypeName(gt.getName())); if (gt.isPlaceholder() && fromMap != null) { gt = fromMap; } ClassNode type = fullyResolveType(gt.getType(), placeholders); ClassNode lowerBound = gt.getLowerBound(); if (lowerBound != null) lowerBound = fullyResolveType(lowerBound, placeholders); ClassNode[] upperBounds = gt.getUpperBounds(); if (upperBounds != null) { ClassNode[] copy = new ClassNode[upperBounds.length]; for (int i = 0, upperBoundsLength = upperBounds.length; i < upperBoundsLength; i++) { final ClassNode upperBound = upperBounds[i]; copy[i] = fullyResolveType(upperBound, placeholders); } upperBounds = copy; } GenericsType genericsType = new GenericsType(type, upperBounds, lowerBound); genericsType.setWildcard(gt.isWildcard()); return genericsType; }
[ "protected", "static", "GenericsType", "fullyResolve", "(", "GenericsType", "gt", ",", "Map", "<", "GenericsTypeName", ",", "GenericsType", ">", "placeholders", ")", "{", "GenericsType", "fromMap", "=", "placeholders", ".", "get", "(", "new", "GenericsTypeName", "...
Given a generics type representing SomeClass&lt;T,V&gt; and a resolved placeholder map, returns a new generics type for which placeholders are resolved recursively.
[ "Given", "a", "generics", "type", "representing", "SomeClass&lt", ";", "T", "V&gt", ";", "and", "a", "resolved", "placeholder", "map", "returns", "a", "new", "generics", "type", "for", "which", "placeholders", "are", "resolved", "recursively", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L1362-L1383
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/CertificatesInner.java
CertificatesInner.createOrUpdate
public IntegrationAccountCertificateInner createOrUpdate(String resourceGroupName, String integrationAccountName, String certificateName, IntegrationAccountCertificateInner certificate) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, certificateName, certificate).toBlocking().single().body(); }
java
public IntegrationAccountCertificateInner createOrUpdate(String resourceGroupName, String integrationAccountName, String certificateName, IntegrationAccountCertificateInner certificate) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, certificateName, certificate).toBlocking().single().body(); }
[ "public", "IntegrationAccountCertificateInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "certificateName", ",", "IntegrationAccountCertificateInner", "certificate", ")", "{", "return", "createOrUpdateWithServic...
Creates or updates an integration account certificate. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param certificateName The integration account certificate name. @param certificate The integration account certificate. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the IntegrationAccountCertificateInner object if successful.
[ "Creates", "or", "updates", "an", "integration", "account", "certificate", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/CertificatesInner.java#L436-L438
soi-toolkit/soi-toolkit-mule
tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/model/ModelFactory.java
ModelFactory.doCreateNewModel
private static IModel doCreateNewModel(String groupId, String artifactId, String version, String service, MuleVersionEnum muleVersion, DeploymentModelEnum deploymentModel, List<TransportEnum> transports, TransportEnum inboundTransport, TransportEnum outboundTransport, TransformerEnum transformerType, String serviceDescriptor, List<String> operations) { try { DefaultModelImpl m = (DefaultModelImpl)modelClass.newInstance(); m.initModel(groupId, artifactId, version, service, muleVersion, deploymentModel, transports, inboundTransport, outboundTransport, transformerType, serviceDescriptor, operations); return m; } catch (Exception e) { throw new RuntimeException(e); } }
java
private static IModel doCreateNewModel(String groupId, String artifactId, String version, String service, MuleVersionEnum muleVersion, DeploymentModelEnum deploymentModel, List<TransportEnum> transports, TransportEnum inboundTransport, TransportEnum outboundTransport, TransformerEnum transformerType, String serviceDescriptor, List<String> operations) { try { DefaultModelImpl m = (DefaultModelImpl)modelClass.newInstance(); m.initModel(groupId, artifactId, version, service, muleVersion, deploymentModel, transports, inboundTransport, outboundTransport, transformerType, serviceDescriptor, operations); return m; } catch (Exception e) { throw new RuntimeException(e); } }
[ "private", "static", "IModel", "doCreateNewModel", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "version", ",", "String", "service", ",", "MuleVersionEnum", "muleVersion", ",", "DeploymentModelEnum", "deploymentModel", ",", "List", "<", "Tra...
Constructor-method to use when service descriptors are required (e.g. schema and wsdl for services) @param groupId @param artifactId @param version @param service @param deploymentModel @param serviceDescriptor @param operations @return the new model instance
[ "Constructor", "-", "method", "to", "use", "when", "service", "descriptors", "are", "required", "(", "e", ".", "g", ".", "schema", "and", "wsdl", "for", "services", ")" ]
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/model/ModelFactory.java#L140-L148
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.countRegexpMatches
public static int countRegexpMatches(String str, String regexp) { if (isEmpty(str) || isEmpty(regexp)) { return 0; } Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(str); int i = 0; while (matcher.find()) { i++; } return i; }
java
public static int countRegexpMatches(String str, String regexp) { if (isEmpty(str) || isEmpty(regexp)) { return 0; } Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(str); int i = 0; while (matcher.find()) { i++; } return i; }
[ "public", "static", "int", "countRegexpMatches", "(", "String", "str", ",", "String", "regexp", ")", "{", "if", "(", "isEmpty", "(", "str", ")", "||", "isEmpty", "(", "regexp", ")", ")", "{", "return", "0", ";", "}", "Pattern", "pattern", "=", "Pattern...
<p>Counts how many times the regexp appears in the larger String.</p> <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p> <pre> GosuStringUtil.countMatches(null, *) = 0 GosuStringUtil.countMatches("", *) = 0 GosuStringUtil.countMatches("abba", null) = 0 GosuStringUtil.countMatches("abba", "") = 0 GosuStringUtil.countMatches("abba", "a") = 2 GosuStringUtil.countMatches("abba", "ab") = 1 GosuStringUtil.countMatches("abba", ".b") = 2 GosuStringUtil.countMatches("abba", "xxx") = 0 </pre> @param str the String to check, may be null @param regexp the regexp to count, may be null @return the number of occurrences, 0 if either String is <code>null</code>
[ "<p", ">", "Counts", "how", "many", "times", "the", "regexp", "appears", "in", "the", "larger", "String", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L4892-L4903
alkacon/opencms-core
src/org/opencms/jsp/CmsJspTagBundle.java
CmsJspTagBundle.findMatch
private static ResourceBundle findMatch(String basename, Locale pref) { ResourceBundle match = null; try { ResourceBundle bundle = CmsResourceBundleLoader.getBundle(basename, pref); match = bundle; } catch (MissingResourceException mre) { // ignored } return match; }
java
private static ResourceBundle findMatch(String basename, Locale pref) { ResourceBundle match = null; try { ResourceBundle bundle = CmsResourceBundleLoader.getBundle(basename, pref); match = bundle; } catch (MissingResourceException mre) { // ignored } return match; }
[ "private", "static", "ResourceBundle", "findMatch", "(", "String", "basename", ",", "Locale", "pref", ")", "{", "ResourceBundle", "match", "=", "null", ";", "try", "{", "ResourceBundle", "bundle", "=", "CmsResourceBundleLoader", ".", "getBundle", "(", "basename", ...
Gets the resource bundle with the given base name and preferred locale. @param basename the resource bundle base name @param pref the preferred locale
[ "Gets", "the", "resource", "bundle", "with", "the", "given", "base", "name", "and", "preferred", "locale", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagBundle.java#L190-L200
alkacon/opencms-core
src-gwt/org/opencms/ade/galleries/client/ui/CmsResultListItem.java
CmsResultListItem.createButton
private static CmsPushButton createButton(String imageClass, String title) { CmsPushButton result = new CmsPushButton(); result.setImageClass(imageClass); result.setButtonStyle(ButtonStyle.FONT_ICON, null); result.setTitle(title); return result; }
java
private static CmsPushButton createButton(String imageClass, String title) { CmsPushButton result = new CmsPushButton(); result.setImageClass(imageClass); result.setButtonStyle(ButtonStyle.FONT_ICON, null); result.setTitle(title); return result; }
[ "private", "static", "CmsPushButton", "createButton", "(", "String", "imageClass", ",", "String", "title", ")", "{", "CmsPushButton", "result", "=", "new", "CmsPushButton", "(", ")", ";", "result", ".", "setImageClass", "(", "imageClass", ")", ";", "result", "...
Creates a button for the list item.<p> @param imageClass the icon image class @param title the button title @return the button
[ "Creates", "a", "button", "for", "the", "list", "item", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsResultListItem.java#L140-L147
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/StringUtils.java
StringUtils.trimLeadingCharacter
public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuilder buf = new StringBuilder(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); }
java
public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuilder buf = new StringBuilder(str); while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) { buf.deleteCharAt(0); } return buf.toString(); }
[ "public", "static", "String", "trimLeadingCharacter", "(", "String", "str", ",", "char", "leadingCharacter", ")", "{", "if", "(", "!", "hasLength", "(", "str", ")", ")", "{", "return", "str", ";", "}", "StringBuilder", "buf", "=", "new", "StringBuilder", "...
Trim all occurrences of the supplied leading character from the given {@code String}. @param str the {@code String} to check @param leadingCharacter the leading character to be trimmed @return the trimmed {@code String}
[ "Trim", "all", "occurrences", "of", "the", "supplied", "leading", "character", "from", "the", "given", "{", "@code", "String", "}", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/StringUtils.java#L234-L243
onepf/OpenIAB
library/src/main/java/org/onepf/oms/util/Utils.java
Utils.hasRequestedPermission
public static boolean hasRequestedPermission(@NotNull Context context, @NotNull final String permission) { boolean hasRequestedPermission = false; if (TextUtils.isEmpty(permission)) { throw new IllegalArgumentException("Permission can't be null or empty."); } try { PackageInfo info = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); if (!CollectionUtils.isEmpty(info.requestedPermissions)) { for (String requestedPermission : info.requestedPermissions) { if (permission.equals(requestedPermission)) { hasRequestedPermission = true; break; } } } } catch (PackageManager.NameNotFoundException e) { Logger.e(e, "Error during checking permission ", permission); } Logger.d("hasRequestedPermission() is ", hasRequestedPermission, " for ", permission); return hasRequestedPermission; }
java
public static boolean hasRequestedPermission(@NotNull Context context, @NotNull final String permission) { boolean hasRequestedPermission = false; if (TextUtils.isEmpty(permission)) { throw new IllegalArgumentException("Permission can't be null or empty."); } try { PackageInfo info = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); if (!CollectionUtils.isEmpty(info.requestedPermissions)) { for (String requestedPermission : info.requestedPermissions) { if (permission.equals(requestedPermission)) { hasRequestedPermission = true; break; } } } } catch (PackageManager.NameNotFoundException e) { Logger.e(e, "Error during checking permission ", permission); } Logger.d("hasRequestedPermission() is ", hasRequestedPermission, " for ", permission); return hasRequestedPermission; }
[ "public", "static", "boolean", "hasRequestedPermission", "(", "@", "NotNull", "Context", "context", ",", "@", "NotNull", "final", "String", "permission", ")", "{", "boolean", "hasRequestedPermission", "=", "false", ";", "if", "(", "TextUtils", ".", "isEmpty", "(...
Checks if the AndroidManifest contains a permission. @param permission The permission to test. @return true if the permission is requested by the application.
[ "Checks", "if", "the", "AndroidManifest", "contains", "a", "permission", "." ]
train
https://github.com/onepf/OpenIAB/blob/90552d53c5303b322940d96a0c4b7cb797d78760/library/src/main/java/org/onepf/oms/util/Utils.java#L24-L46
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Index.java
Index.getObjects
public JSONObject getObjects(List<String> objectIDs, List<String> attributesToRetrieve, RequestOptions requestOptions) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (String id : objectIDs) { JSONObject request = new JSONObject(); request.put("indexName", this.indexName); request.put("objectID", id); request.put("attributesToRetrieve", encodeAttributes(attributesToRetrieve, false)); requests.put(request); } JSONObject body = new JSONObject(); body.put("requests", requests); return client.postRequest("/1/indexes/*/objects", body.toString(), false, false, requestOptions); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException(e.getMessage()); } }
java
public JSONObject getObjects(List<String> objectIDs, List<String> attributesToRetrieve, RequestOptions requestOptions) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (String id : objectIDs) { JSONObject request = new JSONObject(); request.put("indexName", this.indexName); request.put("objectID", id); request.put("attributesToRetrieve", encodeAttributes(attributesToRetrieve, false)); requests.put(request); } JSONObject body = new JSONObject(); body.put("requests", requests); return client.postRequest("/1/indexes/*/objects", body.toString(), false, false, requestOptions); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException(e.getMessage()); } }
[ "public", "JSONObject", "getObjects", "(", "List", "<", "String", ">", "objectIDs", ",", "List", "<", "String", ">", "attributesToRetrieve", ",", "RequestOptions", "requestOptions", ")", "throws", "AlgoliaException", "{", "try", "{", "JSONArray", "requests", "=", ...
Get several objects from this index @param objectIDs the array of unique identifier of objects to retrieve @param attributesToRetrieve contains the list of attributes to retrieve. @param requestOptions Options to pass to this request
[ "Get", "several", "objects", "from", "this", "index" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L312-L330
mpetazzoni/ttorrent
ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java
TrackerClient.fireAnnounceResponseEvent
protected void fireAnnounceResponseEvent(int complete, int incomplete, int interval, String hexInfoHash) { for (AnnounceResponseListener listener : this.listeners) { listener.handleAnnounceResponse(interval, complete, incomplete, hexInfoHash); } }
java
protected void fireAnnounceResponseEvent(int complete, int incomplete, int interval, String hexInfoHash) { for (AnnounceResponseListener listener : this.listeners) { listener.handleAnnounceResponse(interval, complete, incomplete, hexInfoHash); } }
[ "protected", "void", "fireAnnounceResponseEvent", "(", "int", "complete", ",", "int", "incomplete", ",", "int", "interval", ",", "String", "hexInfoHash", ")", "{", "for", "(", "AnnounceResponseListener", "listener", ":", "this", ".", "listeners", ")", "{", "list...
Fire the announce response event to all listeners. @param complete The number of seeders on this torrent. @param incomplete The number of leechers on this torrent. @param interval The announce interval requested by the tracker.
[ "Fire", "the", "announce", "response", "event", "to", "all", "listeners", "." ]
train
https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java#L199-L203
teatrove/teatrove
teaapps/src/main/java/org/teatrove/teaapps/contexts/StringContext.java
StringContext.splitString
public String[] splitString(String text, int maxChars) { String[] splitVals = {" "}; return splitString(text,maxChars,splitVals); }
java
public String[] splitString(String text, int maxChars) { String[] splitVals = {" "}; return splitString(text,maxChars,splitVals); }
[ "public", "String", "[", "]", "splitString", "(", "String", "text", ",", "int", "maxChars", ")", "{", "String", "[", "]", "splitVals", "=", "{", "\" \"", "}", ";", "return", "splitString", "(", "text", ",", "maxChars", ",", "splitVals", ")", ";", "}" ]
Split the given string on spaces ensuring the maximum number of characters in each token. @param text The value to split @param maxChars The maximum required characters in each split token @return The array of tokens from splitting the string @see #splitString(String, int, String[])
[ "Split", "the", "given", "string", "on", "spaces", "ensuring", "the", "maximum", "number", "of", "characters", "in", "each", "token", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaapps/src/main/java/org/teatrove/teaapps/contexts/StringContext.java#L471-L474
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/independentsamples/MannWhitney.java
MannWhitney.scoreToPvalue
private static double scoreToPvalue(double score, int n1, int n2) { /* if(n1<=10 && n2<=10) { //calculate it from tables too small values } */ double mean=n1*(n1+n2+1.0)/2.0; double variable=n1*n2*(n1+n2+1.0)/12.0; double z=(score-mean)/Math.sqrt(variable); return ContinuousDistributions.gaussCdf(z); }
java
private static double scoreToPvalue(double score, int n1, int n2) { /* if(n1<=10 && n2<=10) { //calculate it from tables too small values } */ double mean=n1*(n1+n2+1.0)/2.0; double variable=n1*n2*(n1+n2+1.0)/12.0; double z=(score-mean)/Math.sqrt(variable); return ContinuousDistributions.gaussCdf(z); }
[ "private", "static", "double", "scoreToPvalue", "(", "double", "score", ",", "int", "n1", ",", "int", "n2", ")", "{", "/*\n if(n1<=10 && n2<=10) {\n //calculate it from tables too small values\n }\n */", "double", "mean", "=", "n1", "*", "(",...
Returns the Pvalue for a particular score @param score @param n1 @param n2 @return
[ "Returns", "the", "Pvalue", "for", "a", "particular", "score" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/nonparametrics/independentsamples/MannWhitney.java#L133-L145
czyzby/gdx-lml
lml-uedi/src/main/java/com/github/czyzby/lml/uedi/LmlApplication.java
LmlApplication.addDefaultComponents
protected void addDefaultComponents() { // Creating components manually to speed up the start-up. final boolean mapSuper = context.isMapSuperTypes(); context.setMapSuperTypes(false); // Assets: final AssetManagerProvider assetManagerProvider = new AssetManagerProvider(); context.addProvider(assetManagerProvider); context.addDestructible(assetManagerProvider); final InjectingAssetManager assetManager = assetManagerProvider.getAssetManager(); context.addProvider(new BitmapFontProvider(assetManager)); context.addProvider(new ModelProvider(assetManager)); context.addProvider(new MusicProvider(assetManager)); context.addProvider(new Particle3dEffectProvider(assetManager)); context.addProvider(new ParticleEffectProvider(assetManager)); context.addProvider(new PixmapProvider(assetManager)); context.addProvider(new SoundProvider(assetManager)); context.addProvider(new TextureAtlasProvider(assetManager)); context.addProvider(new TextureProvider(assetManager)); // Collections: context.addProvider(new ArrayProvider<Object>()); context.addProvider(new ListProvider<Object>()); context.addProvider(new MapProvider<Object, Object>()); context.addProvider(new SetProvider<Object>()); // I18n: i18nBundleProvider = new I18NBundleProvider(assetManager); localePreference = new LocalePreference(i18nBundleProvider); i18nBundleProvider.setLocalePreference(localePreference); context.addProvider(i18nBundleProvider); context.addProperty(localePreference); context.addProvider(localePreference); // Logging: context.addProvider(new LoggerProvider()); // Preferences: context.addProvider(new PreferencesProvider()); // UI: final SpriteBatchProvider spriteBatchProvider = new SpriteBatchProvider(); context.addProvider(new BatchProvider(spriteBatchProvider)); context.addProvider(spriteBatchProvider); context.addDestructible(spriteBatchProvider); context.addProvider(new SkinProvider(assetManager)); final StageProvider stageProvider = new StageProvider(spriteBatchProvider.getBatch()); stage = stageProvider.getStage(); context.addProvider(stageProvider); if (includeMusicService()) { // Music: final MusicOnPreference musicOn = new MusicOnPreference(); final SoundOnPreference soundOn = new SoundOnPreference(); final MusicVolumePreference musicVolume = new MusicVolumePreference(); final SoundVolumePreference soundVolume = new SoundVolumePreference(); context.addProperty(musicOn); context.addProperty(soundOn); context.addProperty(musicVolume); context.addProperty(soundVolume); context.add(new MusicService(stage, musicOn, soundOn, musicVolume, soundVolume)); } context.setMapSuperTypes(mapSuper); // Application listener: context.add(this); }
java
protected void addDefaultComponents() { // Creating components manually to speed up the start-up. final boolean mapSuper = context.isMapSuperTypes(); context.setMapSuperTypes(false); // Assets: final AssetManagerProvider assetManagerProvider = new AssetManagerProvider(); context.addProvider(assetManagerProvider); context.addDestructible(assetManagerProvider); final InjectingAssetManager assetManager = assetManagerProvider.getAssetManager(); context.addProvider(new BitmapFontProvider(assetManager)); context.addProvider(new ModelProvider(assetManager)); context.addProvider(new MusicProvider(assetManager)); context.addProvider(new Particle3dEffectProvider(assetManager)); context.addProvider(new ParticleEffectProvider(assetManager)); context.addProvider(new PixmapProvider(assetManager)); context.addProvider(new SoundProvider(assetManager)); context.addProvider(new TextureAtlasProvider(assetManager)); context.addProvider(new TextureProvider(assetManager)); // Collections: context.addProvider(new ArrayProvider<Object>()); context.addProvider(new ListProvider<Object>()); context.addProvider(new MapProvider<Object, Object>()); context.addProvider(new SetProvider<Object>()); // I18n: i18nBundleProvider = new I18NBundleProvider(assetManager); localePreference = new LocalePreference(i18nBundleProvider); i18nBundleProvider.setLocalePreference(localePreference); context.addProvider(i18nBundleProvider); context.addProperty(localePreference); context.addProvider(localePreference); // Logging: context.addProvider(new LoggerProvider()); // Preferences: context.addProvider(new PreferencesProvider()); // UI: final SpriteBatchProvider spriteBatchProvider = new SpriteBatchProvider(); context.addProvider(new BatchProvider(spriteBatchProvider)); context.addProvider(spriteBatchProvider); context.addDestructible(spriteBatchProvider); context.addProvider(new SkinProvider(assetManager)); final StageProvider stageProvider = new StageProvider(spriteBatchProvider.getBatch()); stage = stageProvider.getStage(); context.addProvider(stageProvider); if (includeMusicService()) { // Music: final MusicOnPreference musicOn = new MusicOnPreference(); final SoundOnPreference soundOn = new SoundOnPreference(); final MusicVolumePreference musicVolume = new MusicVolumePreference(); final SoundVolumePreference soundVolume = new SoundVolumePreference(); context.addProperty(musicOn); context.addProperty(soundOn); context.addProperty(musicVolume); context.addProperty(soundVolume); context.add(new MusicService(stage, musicOn, soundOn, musicVolume, soundVolume)); } context.setMapSuperTypes(mapSuper); // Application listener: context.add(this); }
[ "protected", "void", "addDefaultComponents", "(", ")", "{", "// Creating components manually to speed up the start-up.", "final", "boolean", "mapSuper", "=", "context", ".", "isMapSuperTypes", "(", ")", ";", "context", ".", "setMapSuperTypes", "(", "false", ")", ";", ...
Registers multiple providers and singletons that produce LibGDX-related object instances.
[ "Registers", "multiple", "providers", "and", "singletons", "that", "produce", "LibGDX", "-", "related", "object", "instances", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/lml-uedi/src/main/java/com/github/czyzby/lml/uedi/LmlApplication.java#L181-L239
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.openapi/src/com/ibm/ws/microprofile/openapi/impl/validation/ServerValidator.java
ServerValidator.validateServerVariables
private void validateServerVariables(ValidationHelper helper, Context context, Set<String> variables, Server t) { ServerVariables serverVariables = t.getVariables(); for (String variable : variables) { if (serverVariables == null || !serverVariables.containsKey(variable)) { final String message = Tr.formatMessage(tc, "serverVariableNotDefined", variable); helper.addValidationEvent(new ValidationEvent(ValidationEvent.Severity.ERROR, context.getLocation("variables"), message)); } } }
java
private void validateServerVariables(ValidationHelper helper, Context context, Set<String> variables, Server t) { ServerVariables serverVariables = t.getVariables(); for (String variable : variables) { if (serverVariables == null || !serverVariables.containsKey(variable)) { final String message = Tr.formatMessage(tc, "serverVariableNotDefined", variable); helper.addValidationEvent(new ValidationEvent(ValidationEvent.Severity.ERROR, context.getLocation("variables"), message)); } } }
[ "private", "void", "validateServerVariables", "(", "ValidationHelper", "helper", ",", "Context", "context", ",", "Set", "<", "String", ">", "variables", ",", "Server", "t", ")", "{", "ServerVariables", "serverVariables", "=", "t", ".", "getVariables", "(", ")", ...
Ensures that all the serverVariables are defined @param helper the helper to send validation messages @param variables the set of variables to validate
[ "Ensures", "that", "all", "the", "serverVariables", "are", "defined" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.openapi/src/com/ibm/ws/microprofile/openapi/impl/validation/ServerValidator.java#L61-L70
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgSeqend.java
DwgSeqend.readDwgSeqendV15
public void readDwgSeqendV15(int[] data, int offset) throws Exception { int bitPos = offset; bitPos = readObjectHeaderV15(data, bitPos); bitPos = readObjectTailV15(data, bitPos); }
java
public void readDwgSeqendV15(int[] data, int offset) throws Exception { int bitPos = offset; bitPos = readObjectHeaderV15(data, bitPos); bitPos = readObjectTailV15(data, bitPos); }
[ "public", "void", "readDwgSeqendV15", "(", "int", "[", "]", "data", ",", "int", "offset", ")", "throws", "Exception", "{", "int", "bitPos", "=", "offset", ";", "bitPos", "=", "readObjectHeaderV15", "(", "data", ",", "bitPos", ")", ";", "bitPos", "=", "re...
Read a Seqend in the DWG format Version 15 @param data Array of unsigned bytes obtained from the DWG binary file @param offset The current bit offset where the value begins @throws Exception If an unexpected bit value is found in the DWG file. Occurs when we are looking for LwPolylines.
[ "Read", "a", "Seqend", "in", "the", "DWG", "format", "Version", "15" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgSeqend.java#L38-L42
lucee/Lucee
core/src/main/java/lucee/runtime/tag/Video.java
Video.setNameconflict
public void setNameconflict(String nameconflict) throws PageException { nameconflict = nameconflict.toLowerCase().trim(); if ("error".equals(nameconflict)) this.nameconflict = NAMECONFLICT_ERROR; else if ("skip".equals(nameconflict)) this.nameconflict = NAMECONFLICT_SKIP; else if ("overwrite".equals(nameconflict)) this.nameconflict = NAMECONFLICT_OVERWRITE; else if ("makeunique".equals(nameconflict)) this.nameconflict = NAMECONFLICT_MAKEUNIQUE; else throw doThrow("invalid value for attribute nameconflict [" + nameconflict + "]", "valid values are [error,skip,overwrite,makeunique]"); }
java
public void setNameconflict(String nameconflict) throws PageException { nameconflict = nameconflict.toLowerCase().trim(); if ("error".equals(nameconflict)) this.nameconflict = NAMECONFLICT_ERROR; else if ("skip".equals(nameconflict)) this.nameconflict = NAMECONFLICT_SKIP; else if ("overwrite".equals(nameconflict)) this.nameconflict = NAMECONFLICT_OVERWRITE; else if ("makeunique".equals(nameconflict)) this.nameconflict = NAMECONFLICT_MAKEUNIQUE; else throw doThrow("invalid value for attribute nameconflict [" + nameconflict + "]", "valid values are [error,skip,overwrite,makeunique]"); }
[ "public", "void", "setNameconflict", "(", "String", "nameconflict", ")", "throws", "PageException", "{", "nameconflict", "=", "nameconflict", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", ";", "if", "(", "\"error\"", ".", "equals", "(", "nameconflict", ...
set the value nameconflict Action to take if filename is the same as that of a file in the directory. @param nameconflict value to set @throws ApplicationException
[ "set", "the", "value", "nameconflict", "Action", "to", "take", "if", "filename", "is", "the", "same", "as", "that", "of", "a", "file", "in", "the", "directory", "." ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/tag/Video.java#L221-L228
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.skewDivergence
public static <E> double skewDivergence(Counter<E> c1, Counter<E> c2, double skew) { Counter<E> average = linearCombination(c2, skew, c1, (1.0 - skew)); return klDivergence(c1, average); }
java
public static <E> double skewDivergence(Counter<E> c1, Counter<E> c2, double skew) { Counter<E> average = linearCombination(c2, skew, c1, (1.0 - skew)); return klDivergence(c1, average); }
[ "public", "static", "<", "E", ">", "double", "skewDivergence", "(", "Counter", "<", "E", ">", "c1", ",", "Counter", "<", "E", ">", "c2", ",", "double", "skew", ")", "{", "Counter", "<", "E", ">", "average", "=", "linearCombination", "(", "c2", ",", ...
Calculates the skew divergence between the two counters. That is, it calculates KL(c1 || (c2*skew + c1*(1-skew))) . In other words, how well can c1 be represented by a "smoothed" c2. @return The skew divergence between the distributions
[ "Calculates", "the", "skew", "divergence", "between", "the", "two", "counters", ".", "That", "is", "it", "calculates", "KL", "(", "c1", "||", "(", "c2", "*", "skew", "+", "c1", "*", "(", "1", "-", "skew", ")))", ".", "In", "other", "words", "how", ...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L1248-L1251
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/AcroFields.java
AcroFields.extractRevision
public InputStream extractRevision(String field) throws IOException { getSignatureNames(); field = getTranslatedFieldName(field); if (!sigNames.containsKey(field)) return null; int length = ((int[])sigNames.get(field))[0]; RandomAccessFileOrArray raf = reader.getSafeFile(); raf.reOpen(); raf.seek(0); return new RevisionStream(raf, length); }
java
public InputStream extractRevision(String field) throws IOException { getSignatureNames(); field = getTranslatedFieldName(field); if (!sigNames.containsKey(field)) return null; int length = ((int[])sigNames.get(field))[0]; RandomAccessFileOrArray raf = reader.getSafeFile(); raf.reOpen(); raf.seek(0); return new RevisionStream(raf, length); }
[ "public", "InputStream", "extractRevision", "(", "String", "field", ")", "throws", "IOException", "{", "getSignatureNames", "(", ")", ";", "field", "=", "getTranslatedFieldName", "(", "field", ")", ";", "if", "(", "!", "sigNames", ".", "containsKey", "(", "fie...
Extracts a revision from the document. @param field the signature field name @return an <CODE>InputStream</CODE> covering the revision. Returns <CODE>null</CODE> if it's not a signature field @throws IOException on error
[ "Extracts", "a", "revision", "from", "the", "document", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/AcroFields.java#L2280-L2290
ksclarke/vertx-pairtree
src/main/java/info/freelibrary/pairtree/PairtreeUtils.java
PairtreeUtils.mapToPtPath
public static String mapToPtPath(final String aBasePath, final String aID) { return concat(aBasePath, mapToPtPath(aID), null); }
java
public static String mapToPtPath(final String aBasePath, final String aID) { return concat(aBasePath, mapToPtPath(aID), null); }
[ "public", "static", "String", "mapToPtPath", "(", "final", "String", "aBasePath", ",", "final", "String", "aID", ")", "{", "return", "concat", "(", "aBasePath", ",", "mapToPtPath", "(", "aID", ")", ",", "null", ")", ";", "}" ]
Maps the supplied ID to a Pairtree path using the supplied base path. @param aID An ID to map to a Pairtree path @param aBasePath The base path to use in the mapping @return The Pairtree path for the supplied ID
[ "Maps", "the", "supplied", "ID", "to", "a", "Pairtree", "path", "using", "the", "supplied", "base", "path", "." ]
train
https://github.com/ksclarke/vertx-pairtree/blob/b2ea1e32057e5df262e9265540d346a732b718df/src/main/java/info/freelibrary/pairtree/PairtreeUtils.java#L164-L166
knowm/XChange
xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java
WexAdapters.adaptOrderInfo
public static LimitOrder adaptOrderInfo(String orderId, WexOrderInfoResult orderInfo) { OrderType orderType = orderInfo.getType() == WexOrderInfoResult.Type.buy ? OrderType.BID : OrderType.ASK; BigDecimal price = orderInfo.getRate(); Date timestamp = DateUtils.fromMillisUtc(orderInfo.getTimestampCreated() * 1000L); CurrencyPair currencyPair = adaptCurrencyPair(orderInfo.getPair()); OrderStatus orderStatus = null; switch (orderInfo.getStatus()) { case 0: if (orderInfo.getAmount().compareTo(orderInfo.getStartAmount()) == 0) { orderStatus = OrderStatus.NEW; } else { orderStatus = OrderStatus.PARTIALLY_FILLED; } break; case 1: orderStatus = OrderStatus.FILLED; break; case 2: case 3: orderStatus = OrderStatus.CANCELED; break; } return new LimitOrder( orderType, orderInfo.getStartAmount(), currencyPair, orderId, timestamp, price, price, orderInfo.getStartAmount().subtract(orderInfo.getAmount()), null, orderStatus); }
java
public static LimitOrder adaptOrderInfo(String orderId, WexOrderInfoResult orderInfo) { OrderType orderType = orderInfo.getType() == WexOrderInfoResult.Type.buy ? OrderType.BID : OrderType.ASK; BigDecimal price = orderInfo.getRate(); Date timestamp = DateUtils.fromMillisUtc(orderInfo.getTimestampCreated() * 1000L); CurrencyPair currencyPair = adaptCurrencyPair(orderInfo.getPair()); OrderStatus orderStatus = null; switch (orderInfo.getStatus()) { case 0: if (orderInfo.getAmount().compareTo(orderInfo.getStartAmount()) == 0) { orderStatus = OrderStatus.NEW; } else { orderStatus = OrderStatus.PARTIALLY_FILLED; } break; case 1: orderStatus = OrderStatus.FILLED; break; case 2: case 3: orderStatus = OrderStatus.CANCELED; break; } return new LimitOrder( orderType, orderInfo.getStartAmount(), currencyPair, orderId, timestamp, price, price, orderInfo.getStartAmount().subtract(orderInfo.getAmount()), null, orderStatus); }
[ "public", "static", "LimitOrder", "adaptOrderInfo", "(", "String", "orderId", ",", "WexOrderInfoResult", "orderInfo", ")", "{", "OrderType", "orderType", "=", "orderInfo", ".", "getType", "(", ")", "==", "WexOrderInfoResult", ".", "Type", ".", "buy", "?", "Order...
Adapts a WexOrderInfoResult to a LimitOrder @param orderId Order original id @param orderInfo @return
[ "Adapts", "a", "WexOrderInfoResult", "to", "a", "LimitOrder" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java#L235-L271
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
MutableBigInteger.divideAndRemainderBurnikelZiegler
MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) { int r = intLen; int s = b.intLen; // Clear the quotient quotient.offset = quotient.intLen = 0; if (r < s) { return this; } else { // Unlike Knuth division, we don't check for common powers of two here because // BZ already runs faster if both numbers contain powers of two and cancelling them has no // additional benefit. // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s} int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD)); int j = (s+m-1) / m; // step 2a: j = ceil(s/m) int n = j * m; // step 2b: block length in 32-bit units long n32 = 32L * n; // block length in bits int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n} MutableBigInteger bShifted = new MutableBigInteger(b); bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n safeLeftShift(sigma); // step 4b: shift this by the same amount // step 5: t is the number of blocks needed to accommodate this plus one additional bit int t = (int) ((bitLength()+n32) / n32); if (t < 2) { t = 2; } // step 6: conceptually split this into blocks a[t-1], ..., a[0] MutableBigInteger a1 = getBlock(t-1, t, n); // the most significant block of this // step 7: z[t-2] = [a[t-1], a[t-2]] MutableBigInteger z = getBlock(t-2, t, n); // the second to most significant block z.addDisjoint(a1, n); // z[t-2] // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers MutableBigInteger qi = new MutableBigInteger(); MutableBigInteger ri; for (int i=t-2; i > 0; i--) { // step 8a: compute (qi,ri) such that z=b*qi+ri ri = z.divide2n1n(bShifted, qi); // step 8b: z = [ri, a[i-1]] z = getBlock(i-1, t, n); // a[i-1] z.addDisjoint(ri, n); quotient.addShifted(qi, i*n); // update q (part of step 9) } // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged ri = z.divide2n1n(bShifted, qi); quotient.add(qi); ri.rightShift(sigma); // step 9: this and b were shifted, so shift back return ri; } }
java
MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) { int r = intLen; int s = b.intLen; // Clear the quotient quotient.offset = quotient.intLen = 0; if (r < s) { return this; } else { // Unlike Knuth division, we don't check for common powers of two here because // BZ already runs faster if both numbers contain powers of two and cancelling them has no // additional benefit. // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s} int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD)); int j = (s+m-1) / m; // step 2a: j = ceil(s/m) int n = j * m; // step 2b: block length in 32-bit units long n32 = 32L * n; // block length in bits int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n} MutableBigInteger bShifted = new MutableBigInteger(b); bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n safeLeftShift(sigma); // step 4b: shift this by the same amount // step 5: t is the number of blocks needed to accommodate this plus one additional bit int t = (int) ((bitLength()+n32) / n32); if (t < 2) { t = 2; } // step 6: conceptually split this into blocks a[t-1], ..., a[0] MutableBigInteger a1 = getBlock(t-1, t, n); // the most significant block of this // step 7: z[t-2] = [a[t-1], a[t-2]] MutableBigInteger z = getBlock(t-2, t, n); // the second to most significant block z.addDisjoint(a1, n); // z[t-2] // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers MutableBigInteger qi = new MutableBigInteger(); MutableBigInteger ri; for (int i=t-2; i > 0; i--) { // step 8a: compute (qi,ri) such that z=b*qi+ri ri = z.divide2n1n(bShifted, qi); // step 8b: z = [ri, a[i-1]] z = getBlock(i-1, t, n); // a[i-1] z.addDisjoint(ri, n); quotient.addShifted(qi, i*n); // update q (part of step 9) } // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged ri = z.divide2n1n(bShifted, qi); quotient.add(qi); ri.rightShift(sigma); // step 9: this and b were shifted, so shift back return ri; } }
[ "MutableBigInteger", "divideAndRemainderBurnikelZiegler", "(", "MutableBigInteger", "b", ",", "MutableBigInteger", "quotient", ")", "{", "int", "r", "=", "intLen", ";", "int", "s", "=", "b", ".", "intLen", ";", "// Clear the quotient", "quotient", ".", "offset", "...
Computes {@code this/b} and {@code this%b} using the <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>. This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper. The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are multiples of 32 bits.<br/> {@code this} and {@code b} must be nonnegative. @param b the divisor @param quotient output parameter for {@code this/b} @return the remainder
[ "Computes", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java#L1241-L1298
apereo/cas
support/cas-server-support-cosmosdb-core/src/main/java/org/apereo/cas/cosmosdb/CosmosDbObjectFactory.java
CosmosDbObjectFactory.getDocumentLink
public static String getDocumentLink(final String databaseName, final String collectionName, final String documentId) { return getCollectionLink(databaseName, collectionName) + "/docs/" + documentId; }
java
public static String getDocumentLink(final String databaseName, final String collectionName, final String documentId) { return getCollectionLink(databaseName, collectionName) + "/docs/" + documentId; }
[ "public", "static", "String", "getDocumentLink", "(", "final", "String", "databaseName", ",", "final", "String", "collectionName", ",", "final", "String", "documentId", ")", "{", "return", "getCollectionLink", "(", "databaseName", ",", "collectionName", ")", "+", ...
Gets document link. @param databaseName the database name @param collectionName the collection name @param documentId the document id @return the document link
[ "Gets", "document", "link", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-cosmosdb-core/src/main/java/org/apereo/cas/cosmosdb/CosmosDbObjectFactory.java#L62-L64
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupsInner.java
NetworkSecurityGroupsInner.createOrUpdate
public NetworkSecurityGroupInner createOrUpdate(String resourceGroupName, String networkSecurityGroupName, NetworkSecurityGroupInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, parameters).toBlocking().last().body(); }
java
public NetworkSecurityGroupInner createOrUpdate(String resourceGroupName, String networkSecurityGroupName, NetworkSecurityGroupInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, parameters).toBlocking().last().body(); }
[ "public", "NetworkSecurityGroupInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "networkSecurityGroupName", ",", "NetworkSecurityGroupInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "...
Creates or updates a network security group in the specified resource group. @param resourceGroupName The name of the resource group. @param networkSecurityGroupName The name of the network security group. @param parameters Parameters supplied to the create or update network security group operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the NetworkSecurityGroupInner object if successful.
[ "Creates", "or", "updates", "a", "network", "security", "group", "in", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupsInner.java#L444-L446
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/Utils.java
Utils.getGroupIds
GroupIds getGroupIds(Node groupNode) throws RepositoryException { String storagePath = getGroupStoragePath(); String nodePath = groupNode.getPath(); String groupId = nodePath.substring(storagePath.length()); String parentId = groupId.substring(0, groupId.lastIndexOf("/")); return new GroupIds(groupId, parentId); }
java
GroupIds getGroupIds(Node groupNode) throws RepositoryException { String storagePath = getGroupStoragePath(); String nodePath = groupNode.getPath(); String groupId = nodePath.substring(storagePath.length()); String parentId = groupId.substring(0, groupId.lastIndexOf("/")); return new GroupIds(groupId, parentId); }
[ "GroupIds", "getGroupIds", "(", "Node", "groupNode", ")", "throws", "RepositoryException", "{", "String", "storagePath", "=", "getGroupStoragePath", "(", ")", ";", "String", "nodePath", "=", "groupNode", ".", "getPath", "(", ")", ";", "String", "groupId", "=", ...
Evaluate the group identifier and parent group identifier based on group node path.
[ "Evaluate", "the", "group", "identifier", "and", "parent", "group", "identifier", "based", "on", "group", "node", "path", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/Utils.java#L219-L228
casmi/casmi
src/main/java/casmi/graphics/color/CMYKColor.java
CMYKColor.lerpColor
public static Color lerpColor(CMYKColor color1, CMYKColor color2, double amt) { double cyan, magenta, yellow, black, alpha; cyan = color2.cyan * amt + color1.cyan * (1.0 - amt); magenta = color2.magenta * amt + color1.magenta * (1.0 - amt); yellow = color2.yellow * amt + color1.yellow * (1.0 - amt); black = color2.black * amt + color1.black * (1.0 - amt); alpha = color2.alpha * amt + color1.alpha * (1.0 - amt); return new CMYKColor(cyan, magenta, yellow, black, alpha); }
java
public static Color lerpColor(CMYKColor color1, CMYKColor color2, double amt) { double cyan, magenta, yellow, black, alpha; cyan = color2.cyan * amt + color1.cyan * (1.0 - amt); magenta = color2.magenta * amt + color1.magenta * (1.0 - amt); yellow = color2.yellow * amt + color1.yellow * (1.0 - amt); black = color2.black * amt + color1.black * (1.0 - amt); alpha = color2.alpha * amt + color1.alpha * (1.0 - amt); return new CMYKColor(cyan, magenta, yellow, black, alpha); }
[ "public", "static", "Color", "lerpColor", "(", "CMYKColor", "color1", ",", "CMYKColor", "color2", ",", "double", "amt", ")", "{", "double", "cyan", ",", "magenta", ",", "yellow", ",", "black", ",", "alpha", ";", "cyan", "=", "color2", ".", "cyan", "*", ...
Calculates a color or colors between two color at a specific increment. @param color1 interpolate from this color @param color2 interpolate to this color @param amt between 0.0 and 1.0 @return The calculated color values.
[ "Calculates", "a", "color", "or", "colors", "between", "two", "color", "at", "a", "specific", "increment", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/color/CMYKColor.java#L181-L189
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/user/UserCoreDao.java
UserCoreDao.buildWhere
public String buildWhere(String field, ColumnValue value) { String where; if (value != null) { if (value.getValue() != null && value.getTolerance() != null) { if (!(value.getValue() instanceof Number)) { throw new GeoPackageException( "Field value is not a number and can not use a tolerance, Field: " + field + ", Value: " + value); } String quotedField = CoreSQLUtils.quoteWrap(field); where = quotedField + " >= ? AND " + quotedField + " <= ?"; } else { where = buildWhere(field, value.getValue()); } } else { where = buildWhere(field, null, null); } return where; }
java
public String buildWhere(String field, ColumnValue value) { String where; if (value != null) { if (value.getValue() != null && value.getTolerance() != null) { if (!(value.getValue() instanceof Number)) { throw new GeoPackageException( "Field value is not a number and can not use a tolerance, Field: " + field + ", Value: " + value); } String quotedField = CoreSQLUtils.quoteWrap(field); where = quotedField + " >= ? AND " + quotedField + " <= ?"; } else { where = buildWhere(field, value.getValue()); } } else { where = buildWhere(field, null, null); } return where; }
[ "public", "String", "buildWhere", "(", "String", "field", ",", "ColumnValue", "value", ")", "{", "String", "where", ";", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "value", ".", "getValue", "(", ")", "!=", "null", "&&", "value", ".", "get...
Build where (or selection) statement for a single field @param field field name @param value column value @return where clause
[ "Build", "where", "(", "or", "selection", ")", "statement", "for", "a", "single", "field" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/user/UserCoreDao.java#L729-L747
OwlPlatform/java-owl-solver
src/main/java/com/owlplatform/solver/SolverAggregatorInterface.java
SolverAggregatorInterface.exceptionCaught
protected void exceptionCaught(IoSession session, Throwable cause) { log.error("Unhandled exception for: " + String.valueOf(session), cause); if (this.disconnectOnException) { this._disconnect(); } }
java
protected void exceptionCaught(IoSession session, Throwable cause) { log.error("Unhandled exception for: " + String.valueOf(session), cause); if (this.disconnectOnException) { this._disconnect(); } }
[ "protected", "void", "exceptionCaught", "(", "IoSession", "session", ",", "Throwable", "cause", ")", "{", "log", ".", "error", "(", "\"Unhandled exception for: \"", "+", "String", ".", "valueOf", "(", "session", ")", ",", "cause", ")", ";", "if", "(", "this"...
Called when an exception occurs on the session @param session the session on which the exception occurred @param cause the exception
[ "Called", "when", "an", "exception", "occurs", "on", "the", "session" ]
train
https://github.com/OwlPlatform/java-owl-solver/blob/53a1faabd63613c716203922cd52f871e5fedb9b/src/main/java/com/owlplatform/solver/SolverAggregatorInterface.java#L827-L832
OpenLiberty/open-liberty
dev/com.ibm.ws.security.audit.reader/src/com/ibm/ws/security/audit/reader/tasks/BaseCommandTask.java
BaseCommandTask.promptForText
private String promptForText(ConsoleWrapper stdin, PrintStream stdout, String enterText, String reenterText, String readError, String entriesDidNotMatch) { String read1 = stdin.readMaskedText(getMessage(enterText) + " "); String read2 = stdin.readMaskedText(getMessage(reenterText) + " "); if (read1 == null && read2 == null) { throw new IllegalArgumentException("Unable to read either entry. Aborting prompt."); } else if (read1 == null || read2 == null) { stdout.println(getMessage(readError)); return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch); } else if (read1.equals(read2)) { return read1; } else { stdout.println(getMessage(entriesDidNotMatch)); return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch); } }
java
private String promptForText(ConsoleWrapper stdin, PrintStream stdout, String enterText, String reenterText, String readError, String entriesDidNotMatch) { String read1 = stdin.readMaskedText(getMessage(enterText) + " "); String read2 = stdin.readMaskedText(getMessage(reenterText) + " "); if (read1 == null && read2 == null) { throw new IllegalArgumentException("Unable to read either entry. Aborting prompt."); } else if (read1 == null || read2 == null) { stdout.println(getMessage(readError)); return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch); } else if (read1.equals(read2)) { return read1; } else { stdout.println(getMessage(entriesDidNotMatch)); return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch); } }
[ "private", "String", "promptForText", "(", "ConsoleWrapper", "stdin", ",", "PrintStream", "stdout", ",", "String", "enterText", ",", "String", "reenterText", ",", "String", "readError", ",", "String", "entriesDidNotMatch", ")", "{", "String", "read1", "=", "stdin"...
Prompt the user to enter text. Prompts twice and compares to ensure it was entered correctly. @return Entered String
[ "Prompt", "the", "user", "to", "enter", "text", ".", "Prompts", "twice", "and", "compares", "to", "ensure", "it", "was", "entered", "correctly", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.audit.reader/src/com/ibm/ws/security/audit/reader/tasks/BaseCommandTask.java#L203-L219
james-hu/jabb-core
src/main/java/net/sf/jabb/quartz/SchedulerUtility.java
SchedulerUtility.convertDataMapToText
public static String convertDataMapToText(Map<String, Object> dataMap){ StringBuilder sb = new StringBuilder(); for (Entry<String, Object> entry: dataMap.entrySet()){ sb.append(entry.getKey()).append("=").append(entry.getValue()); sb.append('\n'); } return sb.toString(); }
java
public static String convertDataMapToText(Map<String, Object> dataMap){ StringBuilder sb = new StringBuilder(); for (Entry<String, Object> entry: dataMap.entrySet()){ sb.append(entry.getKey()).append("=").append(entry.getValue()); sb.append('\n'); } return sb.toString(); }
[ "public", "static", "String", "convertDataMapToText", "(", "Map", "<", "String", ",", "Object", ">", "dataMap", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Entry", "<", "String", ",", "Object", ">", "entry", ...
Convert JobDataMap into text in properties file format @param dataMap the JobDataMap @return a text in properties file format
[ "Convert", "JobDataMap", "into", "text", "in", "properties", "file", "format" ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/quartz/SchedulerUtility.java#L75-L82
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/dialects/DefaultDialect.java
DefaultDialect.selectStarParametrized
@Override public String selectStarParametrized(String table, String ... parameters) { StringBuilder sql = new StringBuilder().append("SELECT * FROM ").append(table).append(" WHERE "); join(sql, parameters, " = ? AND "); sql.append(" = ?"); return sql.toString(); }
java
@Override public String selectStarParametrized(String table, String ... parameters) { StringBuilder sql = new StringBuilder().append("SELECT * FROM ").append(table).append(" WHERE "); join(sql, parameters, " = ? AND "); sql.append(" = ?"); return sql.toString(); }
[ "@", "Override", "public", "String", "selectStarParametrized", "(", "String", "table", ",", "String", "...", "parameters", ")", "{", "StringBuilder", "sql", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\"SELECT * FROM \"", ")", ".", "append", "(...
Produces a parametrized AND query. Example: <pre> String sql = dialect.selectStarParametrized("people", "name", "ssn", "dob"); //generates: //SELECT * FROM people WHERE name = ? AND ssn = ? AND dob = ? </pre> @param table name of table @param parameters list of parameter names @return something like: "select * from table_name where name = ? and last_name = ? ..."
[ "Produces", "a", "parametrized", "AND", "query", ".", "Example", ":", "<pre", ">", "String", "sql", "=", "dialect", ".", "selectStarParametrized", "(", "people", "name", "ssn", "dob", ")", ";", "//", "generates", ":", "//", "SELECT", "*", "FROM", "people",...
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/dialects/DefaultDialect.java#L71-L77
aws/aws-sdk-java
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/CreateProvisioningArtifactResult.java
CreateProvisioningArtifactResult.withInfo
public CreateProvisioningArtifactResult withInfo(java.util.Map<String, String> info) { setInfo(info); return this; }
java
public CreateProvisioningArtifactResult withInfo(java.util.Map<String, String> info) { setInfo(info); return this; }
[ "public", "CreateProvisioningArtifactResult", "withInfo", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "info", ")", "{", "setInfo", "(", "info", ")", ";", "return", "this", ";", "}" ]
<p> The URL of the CloudFormation template in Amazon S3, in JSON format. </p> @param info The URL of the CloudFormation template in Amazon S3, in JSON format. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "URL", "of", "the", "CloudFormation", "template", "in", "Amazon", "S3", "in", "JSON", "format", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/CreateProvisioningArtifactResult.java#L120-L123
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.clickLongOnTextAndPress
public void clickLongOnTextAndPress(String text, int index) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickLongOnTextAndPress(\""+text+"\", "+index+")"); } clicker.clickLongOnTextAndPress(text, index); }
java
public void clickLongOnTextAndPress(String text, int index) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickLongOnTextAndPress(\""+text+"\", "+index+")"); } clicker.clickLongOnTextAndPress(text, index); }
[ "public", "void", "clickLongOnTextAndPress", "(", "String", "text", ",", "int", "index", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"clickLongOnTextAndPress(\\\"\"", "+", "te...
Long clicks a View displaying the specified text and then selects an item from the context menu that appears. Will automatically scroll when needed. @param text the text to click. The parameter will be interpreted as a regular expression @param index the index of the menu item to press. {@code 0} if only one is available
[ "Long", "clicks", "a", "View", "displaying", "the", "specified", "text", "and", "then", "selects", "an", "item", "from", "the", "context", "menu", "that", "appears", ".", "Will", "automatically", "scroll", "when", "needed", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L1619-L1625
alkacon/opencms-core
src/org/opencms/cmis/CmsCmisResourceHelper.java
CmsCmisResourceHelper.deleteObject
public synchronized void deleteObject(CmsCmisCallContext context, String objectId, boolean allVersions) { try { CmsObject cms = m_repository.getCmsObject(context); CmsUUID structureId = new CmsUUID(objectId); CmsResource resource = cms.readResource(structureId); if (resource.isFolder()) { boolean isLeaf = !hasChildren(cms, resource); if (!isLeaf) { throw new CmisConstraintException("Only leaf resources can be deleted."); } } ensureLock(cms, resource); cms.deleteResource(resource.getRootPath(), CmsResource.DELETE_PRESERVE_SIBLINGS); } catch (CmsException e) { handleCmsException(e); } }
java
public synchronized void deleteObject(CmsCmisCallContext context, String objectId, boolean allVersions) { try { CmsObject cms = m_repository.getCmsObject(context); CmsUUID structureId = new CmsUUID(objectId); CmsResource resource = cms.readResource(structureId); if (resource.isFolder()) { boolean isLeaf = !hasChildren(cms, resource); if (!isLeaf) { throw new CmisConstraintException("Only leaf resources can be deleted."); } } ensureLock(cms, resource); cms.deleteResource(resource.getRootPath(), CmsResource.DELETE_PRESERVE_SIBLINGS); } catch (CmsException e) { handleCmsException(e); } }
[ "public", "synchronized", "void", "deleteObject", "(", "CmsCmisCallContext", "context", ",", "String", "objectId", ",", "boolean", "allVersions", ")", "{", "try", "{", "CmsObject", "cms", "=", "m_repository", ".", "getCmsObject", "(", "context", ")", ";", "CmsUU...
Deletes a CMIS object.<p> @param context the call context @param objectId the id of the object to delete @param allVersions flag to delete all version
[ "Deletes", "a", "CMIS", "object", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cmis/CmsCmisResourceHelper.java#L119-L136
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java
PhotosApi.setDates
public Response setDates(String photoId, Date datePosted, Date dateTaken, int dateTakenGranularity) throws JinxException { JinxUtils.validateParams(photoId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.setDates"); params.put("photo_id", photoId); if (datePosted != null) { params.put("date_posted", JinxUtils.formatDateAsUnixTimestamp(datePosted)); } if (dateTaken != null) { params.put("date_taken", JinxUtils.formatDateAsMySqlTimestamp(dateTaken)); } if (dateTakenGranularity == 0 || dateTakenGranularity == 4 || dateTakenGranularity == 6 || dateTakenGranularity == 8) { params.put("date_taken_granularity", Integer.toString(dateTakenGranularity)); } return jinx.flickrPost(params, Response.class); }
java
public Response setDates(String photoId, Date datePosted, Date dateTaken, int dateTakenGranularity) throws JinxException { JinxUtils.validateParams(photoId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.setDates"); params.put("photo_id", photoId); if (datePosted != null) { params.put("date_posted", JinxUtils.formatDateAsUnixTimestamp(datePosted)); } if (dateTaken != null) { params.put("date_taken", JinxUtils.formatDateAsMySqlTimestamp(dateTaken)); } if (dateTakenGranularity == 0 || dateTakenGranularity == 4 || dateTakenGranularity == 6 || dateTakenGranularity == 8) { params.put("date_taken_granularity", Integer.toString(dateTakenGranularity)); } return jinx.flickrPost(params, Response.class); }
[ "public", "Response", "setDates", "(", "String", "photoId", ",", "Date", "datePosted", ",", "Date", "dateTaken", ",", "int", "dateTakenGranularity", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "photoId", ")", ";", "Map", "<", ...
Set one or both of the dates for a photo. <br> This method requires authentication with 'write' permission. <br> One or both dates can be set. If no dates are set, nothing will happen. <br> Taken dates also have a 'granularity' - the accuracy to which we know the date to be true. At present, the following granularities are used: <ul> <li>0 Y-m-d H:i:s</li> <li>4 Y-m</li> <li>6 Y</li> <li>8 Circa...</li> </ul> @param photoId Required. The id of the photo to change dates for. @param datePosted Optional. date the photo was uploaded to flickr @param dateTaken Optional. date the photo was taken. @param dateTakenGranularity Optional. granularity of the date the photo was taken. @return response object with the result of the requested operation. @throws JinxException if required parameters are null or empty, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.photos.setDates.html">flickr.photos.setDates</a>
[ "Set", "one", "or", "both", "of", "the", "dates", "for", "a", "photo", ".", "<br", ">", "This", "method", "requires", "authentication", "with", "write", "permission", ".", "<br", ">", "One", "or", "both", "dates", "can", "be", "set", ".", "If", "no", ...
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java#L919-L934
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/ValidationMessageManager.java
ValidationMessageManager.getString
public static String getString(String key, Object... params) { String message = getStringSafely(key); if (params != null && params.length > 0) { return MessageFormat.format(message, params); } else { return message; } }
java
public static String getString(String key, Object... params) { String message = getStringSafely(key); if (params != null && params.length > 0) { return MessageFormat.format(message, params); } else { return message; } }
[ "public", "static", "String", "getString", "(", "String", "key", ",", "Object", "...", "params", ")", "{", "String", "message", "=", "getStringSafely", "(", "key", ")", ";", "if", "(", "params", "!=", "null", "&&", "params", ".", "length", ">", "0", ")...
Applies the message parameters and returns the message from one of the message bundles. @param key property key @param params message parameters to be used in message's place holders @return Resource value or place-holder error String
[ "Applies", "the", "message", "parameters", "and", "returns", "the", "message", "from", "one", "of", "the", "message", "bundles", "." ]
train
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/ValidationMessageManager.java#L57-L64
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/impl/DefaultFaceletFactory.java
DefaultFaceletFactory.resolveURL
public URL resolveURL(FacesContext context, URL source, String path) throws IOException { if (path.startsWith("/")) { context.getAttributes().put(LAST_RESOURCE_RESOLVED, null); URL url = resolveURL(context, path); if (url == null) { throw new FileNotFoundException(path + " Not Found in ExternalContext as a Resource"); } return url; } else { return new URL(source, path); } }
java
public URL resolveURL(FacesContext context, URL source, String path) throws IOException { if (path.startsWith("/")) { context.getAttributes().put(LAST_RESOURCE_RESOLVED, null); URL url = resolveURL(context, path); if (url == null) { throw new FileNotFoundException(path + " Not Found in ExternalContext as a Resource"); } return url; } else { return new URL(source, path); } }
[ "public", "URL", "resolveURL", "(", "FacesContext", "context", ",", "URL", "source", ",", "String", "path", ")", "throws", "IOException", "{", "if", "(", "path", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "context", ".", "getAttributes", "(", ")", "...
Resolves a path based on the passed URL. If the path starts with '/', then resolve the path against {@link javax.faces.context.ExternalContext#getResource(java.lang.String) javax.faces.context.ExternalContext#getResource(java.lang.String)}. Otherwise create a new URL via {@link URL#URL(java.net.URL, java.lang.String) URL(URL, String)}. @param source base to resolve from @param path relative path to the source @return resolved URL @throws IOException
[ "Resolves", "a", "path", "based", "on", "the", "passed", "URL", ".", "If", "the", "path", "starts", "with", "/", "then", "resolve", "the", "path", "against", "{", "@link", "javax", ".", "faces", ".", "context", ".", "ExternalContext#getResource", "(", "jav...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/impl/DefaultFaceletFactory.java#L300-L316
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendCloseBlocking
public static void sendCloseBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException { sendCloseBlocking(new CloseMessage(data), wsChannel); }
java
public static void sendCloseBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException { sendCloseBlocking(new CloseMessage(data), wsChannel); }
[ "public", "static", "void", "sendCloseBlocking", "(", "final", "ByteBuffer", "data", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "sendCloseBlocking", "(", "new", "CloseMessage", "(", "data", ")", ",", "wsChannel", ")", ";", ...
Sends a complete close message, invoking the callback when complete @param data The data to send @param wsChannel The web socket channel
[ "Sends", "a", "complete", "close", "message", "invoking", "the", "callback", "when", "complete" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L885-L887
jbundle/jbundle
thin/base/screen/cal/other/src/main/java/org/jbundle/thin/base/screen/cal/opt/CachedItem.java
CachedItem.setCacheData
public synchronized void setCacheData(Date startTime, Date endTime, String description, String [] rgstrMeals) { m_cachedInfo.setCacheData(startTime, endTime, description, rgstrMeals); }
java
public synchronized void setCacheData(Date startTime, Date endTime, String description, String [] rgstrMeals) { m_cachedInfo.setCacheData(startTime, endTime, description, rgstrMeals); }
[ "public", "synchronized", "void", "setCacheData", "(", "Date", "startTime", ",", "Date", "endTime", ",", "String", "description", ",", "String", "[", "]", "rgstrMeals", ")", "{", "m_cachedInfo", ".", "setCacheData", "(", "startTime", ",", "endTime", ",", "desc...
Change the cache data without calling the methods to change the underlying model. This method is used by the lineItem to change the screen model without calling a change to the model.
[ "Change", "the", "cache", "data", "without", "calling", "the", "methods", "to", "change", "the", "underlying", "model", ".", "This", "method", "is", "used", "by", "the", "lineItem", "to", "change", "the", "screen", "model", "without", "calling", "a", "change...
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/cal/other/src/main/java/org/jbundle/thin/base/screen/cal/opt/CachedItem.java#L213-L216
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.createToken
public CompletableFuture<Revision> createToken(Author author, String appId, String secret, boolean isAdmin) { requireNonNull(author, "author"); requireNonNull(appId, "appId"); requireNonNull(secret, "secret"); checkArgument(secret.startsWith(SECRET_PREFIX), "secret must start with: " + SECRET_PREFIX); final Token newToken = new Token(appId, secret, isAdmin, UserAndTimestamp.of(author)); final JsonPointer appIdPath = JsonPointer.compile("/appIds" + encodeSegment(newToken.id())); final String newTokenSecret = newToken.secret(); assert newTokenSecret != null; final JsonPointer secretPath = JsonPointer.compile("/secrets" + encodeSegment(newTokenSecret)); final Change<JsonNode> change = Change.ofJsonPatch(TOKEN_JSON, asJsonArray(new TestAbsenceOperation(appIdPath), new TestAbsenceOperation(secretPath), new AddOperation(appIdPath, Jackson.valueToTree(newToken)), new AddOperation(secretPath, Jackson.valueToTree(newToken.id())))); return tokenRepo.push(INTERNAL_PROJ, Project.REPO_DOGMA, author, "Add a token: '" + newToken.id(), change); }
java
public CompletableFuture<Revision> createToken(Author author, String appId, String secret, boolean isAdmin) { requireNonNull(author, "author"); requireNonNull(appId, "appId"); requireNonNull(secret, "secret"); checkArgument(secret.startsWith(SECRET_PREFIX), "secret must start with: " + SECRET_PREFIX); final Token newToken = new Token(appId, secret, isAdmin, UserAndTimestamp.of(author)); final JsonPointer appIdPath = JsonPointer.compile("/appIds" + encodeSegment(newToken.id())); final String newTokenSecret = newToken.secret(); assert newTokenSecret != null; final JsonPointer secretPath = JsonPointer.compile("/secrets" + encodeSegment(newTokenSecret)); final Change<JsonNode> change = Change.ofJsonPatch(TOKEN_JSON, asJsonArray(new TestAbsenceOperation(appIdPath), new TestAbsenceOperation(secretPath), new AddOperation(appIdPath, Jackson.valueToTree(newToken)), new AddOperation(secretPath, Jackson.valueToTree(newToken.id())))); return tokenRepo.push(INTERNAL_PROJ, Project.REPO_DOGMA, author, "Add a token: '" + newToken.id(), change); }
[ "public", "CompletableFuture", "<", "Revision", ">", "createToken", "(", "Author", "author", ",", "String", "appId", ",", "String", "secret", ",", "boolean", "isAdmin", ")", "{", "requireNonNull", "(", "author", ",", "\"author\"", ")", ";", "requireNonNull", "...
Creates a new {@link Token} with the specified {@code appId}, {@code secret} and {@code isAdmin}.
[ "Creates", "a", "new", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L718-L740
wealthfront/magellan
magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java
Navigator.goBackTo
public void goBackTo(final Screen screen, NavigationType navigationType) { navigate(new HistoryRewriter() { @Override public void rewriteHistory(Deque<Screen> history) { checkArgument(history.contains(screen), "Can't go back to a screen that isn't in history."); while (history.size() > 1) { if (history.peek() == screen) { break; } history.pop(); } } }, navigationType, BACKWARD); }
java
public void goBackTo(final Screen screen, NavigationType navigationType) { navigate(new HistoryRewriter() { @Override public void rewriteHistory(Deque<Screen> history) { checkArgument(history.contains(screen), "Can't go back to a screen that isn't in history."); while (history.size() > 1) { if (history.peek() == screen) { break; } history.pop(); } } }, navigationType, BACKWARD); }
[ "public", "void", "goBackTo", "(", "final", "Screen", "screen", ",", "NavigationType", "navigationType", ")", "{", "navigate", "(", "new", "HistoryRewriter", "(", ")", "{", "@", "Override", "public", "void", "rewriteHistory", "(", "Deque", "<", "Screen", ">", ...
Navigates from the current screen back to the Screen parameter wherever it is in this Navigator's back stack. Screens in between the current screen and the Screen parameter on the back stack are removed. If the Screen parameter is not present in this Navigator's back stack, this method is equivalent to {@link #goBackToRoot(NavigationType) goBackToRoot(navigationType)} @param screen screen to navigate back to through this Navigator's back stack @param navigationType determines how the navigation event is animated
[ "Navigates", "from", "the", "current", "screen", "back", "to", "the", "Screen", "parameter", "wherever", "it", "is", "in", "this", "Navigator", "s", "back", "stack", ".", "Screens", "in", "between", "the", "current", "screen", "and", "the", "Screen", "parame...
train
https://github.com/wealthfront/magellan/blob/f690979161a97e40fb9d11dc9d7e3c8cf85ba312/magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java#L458-L471
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/metrics/metricsets/OperatingSystemMetricSet.java
OperatingSystemMetricSet.getMethod
private static Method getMethod(Object source, String methodName, String name) { try { Method method = source.getClass().getMethod(methodName); method.setAccessible(true); return method; } catch (Exception e) { if (LOGGER.isFinestEnabled()) { LOGGER.log(Level.FINEST, "Unable to register OperatingSystemMXBean method " + methodName + " used for probe " + name, e); } return null; } }
java
private static Method getMethod(Object source, String methodName, String name) { try { Method method = source.getClass().getMethod(methodName); method.setAccessible(true); return method; } catch (Exception e) { if (LOGGER.isFinestEnabled()) { LOGGER.log(Level.FINEST, "Unable to register OperatingSystemMXBean method " + methodName + " used for probe " + name, e); } return null; } }
[ "private", "static", "Method", "getMethod", "(", "Object", "source", ",", "String", "methodName", ",", "String", "name", ")", "{", "try", "{", "Method", "method", "=", "source", ".", "getClass", "(", ")", ".", "getMethod", "(", "methodName", ")", ";", "m...
Returns a method from the given source object. @param source the source object. @param methodName the name of the method to retrieve. @param name the probe name @return the method
[ "Returns", "a", "method", "from", "the", "given", "source", "object", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/metrics/metricsets/OperatingSystemMetricSet.java#L109-L121
anotheria/configureme
src/main/java/org/configureme/sources/ConfigurationSourceKey.java
ConfigurationSourceKey.xmlFile
public static final ConfigurationSourceKey xmlFile(final String name){ return new ConfigurationSourceKey(Type.FILE, Format.XML, name); }
java
public static final ConfigurationSourceKey xmlFile(final String name){ return new ConfigurationSourceKey(Type.FILE, Format.XML, name); }
[ "public", "static", "final", "ConfigurationSourceKey", "xmlFile", "(", "final", "String", "name", ")", "{", "return", "new", "ConfigurationSourceKey", "(", "Type", ".", "FILE", ",", "Format", ".", "XML", ",", "name", ")", ";", "}" ]
Creates a new configuration source key for xml files. @param name name of the xml file. @return a new configuration source key instance for xml files
[ "Creates", "a", "new", "configuration", "source", "key", "for", "xml", "files", "." ]
train
https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/sources/ConfigurationSourceKey.java#L211-L213
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/JARVerifier.java
JARVerifier.create
public static JARVerifier create(String keystore, String alias, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fileIn=null; try { fileIn = new FileInputStream(keystore); keyStore.load(fileIn, passwd); } finally { if(null!= fileIn){ fileIn.close(); } } Certificate[] chain = keyStore.getCertificateChain(alias); if (chain == null) { Certificate cert = keyStore.getCertificate(alias); if (cert == null) { throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias); } chain = new Certificate[]{cert}; } X509Certificate certChain[] = new X509Certificate[chain.length]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int count = 0; count < chain.length; count++) { ByteArrayInputStream certIn = new ByteArrayInputStream(chain[count].getEncoded()); X509Certificate cert = (X509Certificate) cf.generateCertificate(certIn); certChain[count] = cert; } JARVerifier jarVerifier = new JARVerifier(certChain); return jarVerifier; }
java
public static JARVerifier create(String keystore, String alias, char[] passwd) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fileIn=null; try { fileIn = new FileInputStream(keystore); keyStore.load(fileIn, passwd); } finally { if(null!= fileIn){ fileIn.close(); } } Certificate[] chain = keyStore.getCertificateChain(alias); if (chain == null) { Certificate cert = keyStore.getCertificate(alias); if (cert == null) { throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias); } chain = new Certificate[]{cert}; } X509Certificate certChain[] = new X509Certificate[chain.length]; CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (int count = 0; count < chain.length; count++) { ByteArrayInputStream certIn = new ByteArrayInputStream(chain[count].getEncoded()); X509Certificate cert = (X509Certificate) cf.generateCertificate(certIn); certChain[count] = cert; } JARVerifier jarVerifier = new JARVerifier(certChain); return jarVerifier; }
[ "public", "static", "JARVerifier", "create", "(", "String", "keystore", ",", "String", "alias", ",", "char", "[", "]", "passwd", ")", "throws", "IOException", ",", "KeyStoreException", ",", "NoSuchAlgorithmException", ",", "CertificateException", "{", "KeyStore", ...
@return Construct a JARVerifier with a keystore and alias and password. @param keystore filepath to the keystore @param alias alias name of the cert chain to verify with @param passwd password to use to verify the keystore, or null @throws IOException on io error @throws KeyStoreException key store error @throws NoSuchAlgorithmException algorithm missing @throws CertificateException cert error
[ "@return", "Construct", "a", "JARVerifier", "with", "a", "keystore", "and", "alias", "and", "password", "." ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/JARVerifier.java#L76-L110
netplex/json-smart-v2
json-smart/src/main/java/net/minidev/json/parser/JSONParser.java
JSONParser.parse
public <T> T parse(String in, JsonReaderI<T> mapper) throws ParseException { return getPString().parse(in, mapper); }
java
public <T> T parse(String in, JsonReaderI<T> mapper) throws ParseException { return getPString().parse(in, mapper); }
[ "public", "<", "T", ">", "T", "parse", "(", "String", "in", ",", "JsonReaderI", "<", "T", ">", "mapper", ")", "throws", "ParseException", "{", "return", "getPString", "(", ")", ".", "parse", "(", "in", ",", "mapper", ")", ";", "}" ]
use to return Primitive Type, or String, Or JsonObject or JsonArray generated by a ContainerFactory
[ "use", "to", "return", "Primitive", "Type", "or", "String", "Or", "JsonObject", "or", "JsonArray", "generated", "by", "a", "ContainerFactory" ]
train
https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart/src/main/java/net/minidev/json/parser/JSONParser.java#L270-L272
geomajas/geomajas-project-server
impl/src/main/java/org/geomajas/internal/rendering/painter/tile/StringContentTilePainter.java
StringContentTilePainter.createLabelDocument
private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo, geoService, textService)); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight, getTransformer(), labelStyleInfo, geoService, textService)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
java
private GraphicsDocument createLabelDocument(StringWriter writer, LabelStyleInfo labelStyleInfo) throws RenderException { if (TileMetadata.PARAM_SVG_RENDERER.equalsIgnoreCase(renderer)) { DefaultSvgDocument document = new DefaultSvgDocument(writer, false); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); document.registerWriter(InternalTileImpl.class, new SvgLabelTileWriter(getTransformer(), labelStyleInfo, geoService, textService)); return document; } else if (TileMetadata.PARAM_VML_RENDERER.equalsIgnoreCase(renderer)) { DefaultVmlDocument document = new DefaultVmlDocument(writer); int coordWidth = tile.getScreenWidth(); int coordHeight = tile.getScreenHeight(); document.registerWriter(InternalFeatureImpl.class, new VmlFeatureWriter(getTransformer(), coordWidth, coordHeight)); document.registerWriter(InternalTileImpl.class, new VmlLabelTileWriter(coordWidth, coordHeight, getTransformer(), labelStyleInfo, geoService, textService)); document.setMaximumFractionDigits(MAXIMUM_FRACTION_DIGITS); return document; } else { throw new RenderException(ExceptionCode.RENDERER_TYPE_NOT_SUPPORTED, renderer); } }
[ "private", "GraphicsDocument", "createLabelDocument", "(", "StringWriter", "writer", ",", "LabelStyleInfo", "labelStyleInfo", ")", "throws", "RenderException", "{", "if", "(", "TileMetadata", ".", "PARAM_SVG_RENDERER", ".", "equalsIgnoreCase", "(", "renderer", ")", ")",...
Create a document that parses the tile's labelFragment, using GraphicsWriter classes. @param writer writer @param labelStyleInfo label style info @return graphics document @throws RenderException cannot render
[ "Create", "a", "document", "that", "parses", "the", "tile", "s", "labelFragment", "using", "GraphicsWriter", "classes", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/internal/rendering/painter/tile/StringContentTilePainter.java#L282-L304
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java
BouncyCastleUtil.getCertificateType
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts) throws CertificateException { try { TBSCertificateStructure crt = getTBSCertificateStructure(cert); GSIConstants.CertificateType type = getCertificateType(crt); // check subject of the cert in trusted cert list // to make sure the cert is not a ca cert if (type == GSIConstants.CertificateType.EEC) { X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); Collection c = trustedCerts.getCertificates(selector); if (c != null && c.size() > 0) { type = GSIConstants.CertificateType.CA; } } return type; } catch (Exception e) { // but this should not happen throw new CertificateException("", e); } }
java
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts) throws CertificateException { try { TBSCertificateStructure crt = getTBSCertificateStructure(cert); GSIConstants.CertificateType type = getCertificateType(crt); // check subject of the cert in trusted cert list // to make sure the cert is not a ca cert if (type == GSIConstants.CertificateType.EEC) { X509CertSelector selector = new X509CertSelector(); selector.setSubject(cert.getSubjectX500Principal()); Collection c = trustedCerts.getCertificates(selector); if (c != null && c.size() > 0) { type = GSIConstants.CertificateType.CA; } } return type; } catch (Exception e) { // but this should not happen throw new CertificateException("", e); } }
[ "public", "static", "GSIConstants", ".", "CertificateType", "getCertificateType", "(", "X509Certificate", "cert", ",", "CertStore", "trustedCerts", ")", "throws", "CertificateException", "{", "try", "{", "TBSCertificateStructure", "crt", "=", "getTBSCertificateStructure", ...
Returns the certificate type of the given certificate. Please see {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType} for details for determining the certificate type. @param cert the certificate to get the type of. @param trustedCerts the trusted certificates to double check the {@link GSIConstants#EEC GSIConstants.EEC} certificate against. @return the certificate type as determined by {@link #getCertificateType(TBSCertificateStructure, TrustedCertificates) getCertificateType}. @exception CertificateException if something goes wrong.
[ "Returns", "the", "certificate", "type", "of", "the", "given", "certificate", ".", "Please", "see", "{", "@link", "#getCertificateType", "(", "TBSCertificateStructure", "TrustedCertificates", ")", "getCertificateType", "}", "for", "details", "for", "determining", "the...
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleUtil.java#L181-L202
btrplace/scheduler
json/src/main/java/org/btrplace/json/JSONs.java
JSONs.requiredDouble
public static double requiredDouble(JSONObject o, String id) throws JSONConverterException { checkKeys(o, id); Object x = o.get(id); if (!(x instanceof Number)) { throw new JSONConverterException("Number expected at key '" + id + "' but was '" + x.getClass() + "'."); } return ((Number) x).doubleValue(); }
java
public static double requiredDouble(JSONObject o, String id) throws JSONConverterException { checkKeys(o, id); Object x = o.get(id); if (!(x instanceof Number)) { throw new JSONConverterException("Number expected at key '" + id + "' but was '" + x.getClass() + "'."); } return ((Number) x).doubleValue(); }
[ "public", "static", "double", "requiredDouble", "(", "JSONObject", "o", ",", "String", "id", ")", "throws", "JSONConverterException", "{", "checkKeys", "(", "o", ",", "id", ")", ";", "Object", "x", "=", "o", ".", "get", "(", "id", ")", ";", "if", "(", ...
Read an expected double. @param o the object to parse @param id the key in the map that points to the double @return the double @throws JSONConverterException if the key does not point to a double
[ "Read", "an", "expected", "double", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/JSONs.java#L158-L165
centic9/commons-dost
src/main/java/org/dstadler/commons/svn/SVNCommands.java
SVNCommands.getRemoteFileContent
public static InputStream getRemoteFileContent(String file, long revision, String baseUrl, String user, String pwd) throws IOException { // svn cat -r 666 file CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_CAT); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument("-r"); cmdLine.addArgument(Long.toString(revision)); cmdLine.addArgument(baseUrl + file); return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000); }
java
public static InputStream getRemoteFileContent(String file, long revision, String baseUrl, String user, String pwd) throws IOException { // svn cat -r 666 file CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument(CMD_CAT); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument("-r"); cmdLine.addArgument(Long.toString(revision)); cmdLine.addArgument(baseUrl + file); return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000); }
[ "public", "static", "InputStream", "getRemoteFileContent", "(", "String", "file", ",", "long", "revision", ",", "String", "baseUrl", ",", "String", "user", ",", "String", "pwd", ")", "throws", "IOException", "{", "// svn cat -r 666 file", "CommandLine", "cmdLine", ...
Retrieve the contents of a file from the web-interface of the SVN server. @param file The file to fetch from the SVN server via @param revision The SVN revision to use @param baseUrl The SVN url to connect to @param user The SVN user or null if the default user from the machine should be used @param pwd The SVN password or null if the default user from the machine should be used @return The contents of the file. @return An InputStream which provides the content of the revision of the specified file @throws IOException Execution of the SVN sub-process failed or the sub-process returned a exit value indicating a failure
[ "Retrieve", "the", "contents", "of", "a", "file", "from", "the", "web", "-", "interface", "of", "the", "SVN", "server", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L229-L239
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceCompositeGroupService.java
ReferenceCompositeGroupService.getEntity
@Override public IEntity getEntity(String key, Class type) throws GroupsException { return getEntity(key, type, null); }
java
@Override public IEntity getEntity(String key, Class type) throws GroupsException { return getEntity(key, type, null); }
[ "@", "Override", "public", "IEntity", "getEntity", "(", "String", "key", ",", "Class", "type", ")", "throws", "GroupsException", "{", "return", "getEntity", "(", "key", ",", "type", ",", "null", ")", ";", "}" ]
Returns an <code>IEntity</code> representing a portal entity. This does not guarantee that the entity actually exists.
[ "Returns", "an", "<code", ">", "IEntity<", "/", "code", ">", "representing", "a", "portal", "entity", ".", "This", "does", "not", "guarantee", "that", "the", "entity", "actually", "exists", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceCompositeGroupService.java#L107-L110
RuedigerMoeller/kontraktor
modules/reactive-streams/src/main/java/org/nustaq/kontraktor/reactivestreams/KxReactiveStreams.java
KxReactiveStreams.serve
public <OUT> IPromise serve(Publisher<OUT> source, ActorPublisher networRxPublisher, boolean closeConnectionOnCompleteOrError, Consumer<Actor> disconCB) { if ( networRxPublisher.getClass().getSimpleName().equals("HttpPublisher") ) { throw new RuntimeException("Http long poll cannot be supported. Use WebSockets instead."); } if (source instanceof KxPublisherActor == false || source instanceof ActorProxy == false ) { Processor<OUT, OUT> proc = newAsyncProcessor(a -> a); // we need a queue before going to network source.subscribe(proc); source = proc; } ((KxPublisherActor)source).setCloseOnComplete(closeConnectionOnCompleteOrError); return networRxPublisher.facade((Actor) source).publish(disconCB); }
java
public <OUT> IPromise serve(Publisher<OUT> source, ActorPublisher networRxPublisher, boolean closeConnectionOnCompleteOrError, Consumer<Actor> disconCB) { if ( networRxPublisher.getClass().getSimpleName().equals("HttpPublisher") ) { throw new RuntimeException("Http long poll cannot be supported. Use WebSockets instead."); } if (source instanceof KxPublisherActor == false || source instanceof ActorProxy == false ) { Processor<OUT, OUT> proc = newAsyncProcessor(a -> a); // we need a queue before going to network source.subscribe(proc); source = proc; } ((KxPublisherActor)source).setCloseOnComplete(closeConnectionOnCompleteOrError); return networRxPublisher.facade((Actor) source).publish(disconCB); }
[ "public", "<", "OUT", ">", "IPromise", "serve", "(", "Publisher", "<", "OUT", ">", "source", ",", "ActorPublisher", "networRxPublisher", ",", "boolean", "closeConnectionOnCompleteOrError", ",", "Consumer", "<", "Actor", ">", "disconCB", ")", "{", "if", "(", "n...
exposes a publisher on the network via kontraktor's generic remoting. Usually not called directly (see EventSink+RxPublisher) @param source @param networRxPublisher - the appropriate network publisher (TCP,TCPNIO,WS) @param disconCB - called once a client disconnects/stops. can be null @param <OUT> @return
[ "exposes", "a", "publisher", "on", "the", "network", "via", "kontraktor", "s", "generic", "remoting", ".", "Usually", "not", "called", "directly", "(", "see", "EventSink", "+", "RxPublisher", ")" ]
train
https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/reactive-streams/src/main/java/org/nustaq/kontraktor/reactivestreams/KxReactiveStreams.java#L323-L334
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/utils/Assert.java
Assert.parameterNotNull
public static void parameterNotNull(final String name, final Object reference) { if (reference == null) { raiseError(format("Parameter '%s' is not expected to be null.", name)); } }
java
public static void parameterNotNull(final String name, final Object reference) { if (reference == null) { raiseError(format("Parameter '%s' is not expected to be null.", name)); } }
[ "public", "static", "void", "parameterNotNull", "(", "final", "String", "name", ",", "final", "Object", "reference", ")", "{", "if", "(", "reference", "==", "null", ")", "{", "raiseError", "(", "format", "(", "\"Parameter '%s' is not expected to be null.\"", ",", ...
Validates that the parameter is not null @param name the parameter name @param reference the proposed parameter value
[ "Validates", "that", "the", "parameter", "is", "not", "null" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/utils/Assert.java#L49-L53
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/Numbers.java
Numbers.parseInt
public static int parseInt(Object val) { if (val instanceof String) { return Integer.parseInt((String) val); } else if (val instanceof Number) { return ((Number) val).intValue(); } else { if (val == null) { throw new NullPointerException("Input is null"); } else { throw new ISE("Unknown type [%s]", val.getClass()); } } }
java
public static int parseInt(Object val) { if (val instanceof String) { return Integer.parseInt((String) val); } else if (val instanceof Number) { return ((Number) val).intValue(); } else { if (val == null) { throw new NullPointerException("Input is null"); } else { throw new ISE("Unknown type [%s]", val.getClass()); } } }
[ "public", "static", "int", "parseInt", "(", "Object", "val", ")", "{", "if", "(", "val", "instanceof", "String", ")", "{", "return", "Integer", ".", "parseInt", "(", "(", "String", ")", "val", ")", ";", "}", "else", "if", "(", "val", "instanceof", "N...
Parse the given object as a {@code int}. The input object can be a {@link String} or one of the implementations of {@link Number}. @throws NumberFormatException if the input is an unparseable string. @throws NullPointerException if the input is null. @throws ISE if the input is not a string or a number.
[ "Parse", "the", "given", "object", "as", "a", "{", "@code", "int", "}", ".", "The", "input", "object", "can", "be", "a", "{", "@link", "String", "}", "or", "one", "of", "the", "implementations", "of", "{", "@link", "Number", "}", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/Numbers.java#L56-L69
code4everything/util
src/main/java/com/zhazhapan/util/LoggerUtils.java
LoggerUtils.debug
public static void debug(Class<?> clazz, String message, String... values) { getLogger(clazz).debug(formatString(message, values)); }
java
public static void debug(Class<?> clazz, String message, String... values) { getLogger(clazz).debug(formatString(message, values)); }
[ "public", "static", "void", "debug", "(", "Class", "<", "?", ">", "clazz", ",", "String", "message", ",", "String", "...", "values", ")", "{", "getLogger", "(", "clazz", ")", ".", "debug", "(", "formatString", "(", "message", ",", "values", ")", ")", ...
调试 @param clazz 类 @param message 消息 @param values 格式化参数 @since 1.0.8
[ "调试" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/LoggerUtils.java#L219-L221
lucmoreau/ProvToolbox
prov-interop/src/main/java/org/openprovenance/prov/interop/InteropFramework.java
InteropFramework.writeDocument
public void writeDocument(String filename, Document document) { ProvFormat format = getTypeForFile(filename); if (format == null) { System.err.println("Unknown output file format: " + filename); return; } writeDocument(filename, format, document); }
java
public void writeDocument(String filename, Document document) { ProvFormat format = getTypeForFile(filename); if (format == null) { System.err.println("Unknown output file format: " + filename); return; } writeDocument(filename, format, document); }
[ "public", "void", "writeDocument", "(", "String", "filename", ",", "Document", "document", ")", "{", "ProvFormat", "format", "=", "getTypeForFile", "(", "filename", ")", ";", "if", "(", "format", "==", "null", ")", "{", "System", ".", "err", ".", "println"...
Write a {@link Document} to file, serialized according to the file extension @param filename path of the file to write the Document to @param document a {@link Document} to serialize
[ "Write", "a", "{" ]
train
https://github.com/lucmoreau/ProvToolbox/blob/f865952868ffb69432937b08728c86bebbe4678a/prov-interop/src/main/java/org/openprovenance/prov/interop/InteropFramework.java#L1173-L1180
j256/simplejmx
src/main/java/com/j256/simplejmx/client/JmxClient.java
JmxClient.invokeOperationToString
public String invokeOperationToString(ObjectName name, String operName, String... paramStrings) throws Exception { return ClientUtils.valueToString(invokeOperation(name, operName, paramStrings)); }
java
public String invokeOperationToString(ObjectName name, String operName, String... paramStrings) throws Exception { return ClientUtils.valueToString(invokeOperation(name, operName, paramStrings)); }
[ "public", "String", "invokeOperationToString", "(", "ObjectName", "name", ",", "String", "operName", ",", "String", "...", "paramStrings", ")", "throws", "Exception", "{", "return", "ClientUtils", ".", "valueToString", "(", "invokeOperation", "(", "name", ",", "op...
Invoke a JMX method as an array of parameter strings. @return The value returned by the method as a string or null if none.
[ "Invoke", "a", "JMX", "method", "as", "an", "array", "of", "parameter", "strings", "." ]
train
https://github.com/j256/simplejmx/blob/1a04f52512dfa0a711ba0cc7023c604dbc82a352/src/main/java/com/j256/simplejmx/client/JmxClient.java#L440-L442
sd4324530/fastweixin
src/main/java/com/github/sd4324530/fastweixin/company/api/QYTagAPI.java
QYTagAPI.addTagUsers
public AddTagUsersResponse addTagUsers(Integer tagid, List<String> users, List<Integer> partys){ BeanUtil.requireNonNull(tagid, "tagid不能为空!"); if((users == null || users.size() == 0) && (partys == null || partys.size() == 0)){ throw new WeixinException("userlist、partylist不能同时为空!"); } if(users != null && users.size() > 1000){ throw new WeixinException("userlist单次请求长度不能大于1000"); } if(partys != null && partys.size() > 100){ throw new WeixinException("partylist单次请求长度不能大于100"); } AddTagUsersResponse response; String url = BASE_API_URL + "cgi-bin/tag/addtagusers?access_token=#"; final Map<String, Object> params = new HashMap<String, Object>(); params.put("tagid", tagid); params.put("userlist", users); params.put("partylist", partys); BaseResponse r = executePost(url, JSONUtil.toJson(params)); String jsonResult = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); response = JSONUtil.toBean(jsonResult, AddTagUsersResponse.class); return response; }
java
public AddTagUsersResponse addTagUsers(Integer tagid, List<String> users, List<Integer> partys){ BeanUtil.requireNonNull(tagid, "tagid不能为空!"); if((users == null || users.size() == 0) && (partys == null || partys.size() == 0)){ throw new WeixinException("userlist、partylist不能同时为空!"); } if(users != null && users.size() > 1000){ throw new WeixinException("userlist单次请求长度不能大于1000"); } if(partys != null && partys.size() > 100){ throw new WeixinException("partylist单次请求长度不能大于100"); } AddTagUsersResponse response; String url = BASE_API_URL + "cgi-bin/tag/addtagusers?access_token=#"; final Map<String, Object> params = new HashMap<String, Object>(); params.put("tagid", tagid); params.put("userlist", users); params.put("partylist", partys); BaseResponse r = executePost(url, JSONUtil.toJson(params)); String jsonResult = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); response = JSONUtil.toBean(jsonResult, AddTagUsersResponse.class); return response; }
[ "public", "AddTagUsersResponse", "addTagUsers", "(", "Integer", "tagid", ",", "List", "<", "String", ">", "users", ",", "List", "<", "Integer", ">", "partys", ")", "{", "BeanUtil", ".", "requireNonNull", "(", "tagid", ",", "\"tagid不能为空!\");", "", "", "if", ...
增加标签成员。userlist与partylist非必须,但不能同时为空 @param tagid 目标标签id。必填 @param users 企业成员ID列表。单次请求长度不能超过1000 @param partys 企业部门ID列表。单次请求长度不能超过100 @return 操作结果
[ "增加标签成员。userlist与partylist非必须,但不能同时为空" ]
train
https://github.com/sd4324530/fastweixin/blob/6bc0a7abfa23aad0dbad4c3123a47a7fb53f3447/src/main/java/com/github/sd4324530/fastweixin/company/api/QYTagAPI.java#L101-L122
looly/hutool
hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java
CollUtil.valuesOfKeys
public static <K, V> ArrayList<V> valuesOfKeys(Map<K, V> map, Iterable<K> keys) { return valuesOfKeys(map, keys.iterator()); }
java
public static <K, V> ArrayList<V> valuesOfKeys(Map<K, V> map, Iterable<K> keys) { return valuesOfKeys(map, keys.iterator()); }
[ "public", "static", "<", "K", ",", "V", ">", "ArrayList", "<", "V", ">", "valuesOfKeys", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "Iterable", "<", "K", ">", "keys", ")", "{", "return", "valuesOfKeys", "(", "map", ",", "keys", ".", "iterat...
从Map中获取指定键列表对应的值列表<br> 如果key在map中不存在或key对应值为null,则返回值列表对应位置的值也为null @param <K> 键类型 @param <V> 值类型 @param map {@link Map} @param keys 键列表 @return 值列表 @since 3.0.9
[ "从Map中获取指定键列表对应的值列表<br", ">", "如果key在map中不存在或key对应值为null,则返回值列表对应位置的值也为null" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java#L1995-L1997
liferay/com-liferay-commerce
commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListPersistenceImpl.java
CommerceWishListPersistenceImpl.findAll
@Override public List<CommerceWishList> findAll(int start, int end) { return findAll(start, end, null); }
java
@Override public List<CommerceWishList> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceWishList", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce wish lists. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWishListModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce wish lists @param end the upper bound of the range of commerce wish lists (not inclusive) @return the range of commerce wish lists
[ "Returns", "a", "range", "of", "all", "the", "commerce", "wish", "lists", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListPersistenceImpl.java#L4930-L4933
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java
PipelineBuilder.addIfExpression
public void addIfExpression(final INodeReadTrx mTransaction) { assert getPipeStack().size() >= 3; final INodeReadTrx rtx = mTransaction; final AbsAxis elseExpr = getPipeStack().pop().getExpr(); final AbsAxis thenExpr = getPipeStack().pop().getExpr(); final AbsAxis ifExpr = getPipeStack().pop().getExpr(); if (getPipeStack().empty() || getExpression().getSize() != 0) { addExpressionSingle(); } getExpression().add(new IfAxis(rtx, ifExpr, thenExpr, elseExpr)); }
java
public void addIfExpression(final INodeReadTrx mTransaction) { assert getPipeStack().size() >= 3; final INodeReadTrx rtx = mTransaction; final AbsAxis elseExpr = getPipeStack().pop().getExpr(); final AbsAxis thenExpr = getPipeStack().pop().getExpr(); final AbsAxis ifExpr = getPipeStack().pop().getExpr(); if (getPipeStack().empty() || getExpression().getSize() != 0) { addExpressionSingle(); } getExpression().add(new IfAxis(rtx, ifExpr, thenExpr, elseExpr)); }
[ "public", "void", "addIfExpression", "(", "final", "INodeReadTrx", "mTransaction", ")", "{", "assert", "getPipeStack", "(", ")", ".", "size", "(", ")", ">=", "3", ";", "final", "INodeReadTrx", "rtx", "=", "mTransaction", ";", "final", "AbsAxis", "elseExpr", ...
Adds a if expression to the pipeline. @param mTransaction Transaction to operate with.
[ "Adds", "a", "if", "expression", "to", "the", "pipeline", "." ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java#L250-L265
Omertron/api-tvrage
src/main/java/com/omertron/tvrageapi/tools/DOMHelper.java
DOMHelper.requestWebContent
private static byte[] requestWebContent(String url) throws TVRageException { try { HttpGet httpGet = new HttpGet(url); httpGet.addHeader("accept", "application/xml"); final DigestedResponse response = DigestedResponseReader.requestContent(httpClient, httpGet, CHARSET); if (response.getStatusCode() >= 500) { throw new TVRageException(ApiExceptionType.HTTP_503_ERROR, url); } else if (response.getStatusCode() >= 300) { throw new TVRageException(ApiExceptionType.HTTP_404_ERROR, url); } return response.getContent().getBytes(DEFAULT_CHARSET); } catch (IOException ex) { throw new TVRageException(ApiExceptionType.MAPPING_FAILED, UNABLE_TO_PARSE, url, ex); } }
java
private static byte[] requestWebContent(String url) throws TVRageException { try { HttpGet httpGet = new HttpGet(url); httpGet.addHeader("accept", "application/xml"); final DigestedResponse response = DigestedResponseReader.requestContent(httpClient, httpGet, CHARSET); if (response.getStatusCode() >= 500) { throw new TVRageException(ApiExceptionType.HTTP_503_ERROR, url); } else if (response.getStatusCode() >= 300) { throw new TVRageException(ApiExceptionType.HTTP_404_ERROR, url); } return response.getContent().getBytes(DEFAULT_CHARSET); } catch (IOException ex) { throw new TVRageException(ApiExceptionType.MAPPING_FAILED, UNABLE_TO_PARSE, url, ex); } }
[ "private", "static", "byte", "[", "]", "requestWebContent", "(", "String", "url", ")", "throws", "TVRageException", "{", "try", "{", "HttpGet", "httpGet", "=", "new", "HttpGet", "(", "url", ")", ";", "httpGet", ".", "addHeader", "(", "\"accept\"", ",", "\"...
Get content from URL in byte array @param url @return @throws TVRageException
[ "Get", "content", "from", "URL", "in", "byte", "array" ]
train
https://github.com/Omertron/api-tvrage/blob/4e805a99de812fabea69d97098f2376be14d51bc/src/main/java/com/omertron/tvrageapi/tools/DOMHelper.java#L132-L148
codeprimate-software/cp-elements
src/main/java/org/cp/elements/tools/net/support/AbstractClientServerSupport.java
AbstractClientServerSupport.sendMessage
protected Socket sendMessage(Socket socket, String message) throws IOException { PrintWriter printWriter = newPrintWriter(socket); printWriter.println(message); printWriter.flush(); return socket; }
java
protected Socket sendMessage(Socket socket, String message) throws IOException { PrintWriter printWriter = newPrintWriter(socket); printWriter.println(message); printWriter.flush(); return socket; }
[ "protected", "Socket", "sendMessage", "(", "Socket", "socket", ",", "String", "message", ")", "throws", "IOException", "{", "PrintWriter", "printWriter", "=", "newPrintWriter", "(", "socket", ")", ";", "printWriter", ".", "println", "(", "message", ")", ";", "...
Sends a simple {@link String message} over the given {@link Socket}. @param socket {@link Socket} on which the {@link String message} is sent. @param message {@link String} containing the message to send over the {@link Socket}. @return the given {@link Socket} in order to chain multiple send operations. @throws IOException if an I/O error occurs while sending the given {@code message} using the provided {@link Socket}. @see #newBufferedReader(Socket) @see java.io.BufferedReader#readLine() @see java.net.Socket
[ "Sends", "a", "simple", "{", "@link", "String", "message", "}", "over", "the", "given", "{", "@link", "Socket", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/tools/net/support/AbstractClientServerSupport.java#L203-L210
javers/javers
javers-core/src/main/java/org/javers/core/Changes.java
Changes.groupByObject
public List<ChangesByObject> groupByObject() { Map<GlobalId, List<Change>> changesByObject = changes.stream().collect( groupingBy(c -> c.getAffectedGlobalId().masterObjectId())); List<ChangesByObject> result = new ArrayList<>(); changesByObject.forEach((k, v) -> { result.add(new ChangesByObject(k, v, valuePrinter)); }); return Collections.unmodifiableList(result); }
java
public List<ChangesByObject> groupByObject() { Map<GlobalId, List<Change>> changesByObject = changes.stream().collect( groupingBy(c -> c.getAffectedGlobalId().masterObjectId())); List<ChangesByObject> result = new ArrayList<>(); changesByObject.forEach((k, v) -> { result.add(new ChangesByObject(k, v, valuePrinter)); }); return Collections.unmodifiableList(result); }
[ "public", "List", "<", "ChangesByObject", ">", "groupByObject", "(", ")", "{", "Map", "<", "GlobalId", ",", "List", "<", "Change", ">", ">", "changesByObject", "=", "changes", ".", "stream", "(", ")", ".", "collect", "(", "groupingBy", "(", "c", "->", ...
Changes grouped by entities. <br/> See example in {@link #groupByCommit()} @since 3.9
[ "Changes", "grouped", "by", "entities", ".", "<br", "/", ">" ]
train
https://github.com/javers/javers/blob/a51511be7d8bcee3e1812db8b7e69a45330b4e14/javers-core/src/main/java/org/javers/core/Changes.java#L106-L116
BlueBrain/bluima
modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java
diff_match_patch.diff_xIndex
public int diff_xIndex(LinkedList<Diff> diffs, int loc) { int chars1 = 0; int chars2 = 0; int last_chars1 = 0; int last_chars2 = 0; Diff lastDiff = null; for (Diff aDiff : diffs) { if (aDiff.operation != Operation.INSERT) { // Equality or deletion. chars1 += aDiff.text.length(); } if (aDiff.operation != Operation.DELETE) { // Equality or insertion. chars2 += aDiff.text.length(); } if (chars1 > loc) { // Overshot the location. lastDiff = aDiff; break; } last_chars1 = chars1; last_chars2 = chars2; } if (lastDiff != null && lastDiff.operation == Operation.DELETE) { // The location was deleted. return last_chars2; } // Add the remaining character length. return last_chars2 + (loc - last_chars1); }
java
public int diff_xIndex(LinkedList<Diff> diffs, int loc) { int chars1 = 0; int chars2 = 0; int last_chars1 = 0; int last_chars2 = 0; Diff lastDiff = null; for (Diff aDiff : diffs) { if (aDiff.operation != Operation.INSERT) { // Equality or deletion. chars1 += aDiff.text.length(); } if (aDiff.operation != Operation.DELETE) { // Equality or insertion. chars2 += aDiff.text.length(); } if (chars1 > loc) { // Overshot the location. lastDiff = aDiff; break; } last_chars1 = chars1; last_chars2 = chars2; } if (lastDiff != null && lastDiff.operation == Operation.DELETE) { // The location was deleted. return last_chars2; } // Add the remaining character length. return last_chars2 + (loc - last_chars1); }
[ "public", "int", "diff_xIndex", "(", "LinkedList", "<", "Diff", ">", "diffs", ",", "int", "loc", ")", "{", "int", "chars1", "=", "0", ";", "int", "chars2", "=", "0", ";", "int", "last_chars1", "=", "0", ";", "int", "last_chars2", "=", "0", ";", "Di...
loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 @param diffs LinkedList of Diff objects. @param loc Location within text1. @return Location within text2.
[ "loc", "is", "a", "location", "in", "text1", "compute", "and", "return", "the", "equivalent", "location", "in", "text2", ".", "e", ".", "g", ".", "The", "cat", "vs", "The", "big", "cat", "1", "-", ">", "1", "5", "-", ">", "8" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_pdf/src/main/java/ch/epfl/bbp/uima/pdf/grobid/diff_match_patch.java#L1415-L1444
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.serviceName_datacenter_datacenterId_host_hostId_GET
public OvhHost serviceName_datacenter_datacenterId_host_hostId_GET(String serviceName, Long datacenterId, Long hostId) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}"; StringBuilder sb = path(qPath, serviceName, datacenterId, hostId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhHost.class); }
java
public OvhHost serviceName_datacenter_datacenterId_host_hostId_GET(String serviceName, Long datacenterId, Long hostId) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId}"; StringBuilder sb = path(qPath, serviceName, datacenterId, hostId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhHost.class); }
[ "public", "OvhHost", "serviceName_datacenter_datacenterId_host_hostId_GET", "(", "String", "serviceName", ",", "Long", "datacenterId", ",", "Long", "hostId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/ho...
Get this object properties REST: GET /dedicatedCloud/{serviceName}/datacenter/{datacenterId}/host/{hostId} @param serviceName [required] Domain of the service @param datacenterId [required] @param hostId [required] Id of the host
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1620-L1625
alkacon/opencms-core
src/org/opencms/xml/CmsXmlContentDefinition.java
CmsXmlContentDefinition.getContentDefinitionForType
public static CmsXmlContentDefinition getContentDefinitionForType(CmsObject cms, String typeName) throws CmsException { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeName); String schema = resType.getConfiguration().get(CmsResourceTypeXmlContent.CONFIGURATION_SCHEMA); CmsXmlContentDefinition contentDef = null; if (schema == null) { return null; } contentDef = unmarshal(cms, schema); return contentDef; }
java
public static CmsXmlContentDefinition getContentDefinitionForType(CmsObject cms, String typeName) throws CmsException { I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeName); String schema = resType.getConfiguration().get(CmsResourceTypeXmlContent.CONFIGURATION_SCHEMA); CmsXmlContentDefinition contentDef = null; if (schema == null) { return null; } contentDef = unmarshal(cms, schema); return contentDef; }
[ "public", "static", "CmsXmlContentDefinition", "getContentDefinitionForType", "(", "CmsObject", "cms", ",", "String", "typeName", ")", "throws", "CmsException", "{", "I_CmsResourceType", "resType", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceTy...
Reads the content definition which is configured for a resource type.<p> @param cms the current CMS context @param typeName the type name @return the content definition @throws CmsException if something goes wrong
[ "Reads", "the", "content", "definition", "which", "is", "configured", "for", "a", "resource", "type", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlContentDefinition.java#L318-L329
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpClient.java
UdpClient.doOnDisconnected
public final UdpClient doOnDisconnected(Consumer<? super Connection> doOnDisconnected) { Objects.requireNonNull(doOnDisconnected, "doOnDisconnected"); return new UdpClientDoOn(this, null, null, doOnDisconnected); }
java
public final UdpClient doOnDisconnected(Consumer<? super Connection> doOnDisconnected) { Objects.requireNonNull(doOnDisconnected, "doOnDisconnected"); return new UdpClientDoOn(this, null, null, doOnDisconnected); }
[ "public", "final", "UdpClient", "doOnDisconnected", "(", "Consumer", "<", "?", "super", "Connection", ">", "doOnDisconnected", ")", "{", "Objects", ".", "requireNonNull", "(", "doOnDisconnected", ",", "\"doOnDisconnected\"", ")", ";", "return", "new", "UdpClientDoOn...
Setup a callback called when {@link io.netty.channel.Channel} is disconnected. @param doOnDisconnected a consumer observing client stop event @return a new {@link UdpClient}
[ "Setup", "a", "callback", "called", "when", "{", "@link", "io", ".", "netty", ".", "channel", ".", "Channel", "}", "is", "disconnected", "." ]
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpClient.java#L206-L209
sporniket/core
sporniket-core-lang/src/main/java/com/sporniket/libre/lang/CollectionTools.java
CollectionTools.getObject
public static Object getObject(final ResourceBundle source, final String key, final Object defaultValue) { try { return source.getObject(key); } catch (Exception _exception) { return defaultValue; } }
java
public static Object getObject(final ResourceBundle source, final String key, final Object defaultValue) { try { return source.getObject(key); } catch (Exception _exception) { return defaultValue; } }
[ "public", "static", "Object", "getObject", "(", "final", "ResourceBundle", "source", ",", "final", "String", "key", ",", "final", "Object", "defaultValue", ")", "{", "try", "{", "return", "source", ".", "getObject", "(", "key", ")", ";", "}", "catch", "(",...
Return an object from a ResourceBundle. @param source ResourceBundle from which extract the value @param key The key to retrieve the value @param defaultValue When the wanted value doesn't exist, return this one @return The wanted object or defaulValue
[ "Return", "an", "object", "from", "a", "ResourceBundle", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-lang/src/main/java/com/sporniket/libre/lang/CollectionTools.java#L54-L64
networknt/light-4j
utility/src/main/java/com/networknt/utility/RegExUtils.java
RegExUtils.replacePattern
public static String replacePattern(final String text, final String regex, final String replacement) { if (text == null || regex == null || replacement == null) { return text; } return Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement); }
java
public static String replacePattern(final String text, final String regex, final String replacement) { if (text == null || regex == null || replacement == null) { return text; } return Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement); }
[ "public", "static", "String", "replacePattern", "(", "final", "String", "text", ",", "final", "String", "regex", ",", "final", "String", "replacement", ")", "{", "if", "(", "text", "==", "null", "||", "regex", "==", "null", "||", "replacement", "==", "null...
<p>Replaces each substring of the source String that matches the given regular expression with the given replacement using the {@link Pattern#DOTALL} option. DOTALL is also known as single-line mode in Perl.</p> This call is a {@code null} safe equivalent to: <ul> <li>{@code text.replaceAll(&quot;(?s)&quot; + regex, replacement)}</li> <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement)}</li> </ul> <p>A {@code null} reference passed to this method is a no-op.</p> <pre> StringUtils.replacePattern(null, *, *) = null StringUtils.replacePattern("any", (String) null, *) = "any" StringUtils.replacePattern("any", *, null) = "any" StringUtils.replacePattern("", "", "zzz") = "zzz" StringUtils.replacePattern("", ".*", "zzz") = "zzz" StringUtils.replacePattern("", ".+", "zzz") = "" StringUtils.replacePattern("&lt;__&gt;\n&lt;__&gt;", "&lt;.*&gt;", "z") = "z" StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123" StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123" StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123" StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit" </pre> @param text the source string @param regex the regular expression to which this string is to be matched @param replacement the string to be substituted for each match @return The resulting {@code String} @see #replaceAll(String, String, String) @see String#replaceAll(String, String) @see Pattern#DOTALL
[ "<p", ">", "Replaces", "each", "substring", "of", "the", "source", "String", "that", "matches", "the", "given", "regular", "expression", "with", "the", "given", "replacement", "using", "the", "{", "@link", "Pattern#DOTALL", "}", "option", ".", "DOTALL", "is", ...
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/RegExUtils.java#L451-L456