repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
apache/incubator-gobblin
gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/HiveProxyQueryExecutor.java
HiveProxyQueryExecutor.executeQueries
public void executeQueries(List<String> queries, Optional<String> proxy) throws SQLException { """ Execute queries. @param queries the queries @param proxy the proxy @throws SQLException the sql exception """ Preconditions.checkArgument(!this.statementMap.isEmpty(), "No hive connection. Unable to execute queries"); if (!proxy.isPresent()) { Preconditions.checkArgument(this.statementMap.size() == 1, "Multiple Hive connections. Please specify a user"); proxy = Optional.fromNullable(this.statementMap.keySet().iterator().next()); } Statement statement = this.statementMap.get(proxy.get()); for (String query : queries) { statement.execute(query); } }
java
public void executeQueries(List<String> queries, Optional<String> proxy) throws SQLException { Preconditions.checkArgument(!this.statementMap.isEmpty(), "No hive connection. Unable to execute queries"); if (!proxy.isPresent()) { Preconditions.checkArgument(this.statementMap.size() == 1, "Multiple Hive connections. Please specify a user"); proxy = Optional.fromNullable(this.statementMap.keySet().iterator().next()); } Statement statement = this.statementMap.get(proxy.get()); for (String query : queries) { statement.execute(query); } }
[ "public", "void", "executeQueries", "(", "List", "<", "String", ">", "queries", ",", "Optional", "<", "String", ">", "proxy", ")", "throws", "SQLException", "{", "Preconditions", ".", "checkArgument", "(", "!", "this", ".", "statementMap", ".", "isEmpty", "(", ")", ",", "\"No hive connection. Unable to execute queries\"", ")", ";", "if", "(", "!", "proxy", ".", "isPresent", "(", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "this", ".", "statementMap", ".", "size", "(", ")", "==", "1", ",", "\"Multiple Hive connections. Please specify a user\"", ")", ";", "proxy", "=", "Optional", ".", "fromNullable", "(", "this", ".", "statementMap", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ";", "}", "Statement", "statement", "=", "this", ".", "statementMap", ".", "get", "(", "proxy", ".", "get", "(", ")", ")", ";", "for", "(", "String", "query", ":", "queries", ")", "{", "statement", ".", "execute", "(", "query", ")", ";", "}", "}" ]
Execute queries. @param queries the queries @param proxy the proxy @throws SQLException the sql exception
[ "Execute", "queries", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/HiveProxyQueryExecutor.java#L180-L191
apache/groovy
src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionWriter.java
BinaryExpressionWriter.writeBitwiseOp
protected boolean writeBitwiseOp(int type, boolean simulate) { """ writes some the bitwise operations. type is one of BITWISE_OR, BITWISE_AND, BITWISE_XOR @param type the token type @return true if a successful bitwise operation write """ type = type-BITWISE_OR; if (type<0 || type>2) return false; if (!simulate) { int bytecode = getBitwiseOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; }
java
protected boolean writeBitwiseOp(int type, boolean simulate) { type = type-BITWISE_OR; if (type<0 || type>2) return false; if (!simulate) { int bytecode = getBitwiseOperationBytecode(type); controller.getMethodVisitor().visitInsn(bytecode); controller.getOperandStack().replace(getNormalOpResultType(), 2); } return true; }
[ "protected", "boolean", "writeBitwiseOp", "(", "int", "type", ",", "boolean", "simulate", ")", "{", "type", "=", "type", "-", "BITWISE_OR", ";", "if", "(", "type", "<", "0", "||", "type", ">", "2", ")", "return", "false", ";", "if", "(", "!", "simulate", ")", "{", "int", "bytecode", "=", "getBitwiseOperationBytecode", "(", "type", ")", ";", "controller", ".", "getMethodVisitor", "(", ")", ".", "visitInsn", "(", "bytecode", ")", ";", "controller", ".", "getOperandStack", "(", ")", ".", "replace", "(", "getNormalOpResultType", "(", ")", ",", "2", ")", ";", "}", "return", "true", ";", "}" ]
writes some the bitwise operations. type is one of BITWISE_OR, BITWISE_AND, BITWISE_XOR @param type the token type @return true if a successful bitwise operation write
[ "writes", "some", "the", "bitwise", "operations", ".", "type", "is", "one", "of", "BITWISE_OR", "BITWISE_AND", "BITWISE_XOR" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionWriter.java#L238-L248
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbDiscover.java
TmdbDiscover.getDiscoverMovies
public ResultList<MovieBasic> getDiscoverMovies(Discover discover) throws MovieDbException { """ Discover movies by different types of data like average rating, number of votes, genres and certifications. @param discover A discover object containing the search criteria required @return @throws MovieDbException """ URL url = new ApiUrl(apiKey, MethodBase.DISCOVER).subMethod(MethodSub.MOVIE).buildUrl(discover.getParams()); String webpage = httpTools.getRequest(url); WrapperGenericList<MovieBasic> wrapper = processWrapper(getTypeReference(MovieBasic.class), url, webpage); return wrapper.getResultsList(); }
java
public ResultList<MovieBasic> getDiscoverMovies(Discover discover) throws MovieDbException { URL url = new ApiUrl(apiKey, MethodBase.DISCOVER).subMethod(MethodSub.MOVIE).buildUrl(discover.getParams()); String webpage = httpTools.getRequest(url); WrapperGenericList<MovieBasic> wrapper = processWrapper(getTypeReference(MovieBasic.class), url, webpage); return wrapper.getResultsList(); }
[ "public", "ResultList", "<", "MovieBasic", ">", "getDiscoverMovies", "(", "Discover", "discover", ")", "throws", "MovieDbException", "{", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "DISCOVER", ")", ".", "subMethod", "(", "MethodSub", ".", "MOVIE", ")", ".", "buildUrl", "(", "discover", ".", "getParams", "(", ")", ")", ";", "String", "webpage", "=", "httpTools", ".", "getRequest", "(", "url", ")", ";", "WrapperGenericList", "<", "MovieBasic", ">", "wrapper", "=", "processWrapper", "(", "getTypeReference", "(", "MovieBasic", ".", "class", ")", ",", "url", ",", "webpage", ")", ";", "return", "wrapper", ".", "getResultsList", "(", ")", ";", "}" ]
Discover movies by different types of data like average rating, number of votes, genres and certifications. @param discover A discover object containing the search criteria required @return @throws MovieDbException
[ "Discover", "movies", "by", "different", "types", "of", "data", "like", "average", "rating", "number", "of", "votes", "genres", "and", "certifications", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbDiscover.java#L58-L63
Waikato/jclasslocator
src/main/java/nz/ac/waikato/cms/locator/ClassLister.java
ClassLister.updateClassnames
protected void updateClassnames(HashMap<String,List<String>> list, String superclass, List<String> names) { """ Updates list for the superclass. @param list the list to update @param superclass the superclass @param names the names to add """ if (!list.containsKey(superclass)) { list.put(superclass, names); } else { for (String name: names) { if (!list.get(superclass).contains(name)) list.get(superclass).add(name); } } }
java
protected void updateClassnames(HashMap<String,List<String>> list, String superclass, List<String> names) { if (!list.containsKey(superclass)) { list.put(superclass, names); } else { for (String name: names) { if (!list.get(superclass).contains(name)) list.get(superclass).add(name); } } }
[ "protected", "void", "updateClassnames", "(", "HashMap", "<", "String", ",", "List", "<", "String", ">", ">", "list", ",", "String", "superclass", ",", "List", "<", "String", ">", "names", ")", "{", "if", "(", "!", "list", ".", "containsKey", "(", "superclass", ")", ")", "{", "list", ".", "put", "(", "superclass", ",", "names", ")", ";", "}", "else", "{", "for", "(", "String", "name", ":", "names", ")", "{", "if", "(", "!", "list", ".", "get", "(", "superclass", ")", ".", "contains", "(", "name", ")", ")", "list", ".", "get", "(", "superclass", ")", ".", "add", "(", "name", ")", ";", "}", "}", "}" ]
Updates list for the superclass. @param list the list to update @param superclass the superclass @param names the names to add
[ "Updates", "list", "for", "the", "superclass", "." ]
train
https://github.com/Waikato/jclasslocator/blob/c899072fff607a56ee7f8c2d01fbeb15157ad144/src/main/java/nz/ac/waikato/cms/locator/ClassLister.java#L233-L243
voldemort/voldemort
src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java
QueuedKeyedResourcePool.internalNonBlockingGet
public V internalNonBlockingGet(K key) throws Exception { """ Used only for unit testing. Please do not use this method in other ways. @param key @return @throws Exception """ Pool<V> resourcePool = getResourcePoolForKey(key); return attemptNonBlockingCheckout(key, resourcePool); }
java
public V internalNonBlockingGet(K key) throws Exception { Pool<V> resourcePool = getResourcePoolForKey(key); return attemptNonBlockingCheckout(key, resourcePool); }
[ "public", "V", "internalNonBlockingGet", "(", "K", "key", ")", "throws", "Exception", "{", "Pool", "<", "V", ">", "resourcePool", "=", "getResourcePoolForKey", "(", "key", ")", ";", "return", "attemptNonBlockingCheckout", "(", "key", ",", "resourcePool", ")", ";", "}" ]
Used only for unit testing. Please do not use this method in other ways. @param key @return @throws Exception
[ "Used", "only", "for", "unit", "testing", ".", "Please", "do", "not", "use", "this", "method", "in", "other", "ways", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/pool/QueuedKeyedResourcePool.java#L131-L134
CenturyLinkCloud/clc-java-sdk
sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/InvoiceService.java
InvoiceService.getInvoice
public InvoiceData getInvoice(LocalDate date, String pricingAccountAlias) { """ Gets a list of invoicing data for a given account alias for a given month. @param date Date of usage @param pricingAccountAlias Short code of the account that sends the invoice for the accountAlias @return the invoice data """ return getInvoice(date.getYear(), date.getMonthValue(), pricingAccountAlias); }
java
public InvoiceData getInvoice(LocalDate date, String pricingAccountAlias) { return getInvoice(date.getYear(), date.getMonthValue(), pricingAccountAlias); }
[ "public", "InvoiceData", "getInvoice", "(", "LocalDate", "date", ",", "String", "pricingAccountAlias", ")", "{", "return", "getInvoice", "(", "date", ".", "getYear", "(", ")", ",", "date", ".", "getMonthValue", "(", ")", ",", "pricingAccountAlias", ")", ";", "}" ]
Gets a list of invoicing data for a given account alias for a given month. @param date Date of usage @param pricingAccountAlias Short code of the account that sends the invoice for the accountAlias @return the invoice data
[ "Gets", "a", "list", "of", "invoicing", "data", "for", "a", "given", "account", "alias", "for", "a", "given", "month", "." ]
train
https://github.com/CenturyLinkCloud/clc-java-sdk/blob/c026322f077dea71b1acf9f2d665253d79d9bf85/sdk/src/main/java/com/centurylink/cloud/sdk/server/services/dsl/InvoiceService.java#L76-L78
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) { """ 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 """ 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", "(", "cuGraphInstantiateNative", "(", "phGraphExec", ",", "hGraph", ",", "phErrorNode", ",", "logBuffer", ",", "bufferSize", ")", ")", ";", "}" ]
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", "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", ">" ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L12946-L12949
hankcs/HanLP
src/main/java/com/hankcs/hanlp/seg/common/Vertex.java
Vertex.confirmNature
public boolean confirmNature(Nature nature, boolean updateWord) { """ 将属性的词性锁定为nature,此重载会降低性能 @param nature 词性 @param updateWord 是否更新预编译字串 @return 如果锁定词性在词性列表中,返回真,否则返回假 """ switch (nature.firstChar()) { case 'm': word = Predefine.TAG_NUMBER; break; case 't': word = Predefine.TAG_TIME; break; default: logger.warning("没有与" + nature + "对应的case"); break; } return confirmNature(nature); }
java
public boolean confirmNature(Nature nature, boolean updateWord) { switch (nature.firstChar()) { case 'm': word = Predefine.TAG_NUMBER; break; case 't': word = Predefine.TAG_TIME; break; default: logger.warning("没有与" + nature + "对应的case"); break; } return confirmNature(nature); }
[ "public", "boolean", "confirmNature", "(", "Nature", "nature", ",", "boolean", "updateWord", ")", "{", "switch", "(", "nature", ".", "firstChar", "(", ")", ")", "{", "case", "'", "'", ":", "word", "=", "Predefine", ".", "TAG_NUMBER", ";", "break", ";", "case", "'", "'", ":", "word", "=", "Predefine", ".", "TAG_TIME", ";", "break", ";", "default", ":", "logger", ".", "warning", "(", "\"没有与\" + nat", "r", " + \"对应", "c", "se\");", "", "", "break", ";", "}", "return", "confirmNature", "(", "nature", ")", ";", "}" ]
将属性的词性锁定为nature,此重载会降低性能 @param nature 词性 @param updateWord 是否更新预编译字串 @return 如果锁定词性在词性列表中,返回真,否则返回假
[ "将属性的词性锁定为nature,此重载会降低性能" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/seg/common/Vertex.java#L265-L282
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/trees/Treebank.java
Treebank.decimate
public void decimate(Writer trainW, Writer devW, Writer testW) throws IOException { """ Divide a Treebank into 3, by taking every 9th sentence for the dev set and every 10th for the test set. Penn people do this. """ PrintWriter trainPW = new PrintWriter(trainW, true); PrintWriter devPW = new PrintWriter(devW, true); PrintWriter testPW = new PrintWriter(testW, true); int i = 0; for (Tree t : this) { if (i == 8) { t.pennPrint(devPW); } else if (i == 9) { t.pennPrint(testPW); } else { t.pennPrint(trainPW); } i = (i+1) % 10; } }
java
public void decimate(Writer trainW, Writer devW, Writer testW) throws IOException { PrintWriter trainPW = new PrintWriter(trainW, true); PrintWriter devPW = new PrintWriter(devW, true); PrintWriter testPW = new PrintWriter(testW, true); int i = 0; for (Tree t : this) { if (i == 8) { t.pennPrint(devPW); } else if (i == 9) { t.pennPrint(testPW); } else { t.pennPrint(trainPW); } i = (i+1) % 10; } }
[ "public", "void", "decimate", "(", "Writer", "trainW", ",", "Writer", "devW", ",", "Writer", "testW", ")", "throws", "IOException", "{", "PrintWriter", "trainPW", "=", "new", "PrintWriter", "(", "trainW", ",", "true", ")", ";", "PrintWriter", "devPW", "=", "new", "PrintWriter", "(", "devW", ",", "true", ")", ";", "PrintWriter", "testPW", "=", "new", "PrintWriter", "(", "testW", ",", "true", ")", ";", "int", "i", "=", "0", ";", "for", "(", "Tree", "t", ":", "this", ")", "{", "if", "(", "i", "==", "8", ")", "{", "t", ".", "pennPrint", "(", "devPW", ")", ";", "}", "else", "if", "(", "i", "==", "9", ")", "{", "t", ".", "pennPrint", "(", "testPW", ")", ";", "}", "else", "{", "t", ".", "pennPrint", "(", "trainPW", ")", ";", "}", "i", "=", "(", "i", "+", "1", ")", "%", "10", ";", "}", "}" ]
Divide a Treebank into 3, by taking every 9th sentence for the dev set and every 10th for the test set. Penn people do this.
[ "Divide", "a", "Treebank", "into", "3", "by", "taking", "every", "9th", "sentence", "for", "the", "dev", "set", "and", "every", "10th", "for", "the", "test", "set", ".", "Penn", "people", "do", "this", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/Treebank.java#L276-L291
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/contentassist/SARLProposalProvider.java
SARLProposalProvider.getExpectedPackageName
protected String getExpectedPackageName(EObject model) { """ Replies the expected package for the given model. @param model the model. @return the expected package name. """ final URI fileURI = model.eResource().getURI(); for (final Pair<IStorage, IProject> storage: this.storage2UriMapper.getStorages(fileURI)) { if (storage.getFirst() instanceof IFile) { final IPath fileWorkspacePath = storage.getFirst().getFullPath(); final IJavaProject javaProject = JavaCore.create(storage.getSecond()); return extractProjectPath(fileWorkspacePath, javaProject); } } return null; }
java
protected String getExpectedPackageName(EObject model) { final URI fileURI = model.eResource().getURI(); for (final Pair<IStorage, IProject> storage: this.storage2UriMapper.getStorages(fileURI)) { if (storage.getFirst() instanceof IFile) { final IPath fileWorkspacePath = storage.getFirst().getFullPath(); final IJavaProject javaProject = JavaCore.create(storage.getSecond()); return extractProjectPath(fileWorkspacePath, javaProject); } } return null; }
[ "protected", "String", "getExpectedPackageName", "(", "EObject", "model", ")", "{", "final", "URI", "fileURI", "=", "model", ".", "eResource", "(", ")", ".", "getURI", "(", ")", ";", "for", "(", "final", "Pair", "<", "IStorage", ",", "IProject", ">", "storage", ":", "this", ".", "storage2UriMapper", ".", "getStorages", "(", "fileURI", ")", ")", "{", "if", "(", "storage", ".", "getFirst", "(", ")", "instanceof", "IFile", ")", "{", "final", "IPath", "fileWorkspacePath", "=", "storage", ".", "getFirst", "(", ")", ".", "getFullPath", "(", ")", ";", "final", "IJavaProject", "javaProject", "=", "JavaCore", ".", "create", "(", "storage", ".", "getSecond", "(", ")", ")", ";", "return", "extractProjectPath", "(", "fileWorkspacePath", ",", "javaProject", ")", ";", "}", "}", "return", "null", ";", "}" ]
Replies the expected package for the given model. @param model the model. @return the expected package name.
[ "Replies", "the", "expected", "package", "for", "the", "given", "model", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/contentassist/SARLProposalProvider.java#L337-L347
duracloud/duracloud
security/src/main/java/org/duracloud/security/vote/UserIpLimitsAccessVoter.java
UserIpLimitsAccessVoter.ipInRange
protected boolean ipInRange(String ipAddress, String range) { """ Determines if a given IP address is in the given IP range. @param ipAddress single IP address @param range IP address range using CIDR notation @return true if the address is in the range, false otherwise """ IpAddressMatcher addressMatcher = new IpAddressMatcher(range); return addressMatcher.matches(ipAddress); }
java
protected boolean ipInRange(String ipAddress, String range) { IpAddressMatcher addressMatcher = new IpAddressMatcher(range); return addressMatcher.matches(ipAddress); }
[ "protected", "boolean", "ipInRange", "(", "String", "ipAddress", ",", "String", "range", ")", "{", "IpAddressMatcher", "addressMatcher", "=", "new", "IpAddressMatcher", "(", "range", ")", ";", "return", "addressMatcher", ".", "matches", "(", "ipAddress", ")", ";", "}" ]
Determines if a given IP address is in the given IP range. @param ipAddress single IP address @param range IP address range using CIDR notation @return true if the address is in the range, false otherwise
[ "Determines", "if", "a", "given", "IP", "address", "is", "in", "the", "given", "IP", "range", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/security/src/main/java/org/duracloud/security/vote/UserIpLimitsAccessVoter.java#L138-L141
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/CmsEditorBase.java
CmsEditorBase.getMessageForKey
public static String getMessageForKey(String key, Object... args) { """ Returns the formated message.<p> @param key the message key @param args the parameters to insert into the placeholders @return the formated message """ String result = null; if (hasDictionary()) { result = m_dictionary.get(key); if ((result != null) && (args != null) && (args.length > 0)) { for (int i = 0; i < args.length; i++) { result = result.replace("{" + i + "}", String.valueOf(args[i])); } } } if (result == null) { result = ""; } return result; }
java
public static String getMessageForKey(String key, Object... args) { String result = null; if (hasDictionary()) { result = m_dictionary.get(key); if ((result != null) && (args != null) && (args.length > 0)) { for (int i = 0; i < args.length; i++) { result = result.replace("{" + i + "}", String.valueOf(args[i])); } } } if (result == null) { result = ""; } return result; }
[ "public", "static", "String", "getMessageForKey", "(", "String", "key", ",", "Object", "...", "args", ")", "{", "String", "result", "=", "null", ";", "if", "(", "hasDictionary", "(", ")", ")", "{", "result", "=", "m_dictionary", ".", "get", "(", "key", ")", ";", "if", "(", "(", "result", "!=", "null", ")", "&&", "(", "args", "!=", "null", ")", "&&", "(", "args", ".", "length", ">", "0", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "result", "=", "result", ".", "replace", "(", "\"{\"", "+", "i", "+", "\"}\"", ",", "String", ".", "valueOf", "(", "args", "[", "i", "]", ")", ")", ";", "}", "}", "}", "if", "(", "result", "==", "null", ")", "{", "result", "=", "\"\"", ";", "}", "return", "result", ";", "}" ]
Returns the formated message.<p> @param key the message key @param args the parameters to insert into the placeholders @return the formated message
[ "Returns", "the", "formated", "message", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/CmsEditorBase.java#L202-L217
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/JDBCStorageConnection.java
JDBCStorageConnection.getNodesCount
public long getNodesCount() throws RepositoryException { """ Reads count of nodes in workspace. @return nodes count @throws RepositoryException if a database access error occurs """ try { ResultSet countNodes = findNodesCount(); try { if (countNodes.next()) { return countNodes.getLong(1); } else { throw new SQLException("ResultSet has't records."); } } finally { JDBCUtils.freeResources(countNodes, null, null); } } catch (SQLException e) { throw new RepositoryException("Can not calculate nodes count", e); } }
java
public long getNodesCount() throws RepositoryException { try { ResultSet countNodes = findNodesCount(); try { if (countNodes.next()) { return countNodes.getLong(1); } else { throw new SQLException("ResultSet has't records."); } } finally { JDBCUtils.freeResources(countNodes, null, null); } } catch (SQLException e) { throw new RepositoryException("Can not calculate nodes count", e); } }
[ "public", "long", "getNodesCount", "(", ")", "throws", "RepositoryException", "{", "try", "{", "ResultSet", "countNodes", "=", "findNodesCount", "(", ")", ";", "try", "{", "if", "(", "countNodes", ".", "next", "(", ")", ")", "{", "return", "countNodes", ".", "getLong", "(", "1", ")", ";", "}", "else", "{", "throw", "new", "SQLException", "(", "\"ResultSet has't records.\"", ")", ";", "}", "}", "finally", "{", "JDBCUtils", ".", "freeResources", "(", "countNodes", ",", "null", ",", "null", ")", ";", "}", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "new", "RepositoryException", "(", "\"Can not calculate nodes count\"", ",", "e", ")", ";", "}", "}" ]
Reads count of nodes in workspace. @return nodes count @throws RepositoryException if a database access error occurs
[ "Reads", "count", "of", "nodes", "in", "workspace", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/JDBCStorageConnection.java#L1533-L1558
threerings/playn
core/src/playn/core/gl/GLContext.java
GLContext.pushFramebuffer
public void pushFramebuffer(int fbuf, int width, int height) { """ Stores the metadata for the currently bound frame buffer, and binds the supplied framebuffer. This must be followed by a call to {@link #popFramebuffer}. Also, it is not allowed to push a framebuffer if a framebuffer is already pushed. Only one level of nesting is supported. """ assert pushedFramebuffer == -1 : "Already have a pushed framebuffer"; pushedFramebuffer = lastFramebuffer; pushedWidth = curFbufWidth; pushedHeight = curFbufHeight; bindFramebuffer(fbuf, width, height); }
java
public void pushFramebuffer(int fbuf, int width, int height) { assert pushedFramebuffer == -1 : "Already have a pushed framebuffer"; pushedFramebuffer = lastFramebuffer; pushedWidth = curFbufWidth; pushedHeight = curFbufHeight; bindFramebuffer(fbuf, width, height); }
[ "public", "void", "pushFramebuffer", "(", "int", "fbuf", ",", "int", "width", ",", "int", "height", ")", "{", "assert", "pushedFramebuffer", "==", "-", "1", ":", "\"Already have a pushed framebuffer\"", ";", "pushedFramebuffer", "=", "lastFramebuffer", ";", "pushedWidth", "=", "curFbufWidth", ";", "pushedHeight", "=", "curFbufHeight", ";", "bindFramebuffer", "(", "fbuf", ",", "width", ",", "height", ")", ";", "}" ]
Stores the metadata for the currently bound frame buffer, and binds the supplied framebuffer. This must be followed by a call to {@link #popFramebuffer}. Also, it is not allowed to push a framebuffer if a framebuffer is already pushed. Only one level of nesting is supported.
[ "Stores", "the", "metadata", "for", "the", "currently", "bound", "frame", "buffer", "and", "binds", "the", "supplied", "framebuffer", ".", "This", "must", "be", "followed", "by", "a", "call", "to", "{" ]
train
https://github.com/threerings/playn/blob/c266eeb39188dcada4b00992a0d1199759e03d42/core/src/playn/core/gl/GLContext.java#L263-L269
k0shk0sh/PermissionHelper
permission/src/main/java/com/fastaccess/permission/base/PermissionFragmentHelper.java
PermissionFragmentHelper.declinedPermission
@Nullable public static String declinedPermission(@NonNull Fragment context, @NonNull String[] permissions) { """ be aware as it might return null (do check if the returned result is not null!) <p/> can be used outside of activity. """ for (String permission : permissions) { if (isPermissionDeclined(context, permission)) { return permission; } } return null; }
java
@Nullable public static String declinedPermission(@NonNull Fragment context, @NonNull String[] permissions) { for (String permission : permissions) { if (isPermissionDeclined(context, permission)) { return permission; } } return null; }
[ "@", "Nullable", "public", "static", "String", "declinedPermission", "(", "@", "NonNull", "Fragment", "context", ",", "@", "NonNull", "String", "[", "]", "permissions", ")", "{", "for", "(", "String", "permission", ":", "permissions", ")", "{", "if", "(", "isPermissionDeclined", "(", "context", ",", "permission", ")", ")", "{", "return", "permission", ";", "}", "}", "return", "null", ";", "}" ]
be aware as it might return null (do check if the returned result is not null!) <p/> can be used outside of activity.
[ "be", "aware", "as", "it", "might", "return", "null", "(", "do", "check", "if", "the", "returned", "result", "is", "not", "null!", ")", "<p", "/", ">", "can", "be", "used", "outside", "of", "activity", "." ]
train
https://github.com/k0shk0sh/PermissionHelper/blob/04edce2af49981d1dd321bcdfbe981a1000b29d7/permission/src/main/java/com/fastaccess/permission/base/PermissionFragmentHelper.java#L302-L309
biojava/biojava
biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java
ChromosomeMappingTools.getChromosomalRangesForCDS
public static List<Range<Integer>> getChromosomalRangesForCDS(GeneChromosomePosition chromPos) { """ Extracts the boundaries of the coding regions in chromosomal coordinates @param chromPos @return """ if ( chromPos.getOrientation() == '+') return getCDSExonRangesForward(chromPos,CHROMOSOME); return getCDSExonRangesReverse(chromPos,CHROMOSOME); }
java
public static List<Range<Integer>> getChromosomalRangesForCDS(GeneChromosomePosition chromPos){ if ( chromPos.getOrientation() == '+') return getCDSExonRangesForward(chromPos,CHROMOSOME); return getCDSExonRangesReverse(chromPos,CHROMOSOME); }
[ "public", "static", "List", "<", "Range", "<", "Integer", ">", ">", "getChromosomalRangesForCDS", "(", "GeneChromosomePosition", "chromPos", ")", "{", "if", "(", "chromPos", ".", "getOrientation", "(", ")", "==", "'", "'", ")", "return", "getCDSExonRangesForward", "(", "chromPos", ",", "CHROMOSOME", ")", ";", "return", "getCDSExonRangesReverse", "(", "chromPos", ",", "CHROMOSOME", ")", ";", "}" ]
Extracts the boundaries of the coding regions in chromosomal coordinates @param chromPos @return
[ "Extracts", "the", "boundaries", "of", "the", "coding", "regions", "in", "chromosomal", "coordinates" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java#L588-L592
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) { """ 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. """ 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", "}", ")", ";", "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", ";", "}" ]
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", "user", "s", "actual", "data", "type", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelDataProviderImpl.java#L388-L405
hibernate/hibernate-ogm
neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jAssociationQueries.java
BaseNeo4jAssociationQueries.initRemoveAssociationQuery
private static String initRemoveAssociationQuery(EntityKeyMetadata ownerEntityKeyMetadata, AssociationKeyMetadata associationKeyMetadata) { """ /* Example with association: MATCH (n:ENTITY:table {id: {0}}) -[r:role] - () DELETE r Example with an embedded association: MATCH (n:ENTITY:table {id: {0}}) -[a:role] - (e:EMBEDDED) WITH a, e MATCH path=(e) -[*0..]-> (:EMBEDDED) FOREACH (r IN relationships(path) | DELETE r) FOREACH (e IN nodes(path) | DELETE e) DELETE a """ StringBuilder queryBuilder = new StringBuilder( "MATCH " ); queryBuilder.append( "(n:" ); queryBuilder.append( ENTITY ); queryBuilder.append( ":" ); appendLabel( ownerEntityKeyMetadata, queryBuilder ); appendProperties( ownerEntityKeyMetadata, queryBuilder ); queryBuilder.append( ") - " ); queryBuilder.append( "[a" ); queryBuilder.append( ":" ); appendRelationshipType( queryBuilder, associationKeyMetadata ); queryBuilder.append( "]" ); if ( associationKeyMetadata.getAssociationKind() == AssociationKind.EMBEDDED_COLLECTION ) { queryBuilder.append( " - (e:" ); queryBuilder.append( EMBEDDED ); queryBuilder.append( ")" ); queryBuilder.append( " WITH a,e" ); queryBuilder.append( " MATCH path=(e) -[*0..]-> (:EMBEDDED) " ); queryBuilder.append( " FOREACH ( r IN relationships(path) | DELETE r )" ); queryBuilder.append( " FOREACH ( e IN nodes(path) | DELETE e )" ); queryBuilder.append( " DELETE a" ); } else { queryBuilder.append( " - () DELETE a" ); } return queryBuilder.toString(); }
java
private static String initRemoveAssociationQuery(EntityKeyMetadata ownerEntityKeyMetadata, AssociationKeyMetadata associationKeyMetadata) { StringBuilder queryBuilder = new StringBuilder( "MATCH " ); queryBuilder.append( "(n:" ); queryBuilder.append( ENTITY ); queryBuilder.append( ":" ); appendLabel( ownerEntityKeyMetadata, queryBuilder ); appendProperties( ownerEntityKeyMetadata, queryBuilder ); queryBuilder.append( ") - " ); queryBuilder.append( "[a" ); queryBuilder.append( ":" ); appendRelationshipType( queryBuilder, associationKeyMetadata ); queryBuilder.append( "]" ); if ( associationKeyMetadata.getAssociationKind() == AssociationKind.EMBEDDED_COLLECTION ) { queryBuilder.append( " - (e:" ); queryBuilder.append( EMBEDDED ); queryBuilder.append( ")" ); queryBuilder.append( " WITH a,e" ); queryBuilder.append( " MATCH path=(e) -[*0..]-> (:EMBEDDED) " ); queryBuilder.append( " FOREACH ( r IN relationships(path) | DELETE r )" ); queryBuilder.append( " FOREACH ( e IN nodes(path) | DELETE e )" ); queryBuilder.append( " DELETE a" ); } else { queryBuilder.append( " - () DELETE a" ); } return queryBuilder.toString(); }
[ "private", "static", "String", "initRemoveAssociationQuery", "(", "EntityKeyMetadata", "ownerEntityKeyMetadata", ",", "AssociationKeyMetadata", "associationKeyMetadata", ")", "{", "StringBuilder", "queryBuilder", "=", "new", "StringBuilder", "(", "\"MATCH \"", ")", ";", "queryBuilder", ".", "append", "(", "\"(n:\"", ")", ";", "queryBuilder", ".", "append", "(", "ENTITY", ")", ";", "queryBuilder", ".", "append", "(", "\":\"", ")", ";", "appendLabel", "(", "ownerEntityKeyMetadata", ",", "queryBuilder", ")", ";", "appendProperties", "(", "ownerEntityKeyMetadata", ",", "queryBuilder", ")", ";", "queryBuilder", ".", "append", "(", "\") - \"", ")", ";", "queryBuilder", ".", "append", "(", "\"[a\"", ")", ";", "queryBuilder", ".", "append", "(", "\":\"", ")", ";", "appendRelationshipType", "(", "queryBuilder", ",", "associationKeyMetadata", ")", ";", "queryBuilder", ".", "append", "(", "\"]\"", ")", ";", "if", "(", "associationKeyMetadata", ".", "getAssociationKind", "(", ")", "==", "AssociationKind", ".", "EMBEDDED_COLLECTION", ")", "{", "queryBuilder", ".", "append", "(", "\" - (e:\"", ")", ";", "queryBuilder", ".", "append", "(", "EMBEDDED", ")", ";", "queryBuilder", ".", "append", "(", "\")\"", ")", ";", "queryBuilder", ".", "append", "(", "\" WITH a,e\"", ")", ";", "queryBuilder", ".", "append", "(", "\" MATCH path=(e) -[*0..]-> (:EMBEDDED) \"", ")", ";", "queryBuilder", ".", "append", "(", "\" FOREACH ( r IN relationships(path) | DELETE r )\"", ")", ";", "queryBuilder", ".", "append", "(", "\" FOREACH ( e IN nodes(path) | DELETE e )\"", ")", ";", "queryBuilder", ".", "append", "(", "\" DELETE a\"", ")", ";", "}", "else", "{", "queryBuilder", ".", "append", "(", "\" - () DELETE a\"", ")", ";", "}", "return", "queryBuilder", ".", "toString", "(", ")", ";", "}" ]
/* Example with association: MATCH (n:ENTITY:table {id: {0}}) -[r:role] - () DELETE r Example with an embedded association: MATCH (n:ENTITY:table {id: {0}}) -[a:role] - (e:EMBEDDED) WITH a, e MATCH path=(e) -[*0..]-> (:EMBEDDED) FOREACH (r IN relationships(path) | DELETE r) FOREACH (e IN nodes(path) | DELETE e) DELETE a
[ "/", "*", "Example", "with", "association", ":" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jAssociationQueries.java#L146-L172
hector-client/hector
object-mapper/src/main/java/me/prettyprint/hom/EntityManagerImpl.java
EntityManagerImpl.find
public <T> T find(Class<T> clazz, Object id, ColumnSlice<String, byte[]> colSlice) { """ Load an entity instance given the raw column slice. This is a stop gap solution for instanting objects using entity manager while iterating over rows. @param <T> The type of entity to load for compile time type checking @param clazz The type of entity to load for runtime instance creation @param id ID of the instance to load @param colSlice Raw row slice as returned from Hector API, of the type <code>ColumnSlice<String, byte[]></code> @return Completely instantiated persisted object """ if (null == clazz) { throw new IllegalArgumentException("clazz cannot be null"); } if (null == id) { throw new IllegalArgumentException("id cannot be null"); } CFMappingDef<T> cfMapDef = cacheMgr.getCfMapDef(clazz, false); if (null == cfMapDef) { throw new HectorObjectMapperException("No class annotated with @" + Entity.class.getSimpleName() + " for type, " + clazz.getName()); } T obj = objMapper.createObject(cfMapDef, id, colSlice); return obj; }
java
public <T> T find(Class<T> clazz, Object id, ColumnSlice<String, byte[]> colSlice) { if (null == clazz) { throw new IllegalArgumentException("clazz cannot be null"); } if (null == id) { throw new IllegalArgumentException("id cannot be null"); } CFMappingDef<T> cfMapDef = cacheMgr.getCfMapDef(clazz, false); if (null == cfMapDef) { throw new HectorObjectMapperException("No class annotated with @" + Entity.class.getSimpleName() + " for type, " + clazz.getName()); } T obj = objMapper.createObject(cfMapDef, id, colSlice); return obj; }
[ "public", "<", "T", ">", "T", "find", "(", "Class", "<", "T", ">", "clazz", ",", "Object", "id", ",", "ColumnSlice", "<", "String", ",", "byte", "[", "]", ">", "colSlice", ")", "{", "if", "(", "null", "==", "clazz", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"clazz cannot be null\"", ")", ";", "}", "if", "(", "null", "==", "id", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"id cannot be null\"", ")", ";", "}", "CFMappingDef", "<", "T", ">", "cfMapDef", "=", "cacheMgr", ".", "getCfMapDef", "(", "clazz", ",", "false", ")", ";", "if", "(", "null", "==", "cfMapDef", ")", "{", "throw", "new", "HectorObjectMapperException", "(", "\"No class annotated with @\"", "+", "Entity", ".", "class", ".", "getSimpleName", "(", ")", "+", "\" for type, \"", "+", "clazz", ".", "getName", "(", ")", ")", ";", "}", "T", "obj", "=", "objMapper", ".", "createObject", "(", "cfMapDef", ",", "id", ",", "colSlice", ")", ";", "return", "obj", ";", "}" ]
Load an entity instance given the raw column slice. This is a stop gap solution for instanting objects using entity manager while iterating over rows. @param <T> The type of entity to load for compile time type checking @param clazz The type of entity to load for runtime instance creation @param id ID of the instance to load @param colSlice Raw row slice as returned from Hector API, of the type <code>ColumnSlice<String, byte[]></code> @return Completely instantiated persisted object
[ "Load", "an", "entity", "instance", "given", "the", "raw", "column", "slice", ".", "This", "is", "a", "stop", "gap", "solution", "for", "instanting", "objects", "using", "entity", "manager", "while", "iterating", "over", "rows", "." ]
train
https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/object-mapper/src/main/java/me/prettyprint/hom/EntityManagerImpl.java#L177-L193
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.persistProperties
public synchronized void persistProperties(Properties properties, File propsFile, String message) { """ Persist properties that are not system env or other system properties, in a thread synchronized manner """ Properties toWrite = new Properties(); for(String key : properties.stringPropertyNames()) { if(System.getProperties().containsKey(key) && !properties.getProperty(key).equals(System.getProperty(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(System.getenv().containsKey(key) && !properties.getProperty(key).equals(System.getenv(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(!System.getProperties().containsKey(key) && !System.getenv().containsKey(key)){ toWrite.setProperty(key, properties.getProperty(key)); } } writer.persistProperties(toWrite, propsFile, message, log); }
java
public synchronized void persistProperties(Properties properties, File propsFile, String message) { Properties toWrite = new Properties(); for(String key : properties.stringPropertyNames()) { if(System.getProperties().containsKey(key) && !properties.getProperty(key).equals(System.getProperty(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(System.getenv().containsKey(key) && !properties.getProperty(key).equals(System.getenv(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(!System.getProperties().containsKey(key) && !System.getenv().containsKey(key)){ toWrite.setProperty(key, properties.getProperty(key)); } } writer.persistProperties(toWrite, propsFile, message, log); }
[ "public", "synchronized", "void", "persistProperties", "(", "Properties", "properties", ",", "File", "propsFile", ",", "String", "message", ")", "{", "Properties", "toWrite", "=", "new", "Properties", "(", ")", ";", "for", "(", "String", "key", ":", "properties", ".", "stringPropertyNames", "(", ")", ")", "{", "if", "(", "System", ".", "getProperties", "(", ")", ".", "containsKey", "(", "key", ")", "&&", "!", "properties", ".", "getProperty", "(", "key", ")", ".", "equals", "(", "System", ".", "getProperty", "(", "key", ")", ")", ")", "{", "toWrite", ".", "setProperty", "(", "key", ",", "properties", ".", "getProperty", "(", "key", ")", ")", ";", "}", "else", "if", "(", "System", ".", "getenv", "(", ")", ".", "containsKey", "(", "key", ")", "&&", "!", "properties", ".", "getProperty", "(", "key", ")", ".", "equals", "(", "System", ".", "getenv", "(", "key", ")", ")", ")", "{", "toWrite", ".", "setProperty", "(", "key", ",", "properties", ".", "getProperty", "(", "key", ")", ")", ";", "}", "else", "if", "(", "!", "System", ".", "getProperties", "(", ")", ".", "containsKey", "(", "key", ")", "&&", "!", "System", ".", "getenv", "(", ")", ".", "containsKey", "(", "key", ")", ")", "{", "toWrite", ".", "setProperty", "(", "key", ",", "properties", ".", "getProperty", "(", "key", ")", ")", ";", "}", "}", "writer", ".", "persistProperties", "(", "toWrite", ",", "propsFile", ",", "message", ",", "log", ")", ";", "}" ]
Persist properties that are not system env or other system properties, in a thread synchronized manner
[ "Persist", "properties", "that", "are", "not", "system", "env", "or", "other", "system", "properties", "in", "a", "thread", "synchronized", "manner" ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L164-L182
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DocumentRevisionTree.java
DocumentRevisionTree.lookup
public InternalDocumentRevision lookup(String id, String rev) { """ <p>Returns the {@link InternalDocumentRevision} for a document ID and revision ID.</p> @param id document ID @param rev revision ID @return the {@code DocumentRevision} for the document and revision ID """ for(DocumentRevisionNode n : sequenceMap.values()) { if(n.getData().getId().equals(id) && n.getData().getRevision().equals(rev)) { return n.getData(); } } return null; }
java
public InternalDocumentRevision lookup(String id, String rev) { for(DocumentRevisionNode n : sequenceMap.values()) { if(n.getData().getId().equals(id) && n.getData().getRevision().equals(rev)) { return n.getData(); } } return null; }
[ "public", "InternalDocumentRevision", "lookup", "(", "String", "id", ",", "String", "rev", ")", "{", "for", "(", "DocumentRevisionNode", "n", ":", "sequenceMap", ".", "values", "(", ")", ")", "{", "if", "(", "n", ".", "getData", "(", ")", ".", "getId", "(", ")", ".", "equals", "(", "id", ")", "&&", "n", ".", "getData", "(", ")", ".", "getRevision", "(", ")", ".", "equals", "(", "rev", ")", ")", "{", "return", "n", ".", "getData", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
<p>Returns the {@link InternalDocumentRevision} for a document ID and revision ID.</p> @param id document ID @param rev revision ID @return the {@code DocumentRevision} for the document and revision ID
[ "<p", ">", "Returns", "the", "{" ]
train
https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/DocumentRevisionTree.java#L248-L255
alkacon/opencms-core
src-setup/org/opencms/setup/db/CmsUpdateDBManager.java
CmsUpdateDBManager.getInstanceForDb
protected I_CmsUpdateDBPart getInstanceForDb(I_CmsUpdateDBPart dbUpdater, String dbName) { """ Creates a new instance for the given database and setting the db pool data.<p> @param dbUpdater the generic updater part @param dbName the database to get a new instance for @return right instance instance for the given database """ String clazz = dbUpdater.getClass().getName(); int pos = clazz.lastIndexOf('.'); clazz = clazz.substring(0, pos) + "." + dbName + clazz.substring(pos); try { return (I_CmsUpdateDBPart)Class.forName(clazz).newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } }
java
protected I_CmsUpdateDBPart getInstanceForDb(I_CmsUpdateDBPart dbUpdater, String dbName) { String clazz = dbUpdater.getClass().getName(); int pos = clazz.lastIndexOf('.'); clazz = clazz.substring(0, pos) + "." + dbName + clazz.substring(pos); try { return (I_CmsUpdateDBPart)Class.forName(clazz).newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } }
[ "protected", "I_CmsUpdateDBPart", "getInstanceForDb", "(", "I_CmsUpdateDBPart", "dbUpdater", ",", "String", "dbName", ")", "{", "String", "clazz", "=", "dbUpdater", ".", "getClass", "(", ")", ".", "getName", "(", ")", ";", "int", "pos", "=", "clazz", ".", "lastIndexOf", "(", "'", "'", ")", ";", "clazz", "=", "clazz", ".", "substring", "(", "0", ",", "pos", ")", "+", "\".\"", "+", "dbName", "+", "clazz", ".", "substring", "(", "pos", ")", ";", "try", "{", "return", "(", "I_CmsUpdateDBPart", ")", "Class", ".", "forName", "(", "clazz", ")", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}" ]
Creates a new instance for the given database and setting the db pool data.<p> @param dbUpdater the generic updater part @param dbName the database to get a new instance for @return right instance instance for the given database
[ "Creates", "a", "new", "instance", "for", "the", "given", "database", "and", "setting", "the", "db", "pool", "data", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/db/CmsUpdateDBManager.java#L371-L382
dlew/joda-time-android
library/src/main/java/net/danlew/android/joda/DateUtils.java
DateUtils.getRelativeDateTimeString
public static CharSequence getRelativeDateTimeString(Context context, ReadablePartial time, ReadablePeriod transitionResolution, int flags) { """ Return string describing the time until/elapsed time since 'time' formatted like "[relative time/date], [time]". See {@link android.text.format.DateUtils#getRelativeDateTimeString} for full docs. @throws IllegalArgumentException if using a ReadablePartial without a time component @see #getRelativeDateTimeString(Context, ReadableInstant, ReadablePeriod, int) """ if (!time.isSupported(DateTimeFieldType.hourOfDay()) || !time.isSupported(DateTimeFieldType.minuteOfHour())) { throw new IllegalArgumentException("getRelativeDateTimeString() must be passed a ReadablePartial that " + "supports time, otherwise it makes no sense"); } return getRelativeDateTimeString(context, time.toDateTime(DateTime.now()), transitionResolution, flags); }
java
public static CharSequence getRelativeDateTimeString(Context context, ReadablePartial time, ReadablePeriod transitionResolution, int flags) { if (!time.isSupported(DateTimeFieldType.hourOfDay()) || !time.isSupported(DateTimeFieldType.minuteOfHour())) { throw new IllegalArgumentException("getRelativeDateTimeString() must be passed a ReadablePartial that " + "supports time, otherwise it makes no sense"); } return getRelativeDateTimeString(context, time.toDateTime(DateTime.now()), transitionResolution, flags); }
[ "public", "static", "CharSequence", "getRelativeDateTimeString", "(", "Context", "context", ",", "ReadablePartial", "time", ",", "ReadablePeriod", "transitionResolution", ",", "int", "flags", ")", "{", "if", "(", "!", "time", ".", "isSupported", "(", "DateTimeFieldType", ".", "hourOfDay", "(", ")", ")", "||", "!", "time", ".", "isSupported", "(", "DateTimeFieldType", ".", "minuteOfHour", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"getRelativeDateTimeString() must be passed a ReadablePartial that \"", "+", "\"supports time, otherwise it makes no sense\"", ")", ";", "}", "return", "getRelativeDateTimeString", "(", "context", ",", "time", ".", "toDateTime", "(", "DateTime", ".", "now", "(", ")", ")", ",", "transitionResolution", ",", "flags", ")", ";", "}" ]
Return string describing the time until/elapsed time since 'time' formatted like "[relative time/date], [time]". See {@link android.text.format.DateUtils#getRelativeDateTimeString} for full docs. @throws IllegalArgumentException if using a ReadablePartial without a time component @see #getRelativeDateTimeString(Context, ReadableInstant, ReadablePeriod, int)
[ "Return", "string", "describing", "the", "time", "until", "/", "elapsed", "time", "since", "time", "formatted", "like", "[", "relative", "time", "/", "date", "]", "[", "time", "]", "." ]
train
https://github.com/dlew/joda-time-android/blob/5bf96f6ef4ea63ee91e73e1e528896fa00108dec/library/src/main/java/net/danlew/android/joda/DateUtils.java#L406-L415
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/WikisApi.java
WikisApi.getPage
public WikiPage getPage(Object projectIdOrPath, String slug) throws GitLabApiException { """ Get a single page of project wiki. <pre><code>GitLab Endpoint: GET /projects/:id/wikis/:slug</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param slug the slug of the project's wiki page @return the specified project Snippet @throws GitLabApiException if any exception occurs """ Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "wikis", slug); return (response.readEntity(WikiPage.class)); }
java
public WikiPage getPage(Object projectIdOrPath, String slug) throws GitLabApiException { Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "wikis", slug); return (response.readEntity(WikiPage.class)); }
[ "public", "WikiPage", "getPage", "(", "Object", "projectIdOrPath", ",", "String", "slug", ")", "throws", "GitLabApiException", "{", "Response", "response", "=", "get", "(", "Response", ".", "Status", ".", "OK", ",", "null", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"wikis\"", ",", "slug", ")", ";", "return", "(", "response", ".", "readEntity", "(", "WikiPage", ".", "class", ")", ")", ";", "}" ]
Get a single page of project wiki. <pre><code>GitLab Endpoint: GET /projects/:id/wikis/:slug</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param slug the slug of the project's wiki page @return the specified project Snippet @throws GitLabApiException if any exception occurs
[ "Get", "a", "single", "page", "of", "project", "wiki", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/WikisApi.java#L89-L93
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/extension/link/FeatureTileTableCoreLinker.java
FeatureTileTableCoreLinker.isLinked
public boolean isLinked(String featureTable, String tileTable) { """ Determine if the feature table is linked to the tile table @param featureTable feature table @param tileTable tile table @return true if linked """ FeatureTileLink link = getLink(featureTable, tileTable); return link != null; }
java
public boolean isLinked(String featureTable, String tileTable) { FeatureTileLink link = getLink(featureTable, tileTable); return link != null; }
[ "public", "boolean", "isLinked", "(", "String", "featureTable", ",", "String", "tileTable", ")", "{", "FeatureTileLink", "link", "=", "getLink", "(", "featureTable", ",", "tileTable", ")", ";", "return", "link", "!=", "null", ";", "}" ]
Determine if the feature table is linked to the tile table @param featureTable feature table @param tileTable tile table @return true if linked
[ "Determine", "if", "the", "feature", "table", "is", "linked", "to", "the", "tile", "table" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/link/FeatureTileTableCoreLinker.java#L122-L125
sksamuel/scrimage
scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java
MarvinImage.setIntColor
public void setIntColor(int x, int y, int c0, int c1, int c2) { """ Sets the integer color in X an Y position @param x position @param y position @param c0 component 0 @param c1 component 1 @param c2 component 2 """ int alpha = (arrIntColor[((y * width + x))] & 0xFF000000) >>> 24; setIntColor(x, y, alpha, c0, c1, c2); }
java
public void setIntColor(int x, int y, int c0, int c1, int c2) { int alpha = (arrIntColor[((y * width + x))] & 0xFF000000) >>> 24; setIntColor(x, y, alpha, c0, c1, c2); }
[ "public", "void", "setIntColor", "(", "int", "x", ",", "int", "y", ",", "int", "c0", ",", "int", "c1", ",", "int", "c2", ")", "{", "int", "alpha", "=", "(", "arrIntColor", "[", "(", "(", "y", "*", "width", "+", "x", ")", ")", "]", "&", "0xFF000000", ")", ">>>", "24", ";", "setIntColor", "(", "x", ",", "y", ",", "alpha", ",", "c0", ",", "c1", ",", "c2", ")", ";", "}" ]
Sets the integer color in X an Y position @param x position @param y position @param c0 component 0 @param c1 component 1 @param c2 component 2
[ "Sets", "the", "integer", "color", "in", "X", "an", "Y", "position" ]
train
https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/marvin/image/MarvinImage.java#L327-L330
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 { """ 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 """ 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", ",", "extract", ")", ";", "}" ]
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", "rootWebApp", "it", "is", "added", "as", "the", "/", "context", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/jetty/Server.java#L308-L314
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLClassImpl_CustomFieldSerializer.java
OWLClassImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLClass instance) throws SerializationException { """ Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful """ deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLClass instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLClass", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{" ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLClassImpl_CustomFieldSerializer.java#L85-L88
stephanrauh/AngularFaces
AngularFaces_2.0/incubator/AngularFaces-widgets/src/main/java/de/beyondjava/angularFaces/secure/NGSecureRenderer.java
NGSecureRenderer.encodeBegin
@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { """ Stores a unique token in the session to prevent repeated submission of the same form. """ long timer = System.nanoTime(); long random = (long) (Math.random() * Integer.MAX_VALUE); long token = timer ^ random; NGSecureUtilities.setSecurityToken(String.valueOf(token), component.getClientId()); super.encodeBegin(context, component); NGSecurityFilter filter = findAndVerifySecurityFilter(context, component); showLegalDisclaimer(context, filter); }
java
@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { long timer = System.nanoTime(); long random = (long) (Math.random() * Integer.MAX_VALUE); long token = timer ^ random; NGSecureUtilities.setSecurityToken(String.valueOf(token), component.getClientId()); super.encodeBegin(context, component); NGSecurityFilter filter = findAndVerifySecurityFilter(context, component); showLegalDisclaimer(context, filter); }
[ "@", "Override", "public", "void", "encodeBegin", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "throws", "IOException", "{", "long", "timer", "=", "System", ".", "nanoTime", "(", ")", ";", "long", "random", "=", "(", "long", ")", "(", "Math", ".", "random", "(", ")", "*", "Integer", ".", "MAX_VALUE", ")", ";", "long", "token", "=", "timer", "^", "random", ";", "NGSecureUtilities", ".", "setSecurityToken", "(", "String", ".", "valueOf", "(", "token", ")", ",", "component", ".", "getClientId", "(", ")", ")", ";", "super", ".", "encodeBegin", "(", "context", ",", "component", ")", ";", "NGSecurityFilter", "filter", "=", "findAndVerifySecurityFilter", "(", "context", ",", "component", ")", ";", "showLegalDisclaimer", "(", "context", ",", "filter", ")", ";", "}" ]
Stores a unique token in the session to prevent repeated submission of the same form.
[ "Stores", "a", "unique", "token", "in", "the", "session", "to", "prevent", "repeated", "submission", "of", "the", "same", "form", "." ]
train
https://github.com/stephanrauh/AngularFaces/blob/43d915f004645b1bbbf2625214294dab0858ba01/AngularFaces_2.0/incubator/AngularFaces-widgets/src/main/java/de/beyondjava/angularFaces/secure/NGSecureRenderer.java#L54-L64
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaMessageStream.java
SagaMessageStream.timeoutHasExpired
private void timeoutHasExpired(final Timeout timeout, final TimeoutExpirationContext context) { """ Called whenever the timeout manager reports an expired timeout. """ try { addMessage(timeout, context.getOriginalHeaders()); } catch (Exception ex) { LOG.error("Error handling timeout {}", timeout, ex); } }
java
private void timeoutHasExpired(final Timeout timeout, final TimeoutExpirationContext context) { try { addMessage(timeout, context.getOriginalHeaders()); } catch (Exception ex) { LOG.error("Error handling timeout {}", timeout, ex); } }
[ "private", "void", "timeoutHasExpired", "(", "final", "Timeout", "timeout", ",", "final", "TimeoutExpirationContext", "context", ")", "{", "try", "{", "addMessage", "(", "timeout", ",", "context", ".", "getOriginalHeaders", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "error", "(", "\"Error handling timeout {}\"", ",", "timeout", ",", "ex", ")", ";", "}", "}" ]
Called whenever the timeout manager reports an expired timeout.
[ "Called", "whenever", "the", "timeout", "manager", "reports", "an", "expired", "timeout", "." ]
train
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaMessageStream.java#L169-L175
wisdom-framework/wisdom
extensions/wisdom-monitor/src/main/java/org/wisdom/monitor/extensions/wisdom/RouteModel.java
RouteModel.from
public static ObjectNode from(Route route, Json json) { """ Creates the JSON representation of the given route. @param route the route @param json the JSON service @return the json representation """ return json.newObject().put("url", route.getUrl()) .put("controller", route.getControllerClass().getName()) .put("method", route.getControllerMethod().getName()) .put("http_method", route.getHttpMethod().toString()); }
java
public static ObjectNode from(Route route, Json json) { return json.newObject().put("url", route.getUrl()) .put("controller", route.getControllerClass().getName()) .put("method", route.getControllerMethod().getName()) .put("http_method", route.getHttpMethod().toString()); }
[ "public", "static", "ObjectNode", "from", "(", "Route", "route", ",", "Json", "json", ")", "{", "return", "json", ".", "newObject", "(", ")", ".", "put", "(", "\"url\"", ",", "route", ".", "getUrl", "(", ")", ")", ".", "put", "(", "\"controller\"", ",", "route", ".", "getControllerClass", "(", ")", ".", "getName", "(", ")", ")", ".", "put", "(", "\"method\"", ",", "route", ".", "getControllerMethod", "(", ")", ".", "getName", "(", ")", ")", ".", "put", "(", "\"http_method\"", ",", "route", ".", "getHttpMethod", "(", ")", ".", "toString", "(", ")", ")", ";", "}" ]
Creates the JSON representation of the given route. @param route the route @param json the JSON service @return the json representation
[ "Creates", "the", "JSON", "representation", "of", "the", "given", "route", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-monitor/src/main/java/org/wisdom/monitor/extensions/wisdom/RouteModel.java#L37-L42
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.refund_refundId_payment_GET
public OvhPayment refund_refundId_payment_GET(String refundId) throws IOException { """ Get this object properties REST: GET /me/refund/{refundId}/payment @param refundId [required] """ String qPath = "/me/refund/{refundId}/payment"; StringBuilder sb = path(qPath, refundId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPayment.class); }
java
public OvhPayment refund_refundId_payment_GET(String refundId) throws IOException { String qPath = "/me/refund/{refundId}/payment"; StringBuilder sb = path(qPath, refundId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPayment.class); }
[ "public", "OvhPayment", "refund_refundId_payment_GET", "(", "String", "refundId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/refund/{refundId}/payment\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "refundId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhPayment", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /me/refund/{refundId}/payment @param refundId [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L1436-L1441
tvesalainen/util
util/src/main/java/org/vesalainen/math/matrix/DoubleMatrix.java
DoubleMatrix.set
public void set(int i, int j, DoubleMatrix B) { """ Assign matrix A items starting at i,j @param i @param j @param B """ int m = B.rows(); int n = B.columns(); for (int ii = 0; ii < m; ii++) { for (int jj = 0; jj < n; jj++) { set(i+ii, j+jj, B.get(ii, jj)); } } }
java
public void set(int i, int j, DoubleMatrix B) { int m = B.rows(); int n = B.columns(); for (int ii = 0; ii < m; ii++) { for (int jj = 0; jj < n; jj++) { set(i+ii, j+jj, B.get(ii, jj)); } } }
[ "public", "void", "set", "(", "int", "i", ",", "int", "j", ",", "DoubleMatrix", "B", ")", "{", "int", "m", "=", "B", ".", "rows", "(", ")", ";", "int", "n", "=", "B", ".", "columns", "(", ")", ";", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "m", ";", "ii", "++", ")", "{", "for", "(", "int", "jj", "=", "0", ";", "jj", "<", "n", ";", "jj", "++", ")", "{", "set", "(", "i", "+", "ii", ",", "j", "+", "jj", ",", "B", ".", "get", "(", "ii", ",", "jj", ")", ")", ";", "}", "}", "}" ]
Assign matrix A items starting at i,j @param i @param j @param B
[ "Assign", "matrix", "A", "items", "starting", "at", "i", "j" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/matrix/DoubleMatrix.java#L92-L103
Baidu-AIP/java-sdk
src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java
AipImageSearch.productSearchUrl
public JSONObject productSearchUrl(String url, HashMap<String, String> options) { """ 商品检索—检索接口 完成入库后,可使用该接口实现商品检索。**支持传入指定分类维度(具体变量class_id1、class_id2)进行检索,返回结果支持翻页(具体变量pn、rn)。****请注意,检索接口不返回原图,仅反馈当前填写的brief信息,请调用入库接口时尽量填写可关联至本地图库的图片id或者图片url等信息** @param url - 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 @param options - 可选参数对象,key: value都为string类型 options - options列表: class_id1 商品分类维度1,支持1-60范围内的整数。检索时可圈定该分类维度进行检索 class_id2 商品分类维度1,支持1-60范围内的整数。检索时可圈定该分类维度进行检索 pn 分页功能,起始位置,例:0。未指定分页时,默认返回前300个结果;接口返回数量最大限制1000条,例如:起始位置为900,截取条数500条,接口也只返回第900 - 1000条的结果,共计100条 rn 分页功能,截取条数,例:250 @return JSONObject """ AipRequest request = new AipRequest(); preOperation(request); request.addBody("url", url); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.PRODUCT_SEARCH); postOperation(request); return requestServer(request); }
java
public JSONObject productSearchUrl(String url, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("url", url); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.PRODUCT_SEARCH); postOperation(request); return requestServer(request); }
[ "public", "JSONObject", "productSearchUrl", "(", "String", "url", ",", "HashMap", "<", "String", ",", "String", ">", "options", ")", "{", "AipRequest", "request", "=", "new", "AipRequest", "(", ")", ";", "preOperation", "(", "request", ")", ";", "request", ".", "addBody", "(", "\"url\"", ",", "url", ")", ";", "if", "(", "options", "!=", "null", ")", "{", "request", ".", "addBody", "(", "options", ")", ";", "}", "request", ".", "setUri", "(", "ImageSearchConsts", ".", "PRODUCT_SEARCH", ")", ";", "postOperation", "(", "request", ")", ";", "return", "requestServer", "(", "request", ")", ";", "}" ]
商品检索—检索接口 完成入库后,可使用该接口实现商品检索。**支持传入指定分类维度(具体变量class_id1、class_id2)进行检索,返回结果支持翻页(具体变量pn、rn)。****请注意,检索接口不返回原图,仅反馈当前填写的brief信息,请调用入库接口时尽量填写可关联至本地图库的图片id或者图片url等信息** @param url - 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 @param options - 可选参数对象,key: value都为string类型 options - options列表: class_id1 商品分类维度1,支持1-60范围内的整数。检索时可圈定该分类维度进行检索 class_id2 商品分类维度1,支持1-60范围内的整数。检索时可圈定该分类维度进行检索 pn 分页功能,起始位置,例:0。未指定分页时,默认返回前300个结果;接口返回数量最大限制1000条,例如:起始位置为900,截取条数500条,接口也只返回第900 - 1000条的结果,共计100条 rn 分页功能,截取条数,例:250 @return JSONObject
[ "商品检索—检索接口", "完成入库后,可使用该接口实现商品检索。", "**", "支持传入指定分类维度(具体变量class_id1、class_id2)进行检索,返回结果支持翻页(具体变量pn、rn)。", "****", "请注意,检索接口不返回原图,仅反馈当前填写的brief信息,请调用入库接口时尽量填写可关联至本地图库的图片id或者图片url等信息", "**" ]
train
https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java#L820-L831
JDBDT/jdbdt
src/main/java/org/jdbdt/JDBDT.java
JDBDT.assertState
public static void assertState(String message, DataSet dataSet) throws DBAssertionError { """ Assert that the database state matches the given data set (error message variant). @param message Assertion error message. @param dataSet Data set. @throws DBAssertionError if the assertion fails. @see #assertEmpty(String, DataSource) """ DBAssert.stateAssertion(CallInfo.create(message), dataSet); }
java
public static void assertState(String message, DataSet dataSet) throws DBAssertionError { DBAssert.stateAssertion(CallInfo.create(message), dataSet); }
[ "public", "static", "void", "assertState", "(", "String", "message", ",", "DataSet", "dataSet", ")", "throws", "DBAssertionError", "{", "DBAssert", ".", "stateAssertion", "(", "CallInfo", ".", "create", "(", "message", ")", ",", "dataSet", ")", ";", "}" ]
Assert that the database state matches the given data set (error message variant). @param message Assertion error message. @param dataSet Data set. @throws DBAssertionError if the assertion fails. @see #assertEmpty(String, DataSource)
[ "Assert", "that", "the", "database", "state", "matches", "the", "given", "data", "set", "(", "error", "message", "variant", ")", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L611-L613
JodaOrg/joda-time
src/main/java/org/joda/time/format/DateTimeFormatter.java
DateTimeFormatter.printTo
public void printTo(Writer out, ReadablePartial partial) throws IOException { """ Prints a ReadablePartial. <p> Neither the override chronology nor the override zone are used by this method. @param out the destination to format to, not null @param partial partial to format """ printTo((Appendable) out, partial); }
java
public void printTo(Writer out, ReadablePartial partial) throws IOException { printTo((Appendable) out, partial); }
[ "public", "void", "printTo", "(", "Writer", "out", ",", "ReadablePartial", "partial", ")", "throws", "IOException", "{", "printTo", "(", "(", "Appendable", ")", "out", ",", "partial", ")", ";", "}" ]
Prints a ReadablePartial. <p> Neither the override chronology nor the override zone are used by this method. @param out the destination to format to, not null @param partial partial to format
[ "Prints", "a", "ReadablePartial", ".", "<p", ">", "Neither", "the", "override", "chronology", "nor", "the", "override", "zone", "are", "used", "by", "this", "method", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatter.java#L636-L638
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) { """ 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 """ 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", ")", ";", "modelAndView", ".", "addObject", "(", "\"code\"", ",", "StringEscapeUtils", ".", "escapeHtml4", "(", "code", ")", ")", ";", "val", "desc", "=", "StringEscapeUtils", ".", "escapeHtml4", "(", "this", ".", "context", ".", "getMessage", "(", "code", ",", "args", ",", "code", ",", "request", ".", "getLocale", "(", ")", ")", ")", ";", "modelAndView", ".", "addObject", "(", "\"description\"", ",", "desc", ")", ";", "return", "modelAndView", ";", "}" ]
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
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/workspace/VoiceApi.java
VoiceApi.singleStepTransfer
public void singleStepTransfer(String connId, String destination) throws WorkspaceApiException { """ Perform a single-step transfer to the specified destination. @param connId The connection ID of the call to transfer. @param destination The number where the call should be transferred. """ this.singleStepTransfer(connId, destination, null, null, null, null); }
java
public void singleStepTransfer(String connId, String destination) throws WorkspaceApiException { this.singleStepTransfer(connId, destination, null, null, null, null); }
[ "public", "void", "singleStepTransfer", "(", "String", "connId", ",", "String", "destination", ")", "throws", "WorkspaceApiException", "{", "this", ".", "singleStepTransfer", "(", "connId", ",", "destination", ",", "null", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Perform a single-step transfer to the specified destination. @param connId The connection ID of the call to transfer. @param destination The number where the call should be transferred.
[ "Perform", "a", "single", "-", "step", "transfer", "to", "the", "specified", "destination", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L944-L946
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/BitFieldArgs.java
BitFieldArgs.incrBy
public BitFieldArgs incrBy(BitFieldType bitFieldType, int offset, long value) { """ Adds a new {@code INCRBY} subcommand. @param bitFieldType the bit field type, must not be {@literal null}. @param offset bitfield offset @param value the value @return a new {@code INCRBY} subcommand for the given {@code bitFieldType}, {@code offset} and {@code value}. """ return addSubCommand(new IncrBy(bitFieldType, false, offset, value)); }
java
public BitFieldArgs incrBy(BitFieldType bitFieldType, int offset, long value) { return addSubCommand(new IncrBy(bitFieldType, false, offset, value)); }
[ "public", "BitFieldArgs", "incrBy", "(", "BitFieldType", "bitFieldType", ",", "int", "offset", ",", "long", "value", ")", "{", "return", "addSubCommand", "(", "new", "IncrBy", "(", "bitFieldType", ",", "false", ",", "offset", ",", "value", ")", ")", ";", "}" ]
Adds a new {@code INCRBY} subcommand. @param bitFieldType the bit field type, must not be {@literal null}. @param offset bitfield offset @param value the value @return a new {@code INCRBY} subcommand for the given {@code bitFieldType}, {@code offset} and {@code value}.
[ "Adds", "a", "new", "{", "@code", "INCRBY", "}", "subcommand", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/BitFieldArgs.java#L367-L369
JoeKerouac/utils
src/main/java/com/joe/utils/reflect/ReflectUtil.java
ReflectUtil.invoke
@SuppressWarnings("unchecked") public static <R> R invoke(Object obj, Method method, Object... args) { """ 调用指定对象的指定方法 @param obj 指定对象,不能为空,如果要调用的方法为静态方法那么传入Class对象 @param method 要调用的方法 @param args 参数 @param <R> 结果类型 @return 调用结果 """ try { if (obj instanceof Class) { return (R) method.invoke(null, args); } else { return (R) method.invoke(obj, args); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new ReflectException("调用方法[" + method + "]失败", e); } }
java
@SuppressWarnings("unchecked") public static <R> R invoke(Object obj, Method method, Object... args) { try { if (obj instanceof Class) { return (R) method.invoke(null, args); } else { return (R) method.invoke(obj, args); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new ReflectException("调用方法[" + method + "]失败", e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "R", ">", "R", "invoke", "(", "Object", "obj", ",", "Method", "method", ",", "Object", "...", "args", ")", "{", "try", "{", "if", "(", "obj", "instanceof", "Class", ")", "{", "return", "(", "R", ")", "method", ".", "invoke", "(", "null", ",", "args", ")", ";", "}", "else", "{", "return", "(", "R", ")", "method", ".", "invoke", "(", "obj", ",", "args", ")", ";", "}", "}", "catch", "(", "IllegalAccessException", "|", "IllegalArgumentException", "|", "InvocationTargetException", "e", ")", "{", "throw", "new", "ReflectException", "(", "\"调用方法[\" + metho", " ", " \"]失败\"", " ", ");", "", "", "", "", "}", "}" ]
调用指定对象的指定方法 @param obj 指定对象,不能为空,如果要调用的方法为静态方法那么传入Class对象 @param method 要调用的方法 @param args 参数 @param <R> 结果类型 @return 调用结果
[ "调用指定对象的指定方法" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/ReflectUtil.java#L132-L143
looly/hutool
hutool-captcha/src/main/java/cn/hutool/captcha/LineCaptcha.java
LineCaptcha.drawString
private void drawString(Graphics2D g, String code) { """ 绘制字符串 @param g {@link Graphics2D}画笔 @param random 随机对象 @param code 验证码 """ // 抗锯齿 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 创建字体 g.setFont(this.font); // 文字 int minY = GraphicsUtil.getMinY(g); if(minY < 0) { minY = this.height -1; } final int len = this.generator.getLength(); int charWidth = width / len; for (int i = 0; i < len; i++) { // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。 g.setColor(ImgUtil.randomColor()); g.drawString(String.valueOf(code.charAt(i)), i * charWidth, RandomUtil.randomInt(minY, this.height)); } }
java
private void drawString(Graphics2D g, String code) { // 抗锯齿 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 创建字体 g.setFont(this.font); // 文字 int minY = GraphicsUtil.getMinY(g); if(minY < 0) { minY = this.height -1; } final int len = this.generator.getLength(); int charWidth = width / len; for (int i = 0; i < len; i++) { // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。 g.setColor(ImgUtil.randomColor()); g.drawString(String.valueOf(code.charAt(i)), i * charWidth, RandomUtil.randomInt(minY, this.height)); } }
[ "private", "void", "drawString", "(", "Graphics2D", "g", ",", "String", "code", ")", "{", "// 抗锯齿\r", "g", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_ANTIALIASING", ",", "RenderingHints", ".", "VALUE_ANTIALIAS_ON", ")", ";", "// 创建字体\r", "g", ".", "setFont", "(", "this", ".", "font", ")", ";", "// 文字\r", "int", "minY", "=", "GraphicsUtil", ".", "getMinY", "(", "g", ")", ";", "if", "(", "minY", "<", "0", ")", "{", "minY", "=", "this", ".", "height", "-", "1", ";", "}", "final", "int", "len", "=", "this", ".", "generator", ".", "getLength", "(", ")", ";", "int", "charWidth", "=", "width", "/", "len", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。\r", "g", ".", "setColor", "(", "ImgUtil", ".", "randomColor", "(", ")", ")", ";", "g", ".", "drawString", "(", "String", ".", "valueOf", "(", "code", ".", "charAt", "(", "i", ")", ")", ",", "i", "*", "charWidth", ",", "RandomUtil", ".", "randomInt", "(", "minY", ",", "this", ".", "height", ")", ")", ";", "}", "}" ]
绘制字符串 @param g {@link Graphics2D}画笔 @param random 随机对象 @param code 验证码
[ "绘制字符串" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-captcha/src/main/java/cn/hutool/captcha/LineCaptcha.java#L71-L90
domaframework/doma-gen
src/main/java/org/seasar/doma/extension/gen/EntityDescFactory.java
EntityDescFactory.createEntityDesc
public EntityDesc createEntityDesc( TableMeta tableMeta, String entityPrefix, String entitySuffix) { """ エンティティ記述を作成します。 @param tableMeta テーブルメタデータ @param entityPrefix エンティティクラスのプリフィックス @param entitySuffix エンティティクラスのサフィックス @return エンティティ記述 """ String name = StringUtil.fromSnakeCaseToCamelCase(tableMeta.getName()); return createEntityDesc(tableMeta, entityPrefix, entitySuffix, StringUtil.capitalize(name)); }
java
public EntityDesc createEntityDesc( TableMeta tableMeta, String entityPrefix, String entitySuffix) { String name = StringUtil.fromSnakeCaseToCamelCase(tableMeta.getName()); return createEntityDesc(tableMeta, entityPrefix, entitySuffix, StringUtil.capitalize(name)); }
[ "public", "EntityDesc", "createEntityDesc", "(", "TableMeta", "tableMeta", ",", "String", "entityPrefix", ",", "String", "entitySuffix", ")", "{", "String", "name", "=", "StringUtil", ".", "fromSnakeCaseToCamelCase", "(", "tableMeta", ".", "getName", "(", ")", ")", ";", "return", "createEntityDesc", "(", "tableMeta", ",", "entityPrefix", ",", "entitySuffix", ",", "StringUtil", ".", "capitalize", "(", "name", ")", ")", ";", "}" ]
エンティティ記述を作成します。 @param tableMeta テーブルメタデータ @param entityPrefix エンティティクラスのプリフィックス @param entitySuffix エンティティクラスのサフィックス @return エンティティ記述
[ "エンティティ記述を作成します。" ]
train
https://github.com/domaframework/doma-gen/blob/8046e0b28d2167d444125f206ce36e554b3ee616/src/main/java/org/seasar/doma/extension/gen/EntityDescFactory.java#L129-L133
xm-online/xm-commons
xm-commons-lep/src/main/java/com/icthh/xm/commons/lep/XmExtensionService.java
XmExtensionService.getResourceKey
@Override public UrlLepResourceKey getResourceKey(LepKey extensionKey, Version extensionResourceVersion) { """ Return composite resource key for specified extension key. If extension has no resource or extension with specified key doesn't exist the method returns {@code null}. @param extensionKey the extension key @param extensionResourceVersion ignored in current implementation @return composite resource key or {@code null} if not found """ if (extensionKey == null) { return null; } LepKey groupKey = extensionKey.getGroupKey(); String extensionKeyId = extensionKey.getId(); String extensionName; String[] groupSegments; if (groupKey == null) { groupSegments = EMPTY_GROUP_SEGMENTS; extensionName = extensionKeyId; } else { groupSegments = groupKey.getId().split(EXTENSION_KEY_SEPARATOR_REGEXP); // remove group from id extensionName = extensionKeyId.replace(groupKey.getId(), ""); if (extensionName.startsWith(XmLepConstants.EXTENSION_KEY_SEPARATOR)) { extensionName = extensionName.substring(XmLepConstants.EXTENSION_KEY_SEPARATOR.length()); } } // change script name: capitalize first character & add script type extension String scriptName = extensionName.replaceAll(EXTENSION_KEY_SEPARATOR_REGEXP, SCRIPT_NAME_SEPARATOR_REGEXP); scriptName = StringUtils.capitalize(scriptName); String urlPath = URL_DELIMITER; if (groupSegments.length > 0) { urlPath += String.join(URL_DELIMITER, groupSegments) + URL_DELIMITER; } urlPath += scriptName + SCRIPT_EXTENSION_SEPARATOR + SCRIPT_EXTENSION_GROOVY; // TODO if possible add check that returned resourceKey contains resources (for speed up executor reaction) // Check example : return isResourceExists(resourceKey) ? resourceKey : null; UrlLepResourceKey urlLepResourceKey = UrlLepResourceKey.valueOfUrlResourcePath(urlPath); if (extensionResourceVersion == null) { log.debug("LEP extension key: '{}' translated to --> composite resource key: '{}'", extensionKey, urlLepResourceKey); } else { log.debug("LEP extension 'key: {}, v{}' translated to --> composite resource key: '{}'", extensionKey, extensionResourceVersion, urlLepResourceKey); } return urlLepResourceKey; }
java
@Override public UrlLepResourceKey getResourceKey(LepKey extensionKey, Version extensionResourceVersion) { if (extensionKey == null) { return null; } LepKey groupKey = extensionKey.getGroupKey(); String extensionKeyId = extensionKey.getId(); String extensionName; String[] groupSegments; if (groupKey == null) { groupSegments = EMPTY_GROUP_SEGMENTS; extensionName = extensionKeyId; } else { groupSegments = groupKey.getId().split(EXTENSION_KEY_SEPARATOR_REGEXP); // remove group from id extensionName = extensionKeyId.replace(groupKey.getId(), ""); if (extensionName.startsWith(XmLepConstants.EXTENSION_KEY_SEPARATOR)) { extensionName = extensionName.substring(XmLepConstants.EXTENSION_KEY_SEPARATOR.length()); } } // change script name: capitalize first character & add script type extension String scriptName = extensionName.replaceAll(EXTENSION_KEY_SEPARATOR_REGEXP, SCRIPT_NAME_SEPARATOR_REGEXP); scriptName = StringUtils.capitalize(scriptName); String urlPath = URL_DELIMITER; if (groupSegments.length > 0) { urlPath += String.join(URL_DELIMITER, groupSegments) + URL_DELIMITER; } urlPath += scriptName + SCRIPT_EXTENSION_SEPARATOR + SCRIPT_EXTENSION_GROOVY; // TODO if possible add check that returned resourceKey contains resources (for speed up executor reaction) // Check example : return isResourceExists(resourceKey) ? resourceKey : null; UrlLepResourceKey urlLepResourceKey = UrlLepResourceKey.valueOfUrlResourcePath(urlPath); if (extensionResourceVersion == null) { log.debug("LEP extension key: '{}' translated to --> composite resource key: '{}'", extensionKey, urlLepResourceKey); } else { log.debug("LEP extension 'key: {}, v{}' translated to --> composite resource key: '{}'", extensionKey, extensionResourceVersion, urlLepResourceKey); } return urlLepResourceKey; }
[ "@", "Override", "public", "UrlLepResourceKey", "getResourceKey", "(", "LepKey", "extensionKey", ",", "Version", "extensionResourceVersion", ")", "{", "if", "(", "extensionKey", "==", "null", ")", "{", "return", "null", ";", "}", "LepKey", "groupKey", "=", "extensionKey", ".", "getGroupKey", "(", ")", ";", "String", "extensionKeyId", "=", "extensionKey", ".", "getId", "(", ")", ";", "String", "extensionName", ";", "String", "[", "]", "groupSegments", ";", "if", "(", "groupKey", "==", "null", ")", "{", "groupSegments", "=", "EMPTY_GROUP_SEGMENTS", ";", "extensionName", "=", "extensionKeyId", ";", "}", "else", "{", "groupSegments", "=", "groupKey", ".", "getId", "(", ")", ".", "split", "(", "EXTENSION_KEY_SEPARATOR_REGEXP", ")", ";", "// remove group from id", "extensionName", "=", "extensionKeyId", ".", "replace", "(", "groupKey", ".", "getId", "(", ")", ",", "\"\"", ")", ";", "if", "(", "extensionName", ".", "startsWith", "(", "XmLepConstants", ".", "EXTENSION_KEY_SEPARATOR", ")", ")", "{", "extensionName", "=", "extensionName", ".", "substring", "(", "XmLepConstants", ".", "EXTENSION_KEY_SEPARATOR", ".", "length", "(", ")", ")", ";", "}", "}", "// change script name: capitalize first character & add script type extension", "String", "scriptName", "=", "extensionName", ".", "replaceAll", "(", "EXTENSION_KEY_SEPARATOR_REGEXP", ",", "SCRIPT_NAME_SEPARATOR_REGEXP", ")", ";", "scriptName", "=", "StringUtils", ".", "capitalize", "(", "scriptName", ")", ";", "String", "urlPath", "=", "URL_DELIMITER", ";", "if", "(", "groupSegments", ".", "length", ">", "0", ")", "{", "urlPath", "+=", "String", ".", "join", "(", "URL_DELIMITER", ",", "groupSegments", ")", "+", "URL_DELIMITER", ";", "}", "urlPath", "+=", "scriptName", "+", "SCRIPT_EXTENSION_SEPARATOR", "+", "SCRIPT_EXTENSION_GROOVY", ";", "// TODO if possible add check that returned resourceKey contains resources (for speed up executor reaction)", "// Check example : return isResourceExists(resourceKey) ? resourceKey : null;", "UrlLepResourceKey", "urlLepResourceKey", "=", "UrlLepResourceKey", ".", "valueOfUrlResourcePath", "(", "urlPath", ")", ";", "if", "(", "extensionResourceVersion", "==", "null", ")", "{", "log", ".", "debug", "(", "\"LEP extension key: '{}' translated to --> composite resource key: '{}'\"", ",", "extensionKey", ",", "urlLepResourceKey", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"LEP extension 'key: {}, v{}' translated to --> composite resource key: '{}'\"", ",", "extensionKey", ",", "extensionResourceVersion", ",", "urlLepResourceKey", ")", ";", "}", "return", "urlLepResourceKey", ";", "}" ]
Return composite resource key for specified extension key. If extension has no resource or extension with specified key doesn't exist the method returns {@code null}. @param extensionKey the extension key @param extensionResourceVersion ignored in current implementation @return composite resource key or {@code null} if not found
[ "Return", "composite", "resource", "key", "for", "specified", "extension", "key", ".", "If", "extension", "has", "no", "resource", "or", "extension", "with", "specified", "key", "doesn", "t", "exist", "the", "method", "returns", "{", "@code", "null", "}", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-lep/src/main/java/com/icthh/xm/commons/lep/XmExtensionService.java#L41-L85
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/triangulate/ResidualsTriangulateProjective.java
ResidualsTriangulateProjective.setObservations
public void setObservations( List<Point2D_F64> observations , List<DMatrixRMaj> cameraMatrices ) { """ Configures inputs. @param observations Observations of the feature at different locations. Pixels. @param cameraMatrices Camera matrices """ if( observations.size() != cameraMatrices.size() ) throw new IllegalArgumentException("Different size lists"); this.observations = observations; this.cameraMatrices = cameraMatrices; }
java
public void setObservations( List<Point2D_F64> observations , List<DMatrixRMaj> cameraMatrices ) { if( observations.size() != cameraMatrices.size() ) throw new IllegalArgumentException("Different size lists"); this.observations = observations; this.cameraMatrices = cameraMatrices; }
[ "public", "void", "setObservations", "(", "List", "<", "Point2D_F64", ">", "observations", ",", "List", "<", "DMatrixRMaj", ">", "cameraMatrices", ")", "{", "if", "(", "observations", ".", "size", "(", ")", "!=", "cameraMatrices", ".", "size", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Different size lists\"", ")", ";", "this", ".", "observations", "=", "observations", ";", "this", ".", "cameraMatrices", "=", "cameraMatrices", ";", "}" ]
Configures inputs. @param observations Observations of the feature at different locations. Pixels. @param cameraMatrices Camera matrices
[ "Configures", "inputs", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/triangulate/ResidualsTriangulateProjective.java#L51-L57
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/TopologyManager.java
TopologyManager.addSubPartition
public static void addSubPartition(SqlgGraph sqlgGraph, Partition partition) { """ Adds the partition to a partition. A new Vertex with label Partition is added and in linked to its parent with the SQLG_SCHEMA_PARTITION_PARTITION_EDGE edge label. @param sqlgGraph """ AbstractLabel abstractLabel = partition.getAbstractLabel(); addSubPartition( sqlgGraph, partition.getParentPartition().getParentPartition() != null, abstractLabel instanceof VertexLabel, abstractLabel.getSchema().getName(), abstractLabel.getName(), partition.getParentPartition().getName(), partition.getName(), partition.getPartitionType(), partition.getPartitionExpression(), partition.getFrom(), partition.getTo(), partition.getIn() ); }
java
public static void addSubPartition(SqlgGraph sqlgGraph, Partition partition) { AbstractLabel abstractLabel = partition.getAbstractLabel(); addSubPartition( sqlgGraph, partition.getParentPartition().getParentPartition() != null, abstractLabel instanceof VertexLabel, abstractLabel.getSchema().getName(), abstractLabel.getName(), partition.getParentPartition().getName(), partition.getName(), partition.getPartitionType(), partition.getPartitionExpression(), partition.getFrom(), partition.getTo(), partition.getIn() ); }
[ "public", "static", "void", "addSubPartition", "(", "SqlgGraph", "sqlgGraph", ",", "Partition", "partition", ")", "{", "AbstractLabel", "abstractLabel", "=", "partition", ".", "getAbstractLabel", "(", ")", ";", "addSubPartition", "(", "sqlgGraph", ",", "partition", ".", "getParentPartition", "(", ")", ".", "getParentPartition", "(", ")", "!=", "null", ",", "abstractLabel", "instanceof", "VertexLabel", ",", "abstractLabel", ".", "getSchema", "(", ")", ".", "getName", "(", ")", ",", "abstractLabel", ".", "getName", "(", ")", ",", "partition", ".", "getParentPartition", "(", ")", ".", "getName", "(", ")", ",", "partition", ".", "getName", "(", ")", ",", "partition", ".", "getPartitionType", "(", ")", ",", "partition", ".", "getPartitionExpression", "(", ")", ",", "partition", ".", "getFrom", "(", ")", ",", "partition", ".", "getTo", "(", ")", ",", "partition", ".", "getIn", "(", ")", ")", ";", "}" ]
Adds the partition to a partition. A new Vertex with label Partition is added and in linked to its parent with the SQLG_SCHEMA_PARTITION_PARTITION_EDGE edge label. @param sqlgGraph
[ "Adds", "the", "partition", "to", "a", "partition", ".", "A", "new", "Vertex", "with", "label", "Partition", "is", "added", "and", "in", "linked", "to", "its", "parent", "with", "the", "SQLG_SCHEMA_PARTITION_PARTITION_EDGE", "edge", "label", "." ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/TopologyManager.java#L1215-L1232
google/closure-templates
java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java
SoyJsPluginUtils.applyDirective
public static Expression applyDirective( Expression expr, SoyJsSrcPrintDirective directive, List<Expression> args, SourceLocation location, ErrorReporter errorReporter) { """ Applies the given print directive to {@code expr} and returns the result. @param generator The CodeChunk generator to use. @param expr The expression to apply the print directive to. @param directive The print directive to apply. @param args Print directive args, if any. """ List<JsExpr> argExprs = Lists.transform(args, Expression::singleExprOrName); JsExpr applied; try { applied = directive.applyForJsSrc(expr.singleExprOrName(), argExprs); } catch (Throwable t) { applied = report(location, directive, t, errorReporter); } RequiresCollector.IntoImmutableSet collector = new RequiresCollector.IntoImmutableSet(); expr.collectRequires(collector); for (Expression arg : args) { arg.collectRequires(collector); } if (directive instanceof SoyLibraryAssistedJsSrcPrintDirective) { for (String name : ((SoyLibraryAssistedJsSrcPrintDirective) directive).getRequiredJsLibNames()) { collector.add(GoogRequire.create(name)); } } ImmutableList.Builder<Statement> initialStatements = ImmutableList.<Statement>builder().addAll(expr.initialStatements()); for (Expression arg : args) { initialStatements.addAll(arg.initialStatements()); } return fromExpr(applied, collector.get()).withInitialStatements(initialStatements.build()); }
java
public static Expression applyDirective( Expression expr, SoyJsSrcPrintDirective directive, List<Expression> args, SourceLocation location, ErrorReporter errorReporter) { List<JsExpr> argExprs = Lists.transform(args, Expression::singleExprOrName); JsExpr applied; try { applied = directive.applyForJsSrc(expr.singleExprOrName(), argExprs); } catch (Throwable t) { applied = report(location, directive, t, errorReporter); } RequiresCollector.IntoImmutableSet collector = new RequiresCollector.IntoImmutableSet(); expr.collectRequires(collector); for (Expression arg : args) { arg.collectRequires(collector); } if (directive instanceof SoyLibraryAssistedJsSrcPrintDirective) { for (String name : ((SoyLibraryAssistedJsSrcPrintDirective) directive).getRequiredJsLibNames()) { collector.add(GoogRequire.create(name)); } } ImmutableList.Builder<Statement> initialStatements = ImmutableList.<Statement>builder().addAll(expr.initialStatements()); for (Expression arg : args) { initialStatements.addAll(arg.initialStatements()); } return fromExpr(applied, collector.get()).withInitialStatements(initialStatements.build()); }
[ "public", "static", "Expression", "applyDirective", "(", "Expression", "expr", ",", "SoyJsSrcPrintDirective", "directive", ",", "List", "<", "Expression", ">", "args", ",", "SourceLocation", "location", ",", "ErrorReporter", "errorReporter", ")", "{", "List", "<", "JsExpr", ">", "argExprs", "=", "Lists", ".", "transform", "(", "args", ",", "Expression", "::", "singleExprOrName", ")", ";", "JsExpr", "applied", ";", "try", "{", "applied", "=", "directive", ".", "applyForJsSrc", "(", "expr", ".", "singleExprOrName", "(", ")", ",", "argExprs", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "applied", "=", "report", "(", "location", ",", "directive", ",", "t", ",", "errorReporter", ")", ";", "}", "RequiresCollector", ".", "IntoImmutableSet", "collector", "=", "new", "RequiresCollector", ".", "IntoImmutableSet", "(", ")", ";", "expr", ".", "collectRequires", "(", "collector", ")", ";", "for", "(", "Expression", "arg", ":", "args", ")", "{", "arg", ".", "collectRequires", "(", "collector", ")", ";", "}", "if", "(", "directive", "instanceof", "SoyLibraryAssistedJsSrcPrintDirective", ")", "{", "for", "(", "String", "name", ":", "(", "(", "SoyLibraryAssistedJsSrcPrintDirective", ")", "directive", ")", ".", "getRequiredJsLibNames", "(", ")", ")", "{", "collector", ".", "add", "(", "GoogRequire", ".", "create", "(", "name", ")", ")", ";", "}", "}", "ImmutableList", ".", "Builder", "<", "Statement", ">", "initialStatements", "=", "ImmutableList", ".", "<", "Statement", ">", "builder", "(", ")", ".", "addAll", "(", "expr", ".", "initialStatements", "(", ")", ")", ";", "for", "(", "Expression", "arg", ":", "args", ")", "{", "initialStatements", ".", "addAll", "(", "arg", ".", "initialStatements", "(", ")", ")", ";", "}", "return", "fromExpr", "(", "applied", ",", "collector", ".", "get", "(", ")", ")", ".", "withInitialStatements", "(", "initialStatements", ".", "build", "(", ")", ")", ";", "}" ]
Applies the given print directive to {@code expr} and returns the result. @param generator The CodeChunk generator to use. @param expr The expression to apply the print directive to. @param directive The print directive to apply. @param args Print directive args, if any.
[ "Applies", "the", "given", "print", "directive", "to", "{", "@code", "expr", "}", "and", "returns", "the", "result", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/SoyJsPluginUtils.java#L81-L112
ModeShape/modeshape
connectors/modeshape-connector-cmis/src/main/java/org/modeshape/connector/cmis/CmisConnector.java
CmisConnector.cmisContent
private Document cmisContent( String id ) { """ Converts binary content into JCR node. @param id the id of the CMIS document. @return JCR node representation. """ 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", ".", "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", "(", ")", ";", "}" ]
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
erlang/otp
lib/jinterface/java_src/com/ericsson/otp/erlang/AbstractConnection.java
AbstractConnection.readSock
protected int readSock(final OtpTransport s, final byte[] b) throws IOException { """ /* this method now throws exception if we don't get full read """ int got = 0; final int len = b.length; int i; synchronized (this) { if (s == null) { throw new IOException("expected " + len + " bytes, socket was closed"); } } while (got < len) { i = s.getInputStream().read(b, got, len - got); if (i < 0) { throw new IOException("expected " + len + " bytes, got EOF after " + got + " bytes"); } else if (i == 0 && len != 0) { /* * This is a corner case. According to * http://java.sun.com/j2se/1.4.2/docs/api/ class InputStream * is.read(,,l) can only return 0 if l==0. In other words it * should not happen, but apparently did. */ throw new IOException("Remote connection closed"); } else { got += i; } } return got; }
java
protected int readSock(final OtpTransport s, final byte[] b) throws IOException { int got = 0; final int len = b.length; int i; synchronized (this) { if (s == null) { throw new IOException("expected " + len + " bytes, socket was closed"); } } while (got < len) { i = s.getInputStream().read(b, got, len - got); if (i < 0) { throw new IOException("expected " + len + " bytes, got EOF after " + got + " bytes"); } else if (i == 0 && len != 0) { /* * This is a corner case. According to * http://java.sun.com/j2se/1.4.2/docs/api/ class InputStream * is.read(,,l) can only return 0 if l==0. In other words it * should not happen, but apparently did. */ throw new IOException("Remote connection closed"); } else { got += i; } } return got; }
[ "protected", "int", "readSock", "(", "final", "OtpTransport", "s", ",", "final", "byte", "[", "]", "b", ")", "throws", "IOException", "{", "int", "got", "=", "0", ";", "final", "int", "len", "=", "b", ".", "length", ";", "int", "i", ";", "synchronized", "(", "this", ")", "{", "if", "(", "s", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"expected \"", "+", "len", "+", "\" bytes, socket was closed\"", ")", ";", "}", "}", "while", "(", "got", "<", "len", ")", "{", "i", "=", "s", ".", "getInputStream", "(", ")", ".", "read", "(", "b", ",", "got", ",", "len", "-", "got", ")", ";", "if", "(", "i", "<", "0", ")", "{", "throw", "new", "IOException", "(", "\"expected \"", "+", "len", "+", "\" bytes, got EOF after \"", "+", "got", "+", "\" bytes\"", ")", ";", "}", "else", "if", "(", "i", "==", "0", "&&", "len", "!=", "0", ")", "{", "/*\n * This is a corner case. According to\n * http://java.sun.com/j2se/1.4.2/docs/api/ class InputStream\n * is.read(,,l) can only return 0 if l==0. In other words it\n * should not happen, but apparently did.\n */", "throw", "new", "IOException", "(", "\"Remote connection closed\"", ")", ";", "}", "else", "{", "got", "+=", "i", ";", "}", "}", "return", "got", ";", "}" ]
/* this method now throws exception if we don't get full read
[ "/", "*", "this", "method", "now", "throws", "exception", "if", "we", "don", "t", "get", "full", "read" ]
train
https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/AbstractConnection.java#L921-L953
OpenLiberty/open-liberty
dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/asn1/x509/X509Name.java
X509Name.getInstance
public static X509Name getInstance( ASN1TaggedObject obj, boolean explicit) { """ Return a X509Name based on the passed in tagged object. @param obj tag object holding name. @param explicit true if explicitly tagged false otherwise. @return the X509Name """ return getInstance(ASN1Sequence.getInstance(obj, explicit)); }
java
public static X509Name getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); }
[ "public", "static", "X509Name", "getInstance", "(", "ASN1TaggedObject", "obj", ",", "boolean", "explicit", ")", "{", "return", "getInstance", "(", "ASN1Sequence", ".", "getInstance", "(", "obj", ",", "explicit", ")", ")", ";", "}" ]
Return a X509Name based on the passed in tagged object. @param obj tag object holding name. @param explicit true if explicitly tagged false otherwise. @return the X509Name
[ "Return", "a", "X509Name", "based", "on", "the", "passed", "in", "tagged", "object", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/asn1/x509/X509Name.java#L228-L233
sockeqwe/SwipeBack
library/src/com/hannesdorfmann/swipeback/DraggableSwipeBack.java
DraggableSwipeBack.canChildScrollVertically
protected boolean canChildScrollVertically(View v, boolean checkV, int dx, int x, int y) { """ Tests scrollability within child views of v given a delta of dx. @param v View to test for horizontal scrollability @param checkV Whether the view should be checked for draggability @param dx Delta scrolled in pixels @param x X coordinate of the active touch point @param y Y coordinate of the active touch point @return true if child views of v can be scrolled by delta of dx. """ if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { final View child = group.getChildAt(i); final int childLeft = child.getLeft() + supportGetTranslationX(child); final int childRight = child.getRight() + supportGetTranslationX(child); final int childTop = child.getTop() + supportGetTranslationY(child); final int childBottom = child.getBottom() + supportGetTranslationY(child); if (x >= childLeft && x < childRight && y >= childTop && y < childBottom && canChildScrollVertically(child, true, dx, x - childLeft, y - childTop)) { return true; } } } return checkV && mOnInterceptMoveEventListener.isViewDraggable(v, dx, x, y); }
java
protected boolean canChildScrollVertically(View v, boolean checkV, int dx, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { final View child = group.getChildAt(i); final int childLeft = child.getLeft() + supportGetTranslationX(child); final int childRight = child.getRight() + supportGetTranslationX(child); final int childTop = child.getTop() + supportGetTranslationY(child); final int childBottom = child.getBottom() + supportGetTranslationY(child); if (x >= childLeft && x < childRight && y >= childTop && y < childBottom && canChildScrollVertically(child, true, dx, x - childLeft, y - childTop)) { return true; } } } return checkV && mOnInterceptMoveEventListener.isViewDraggable(v, dx, x, y); }
[ "protected", "boolean", "canChildScrollVertically", "(", "View", "v", ",", "boolean", "checkV", ",", "int", "dx", ",", "int", "x", ",", "int", "y", ")", "{", "if", "(", "v", "instanceof", "ViewGroup", ")", "{", "final", "ViewGroup", "group", "=", "(", "ViewGroup", ")", "v", ";", "final", "int", "count", "=", "group", ".", "getChildCount", "(", ")", ";", "// Count backwards - let topmost views consume scroll distance first.", "for", "(", "int", "i", "=", "count", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "final", "View", "child", "=", "group", ".", "getChildAt", "(", "i", ")", ";", "final", "int", "childLeft", "=", "child", ".", "getLeft", "(", ")", "+", "supportGetTranslationX", "(", "child", ")", ";", "final", "int", "childRight", "=", "child", ".", "getRight", "(", ")", "+", "supportGetTranslationX", "(", "child", ")", ";", "final", "int", "childTop", "=", "child", ".", "getTop", "(", ")", "+", "supportGetTranslationY", "(", "child", ")", ";", "final", "int", "childBottom", "=", "child", ".", "getBottom", "(", ")", "+", "supportGetTranslationY", "(", "child", ")", ";", "if", "(", "x", ">=", "childLeft", "&&", "x", "<", "childRight", "&&", "y", ">=", "childTop", "&&", "y", "<", "childBottom", "&&", "canChildScrollVertically", "(", "child", ",", "true", ",", "dx", ",", "x", "-", "childLeft", ",", "y", "-", "childTop", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "checkV", "&&", "mOnInterceptMoveEventListener", ".", "isViewDraggable", "(", "v", ",", "dx", ",", "x", ",", "y", ")", ";", "}" ]
Tests scrollability within child views of v given a delta of dx. @param v View to test for horizontal scrollability @param checkV Whether the view should be checked for draggability @param dx Delta scrolled in pixels @param x X coordinate of the active touch point @param y Y coordinate of the active touch point @return true if child views of v can be scrolled by delta of dx.
[ "Tests", "scrollability", "within", "child", "views", "of", "v", "given", "a", "delta", "of", "dx", "." ]
train
https://github.com/sockeqwe/SwipeBack/blob/09ed11f48e930ed47fd4f07ad1c786fc9fff3c48/library/src/com/hannesdorfmann/swipeback/DraggableSwipeBack.java#L582-L604
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java
ByteUtils.intsToBytes
public static final void intsToBytes( byte[] dst, int dst_offset, int[] src, int src_offset, int length ) { """ Convert an array of <code>int</code>s into an array of <code>bytes</code>. @param dst the array to write @param dst_offset the start offset in <code>dst</code> @param src the array to read @param src_offset the start offset in <code>src</code>, times 4. This measures the offset as if <code>src</code> were an array of <code>byte</code>s (rather than <code>int</code>s). @param length the number of <code>byte</code>s to copy. """ if ((src == null) || (dst == null) || ((dst_offset + length) > dst.length) || ((src_offset + length) > (src.length * 4)) || ((src_offset % 4) != 0) || ((length % 4) != 0)) { croak("intsToBytes parameters are invalid:" + " src=" + Arrays.toString(src) + " dst=" + Arrays.toString(dst) + " (dst_offset=" + dst_offset + " + length=" + length + ")=" + (dst_offset + length) + " > dst.length=" + ((dst == null) ? 0 : dst.length) + " (src_offset=" + src_offset + " + length=" + length + ")=" + (src_offset + length) + " > (src.length=" + ((src == null) ? 0 : src.length) + "*4)=" + ((src == null) ? 0 : (src.length * 4)) + " (src_offset=" + src_offset + " % 4)=" + (src_offset % 4) + " != 0" + " (length=" + length + " % 4)=" + (length % 4) + " != 0"); } // Convert parameters to normal format int[] offset = new int[1]; offset[0] = dst_offset; int int_src_offset = src_offset / 4; for( int i = 0; i < (length / 4); ++i ) { intToBytes(src[int_src_offset++], dst, offset); } }
java
public static final void intsToBytes( byte[] dst, int dst_offset, int[] src, int src_offset, int length ) { if ((src == null) || (dst == null) || ((dst_offset + length) > dst.length) || ((src_offset + length) > (src.length * 4)) || ((src_offset % 4) != 0) || ((length % 4) != 0)) { croak("intsToBytes parameters are invalid:" + " src=" + Arrays.toString(src) + " dst=" + Arrays.toString(dst) + " (dst_offset=" + dst_offset + " + length=" + length + ")=" + (dst_offset + length) + " > dst.length=" + ((dst == null) ? 0 : dst.length) + " (src_offset=" + src_offset + " + length=" + length + ")=" + (src_offset + length) + " > (src.length=" + ((src == null) ? 0 : src.length) + "*4)=" + ((src == null) ? 0 : (src.length * 4)) + " (src_offset=" + src_offset + " % 4)=" + (src_offset % 4) + " != 0" + " (length=" + length + " % 4)=" + (length % 4) + " != 0"); } // Convert parameters to normal format int[] offset = new int[1]; offset[0] = dst_offset; int int_src_offset = src_offset / 4; for( int i = 0; i < (length / 4); ++i ) { intToBytes(src[int_src_offset++], dst, offset); } }
[ "public", "static", "final", "void", "intsToBytes", "(", "byte", "[", "]", "dst", ",", "int", "dst_offset", ",", "int", "[", "]", "src", ",", "int", "src_offset", ",", "int", "length", ")", "{", "if", "(", "(", "src", "==", "null", ")", "||", "(", "dst", "==", "null", ")", "||", "(", "(", "dst_offset", "+", "length", ")", ">", "dst", ".", "length", ")", "||", "(", "(", "src_offset", "+", "length", ")", ">", "(", "src", ".", "length", "*", "4", ")", ")", "||", "(", "(", "src_offset", "%", "4", ")", "!=", "0", ")", "||", "(", "(", "length", "%", "4", ")", "!=", "0", ")", ")", "{", "croak", "(", "\"intsToBytes parameters are invalid:\"", "+", "\" src=\"", "+", "Arrays", ".", "toString", "(", "src", ")", "+", "\" dst=\"", "+", "Arrays", ".", "toString", "(", "dst", ")", "+", "\" (dst_offset=\"", "+", "dst_offset", "+", "\" + length=\"", "+", "length", "+", "\")=\"", "+", "(", "dst_offset", "+", "length", ")", "+", "\" > dst.length=\"", "+", "(", "(", "dst", "==", "null", ")", "?", "0", ":", "dst", ".", "length", ")", "+", "\" (src_offset=\"", "+", "src_offset", "+", "\" + length=\"", "+", "length", "+", "\")=\"", "+", "(", "src_offset", "+", "length", ")", "+", "\" > (src.length=\"", "+", "(", "(", "src", "==", "null", ")", "?", "0", ":", "src", ".", "length", ")", "+", "\"*4)=\"", "+", "(", "(", "src", "==", "null", ")", "?", "0", ":", "(", "src", ".", "length", "*", "4", ")", ")", "+", "\" (src_offset=\"", "+", "src_offset", "+", "\" % 4)=\"", "+", "(", "src_offset", "%", "4", ")", "+", "\" != 0\"", "+", "\" (length=\"", "+", "length", "+", "\" % 4)=\"", "+", "(", "length", "%", "4", ")", "+", "\" != 0\"", ")", ";", "}", "// Convert parameters to normal format", "int", "[", "]", "offset", "=", "new", "int", "[", "1", "]", ";", "offset", "[", "0", "]", "=", "dst_offset", ";", "int", "int_src_offset", "=", "src_offset", "/", "4", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "(", "length", "/", "4", ")", ";", "++", "i", ")", "{", "intToBytes", "(", "src", "[", "int_src_offset", "++", "]", ",", "dst", ",", "offset", ")", ";", "}", "}" ]
Convert an array of <code>int</code>s into an array of <code>bytes</code>. @param dst the array to write @param dst_offset the start offset in <code>dst</code> @param src the array to read @param src_offset the start offset in <code>src</code>, times 4. This measures the offset as if <code>src</code> were an array of <code>byte</code>s (rather than <code>int</code>s). @param length the number of <code>byte</code>s to copy.
[ "Convert", "an", "array", "of", "<code", ">", "int<", "/", "code", ">", "s", "into", "an", "array", "of", "<code", ">", "bytes<", "/", "code", ">", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java#L435-L455
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/decompose/hessenberg/TridiagonalDecompositionHouseholder_ZDRM.java
TridiagonalDecompositionHouseholder_ZDRM.getQ
@Override public ZMatrixRMaj getQ(ZMatrixRMaj Q , boolean transposed ) { """ An orthogonal matrix that has the following property: T = Q<sup>H</sup>AQ @param Q If not null then the results will be stored here. Otherwise a new matrix will be created. @return The extracted Q matrix. """ Q = UtilDecompositons_ZDRM.checkIdentity(Q,N,N); Arrays.fill(w,0,N*2,0); if( transposed ) { for( int j = N-2; j >= 0; j-- ) { QrHelperFunctions_ZDRM.extractHouseholderRow(QT,j,j+1,N,w,0); QrHelperFunctions_ZDRM.rank1UpdateMultL(Q, w, 0, gammas[j], j+1, j+1 , N); } } else { for( int j = N-2; j >= 0; j-- ) { QrHelperFunctions_ZDRM.extractHouseholderRow(QT,j,j+1,N,w,0); QrHelperFunctions_ZDRM.rank1UpdateMultR(Q, w, 0, gammas[j], j+1, j+1 , N, b); } } return Q; }
java
@Override public ZMatrixRMaj getQ(ZMatrixRMaj Q , boolean transposed ) { Q = UtilDecompositons_ZDRM.checkIdentity(Q,N,N); Arrays.fill(w,0,N*2,0); if( transposed ) { for( int j = N-2; j >= 0; j-- ) { QrHelperFunctions_ZDRM.extractHouseholderRow(QT,j,j+1,N,w,0); QrHelperFunctions_ZDRM.rank1UpdateMultL(Q, w, 0, gammas[j], j+1, j+1 , N); } } else { for( int j = N-2; j >= 0; j-- ) { QrHelperFunctions_ZDRM.extractHouseholderRow(QT,j,j+1,N,w,0); QrHelperFunctions_ZDRM.rank1UpdateMultR(Q, w, 0, gammas[j], j+1, j+1 , N, b); } } return Q; }
[ "@", "Override", "public", "ZMatrixRMaj", "getQ", "(", "ZMatrixRMaj", "Q", ",", "boolean", "transposed", ")", "{", "Q", "=", "UtilDecompositons_ZDRM", ".", "checkIdentity", "(", "Q", ",", "N", ",", "N", ")", ";", "Arrays", ".", "fill", "(", "w", ",", "0", ",", "N", "*", "2", ",", "0", ")", ";", "if", "(", "transposed", ")", "{", "for", "(", "int", "j", "=", "N", "-", "2", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "QrHelperFunctions_ZDRM", ".", "extractHouseholderRow", "(", "QT", ",", "j", ",", "j", "+", "1", ",", "N", ",", "w", ",", "0", ")", ";", "QrHelperFunctions_ZDRM", ".", "rank1UpdateMultL", "(", "Q", ",", "w", ",", "0", ",", "gammas", "[", "j", "]", ",", "j", "+", "1", ",", "j", "+", "1", ",", "N", ")", ";", "}", "}", "else", "{", "for", "(", "int", "j", "=", "N", "-", "2", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "QrHelperFunctions_ZDRM", ".", "extractHouseholderRow", "(", "QT", ",", "j", ",", "j", "+", "1", ",", "N", ",", "w", ",", "0", ")", ";", "QrHelperFunctions_ZDRM", ".", "rank1UpdateMultR", "(", "Q", ",", "w", ",", "0", ",", "gammas", "[", "j", "]", ",", "j", "+", "1", ",", "j", "+", "1", ",", "N", ",", "b", ")", ";", "}", "}", "return", "Q", ";", "}" ]
An orthogonal matrix that has the following property: T = Q<sup>H</sup>AQ @param Q If not null then the results will be stored here. Otherwise a new matrix will be created. @return The extracted Q matrix.
[ "An", "orthogonal", "matrix", "that", "has", "the", "following", "property", ":", "T", "=", "Q<sup", ">", "H<", "/", "sup", ">", "AQ" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/decompose/hessenberg/TridiagonalDecompositionHouseholder_ZDRM.java#L129-L148
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/CompactDecimalDataCache.java
CompactDecimalDataCache.checkForOtherVariants
private static void checkForOtherVariants(Data data, ULocale locale, String style) { """ Checks to make sure that an "other" variant is present in all powers of 10. @param data """ DecimalFormat.Unit[] otherByBase = data.units.get(OTHER); if (otherByBase == null) { throw new IllegalArgumentException("No 'other' plural variants defined in " + localeAndStyle(locale, style)); } // Check all other plural variants, and make sure that if any of them are populated, then // other is also populated for (Map.Entry<String, Unit[]> entry : data.units.entrySet()) { if (entry.getKey() == OTHER) continue; DecimalFormat.Unit[] variantByBase = entry.getValue(); for (int log10Value = 0; log10Value < MAX_DIGITS; log10Value++) { if (variantByBase[log10Value] != null && otherByBase[log10Value] == null) { throw new IllegalArgumentException( "No 'other' plural variant defined for 10^" + log10Value + " but a '" + entry.getKey() + "' variant is defined" + " in " +localeAndStyle(locale, style)); } } } }
java
private static void checkForOtherVariants(Data data, ULocale locale, String style) { DecimalFormat.Unit[] otherByBase = data.units.get(OTHER); if (otherByBase == null) { throw new IllegalArgumentException("No 'other' plural variants defined in " + localeAndStyle(locale, style)); } // Check all other plural variants, and make sure that if any of them are populated, then // other is also populated for (Map.Entry<String, Unit[]> entry : data.units.entrySet()) { if (entry.getKey() == OTHER) continue; DecimalFormat.Unit[] variantByBase = entry.getValue(); for (int log10Value = 0; log10Value < MAX_DIGITS; log10Value++) { if (variantByBase[log10Value] != null && otherByBase[log10Value] == null) { throw new IllegalArgumentException( "No 'other' plural variant defined for 10^" + log10Value + " but a '" + entry.getKey() + "' variant is defined" + " in " +localeAndStyle(locale, style)); } } } }
[ "private", "static", "void", "checkForOtherVariants", "(", "Data", "data", ",", "ULocale", "locale", ",", "String", "style", ")", "{", "DecimalFormat", ".", "Unit", "[", "]", "otherByBase", "=", "data", ".", "units", ".", "get", "(", "OTHER", ")", ";", "if", "(", "otherByBase", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No 'other' plural variants defined in \"", "+", "localeAndStyle", "(", "locale", ",", "style", ")", ")", ";", "}", "// Check all other plural variants, and make sure that if any of them are populated, then", "// other is also populated", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Unit", "[", "]", ">", "entry", ":", "data", ".", "units", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getKey", "(", ")", "==", "OTHER", ")", "continue", ";", "DecimalFormat", ".", "Unit", "[", "]", "variantByBase", "=", "entry", ".", "getValue", "(", ")", ";", "for", "(", "int", "log10Value", "=", "0", ";", "log10Value", "<", "MAX_DIGITS", ";", "log10Value", "++", ")", "{", "if", "(", "variantByBase", "[", "log10Value", "]", "!=", "null", "&&", "otherByBase", "[", "log10Value", "]", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No 'other' plural variant defined for 10^\"", "+", "log10Value", "+", "\" but a '\"", "+", "entry", ".", "getKey", "(", ")", "+", "\"' variant is defined\"", "+", "\" in \"", "+", "localeAndStyle", "(", "locale", ",", "style", ")", ")", ";", "}", "}", "}", "}" ]
Checks to make sure that an "other" variant is present in all powers of 10. @param data
[ "Checks", "to", "make", "sure", "that", "an", "other", "variant", "is", "present", "in", "all", "powers", "of", "10", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/CompactDecimalDataCache.java#L413-L435
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/fills/GradientFill.java
GradientFill.colorAt
public Color colorAt(float x, float y) { """ Get the colour that should be applied at the specified location @param x The x coordinate of the point being coloured @param y The y coordinate of the point being coloured @return The colour that should be applied based on the control points of this gradient """ float dx1 = end.getX() - start.getX(); float dy1 = end.getY() - start.getY(); float dx2 = -dy1; float dy2 = dx1; float denom = (dy2 * dx1) - (dx2 * dy1); if (denom == 0) { return Color.black; } float ua = (dx2 * (start.getY() - y)) - (dy2 * (start.getX() - x)); ua /= denom; float ub = (dx1 * (start.getY() - y)) - (dy1 * (start.getX() - x)); ub /= denom; float u = ua; if (u < 0) { u = 0; } if (u > 1) { u = 1; } float v = 1 - u; // u is the proportion down the line we are Color col = new Color(1,1,1,1); col.r = (u * endCol.r) + (v * startCol.r); col.b = (u * endCol.b) + (v * startCol.b); col.g = (u * endCol.g) + (v * startCol.g); col.a = (u * endCol.a) + (v * startCol.a); return col; }
java
public Color colorAt(float x, float y) { float dx1 = end.getX() - start.getX(); float dy1 = end.getY() - start.getY(); float dx2 = -dy1; float dy2 = dx1; float denom = (dy2 * dx1) - (dx2 * dy1); if (denom == 0) { return Color.black; } float ua = (dx2 * (start.getY() - y)) - (dy2 * (start.getX() - x)); ua /= denom; float ub = (dx1 * (start.getY() - y)) - (dy1 * (start.getX() - x)); ub /= denom; float u = ua; if (u < 0) { u = 0; } if (u > 1) { u = 1; } float v = 1 - u; // u is the proportion down the line we are Color col = new Color(1,1,1,1); col.r = (u * endCol.r) + (v * startCol.r); col.b = (u * endCol.b) + (v * startCol.b); col.g = (u * endCol.g) + (v * startCol.g); col.a = (u * endCol.a) + (v * startCol.a); return col; }
[ "public", "Color", "colorAt", "(", "float", "x", ",", "float", "y", ")", "{", "float", "dx1", "=", "end", ".", "getX", "(", ")", "-", "start", ".", "getX", "(", ")", ";", "float", "dy1", "=", "end", ".", "getY", "(", ")", "-", "start", ".", "getY", "(", ")", ";", "float", "dx2", "=", "-", "dy1", ";", "float", "dy2", "=", "dx1", ";", "float", "denom", "=", "(", "dy2", "*", "dx1", ")", "-", "(", "dx2", "*", "dy1", ")", ";", "if", "(", "denom", "==", "0", ")", "{", "return", "Color", ".", "black", ";", "}", "float", "ua", "=", "(", "dx2", "*", "(", "start", ".", "getY", "(", ")", "-", "y", ")", ")", "-", "(", "dy2", "*", "(", "start", ".", "getX", "(", ")", "-", "x", ")", ")", ";", "ua", "/=", "denom", ";", "float", "ub", "=", "(", "dx1", "*", "(", "start", ".", "getY", "(", ")", "-", "y", ")", ")", "-", "(", "dy1", "*", "(", "start", ".", "getX", "(", ")", "-", "x", ")", ")", ";", "ub", "/=", "denom", ";", "float", "u", "=", "ua", ";", "if", "(", "u", "<", "0", ")", "{", "u", "=", "0", ";", "}", "if", "(", "u", ">", "1", ")", "{", "u", "=", "1", ";", "}", "float", "v", "=", "1", "-", "u", ";", "// u is the proportion down the line we are\r", "Color", "col", "=", "new", "Color", "(", "1", ",", "1", ",", "1", ",", "1", ")", ";", "col", ".", "r", "=", "(", "u", "*", "endCol", ".", "r", ")", "+", "(", "v", "*", "startCol", ".", "r", ")", ";", "col", ".", "b", "=", "(", "u", "*", "endCol", ".", "b", ")", "+", "(", "v", "*", "startCol", ".", "b", ")", ";", "col", ".", "g", "=", "(", "u", "*", "endCol", ".", "g", ")", "+", "(", "v", "*", "startCol", ".", "g", ")", ";", "col", ".", "a", "=", "(", "u", "*", "endCol", ".", "a", ")", "+", "(", "v", "*", "startCol", ".", "a", ")", ";", "return", "col", ";", "}" ]
Get the colour that should be applied at the specified location @param x The x coordinate of the point being coloured @param y The y coordinate of the point being coloured @return The colour that should be applied based on the control points of this gradient
[ "Get", "the", "colour", "that", "should", "be", "applied", "at", "the", "specified", "location" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/fills/GradientFill.java#L212-L245
UrielCh/ovh-java-sdk
ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java
ApiOvhDbaaslogs.serviceName_output_graylog_stream_streamId_GET
public OvhStream serviceName_output_graylog_stream_streamId_GET(String serviceName, String streamId) throws IOException { """ Returns details of specified graylog stream REST: GET /dbaas/logs/{serviceName}/output/graylog/stream/{streamId} @param serviceName [required] Service name @param streamId [required] Stream ID """ String qPath = "/dbaas/logs/{serviceName}/output/graylog/stream/{streamId}"; StringBuilder sb = path(qPath, serviceName, streamId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhStream.class); }
java
public OvhStream serviceName_output_graylog_stream_streamId_GET(String serviceName, String streamId) throws IOException { String qPath = "/dbaas/logs/{serviceName}/output/graylog/stream/{streamId}"; StringBuilder sb = path(qPath, serviceName, streamId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhStream.class); }
[ "public", "OvhStream", "serviceName_output_graylog_stream_streamId_GET", "(", "String", "serviceName", ",", "String", "streamId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dbaas/logs/{serviceName}/output/graylog/stream/{streamId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "streamId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhStream", ".", "class", ")", ";", "}" ]
Returns details of specified graylog stream REST: GET /dbaas/logs/{serviceName}/output/graylog/stream/{streamId} @param serviceName [required] Service name @param streamId [required] Stream ID
[ "Returns", "details", "of", "specified", "graylog", "stream" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L1286-L1291
netkicorp/java-wns-resolver
src/main/java/com/netki/tlsa/CertChainValidator.java
CertChainValidator.validateKeyChain
private boolean validateKeyChain(X509Certificate client, X509Certificate... trustedCerts) throws CertificateException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { """ Validate keychain @param client is the client X509Certificate @param trustedCerts is Array containing all trusted X509Certificate @return true if validation until root certificate success, false otherwise @throws CertificateException Certificate is invalid @throws InvalidAlgorithmParameterException Algorithm parameter is invalid @throws NoSuchAlgorithmException No Such Algorithm Exists @throws NoSuchProviderException No Such Security Provider Exists """ boolean found = false; int i = trustedCerts.length; CertificateFactory cf = CertificateFactory.getInstance("X.509"); TrustAnchor anchor; Set<TrustAnchor> anchors; CertPath path; List<Certificate> list; PKIXParameters params; CertPathValidator validator = CertPathValidator.getInstance("PKIX"); while (!found && i > 0) { anchor = new TrustAnchor(trustedCerts[--i], null); anchors = Collections.singleton(anchor); list = Arrays.asList(new Certificate[]{client}); path = cf.generateCertPath(list); params = new PKIXParameters(anchors); params.setRevocationEnabled(false); if (client.getIssuerDN().equals(trustedCerts[i].getSubjectDN())) { try { validator.validate(path, params); if (isSelfSigned(trustedCerts[i])) { // found root ca found = true; } else if (!client.equals(trustedCerts[i])) { // find parent ca found = validateKeyChain(trustedCerts[i], trustedCerts); } } catch (CertPathValidatorException e) { // validation fail, check next certificate in the trustedCerts array } } } return found; }
java
private boolean validateKeyChain(X509Certificate client, X509Certificate... trustedCerts) throws CertificateException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { boolean found = false; int i = trustedCerts.length; CertificateFactory cf = CertificateFactory.getInstance("X.509"); TrustAnchor anchor; Set<TrustAnchor> anchors; CertPath path; List<Certificate> list; PKIXParameters params; CertPathValidator validator = CertPathValidator.getInstance("PKIX"); while (!found && i > 0) { anchor = new TrustAnchor(trustedCerts[--i], null); anchors = Collections.singleton(anchor); list = Arrays.asList(new Certificate[]{client}); path = cf.generateCertPath(list); params = new PKIXParameters(anchors); params.setRevocationEnabled(false); if (client.getIssuerDN().equals(trustedCerts[i].getSubjectDN())) { try { validator.validate(path, params); if (isSelfSigned(trustedCerts[i])) { // found root ca found = true; } else if (!client.equals(trustedCerts[i])) { // find parent ca found = validateKeyChain(trustedCerts[i], trustedCerts); } } catch (CertPathValidatorException e) { // validation fail, check next certificate in the trustedCerts array } } } return found; }
[ "private", "boolean", "validateKeyChain", "(", "X509Certificate", "client", ",", "X509Certificate", "...", "trustedCerts", ")", "throws", "CertificateException", ",", "InvalidAlgorithmParameterException", ",", "NoSuchAlgorithmException", ",", "NoSuchProviderException", "{", "boolean", "found", "=", "false", ";", "int", "i", "=", "trustedCerts", ".", "length", ";", "CertificateFactory", "cf", "=", "CertificateFactory", ".", "getInstance", "(", "\"X.509\"", ")", ";", "TrustAnchor", "anchor", ";", "Set", "<", "TrustAnchor", ">", "anchors", ";", "CertPath", "path", ";", "List", "<", "Certificate", ">", "list", ";", "PKIXParameters", "params", ";", "CertPathValidator", "validator", "=", "CertPathValidator", ".", "getInstance", "(", "\"PKIX\"", ")", ";", "while", "(", "!", "found", "&&", "i", ">", "0", ")", "{", "anchor", "=", "new", "TrustAnchor", "(", "trustedCerts", "[", "--", "i", "]", ",", "null", ")", ";", "anchors", "=", "Collections", ".", "singleton", "(", "anchor", ")", ";", "list", "=", "Arrays", ".", "asList", "(", "new", "Certificate", "[", "]", "{", "client", "}", ")", ";", "path", "=", "cf", ".", "generateCertPath", "(", "list", ")", ";", "params", "=", "new", "PKIXParameters", "(", "anchors", ")", ";", "params", ".", "setRevocationEnabled", "(", "false", ")", ";", "if", "(", "client", ".", "getIssuerDN", "(", ")", ".", "equals", "(", "trustedCerts", "[", "i", "]", ".", "getSubjectDN", "(", ")", ")", ")", "{", "try", "{", "validator", ".", "validate", "(", "path", ",", "params", ")", ";", "if", "(", "isSelfSigned", "(", "trustedCerts", "[", "i", "]", ")", ")", "{", "// found root ca", "found", "=", "true", ";", "}", "else", "if", "(", "!", "client", ".", "equals", "(", "trustedCerts", "[", "i", "]", ")", ")", "{", "// find parent ca", "found", "=", "validateKeyChain", "(", "trustedCerts", "[", "i", "]", ",", "trustedCerts", ")", ";", "}", "}", "catch", "(", "CertPathValidatorException", "e", ")", "{", "// validation fail, check next certificate in the trustedCerts array", "}", "}", "}", "return", "found", ";", "}" ]
Validate keychain @param client is the client X509Certificate @param trustedCerts is Array containing all trusted X509Certificate @return true if validation until root certificate success, false otherwise @throws CertificateException Certificate is invalid @throws InvalidAlgorithmParameterException Algorithm parameter is invalid @throws NoSuchAlgorithmException No Such Algorithm Exists @throws NoSuchProviderException No Such Security Provider Exists
[ "Validate", "keychain" ]
train
https://github.com/netkicorp/java-wns-resolver/blob/a7aad04d96c03feb05536aef189617beb4f011bc/src/main/java/com/netki/tlsa/CertChainValidator.java#L54-L98
lucee/Lucee
core/src/main/java/lucee/runtime/ComponentImpl.java
ComponentImpl.afterConstructor
public void afterConstructor(PageContext pc, Variables parent) throws ApplicationException { """ will be called after invoking constructor, only invoked by constructor (component body execution) @param pc @param 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(constructorUDFs!=null){ Iterator<Entry<Key, UDF>> it = constructorUDFs.entrySet().iterator();\n\t * Map.Entry<Key, UDF> entry; Key key; UDFPlus udf; PageSource ps; while(it.hasNext()){\n\t * entry=it.next(); key=entry.getKey(); udf=(UDFPlus) entry.getValue(); ps=udf.getPageSource();\n\t * //if(ps!=null && ps.equals(getPageSource()))continue; // TODO can we avoid that udfs from the\n\t * component itself are here? registerUDF(key, udf,false,true); } }\n\t */", "}" ]
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
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/Assert.java
Assert.isFalse
public static void isFalse(Boolean condition, String message, Object... arguments) { """ Asserts that the condition is {@literal false}. The assertion holds if and only if the value is equal to {@literal false}. @param condition {@link Boolean} value being evaluated. @param message {@link String} containing the message used in the {@link IllegalArgumentException} thrown if the assertion fails. @param arguments array of {@link Object arguments} used as placeholder values when formatting the {@link String message}. @throws java.lang.IllegalArgumentException if the value is not {@literal false}. @see #isFalse(Boolean, RuntimeException) @see java.lang.Boolean#FALSE """ isFalse(condition, new IllegalArgumentException(format(message, arguments))); }
java
public static void isFalse(Boolean condition, String message, Object... arguments) { isFalse(condition, new IllegalArgumentException(format(message, arguments))); }
[ "public", "static", "void", "isFalse", "(", "Boolean", "condition", ",", "String", "message", ",", "Object", "...", "arguments", ")", "{", "isFalse", "(", "condition", ",", "new", "IllegalArgumentException", "(", "format", "(", "message", ",", "arguments", ")", ")", ")", ";", "}" ]
Asserts that the condition is {@literal false}. The assertion holds if and only if the value is equal to {@literal false}. @param condition {@link Boolean} value being evaluated. @param message {@link String} containing the message used in the {@link IllegalArgumentException} thrown if the assertion fails. @param arguments array of {@link Object arguments} used as placeholder values when formatting the {@link String message}. @throws java.lang.IllegalArgumentException if the value is not {@literal false}. @see #isFalse(Boolean, RuntimeException) @see java.lang.Boolean#FALSE
[ "Asserts", "that", "the", "condition", "is", "{", "@literal", "false", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Assert.java#L634-L636
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ExpiringResourceClaim.java
ExpiringResourceClaim.claimExpiring
public static ResourceClaim claimExpiring(ZooKeeperConnection zooKeeperConnection, int poolSize, String znode) throws IOException { """ Claim a resource. @param zooKeeperConnection ZooKeeper connection to use. @param poolSize Size of the resource pool. @param znode Root znode of the ZooKeeper resource-pool. @return A resource claim. """ return claimExpiring(zooKeeperConnection, poolSize, znode, DEFAULT_TIMEOUT); }
java
public static ResourceClaim claimExpiring(ZooKeeperConnection zooKeeperConnection, int poolSize, String znode) throws IOException { return claimExpiring(zooKeeperConnection, poolSize, znode, DEFAULT_TIMEOUT); }
[ "public", "static", "ResourceClaim", "claimExpiring", "(", "ZooKeeperConnection", "zooKeeperConnection", ",", "int", "poolSize", ",", "String", "znode", ")", "throws", "IOException", "{", "return", "claimExpiring", "(", "zooKeeperConnection", ",", "poolSize", ",", "znode", ",", "DEFAULT_TIMEOUT", ")", ";", "}" ]
Claim a resource. @param zooKeeperConnection ZooKeeper connection to use. @param poolSize Size of the resource pool. @param znode Root znode of the ZooKeeper resource-pool. @return A resource claim.
[ "Claim", "a", "resource", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ExpiringResourceClaim.java#L54-L57
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/RamUsageEstimator.java
RamUsageEstimator.humanReadableUnits
static String humanReadableUnits(long bytes, DecimalFormat df) { """ Returns <code>size</code> in human-readable units (GB, MB, KB or bytes). """ if (bytes / ONE_GB > 0) { return df.format((float) bytes / ONE_GB) + " GB"; } else if (bytes / ONE_MB > 0) { return df.format((float) bytes / ONE_MB) + " MB"; } else if (bytes / ONE_KB > 0) { return df.format((float) bytes / ONE_KB) + " KB"; } else { return bytes + " bytes"; } }
java
static String humanReadableUnits(long bytes, DecimalFormat df) { if (bytes / ONE_GB > 0) { return df.format((float) bytes / ONE_GB) + " GB"; } else if (bytes / ONE_MB > 0) { return df.format((float) bytes / ONE_MB) + " MB"; } else if (bytes / ONE_KB > 0) { return df.format((float) bytes / ONE_KB) + " KB"; } else { return bytes + " bytes"; } }
[ "static", "String", "humanReadableUnits", "(", "long", "bytes", ",", "DecimalFormat", "df", ")", "{", "if", "(", "bytes", "/", "ONE_GB", ">", "0", ")", "{", "return", "df", ".", "format", "(", "(", "float", ")", "bytes", "/", "ONE_GB", ")", "+", "\" GB\"", ";", "}", "else", "if", "(", "bytes", "/", "ONE_MB", ">", "0", ")", "{", "return", "df", ".", "format", "(", "(", "float", ")", "bytes", "/", "ONE_MB", ")", "+", "\" MB\"", ";", "}", "else", "if", "(", "bytes", "/", "ONE_KB", ">", "0", ")", "{", "return", "df", ".", "format", "(", "(", "float", ")", "bytes", "/", "ONE_KB", ")", "+", "\" KB\"", ";", "}", "else", "{", "return", "bytes", "+", "\" bytes\"", ";", "}", "}" ]
Returns <code>size</code> in human-readable units (GB, MB, KB or bytes).
[ "Returns", "<code", ">", "size<", "/", "code", ">", "in", "human", "-", "readable", "units", "(", "GB", "MB", "KB", "or", "bytes", ")", "." ]
train
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/RamUsageEstimator.java#L394-L404
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/model/IfdTags.java
IfdTags.addTag
public void addTag(String tagName, String tagValue) { """ Adds the tag. @param tagName the tag name @param tagValue the tag value """ int id = TiffTags.getTagId(tagName); TagValue tag = new TagValue(id, 2); for (int i = 0; i < tagValue.length(); i++) { int val = tagValue.charAt(i); if (val > 127) val = 0; Ascii cha = new Ascii(val); tag.add(cha); } Ascii chaf = new Ascii(0); tag.add(chaf); addTag(tag); }
java
public void addTag(String tagName, String tagValue) { int id = TiffTags.getTagId(tagName); TagValue tag = new TagValue(id, 2); for (int i = 0; i < tagValue.length(); i++) { int val = tagValue.charAt(i); if (val > 127) val = 0; Ascii cha = new Ascii(val); tag.add(cha); } Ascii chaf = new Ascii(0); tag.add(chaf); addTag(tag); }
[ "public", "void", "addTag", "(", "String", "tagName", ",", "String", "tagValue", ")", "{", "int", "id", "=", "TiffTags", ".", "getTagId", "(", "tagName", ")", ";", "TagValue", "tag", "=", "new", "TagValue", "(", "id", ",", "2", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tagValue", ".", "length", "(", ")", ";", "i", "++", ")", "{", "int", "val", "=", "tagValue", ".", "charAt", "(", "i", ")", ";", "if", "(", "val", ">", "127", ")", "val", "=", "0", ";", "Ascii", "cha", "=", "new", "Ascii", "(", "val", ")", ";", "tag", ".", "add", "(", "cha", ")", ";", "}", "Ascii", "chaf", "=", "new", "Ascii", "(", "0", ")", ";", "tag", ".", "add", "(", "chaf", ")", ";", "addTag", "(", "tag", ")", ";", "}" ]
Adds the tag. @param tagName the tag name @param tagValue the tag value
[ "Adds", "the", "tag", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/model/IfdTags.java#L108-L120
saxsys/SynchronizeFX
synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/executors/lists/AddToListRepairer.java
AddToListRepairer.repairCommand
public AddToList repairCommand(final AddToList toRepair, final RemoveFromList repairAgainst) { """ Repairs an {@link AddToList} in relation to a {@link RemoveFromList} command. @param toRepair The command to repair. @param repairAgainst The command to repair against. @return The repaired command. """ final int indicesBefore = toRepair.getPosition() - repairAgainst.getStartPosition(); if (indicesBefore <= 0) { return toRepair; } final int indicesToDecrese = indicesBefore < repairAgainst.getRemoveCount() ? indicesBefore : repairAgainst .getRemoveCount(); return createCommand(toRepair, toRepair.getPosition() - indicesToDecrese); }
java
public AddToList repairCommand(final AddToList toRepair, final RemoveFromList repairAgainst) { final int indicesBefore = toRepair.getPosition() - repairAgainst.getStartPosition(); if (indicesBefore <= 0) { return toRepair; } final int indicesToDecrese = indicesBefore < repairAgainst.getRemoveCount() ? indicesBefore : repairAgainst .getRemoveCount(); return createCommand(toRepair, toRepair.getPosition() - indicesToDecrese); }
[ "public", "AddToList", "repairCommand", "(", "final", "AddToList", "toRepair", ",", "final", "RemoveFromList", "repairAgainst", ")", "{", "final", "int", "indicesBefore", "=", "toRepair", ".", "getPosition", "(", ")", "-", "repairAgainst", ".", "getStartPosition", "(", ")", ";", "if", "(", "indicesBefore", "<=", "0", ")", "{", "return", "toRepair", ";", "}", "final", "int", "indicesToDecrese", "=", "indicesBefore", "<", "repairAgainst", ".", "getRemoveCount", "(", ")", "?", "indicesBefore", ":", "repairAgainst", ".", "getRemoveCount", "(", ")", ";", "return", "createCommand", "(", "toRepair", ",", "toRepair", ".", "getPosition", "(", ")", "-", "indicesToDecrese", ")", ";", "}" ]
Repairs an {@link AddToList} in relation to a {@link RemoveFromList} command. @param toRepair The command to repair. @param repairAgainst The command to repair against. @return The repaired command.
[ "Repairs", "an", "{", "@link", "AddToList", "}", "in", "relation", "to", "a", "{", "@link", "RemoveFromList", "}", "command", "." ]
train
https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/executors/lists/AddToListRepairer.java#L76-L84
alkacon/opencms-core
src/org/opencms/ade/contenteditor/CmsContentService.java
CmsContentService.transferSettingValues
private void transferSettingValues(CmsEntity source, CmsEntity target) { """ Transfers settings attribute values from one entity to another.<p> @param source the source entity @param target the target entity """ for (CmsEntityAttribute attr : source.getAttributes()) { if (isSettingsAttribute(attr.getAttributeName())) { if (attr.isSimpleValue()) { target.addAttributeValue(attr.getAttributeName(), attr.getSimpleValue()); } else { CmsEntity nestedSource = attr.getComplexValue(); CmsEntity nested = new CmsEntity(nestedSource.getId(), nestedSource.getTypeName()); for (CmsEntityAttribute nestedAttr : nestedSource.getAttributes()) { nested.addAttributeValue(nestedAttr.getAttributeName(), nestedAttr.getSimpleValue()); } target.addAttributeValue(attr.getAttributeName(), nested); } } } }
java
private void transferSettingValues(CmsEntity source, CmsEntity target) { for (CmsEntityAttribute attr : source.getAttributes()) { if (isSettingsAttribute(attr.getAttributeName())) { if (attr.isSimpleValue()) { target.addAttributeValue(attr.getAttributeName(), attr.getSimpleValue()); } else { CmsEntity nestedSource = attr.getComplexValue(); CmsEntity nested = new CmsEntity(nestedSource.getId(), nestedSource.getTypeName()); for (CmsEntityAttribute nestedAttr : nestedSource.getAttributes()) { nested.addAttributeValue(nestedAttr.getAttributeName(), nestedAttr.getSimpleValue()); } target.addAttributeValue(attr.getAttributeName(), nested); } } } }
[ "private", "void", "transferSettingValues", "(", "CmsEntity", "source", ",", "CmsEntity", "target", ")", "{", "for", "(", "CmsEntityAttribute", "attr", ":", "source", ".", "getAttributes", "(", ")", ")", "{", "if", "(", "isSettingsAttribute", "(", "attr", ".", "getAttributeName", "(", ")", ")", ")", "{", "if", "(", "attr", ".", "isSimpleValue", "(", ")", ")", "{", "target", ".", "addAttributeValue", "(", "attr", ".", "getAttributeName", "(", ")", ",", "attr", ".", "getSimpleValue", "(", ")", ")", ";", "}", "else", "{", "CmsEntity", "nestedSource", "=", "attr", ".", "getComplexValue", "(", ")", ";", "CmsEntity", "nested", "=", "new", "CmsEntity", "(", "nestedSource", ".", "getId", "(", ")", ",", "nestedSource", ".", "getTypeName", "(", ")", ")", ";", "for", "(", "CmsEntityAttribute", "nestedAttr", ":", "nestedSource", ".", "getAttributes", "(", ")", ")", "{", "nested", ".", "addAttributeValue", "(", "nestedAttr", ".", "getAttributeName", "(", ")", ",", "nestedAttr", ".", "getSimpleValue", "(", ")", ")", ";", "}", "target", ".", "addAttributeValue", "(", "attr", ".", "getAttributeName", "(", ")", ",", "nested", ")", ";", "}", "}", "}", "}" ]
Transfers settings attribute values from one entity to another.<p> @param source the source entity @param target the target entity
[ "Transfers", "settings", "attribute", "values", "from", "one", "entity", "to", "another", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/contenteditor/CmsContentService.java#L2437-L2454
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ZooKeeperHelper.java
ZooKeeperHelper.mkdirp
static void mkdirp(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { """ Recursively create empty znodes (if missing) analogous to {@code mkdir -p}. @param zookeeper ZooKeeper instance to work with. @param znode Path to create. @throws org.apache.zookeeper.KeeperException @throws InterruptedException """ boolean createPath = false; for (String path : pathParts(znode)) { if (!createPath) { Stat stat = zookeeper.exists(path, false); if (stat == null) { createPath = true; } } if (createPath) { create(zookeeper, path); } } }
java
static void mkdirp(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { boolean createPath = false; for (String path : pathParts(znode)) { if (!createPath) { Stat stat = zookeeper.exists(path, false); if (stat == null) { createPath = true; } } if (createPath) { create(zookeeper, path); } } }
[ "static", "void", "mkdirp", "(", "ZooKeeper", "zookeeper", ",", "String", "znode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "boolean", "createPath", "=", "false", ";", "for", "(", "String", "path", ":", "pathParts", "(", "znode", ")", ")", "{", "if", "(", "!", "createPath", ")", "{", "Stat", "stat", "=", "zookeeper", ".", "exists", "(", "path", ",", "false", ")", ";", "if", "(", "stat", "==", "null", ")", "{", "createPath", "=", "true", ";", "}", "}", "if", "(", "createPath", ")", "{", "create", "(", "zookeeper", ",", "path", ")", ";", "}", "}", "}" ]
Recursively create empty znodes (if missing) analogous to {@code mkdir -p}. @param zookeeper ZooKeeper instance to work with. @param znode Path to create. @throws org.apache.zookeeper.KeeperException @throws InterruptedException
[ "Recursively", "create", "empty", "znodes", "(", "if", "missing", ")", "analogous", "to", "{", "@code", "mkdir", "-", "p", "}", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ZooKeeperHelper.java#L40-L53
carewebframework/carewebframework-core
org.carewebframework.security-parent/org.carewebframework.security.core/src/main/java/org/carewebframework/security/BaseAuthenticationProvider.java
BaseAuthenticationProvider.authenticate
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { """ Produces a trusted <code>UsernamePasswordAuthenticationToken</code> if authentication was successful. @param authentication The authentication context. @return authentication Authentication object if authentication succeeded. @throws AuthenticationException Exception on authentication failure. """ CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails(); String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); String domain = null; if (log.isDebugEnabled()) { log.debug("User: " + username); log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress()); } if (username != null && username.contains("\\")) { String pcs[] = username.split("\\\\", 2); domain = pcs[0]; username = pcs.length > 1 ? pcs[1] : null; } ISecurityDomain securityDomain = SecurityDomainRegistry.getSecurityDomain(domain); if (username == null || password == null || securityDomain == null) { throw new BadCredentialsException("Missing security credentials."); } IUser user = securityDomain.authenticate(username, password); details.setDetail("user", user); Set<String> mergedAuthorities = mergeAuthorities(securityDomain.getGrantedAuthorities(user), systemGrantedAuthorities); List<GrantedAuthority> userAuthorities = new ArrayList<>(); for (String authority : mergedAuthorities) { if (!authority.isEmpty()) { userAuthorities.add(new SimpleGrantedAuthority(authority)); } } User principal = new User(username, password, true, true, true, true, userAuthorities); authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); ((UsernamePasswordAuthenticationToken) authentication).setDetails(details); return authentication; }
java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails(); String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); String domain = null; if (log.isDebugEnabled()) { log.debug("User: " + username); log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress()); } if (username != null && username.contains("\\")) { String pcs[] = username.split("\\\\", 2); domain = pcs[0]; username = pcs.length > 1 ? pcs[1] : null; } ISecurityDomain securityDomain = SecurityDomainRegistry.getSecurityDomain(domain); if (username == null || password == null || securityDomain == null) { throw new BadCredentialsException("Missing security credentials."); } IUser user = securityDomain.authenticate(username, password); details.setDetail("user", user); Set<String> mergedAuthorities = mergeAuthorities(securityDomain.getGrantedAuthorities(user), systemGrantedAuthorities); List<GrantedAuthority> userAuthorities = new ArrayList<>(); for (String authority : mergedAuthorities) { if (!authority.isEmpty()) { userAuthorities.add(new SimpleGrantedAuthority(authority)); } } User principal = new User(username, password, true, true, true, true, userAuthorities); authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); ((UsernamePasswordAuthenticationToken) authentication).setDetails(details); return authentication; }
[ "@", "Override", "public", "Authentication", "authenticate", "(", "Authentication", "authentication", ")", "throws", "AuthenticationException", "{", "CWFAuthenticationDetails", "details", "=", "(", "CWFAuthenticationDetails", ")", "authentication", ".", "getDetails", "(", ")", ";", "String", "username", "=", "(", "String", ")", "authentication", ".", "getPrincipal", "(", ")", ";", "String", "password", "=", "(", "String", ")", "authentication", ".", "getCredentials", "(", ")", ";", "String", "domain", "=", "null", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"User: \"", "+", "username", ")", ";", "log", ".", "debug", "(", "\"Details, RA: \"", "+", "details", "==", "null", "?", "\"null\"", ":", "details", ".", "getRemoteAddress", "(", ")", ")", ";", "}", "if", "(", "username", "!=", "null", "&&", "username", ".", "contains", "(", "\"\\\\\"", ")", ")", "{", "String", "pcs", "[", "]", "=", "username", ".", "split", "(", "\"\\\\\\\\\"", ",", "2", ")", ";", "domain", "=", "pcs", "[", "0", "]", ";", "username", "=", "pcs", ".", "length", ">", "1", "?", "pcs", "[", "1", "]", ":", "null", ";", "}", "ISecurityDomain", "securityDomain", "=", "SecurityDomainRegistry", ".", "getSecurityDomain", "(", "domain", ")", ";", "if", "(", "username", "==", "null", "||", "password", "==", "null", "||", "securityDomain", "==", "null", ")", "{", "throw", "new", "BadCredentialsException", "(", "\"Missing security credentials.\"", ")", ";", "}", "IUser", "user", "=", "securityDomain", ".", "authenticate", "(", "username", ",", "password", ")", ";", "details", ".", "setDetail", "(", "\"user\"", ",", "user", ")", ";", "Set", "<", "String", ">", "mergedAuthorities", "=", "mergeAuthorities", "(", "securityDomain", ".", "getGrantedAuthorities", "(", "user", ")", ",", "systemGrantedAuthorities", ")", ";", "List", "<", "GrantedAuthority", ">", "userAuthorities", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "authority", ":", "mergedAuthorities", ")", "{", "if", "(", "!", "authority", ".", "isEmpty", "(", ")", ")", "{", "userAuthorities", ".", "add", "(", "new", "SimpleGrantedAuthority", "(", "authority", ")", ")", ";", "}", "}", "User", "principal", "=", "new", "User", "(", "username", ",", "password", ",", "true", ",", "true", ",", "true", ",", "true", ",", "userAuthorities", ")", ";", "authentication", "=", "new", "UsernamePasswordAuthenticationToken", "(", "principal", ",", "principal", ".", "getPassword", "(", ")", ",", "principal", ".", "getAuthorities", "(", ")", ")", ";", "(", "(", "UsernamePasswordAuthenticationToken", ")", "authentication", ")", ".", "setDetails", "(", "details", ")", ";", "return", "authentication", ";", "}" ]
Produces a trusted <code>UsernamePasswordAuthenticationToken</code> if authentication was successful. @param authentication The authentication context. @return authentication Authentication object if authentication succeeded. @throws AuthenticationException Exception on authentication failure.
[ "Produces", "a", "trusted", "<code", ">", "UsernamePasswordAuthenticationToken<", "/", "code", ">", "if", "authentication", "was", "successful", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.security-parent/org.carewebframework.security.core/src/main/java/org/carewebframework/security/BaseAuthenticationProvider.java#L87-L128
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java
TreeScanner.visitTypeParameter
@Override public R visitTypeParameter(TypeParameterTree node, P p) { """ {@inheritDoc} This implementation scans the children in left to right order. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of scanning """ R r = scan(node.getAnnotations(), p); r = scanAndReduce(node.getBounds(), p, r); return r; }
java
@Override public R visitTypeParameter(TypeParameterTree node, P p) { R r = scan(node.getAnnotations(), p); r = scanAndReduce(node.getBounds(), p, r); return r; }
[ "@", "Override", "public", "R", "visitTypeParameter", "(", "TypeParameterTree", "node", ",", "P", "p", ")", "{", "R", "r", "=", "scan", "(", "node", ".", "getAnnotations", "(", ")", ",", "p", ")", ";", "r", "=", "scanAndReduce", "(", "node", ".", "getBounds", "(", ")", ",", "p", ",", "r", ")", ";", "return", "r", ";", "}" ]
{@inheritDoc} This implementation scans the children in left to right order. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of scanning
[ "{", "@inheritDoc", "}", "This", "implementation", "scans", "the", "children", "in", "left", "to", "right", "order", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L790-L795
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) { """ Change the attributes of the tuple. @param segment the segment. @param curviline the curviline coordinate. @param shift the shift distance. """ 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", ".", "segment", "=", "new", "WeakReference", "<>", "(", "segment", ")", ";", "this", ".", "x", "=", "curviline", ";", "this", ".", "y", "=", "shift", ";", "}" ]
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
VoltDB/voltdb
src/frontend/org/voltdb/StoredProcedureInvocation.java
StoredProcedureInvocation.getLoadVoltTablesMagicSeriazlizedSize
public static int getLoadVoltTablesMagicSeriazlizedSize(Table catTable, boolean isPartitioned) { """ Hack for SyncSnapshotBuffer. Note that this is using the ORIGINAL (version 0) serialization format. Moved to this file from that one so you might see it sooner than I did. If you change the serialization, you have to change this too. """ // code below is used to compute the right value slowly /* StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.setProcName("@LoadVoltTableSP"); if (isPartitioned) { spi.setParams(0, catTable.getTypeName(), null); } else { spi.setParams(0, catTable.getTypeName(), null); } int size = spi.getSerializedSizeForOriginalVersion() + 4; int realSize = size - catTable.getTypeName().getBytes(Constants.UTF8ENCODING).length; System.err.printf("@LoadVoltTable** padding size: %d or %d\n", size, realSize); return size; */ // Magic size of @LoadVoltTable* StoredProcedureInvocation int tableNameLengthInBytes = catTable.getTypeName().getBytes(Constants.UTF8ENCODING).length; int metadataSize = 41 + // serialized size for original version tableNameLengthInBytes; if (isPartitioned) { metadataSize += 5; } return metadataSize; }
java
public static int getLoadVoltTablesMagicSeriazlizedSize(Table catTable, boolean isPartitioned) { // code below is used to compute the right value slowly /* StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.setProcName("@LoadVoltTableSP"); if (isPartitioned) { spi.setParams(0, catTable.getTypeName(), null); } else { spi.setParams(0, catTable.getTypeName(), null); } int size = spi.getSerializedSizeForOriginalVersion() + 4; int realSize = size - catTable.getTypeName().getBytes(Constants.UTF8ENCODING).length; System.err.printf("@LoadVoltTable** padding size: %d or %d\n", size, realSize); return size; */ // Magic size of @LoadVoltTable* StoredProcedureInvocation int tableNameLengthInBytes = catTable.getTypeName().getBytes(Constants.UTF8ENCODING).length; int metadataSize = 41 + // serialized size for original version tableNameLengthInBytes; if (isPartitioned) { metadataSize += 5; } return metadataSize; }
[ "public", "static", "int", "getLoadVoltTablesMagicSeriazlizedSize", "(", "Table", "catTable", ",", "boolean", "isPartitioned", ")", "{", "// code below is used to compute the right value slowly", "/*\n StoredProcedureInvocation spi = new StoredProcedureInvocation();\n spi.setProcName(\"@LoadVoltTableSP\");\n if (isPartitioned) {\n spi.setParams(0, catTable.getTypeName(), null);\n }\n else {\n spi.setParams(0, catTable.getTypeName(), null);\n }\n int size = spi.getSerializedSizeForOriginalVersion() + 4;\n int realSize = size - catTable.getTypeName().getBytes(Constants.UTF8ENCODING).length;\n System.err.printf(\"@LoadVoltTable** padding size: %d or %d\\n\", size, realSize);\n return size;\n */", "// Magic size of @LoadVoltTable* StoredProcedureInvocation", "int", "tableNameLengthInBytes", "=", "catTable", ".", "getTypeName", "(", ")", ".", "getBytes", "(", "Constants", ".", "UTF8ENCODING", ")", ".", "length", ";", "int", "metadataSize", "=", "41", "+", "// serialized size for original version", "tableNameLengthInBytes", ";", "if", "(", "isPartitioned", ")", "{", "metadataSize", "+=", "5", ";", "}", "return", "metadataSize", ";", "}" ]
Hack for SyncSnapshotBuffer. Note that this is using the ORIGINAL (version 0) serialization format. Moved to this file from that one so you might see it sooner than I did. If you change the serialization, you have to change this too.
[ "Hack", "for", "SyncSnapshotBuffer", ".", "Note", "that", "this", "is", "using", "the", "ORIGINAL", "(", "version", "0", ")", "serialization", "format", ".", "Moved", "to", "this", "file", "from", "that", "one", "so", "you", "might", "see", "it", "sooner", "than", "I", "did", ".", "If", "you", "change", "the", "serialization", "you", "have", "to", "change", "this", "too", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/StoredProcedureInvocation.java#L282-L309
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java
EncodingUtils.decryptJwtValue
@SneakyThrows public static String decryptJwtValue(final Key secretKeyEncryptionKey, final String value) { """ Decrypt value based on the key created. @param secretKeyEncryptionKey the secret key encryption key @param value the value @return the decrypted value """ val jwe = new JsonWebEncryption(); jwe.setKey(secretKeyEncryptionKey); jwe.setCompactSerialization(value); LOGGER.trace("Decrypting value..."); try { return jwe.getPayload(); } catch (final JoseException e) { if (LOGGER.isTraceEnabled()) { throw new DecryptionException(e); } throw new DecryptionException(); } }
java
@SneakyThrows public static String decryptJwtValue(final Key secretKeyEncryptionKey, final String value) { val jwe = new JsonWebEncryption(); jwe.setKey(secretKeyEncryptionKey); jwe.setCompactSerialization(value); LOGGER.trace("Decrypting value..."); try { return jwe.getPayload(); } catch (final JoseException e) { if (LOGGER.isTraceEnabled()) { throw new DecryptionException(e); } throw new DecryptionException(); } }
[ "@", "SneakyThrows", "public", "static", "String", "decryptJwtValue", "(", "final", "Key", "secretKeyEncryptionKey", ",", "final", "String", "value", ")", "{", "val", "jwe", "=", "new", "JsonWebEncryption", "(", ")", ";", "jwe", ".", "setKey", "(", "secretKeyEncryptionKey", ")", ";", "jwe", ".", "setCompactSerialization", "(", "value", ")", ";", "LOGGER", ".", "trace", "(", "\"Decrypting value...\"", ")", ";", "try", "{", "return", "jwe", ".", "getPayload", "(", ")", ";", "}", "catch", "(", "final", "JoseException", "e", ")", "{", "if", "(", "LOGGER", ".", "isTraceEnabled", "(", ")", ")", "{", "throw", "new", "DecryptionException", "(", "e", ")", ";", "}", "throw", "new", "DecryptionException", "(", ")", ";", "}", "}" ]
Decrypt value based on the key created. @param secretKeyEncryptionKey the secret key encryption key @param value the value @return the decrypted value
[ "Decrypt", "value", "based", "on", "the", "key", "created", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java#L431-L445
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java
BigDecimalUtil.movedInsideThresholdPercentage
public static boolean movedInsideThresholdPercentage(final BigDecimal startValue, final BigDecimal newValue, final BigDecimal thresholdPercent) { """ true if ABS((startValue-newValue)/startValue) &lt;= abs(thresholdPercent) @param startValue @param newValue @param thresholdPercent @return """ return !movedStrictlyOutsideThresholdPercentage(startValue, newValue, thresholdPercent); }
java
public static boolean movedInsideThresholdPercentage(final BigDecimal startValue, final BigDecimal newValue, final BigDecimal thresholdPercent) { return !movedStrictlyOutsideThresholdPercentage(startValue, newValue, thresholdPercent); }
[ "public", "static", "boolean", "movedInsideThresholdPercentage", "(", "final", "BigDecimal", "startValue", ",", "final", "BigDecimal", "newValue", ",", "final", "BigDecimal", "thresholdPercent", ")", "{", "return", "!", "movedStrictlyOutsideThresholdPercentage", "(", "startValue", ",", "newValue", ",", "thresholdPercent", ")", ";", "}" ]
true if ABS((startValue-newValue)/startValue) &lt;= abs(thresholdPercent) @param startValue @param newValue @param thresholdPercent @return
[ "true", "if", "ABS", "((", "startValue", "-", "newValue", ")", "/", "startValue", ")", "&lt", ";", "=", "abs", "(", "thresholdPercent", ")" ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java#L545-L547
elki-project/elki
elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java
DBIDUtil.randomSampleExcept
public static ModifiableDBIDs randomSampleExcept(DBIDs source, DBIDRef except, int k, RandomFactory rnd) { """ Produce a random sample of the given DBIDs. @param source Original DBIDs, no duplicates allowed @param except Excluded object @param k k Parameter @param rnd Random generator @return new DBIDs """ return randomSampleExcept(source, except, k, rnd.getSingleThreadedRandom()); }
java
public static ModifiableDBIDs randomSampleExcept(DBIDs source, DBIDRef except, int k, RandomFactory rnd) { return randomSampleExcept(source, except, k, rnd.getSingleThreadedRandom()); }
[ "public", "static", "ModifiableDBIDs", "randomSampleExcept", "(", "DBIDs", "source", ",", "DBIDRef", "except", ",", "int", "k", ",", "RandomFactory", "rnd", ")", "{", "return", "randomSampleExcept", "(", "source", ",", "except", ",", "k", ",", "rnd", ".", "getSingleThreadedRandom", "(", ")", ")", ";", "}" ]
Produce a random sample of the given DBIDs. @param source Original DBIDs, no duplicates allowed @param except Excluded object @param k k Parameter @param rnd Random generator @return new DBIDs
[ "Produce", "a", "random", "sample", "of", "the", "given", "DBIDs", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L586-L588
greese/dasein-persist
src/main/java/org/dasein/persist/PersistentFactory.java
PersistentFactory.find
public Collection<T> find(Class<? extends Execution> cls, Map<String,Object> criteria) throws PersistenceException { """ Executes an arbitrary search using the passed in search class and criteria. This is useful for searches that simply do not fit well into the rest of the API. @param cls the class to perform the search @param criteria the search criteria @return the results of the search @throws PersistenceException an error occurred performing the search """ logger.debug("enter - find(Class,Map)"); try { Collection<String> keys = criteria.keySet(); SearchTerm[] terms = new SearchTerm[keys.size()]; int i = 0; for( String key : keys ) { terms[i++] = new SearchTerm(key, Operator.EQUALS, criteria.get(key)); } return load(cls, null, terms); } finally { logger.debug("exit - find(Class,Map)"); } }
java
public Collection<T> find(Class<? extends Execution> cls, Map<String,Object> criteria) throws PersistenceException { logger.debug("enter - find(Class,Map)"); try { Collection<String> keys = criteria.keySet(); SearchTerm[] terms = new SearchTerm[keys.size()]; int i = 0; for( String key : keys ) { terms[i++] = new SearchTerm(key, Operator.EQUALS, criteria.get(key)); } return load(cls, null, terms); } finally { logger.debug("exit - find(Class,Map)"); } }
[ "public", "Collection", "<", "T", ">", "find", "(", "Class", "<", "?", "extends", "Execution", ">", "cls", ",", "Map", "<", "String", ",", "Object", ">", "criteria", ")", "throws", "PersistenceException", "{", "logger", ".", "debug", "(", "\"enter - find(Class,Map)\"", ")", ";", "try", "{", "Collection", "<", "String", ">", "keys", "=", "criteria", ".", "keySet", "(", ")", ";", "SearchTerm", "[", "]", "terms", "=", "new", "SearchTerm", "[", "keys", ".", "size", "(", ")", "]", ";", "int", "i", "=", "0", ";", "for", "(", "String", "key", ":", "keys", ")", "{", "terms", "[", "i", "++", "]", "=", "new", "SearchTerm", "(", "key", ",", "Operator", ".", "EQUALS", ",", "criteria", ".", "get", "(", "key", ")", ")", ";", "}", "return", "load", "(", "cls", ",", "null", ",", "terms", ")", ";", "}", "finally", "{", "logger", ".", "debug", "(", "\"exit - find(Class,Map)\"", ")", ";", "}", "}" ]
Executes an arbitrary search using the passed in search class and criteria. This is useful for searches that simply do not fit well into the rest of the API. @param cls the class to perform the search @param criteria the search criteria @return the results of the search @throws PersistenceException an error occurred performing the search
[ "Executes", "an", "arbitrary", "search", "using", "the", "passed", "in", "search", "class", "and", "criteria", ".", "This", "is", "useful", "for", "searches", "that", "simply", "do", "not", "fit", "well", "into", "the", "rest", "of", "the", "API", "." ]
train
https://github.com/greese/dasein-persist/blob/1104621ad1670a45488b093b984ec1db4c7be781/src/main/java/org/dasein/persist/PersistentFactory.java#L1456-L1471
jenkinsci/jenkins
core/src/main/java/jenkins/util/SystemProperties.java
SystemProperties.getInteger
public static Integer getInteger(String name, Integer def, Level logLevel) { """ Determines the integer value of the system property with the specified name, or a default value. This behaves just like <code>Integer.getInteger(String,Integer)</code>, except that it also consults the <code>ServletContext</code>'s "init" parameters. If neither exist, return the default value. @param name property name. @param def a default value. @param logLevel the level of the log if the provided system property name cannot be decoded into Integer. @return the {@code Integer} value of the property. If the property is missing, return the default value. Result may be {@code null} only if the default value is {@code null}. """ String v = getString(name); if (v != null) { try { return Integer.decode(v); } catch (NumberFormatException e) { // Ignore, fallback to default if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property. Value is not integer: {0} => {1}", new Object[] {name, v}); } } } return def; }
java
public static Integer getInteger(String name, Integer def, Level logLevel) { String v = getString(name); if (v != null) { try { return Integer.decode(v); } catch (NumberFormatException e) { // Ignore, fallback to default if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property. Value is not integer: {0} => {1}", new Object[] {name, v}); } } } return def; }
[ "public", "static", "Integer", "getInteger", "(", "String", "name", ",", "Integer", "def", ",", "Level", "logLevel", ")", "{", "String", "v", "=", "getString", "(", "name", ")", ";", "if", "(", "v", "!=", "null", ")", "{", "try", "{", "return", "Integer", ".", "decode", "(", "v", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "// Ignore, fallback to default", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property. Value is not integer: {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "name", ",", "v", "}", ")", ";", "}", "}", "}", "return", "def", ";", "}" ]
Determines the integer value of the system property with the specified name, or a default value. This behaves just like <code>Integer.getInteger(String,Integer)</code>, except that it also consults the <code>ServletContext</code>'s "init" parameters. If neither exist, return the default value. @param name property name. @param def a default value. @param logLevel the level of the log if the provided system property name cannot be decoded into Integer. @return the {@code Integer} value of the property. If the property is missing, return the default value. Result may be {@code null} only if the default value is {@code null}.
[ "Determines", "the", "integer", "value", "of", "the", "system", "property", "with", "the", "specified", "name", "or", "a", "default", "value", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/SystemProperties.java#L366-L380
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/MediaApi.java
MediaApi.readyForMedia
public ApiSuccessResponse readyForMedia(String mediatype, ReadyForMediaData readyForMediaData) throws ApiException { """ Set the agent state to Ready Set the current agent&#39;s state to Ready on the specified media channel. @param mediatype The media channel. (required) @param readyForMediaData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = readyForMediaWithHttpInfo(mediatype, readyForMediaData); return resp.getData(); }
java
public ApiSuccessResponse readyForMedia(String mediatype, ReadyForMediaData readyForMediaData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = readyForMediaWithHttpInfo(mediatype, readyForMediaData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "readyForMedia", "(", "String", "mediatype", ",", "ReadyForMediaData", "readyForMediaData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "readyForMediaWithHttpInfo", "(", "mediatype", ",", "readyForMediaData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Set the agent state to Ready Set the current agent&#39;s state to Ready on the specified media channel. @param mediatype The media channel. (required) @param readyForMediaData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Set", "the", "agent", "state", "to", "Ready", "Set", "the", "current", "agent&#39", ";", "s", "state", "to", "Ready", "on", "the", "specified", "media", "channel", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L3501-L3504
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/ngmf/ui/calc/RandomNormal.java
RandomNormal.nextRatio
public float nextRatio() { """ Compute the next random value using the ratio algorithm. Requires two uniformly-distributed random values in [0, 1). """ float u, v, x, xx; do { // u and v are two uniformly-distributed random values // in [0, 1), and u != 0. while ((u = gen.nextFloat()) == 0); // try again if 0 v = gen.nextFloat(); float y = C1*(v - 0.5f); // y coord of point (u, y) x = y/u; // ratio of point's coords xx = x*x; } while ( (xx > 5f - C2*u) // quick acceptance && ( (xx >= C3/u + 1.4f) || // quick rejection (xx > (float) (-4*Math.log(u))) ) // final test ); return stddev*x + mean; }
java
public float nextRatio() { float u, v, x, xx; do { // u and v are two uniformly-distributed random values // in [0, 1), and u != 0. while ((u = gen.nextFloat()) == 0); // try again if 0 v = gen.nextFloat(); float y = C1*(v - 0.5f); // y coord of point (u, y) x = y/u; // ratio of point's coords xx = x*x; } while ( (xx > 5f - C2*u) // quick acceptance && ( (xx >= C3/u + 1.4f) || // quick rejection (xx > (float) (-4*Math.log(u))) ) // final test ); return stddev*x + mean; }
[ "public", "float", "nextRatio", "(", ")", "{", "float", "u", ",", "v", ",", "x", ",", "xx", ";", "do", "{", "// u and v are two uniformly-distributed random values", "// in [0, 1), and u != 0.", "while", "(", "(", "u", "=", "gen", ".", "nextFloat", "(", ")", ")", "==", "0", ")", ";", "// try again if 0", "v", "=", "gen", ".", "nextFloat", "(", ")", ";", "float", "y", "=", "C1", "*", "(", "v", "-", "0.5f", ")", ";", "// y coord of point (u, y)", "x", "=", "y", "/", "u", ";", "// ratio of point's coords", "xx", "=", "x", "*", "x", ";", "}", "while", "(", "(", "xx", ">", "5f", "-", "C2", "*", "u", ")", "// quick acceptance", "&&", "(", "(", "xx", ">=", "C3", "/", "u", "+", "1.4f", ")", "||", "// quick rejection", "(", "xx", ">", "(", "float", ")", "(", "-", "4", "*", "Math", ".", "log", "(", "u", ")", ")", ")", ")", "// final test", ")", ";", "return", "stddev", "*", "x", "+", "mean", ";", "}" ]
Compute the next random value using the ratio algorithm. Requires two uniformly-distributed random values in [0, 1).
[ "Compute", "the", "next", "random", "value", "using", "the", "ratio", "algorithm", ".", "Requires", "two", "uniformly", "-", "distributed", "random", "values", "in", "[", "0", "1", ")", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/ui/calc/RandomNormal.java#L108-L127
icode/ameba
src/main/java/ameba/lib/Strands.java
Strands.parkNanos
public static void parkNanos(Object blocker, long nanos) { """ Disables the current strand for thread scheduling purposes, for up to the specified waiting time, unless the permit is available. <p> <p> If the permit is available then it is consumed and the call returns immediately; otherwise the current strand becomes disabled for scheduling purposes and lies dormant until one of four things happens: <p> <ul> <li>Some other strand invokes {@link #unpark unpark} with the current strand as the target; or <p> <li>Some other strand interrupts the current strand; or <p> <li>The specified waiting time elapses; or <p> <li>The call spuriously (that is, for no reason) returns. </ul> <p> <p> This method does <em>not</em> report which of these caused the method to return. Callers should re-check the conditions which caused the strand to park in the first place. Callers may also determine, for example, the interrupt status of the strand, or the elapsed time upon return. @param blocker the synchronization object responsible for this strand parking @param nanos the maximum number of nanoseconds to wait """ try { Strand.parkNanos(blocker, nanos); } catch (SuspendExecution e) { throw RuntimeSuspendExecution.of(e); } }
java
public static void parkNanos(Object blocker, long nanos) { try { Strand.parkNanos(blocker, nanos); } catch (SuspendExecution e) { throw RuntimeSuspendExecution.of(e); } }
[ "public", "static", "void", "parkNanos", "(", "Object", "blocker", ",", "long", "nanos", ")", "{", "try", "{", "Strand", ".", "parkNanos", "(", "blocker", ",", "nanos", ")", ";", "}", "catch", "(", "SuspendExecution", "e", ")", "{", "throw", "RuntimeSuspendExecution", ".", "of", "(", "e", ")", ";", "}", "}" ]
Disables the current strand for thread scheduling purposes, for up to the specified waiting time, unless the permit is available. <p> <p> If the permit is available then it is consumed and the call returns immediately; otherwise the current strand becomes disabled for scheduling purposes and lies dormant until one of four things happens: <p> <ul> <li>Some other strand invokes {@link #unpark unpark} with the current strand as the target; or <p> <li>Some other strand interrupts the current strand; or <p> <li>The specified waiting time elapses; or <p> <li>The call spuriously (that is, for no reason) returns. </ul> <p> <p> This method does <em>not</em> report which of these caused the method to return. Callers should re-check the conditions which caused the strand to park in the first place. Callers may also determine, for example, the interrupt status of the strand, or the elapsed time upon return. @param blocker the synchronization object responsible for this strand parking @param nanos the maximum number of nanoseconds to wait
[ "Disables", "the", "current", "strand", "for", "thread", "scheduling", "purposes", "for", "up", "to", "the", "specified", "waiting", "time", "unless", "the", "permit", "is", "available", ".", "<p", ">", "<p", ">", "If", "the", "permit", "is", "available", "then", "it", "is", "consumed", "and", "the", "call", "returns", "immediately", ";", "otherwise", "the", "current", "strand", "becomes", "disabled", "for", "scheduling", "purposes", "and", "lies", "dormant", "until", "one", "of", "four", "things", "happens", ":", "<p", ">", "<ul", ">", "<li", ">", "Some", "other", "strand", "invokes", "{", "@link", "#unpark", "unpark", "}", "with", "the", "current", "strand", "as", "the", "target", ";", "or", "<p", ">", "<li", ">", "Some", "other", "strand", "interrupts", "the", "current", "strand", ";", "or", "<p", ">", "<li", ">", "The", "specified", "waiting", "time", "elapses", ";", "or", "<p", ">", "<li", ">", "The", "call", "spuriously", "(", "that", "is", "for", "no", "reason", ")", "returns", ".", "<", "/", "ul", ">", "<p", ">", "<p", ">", "This", "method", "does", "<em", ">", "not<", "/", "em", ">", "report", "which", "of", "these", "caused", "the", "method", "to", "return", ".", "Callers", "should", "re", "-", "check", "the", "conditions", "which", "caused", "the", "strand", "to", "park", "in", "the", "first", "place", ".", "Callers", "may", "also", "determine", "for", "example", "the", "interrupt", "status", "of", "the", "strand", "or", "the", "elapsed", "time", "upon", "return", "." ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/lib/Strands.java#L368-L374
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) { """ 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 """ 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", "(", "deviceName", ",", "resourceGroupName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "BandwidthScheduleInner", ">", ">", ",", "Page", "<", "BandwidthScheduleInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "BandwidthScheduleInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "BandwidthScheduleInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
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
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/AsynchronousBufferFileWriter.java
AsynchronousBufferFileWriter.writeBlock
@Override public void writeBlock(Buffer buffer) throws IOException { """ Writes the given block asynchronously. @param buffer the buffer to be written (will be recycled when done) @throws IOException thrown if adding the write operation fails """ try { // if successfully added, the buffer will be recycled after the write operation addRequest(new BufferWriteRequest(this, buffer)); } catch (Throwable e) { // if not added, we need to recycle here buffer.recycleBuffer(); ExceptionUtils.rethrowIOException(e); } }
java
@Override public void writeBlock(Buffer buffer) throws IOException { try { // if successfully added, the buffer will be recycled after the write operation addRequest(new BufferWriteRequest(this, buffer)); } catch (Throwable e) { // if not added, we need to recycle here buffer.recycleBuffer(); ExceptionUtils.rethrowIOException(e); } }
[ "@", "Override", "public", "void", "writeBlock", "(", "Buffer", "buffer", ")", "throws", "IOException", "{", "try", "{", "// if successfully added, the buffer will be recycled after the write operation", "addRequest", "(", "new", "BufferWriteRequest", "(", "this", ",", "buffer", ")", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "// if not added, we need to recycle here", "buffer", ".", "recycleBuffer", "(", ")", ";", "ExceptionUtils", ".", "rethrowIOException", "(", "e", ")", ";", "}", "}" ]
Writes the given block asynchronously. @param buffer the buffer to be written (will be recycled when done) @throws IOException thrown if adding the write operation fails
[ "Writes", "the", "given", "block", "asynchronously", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/AsynchronousBufferFileWriter.java#L44-L55
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/AbstractN1qlQuery.java
AbstractN1qlQuery.populateParameters
public static void populateParameters(JsonObject query, JsonValue params) { """ Populate a {@link JsonObject} representation of a query with parameters, either positional or named. - If params is a {@link JsonObject}, named parameters will be used (prefixing the names with '$' if not present). - If params is a {@link JsonArray}, positional parameters will be used. - If params is null or an empty json, no parameters are populated in the query object. Note that the {@link JsonValue} should not be mutated until {@link #n1ql()} is called since it backs the creation of the query string. Also, the {@link Statement} is expected to contain the correct placeholders (corresponding names and number). @param query the query JsonObject to populated with parameters. @param params the parameters. """ if (params instanceof JsonArray && !((JsonArray) params).isEmpty()) { query.put("args", (JsonArray) params); } else if (params instanceof JsonObject && !((JsonObject) params).isEmpty()) { JsonObject namedParams = (JsonObject) params; for (String key : namedParams.getNames()) { Object value = namedParams.get(key); if (key.charAt(0) != '$') { query.put('$' + key, value); } else { query.put(key, value); } } } //else do nothing, as if a simple statement }
java
public static void populateParameters(JsonObject query, JsonValue params) { if (params instanceof JsonArray && !((JsonArray) params).isEmpty()) { query.put("args", (JsonArray) params); } else if (params instanceof JsonObject && !((JsonObject) params).isEmpty()) { JsonObject namedParams = (JsonObject) params; for (String key : namedParams.getNames()) { Object value = namedParams.get(key); if (key.charAt(0) != '$') { query.put('$' + key, value); } else { query.put(key, value); } } } //else do nothing, as if a simple statement }
[ "public", "static", "void", "populateParameters", "(", "JsonObject", "query", ",", "JsonValue", "params", ")", "{", "if", "(", "params", "instanceof", "JsonArray", "&&", "!", "(", "(", "JsonArray", ")", "params", ")", ".", "isEmpty", "(", ")", ")", "{", "query", ".", "put", "(", "\"args\"", ",", "(", "JsonArray", ")", "params", ")", ";", "}", "else", "if", "(", "params", "instanceof", "JsonObject", "&&", "!", "(", "(", "JsonObject", ")", "params", ")", ".", "isEmpty", "(", ")", ")", "{", "JsonObject", "namedParams", "=", "(", "JsonObject", ")", "params", ";", "for", "(", "String", "key", ":", "namedParams", ".", "getNames", "(", ")", ")", "{", "Object", "value", "=", "namedParams", ".", "get", "(", "key", ")", ";", "if", "(", "key", ".", "charAt", "(", "0", ")", "!=", "'", "'", ")", "{", "query", ".", "put", "(", "'", "'", "+", "key", ",", "value", ")", ";", "}", "else", "{", "query", ".", "put", "(", "key", ",", "value", ")", ";", "}", "}", "}", "//else do nothing, as if a simple statement", "}" ]
Populate a {@link JsonObject} representation of a query with parameters, either positional or named. - If params is a {@link JsonObject}, named parameters will be used (prefixing the names with '$' if not present). - If params is a {@link JsonArray}, positional parameters will be used. - If params is null or an empty json, no parameters are populated in the query object. Note that the {@link JsonValue} should not be mutated until {@link #n1ql()} is called since it backs the creation of the query string. Also, the {@link Statement} is expected to contain the correct placeholders (corresponding names and number). @param query the query JsonObject to populated with parameters. @param params the parameters.
[ "Populate", "a", "{", "@link", "JsonObject", "}", "representation", "of", "a", "query", "with", "parameters", "either", "positional", "or", "named", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/AbstractN1qlQuery.java#L82-L96
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/mapping/MappedClass.java
MappedClass.addAnnotation
public void addAnnotation(final Class<? extends Annotation> clazz, final Annotation ann) { """ Adds the given Annotation to the internal list for the given Class. @param clazz the type to add @param ann the annotation to add """ if (ann == null || clazz == null) { return; } if (!foundAnnotations.containsKey(clazz)) { foundAnnotations.put(clazz, new ArrayList<Annotation>()); } foundAnnotations.get(clazz).add(ann); }
java
public void addAnnotation(final Class<? extends Annotation> clazz, final Annotation ann) { if (ann == null || clazz == null) { return; } if (!foundAnnotations.containsKey(clazz)) { foundAnnotations.put(clazz, new ArrayList<Annotation>()); } foundAnnotations.get(clazz).add(ann); }
[ "public", "void", "addAnnotation", "(", "final", "Class", "<", "?", "extends", "Annotation", ">", "clazz", ",", "final", "Annotation", "ann", ")", "{", "if", "(", "ann", "==", "null", "||", "clazz", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "foundAnnotations", ".", "containsKey", "(", "clazz", ")", ")", "{", "foundAnnotations", ".", "put", "(", "clazz", ",", "new", "ArrayList", "<", "Annotation", ">", "(", ")", ")", ";", "}", "foundAnnotations", ".", "get", "(", "clazz", ")", ".", "add", "(", "ann", ")", ";", "}" ]
Adds the given Annotation to the internal list for the given Class. @param clazz the type to add @param ann the annotation to add
[ "Adds", "the", "given", "Annotation", "to", "the", "internal", "list", "for", "the", "given", "Class", "." ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/mapping/MappedClass.java#L222-L232
martinpaljak/apdu4j
src/main/java/apdu4j/remote/RemoteTerminal.java
RemoteTerminal.decrypt
public Button decrypt(String message, byte[] apdu) throws IOException, UserCancelExcption { """ Shows the response of the APDU to the user. Normally this requires the verification of a PIN code beforehand. @param message text to display to the user @param apdu APDU to send to the terminal @return {@link Button} that was pressed by the user @throws IOException when communication fails """ Map<String, Object> m = JSONProtocol.cmd("decrypt"); m.put("text", message); m.put("bytes", HexUtils.bin2hex(apdu)); pipe.send(m); Map<String, Object> r = pipe.recv(); if (JSONProtocol.check(m, r)) { return Button.valueOf(((String)r.get("button")).toUpperCase()); } else { throw new IOException("Unknown button pressed"); } }
java
public Button decrypt(String message, byte[] apdu) throws IOException, UserCancelExcption{ Map<String, Object> m = JSONProtocol.cmd("decrypt"); m.put("text", message); m.put("bytes", HexUtils.bin2hex(apdu)); pipe.send(m); Map<String, Object> r = pipe.recv(); if (JSONProtocol.check(m, r)) { return Button.valueOf(((String)r.get("button")).toUpperCase()); } else { throw new IOException("Unknown button pressed"); } }
[ "public", "Button", "decrypt", "(", "String", "message", ",", "byte", "[", "]", "apdu", ")", "throws", "IOException", ",", "UserCancelExcption", "{", "Map", "<", "String", ",", "Object", ">", "m", "=", "JSONProtocol", ".", "cmd", "(", "\"decrypt\"", ")", ";", "m", ".", "put", "(", "\"text\"", ",", "message", ")", ";", "m", ".", "put", "(", "\"bytes\"", ",", "HexUtils", ".", "bin2hex", "(", "apdu", ")", ")", ";", "pipe", ".", "send", "(", "m", ")", ";", "Map", "<", "String", ",", "Object", ">", "r", "=", "pipe", ".", "recv", "(", ")", ";", "if", "(", "JSONProtocol", ".", "check", "(", "m", ",", "r", ")", ")", "{", "return", "Button", ".", "valueOf", "(", "(", "(", "String", ")", "r", ".", "get", "(", "\"button\"", ")", ")", ".", "toUpperCase", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "IOException", "(", "\"Unknown button pressed\"", ")", ";", "}", "}" ]
Shows the response of the APDU to the user. Normally this requires the verification of a PIN code beforehand. @param message text to display to the user @param apdu APDU to send to the terminal @return {@link Button} that was pressed by the user @throws IOException when communication fails
[ "Shows", "the", "response", "of", "the", "APDU", "to", "the", "user", "." ]
train
https://github.com/martinpaljak/apdu4j/blob/dca977bfa9e4fa236a9a7b87a2a09e5472ea9969/src/main/java/apdu4j/remote/RemoteTerminal.java#L154-L165
primefaces/primefaces
src/main/java/org/primefaces/component/imagecropper/ImageCropperRenderer.java
ImageCropperRenderer.guessImageFormat
private String guessImageFormat(String contentType, String imagePath) throws IOException { """ Attempt to obtain the image format used to write the image from the contentType or the image's file extension. """ String format = "png"; if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(imagePath); } if (contentType != null) { format = contentType.replaceFirst("^image/([^;]+)[;]?.*$", "$1"); } else { int queryStringIndex = imagePath.indexOf('?'); if (queryStringIndex != -1) { imagePath = imagePath.substring(0, queryStringIndex); } String[] pathTokens = imagePath.split("\\."); if (pathTokens.length > 1) { format = pathTokens[pathTokens.length - 1]; } } return format; }
java
private String guessImageFormat(String contentType, String imagePath) throws IOException { String format = "png"; if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(imagePath); } if (contentType != null) { format = contentType.replaceFirst("^image/([^;]+)[;]?.*$", "$1"); } else { int queryStringIndex = imagePath.indexOf('?'); if (queryStringIndex != -1) { imagePath = imagePath.substring(0, queryStringIndex); } String[] pathTokens = imagePath.split("\\."); if (pathTokens.length > 1) { format = pathTokens[pathTokens.length - 1]; } } return format; }
[ "private", "String", "guessImageFormat", "(", "String", "contentType", ",", "String", "imagePath", ")", "throws", "IOException", "{", "String", "format", "=", "\"png\"", ";", "if", "(", "contentType", "==", "null", ")", "{", "contentType", "=", "URLConnection", ".", "guessContentTypeFromName", "(", "imagePath", ")", ";", "}", "if", "(", "contentType", "!=", "null", ")", "{", "format", "=", "contentType", ".", "replaceFirst", "(", "\"^image/([^;]+)[;]?.*$\"", ",", "\"$1\"", ")", ";", "}", "else", "{", "int", "queryStringIndex", "=", "imagePath", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "queryStringIndex", "!=", "-", "1", ")", "{", "imagePath", "=", "imagePath", ".", "substring", "(", "0", ",", "queryStringIndex", ")", ";", "}", "String", "[", "]", "pathTokens", "=", "imagePath", ".", "split", "(", "\"\\\\.\"", ")", ";", "if", "(", "pathTokens", ".", "length", ">", "1", ")", "{", "format", "=", "pathTokens", "[", "pathTokens", ".", "length", "-", "1", "]", ";", "}", "}", "return", "format", ";", "}" ]
Attempt to obtain the image format used to write the image from the contentType or the image's file extension.
[ "Attempt", "to", "obtain", "the", "image", "format", "used", "to", "write", "the", "image", "from", "the", "contentType", "or", "the", "image", "s", "file", "extension", "." ]
train
https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/component/imagecropper/ImageCropperRenderer.java#L281-L307
alkacon/opencms-core
src/org/opencms/file/wrapper/CmsResourceWrapperXmlPage.java
CmsResourceWrapperXmlPage.getUriStyleSheet
protected String getUriStyleSheet(CmsObject cms, CmsResource res) { """ Returns the OpenCms VFS uri of the style sheet of the resource.<p> @param cms the initialized CmsObject @param res the resource where to read the style sheet for @return the OpenCms VFS uri of the style sheet of resource """ String result = ""; try { String currentTemplate = getUriTemplate(cms, res); if (!"".equals(currentTemplate)) { // read the stylesheet from the template file result = cms.readPropertyObject( currentTemplate, CmsPropertyDefinition.PROPERTY_TEMPLATE, false).getValue(""); } } catch (CmsException e) { // noop } return result; }
java
protected String getUriStyleSheet(CmsObject cms, CmsResource res) { String result = ""; try { String currentTemplate = getUriTemplate(cms, res); if (!"".equals(currentTemplate)) { // read the stylesheet from the template file result = cms.readPropertyObject( currentTemplate, CmsPropertyDefinition.PROPERTY_TEMPLATE, false).getValue(""); } } catch (CmsException e) { // noop } return result; }
[ "protected", "String", "getUriStyleSheet", "(", "CmsObject", "cms", ",", "CmsResource", "res", ")", "{", "String", "result", "=", "\"\"", ";", "try", "{", "String", "currentTemplate", "=", "getUriTemplate", "(", "cms", ",", "res", ")", ";", "if", "(", "!", "\"\"", ".", "equals", "(", "currentTemplate", ")", ")", "{", "// read the stylesheet from the template file", "result", "=", "cms", ".", "readPropertyObject", "(", "currentTemplate", ",", "CmsPropertyDefinition", ".", "PROPERTY_TEMPLATE", ",", "false", ")", ".", "getValue", "(", "\"\"", ")", ";", "}", "}", "catch", "(", "CmsException", "e", ")", "{", "// noop", "}", "return", "result", ";", "}" ]
Returns the OpenCms VFS uri of the style sheet of the resource.<p> @param cms the initialized CmsObject @param res the resource where to read the style sheet for @return the OpenCms VFS uri of the style sheet of resource
[ "Returns", "the", "OpenCms", "VFS", "uri", "of", "the", "style", "sheet", "of", "the", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/wrapper/CmsResourceWrapperXmlPage.java#L839-L855
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/SynchronizedUniqueIDGeneratorFactory.java
SynchronizedUniqueIDGeneratorFactory.generatorFor
public static synchronized IDGenerator generatorFor(ZooKeeperConnection zooKeeperConnection, String znode, Mode mode) throws IOException { """ Get the synchronized ID generator instance. @param zooKeeperConnection Connection to the ZooKeeper quorum. @param znode Base-path of the resource pool in ZooKeeper. @param mode Generator mode. @return An instance of this class. @throws IOException Thrown when something went wrong trying to find the cluster ID or trying to claim a generator ID. """ if (!instances.containsKey(znode)) { final int clusterId = ClusterID.get(zooKeeperConnection.getActiveConnection(), znode); SynchronizedGeneratorIdentity generatorIdentityHolder = new SynchronizedGeneratorIdentity(zooKeeperConnection, znode, clusterId, null); return generatorFor(generatorIdentityHolder, mode); } return instances.get(znode); }
java
public static synchronized IDGenerator generatorFor(ZooKeeperConnection zooKeeperConnection, String znode, Mode mode) throws IOException { if (!instances.containsKey(znode)) { final int clusterId = ClusterID.get(zooKeeperConnection.getActiveConnection(), znode); SynchronizedGeneratorIdentity generatorIdentityHolder = new SynchronizedGeneratorIdentity(zooKeeperConnection, znode, clusterId, null); return generatorFor(generatorIdentityHolder, mode); } return instances.get(znode); }
[ "public", "static", "synchronized", "IDGenerator", "generatorFor", "(", "ZooKeeperConnection", "zooKeeperConnection", ",", "String", "znode", ",", "Mode", "mode", ")", "throws", "IOException", "{", "if", "(", "!", "instances", ".", "containsKey", "(", "znode", ")", ")", "{", "final", "int", "clusterId", "=", "ClusterID", ".", "get", "(", "zooKeeperConnection", ".", "getActiveConnection", "(", ")", ",", "znode", ")", ";", "SynchronizedGeneratorIdentity", "generatorIdentityHolder", "=", "new", "SynchronizedGeneratorIdentity", "(", "zooKeeperConnection", ",", "znode", ",", "clusterId", ",", "null", ")", ";", "return", "generatorFor", "(", "generatorIdentityHolder", ",", "mode", ")", ";", "}", "return", "instances", ".", "get", "(", "znode", ")", ";", "}" ]
Get the synchronized ID generator instance. @param zooKeeperConnection Connection to the ZooKeeper quorum. @param znode Base-path of the resource pool in ZooKeeper. @param mode Generator mode. @return An instance of this class. @throws IOException Thrown when something went wrong trying to find the cluster ID or trying to claim a generator ID.
[ "Get", "the", "synchronized", "ID", "generator", "instance", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/SynchronizedUniqueIDGeneratorFactory.java#L53-L66
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreBuilderUtils.java
HadoopStoreBuilderUtils.getDataFileChunkSet
public static DataFileChunkSet getDataFileChunkSet(FileSystem fs, FileStatus[] files) throws IOException { """ Convert list of FileStatus[] files to DataFileChunkSet. The input to this is generally the output of getChunkFiles function. Works only for {@link ReadOnlyStorageFormat.READONLY_V2} @param fs Filesystem used @param files List of data chunk files @return DataFileChunkSet Returns the corresponding data chunk set @throws IOException """ // Make sure it satisfies the partitionId_replicaType format List<FileStatus> fileList = Lists.newArrayList(); for(FileStatus file: files) { if(!ReadOnlyUtils.isFormatCorrect(file.getPath().getName(), ReadOnlyStorageFormat.READONLY_V2)) { throw new VoldemortException("Incorrect data file name format for " + file.getPath().getName() + ". Unsupported by " + ReadOnlyStorageFormat.READONLY_V2); } fileList.add(file); } // Return it in sorted order Collections.sort(fileList, new Comparator<FileStatus>() { public int compare(FileStatus f1, FileStatus f2) { int chunkId1 = ReadOnlyUtils.getChunkId(f1.getPath().getName()); int chunkId2 = ReadOnlyUtils.getChunkId(f2.getPath().getName()); return chunkId1 - chunkId2; } }); List<DataFileChunk> dataFiles = Lists.newArrayList(); List<Integer> dataFileSizes = Lists.newArrayList(); for(FileStatus file: fileList) { dataFiles.add(new HdfsDataFileChunk(fs, file)); dataFileSizes.add((int) file.getLen()); } return new DataFileChunkSet(dataFiles, dataFileSizes); }
java
public static DataFileChunkSet getDataFileChunkSet(FileSystem fs, FileStatus[] files) throws IOException { // Make sure it satisfies the partitionId_replicaType format List<FileStatus> fileList = Lists.newArrayList(); for(FileStatus file: files) { if(!ReadOnlyUtils.isFormatCorrect(file.getPath().getName(), ReadOnlyStorageFormat.READONLY_V2)) { throw new VoldemortException("Incorrect data file name format for " + file.getPath().getName() + ". Unsupported by " + ReadOnlyStorageFormat.READONLY_V2); } fileList.add(file); } // Return it in sorted order Collections.sort(fileList, new Comparator<FileStatus>() { public int compare(FileStatus f1, FileStatus f2) { int chunkId1 = ReadOnlyUtils.getChunkId(f1.getPath().getName()); int chunkId2 = ReadOnlyUtils.getChunkId(f2.getPath().getName()); return chunkId1 - chunkId2; } }); List<DataFileChunk> dataFiles = Lists.newArrayList(); List<Integer> dataFileSizes = Lists.newArrayList(); for(FileStatus file: fileList) { dataFiles.add(new HdfsDataFileChunk(fs, file)); dataFileSizes.add((int) file.getLen()); } return new DataFileChunkSet(dataFiles, dataFileSizes); }
[ "public", "static", "DataFileChunkSet", "getDataFileChunkSet", "(", "FileSystem", "fs", ",", "FileStatus", "[", "]", "files", ")", "throws", "IOException", "{", "// Make sure it satisfies the partitionId_replicaType format", "List", "<", "FileStatus", ">", "fileList", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "FileStatus", "file", ":", "files", ")", "{", "if", "(", "!", "ReadOnlyUtils", ".", "isFormatCorrect", "(", "file", ".", "getPath", "(", ")", ".", "getName", "(", ")", ",", "ReadOnlyStorageFormat", ".", "READONLY_V2", ")", ")", "{", "throw", "new", "VoldemortException", "(", "\"Incorrect data file name format for \"", "+", "file", ".", "getPath", "(", ")", ".", "getName", "(", ")", "+", "\". Unsupported by \"", "+", "ReadOnlyStorageFormat", ".", "READONLY_V2", ")", ";", "}", "fileList", ".", "add", "(", "file", ")", ";", "}", "// Return it in sorted order", "Collections", ".", "sort", "(", "fileList", ",", "new", "Comparator", "<", "FileStatus", ">", "(", ")", "{", "public", "int", "compare", "(", "FileStatus", "f1", ",", "FileStatus", "f2", ")", "{", "int", "chunkId1", "=", "ReadOnlyUtils", ".", "getChunkId", "(", "f1", ".", "getPath", "(", ")", ".", "getName", "(", ")", ")", ";", "int", "chunkId2", "=", "ReadOnlyUtils", ".", "getChunkId", "(", "f2", ".", "getPath", "(", ")", ".", "getName", "(", ")", ")", ";", "return", "chunkId1", "-", "chunkId2", ";", "}", "}", ")", ";", "List", "<", "DataFileChunk", ">", "dataFiles", "=", "Lists", ".", "newArrayList", "(", ")", ";", "List", "<", "Integer", ">", "dataFileSizes", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "FileStatus", "file", ":", "fileList", ")", "{", "dataFiles", ".", "add", "(", "new", "HdfsDataFileChunk", "(", "fs", ",", "file", ")", ")", ";", "dataFileSizes", ".", "add", "(", "(", "int", ")", "file", ".", "getLen", "(", ")", ")", ";", "}", "return", "new", "DataFileChunkSet", "(", "dataFiles", ",", "dataFileSizes", ")", ";", "}" ]
Convert list of FileStatus[] files to DataFileChunkSet. The input to this is generally the output of getChunkFiles function. Works only for {@link ReadOnlyStorageFormat.READONLY_V2} @param fs Filesystem used @param files List of data chunk files @return DataFileChunkSet Returns the corresponding data chunk set @throws IOException
[ "Convert", "list", "of", "FileStatus", "[]", "files", "to", "DataFileChunkSet", ".", "The", "input", "to", "this", "is", "generally", "the", "output", "of", "getChunkFiles", "function", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/HadoopStoreBuilderUtils.java#L149-L182
molgenis/molgenis
molgenis-data-import/src/main/java/org/molgenis/data/importer/emx/EmxMetadataParser.java
EmxMetadataParser.getPackage
Package getPackage(IntermediateParseResults intermediateResults, String packageId) { """ Retrieves a {@link Package} by name from parsed data or existing data. @param intermediateResults parsed data @param packageId package name @return package or <code>null</code> if no package with the given name exists in parsed or existing data """ Package aPackage = intermediateResults.getPackage(packageId); if (aPackage == null) { aPackage = dataService.findOneById(PackageMetadata.PACKAGE, packageId, Package.class); } return aPackage; }
java
Package getPackage(IntermediateParseResults intermediateResults, String packageId) { Package aPackage = intermediateResults.getPackage(packageId); if (aPackage == null) { aPackage = dataService.findOneById(PackageMetadata.PACKAGE, packageId, Package.class); } return aPackage; }
[ "Package", "getPackage", "(", "IntermediateParseResults", "intermediateResults", ",", "String", "packageId", ")", "{", "Package", "aPackage", "=", "intermediateResults", ".", "getPackage", "(", "packageId", ")", ";", "if", "(", "aPackage", "==", "null", ")", "{", "aPackage", "=", "dataService", ".", "findOneById", "(", "PackageMetadata", ".", "PACKAGE", ",", "packageId", ",", "Package", ".", "class", ")", ";", "}", "return", "aPackage", ";", "}" ]
Retrieves a {@link Package} by name from parsed data or existing data. @param intermediateResults parsed data @param packageId package name @return package or <code>null</code> if no package with the given name exists in parsed or existing data
[ "Retrieves", "a", "{", "@link", "Package", "}", "by", "name", "from", "parsed", "data", "or", "existing", "data", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-import/src/main/java/org/molgenis/data/importer/emx/EmxMetadataParser.java#L1246-L1252
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) { """ 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 """ 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", "(", "'", "'", ")", ";", "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", ",", "'", "'", ")", ";", "}", "strBuffer", ".", "append", "(", "floatString", ")", ";", "return", "strBuffer", ".", "toString", "(", ")", ";", "}" ]
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
JOML-CI/JOML
src/org/joml/Matrix4x3d.java
Matrix4x3d.obliqueZ
public Matrix4x3d obliqueZ(double a, double b, Matrix4x3d dest) { """ Apply an oblique projection transformation to this matrix with the given values for <code>a</code> and <code>b</code> and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>O</code> the oblique transformation matrix, then the new matrix will be <code>M * O</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the oblique transformation will be applied first! <p> The oblique transformation is defined as: <pre> x' = x + a*z y' = y + a*z z' = z </pre> or in matrix form: <pre> 1 0 a 0 0 1 b 0 0 0 1 0 </pre> @param a the value for the z factor that applies to x @param b the value for the z factor that applies to y @param dest will hold the result @return dest """ dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m20 = m00 * a + m10 * b + m20; dest.m21 = m01 * a + m11 * b + m21; dest.m22 = m02 * a + m12 * b + m22; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.properties = 0; return dest; }
java
public Matrix4x3d obliqueZ(double a, double b, Matrix4x3d dest) { dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m10 = m10; dest.m11 = m11; dest.m12 = m12; dest.m20 = m00 * a + m10 * b + m20; dest.m21 = m01 * a + m11 * b + m21; dest.m22 = m02 * a + m12 * b + m22; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.properties = 0; return dest; }
[ "public", "Matrix4x3d", "obliqueZ", "(", "double", "a", ",", "double", "b", ",", "Matrix4x3d", "dest", ")", "{", "dest", ".", "m00", "=", "m00", ";", "dest", ".", "m01", "=", "m01", ";", "dest", ".", "m02", "=", "m02", ";", "dest", ".", "m10", "=", "m10", ";", "dest", ".", "m11", "=", "m11", ";", "dest", ".", "m12", "=", "m12", ";", "dest", ".", "m20", "=", "m00", "*", "a", "+", "m10", "*", "b", "+", "m20", ";", "dest", ".", "m21", "=", "m01", "*", "a", "+", "m11", "*", "b", "+", "m21", ";", "dest", ".", "m22", "=", "m02", "*", "a", "+", "m12", "*", "b", "+", "m22", ";", "dest", ".", "m30", "=", "m30", ";", "dest", ".", "m31", "=", "m31", ";", "dest", ".", "m32", "=", "m32", ";", "dest", ".", "properties", "=", "0", ";", "return", "dest", ";", "}" ]
Apply an oblique projection transformation to this matrix with the given values for <code>a</code> and <code>b</code> and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>O</code> the oblique transformation matrix, then the new matrix will be <code>M * O</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the oblique transformation will be applied first! <p> The oblique transformation is defined as: <pre> x' = x + a*z y' = y + a*z z' = z </pre> or in matrix form: <pre> 1 0 a 0 0 1 b 0 0 0 1 0 </pre> @param a the value for the z factor that applies to x @param b the value for the z factor that applies to y @param dest will hold the result @return dest
[ "Apply", "an", "oblique", "projection", "transformation", "to", "this", "matrix", "with", "the", "given", "values", "for", "<code", ">", "a<", "/", "code", ">", "and", "<code", ">", "b<", "/", "code", ">", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", "code", ">", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "O<", "/", "code", ">", "the", "oblique", "transformation", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "O<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "O", "*", "v<", "/", "code", ">", "the", "oblique", "transformation", "will", "be", "applied", "first!", "<p", ">", "The", "oblique", "transformation", "is", "defined", "as", ":", "<pre", ">", "x", "=", "x", "+", "a", "*", "z", "y", "=", "y", "+", "a", "*", "z", "z", "=", "z", "<", "/", "pre", ">", "or", "in", "matrix", "form", ":", "<pre", ">", "1", "0", "a", "0", "0", "1", "b", "0", "0", "0", "1", "0", "<", "/", "pre", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L9961-L9976
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlGeneratorDefaultImpl.java
SqlGeneratorDefaultImpl.toSQLClause
private String toSQLClause(FieldCriteria c, ClassDescriptor cld) { """ Answer the SQL-Clause for a FieldCriteria @param c FieldCriteria @param cld ClassDescriptor """ String colName = toSqlClause(c.getAttribute(), cld); return colName + c.getClause() + c.getValue(); }
java
private String toSQLClause(FieldCriteria c, ClassDescriptor cld) { String colName = toSqlClause(c.getAttribute(), cld); return colName + c.getClause() + c.getValue(); }
[ "private", "String", "toSQLClause", "(", "FieldCriteria", "c", ",", "ClassDescriptor", "cld", ")", "{", "String", "colName", "=", "toSqlClause", "(", "c", ".", "getAttribute", "(", ")", ",", "cld", ")", ";", "return", "colName", "+", "c", ".", "getClause", "(", ")", "+", "c", ".", "getValue", "(", ")", ";", "}" ]
Answer the SQL-Clause for a FieldCriteria @param c FieldCriteria @param cld ClassDescriptor
[ "Answer", "the", "SQL", "-", "Clause", "for", "a", "FieldCriteria" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlGeneratorDefaultImpl.java#L457-L461
hellosign/hellosign-java-sdk
src/main/java/com/hellosign/sdk/HelloSignClient.java
HelloSignClient.addTemplateUser
public Template addTemplateUser(String templateId, String idOrEmail) throws HelloSignException { """ Adds the provided user to the template indicated by the provided template ID. The new user can be designated using their account ID or email address. @param templateId String template ID @param idOrEmail String account ID or email address @return Template @throws HelloSignException thrown if there's a problem processing the HTTP request or the JSON response. """ String url = BASE_URI + TEMPLATE_ADD_USER_URI + "/" + templateId; String key = (idOrEmail != null && idOrEmail.contains("@")) ? Account.ACCOUNT_EMAIL_ADDRESS : Account.ACCOUNT_ID; return new Template(httpClient.withAuth(auth).withPostField(key, idOrEmail).post(url).asJson()); }
java
public Template addTemplateUser(String templateId, String idOrEmail) throws HelloSignException { String url = BASE_URI + TEMPLATE_ADD_USER_URI + "/" + templateId; String key = (idOrEmail != null && idOrEmail.contains("@")) ? Account.ACCOUNT_EMAIL_ADDRESS : Account.ACCOUNT_ID; return new Template(httpClient.withAuth(auth).withPostField(key, idOrEmail).post(url).asJson()); }
[ "public", "Template", "addTemplateUser", "(", "String", "templateId", ",", "String", "idOrEmail", ")", "throws", "HelloSignException", "{", "String", "url", "=", "BASE_URI", "+", "TEMPLATE_ADD_USER_URI", "+", "\"/\"", "+", "templateId", ";", "String", "key", "=", "(", "idOrEmail", "!=", "null", "&&", "idOrEmail", ".", "contains", "(", "\"@\"", ")", ")", "?", "Account", ".", "ACCOUNT_EMAIL_ADDRESS", ":", "Account", ".", "ACCOUNT_ID", ";", "return", "new", "Template", "(", "httpClient", ".", "withAuth", "(", "auth", ")", ".", "withPostField", "(", "key", ",", "idOrEmail", ")", ".", "post", "(", "url", ")", ".", "asJson", "(", ")", ")", ";", "}" ]
Adds the provided user to the template indicated by the provided template ID. The new user can be designated using their account ID or email address. @param templateId String template ID @param idOrEmail String account ID or email address @return Template @throws HelloSignException thrown if there's a problem processing the HTTP request or the JSON response.
[ "Adds", "the", "provided", "user", "to", "the", "template", "indicated", "by", "the", "provided", "template", "ID", ".", "The", "new", "user", "can", "be", "designated", "using", "their", "account", "ID", "or", "email", "address", "." ]
train
https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/HelloSignClient.java#L621-L626
GenesysPureEngage/authentication-client-java
src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java
AuthenticationApi.signInAsync
public com.squareup.okhttp.Call signInAsync(String username, String password, Boolean saml, final ApiCallback<Void> callback) throws ApiException { """ Perform form-based authentication. (asynchronously) Perform form-based authentication by submitting an agent&#39;s username and password. @param username The agent&#39;s username, formatted as &#39;tenant\\username&#39;. (required) @param password The agent&#39;s password. (required) @param saml Specifies whether to login using [Security Assertion Markup Language](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) (SAML). (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object """ ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = signInValidateBeforeCall(username, password, saml, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; }
java
public com.squareup.okhttp.Call signInAsync(String username, String password, Boolean saml, final ApiCallback<Void> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = signInValidateBeforeCall(username, password, saml, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "signInAsync", "(", "String", "username", ",", "String", "password", ",", "Boolean", "saml", ",", "final", "ApiCallback", "<", "Void", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "signInValidateBeforeCall", "(", "username", ",", "password", ",", "saml", ",", "progressListener", ",", "progressRequestListener", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "callback", ")", ";", "return", "call", ";", "}" ]
Perform form-based authentication. (asynchronously) Perform form-based authentication by submitting an agent&#39;s username and password. @param username The agent&#39;s username, formatted as &#39;tenant\\username&#39;. (required) @param password The agent&#39;s password. (required) @param saml Specifies whether to login using [Security Assertion Markup Language](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) (SAML). (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Perform", "form", "-", "based", "authentication", ".", "(", "asynchronously", ")", "Perform", "form", "-", "based", "authentication", "by", "submitting", "an", "agent&#39", ";", "s", "username", "and", "password", "." ]
train
https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java#L1227-L1251
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/svm/PlattSMO.java
PlattSMO.updateSetsLabeled
private void updateSetsLabeled(int i1, final double a1, final double C) { """ Updates the index sets @param i1 the index to update for @param a1 the alphas value for the index @param C the regularization value to use for this datum """ final double y_i = label[i1]; I1[i1] = a1 == 0 && y_i == 1; I2[i1] = a1 == C && y_i == -1; I3[i1] = a1 == C && y_i == 1; I4[i1] = a1 == 0 && y_i == -1; }
java
private void updateSetsLabeled(int i1, final double a1, final double C) { final double y_i = label[i1]; I1[i1] = a1 == 0 && y_i == 1; I2[i1] = a1 == C && y_i == -1; I3[i1] = a1 == C && y_i == 1; I4[i1] = a1 == 0 && y_i == -1; }
[ "private", "void", "updateSetsLabeled", "(", "int", "i1", ",", "final", "double", "a1", ",", "final", "double", "C", ")", "{", "final", "double", "y_i", "=", "label", "[", "i1", "]", ";", "I1", "[", "i1", "]", "=", "a1", "==", "0", "&&", "y_i", "==", "1", ";", "I2", "[", "i1", "]", "=", "a1", "==", "C", "&&", "y_i", "==", "-", "1", ";", "I3", "[", "i1", "]", "=", "a1", "==", "C", "&&", "y_i", "==", "1", ";", "I4", "[", "i1", "]", "=", "a1", "==", "0", "&&", "y_i", "==", "-", "1", ";", "}" ]
Updates the index sets @param i1 the index to update for @param a1 the alphas value for the index @param C the regularization value to use for this datum
[ "Updates", "the", "index", "sets" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/svm/PlattSMO.java#L469-L476
duracloud/duracloud-db
account-management-db-repo/src/main/java/org/duracloud/account/db/repo/UserFinderUtil.java
UserFinderUtil.annotateAddressRange
private String annotateAddressRange(AccountInfo accountInfo, String baseRange) { """ For a user account with an IP limitation, this method is used to update the list of allowed IPs to include the IP of the DuraCloud instance itself. This is required to allow the calls made between applications (like those made from DurAdmin to DuraStore) to pass through the IP range check. @param baseRange set of IP ranges set by the user @return baseRange plus the instance elastic IP, or null if baseRange is null """ if (null == baseRange || baseRange.equals("")) { return baseRange; } else { return baseRange; // delimeter + elasticIp + "/32"; } }
java
private String annotateAddressRange(AccountInfo accountInfo, String baseRange) { if (null == baseRange || baseRange.equals("")) { return baseRange; } else { return baseRange; // delimeter + elasticIp + "/32"; } }
[ "private", "String", "annotateAddressRange", "(", "AccountInfo", "accountInfo", ",", "String", "baseRange", ")", "{", "if", "(", "null", "==", "baseRange", "||", "baseRange", ".", "equals", "(", "\"\"", ")", ")", "{", "return", "baseRange", ";", "}", "else", "{", "return", "baseRange", ";", "// delimeter + elasticIp + \"/32\";", "}", "}" ]
For a user account with an IP limitation, this method is used to update the list of allowed IPs to include the IP of the DuraCloud instance itself. This is required to allow the calls made between applications (like those made from DurAdmin to DuraStore) to pass through the IP range check. @param baseRange set of IP ranges set by the user @return baseRange plus the instance elastic IP, or null if baseRange is null
[ "For", "a", "user", "account", "with", "an", "IP", "limitation", "this", "method", "is", "used", "to", "update", "the", "list", "of", "allowed", "IPs", "to", "include", "the", "IP", "of", "the", "DuraCloud", "instance", "itself", ".", "This", "is", "required", "to", "allow", "the", "calls", "made", "between", "applications", "(", "like", "those", "made", "from", "DurAdmin", "to", "DuraStore", ")", "to", "pass", "through", "the", "IP", "range", "check", "." ]
train
https://github.com/duracloud/duracloud-db/blob/0328c322b2e4538ab6aa82cd16237be89cbe72fb/account-management-db-repo/src/main/java/org/duracloud/account/db/repo/UserFinderUtil.java#L126-L132
nmorel/gwt-jackson
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonDeserializationContext.java
JsonDeserializationContext.traceError
public JsonDeserializationException traceError( String message, JsonReader reader ) { """ Trace an error with current reader state and returns a corresponding exception. @param message error message @param reader current reader @return a {@link JsonDeserializationException} with the given message """ getLogger().log( Level.SEVERE, message ); traceReaderInfo( reader ); return new JsonDeserializationException( message ); }
java
public JsonDeserializationException traceError( String message, JsonReader reader ) { getLogger().log( Level.SEVERE, message ); traceReaderInfo( reader ); return new JsonDeserializationException( message ); }
[ "public", "JsonDeserializationException", "traceError", "(", "String", "message", ",", "JsonReader", "reader", ")", "{", "getLogger", "(", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "message", ")", ";", "traceReaderInfo", "(", "reader", ")", ";", "return", "new", "JsonDeserializationException", "(", "message", ")", ";", "}" ]
Trace an error with current reader state and returns a corresponding exception. @param message error message @param reader current reader @return a {@link JsonDeserializationException} with the given message
[ "Trace", "an", "error", "with", "current", "reader", "state", "and", "returns", "a", "corresponding", "exception", "." ]
train
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonDeserializationContext.java#L359-L363
google/error-prone-javac
src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java
JShellTool.hard
@Override public void hard(String format, Object... args) { """ Must show command output @param format printf format @param args printf args """ rawout(prefix(format), args); }
java
@Override public void hard(String format, Object... args) { rawout(prefix(format), args); }
[ "@", "Override", "public", "void", "hard", "(", "String", "format", ",", "Object", "...", "args", ")", "{", "rawout", "(", "prefix", "(", "format", ")", ",", "args", ")", ";", "}" ]
Must show command output @param format printf format @param args printf args
[ "Must", "show", "command", "output" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java#L667-L670
alkacon/opencms-core
src/org/opencms/db/generic/CmsVfsDriver.java
CmsVfsDriver.wrapException
protected CmsDbSqlException wrapException(PreparedStatement stmt, SQLException e) { """ Wrap a SQL exception into a CmsDbSqlException.<p> @param stmt the used statement @param e the exception @return the CmsDbSqlException """ return new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); }
java
protected CmsDbSqlException wrapException(PreparedStatement stmt, SQLException e) { return new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); }
[ "protected", "CmsDbSqlException", "wrapException", "(", "PreparedStatement", "stmt", ",", "SQLException", "e", ")", "{", "return", "new", "CmsDbSqlException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_GENERIC_SQL_1", ",", "CmsDbSqlException", ".", "getErrorQuery", "(", "stmt", ")", ")", ",", "e", ")", ";", "}" ]
Wrap a SQL exception into a CmsDbSqlException.<p> @param stmt the used statement @param e the exception @return the CmsDbSqlException
[ "Wrap", "a", "SQL", "exception", "into", "a", "CmsDbSqlException", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsVfsDriver.java#L4723-L4728
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 { """ 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 """ 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", "++", ")", "{", "ElementProcessor", "processor", "=", "(", "ElementProcessor", ")", "processors", ".", "get", "(", "i", ")", ";", "if", "(", "processor", ".", "handles", "(", "element", ")", ")", "{", "processor", ".", "process", "(", "this", ",", "element", ",", "diagram", ",", "t", ")", ";", "}", "}", "}" ]
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
fommil/matrix-toolkits-java
src/main/java/no/uib/cipr/matrix/BandLU.java
BandLU.factor
public BandLU factor(BandMatrix A, boolean inplace) { """ Creates an LU decomposition of the given matrix @param A Matrix to decompose. If the decomposition is in-place, its number of superdiagonals must equal <code>kl+ku</code> @param inplace Wheter or not the decomposition should overwrite the passed matrix @return The current decomposition """ if (inplace) return factor(A); else return factor(new BandMatrix(A, kl, kl + ku)); }
java
public BandLU factor(BandMatrix A, boolean inplace) { if (inplace) return factor(A); else return factor(new BandMatrix(A, kl, kl + ku)); }
[ "public", "BandLU", "factor", "(", "BandMatrix", "A", ",", "boolean", "inplace", ")", "{", "if", "(", "inplace", ")", "return", "factor", "(", "A", ")", ";", "else", "return", "factor", "(", "new", "BandMatrix", "(", "A", ",", "kl", ",", "kl", "+", "ku", ")", ")", ";", "}" ]
Creates an LU decomposition of the given matrix @param A Matrix to decompose. If the decomposition is in-place, its number of superdiagonals must equal <code>kl+ku</code> @param inplace Wheter or not the decomposition should overwrite the passed matrix @return The current decomposition
[ "Creates", "an", "LU", "decomposition", "of", "the", "given", "matrix" ]
train
https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/BandLU.java#L101-L106
vkostyukov/la4j
src/main/java/org/la4j/Matrices.java
Matrices.mkManhattanNormAccumulator
public static MatrixAccumulator mkManhattanNormAccumulator() { """ Makes an Manhattan norm accumulator that allows to use {@link org.la4j.Matrix#fold(org.la4j.matrix.functor.MatrixAccumulator)} method for norm calculation. @return a Manhattan norm accumulator """ return new MatrixAccumulator() { private double result = 0.0; @Override public void update(int i, int j, double value) { result += Math.abs(value); } @Override public double accumulate() { double value = result; result = 0.0; return value; } }; }
java
public static MatrixAccumulator mkManhattanNormAccumulator() { return new MatrixAccumulator() { private double result = 0.0; @Override public void update(int i, int j, double value) { result += Math.abs(value); } @Override public double accumulate() { double value = result; result = 0.0; return value; } }; }
[ "public", "static", "MatrixAccumulator", "mkManhattanNormAccumulator", "(", ")", "{", "return", "new", "MatrixAccumulator", "(", ")", "{", "private", "double", "result", "=", "0.0", ";", "@", "Override", "public", "void", "update", "(", "int", "i", ",", "int", "j", ",", "double", "value", ")", "{", "result", "+=", "Math", ".", "abs", "(", "value", ")", ";", "}", "@", "Override", "public", "double", "accumulate", "(", ")", "{", "double", "value", "=", "result", ";", "result", "=", "0.0", ";", "return", "value", ";", "}", "}", ";", "}" ]
Makes an Manhattan norm accumulator that allows to use {@link org.la4j.Matrix#fold(org.la4j.matrix.functor.MatrixAccumulator)} method for norm calculation. @return a Manhattan norm accumulator
[ "Makes", "an", "Manhattan", "norm", "accumulator", "that", "allows", "to", "use", "{", "@link", "org", ".", "la4j", ".", "Matrix#fold", "(", "org", ".", "la4j", ".", "matrix", ".", "functor", ".", "MatrixAccumulator", ")", "}", "method", "for", "norm", "calculation", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrices.java#L590-L606
ThreeTen/threetenbp
src/main/java/org/threeten/bp/zone/ZoneRulesInitializer.java
ZoneRulesInitializer.setInitializer
public static void setInitializer(ZoneRulesInitializer initializer) { """ Sets the initializer to use. <p> This can only be invoked before the {@link ZoneRulesProvider} class is loaded. Invoking this method at a later point will throw an exception. @param initializer the initializer to use @throws IllegalStateException if initialization has already occurred or another initializer has been set """ if (INITIALIZED.get()) { throw new IllegalStateException("Already initialized"); } if (!INITIALIZER.compareAndSet(null, initializer)) { throw new IllegalStateException("Initializer was already set, possibly with a default during initialization"); } }
java
public static void setInitializer(ZoneRulesInitializer initializer) { if (INITIALIZED.get()) { throw new IllegalStateException("Already initialized"); } if (!INITIALIZER.compareAndSet(null, initializer)) { throw new IllegalStateException("Initializer was already set, possibly with a default during initialization"); } }
[ "public", "static", "void", "setInitializer", "(", "ZoneRulesInitializer", "initializer", ")", "{", "if", "(", "INITIALIZED", ".", "get", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Already initialized\"", ")", ";", "}", "if", "(", "!", "INITIALIZER", ".", "compareAndSet", "(", "null", ",", "initializer", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Initializer was already set, possibly with a default during initialization\"", ")", ";", "}", "}" ]
Sets the initializer to use. <p> This can only be invoked before the {@link ZoneRulesProvider} class is loaded. Invoking this method at a later point will throw an exception. @param initializer the initializer to use @throws IllegalStateException if initialization has already occurred or another initializer has been set
[ "Sets", "the", "initializer", "to", "use", ".", "<p", ">", "This", "can", "only", "be", "invoked", "before", "the", "{", "@link", "ZoneRulesProvider", "}", "class", "is", "loaded", ".", "Invoking", "this", "method", "at", "a", "later", "point", "will", "throw", "an", "exception", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/zone/ZoneRulesInitializer.java#L72-L79