repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
joelittlejohn/jsonschema2pojo
jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jsonschema2Pojo.java
Jsonschema2Pojo.generate
public static void generate(GenerationConfig config) throws IOException { Annotator annotator = getAnnotator(config); RuleFactory ruleFactory = createRuleFactory(config); ruleFactory.setAnnotator(annotator); ruleFactory.setGenerationConfig(config); ruleFactory.setSchemaStore(new SchemaStore(createContentResolver(config))); SchemaMapper mapper = new SchemaMapper(ruleFactory, createSchemaGenerator(config)); JCodeModel codeModel = new JCodeModel(); if (config.isRemoveOldOutput()) { removeOldOutput(config.getTargetDirectory()); } for (Iterator<URL> sources = config.getSource(); sources.hasNext();) { URL source = sources.next(); if (URLUtil.parseProtocol(source.toString()) == URLProtocol.FILE && URLUtil.getFileFromURL(source).isDirectory()) { generateRecursive(config, mapper, codeModel, defaultString(config.getTargetPackage()), Arrays.asList(URLUtil.getFileFromURL(source).listFiles(config.getFileFilter()))); } else { mapper.generate(codeModel, getNodeName(source, config), defaultString(config.getTargetPackage()), source); } } if (config.getTargetDirectory().exists() || config.getTargetDirectory().mkdirs()) { if (config.getTargetLanguage() == Language.SCALA) { CodeWriter sourcesWriter = new ScalaFileCodeWriter(config.getTargetDirectory(), config.getOutputEncoding()); CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); codeModel.build(sourcesWriter, resourcesWriter); } else { CodeWriter sourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); codeModel.build(sourcesWriter, resourcesWriter); } } else { throw new GenerationException("Could not create or access target directory " + config.getTargetDirectory().getAbsolutePath()); } }
java
public static void generate(GenerationConfig config) throws IOException { Annotator annotator = getAnnotator(config); RuleFactory ruleFactory = createRuleFactory(config); ruleFactory.setAnnotator(annotator); ruleFactory.setGenerationConfig(config); ruleFactory.setSchemaStore(new SchemaStore(createContentResolver(config))); SchemaMapper mapper = new SchemaMapper(ruleFactory, createSchemaGenerator(config)); JCodeModel codeModel = new JCodeModel(); if (config.isRemoveOldOutput()) { removeOldOutput(config.getTargetDirectory()); } for (Iterator<URL> sources = config.getSource(); sources.hasNext();) { URL source = sources.next(); if (URLUtil.parseProtocol(source.toString()) == URLProtocol.FILE && URLUtil.getFileFromURL(source).isDirectory()) { generateRecursive(config, mapper, codeModel, defaultString(config.getTargetPackage()), Arrays.asList(URLUtil.getFileFromURL(source).listFiles(config.getFileFilter()))); } else { mapper.generate(codeModel, getNodeName(source, config), defaultString(config.getTargetPackage()), source); } } if (config.getTargetDirectory().exists() || config.getTargetDirectory().mkdirs()) { if (config.getTargetLanguage() == Language.SCALA) { CodeWriter sourcesWriter = new ScalaFileCodeWriter(config.getTargetDirectory(), config.getOutputEncoding()); CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); codeModel.build(sourcesWriter, resourcesWriter); } else { CodeWriter sourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); CodeWriter resourcesWriter = new FileCodeWriterWithEncoding(config.getTargetDirectory(), config.getOutputEncoding()); codeModel.build(sourcesWriter, resourcesWriter); } } else { throw new GenerationException("Could not create or access target directory " + config.getTargetDirectory().getAbsolutePath()); } }
[ "public", "static", "void", "generate", "(", "GenerationConfig", "config", ")", "throws", "IOException", "{", "Annotator", "annotator", "=", "getAnnotator", "(", "config", ")", ";", "RuleFactory", "ruleFactory", "=", "createRuleFactory", "(", "config", ")", ";", ...
Reads the contents of the given source and initiates schema generation. @param config the configuration options (including source and target paths, and other behavioural options) that will control code generation @throws FileNotFoundException if the source path is not found @throws IOException if the application is unable to read data from the source
[ "Reads", "the", "contents", "of", "the", "given", "source", "and", "initiates", "schema", "generation", "." ]
train
https://github.com/joelittlejohn/jsonschema2pojo/blob/0552b80db93214eb186e4ae45b40866cc1e7eb84/jsonschema2pojo-core/src/main/java/org/jsonschema2pojo/Jsonschema2Pojo.java#L55-L94
m-m-m/util
nls/src/main/java/net/sf/mmm/util/nls/impl/formatter/NlsFormatterChoice.java
NlsFormatterChoice.parseCondition
private Filter<Object> parseCondition(CharSequenceScanner scanner) { int index = scanner.getCurrentIndex(); Filter<Object> condition; if (scanner.expect(CONDITION_VAR)) { // variable choice String symbol = scanner.readWhile(FILTER_COMPARATOR); CompareOperator comparator = CompareOperator.fromValue(symbol); if (comparator == null) { throw new IllegalArgumentException(symbol); } Object comparatorArgument = parseComparatorArgument(scanner); condition = new Condition(comparator, comparatorArgument); } else if (scanner.expect(CONDITION_ELSE, false)) { condition = FILTER_ELSE; } else { throw new IllegalArgumentException(scanner.substring(index, scanner.getCurrentIndex())); } if (!scanner.expect(CONDITION_END)) { throw new IllegalArgumentException(scanner.substring(index, scanner.getCurrentIndex())); } return condition; }
java
private Filter<Object> parseCondition(CharSequenceScanner scanner) { int index = scanner.getCurrentIndex(); Filter<Object> condition; if (scanner.expect(CONDITION_VAR)) { // variable choice String symbol = scanner.readWhile(FILTER_COMPARATOR); CompareOperator comparator = CompareOperator.fromValue(symbol); if (comparator == null) { throw new IllegalArgumentException(symbol); } Object comparatorArgument = parseComparatorArgument(scanner); condition = new Condition(comparator, comparatorArgument); } else if (scanner.expect(CONDITION_ELSE, false)) { condition = FILTER_ELSE; } else { throw new IllegalArgumentException(scanner.substring(index, scanner.getCurrentIndex())); } if (!scanner.expect(CONDITION_END)) { throw new IllegalArgumentException(scanner.substring(index, scanner.getCurrentIndex())); } return condition; }
[ "private", "Filter", "<", "Object", ">", "parseCondition", "(", "CharSequenceScanner", "scanner", ")", "{", "int", "index", "=", "scanner", ".", "getCurrentIndex", "(", ")", ";", "Filter", "<", "Object", ">", "condition", ";", "if", "(", "scanner", ".", "e...
This method parses the {@link Condition}. @param scanner is the {@link CharSequenceScanner}. @return the parsed {@link Condition} or {@link #FILTER_ELSE} in case of {@link #CONDITION_ELSE}.
[ "This", "method", "parses", "the", "{", "@link", "Condition", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/nls/src/main/java/net/sf/mmm/util/nls/impl/formatter/NlsFormatterChoice.java#L159-L181
sarl/sarl
products/sarlc/src/main/java/io/sarl/lang/sarlc/modules/commands/CompilerCommandModule.java
CompilerCommandModule.provideSarlcCompilerCommand
@SuppressWarnings("static-method") @Provides @Singleton public CompilerCommand provideSarlcCompilerCommand(Provider<SarlBatchCompiler> compiler, Provider<SarlConfig> configuration, Provider<PathDetector> pathDetector, Provider<ProgressBarConfig> commandConfig) { return new CompilerCommand(compiler, configuration, pathDetector, commandConfig); }
java
@SuppressWarnings("static-method") @Provides @Singleton public CompilerCommand provideSarlcCompilerCommand(Provider<SarlBatchCompiler> compiler, Provider<SarlConfig> configuration, Provider<PathDetector> pathDetector, Provider<ProgressBarConfig> commandConfig) { return new CompilerCommand(compiler, configuration, pathDetector, commandConfig); }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "@", "Provides", "@", "Singleton", "public", "CompilerCommand", "provideSarlcCompilerCommand", "(", "Provider", "<", "SarlBatchCompiler", ">", "compiler", ",", "Provider", "<", "SarlConfig", ">", "configuration", ...
Provide the command for running the compiler. @param compiler the compiler. @param configuration the SARLC configuration. @param pathDetector the detector of paths. @param commandConfig the configuration of the command. @return the command.
[ "Provide", "the", "command", "for", "running", "the", "compiler", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/products/sarlc/src/main/java/io/sarl/lang/sarlc/modules/commands/CompilerCommandModule.java#L77-L84
jtrfp/javamod
src/main/java/de/quippy/javamod/multimedia/mp3/streaming/IcyInputStream.java
IcyInputStream.parseInlineIcyTags
protected void parseInlineIcyTags(byte[] tagBlock) { String blockString = null; try { blockString = new String(tagBlock, "UTF-8"); } catch (UnsupportedEncodingException e) { blockString = new String(tagBlock); } StringTokenizer izer = new StringTokenizer(blockString, INLINE_TAG_SEPARATORS); while (izer.hasMoreTokens()) { String tagString = izer.nextToken(); int separatorIdx = tagString.indexOf('='); if (separatorIdx == -1) continue; // bogus tagString if no '=' // try to strip single-quotes around value, if present int valueStartIdx = (tagString.charAt(separatorIdx + 1) == '\'') ? separatorIdx + 2 : separatorIdx + 1; int valueEndIdx = (tagString.charAt(tagString.length() - 1) == '\'') ? tagString.length() - 1 : tagString.length(); String name = tagString.substring(0, separatorIdx); String value = tagString.substring(valueStartIdx, valueEndIdx); addTag(new IcyTag(name, value)); } }
java
protected void parseInlineIcyTags(byte[] tagBlock) { String blockString = null; try { blockString = new String(tagBlock, "UTF-8"); } catch (UnsupportedEncodingException e) { blockString = new String(tagBlock); } StringTokenizer izer = new StringTokenizer(blockString, INLINE_TAG_SEPARATORS); while (izer.hasMoreTokens()) { String tagString = izer.nextToken(); int separatorIdx = tagString.indexOf('='); if (separatorIdx == -1) continue; // bogus tagString if no '=' // try to strip single-quotes around value, if present int valueStartIdx = (tagString.charAt(separatorIdx + 1) == '\'') ? separatorIdx + 2 : separatorIdx + 1; int valueEndIdx = (tagString.charAt(tagString.length() - 1) == '\'') ? tagString.length() - 1 : tagString.length(); String name = tagString.substring(0, separatorIdx); String value = tagString.substring(valueStartIdx, valueEndIdx); addTag(new IcyTag(name, value)); } }
[ "protected", "void", "parseInlineIcyTags", "(", "byte", "[", "]", "tagBlock", ")", "{", "String", "blockString", "=", "null", ";", "try", "{", "blockString", "=", "new", "String", "(", "tagBlock", ",", "\"UTF-8\"", ")", ";", "}", "catch", "(", "Unsupported...
Parse metadata from an in-stream "block" of bytes, add a tag for each one. <p> Hilariously, the inline data format is totally different than the top-of-stream header. For example, here's a block I saw on "Final Fantasy Radio": <pre> StreamTitle='Final Fantasy 8 - Nobuo Uematsu - Blue Fields';StreamUrl=''; </pre> In other words: <ol> <li>Tags are delimited by semicolons <li>Keys/values are delimited by equals-signs <li>Values are wrapped in single-quotes <li>Key names are in SentenceCase, not lowercase-dashed </ol>
[ "Parse", "metadata", "from", "an", "in", "-", "stream", "block", "of", "bytes", "add", "a", "tag", "for", "each", "one", ".", "<p", ">", "Hilariously", "the", "inline", "data", "format", "is", "totally", "different", "than", "the", "top", "-", "of", "-...
train
https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mp3/streaming/IcyInputStream.java#L325-L349
looly/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java
KeyUtil.readCertificate
public static Certificate readCertificate(String type, InputStream in, char[] password, String alias) { final KeyStore keyStore = readKeyStore(type, in, password); try { return keyStore.getCertificate(alias); } catch (KeyStoreException e) { throw new CryptoException(e); } }
java
public static Certificate readCertificate(String type, InputStream in, char[] password, String alias) { final KeyStore keyStore = readKeyStore(type, in, password); try { return keyStore.getCertificate(alias); } catch (KeyStoreException e) { throw new CryptoException(e); } }
[ "public", "static", "Certificate", "readCertificate", "(", "String", "type", ",", "InputStream", "in", ",", "char", "[", "]", "password", ",", "String", "alias", ")", "{", "final", "KeyStore", "keyStore", "=", "readKeyStore", "(", "type", ",", "in", ",", "...
读取Certification文件<br> Certification为证书文件<br> see: http://snowolf.iteye.com/blog/391931 @param type 类型,例如X.509 @param in {@link InputStream} 如果想从文件读取.cer文件,使用 {@link FileUtil#getInputStream(java.io.File)} 读取 @param password 密码 @param alias 别名 @return {@link KeyStore} @since 4.4.1
[ "读取Certification文件<br", ">", "Certification为证书文件<br", ">", "see", ":", "http", ":", "//", "snowolf", ".", "iteye", ".", "com", "/", "blog", "/", "391931" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java#L675-L682
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslContextBuilder.java
SslContextBuilder.keyManager
public SslContextBuilder keyManager(File keyCertChainFile, File keyFile, String keyPassword) { X509Certificate[] keyCertChain; PrivateKey key; try { keyCertChain = SslContext.toX509Certificates(keyCertChainFile); } catch (Exception e) { throw new IllegalArgumentException("File does not contain valid certificates: " + keyCertChainFile, e); } try { key = SslContext.toPrivateKey(keyFile, keyPassword); } catch (Exception e) { throw new IllegalArgumentException("File does not contain valid private key: " + keyFile, e); } return keyManager(key, keyPassword, keyCertChain); }
java
public SslContextBuilder keyManager(File keyCertChainFile, File keyFile, String keyPassword) { X509Certificate[] keyCertChain; PrivateKey key; try { keyCertChain = SslContext.toX509Certificates(keyCertChainFile); } catch (Exception e) { throw new IllegalArgumentException("File does not contain valid certificates: " + keyCertChainFile, e); } try { key = SslContext.toPrivateKey(keyFile, keyPassword); } catch (Exception e) { throw new IllegalArgumentException("File does not contain valid private key: " + keyFile, e); } return keyManager(key, keyPassword, keyCertChain); }
[ "public", "SslContextBuilder", "keyManager", "(", "File", "keyCertChainFile", ",", "File", "keyFile", ",", "String", "keyPassword", ")", "{", "X509Certificate", "[", "]", "keyCertChain", ";", "PrivateKey", "key", ";", "try", "{", "keyCertChain", "=", "SslContext",...
Identifying certificate for this host. {@code keyCertChainFile} and {@code keyFile} may be {@code null} for client contexts, which disables mutual authentication. @param keyCertChainFile an X.509 certificate chain file in PEM format @param keyFile a PKCS#8 private key file in PEM format @param keyPassword the password of the {@code keyFile}, or {@code null} if it's not password-protected
[ "Identifying", "certificate", "for", "this", "host", ".", "{", "@code", "keyCertChainFile", "}", "and", "{", "@code", "keyFile", "}", "may", "be", "{", "@code", "null", "}", "for", "client", "contexts", "which", "disables", "mutual", "authentication", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslContextBuilder.java#L259-L273
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/ClassUseMapper.java
ClassUseMapper.mapAnnotations
private <T extends Element> void mapAnnotations(final Map<TypeElement, List<T>> map, Element e, final T holder) { new SimpleElementVisitor9<Void, Void>() { void addAnnotations(Element e) { for (AnnotationMirror a : e.getAnnotationMirrors()) { add(map, (TypeElement) a.getAnnotationType().asElement(), holder); } } @Override public Void visitPackage(PackageElement e, Void p) { for (AnnotationMirror a : e.getAnnotationMirrors()) { refList(map, a.getAnnotationType().asElement()).add(holder); } return null; } @Override protected Void defaultAction(Element e, Void p) { addAnnotations(e); return null; } }.visit(e); }
java
private <T extends Element> void mapAnnotations(final Map<TypeElement, List<T>> map, Element e, final T holder) { new SimpleElementVisitor9<Void, Void>() { void addAnnotations(Element e) { for (AnnotationMirror a : e.getAnnotationMirrors()) { add(map, (TypeElement) a.getAnnotationType().asElement(), holder); } } @Override public Void visitPackage(PackageElement e, Void p) { for (AnnotationMirror a : e.getAnnotationMirrors()) { refList(map, a.getAnnotationType().asElement()).add(holder); } return null; } @Override protected Void defaultAction(Element e, Void p) { addAnnotations(e); return null; } }.visit(e); }
[ "private", "<", "T", "extends", "Element", ">", "void", "mapAnnotations", "(", "final", "Map", "<", "TypeElement", ",", "List", "<", "T", ">", ">", "map", ",", "Element", "e", ",", "final", "T", "holder", ")", "{", "new", "SimpleElementVisitor9", "<", ...
Map the AnnotationType to the members that use them as type parameters. @param map the map the insert the information into. @param element whose type parameters are being checked. @param holder the holder that owns the type parameters.
[ "Map", "the", "AnnotationType", "to", "the", "members", "that", "use", "them", "as", "type", "parameters", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/ClassUseMapper.java#L557-L581
stapler/stapler
jelly/src/main/java/org/kohsuke/stapler/jelly/ResourceBundle.java
ResourceBundle.getFormatString
public String getFormatString(Locale locale, String key) { String[] suffixes = toStrings(locale); while(true) { for (int i=0; i<suffixes.length; i++) { String suffix = suffixes[i]; String msg = get(suffix).getProperty(key); if(msg!=null && msg.length()>0) // ignore a definition without value, because stapler:i18n generates // value-less definitions return msg; int idx = suffix.lastIndexOf('_'); if(idx<0) // failed to find return null; suffixes[i] = suffix.substring(0,idx); } } }
java
public String getFormatString(Locale locale, String key) { String[] suffixes = toStrings(locale); while(true) { for (int i=0; i<suffixes.length; i++) { String suffix = suffixes[i]; String msg = get(suffix).getProperty(key); if(msg!=null && msg.length()>0) // ignore a definition without value, because stapler:i18n generates // value-less definitions return msg; int idx = suffix.lastIndexOf('_'); if(idx<0) // failed to find return null; suffixes[i] = suffix.substring(0,idx); } } }
[ "public", "String", "getFormatString", "(", "Locale", "locale", ",", "String", "key", ")", "{", "String", "[", "]", "suffixes", "=", "toStrings", "(", "locale", ")", ";", "while", "(", "true", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "...
Gets the format string for the given key. <p> This method performs a search so that a look up for "pt_BR" would delegate to "pt" then "" (the no-locale locale.)
[ "Gets", "the", "format", "string", "for", "the", "given", "key", ".", "<p", ">", "This", "method", "performs", "a", "search", "so", "that", "a", "look", "up", "for", "pt_BR", "would", "delegate", "to", "pt", "then", "(", "the", "no", "-", "locale", "...
train
https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/jelly/src/main/java/org/kohsuke/stapler/jelly/ResourceBundle.java#L83-L101
dickschoeller/gedbrowser
gedbrowser-datamodel/src/main/java/org/schoellerfamily/gedbrowser/datamodel/Date.java
Date.getEstimateDate
public String getEstimateDate() { final DateParser parser = new DateParser(getDate()); if (estimateDate == null) { estimateDate = parser.getEstimateCalendar(); } final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd", Locale.US); return format(formatter, estimateDate); }
java
public String getEstimateDate() { final DateParser parser = new DateParser(getDate()); if (estimateDate == null) { estimateDate = parser.getEstimateCalendar(); } final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd", Locale.US); return format(formatter, estimateDate); }
[ "public", "String", "getEstimateDate", "(", ")", "{", "final", "DateParser", "parser", "=", "new", "DateParser", "(", "getDate", "(", ")", ")", ";", "if", "(", "estimateDate", "==", "null", ")", "{", "estimateDate", "=", "parser", ".", "getEstimateCalendar",...
Like sort date only we are starting in on correcting the problems with approximations. @return string in the form yyyymmdd
[ "Like", "sort", "date", "only", "we", "are", "starting", "in", "on", "correcting", "the", "problems", "with", "approximations", "." ]
train
https://github.com/dickschoeller/gedbrowser/blob/e3e10b1ff3a34ebde9b7edcbfafcd5fe6fb3b3e1/gedbrowser-datamodel/src/main/java/org/schoellerfamily/gedbrowser/datamodel/Date.java#L88-L96
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/ByteArrayUtil.java
ByteArrayUtil.putIntBE
public static void putIntBE(final byte[] array, final int offset, final int value) { array[offset + 3] = (byte) (value ); array[offset + 2] = (byte) (value >>> 8); array[offset + 1] = (byte) (value >>> 16); array[offset ] = (byte) (value >>> 24); }
java
public static void putIntBE(final byte[] array, final int offset, final int value) { array[offset + 3] = (byte) (value ); array[offset + 2] = (byte) (value >>> 8); array[offset + 1] = (byte) (value >>> 16); array[offset ] = (byte) (value >>> 24); }
[ "public", "static", "void", "putIntBE", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "int", "value", ")", "{", "array", "[", "offset", "+", "3", "]", "=", "(", "byte", ")", "(", "value", ")", ";", "array", ...
Put the source <i>int</i> into the destination byte array starting at the given offset in big endian order. There is no bounds checking. @param array destination byte array @param offset destination offset @param value source <i>int</i>
[ "Put", "the", "source", "<i", ">", "int<", "/", "i", ">", "into", "the", "destination", "byte", "array", "starting", "at", "the", "given", "offset", "in", "big", "endian", "order", ".", "There", "is", "no", "bounds", "checking", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/ByteArrayUtil.java#L110-L115
netty/netty
common/src/main/java/io/netty/util/ThreadDeathWatcher.java
ThreadDeathWatcher.unwatch
public static void unwatch(Thread thread, Runnable task) { if (thread == null) { throw new NullPointerException("thread"); } if (task == null) { throw new NullPointerException("task"); } schedule(thread, task, false); }
java
public static void unwatch(Thread thread, Runnable task) { if (thread == null) { throw new NullPointerException("thread"); } if (task == null) { throw new NullPointerException("task"); } schedule(thread, task, false); }
[ "public", "static", "void", "unwatch", "(", "Thread", "thread", ",", "Runnable", "task", ")", "{", "if", "(", "thread", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"thread\"", ")", ";", "}", "if", "(", "task", "==", "null", "...
Cancels the task scheduled via {@link #watch(Thread, Runnable)}.
[ "Cancels", "the", "task", "scheduled", "via", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/ThreadDeathWatcher.java#L96-L105
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetRowResourcesImpl.java
SheetRowResourcesImpl.copyRows
public CopyOrMoveRowResult copyRows(Long sheetId, EnumSet<RowCopyInclusion> includes, Boolean ignoreRowsNotFound, CopyOrMoveRowDirective copyParameters) throws SmartsheetException { String path = "sheets/" + sheetId +"/rows/copy"; HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("include", QueryUtil.generateCommaSeparatedList(includes)); if (ignoreRowsNotFound != null){ parameters.put("ignoreRowsNotFound", ignoreRowsNotFound.toString()); } path += QueryUtil.generateUrl(null, parameters); return this.postAndReceiveRowObject(path, copyParameters); }
java
public CopyOrMoveRowResult copyRows(Long sheetId, EnumSet<RowCopyInclusion> includes, Boolean ignoreRowsNotFound, CopyOrMoveRowDirective copyParameters) throws SmartsheetException { String path = "sheets/" + sheetId +"/rows/copy"; HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("include", QueryUtil.generateCommaSeparatedList(includes)); if (ignoreRowsNotFound != null){ parameters.put("ignoreRowsNotFound", ignoreRowsNotFound.toString()); } path += QueryUtil.generateUrl(null, parameters); return this.postAndReceiveRowObject(path, copyParameters); }
[ "public", "CopyOrMoveRowResult", "copyRows", "(", "Long", "sheetId", ",", "EnumSet", "<", "RowCopyInclusion", ">", "includes", ",", "Boolean", "ignoreRowsNotFound", ",", "CopyOrMoveRowDirective", "copyParameters", ")", "throws", "SmartsheetException", "{", "String", "pa...
Copies Row(s) from the Sheet specified in the URL to (the bottom of) another sheet. It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/rows/copy Exceptions: IllegalArgumentException : if any argument is null, or path is empty string InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param sheetId the sheet ID to move @param includes the parameters to include @param ignoreRowsNotFound optional,specifying row Ids that do not exist within the source sheet @param copyParameters CopyOrMoveRowDirective object @return the result object @throws SmartsheetException the smartsheet exception
[ "Copies", "Row", "(", "s", ")", "from", "the", "Sheet", "specified", "in", "the", "URL", "to", "(", "the", "bottom", "of", ")", "another", "sheet", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetRowResourcesImpl.java#L357-L368
ironjacamar/ironjacamar
web/src/main/java/org/ironjacamar/web/console/HtmlAdaptorServlet.java
HtmlAdaptorServlet.invokeOp
private OpResultInfo invokeOp(final String name, final int index, final String[] args) throws PrivilegedActionException { return AccessController.doPrivileged(new PrivilegedExceptionAction<OpResultInfo>() { public OpResultInfo run() throws Exception { return Server.invokeOp(name, index, args); } }); }
java
private OpResultInfo invokeOp(final String name, final int index, final String[] args) throws PrivilegedActionException { return AccessController.doPrivileged(new PrivilegedExceptionAction<OpResultInfo>() { public OpResultInfo run() throws Exception { return Server.invokeOp(name, index, args); } }); }
[ "private", "OpResultInfo", "invokeOp", "(", "final", "String", "name", ",", "final", "int", "index", ",", "final", "String", "[", "]", "args", ")", "throws", "PrivilegedActionException", "{", "return", "AccessController", ".", "doPrivileged", "(", "new", "Privil...
Invoke an operation on a MBean @param name The name of the bean @param index The operation index @param args The operation arguments @return The operation result @exception PrivilegedExceptionAction Thrown if the operation cannot be performed
[ "Invoke", "an", "operation", "on", "a", "MBean" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/web/src/main/java/org/ironjacamar/web/console/HtmlAdaptorServlet.java#L393-L403
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorInvoker.java
RepresentationModelProcessorInvoker.invokeProcessorsFor
@SuppressWarnings("unchecked") public <T extends RepresentationModel<T>> T invokeProcessorsFor(T value, ResolvableType referenceType) { Assert.notNull(value, "Value must not be null!"); Assert.notNull(referenceType, "Reference type must not be null!"); // For Resources implementations, process elements first if (RepresentationModelProcessorHandlerMethodReturnValueHandler.COLLECTION_MODEL_TYPE .isAssignableFrom(referenceType)) { CollectionModel<?> collectionModel = (CollectionModel<?>) value; Class<?> rawClass = referenceType.getRawClass(); if (rawClass == null) { throw new IllegalArgumentException(String.format("%s does not expose a raw type!", referenceType)); } ResolvableType elementTargetType = ResolvableType.forClass(CollectionModel.class, rawClass).getGeneric(0); List<Object> result = new ArrayList<>(collectionModel.getContent().size()); for (Object element : collectionModel) { ResolvableType elementType = ResolvableType.forClass(element.getClass()); if (!getRawType(elementTargetType).equals(elementType.getRawClass())) { elementTargetType = elementType; } result.add(invokeProcessorsFor(element, elementTargetType)); } if (RepresentationModelProcessorHandlerMethodReturnValueHandler.CONTENT_FIELD != null) { ReflectionUtils.setField( // RepresentationModelProcessorHandlerMethodReturnValueHandler.CONTENT_FIELD, // collectionModel, // result // ); } } return (T) invokeProcessorsFor((Object) value, referenceType); }
java
@SuppressWarnings("unchecked") public <T extends RepresentationModel<T>> T invokeProcessorsFor(T value, ResolvableType referenceType) { Assert.notNull(value, "Value must not be null!"); Assert.notNull(referenceType, "Reference type must not be null!"); // For Resources implementations, process elements first if (RepresentationModelProcessorHandlerMethodReturnValueHandler.COLLECTION_MODEL_TYPE .isAssignableFrom(referenceType)) { CollectionModel<?> collectionModel = (CollectionModel<?>) value; Class<?> rawClass = referenceType.getRawClass(); if (rawClass == null) { throw new IllegalArgumentException(String.format("%s does not expose a raw type!", referenceType)); } ResolvableType elementTargetType = ResolvableType.forClass(CollectionModel.class, rawClass).getGeneric(0); List<Object> result = new ArrayList<>(collectionModel.getContent().size()); for (Object element : collectionModel) { ResolvableType elementType = ResolvableType.forClass(element.getClass()); if (!getRawType(elementTargetType).equals(elementType.getRawClass())) { elementTargetType = elementType; } result.add(invokeProcessorsFor(element, elementTargetType)); } if (RepresentationModelProcessorHandlerMethodReturnValueHandler.CONTENT_FIELD != null) { ReflectionUtils.setField( // RepresentationModelProcessorHandlerMethodReturnValueHandler.CONTENT_FIELD, // collectionModel, // result // ); } } return (T) invokeProcessorsFor((Object) value, referenceType); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "RepresentationModel", "<", "T", ">", ">", "T", "invokeProcessorsFor", "(", "T", "value", ",", "ResolvableType", "referenceType", ")", "{", "Assert", ".", "notNull", "(", "value...
Invokes all {@link RepresentationModelProcessor} instances registered for the type of the given value and reference type. @param value must not be {@literal null}. @param referenceType must not be {@literal null}. @return
[ "Invokes", "all", "{", "@link", "RepresentationModelProcessor", "}", "instances", "registered", "for", "the", "type", "of", "the", "given", "value", "and", "reference", "type", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorInvoker.java#L101-L143
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java
ForwardCurveInterpolation.createForwardCurveFromForwards
public static ForwardCurveInterpolation createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, InterpolationEntityForward interpolationEntityForward, String discountCurveName, AnalyticModel model, double[] times, RandomVariable[] givenForwards) { ForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, referenceDate, paymentOffsetCode, interpolationEntityForward, discountCurveName); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { forwardCurveInterpolation.addForward(model, times[timeIndex], givenForwards[timeIndex], false); } return forwardCurveInterpolation; }
java
public static ForwardCurveInterpolation createForwardCurveFromForwards(String name, LocalDate referenceDate, String paymentOffsetCode, InterpolationEntityForward interpolationEntityForward, String discountCurveName, AnalyticModel model, double[] times, RandomVariable[] givenForwards) { ForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, referenceDate, paymentOffsetCode, interpolationEntityForward, discountCurveName); for(int timeIndex=0; timeIndex<times.length;timeIndex++) { forwardCurveInterpolation.addForward(model, times[timeIndex], givenForwards[timeIndex], false); } return forwardCurveInterpolation; }
[ "public", "static", "ForwardCurveInterpolation", "createForwardCurveFromForwards", "(", "String", "name", ",", "LocalDate", "referenceDate", ",", "String", "paymentOffsetCode", ",", "InterpolationEntityForward", "interpolationEntityForward", ",", "String", "discountCurveName", ...
Create a forward curve from given times and given forwards. @param name The name of this curve. @param referenceDate The reference date for this code, i.e., the date which defines t=0. @param paymentOffsetCode The maturity of the index modeled by this curve. @param interpolationEntityForward Interpolation entity used for forward rate interpolation. @param discountCurveName The name of a discount curve associated with this index (associated with it's funding or collateralization), if any. @param model The model to be used to fetch the discount curve, if needed. @param times A vector of given time points. @param givenForwards A vector of given forwards (corresponding to the given time points). @return A new ForwardCurve object.
[ "Create", "a", "forward", "curve", "from", "given", "times", "and", "given", "forwards", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java#L215-L223
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/extension/RTreeIndexCoreExtension.java
RTreeIndexCoreExtension.createFunctions
public boolean createFunctions(String tableName, String columnName) { boolean created = has(tableName, columnName); if (created) { createAllFunctions(); } return created; }
java
public boolean createFunctions(String tableName, String columnName) { boolean created = has(tableName, columnName); if (created) { createAllFunctions(); } return created; }
[ "public", "boolean", "createFunctions", "(", "String", "tableName", ",", "String", "columnName", ")", "{", "boolean", "created", "=", "has", "(", "tableName", ",", "columnName", ")", ";", "if", "(", "created", ")", "{", "createAllFunctions", "(", ")", ";", ...
Check if the table and column has the RTree extension and create the functions if needed @param tableName table name @param columnName column name @return true if has extension and functions created
[ "Check", "if", "the", "table", "and", "column", "has", "the", "RTree", "extension", "and", "create", "the", "functions", "if", "needed" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/RTreeIndexCoreExtension.java#L338-L345
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJTimeSeriesChartBuilder.java
DJTimeSeriesChartBuilder.addSerie
public DJTimeSeriesChartBuilder addSerie(AbstractColumn column, StringExpression labelExpression) { getDataset().addSerie(column, labelExpression); return this; }
java
public DJTimeSeriesChartBuilder addSerie(AbstractColumn column, StringExpression labelExpression) { getDataset().addSerie(column, labelExpression); return this; }
[ "public", "DJTimeSeriesChartBuilder", "addSerie", "(", "AbstractColumn", "column", ",", "StringExpression", "labelExpression", ")", "{", "getDataset", "(", ")", ".", "addSerie", "(", "column", ",", "labelExpression", ")", ";", "return", "this", ";", "}" ]
Adds the specified serie column to the dataset with custom label. @param column the serie column
[ "Adds", "the", "specified", "serie", "column", "to", "the", "dataset", "with", "custom", "label", "." ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJTimeSeriesChartBuilder.java#L384-L387
JodaOrg/joda-time
src/main/java/org/joda/time/field/FieldUtils.java
FieldUtils.safeAdd
public static int safeAdd(int val1, int val2) { int sum = val1 + val2; // If there is a sign change, but the two values have the same sign... if ((val1 ^ sum) < 0 && (val1 ^ val2) >= 0) { throw new ArithmeticException ("The calculation caused an overflow: " + val1 + " + " + val2); } return sum; }
java
public static int safeAdd(int val1, int val2) { int sum = val1 + val2; // If there is a sign change, but the two values have the same sign... if ((val1 ^ sum) < 0 && (val1 ^ val2) >= 0) { throw new ArithmeticException ("The calculation caused an overflow: " + val1 + " + " + val2); } return sum; }
[ "public", "static", "int", "safeAdd", "(", "int", "val1", ",", "int", "val2", ")", "{", "int", "sum", "=", "val1", "+", "val2", ";", "// If there is a sign change, but the two values have the same sign...", "if", "(", "(", "val1", "^", "sum", ")", "<", "0", ...
Add two values throwing an exception if overflow occurs. @param val1 the first value @param val2 the second value @return the new total @throws ArithmeticException if the value is too big or too small
[ "Add", "two", "values", "throwing", "an", "exception", "if", "overflow", "occurs", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/field/FieldUtils.java#L66-L74
aalmiray/Json-lib
src/main/java/net/sf/json/JsonConfig.java
JsonConfig.registerJavaPropertyNameProcessor
public void registerJavaPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) { if( target != null && propertyNameProcessor != null ) { javaPropertyNameProcessorMap.put( target, propertyNameProcessor ); } }
java
public void registerJavaPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) { if( target != null && propertyNameProcessor != null ) { javaPropertyNameProcessorMap.put( target, propertyNameProcessor ); } }
[ "public", "void", "registerJavaPropertyNameProcessor", "(", "Class", "target", ",", "PropertyNameProcessor", "propertyNameProcessor", ")", "{", "if", "(", "target", "!=", "null", "&&", "propertyNameProcessor", "!=", "null", ")", "{", "javaPropertyNameProcessorMap", ".",...
Registers a PropertyNameProcessor.<br> [JSON -&gt; Java] @param target the class to use as key @param propertyNameProcessor the processor to register
[ "Registers", "a", "PropertyNameProcessor", ".", "<br", ">", "[", "JSON", "-", "&gt", ";", "Java", "]" ]
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JsonConfig.java#L773-L777
NoraUi/NoraUi
src/main/java/com/github/noraui/browser/steps/BrowserSteps.java
BrowserSteps.switchWindow
@Conditioned @Quand("Je passe à la fenêtre '(.*)'[\\.|\\?]") @When("I switch to '(.*)' window[\\.|\\?]") public void switchWindow(String windowKey, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException { switchWindow(windowKey); }
java
@Conditioned @Quand("Je passe à la fenêtre '(.*)'[\\.|\\?]") @When("I switch to '(.*)' window[\\.|\\?]") public void switchWindow(String windowKey, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException { switchWindow(windowKey); }
[ "@", "Conditioned", "@", "Quand", "(", "\"Je passe à la fenêtre '(.*)'[\\\\.|\\\\?]\")\r", "", "@", "When", "(", "\"I switch to '(.*)' window[\\\\.|\\\\?]\"", ")", "public", "void", "switchWindow", "(", "String", "windowKey", ",", "List", "<", "GherkinStepCondition", ">",...
Switch window when the scenario contain more one windows (one more application for example). @param windowKey the key of window (popup, ...) Example: GEOBEER. @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error
[ "Switch", "window", "when", "the", "scenario", "contain", "more", "one", "windows", "(", "one", "more", "application", "for", "example", ")", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/browser/steps/BrowserSteps.java#L116-L121
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/Response.java
Response.andContent
public Response andContent(Map<String, Object> content) { Objects.requireNonNull(content, Required.CONTENT.toString()); this.content.putAll(content); return this; }
java
public Response andContent(Map<String, Object> content) { Objects.requireNonNull(content, Required.CONTENT.toString()); this.content.putAll(content); return this; }
[ "public", "Response", "andContent", "(", "Map", "<", "String", ",", "Object", ">", "content", ")", "{", "Objects", ".", "requireNonNull", "(", "content", ",", "Required", ".", "CONTENT", ".", "toString", "(", ")", ")", ";", "this", ".", "content", ".", ...
Adds an additional content map to the content rendered in the template. Already existing values with the same key are overwritten. @param content The content map to add @return A response object {@link io.mangoo.routing.Response}
[ "Adds", "an", "additional", "content", "map", "to", "the", "content", "rendered", "in", "the", "template", ".", "Already", "existing", "values", "with", "the", "same", "key", "are", "overwritten", "." ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/Response.java#L425-L430
alkacon/opencms-core
src/org/opencms/xml/containerpage/CmsFormatterConfiguration.java
CmsFormatterConfiguration.getFormatterSelection
public Map<String, I_CmsFormatterBean> getFormatterSelection(String containerTypes, int containerWidth) { Map<String, I_CmsFormatterBean> result = new LinkedHashMap<String, I_CmsFormatterBean>(); for (I_CmsFormatterBean formatter : Collections2.filter( m_allFormatters, new MatchesTypeOrWidth(containerTypes, containerWidth))) { if (formatter.isFromFormatterConfigFile()) { result.put(formatter.getId(), formatter); } else { result.put( CmsFormatterConfig.SCHEMA_FORMATTER_ID + formatter.getJspStructureId().toString(), formatter); } } return result; }
java
public Map<String, I_CmsFormatterBean> getFormatterSelection(String containerTypes, int containerWidth) { Map<String, I_CmsFormatterBean> result = new LinkedHashMap<String, I_CmsFormatterBean>(); for (I_CmsFormatterBean formatter : Collections2.filter( m_allFormatters, new MatchesTypeOrWidth(containerTypes, containerWidth))) { if (formatter.isFromFormatterConfigFile()) { result.put(formatter.getId(), formatter); } else { result.put( CmsFormatterConfig.SCHEMA_FORMATTER_ID + formatter.getJspStructureId().toString(), formatter); } } return result; }
[ "public", "Map", "<", "String", ",", "I_CmsFormatterBean", ">", "getFormatterSelection", "(", "String", "containerTypes", ",", "int", "containerWidth", ")", "{", "Map", "<", "String", ",", "I_CmsFormatterBean", ">", "result", "=", "new", "LinkedHashMap", "<", "S...
Returns the formatters available for selection for the given container type and width.<p> @param containerTypes the container types (comma separated) @param containerWidth the container width @return the list of available formatters
[ "Returns", "the", "formatters", "available", "for", "selection", "for", "the", "given", "container", "type", "and", "width", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsFormatterConfiguration.java#L396-L411
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/ComapiChat.java
ComapiChat.createShared
private static ComapiChatClient createShared(Application app, @NonNull RxComapiClient comapiClient, @NonNull final ChatConfig chatConfig, @NonNull final EventsHandler eventsHandler, @NonNull final CallbackAdapter adapter) { if (instance == null) { synchronized (ComapiChatClient.class) { if (instance == null) { instance = new ComapiChatClient(app, comapiClient, chatConfig, eventsHandler, adapter); } } } return instance; }
java
private static ComapiChatClient createShared(Application app, @NonNull RxComapiClient comapiClient, @NonNull final ChatConfig chatConfig, @NonNull final EventsHandler eventsHandler, @NonNull final CallbackAdapter adapter) { if (instance == null) { synchronized (ComapiChatClient.class) { if (instance == null) { instance = new ComapiChatClient(app, comapiClient, chatConfig, eventsHandler, adapter); } } } return instance; }
[ "private", "static", "ComapiChatClient", "createShared", "(", "Application", "app", ",", "@", "NonNull", "RxComapiClient", "comapiClient", ",", "@", "NonNull", "final", "ChatConfig", "chatConfig", ",", "@", "NonNull", "final", "EventsHandler", "eventsHandler", ",", ...
Get global singleton of {@link ComapiChatClient}. @return Singleton of {@link ComapiChatClient}
[ "Get", "global", "singleton", "of", "{", "@link", "ComapiChatClient", "}", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/ComapiChat.java#L104-L115
kite-sdk/kite
kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/shaded/org/apache/commons/codec/binary/binary/BaseNCodec.java
BaseNCodec.readResults
int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) { if (context.buffer != null) { final int len = Math.min(available(context), bAvail); System.arraycopy(context.buffer, context.readPos, b, bPos, len); context.readPos += len; if (context.readPos >= context.pos) { context.buffer = null; // so hasData() will return false, and this method can return -1 } return len; } return context.eof ? EOF : 0; }
java
int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) { if (context.buffer != null) { final int len = Math.min(available(context), bAvail); System.arraycopy(context.buffer, context.readPos, b, bPos, len); context.readPos += len; if (context.readPos >= context.pos) { context.buffer = null; // so hasData() will return false, and this method can return -1 } return len; } return context.eof ? EOF : 0; }
[ "int", "readResults", "(", "final", "byte", "[", "]", "b", ",", "final", "int", "bPos", ",", "final", "int", "bAvail", ",", "final", "Context", "context", ")", "{", "if", "(", "context", ".", "buffer", "!=", "null", ")", "{", "final", "int", "len", ...
Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes. Returns how many bytes were actually extracted. <p> Package protected for access from I/O streams. @param b byte[] array to extract the buffered data into. @param bPos position in byte[] array to start extraction at. @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available). @param context the context to be used @return The number of bytes successfully extracted into the provided byte[] array.
[ "Extracts", "buffered", "data", "into", "the", "provided", "byte", "[]", "array", "starting", "at", "position", "bPos", "up", "to", "a", "maximum", "of", "bAvail", "bytes", ".", "Returns", "how", "many", "bytes", "were", "actually", "extracted", ".", "<p", ...
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/shaded/org/apache/commons/codec/binary/binary/BaseNCodec.java#L265-L276
jenkinsci/jenkins
core/src/main/java/hudson/model/Computer.java
Computer.setTemporarilyOffline
public void setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause) { offlineCause = temporarilyOffline ? cause : null; this.temporarilyOffline = temporarilyOffline; Node node = getNode(); if (node != null) { node.setTemporaryOfflineCause(offlineCause); } synchronized (statusChangeLock) { statusChangeLock.notifyAll(); } for (ComputerListener cl : ComputerListener.all()) { if (temporarilyOffline) cl.onTemporarilyOffline(this,cause); else cl.onTemporarilyOnline(this); } }
java
public void setTemporarilyOffline(boolean temporarilyOffline, OfflineCause cause) { offlineCause = temporarilyOffline ? cause : null; this.temporarilyOffline = temporarilyOffline; Node node = getNode(); if (node != null) { node.setTemporaryOfflineCause(offlineCause); } synchronized (statusChangeLock) { statusChangeLock.notifyAll(); } for (ComputerListener cl : ComputerListener.all()) { if (temporarilyOffline) cl.onTemporarilyOffline(this,cause); else cl.onTemporarilyOnline(this); } }
[ "public", "void", "setTemporarilyOffline", "(", "boolean", "temporarilyOffline", ",", "OfflineCause", "cause", ")", "{", "offlineCause", "=", "temporarilyOffline", "?", "cause", ":", "null", ";", "this", ".", "temporarilyOffline", "=", "temporarilyOffline", ";", "No...
Marks the computer as temporarily offline. This retains the underlying {@link Channel} connection, but prevent builds from executing. @param cause If the first argument is true, specify the reason why the node is being put offline.
[ "Marks", "the", "computer", "as", "temporarily", "offline", ".", "This", "retains", "the", "underlying", "{", "@link", "Channel", "}", "connection", "but", "prevent", "builds", "from", "executing", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/Computer.java#L710-L724
prestodb/presto
presto-main/src/main/java/com/facebook/presto/execution/StateMachine.java
StateMachine.compareAndSet
public boolean compareAndSet(T expectedState, T newState) { checkState(!Thread.holdsLock(lock), "Can not set state while holding the lock"); requireNonNull(expectedState, "expectedState is null"); requireNonNull(newState, "newState is null"); FutureStateChange<T> futureStateChange; ImmutableList<StateChangeListener<T>> stateChangeListeners; synchronized (lock) { if (!state.equals(expectedState)) { return false; } // change to same state is not a change, and does not notify the notify listeners if (state.equals(newState)) { return false; } checkState(!isTerminalState(state), "%s can not transition from %s to %s", name, state, newState); state = newState; futureStateChange = this.futureStateChange.getAndSet(new FutureStateChange<>()); stateChangeListeners = ImmutableList.copyOf(this.stateChangeListeners); // if we are now in a terminal state, free the listeners since this will be the last notification if (isTerminalState(state)) { this.stateChangeListeners.clear(); } } fireStateChanged(newState, futureStateChange, stateChangeListeners); return true; }
java
public boolean compareAndSet(T expectedState, T newState) { checkState(!Thread.holdsLock(lock), "Can not set state while holding the lock"); requireNonNull(expectedState, "expectedState is null"); requireNonNull(newState, "newState is null"); FutureStateChange<T> futureStateChange; ImmutableList<StateChangeListener<T>> stateChangeListeners; synchronized (lock) { if (!state.equals(expectedState)) { return false; } // change to same state is not a change, and does not notify the notify listeners if (state.equals(newState)) { return false; } checkState(!isTerminalState(state), "%s can not transition from %s to %s", name, state, newState); state = newState; futureStateChange = this.futureStateChange.getAndSet(new FutureStateChange<>()); stateChangeListeners = ImmutableList.copyOf(this.stateChangeListeners); // if we are now in a terminal state, free the listeners since this will be the last notification if (isTerminalState(state)) { this.stateChangeListeners.clear(); } } fireStateChanged(newState, futureStateChange, stateChangeListeners); return true; }
[ "public", "boolean", "compareAndSet", "(", "T", "expectedState", ",", "T", "newState", ")", "{", "checkState", "(", "!", "Thread", ".", "holdsLock", "(", "lock", ")", ",", "\"Can not set state while holding the lock\"", ")", ";", "requireNonNull", "(", "expectedSt...
Sets the state if the current state {@code .equals()} the specified expected state. If the new state does not {@code .equals()} the current state, listeners and waiters will be notified. @return true if the state is set
[ "Sets", "the", "state", "if", "the", "current", "state", "{", "@code", ".", "equals", "()", "}", "the", "specified", "expected", "state", ".", "If", "the", "new", "state", "does", "not", "{", "@code", ".", "equals", "()", "}", "the", "current", "state"...
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/execution/StateMachine.java#L171-L204
GoogleCloudPlatform/appengine-pipelines
java/src/main/java/com/google/appengine/tools/pipeline/Job.java
Job.futureCall
public <T, T1> FutureValue<T> futureCall( Job1<T, T1> jobInstance, Value<? extends T1> v1, JobSetting... settings) { return futureCallUnchecked(settings, jobInstance, v1); }
java
public <T, T1> FutureValue<T> futureCall( Job1<T, T1> jobInstance, Value<? extends T1> v1, JobSetting... settings) { return futureCallUnchecked(settings, jobInstance, v1); }
[ "public", "<", "T", ",", "T1", ">", "FutureValue", "<", "T", ">", "futureCall", "(", "Job1", "<", "T", ",", "T1", ">", "jobInstance", ",", "Value", "<", "?", "extends", "T1", ">", "v1", ",", "JobSetting", "...", "settings", ")", "{", "return", "fut...
Invoke this method from within the {@code run} method of a <b>generator job</b> in order to specify a job node in the generated child job graph. This version of the method is for child jobs that take one argument. @param <T> The return type of the child job being specified @param <T1> The type of the first input to the child job @param jobInstance A user-written job object @param v1 the first input to the child job @param settings Optional one or more {@code JobSetting} @return a {@code FutureValue} representing an empty value slot that will be filled by the output of {@code jobInstance} when it finalizes. This may be passed in to further invocations of {@code futureCall()} in order to specify a data dependency.
[ "Invoke", "this", "method", "from", "within", "the", "{", "@code", "run", "}", "method", "of", "a", "<b", ">", "generator", "job<", "/", "b", ">", "in", "order", "to", "specify", "a", "job", "node", "in", "the", "generated", "child", "job", "graph", ...
train
https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/java/src/main/java/com/google/appengine/tools/pipeline/Job.java#L218-L221
dita-ot/dita-ot
src/main/java/org/dita/dost/util/FileUtils.java
FileUtils.getFragment
@Deprecated public static String getFragment(final String path, final String defaultValue) { final int i = path.indexOf(SHARP); if (i != -1) { return path.substring(i + 1); } else { return defaultValue; } }
java
@Deprecated public static String getFragment(final String path, final String defaultValue) { final int i = path.indexOf(SHARP); if (i != -1) { return path.substring(i + 1); } else { return defaultValue; } }
[ "@", "Deprecated", "public", "static", "String", "getFragment", "(", "final", "String", "path", ",", "final", "String", "defaultValue", ")", "{", "final", "int", "i", "=", "path", ".", "indexOf", "(", "SHARP", ")", ";", "if", "(", "i", "!=", "-", "1", ...
Get fragment part from path or return default fragment. @param path path @param defaultValue default fragment value @return fragment without {@link Constants#SHARP}, default value if no fragment exists
[ "Get", "fragment", "part", "from", "path", "or", "return", "default", "fragment", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/FileUtils.java#L592-L600
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/FSSpecStore.java
FSSpecStore.getURIFromPath
protected URI getURIFromPath(Path fsPath, Path fsSpecStoreDirPath) { return PathUtils.relativizePath(fsPath, fsSpecStoreDirPath).toUri(); }
java
protected URI getURIFromPath(Path fsPath, Path fsSpecStoreDirPath) { return PathUtils.relativizePath(fsPath, fsSpecStoreDirPath).toUri(); }
[ "protected", "URI", "getURIFromPath", "(", "Path", "fsPath", ",", "Path", "fsSpecStoreDirPath", ")", "{", "return", "PathUtils", ".", "relativizePath", "(", "fsPath", ",", "fsSpecStoreDirPath", ")", ".", "toUri", "(", ")", ";", "}" ]
Recover {@link Spec}'s URI from a file path. Note that there's no version awareness of this method, as Spec's version is currently not supported. @param fsPath The given file path to get URI from. @return The exact URI of a Spec.
[ "Recover", "{", "@link", "Spec", "}", "s", "URI", "from", "a", "file", "path", ".", "Note", "that", "there", "s", "no", "version", "awareness", "of", "this", "method", "as", "Spec", "s", "version", "is", "currently", "not", "supported", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/spec_store/FSSpecStore.java#L343-L345
greatman/craftconomy3
src/main/java/com/greatmancode/craftconomy3/converter/Converter.java
Converter.addAccountToString
protected void addAccountToString(String sender, List<User> userList2) { Common.getInstance().getServerCaller().getPlayerCaller().sendMessage(sender, "{{DARK_RED}}Converting accounts. This may take a while."); Common.getInstance().getStorageHandler().getStorageEngine().saveImporterUsers(userList2); Common.getInstance().getServerCaller().getPlayerCaller().sendMessage(sender, userList2.size() + " {{DARK_GREEN}}accounts converted! Enjoy!"); }
java
protected void addAccountToString(String sender, List<User> userList2) { Common.getInstance().getServerCaller().getPlayerCaller().sendMessage(sender, "{{DARK_RED}}Converting accounts. This may take a while."); Common.getInstance().getStorageHandler().getStorageEngine().saveImporterUsers(userList2); Common.getInstance().getServerCaller().getPlayerCaller().sendMessage(sender, userList2.size() + " {{DARK_GREEN}}accounts converted! Enjoy!"); }
[ "protected", "void", "addAccountToString", "(", "String", "sender", ",", "List", "<", "User", ">", "userList2", ")", "{", "Common", ".", "getInstance", "(", ")", ".", "getServerCaller", "(", ")", ".", "getPlayerCaller", "(", ")", ".", "sendMessage", "(", "...
Add the given accounts to the system @param sender The sender so we can send messages back to him @param userList2 Account list
[ "Add", "the", "given", "accounts", "to", "the", "system" ]
train
https://github.com/greatman/craftconomy3/blob/51b1b3de7d039e20c7418d1e70b8c4b02b8cf840/src/main/java/com/greatmancode/craftconomy3/converter/Converter.java#L165-L169
OpenLiberty/open-liberty
dev/wlp-mavenRepoTasks/src/com/ibm/ws/wlp/mavenFeatures/LibertyFeaturesToMavenRepo.java
LibertyFeaturesToMavenRepo.copyArtifact
private static void copyArtifact(File inputDir, File outputDir, LibertyFeature feature, Constants.ArtifactType type) throws MavenRepoGeneratorException { MavenCoordinates artifact = feature.getMavenCoordinates(); File artifactDir = new File(outputDir, Utils.getRepositorySubpath(artifact)); artifactDir.mkdirs(); if (!artifactDir.isDirectory()) { throw new MavenRepoGeneratorException("Artifact directory " + artifactDir + " could not be created."); } File sourceFile = new File(inputDir, feature.getSymbolicName() + type.getLibertyFileExtension()); System.out.println("Source file: " +sourceFile); if (!sourceFile.exists()) { throw new MavenRepoGeneratorException("Artifact source file " + sourceFile + " does not exist."); } File targetFile = new File(artifactDir, Utils.getFileName(artifact, type)); try { Files.copy(sourceFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new MavenRepoGeneratorException("Could not copy artifact from " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath(), e); } }
java
private static void copyArtifact(File inputDir, File outputDir, LibertyFeature feature, Constants.ArtifactType type) throws MavenRepoGeneratorException { MavenCoordinates artifact = feature.getMavenCoordinates(); File artifactDir = new File(outputDir, Utils.getRepositorySubpath(artifact)); artifactDir.mkdirs(); if (!artifactDir.isDirectory()) { throw new MavenRepoGeneratorException("Artifact directory " + artifactDir + " could not be created."); } File sourceFile = new File(inputDir, feature.getSymbolicName() + type.getLibertyFileExtension()); System.out.println("Source file: " +sourceFile); if (!sourceFile.exists()) { throw new MavenRepoGeneratorException("Artifact source file " + sourceFile + " does not exist."); } File targetFile = new File(artifactDir, Utils.getFileName(artifact, type)); try { Files.copy(sourceFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new MavenRepoGeneratorException("Could not copy artifact from " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath(), e); } }
[ "private", "static", "void", "copyArtifact", "(", "File", "inputDir", ",", "File", "outputDir", ",", "LibertyFeature", "feature", ",", "Constants", ".", "ArtifactType", "type", ")", "throws", "MavenRepoGeneratorException", "{", "MavenCoordinates", "artifact", "=", "...
Copy artifact file from inputDir to outputDir. @param inputDir The input directory containing feature files. @param outputDir The root directory of the target Maven repository. @param feature The feature that you want to copy. @param type The type of artifact. @throws MavenRepoGeneratorException If the artifact could not be copied.
[ "Copy", "artifact", "file", "from", "inputDir", "to", "outputDir", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp-mavenRepoTasks/src/com/ibm/ws/wlp/mavenFeatures/LibertyFeaturesToMavenRepo.java#L579-L601
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AbstractResource.java
AbstractResource.copyProperties
protected void copyProperties(Object dest, Object source) { try { BeanUtils.copyProperties(dest, source); } catch (Exception e) { String errorMessage = MessageFormat.format("M:{0};;E:{1}", e.getCause().getMessage(), e.toString()); throw new WebApplicationException(errorMessage, Status.BAD_REQUEST); } }
java
protected void copyProperties(Object dest, Object source) { try { BeanUtils.copyProperties(dest, source); } catch (Exception e) { String errorMessage = MessageFormat.format("M:{0};;E:{1}", e.getCause().getMessage(), e.toString()); throw new WebApplicationException(errorMessage, Status.BAD_REQUEST); } }
[ "protected", "void", "copyProperties", "(", "Object", "dest", ",", "Object", "source", ")", "{", "try", "{", "BeanUtils", ".", "copyProperties", "(", "dest", ",", "source", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "errorMessage", ...
Copies properties. @param dest The object to which the properties will be copied. @param source The object whose properties are copied @throws WebApplicationException Throws exception if beanutils encounter a problem.
[ "Copies", "properties", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AbstractResource.java#L248-L256
cdk/cdk
base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/Expr.java
Expr.setLogical
public void setLogical(Type type, Expr left, Expr right) { switch (type) { case AND: case OR: this.type = type; this.value = 0; this.left = left; this.right = right; this.query = null; break; case NOT: this.type = type; if (left != null && right == null) this.left = left; else if (left == null && right != null) this.left = right; else if (left != null) throw new IllegalArgumentException("Only one sub-expression" + " should be provided" + " for NOT expressions!"); this.query = null; this.value = 0; break; default: throw new IllegalArgumentException("Left/Right sub expressions " + "supplied for " + " non-logical operator!"); } }
java
public void setLogical(Type type, Expr left, Expr right) { switch (type) { case AND: case OR: this.type = type; this.value = 0; this.left = left; this.right = right; this.query = null; break; case NOT: this.type = type; if (left != null && right == null) this.left = left; else if (left == null && right != null) this.left = right; else if (left != null) throw new IllegalArgumentException("Only one sub-expression" + " should be provided" + " for NOT expressions!"); this.query = null; this.value = 0; break; default: throw new IllegalArgumentException("Left/Right sub expressions " + "supplied for " + " non-logical operator!"); } }
[ "public", "void", "setLogical", "(", "Type", "type", ",", "Expr", "left", ",", "Expr", "right", ")", "{", "switch", "(", "type", ")", "{", "case", "AND", ":", "case", "OR", ":", "this", ".", "type", "=", "type", ";", "this", ".", "value", "=", "0...
Set the logical value of this atom expression. @param type the type of expression @param left the left sub-expression @param right the right sub-expression
[ "Set", "the", "logical", "value", "of", "this", "atom", "expression", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/matchers/Expr.java#L595-L623
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.dedicated_server_serviceName_ip_duration_GET
public OvhOrder dedicated_server_serviceName_ip_duration_GET(String serviceName, String duration, OvhIpBlockSizeEnum blockSize, OvhIpCountryEnum country, String organisationId, OvhIpTypeOrderableEnum type) throws IOException { String qPath = "/order/dedicated/server/{serviceName}/ip/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); query(sb, "blockSize", blockSize); query(sb, "country", country); query(sb, "organisationId", organisationId); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder dedicated_server_serviceName_ip_duration_GET(String serviceName, String duration, OvhIpBlockSizeEnum blockSize, OvhIpCountryEnum country, String organisationId, OvhIpTypeOrderableEnum type) throws IOException { String qPath = "/order/dedicated/server/{serviceName}/ip/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); query(sb, "blockSize", blockSize); query(sb, "country", country); query(sb, "organisationId", organisationId); query(sb, "type", type); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "dedicated_server_serviceName_ip_duration_GET", "(", "String", "serviceName", ",", "String", "duration", ",", "OvhIpBlockSizeEnum", "blockSize", ",", "OvhIpCountryEnum", "country", ",", "String", "organisationId", ",", "OvhIpTypeOrderableEnum", "type", ...
Get prices and contracts information REST: GET /order/dedicated/server/{serviceName}/ip/{duration} @param blockSize [required] IP block size @param organisationId [required] Your organisation id to add on block informations @param country [required] IP localization @param type [required] The type of IP @param serviceName [required] The internal name of your dedicated server @param duration [required] Duration
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L2410-L2419
apache/flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/sharedbuffer/SharedBufferAccessor.java
SharedBufferAccessor.put
public NodeId put( final String stateName, final EventId eventId, @Nullable final NodeId previousNodeId, final DeweyNumber version) { if (previousNodeId != null) { lockNode(previousNodeId); } NodeId currentNodeId = new NodeId(eventId, getOriginalNameFromInternal(stateName)); Lockable<SharedBufferNode> currentNode = sharedBuffer.getEntry(currentNodeId); if (currentNode == null) { currentNode = new Lockable<>(new SharedBufferNode(), 0); lockEvent(eventId); } currentNode.getElement().addEdge(new SharedBufferEdge( previousNodeId, version)); sharedBuffer.upsertEntry(currentNodeId, currentNode); return currentNodeId; }
java
public NodeId put( final String stateName, final EventId eventId, @Nullable final NodeId previousNodeId, final DeweyNumber version) { if (previousNodeId != null) { lockNode(previousNodeId); } NodeId currentNodeId = new NodeId(eventId, getOriginalNameFromInternal(stateName)); Lockable<SharedBufferNode> currentNode = sharedBuffer.getEntry(currentNodeId); if (currentNode == null) { currentNode = new Lockable<>(new SharedBufferNode(), 0); lockEvent(eventId); } currentNode.getElement().addEdge(new SharedBufferEdge( previousNodeId, version)); sharedBuffer.upsertEntry(currentNodeId, currentNode); return currentNodeId; }
[ "public", "NodeId", "put", "(", "final", "String", "stateName", ",", "final", "EventId", "eventId", ",", "@", "Nullable", "final", "NodeId", "previousNodeId", ",", "final", "DeweyNumber", "version", ")", "{", "if", "(", "previousNodeId", "!=", "null", ")", "...
Stores given value (value + timestamp) under the given state. It assigns a preceding element relation to the previous entry. @param stateName name of the state that the event should be assigned to @param eventId unique id of event assigned by this SharedBuffer @param previousNodeId id of previous entry (might be null if start of new run) @param version Version of the previous relation @return assigned id of this element
[ "Stores", "given", "value", "(", "value", "+", "timestamp", ")", "under", "the", "given", "state", ".", "It", "assigns", "a", "preceding", "element", "relation", "to", "the", "previous", "entry", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/sharedbuffer/SharedBufferAccessor.java#L87-L110
tweea/matrixjavalib-main-common
src/main/java/net/matrix/util/Collections3.java
Collections3.extractToMap
public static Map extractToMap(final Collection collection, final String keyPropertyName, final String valuePropertyName) { Map map = new HashMap(collection.size()); try { for (Object obj : collection) { map.put(PropertyUtils.getProperty(obj, keyPropertyName), PropertyUtils.getProperty(obj, valuePropertyName)); } } catch (ReflectiveOperationException e) { throw new ReflectionRuntimeException(e); } return map; }
java
public static Map extractToMap(final Collection collection, final String keyPropertyName, final String valuePropertyName) { Map map = new HashMap(collection.size()); try { for (Object obj : collection) { map.put(PropertyUtils.getProperty(obj, keyPropertyName), PropertyUtils.getProperty(obj, valuePropertyName)); } } catch (ReflectiveOperationException e) { throw new ReflectionRuntimeException(e); } return map; }
[ "public", "static", "Map", "extractToMap", "(", "final", "Collection", "collection", ",", "final", "String", "keyPropertyName", ",", "final", "String", "valuePropertyName", ")", "{", "Map", "map", "=", "new", "HashMap", "(", "collection", ".", "size", "(", ")"...
提取集合中的对象的两个属性(通过 Getter 方法),组合成 Map。 @param collection 来源集合 @param keyPropertyName 要提取为 Map 中的 Key 值的属性名 @param valuePropertyName 要提取为 Map 中的 Value 值的属性名 @return 属性集合
[ "提取集合中的对象的两个属性(通过", "Getter", "方法),组合成", "Map。" ]
train
https://github.com/tweea/matrixjavalib-main-common/blob/ac8f98322a422e3ef76c3e12d47b98268cec7006/src/main/java/net/matrix/util/Collections3.java#L40-L52
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/util/LinkUtil.java
LinkUtil.adjustMappedUrl
protected static String adjustMappedUrl(SlingHttpServletRequest request, String url) { // build a pattern with the (false) default port Pattern defaultPortPattern = Pattern.compile( URL_PATTERN_STRING.replaceFirst("\\(:\\\\d\\+\\)\\?", ":" + getDefaultPort(request))); Matcher matcher = defaultPortPattern.matcher(url); // remove the port if the URL matches (contains the port nnumber) if (matcher.matches()) { if (null == matcher.group(1)) url = "//" + matcher.group(2); else url = matcher.group(1) + "://" + matcher.group(2); String uri = matcher.group(3); if (StringUtils.isNotBlank(uri)) { url += uri; } else { url += "/"; } } return url; }
java
protected static String adjustMappedUrl(SlingHttpServletRequest request, String url) { // build a pattern with the (false) default port Pattern defaultPortPattern = Pattern.compile( URL_PATTERN_STRING.replaceFirst("\\(:\\\\d\\+\\)\\?", ":" + getDefaultPort(request))); Matcher matcher = defaultPortPattern.matcher(url); // remove the port if the URL matches (contains the port nnumber) if (matcher.matches()) { if (null == matcher.group(1)) url = "//" + matcher.group(2); else url = matcher.group(1) + "://" + matcher.group(2); String uri = matcher.group(3); if (StringUtils.isNotBlank(uri)) { url += uri; } else { url += "/"; } } return url; }
[ "protected", "static", "String", "adjustMappedUrl", "(", "SlingHttpServletRequest", "request", ",", "String", "url", ")", "{", "// build a pattern with the (false) default port", "Pattern", "defaultPortPattern", "=", "Pattern", ".", "compile", "(", "URL_PATTERN_STRING", "."...
in the case of a forwarded SSL request the resource resolver mapping rules must contain the false port (80) to ensure a proper resolving - but in the result this bad port is included in the mapped URL and must be removed - done here
[ "in", "the", "case", "of", "a", "forwarded", "SSL", "request", "the", "resource", "resolver", "mapping", "rules", "must", "contain", "the", "false", "port", "(", "80", ")", "to", "ensure", "a", "proper", "resolving", "-", "but", "in", "the", "result", "t...
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/util/LinkUtil.java#L218-L235
padrig64/ValidationFramework
validationframework-core/src/main/java/com/google/code/validationframework/base/rule/string/StringRegexRule.java
StringRegexRule.addPattern
public void addPattern(final String pattern, final int flags) { patterns.put(pattern, Pattern.compile(pattern, flags)); }
java
public void addPattern(final String pattern, final int flags) { patterns.put(pattern, Pattern.compile(pattern, flags)); }
[ "public", "void", "addPattern", "(", "final", "String", "pattern", ",", "final", "int", "flags", ")", "{", "patterns", ".", "put", "(", "pattern", ",", "Pattern", ".", "compile", "(", "pattern", ",", "flags", ")", ")", ";", "}" ]
Adds the specified regular expression to be matched against the data to be validated, with the specified pattern flags.<br>Note that if you need the matching to be done strictly on the whole input data, you should surround the patterns with the '^' and '$' characters. @param pattern Regular expression to be added. @param flags Regular expression pattern flags.<br>Refer to {@link Pattern#compile(String, int)}. @see #addPattern(String) @see Matcher#find()
[ "Adds", "the", "specified", "regular", "expression", "to", "be", "matched", "against", "the", "data", "to", "be", "validated", "with", "the", "specified", "pattern", "flags", ".", "<br", ">", "Note", "that", "if", "you", "need", "the", "matching", "to", "b...
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-core/src/main/java/com/google/code/validationframework/base/rule/string/StringRegexRule.java#L103-L105
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java
RemoteInputChannel.assignExclusiveSegments
void assignExclusiveSegments(List<MemorySegment> segments) { checkState(this.initialCredit == 0, "Bug in input channel setup logic: exclusive buffers have " + "already been set for this input channel."); checkNotNull(segments); checkArgument(segments.size() > 0, "The number of exclusive buffers per channel should be larger than 0."); this.initialCredit = segments.size(); this.numRequiredBuffers = segments.size(); synchronized (bufferQueue) { for (MemorySegment segment : segments) { bufferQueue.addExclusiveBuffer(new NetworkBuffer(segment, this), numRequiredBuffers); } } }
java
void assignExclusiveSegments(List<MemorySegment> segments) { checkState(this.initialCredit == 0, "Bug in input channel setup logic: exclusive buffers have " + "already been set for this input channel."); checkNotNull(segments); checkArgument(segments.size() > 0, "The number of exclusive buffers per channel should be larger than 0."); this.initialCredit = segments.size(); this.numRequiredBuffers = segments.size(); synchronized (bufferQueue) { for (MemorySegment segment : segments) { bufferQueue.addExclusiveBuffer(new NetworkBuffer(segment, this), numRequiredBuffers); } } }
[ "void", "assignExclusiveSegments", "(", "List", "<", "MemorySegment", ">", "segments", ")", "{", "checkState", "(", "this", ".", "initialCredit", "==", "0", ",", "\"Bug in input channel setup logic: exclusive buffers have \"", "+", "\"already been set for this input channel.\...
Assigns exclusive buffers to this input channel, and this method should be called only once after this input channel is created.
[ "Assigns", "exclusive", "buffers", "to", "this", "input", "channel", "and", "this", "method", "should", "be", "called", "only", "once", "after", "this", "input", "channel", "is", "created", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java#L135-L150
antopen/alipay-sdk-java
src/main/java/com/alipay/api/internal/util/XmlUtils.java
XmlUtils.getElementValue
public static String getElementValue(Element parent, String tagName) { Element element = getChildElement(parent, tagName); if (element != null) { NodeList nodes = element.getChildNodes(); if (nodes != null && nodes.getLength() > 0) { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node instanceof Text) { return ((Text) node).getData(); } } } } return null; }
java
public static String getElementValue(Element parent, String tagName) { Element element = getChildElement(parent, tagName); if (element != null) { NodeList nodes = element.getChildNodes(); if (nodes != null && nodes.getLength() > 0) { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node instanceof Text) { return ((Text) node).getData(); } } } } return null; }
[ "public", "static", "String", "getElementValue", "(", "Element", "parent", ",", "String", "tagName", ")", "{", "Element", "element", "=", "getChildElement", "(", "parent", ",", "tagName", ")", ";", "if", "(", "element", "!=", "null", ")", "{", "NodeList", ...
Gets the value of the child element by tag name under the given parent element. If there is more than one child element, return the value of the first one. @param parent the parent element @param tagName the tag name of the child element @return value of the first child element, NULL if tag not exists
[ "Gets", "the", "value", "of", "the", "child", "element", "by", "tag", "name", "under", "the", "given", "parent", "element", ".", "If", "there", "is", "more", "than", "one", "child", "element", "return", "the", "value", "of", "the", "first", "one", "." ]
train
https://github.com/antopen/alipay-sdk-java/blob/e82aeac7d0239330ee173c7e393596e51e41c1cd/src/main/java/com/alipay/api/internal/util/XmlUtils.java#L303-L318
twitter/hraven
hraven-core/src/main/java/com/twitter/hraven/util/ByteUtil.java
ByteUtil.splitRanges
public static List<Range> splitRanges(byte[] source, byte[] separator, int limit) { List<Range> segments = new ArrayList<Range>(); int start = 0; itersource: for (int i = 0; i < source.length; i++) { for (int j = 0; j < separator.length; j++) { if (source[i + j] != separator[j]) { continue itersource; } } // all separator elements matched if (limit > 0 && segments.size() >= (limit-1)) { // everything else goes in one final segment break; } segments.add(new Range(start, i)); start = i + separator.length; // i will be incremented again in outer for loop i += separator.length-1; } // add in remaining to a final range if (start <= source.length) { segments.add(new Range(start, source.length)); } return segments; }
java
public static List<Range> splitRanges(byte[] source, byte[] separator, int limit) { List<Range> segments = new ArrayList<Range>(); int start = 0; itersource: for (int i = 0; i < source.length; i++) { for (int j = 0; j < separator.length; j++) { if (source[i + j] != separator[j]) { continue itersource; } } // all separator elements matched if (limit > 0 && segments.size() >= (limit-1)) { // everything else goes in one final segment break; } segments.add(new Range(start, i)); start = i + separator.length; // i will be incremented again in outer for loop i += separator.length-1; } // add in remaining to a final range if (start <= source.length) { segments.add(new Range(start, source.length)); } return segments; }
[ "public", "static", "List", "<", "Range", ">", "splitRanges", "(", "byte", "[", "]", "source", ",", "byte", "[", "]", "separator", ",", "int", "limit", ")", "{", "List", "<", "Range", ">", "segments", "=", "new", "ArrayList", "<", "Range", ">", "(", ...
Returns a list of ranges identifying [start, end) -- closed, open -- positions within the source byte array that would be split using the separator byte array. @param source the source data @param separator the separator pattern to look for @param limit the maximum number of splits to identify in the source
[ "Returns", "a", "list", "of", "ranges", "identifying", "[", "start", "end", ")", "--", "closed", "open", "--", "positions", "within", "the", "source", "byte", "array", "that", "would", "be", "split", "using", "the", "separator", "byte", "array", "." ]
train
https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/util/ByteUtil.java#L129-L154
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/plugins/BaseScriptPlugin.java
BaseScriptPlugin.runPluginScript
protected int runPluginScript( final PluginStepContext executionContext, final PrintStream outputStream, final PrintStream errorStream, final Framework framework, final Map<String, Object> configuration ) throws IOException, InterruptedException, ConfigurationException { Description pluginDesc = getDescription(); final DataContext localDataContext = createScriptDataContext( framework, executionContext.getFrameworkProject(), executionContext.getDataContext() ); Map<String, Object> instanceData = new HashMap<>(configuration); Map<String, String> data = MapData.toStringStringMap(instanceData); loadContentConversionPropertyValues( data, executionContext.getExecutionContext(), pluginDesc.getProperties() ); localDataContext.merge(new BaseDataContext("config", data)); final String[] finalargs = createScriptArgs(localDataContext); executionContext.getLogger().log(3, "[" + getProvider().getName() + "] executing: " + Arrays.asList( finalargs)); Map<String, String> envMap = new HashMap<>(); if (isMergeEnvVars()) { envMap.putAll(getScriptExecHelper().loadLocalEnvironment()); } envMap.putAll(DataContextUtils.generateEnvVarsFromContext(localDataContext)); return getScriptExecHelper().runLocalCommand( finalargs, envMap, null, outputStream, errorStream ); }
java
protected int runPluginScript( final PluginStepContext executionContext, final PrintStream outputStream, final PrintStream errorStream, final Framework framework, final Map<String, Object> configuration ) throws IOException, InterruptedException, ConfigurationException { Description pluginDesc = getDescription(); final DataContext localDataContext = createScriptDataContext( framework, executionContext.getFrameworkProject(), executionContext.getDataContext() ); Map<String, Object> instanceData = new HashMap<>(configuration); Map<String, String> data = MapData.toStringStringMap(instanceData); loadContentConversionPropertyValues( data, executionContext.getExecutionContext(), pluginDesc.getProperties() ); localDataContext.merge(new BaseDataContext("config", data)); final String[] finalargs = createScriptArgs(localDataContext); executionContext.getLogger().log(3, "[" + getProvider().getName() + "] executing: " + Arrays.asList( finalargs)); Map<String, String> envMap = new HashMap<>(); if (isMergeEnvVars()) { envMap.putAll(getScriptExecHelper().loadLocalEnvironment()); } envMap.putAll(DataContextUtils.generateEnvVarsFromContext(localDataContext)); return getScriptExecHelper().runLocalCommand( finalargs, envMap, null, outputStream, errorStream ); }
[ "protected", "int", "runPluginScript", "(", "final", "PluginStepContext", "executionContext", ",", "final", "PrintStream", "outputStream", ",", "final", "PrintStream", "errorStream", ",", "final", "Framework", "framework", ",", "final", "Map", "<", "String", ",", "O...
Runs the script configured for the script plugin and channels the output to two streams. @param executionContext context @param outputStream output stream @param errorStream error stream @param framework fwlk @param configuration configuration @return exit code @throws IOException if any IO exception occurs @throws InterruptedException if interrupted while waiting for the command to finish
[ "Runs", "the", "script", "configured", "for", "the", "script", "plugin", "and", "channels", "the", "output", "to", "two", "streams", "." ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/BaseScriptPlugin.java#L77-L119
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/UTF8ByteArrayUtils.java
UTF8ByteArrayUtils.findNthByte
public static int findNthByte(byte [] utf, byte b, int n) { return findNthByte(utf, 0, utf.length, b, n); }
java
public static int findNthByte(byte [] utf, byte b, int n) { return findNthByte(utf, 0, utf.length, b, n); }
[ "public", "static", "int", "findNthByte", "(", "byte", "[", "]", "utf", ",", "byte", "b", ",", "int", "n", ")", "{", "return", "findNthByte", "(", "utf", ",", "0", ",", "utf", ".", "length", ",", "b", ",", "n", ")", ";", "}" ]
Find the nth occurrence of the given byte b in a UTF-8 encoded string @param utf a byte array containing a UTF-8 encoded string @param b the byte to find @param n the desired occurrence of the given byte @return position that nth occurrence of the given byte if exists; otherwise -1
[ "Find", "the", "nth", "occurrence", "of", "the", "given", "byte", "b", "in", "a", "UTF", "-", "8", "encoded", "string" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/UTF8ByteArrayUtils.java#L93-L95
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java
InboundHttp2ToHttpAdapter.removeMessage
protected final void removeMessage(Http2Stream stream, boolean release) { FullHttpMessage msg = stream.removeProperty(messageKey); if (release && msg != null) { msg.release(); } }
java
protected final void removeMessage(Http2Stream stream, boolean release) { FullHttpMessage msg = stream.removeProperty(messageKey); if (release && msg != null) { msg.release(); } }
[ "protected", "final", "void", "removeMessage", "(", "Http2Stream", "stream", ",", "boolean", "release", ")", "{", "FullHttpMessage", "msg", "=", "stream", ".", "removeProperty", "(", "messageKey", ")", ";", "if", "(", "release", "&&", "msg", "!=", "null", ")...
The stream is out of scope for the HTTP message flow and will no longer be tracked @param stream The stream to remove associated state with @param release {@code true} to call release on the value if it is present. {@code false} to not call release.
[ "The", "stream", "is", "out", "of", "scope", "for", "the", "HTTP", "message", "flow", "and", "will", "no", "longer", "be", "tracked" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java#L93-L98
opencb/biodata
biodata-tools/src/main/java/org/opencb/biodata/tools/variant/algorithm/IdentityByStateClustering.java
IdentityByStateClustering.getCompoundIndex
public int getCompoundIndex(int first, int second) { if (first >= second) { throw new IllegalArgumentException("first (" + first + ") and second (" + second + ") sample indexes, must comply with: 0 <= first < second"); } return (second*second - second)/2 + first; }
java
public int getCompoundIndex(int first, int second) { if (first >= second) { throw new IllegalArgumentException("first (" + first + ") and second (" + second + ") sample indexes, must comply with: 0 <= first < second"); } return (second*second - second)/2 + first; }
[ "public", "int", "getCompoundIndex", "(", "int", "first", ",", "int", "second", ")", "{", "if", "(", "first", ">=", "second", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"first (\"", "+", "first", "+", "\") and second (\"", "+", "second", "+...
j /_0__1__2__3__4_ i 0| - 0 1 3 6 | 1| - 2 4 7 | 2| - 5 8 | 3| - 9 | 4| - | `(j*(j-1)) / 2` is the amount of numbers in the triangular matrix before the column `j`. for example, with i=2, j=4: (j*(j-1)) / 2 == 6; 6+i == 8
[ "j", "/", "_0__1__2__3__4_", "i", "0|", "-", "0", "1", "3", "6", "|", "1|", "-", "2", "4", "7", "|", "2|", "-", "5", "8", "|", "3|", "-", "9", "|", "4|", "-", "|" ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/variant/algorithm/IdentityByStateClustering.java#L169-L176
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapserMetrics.java
HystrixCollapserMetrics.getInstance
public static HystrixCollapserMetrics getInstance(HystrixCollapserKey key, HystrixCollapserProperties properties) { // attempt to retrieve from cache first HystrixCollapserMetrics collapserMetrics = metrics.get(key.name()); if (collapserMetrics != null) { return collapserMetrics; } // it doesn't exist so we need to create it collapserMetrics = new HystrixCollapserMetrics(key, properties); // attempt to store it (race other threads) HystrixCollapserMetrics existing = metrics.putIfAbsent(key.name(), collapserMetrics); if (existing == null) { // we won the thread-race to store the instance we created return collapserMetrics; } else { // we lost so return 'existing' and let the one we created be garbage collected return existing; } }
java
public static HystrixCollapserMetrics getInstance(HystrixCollapserKey key, HystrixCollapserProperties properties) { // attempt to retrieve from cache first HystrixCollapserMetrics collapserMetrics = metrics.get(key.name()); if (collapserMetrics != null) { return collapserMetrics; } // it doesn't exist so we need to create it collapserMetrics = new HystrixCollapserMetrics(key, properties); // attempt to store it (race other threads) HystrixCollapserMetrics existing = metrics.putIfAbsent(key.name(), collapserMetrics); if (existing == null) { // we won the thread-race to store the instance we created return collapserMetrics; } else { // we lost so return 'existing' and let the one we created be garbage collected return existing; } }
[ "public", "static", "HystrixCollapserMetrics", "getInstance", "(", "HystrixCollapserKey", "key", ",", "HystrixCollapserProperties", "properties", ")", "{", "// attempt to retrieve from cache first", "HystrixCollapserMetrics", "collapserMetrics", "=", "metrics", ".", "get", "(",...
Get or create the {@link HystrixCollapserMetrics} instance for a given {@link HystrixCollapserKey}. <p> This is thread-safe and ensures only 1 {@link HystrixCollapserMetrics} per {@link HystrixCollapserKey}. @param key {@link HystrixCollapserKey} of {@link HystrixCollapser} instance requesting the {@link HystrixCollapserMetrics} @return {@link HystrixCollapserMetrics}
[ "Get", "or", "create", "the", "{", "@link", "HystrixCollapserMetrics", "}", "instance", "for", "a", "given", "{", "@link", "HystrixCollapserKey", "}", ".", "<p", ">", "This", "is", "thread", "-", "safe", "and", "ensures", "only", "1", "{", "@link", "Hystri...
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapserMetrics.java#L54-L71
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/AutomationAccountsInner.java
AutomationAccountsInner.updateAsync
public Observable<AutomationAccountInner> updateAsync(String resourceGroupName, String automationAccountName, AutomationAccountUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, parameters).map(new Func1<ServiceResponse<AutomationAccountInner>, AutomationAccountInner>() { @Override public AutomationAccountInner call(ServiceResponse<AutomationAccountInner> response) { return response.body(); } }); }
java
public Observable<AutomationAccountInner> updateAsync(String resourceGroupName, String automationAccountName, AutomationAccountUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, parameters).map(new Func1<ServiceResponse<AutomationAccountInner>, AutomationAccountInner>() { @Override public AutomationAccountInner call(ServiceResponse<AutomationAccountInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "AutomationAccountInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "AutomationAccountUpdateParameters", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resourceG...
Update an automation account. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param parameters Parameters supplied to the update automation account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the AutomationAccountInner object
[ "Update", "an", "automation", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/AutomationAccountsInner.java#L142-L149
OpenLiberty/open-liberty
dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/DataModelSerializer.java
DataModelSerializer.internalGetClassForFieldName
private static ClassAndMethod internalGetClassForFieldName(String fieldName, Class<?> classToLookForFieldIn, boolean isForArray) { Method found = null; //precalc the field name as a setter to use for each method test. String fieldNameAsASetter = new StringBuilder("set").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1)).toString(); //hunt for any matching setter in the object for (Method m : classToLookForFieldIn.getMethods()) { String methodName = m.getName(); //eligible setters must only accept a single argument. if (m.getParameterTypes().length == 1 && methodName.equals(fieldNameAsASetter)) { found = m; break; } } //at the mo, if we don't match a setter, we sysout a warning, this will likely need to become a toggle. if (found == null) { if (DataModelSerializer.IGNORE_UNKNOWN_FIELDS) { return null; } else { throw new IllegalStateException("Data Model Error: Found unexpected JSON field " + fieldName + " supposedly for in class " + classToLookForFieldIn.getName()); } } else { ClassAndMethod cm = new ClassAndMethod(); cm.m = found; if (isForArray) { //for an array we return the type of the collection, eg String for List<String> instead of List. Type t = found.getGenericParameterTypes()[0]; cm.cls = getClassForType(t); return cm; } else { cm.cls = found.getParameterTypes()[0]; return cm; } } }
java
private static ClassAndMethod internalGetClassForFieldName(String fieldName, Class<?> classToLookForFieldIn, boolean isForArray) { Method found = null; //precalc the field name as a setter to use for each method test. String fieldNameAsASetter = new StringBuilder("set").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1)).toString(); //hunt for any matching setter in the object for (Method m : classToLookForFieldIn.getMethods()) { String methodName = m.getName(); //eligible setters must only accept a single argument. if (m.getParameterTypes().length == 1 && methodName.equals(fieldNameAsASetter)) { found = m; break; } } //at the mo, if we don't match a setter, we sysout a warning, this will likely need to become a toggle. if (found == null) { if (DataModelSerializer.IGNORE_UNKNOWN_FIELDS) { return null; } else { throw new IllegalStateException("Data Model Error: Found unexpected JSON field " + fieldName + " supposedly for in class " + classToLookForFieldIn.getName()); } } else { ClassAndMethod cm = new ClassAndMethod(); cm.m = found; if (isForArray) { //for an array we return the type of the collection, eg String for List<String> instead of List. Type t = found.getGenericParameterTypes()[0]; cm.cls = getClassForType(t); return cm; } else { cm.cls = found.getParameterTypes()[0]; return cm; } } }
[ "private", "static", "ClassAndMethod", "internalGetClassForFieldName", "(", "String", "fieldName", ",", "Class", "<", "?", ">", "classToLookForFieldIn", ",", "boolean", "isForArray", ")", "{", "Method", "found", "=", "null", ";", "//precalc the field name as a setter to...
Utility method, given a JSON field name, and an associated POJO, it will hunt for the appropriate setter to use, and if located return the type the setter expects, along with a reflected reference to the method itself. @param fieldName the name of the json key being queried. @param classToLookForFieldIn the object to hunt within for appropriate setters. @param isForArray true, if the setter is expected to be for a collection, based on if the json data was an array. @return instance of ClassAndMethod associating the class and method for the setter.
[ "Utility", "method", "given", "a", "JSON", "field", "name", "and", "an", "associated", "POJO", "it", "will", "hunt", "for", "the", "appropriate", "setter", "to", "use", "and", "if", "located", "return", "the", "type", "the", "setter", "expects", "along", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository/src/com/ibm/ws/repository/transport/client/DataModelSerializer.java#L420-L456
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/block/MatrixOps_DDRB.java
MatrixOps_DDRB.convertTranSrc
public static void convertTranSrc(DMatrixRMaj src , DMatrixRBlock dst ) { if( src.numRows != dst.numCols || src.numCols != dst.numRows ) throw new IllegalArgumentException("Incompatible matrix shapes."); for( int i = 0; i < dst.numRows; i += dst.blockLength ) { int blockHeight = Math.min( dst.blockLength , dst.numRows - i); for( int j = 0; j < dst.numCols; j += dst.blockLength ) { int blockWidth = Math.min( dst.blockLength , dst.numCols - j); int indexDst = i*dst.numCols + blockHeight*j; int indexSrc = j*src.numCols + i; for( int l = 0; l < blockWidth; l++ ) { int rowSrc = indexSrc + l*src.numCols; int rowDst = indexDst + l; for( int k = 0; k < blockHeight; k++ , rowDst += blockWidth ) { dst.data[ rowDst ] = src.data[rowSrc++]; } } } } }
java
public static void convertTranSrc(DMatrixRMaj src , DMatrixRBlock dst ) { if( src.numRows != dst.numCols || src.numCols != dst.numRows ) throw new IllegalArgumentException("Incompatible matrix shapes."); for( int i = 0; i < dst.numRows; i += dst.blockLength ) { int blockHeight = Math.min( dst.blockLength , dst.numRows - i); for( int j = 0; j < dst.numCols; j += dst.blockLength ) { int blockWidth = Math.min( dst.blockLength , dst.numCols - j); int indexDst = i*dst.numCols + blockHeight*j; int indexSrc = j*src.numCols + i; for( int l = 0; l < blockWidth; l++ ) { int rowSrc = indexSrc + l*src.numCols; int rowDst = indexDst + l; for( int k = 0; k < blockHeight; k++ , rowDst += blockWidth ) { dst.data[ rowDst ] = src.data[rowSrc++]; } } } } }
[ "public", "static", "void", "convertTranSrc", "(", "DMatrixRMaj", "src", ",", "DMatrixRBlock", "dst", ")", "{", "if", "(", "src", ".", "numRows", "!=", "dst", ".", "numCols", "||", "src", ".", "numCols", "!=", "dst", ".", "numRows", ")", "throw", "new", ...
Converts the transpose of a row major matrix into a row major block matrix. @param src Original DMatrixRMaj. Not modified. @param dst Equivalent DMatrixRBlock. Modified.
[ "Converts", "the", "transpose", "of", "a", "row", "major", "matrix", "into", "a", "row", "major", "block", "matrix", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/block/MatrixOps_DDRB.java#L146-L169
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java
SynchronousRequest.getCurrencyInfo
public List<Currency> getCurrencyInfo(int[] ids) throws GuildWars2Exception { isParamValid(new ParamChecker(ids)); try { Response<List<Currency>> response = gw2API.getCurrencyInfo(processIds(ids), GuildWars2.lang.getValue()).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody()); return response.body(); } catch (IOException e) { throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage()); } }
java
public List<Currency> getCurrencyInfo(int[] ids) throws GuildWars2Exception { isParamValid(new ParamChecker(ids)); try { Response<List<Currency>> response = gw2API.getCurrencyInfo(processIds(ids), GuildWars2.lang.getValue()).execute(); if (!response.isSuccessful()) throwError(response.code(), response.errorBody()); return response.body(); } catch (IOException e) { throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage()); } }
[ "public", "List", "<", "Currency", ">", "getCurrencyInfo", "(", "int", "[", "]", "ids", ")", "throws", "GuildWars2Exception", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ids", ")", ")", ";", "try", "{", "Response", "<", "List", "<", "Currency", ...
For more info on Currency API go <a href="https://wiki.guildwars2.com/wiki/API:2/currencies">here</a><br/> Get currency info for the given currency id(s) @param ids list of currency id @return list of currency info @throws GuildWars2Exception see {@link ErrorCode} for detail @see Currency currency info
[ "For", "more", "info", "on", "Currency", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "currencies", ">", "here<", "/", "a", ">", "<br", "/", ">", "Get", "curren...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L1686-L1695
wildfly/wildfly-core
protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java
AbstractMessageHandler.awaitCompletion
@Override public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { long deadline = unit.toMillis(timeout) + System.currentTimeMillis(); lock.lock(); try { assert shutdown; while(activeCount != 0) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } condition.await(remaining, TimeUnit.MILLISECONDS); } boolean allComplete = activeCount == 0; if (!allComplete) { ProtocolLogger.ROOT_LOGGER.debugf("ActiveOperation(s) %s have not completed within %d %s", activeRequests.keySet(), timeout, unit); } return allComplete; } finally { lock.unlock(); } }
java
@Override public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { long deadline = unit.toMillis(timeout) + System.currentTimeMillis(); lock.lock(); try { assert shutdown; while(activeCount != 0) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } condition.await(remaining, TimeUnit.MILLISECONDS); } boolean allComplete = activeCount == 0; if (!allComplete) { ProtocolLogger.ROOT_LOGGER.debugf("ActiveOperation(s) %s have not completed within %d %s", activeRequests.keySet(), timeout, unit); } return allComplete; } finally { lock.unlock(); } }
[ "@", "Override", "public", "boolean", "awaitCompletion", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "long", "deadline", "=", "unit", ".", "toMillis", "(", "timeout", ")", "+", "System", ".", "currentTimeMillis", ...
Await the completion of all currently active operations. @param timeout the timeout @param unit the time unit @return {@code } false if the timeout was reached and there were still active operations @throws InterruptedException
[ "Await", "the", "completion", "of", "all", "currently", "active", "operations", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java#L161-L181
rampatra/jbot
jbot/src/main/java/me/ramswaroop/jbot/core/facebook/Bot.java
Bot.startConversation
protected final void startConversation(Event event, String methodName) { startConversation(event.getSender().getId(), methodName); }
java
protected final void startConversation(Event event, String methodName) { startConversation(event.getSender().getId(), methodName); }
[ "protected", "final", "void", "startConversation", "(", "Event", "event", ",", "String", "methodName", ")", "{", "startConversation", "(", "event", ".", "getSender", "(", ")", ".", "getId", "(", ")", ",", "methodName", ")", ";", "}" ]
Call this method to start a conversation. @param event received from facebook
[ "Call", "this", "method", "to", "start", "a", "conversation", "." ]
train
https://github.com/rampatra/jbot/blob/0f42e1a6ec4dcbc5d1257e1307704903e771f7b5/jbot/src/main/java/me/ramswaroop/jbot/core/facebook/Bot.java#L229-L231
apereo/cas
support/cas-server-support-openid/src/main/java/org/apereo/cas/web/DelegatingController.java
DelegatingController.generateErrorView
private ModelAndView generateErrorView(final String code, final Object[] args) { val modelAndView = new ModelAndView(this.failureView); val convertedDescription = getMessageSourceAccessor().getMessage(code, args, code); modelAndView.addObject("code", StringEscapeUtils.escapeHtml4(code)); modelAndView.addObject("description", StringEscapeUtils.escapeHtml4(convertedDescription)); return modelAndView; }
java
private ModelAndView generateErrorView(final String code, final Object[] args) { val modelAndView = new ModelAndView(this.failureView); val convertedDescription = getMessageSourceAccessor().getMessage(code, args, code); modelAndView.addObject("code", StringEscapeUtils.escapeHtml4(code)); modelAndView.addObject("description", StringEscapeUtils.escapeHtml4(convertedDescription)); return modelAndView; }
[ "private", "ModelAndView", "generateErrorView", "(", "final", "String", "code", ",", "final", "Object", "[", "]", "args", ")", "{", "val", "modelAndView", "=", "new", "ModelAndView", "(", "this", ".", "failureView", ")", ";", "val", "convertedDescription", "="...
Generate error view based on {@link #setFailureView(String)}. @param code the code @param args the args @return the model and view
[ "Generate", "error", "view", "based", "on", "{", "@link", "#setFailureView", "(", "String", ")", "}", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-openid/src/main/java/org/apereo/cas/web/DelegatingController.java#L66-L72
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.endsWith
private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) { if (str == null || suffix == null) { return str == null && suffix == null; } if (suffix.length() > str.length()) { return false; } final int strOffset = str.length() - suffix.length(); return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length()); }
java
private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) { if (str == null || suffix == null) { return str == null && suffix == null; } if (suffix.length() > str.length()) { return false; } final int strOffset = str.length() - suffix.length(); return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length()); }
[ "private", "static", "boolean", "endsWith", "(", "final", "CharSequence", "str", ",", "final", "CharSequence", "suffix", ",", "final", "boolean", "ignoreCase", ")", "{", "if", "(", "str", "==", "null", "||", "suffix", "==", "null", ")", "{", "return", "str...
<p>Check if a CharSequence ends with a specified suffix (optionally case insensitive).</p> @see java.lang.String#endsWith(String) @param str the CharSequence to check, may be null @param suffix the suffix to find, may be null @param ignoreCase indicates whether the compare should ignore case (case insensitive) or not. @return {@code true} if the CharSequence starts with the prefix or both {@code null}
[ "<p", ">", "Check", "if", "a", "CharSequence", "ends", "with", "a", "specified", "suffix", "(", "optionally", "case", "insensitive", ")", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L8639-L8648
UrielCh/ovh-java-sdk
ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java
ApiOvhEmaildomain.domain_confirmTermination_POST
public String domain_confirmTermination_POST(String domain, String commentary, OvhTerminationReasonEnum reason, String token) throws IOException { String qPath = "/email/domain/{domain}/confirmTermination"; StringBuilder sb = path(qPath, domain); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "commentary", commentary); addBody(o, "reason", reason); addBody(o, "token", token); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
java
public String domain_confirmTermination_POST(String domain, String commentary, OvhTerminationReasonEnum reason, String token) throws IOException { String qPath = "/email/domain/{domain}/confirmTermination"; StringBuilder sb = path(qPath, domain); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "commentary", commentary); addBody(o, "reason", reason); addBody(o, "token", token); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, String.class); }
[ "public", "String", "domain_confirmTermination_POST", "(", "String", "domain", ",", "String", "commentary", ",", "OvhTerminationReasonEnum", "reason", ",", "String", "token", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/domain/{domain}/confirmTermi...
Confirm termination of your email service REST: POST /email/domain/{domain}/confirmTermination @param reason [required] Reason of your termination request @param commentary [required] Commentary about your termination request @param token [required] The termination token sent by mail to the admin contact @param domain [required] Name of your domain name
[ "Confirm", "termination", "of", "your", "email", "service" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L1261-L1270
protostuff/protostuff
protostuff-yaml/src/main/java/io/protostuff/YamlIOUtil.java
YamlIOUtil.writeTo
public static <T> int writeTo(OutputStream out, T message, Schema<T> schema, LinkedBuffer buffer) throws IOException { if (buffer.start != buffer.offset) throw new IllegalArgumentException("Buffer previously used and had not been reset."); final YamlOutput output = new YamlOutput(buffer, out, schema); output.tail = YamlOutput.writeTag( schema.messageName(), false, output.sink, output, output.sink.writeByteArray( START_DIRECTIVE, output, buffer)); schema.writeTo(output, message); LinkedBuffer.writeTo(out, buffer); return output.getSize(); }
java
public static <T> int writeTo(OutputStream out, T message, Schema<T> schema, LinkedBuffer buffer) throws IOException { if (buffer.start != buffer.offset) throw new IllegalArgumentException("Buffer previously used and had not been reset."); final YamlOutput output = new YamlOutput(buffer, out, schema); output.tail = YamlOutput.writeTag( schema.messageName(), false, output.sink, output, output.sink.writeByteArray( START_DIRECTIVE, output, buffer)); schema.writeTo(output, message); LinkedBuffer.writeTo(out, buffer); return output.getSize(); }
[ "public", "static", "<", "T", ">", "int", "writeTo", "(", "OutputStream", "out", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ",", "LinkedBuffer", "buffer", ")", "throws", "IOException", "{", "if", "(", "buffer", ".", "start", "!=", "bu...
Serializes the {@code message} into an {@link OutputStream} with the supplied buffer. @return the total bytes written to the output.
[ "Serializes", "the", "{", "@code", "message", "}", "into", "an", "{", "@link", "OutputStream", "}", "with", "the", "supplied", "buffer", "." ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-yaml/src/main/java/io/protostuff/YamlIOUtil.java#L107-L130
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java
CheckpointCoordinator.restoreSavepoint
public boolean restoreSavepoint( String savepointPointer, boolean allowNonRestored, Map<JobVertexID, ExecutionJobVertex> tasks, ClassLoader userClassLoader) throws Exception { Preconditions.checkNotNull(savepointPointer, "The savepoint path cannot be null."); LOG.info("Starting job {} from savepoint {} ({})", job, savepointPointer, (allowNonRestored ? "allowing non restored state" : "")); final CompletedCheckpointStorageLocation checkpointLocation = checkpointStorage.resolveCheckpoint(savepointPointer); // Load the savepoint as a checkpoint into the system CompletedCheckpoint savepoint = Checkpoints.loadAndValidateCheckpoint( job, tasks, checkpointLocation, userClassLoader, allowNonRestored); completedCheckpointStore.addCheckpoint(savepoint); // Reset the checkpoint ID counter long nextCheckpointId = savepoint.getCheckpointID() + 1; checkpointIdCounter.setCount(nextCheckpointId); LOG.info("Reset the checkpoint ID of job {} to {}.", job, nextCheckpointId); return restoreLatestCheckpointedState(tasks, true, allowNonRestored); }
java
public boolean restoreSavepoint( String savepointPointer, boolean allowNonRestored, Map<JobVertexID, ExecutionJobVertex> tasks, ClassLoader userClassLoader) throws Exception { Preconditions.checkNotNull(savepointPointer, "The savepoint path cannot be null."); LOG.info("Starting job {} from savepoint {} ({})", job, savepointPointer, (allowNonRestored ? "allowing non restored state" : "")); final CompletedCheckpointStorageLocation checkpointLocation = checkpointStorage.resolveCheckpoint(savepointPointer); // Load the savepoint as a checkpoint into the system CompletedCheckpoint savepoint = Checkpoints.loadAndValidateCheckpoint( job, tasks, checkpointLocation, userClassLoader, allowNonRestored); completedCheckpointStore.addCheckpoint(savepoint); // Reset the checkpoint ID counter long nextCheckpointId = savepoint.getCheckpointID() + 1; checkpointIdCounter.setCount(nextCheckpointId); LOG.info("Reset the checkpoint ID of job {} to {}.", job, nextCheckpointId); return restoreLatestCheckpointedState(tasks, true, allowNonRestored); }
[ "public", "boolean", "restoreSavepoint", "(", "String", "savepointPointer", ",", "boolean", "allowNonRestored", ",", "Map", "<", "JobVertexID", ",", "ExecutionJobVertex", ">", "tasks", ",", "ClassLoader", "userClassLoader", ")", "throws", "Exception", "{", "Preconditi...
Restore the state with given savepoint. @param savepointPointer The pointer to the savepoint. @param allowNonRestored True if allowing checkpoint state that cannot be mapped to any job vertex in tasks. @param tasks Map of job vertices to restore. State for these vertices is restored via {@link Execution#setInitialState(JobManagerTaskRestore)}. @param userClassLoader The class loader to resolve serialized classes in legacy savepoint versions.
[ "Restore", "the", "state", "with", "given", "savepoint", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java#L1144-L1170
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.recoverDeletedStorageAccountAsync
public ServiceFuture<StorageBundle> recoverDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName, final ServiceCallback<StorageBundle> serviceCallback) { return ServiceFuture.fromResponse(recoverDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName), serviceCallback); }
java
public ServiceFuture<StorageBundle> recoverDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName, final ServiceCallback<StorageBundle> serviceCallback) { return ServiceFuture.fromResponse(recoverDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName), serviceCallback); }
[ "public", "ServiceFuture", "<", "StorageBundle", ">", "recoverDeletedStorageAccountAsync", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ",", "final", "ServiceCallback", "<", "StorageBundle", ">", "serviceCallback", ")", "{", "return", "ServiceFuture...
Recovers the deleted storage account. Recovers the deleted storage account in the specified vault. This operation can only be performed on a soft-delete enabled vault. This operation requires the storage/recover permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Recovers", "the", "deleted", "storage", "account", ".", "Recovers", "the", "deleted", "storage", "account", "in", "the", "specified", "vault", ".", "This", "operation", "can", "only", "be", "performed", "on", "a", "soft", "-", "delete", "enabled", "vault", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9446-L9448
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java
DateFormat.getInstanceForSkeleton
public final static DateFormat getInstanceForSkeleton(Calendar cal, String skeleton, Locale locale) { return getPatternInstance(cal, skeleton, ULocale.forLocale(locale)); }
java
public final static DateFormat getInstanceForSkeleton(Calendar cal, String skeleton, Locale locale) { return getPatternInstance(cal, skeleton, ULocale.forLocale(locale)); }
[ "public", "final", "static", "DateFormat", "getInstanceForSkeleton", "(", "Calendar", "cal", ",", "String", "skeleton", ",", "Locale", "locale", ")", "{", "return", "getPatternInstance", "(", "cal", ",", "skeleton", ",", "ULocale", ".", "forLocale", "(", "locale...
<strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and times in the calendar system specified by <code>cal</code>. @param cal The calendar system for which a date/time format is desired. @param skeleton The skeleton that selects the fields to be formatted. (Uses the {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY}, etc. @param locale The locale for which the date/time format is desired.
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Creates", "a", "{", "@link", "DateFormat", "}", "object", "that", "can", "be", "used", "to", "format", "dates", "and", "times", "in", "the", "calendar", "system", "specified", "by", "<code", ">...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java#L1996-L1998
ops4j/org.ops4j.base
ops4j-base-util/src/main/java/org/ops4j/util/environment/Environment.java
Environment.readEnvironment
private static int readEnvironment( String cmdExec, Properties properties ) { // fire up the shell and get echo'd results on stdout BufferedReader reader = null; Process process = null; int exitValue = 99; try { String[] args = new String[]{ cmdExec }; process = startProcess( args ); reader = createReader( process ); processLinesOfEnvironmentVariables( reader, properties ); process.waitFor(); reader.close(); } catch( InterruptedException t ) { throw new EnvironmentException( "NA", t ); } catch( IOException t ) { throw new EnvironmentException( "NA", t ); } finally { if( process != null ) { process.destroy(); exitValue = process.exitValue(); } close( reader ); } return exitValue; }
java
private static int readEnvironment( String cmdExec, Properties properties ) { // fire up the shell and get echo'd results on stdout BufferedReader reader = null; Process process = null; int exitValue = 99; try { String[] args = new String[]{ cmdExec }; process = startProcess( args ); reader = createReader( process ); processLinesOfEnvironmentVariables( reader, properties ); process.waitFor(); reader.close(); } catch( InterruptedException t ) { throw new EnvironmentException( "NA", t ); } catch( IOException t ) { throw new EnvironmentException( "NA", t ); } finally { if( process != null ) { process.destroy(); exitValue = process.exitValue(); } close( reader ); } return exitValue; }
[ "private", "static", "int", "readEnvironment", "(", "String", "cmdExec", ",", "Properties", "properties", ")", "{", "// fire up the shell and get echo'd results on stdout", "BufferedReader", "reader", "=", "null", ";", "Process", "process", "=", "null", ";", "int", "e...
Reads the environment variables and stores them in a Properties object. @param cmdExec The command to execute to get hold of the environment variables. @param properties The Properties object to be populated with the environment variables. @return The exit value of the OS level process upon its termination.
[ "Reads", "the", "environment", "variables", "and", "stores", "them", "in", "a", "Properties", "object", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/environment/Environment.java#L621-L654
libgdx/gdx-ai
gdx-ai/src/com/badlogic/gdx/ai/steer/utils/paths/LinePath.java
LinePath.calculatePointSegmentSquareDistance
public float calculatePointSegmentSquareDistance (T out, T a, T b, T c) { out.set(a); tmpB.set(b); tmpC.set(c); T ab = tmpB.sub(a); float abLen2 = ab.len2(); if (abLen2 != 0) { float t = (tmpC.sub(a)).dot(ab) / abLen2; out.mulAdd(ab, MathUtils.clamp(t, 0, 1)); } return out.dst2(c); }
java
public float calculatePointSegmentSquareDistance (T out, T a, T b, T c) { out.set(a); tmpB.set(b); tmpC.set(c); T ab = tmpB.sub(a); float abLen2 = ab.len2(); if (abLen2 != 0) { float t = (tmpC.sub(a)).dot(ab) / abLen2; out.mulAdd(ab, MathUtils.clamp(t, 0, 1)); } return out.dst2(c); }
[ "public", "float", "calculatePointSegmentSquareDistance", "(", "T", "out", ",", "T", "a", ",", "T", "b", ",", "T", "c", ")", "{", "out", ".", "set", "(", "a", ")", ";", "tmpB", ".", "set", "(", "b", ")", ";", "tmpC", ".", "set", "(", "c", ")", ...
Returns the square distance of the nearest point on line segment {@code a-b}, from point {@code c}. Also, the {@code out} vector is assigned to the nearest point. @param out the output vector that contains the nearest point on return @param a the start point of the line segment @param b the end point of the line segment @param c the point to calculate the distance from
[ "Returns", "the", "square", "distance", "of", "the", "nearest", "point", "on", "line", "segment", "{" ]
train
https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/steer/utils/paths/LinePath.java#L88-L101
code4everything/util
src/main/java/com/zhazhapan/util/BeanUtils.java
BeanUtils.toPrettyJson
public static String toPrettyJson(Object object, FieldModifier modifier) throws IllegalAccessException { return Formatter.formatJson(toJsonString(object, modifier)); }
java
public static String toPrettyJson(Object object, FieldModifier modifier) throws IllegalAccessException { return Formatter.formatJson(toJsonString(object, modifier)); }
[ "public", "static", "String", "toPrettyJson", "(", "Object", "object", ",", "FieldModifier", "modifier", ")", "throws", "IllegalAccessException", "{", "return", "Formatter", ".", "formatJson", "(", "toJsonString", "(", "object", ",", "modifier", ")", ")", ";", "...
将Bean类指定修饰符的属性转换成JSON字符串 @param object Bean对象 @param modifier 属性的权限修饰符 @return 格式化的JSON字符串 @throws IllegalAccessException 异常
[ "将Bean类指定修饰符的属性转换成JSON字符串" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/BeanUtils.java#L259-L261
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java
ProductUrl.configuredProductUrl
public static MozuUrl configuredProductUrl(Boolean includeOptionDetails, String productCode, String purchaseLocation, Integer quantity, String responseFields, Boolean skipInventoryCheck, String variationProductCodeFilter) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/configure?includeOptionDetails={includeOptionDetails}&skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&purchaseLocation={purchaseLocation}&variationProductCodeFilter={variationProductCodeFilter}&responseFields={responseFields}"); formatter.formatUrl("includeOptionDetails", includeOptionDetails); formatter.formatUrl("productCode", productCode); formatter.formatUrl("purchaseLocation", purchaseLocation); formatter.formatUrl("quantity", quantity); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("skipInventoryCheck", skipInventoryCheck); formatter.formatUrl("variationProductCodeFilter", variationProductCodeFilter); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl configuredProductUrl(Boolean includeOptionDetails, String productCode, String purchaseLocation, Integer quantity, String responseFields, Boolean skipInventoryCheck, String variationProductCodeFilter) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/storefront/products/{productCode}/configure?includeOptionDetails={includeOptionDetails}&skipInventoryCheck={skipInventoryCheck}&quantity={quantity}&purchaseLocation={purchaseLocation}&variationProductCodeFilter={variationProductCodeFilter}&responseFields={responseFields}"); formatter.formatUrl("includeOptionDetails", includeOptionDetails); formatter.formatUrl("productCode", productCode); formatter.formatUrl("purchaseLocation", purchaseLocation); formatter.formatUrl("quantity", quantity); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("skipInventoryCheck", skipInventoryCheck); formatter.formatUrl("variationProductCodeFilter", variationProductCodeFilter); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "configuredProductUrl", "(", "Boolean", "includeOptionDetails", ",", "String", "productCode", ",", "String", "purchaseLocation", ",", "Integer", "quantity", ",", "String", "responseFields", ",", "Boolean", "skipInventoryCheck", ",", "Strin...
Get Resource Url for ConfiguredProduct @param includeOptionDetails If true, the response returns details about the product. If false, returns a product summary such as the product name, price, and sale price. @param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product. @param purchaseLocation The location where the order item(s) was purchased. @param quantity The number of cart items in the shopper's active cart. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation. @param variationProductCodeFilter @return String Resource Url
[ "Get", "Resource", "Url", "for", "ConfiguredProduct" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/storefront/ProductUrl.java#L117-L128
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/handlers/InboundCookiesHandler.java
InboundCookiesHandler.getFlashCookie
@SuppressWarnings("unchecked") protected Flash getFlashCookie(HttpServerExchange exchange) { Flash flash = Flash.create(); final String cookieValue = getCookieValue(exchange, this.config.getFlashCookieName()); if (StringUtils.isNotBlank(cookieValue)) { try { String decryptedValue = Application.getInstance(Crypto.class).decrypt(cookieValue, this.config.getFlashCookieEncryptionKey()); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(new HmacKey(this.config.getFlashCookieSignKey().getBytes(StandardCharsets.UTF_8))) .setJwsAlgorithmConstraints(new AlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.HMAC_SHA512)) .build(); JwtClaims jwtClaims = jwtConsumer.processToClaims(decryptedValue); LocalDateTime expires = LocalDateTime.parse(jwtClaims.getClaimValue(ClaimKey.EXPIRES.toString(), String.class), DateUtils.formatter); if (expires.isAfter(LocalDateTime.now())) { if (jwtClaims.hasClaim(ClaimKey.FORM.toString())) { this.form = CodecUtils.deserializeFromBase64(jwtClaims.getClaimValue(ClaimKey.FORM.toString(), String.class)); } flash = Flash.create() .withContent(MangooUtils.copyMap(jwtClaims.getClaimValue(ClaimKey.DATA.toString(), Map.class))).setDiscard(true); } } catch (MalformedClaimException | InvalidJwtException e) { LOG.error("Failed to parse flash cookie", e); flash.invalidate(); } } return flash; }
java
@SuppressWarnings("unchecked") protected Flash getFlashCookie(HttpServerExchange exchange) { Flash flash = Flash.create(); final String cookieValue = getCookieValue(exchange, this.config.getFlashCookieName()); if (StringUtils.isNotBlank(cookieValue)) { try { String decryptedValue = Application.getInstance(Crypto.class).decrypt(cookieValue, this.config.getFlashCookieEncryptionKey()); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(new HmacKey(this.config.getFlashCookieSignKey().getBytes(StandardCharsets.UTF_8))) .setJwsAlgorithmConstraints(new AlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.HMAC_SHA512)) .build(); JwtClaims jwtClaims = jwtConsumer.processToClaims(decryptedValue); LocalDateTime expires = LocalDateTime.parse(jwtClaims.getClaimValue(ClaimKey.EXPIRES.toString(), String.class), DateUtils.formatter); if (expires.isAfter(LocalDateTime.now())) { if (jwtClaims.hasClaim(ClaimKey.FORM.toString())) { this.form = CodecUtils.deserializeFromBase64(jwtClaims.getClaimValue(ClaimKey.FORM.toString(), String.class)); } flash = Flash.create() .withContent(MangooUtils.copyMap(jwtClaims.getClaimValue(ClaimKey.DATA.toString(), Map.class))).setDiscard(true); } } catch (MalformedClaimException | InvalidJwtException e) { LOG.error("Failed to parse flash cookie", e); flash.invalidate(); } } return flash; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "Flash", "getFlashCookie", "(", "HttpServerExchange", "exchange", ")", "{", "Flash", "flash", "=", "Flash", ".", "create", "(", ")", ";", "final", "String", "cookieValue", "=", "getCookieValue", "(...
Retrieves the flash cookie from the current @param exchange The Undertow HttpServerExchange
[ "Retrieves", "the", "flash", "cookie", "from", "the", "current" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/handlers/InboundCookiesHandler.java#L166-L197
cybazeitalia/emaze-dysfunctional
src/main/java/net/emaze/dysfunctional/Filtering.java
Filtering.atMostLast
public static <E> Iterator<E> atMostLast(int howMany, E[] from) { return atMostLast(howMany, new ArrayIterator<E>(from)); }
java
public static <E> Iterator<E> atMostLast(int howMany, E[] from) { return atMostLast(howMany, new ArrayIterator<E>(from)); }
[ "public", "static", "<", "E", ">", "Iterator", "<", "E", ">", "atMostLast", "(", "int", "howMany", ",", "E", "[", "]", "from", ")", "{", "return", "atMostLast", "(", "howMany", ",", "new", "ArrayIterator", "<", "E", ">", "(", "from", ")", ")", ";",...
Creates an iterator yielding at most last n elements from the source array. E.g: <code>atMostLast(4, [1, 2, 3]) -> [1, 2, 3]</code> <code>atMostLast(2, [1, 2, 3]) -> [2, 3]</code> @param <E> the array element type @param howMany number of elements to be yielded (at most) @param from the source array @return the resulting iterator
[ "Creates", "an", "iterator", "yielding", "at", "most", "last", "n", "elements", "from", "the", "source", "array", ".", "E", ".", "g", ":", "<code", ">", "atMostLast", "(", "4", "[", "1", "2", "3", "]", ")", "-", ">", "[", "1", "2", "3", "]", "<...
train
https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Filtering.java#L159-L161
mapsforge/mapsforge
sqlite-android/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java
SQLiteDatabase.execSQL
public void execSQL(String sql, Object[] bindArgs) throws SQLException { if (bindArgs == null) { throw new IllegalArgumentException("Empty bindArgs"); } executeSql(sql, bindArgs); }
java
public void execSQL(String sql, Object[] bindArgs) throws SQLException { if (bindArgs == null) { throw new IllegalArgumentException("Empty bindArgs"); } executeSql(sql, bindArgs); }
[ "public", "void", "execSQL", "(", "String", "sql", ",", "Object", "[", "]", "bindArgs", ")", "throws", "SQLException", "{", "if", "(", "bindArgs", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Empty bindArgs\"", ")", ";", "}", ...
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. <p> For INSERT statements, use any of the following instead. <ul> <li>{@link #insert(String, String, ContentValues)}</li> <li>{@link #insertOrThrow(String, String, ContentValues)}</li> <li>{@link #insertWithOnConflict(String, String, ContentValues, int)}</li> </ul> <p> For UPDATE statements, use any of the following instead. <ul> <li>{@link #update(String, ContentValues, String, String[])}</li> <li>{@link #updateWithOnConflict(String, ContentValues, String, String[], int)}</li> </ul> <p> For DELETE statements, use any of the following instead. <ul> <li>{@link #delete(String, String, String[])}</li> </ul> <p> For example, the following are good candidates for using this method: <ul> <li>ALTER TABLE</li> <li>CREATE or DROP table / trigger / view / index / virtual table</li> <li>REINDEX</li> <li>RELEASE</li> <li>SAVEPOINT</li> <li>PRAGMA that returns no data</li> </ul> </p> <p> When using {@link #enableWriteAheadLogging()}, journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'<value>" statement if your app is using {@link #enableWriteAheadLogging()} </p> @param sql the SQL statement to be executed. Multiple statements separated by semicolons are not supported. @param bindArgs only byte[], String, Long and Double are supported in bindArgs. @throws SQLException if the SQL string is invalid
[ "Execute", "a", "single", "SQL", "statement", "that", "is", "NOT", "a", "SELECT", "/", "INSERT", "/", "UPDATE", "/", "DELETE", ".", "<p", ">", "For", "INSERT", "statements", "use", "any", "of", "the", "following", "instead", ".", "<ul", ">", "<li", ">"...
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java#L1656-L1661
jbundle/jbundle
thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/mem/serial/SDatabase.java
SDatabase.openSerialStream
public InputStream openSerialStream(FieldList record, String strLookupKey) { try { String strFilePathName = this.getFilename(strLookupKey, false); File file = new File(strFilePathName); if (file.exists()) { return new FileInputStream(strFilePathName); } } catch (Exception ex) { ex.printStackTrace(); } return null; }
java
public InputStream openSerialStream(FieldList record, String strLookupKey) { try { String strFilePathName = this.getFilename(strLookupKey, false); File file = new File(strFilePathName); if (file.exists()) { return new FileInputStream(strFilePathName); } } catch (Exception ex) { ex.printStackTrace(); } return null; }
[ "public", "InputStream", "openSerialStream", "(", "FieldList", "record", ",", "String", "strLookupKey", ")", "{", "try", "{", "String", "strFilePathName", "=", "this", ".", "getFilename", "(", "strLookupKey", ",", "false", ")", ";", "File", "file", "=", "new",...
Get the physical table that matches this BaseTable and return an Input stream to it if it exists. @param table The table to get the serial stream for (named ser/dbname/tablename.ser). @return The FileInputStream or null if it doesn't exist.
[ "Get", "the", "physical", "table", "that", "matches", "this", "BaseTable", "and", "return", "an", "Input", "stream", "to", "it", "if", "it", "exists", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/mem/serial/SDatabase.java#L102-L117
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/WePayApi.java
WePayApi.getConnection
private HttpURLConnection getConnection(String uri, String postJson, String token) throws IOException { int tries = 0; IOException last = null; while (tries++ <= retries) { try { return getConnectionOnce(uri, postJson, token); } catch (IOException ex) { last = ex; } } throw last; }
java
private HttpURLConnection getConnection(String uri, String postJson, String token) throws IOException { int tries = 0; IOException last = null; while (tries++ <= retries) { try { return getConnectionOnce(uri, postJson, token); } catch (IOException ex) { last = ex; } } throw last; }
[ "private", "HttpURLConnection", "getConnection", "(", "String", "uri", ",", "String", "postJson", ",", "String", "token", ")", "throws", "IOException", "{", "int", "tries", "=", "0", ";", "IOException", "last", "=", "null", ";", "while", "(", "tries", "++", ...
Common functionality for posting data. Smart about retries. WePay's API is not strictly RESTful, so all requests are sent as POST unless there are no request values
[ "Common", "functionality", "for", "posting", "data", ".", "Smart", "about", "retries", "." ]
train
https://github.com/lookfirst/WePay-Java-SDK/blob/3c0a47d6fa051d531c8fdbbfd54a0ef2891aa8f0/src/main/java/com/lookfirst/wepay/WePayApi.java#L265-L278
lucee/Lucee
loader/src/main/java/lucee/loader/engine/CFMLEngineFactory.java
CFMLEngineFactory.getInstance
public static CFMLEngine getInstance(final ServletConfig config, final EngineChangeListener listener) throws ServletException { getInstance(config); // add listener for update factory.addListener(listener); // read init param from config factory.readInitParam(config); factory.initEngineIfNecessary(); singelton.addServletConfig(config); // make the FDController visible for the FDClient FDControllerFactory.makeVisible(); return singelton; }
java
public static CFMLEngine getInstance(final ServletConfig config, final EngineChangeListener listener) throws ServletException { getInstance(config); // add listener for update factory.addListener(listener); // read init param from config factory.readInitParam(config); factory.initEngineIfNecessary(); singelton.addServletConfig(config); // make the FDController visible for the FDClient FDControllerFactory.makeVisible(); return singelton; }
[ "public", "static", "CFMLEngine", "getInstance", "(", "final", "ServletConfig", "config", ",", "final", "EngineChangeListener", "listener", ")", "throws", "ServletException", "{", "getInstance", "(", "config", ")", ";", "// add listener for update", "factory", ".", "a...
returns instance of this factory (singelton always the same instance) @param config @param listener @return Singelton Instance of the Factory @throws ServletException
[ "returns", "instance", "of", "this", "factory", "(", "singelton", "always", "the", "same", "instance", ")" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/loader/src/main/java/lucee/loader/engine/CFMLEngineFactory.java#L200-L216
sawano/java-commons
src/main/java/se/sawano/java/commons/lang/validate/AbstractValidate.java
AbstractValidate.inclusiveBetween
public <T, V extends Comparable<T>> V inclusiveBetween(final T start, final T end, final V value) { if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { fail(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } return value; }
java
public <T, V extends Comparable<T>> V inclusiveBetween(final T start, final T end, final V value) { if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { fail(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } return value; }
[ "public", "<", "T", ",", "V", "extends", "Comparable", "<", "T", ">", ">", "V", "inclusiveBetween", "(", "final", "T", "start", ",", "final", "T", "end", ",", "final", "V", "value", ")", "{", "if", "(", "value", ".", "compareTo", "(", "start", ")",...
<p>Validate that the specified argument object fall between the two inclusive values specified; otherwise, throws an exception.</p> <pre>Validate.inclusiveBetween(0, 2, 1);</pre> @param <T> the type of the start and end values @param <V> the type of the argument @param start the inclusive start value, not null @param end the inclusive end value, not null @param value the object to validate, not null @return the value @throws IllegalArgumentValidationException if the value falls outside the boundaries @see #inclusiveBetween(Object, Object, Comparable, String, Object...)
[ "<p", ">", "Validate", "that", "the", "specified", "argument", "object", "fall", "between", "the", "two", "inclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", ".", "<", "/", "p", ">", "<pre", ">", "Validate", ".", "inclusiveBetw...
train
https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/AbstractValidate.java#L1228-L1233
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsVfsSitemapService.java
CmsVfsSitemapService.updateNavPos
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException { if (change.hasChangedPosition()) { applyNavigationChanges(change, res); } }
java
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException { if (change.hasChangedPosition()) { applyNavigationChanges(change, res); } }
[ "private", "void", "updateNavPos", "(", "CmsResource", "res", ",", "CmsSitemapChange", "change", ")", "throws", "CmsException", "{", "if", "(", "change", ".", "hasChangedPosition", "(", ")", ")", "{", "applyNavigationChanges", "(", "change", ",", "res", ")", "...
Updates the navigation position for a resource.<p> @param res the resource for which to update the navigation position @param change the sitemap change @throws CmsException if something goes wrong
[ "Updates", "the", "navigation", "position", "for", "a", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L3261-L3266
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/util/WorkQueue.java
WorkQueue.registerTaskGroup
public boolean registerTaskGroup(Object taskGroupId, int numTasks) { return taskKeyToLatch. putIfAbsent(taskGroupId, new CountDownLatch(numTasks)) == null; }
java
public boolean registerTaskGroup(Object taskGroupId, int numTasks) { return taskKeyToLatch. putIfAbsent(taskGroupId, new CountDownLatch(numTasks)) == null; }
[ "public", "boolean", "registerTaskGroup", "(", "Object", "taskGroupId", ",", "int", "numTasks", ")", "{", "return", "taskKeyToLatch", ".", "putIfAbsent", "(", "taskGroupId", ",", "new", "CountDownLatch", "(", "numTasks", ")", ")", "==", "null", ";", "}" ]
Registers a new task group with the specified number of tasks to execute, or returns {@code false} if a task group with the same identifier has already been registered. This identifier will remain valid in the queue until {@link #await(Object) await} has been called. @param taskGroupId an identifier to be associated with a group of tasks @param numTasks the number of tasks that will be eventually run as a part of this group. @returns {@code true} if a new task group was registered or {@code false} if a task group with the same identifier had already been registered.
[ "Registers", "a", "new", "task", "group", "with", "the", "specified", "number", "of", "tasks", "to", "execute", "or", "returns", "{", "@code", "false", "}", "if", "a", "task", "group", "with", "the", "same", "identifier", "has", "already", "been", "registe...
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/WorkQueue.java#L286-L289
guardtime/ksi-java-sdk
ksi-service-client-common-http/src/main/java/com/guardtime/ksi/service/client/http/HttpPostRequestFuture.java
HttpPostRequestFuture.parse
protected TLVElement parse(int statusCode, String responseMessage, InputStream response) throws HttpProtocolException { try { return TLVElement.create(Util.toByteArray(response)); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Invalid TLV response.", e); } throw new HttpProtocolException(statusCode, responseMessage); } }
java
protected TLVElement parse(int statusCode, String responseMessage, InputStream response) throws HttpProtocolException { try { return TLVElement.create(Util.toByteArray(response)); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Invalid TLV response.", e); } throw new HttpProtocolException(statusCode, responseMessage); } }
[ "protected", "TLVElement", "parse", "(", "int", "statusCode", ",", "String", "responseMessage", ",", "InputStream", "response", ")", "throws", "HttpProtocolException", "{", "try", "{", "return", "TLVElement", ".", "create", "(", "Util", ".", "toByteArray", "(", ...
Validates HTTP response message. @param statusCode HTTP status code. @param responseMessage HTTP header response message. @param response response input stream. @return {@link TLVElement} @throws HttpProtocolException will be thrown when KSI HTTP response is not valid.
[ "Validates", "HTTP", "response", "message", "." ]
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-client-common-http/src/main/java/com/guardtime/ksi/service/client/http/HttpPostRequestFuture.java#L51-L60
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java
SpaceRepository.fireSpaceRemoved
protected void fireSpaceRemoved(Space space, boolean isLocalDestruction) { if (this.externalListener != null) { this.externalListener.spaceDestroyed(space, isLocalDestruction); } }
java
protected void fireSpaceRemoved(Space space, boolean isLocalDestruction) { if (this.externalListener != null) { this.externalListener.spaceDestroyed(space, isLocalDestruction); } }
[ "protected", "void", "fireSpaceRemoved", "(", "Space", "space", ",", "boolean", "isLocalDestruction", ")", "{", "if", "(", "this", ".", "externalListener", "!=", "null", ")", "{", "this", ".", "externalListener", ".", "spaceDestroyed", "(", "space", ",", "isLo...
Notifies the listeners on the space destruction. @param space the removed space. @param isLocalDestruction indicates if the destruction of the space was initiated on the current kernel.
[ "Notifies", "the", "listeners", "on", "the", "space", "destruction", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java#L395-L399
haraldk/TwelveMonkeys
common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java
IndexImage.getIndexedImage
public static BufferedImage getIndexedImage(BufferedImage pImage, Image pPalette, int pHints) { return getIndexedImage(pImage, pPalette, null, pHints); }
java
public static BufferedImage getIndexedImage(BufferedImage pImage, Image pPalette, int pHints) { return getIndexedImage(pImage, pPalette, null, pHints); }
[ "public", "static", "BufferedImage", "getIndexedImage", "(", "BufferedImage", "pImage", ",", "Image", "pPalette", ",", "int", "pHints", ")", "{", "return", "getIndexedImage", "(", "pImage", ",", "pPalette", ",", "null", ",", "pHints", ")", ";", "}" ]
Converts the input image (must be {@code TYPE_INT_RGB} or {@code TYPE_INT_ARGB}) to an indexed image. If the palette image uses an {@code IndexColorModel}, this will be used. Otherwise, generating an adaptive palette (8 bit) from the given palette image. Dithering, transparency and color selection is controlled with the {@code pHints}parameter. <p/> The image returned is a new image, the input image is not modified. @param pImage the BufferedImage to index @param pPalette the Image to read color information from @param pHints hints that control output quality and speed. @return the indexed BufferedImage. The image will be of type {@code BufferedImage.TYPE_BYTE_INDEXED} or {@code BufferedImage.TYPE_BYTE_BINARY}, and use an {@code IndexColorModel}. @see #DITHER_DIFFUSION @see #DITHER_NONE @see #COLOR_SELECTION_FAST @see #COLOR_SELECTION_QUALITY @see #TRANSPARENCY_OPAQUE @see #TRANSPARENCY_BITMASK @see BufferedImage#TYPE_BYTE_INDEXED @see BufferedImage#TYPE_BYTE_BINARY @see IndexColorModel
[ "Converts", "the", "input", "image", "(", "must", "be", "{", "@code", "TYPE_INT_RGB", "}", "or", "{", "@code", "TYPE_INT_ARGB", "}", ")", "to", "an", "indexed", "image", ".", "If", "the", "palette", "image", "uses", "an", "{", "@code", "IndexColorModel", ...
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java#L1153-L1155
centic9/commons-dost
src/main/java/org/dstadler/commons/svn/SVNCommands.java
SVNCommands.getLastRevision
public static long getLastRevision(String branch, String baseUrl, String user, String pwd) throws IOException { CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument("info"); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument(baseUrl + branch); try (InputStream inStr = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) { String info = IOUtils.toString(inStr, "UTF-8"); log.info("Info:\n" + info); /* svn info http://... Repository Root: https://svn-lnz.emea.cpwr.corp/svn/dev Repository UUID: 35fb04cf-4f84-b44d-92fa-8d0d0442729e Revision: 390864 Node Kind: directory */ // read the revision Matcher matcher = Pattern.compile("Revision: ([0-9]+)").matcher(info); if (!matcher.find()) { throw new IOException("Could not find Revision entry in info-output: " + info); } log.info("Found rev: " + matcher.group(1) + " for branch " + branch); return Long.parseLong(matcher.group(1)); } }
java
public static long getLastRevision(String branch, String baseUrl, String user, String pwd) throws IOException { CommandLine cmdLine = new CommandLine(SVN_CMD); cmdLine.addArgument("info"); addDefaultArguments(cmdLine, user, pwd); cmdLine.addArgument(baseUrl + branch); try (InputStream inStr = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) { String info = IOUtils.toString(inStr, "UTF-8"); log.info("Info:\n" + info); /* svn info http://... Repository Root: https://svn-lnz.emea.cpwr.corp/svn/dev Repository UUID: 35fb04cf-4f84-b44d-92fa-8d0d0442729e Revision: 390864 Node Kind: directory */ // read the revision Matcher matcher = Pattern.compile("Revision: ([0-9]+)").matcher(info); if (!matcher.find()) { throw new IOException("Could not find Revision entry in info-output: " + info); } log.info("Found rev: " + matcher.group(1) + " for branch " + branch); return Long.parseLong(matcher.group(1)); } }
[ "public", "static", "long", "getLastRevision", "(", "String", "branch", ",", "String", "baseUrl", ",", "String", "user", ",", "String", "pwd", ")", "throws", "IOException", "{", "CommandLine", "cmdLine", "=", "new", "CommandLine", "(", "SVN_CMD", ")", ";", "...
Return the last revision of the given branch. Uses the full svn repository if branch is "" @param branch The name of the branch including the path to the branch, e.g. branches/4.2.x @param baseUrl The SVN url to connect to @param user The SVN user or null if the default user from the machine should be used @param pwd The SVN password or null if the default user from the machine should be used @return The contents of the file. @return The last revision where a check-in was made on the branch @throws IOException Execution of the SVN sub-process failed or the sub-process returned a exit value indicating a failure
[ "Return", "the", "last", "revision", "of", "the", "given", "branch", ".", "Uses", "the", "full", "svn", "repository", "if", "branch", "is" ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L312-L339
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java
ManagementEnforcer.removeFilteredNamedPolicy
public boolean removeFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) { return removeFilteredPolicy("p", ptype, fieldIndex, fieldValues); }
java
public boolean removeFilteredNamedPolicy(String ptype, int fieldIndex, String... fieldValues) { return removeFilteredPolicy("p", ptype, fieldIndex, fieldValues); }
[ "public", "boolean", "removeFilteredNamedPolicy", "(", "String", "ptype", ",", "int", "fieldIndex", ",", "String", "...", "fieldValues", ")", "{", "return", "removeFilteredPolicy", "(", "\"p\"", ",", "ptype", ",", "fieldIndex", ",", "fieldValues", ")", ";", "}" ...
removeFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified. @param ptype the policy type, can be "p", "p2", "p3", .. @param fieldIndex the policy rule's start index to be matched. @param fieldValues the field values to be matched, value "" means not to match this field. @return succeeds or not.
[ "removeFilteredNamedPolicy", "removes", "an", "authorization", "rule", "from", "the", "current", "named", "policy", "field", "filters", "can", "be", "specified", "." ]
train
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L369-L371
jayantk/jklol
src/com/jayantkrish/jklol/util/PairCountAccumulator.java
PairCountAccumulator.increment
public void increment(PairCountAccumulator<A,B> other) { for (A key1 : other.counts.keySet()) { for (B key2 : other.counts.get(key1).keySet()) { double value = other.getCount(key1, key2); incrementOutcome(key1, key2, value); } } }
java
public void increment(PairCountAccumulator<A,B> other) { for (A key1 : other.counts.keySet()) { for (B key2 : other.counts.get(key1).keySet()) { double value = other.getCount(key1, key2); incrementOutcome(key1, key2, value); } } }
[ "public", "void", "increment", "(", "PairCountAccumulator", "<", "A", ",", "B", ">", "other", ")", "{", "for", "(", "A", "key1", ":", "other", ".", "counts", ".", "keySet", "(", ")", ")", "{", "for", "(", "B", "key2", ":", "other", ".", "counts", ...
Adds the counts of outcomes in {@code other} to the counts in {@code this}. @param other
[ "Adds", "the", "counts", "of", "outcomes", "in", "{", "@code", "other", "}", "to", "the", "counts", "in", "{", "@code", "this", "}", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/PairCountAccumulator.java#L82-L89
VoltDB/voltdb
src/frontend/org/voltdb/planner/QueryPlanner.java
QueryPlanner.validateMigrateStmt
private static void validateMigrateStmt(String sql, VoltXMLElement xmlSQL, Database db) { final Map<String, String> attributes = xmlSQL.attributes; assert attributes.size() == 1; final Table targetTable = db.getTables().get(attributes.get("table")); assert targetTable != null; final CatalogMap<TimeToLive> ttls = targetTable.getTimetolive(); if (ttls.isEmpty()) { throw new PlanningErrorException(String.format( "%s: Cannot migrate from table %s because it does not have a TTL column", sql, targetTable.getTypeName())); } else { final Column ttl = ttls.iterator().next().getTtlcolumn(); final TupleValueExpression columnExpression = new TupleValueExpression( targetTable.getTypeName(), ttl.getName(), ttl.getIndex()); if (! ExpressionUtil.collectTerminals( ExpressionUtil.from(db, VoltXMLElementHelper.getFirstChild( VoltXMLElementHelper.getFirstChild(xmlSQL, "condition"), "operation"))) .contains(columnExpression)) { throw new PlanningErrorException(String.format( "%s: Cannot migrate from table %s because the WHERE caluse does not contain TTL column %s", sql, targetTable.getTypeName(), ttl.getName())); } } }
java
private static void validateMigrateStmt(String sql, VoltXMLElement xmlSQL, Database db) { final Map<String, String> attributes = xmlSQL.attributes; assert attributes.size() == 1; final Table targetTable = db.getTables().get(attributes.get("table")); assert targetTable != null; final CatalogMap<TimeToLive> ttls = targetTable.getTimetolive(); if (ttls.isEmpty()) { throw new PlanningErrorException(String.format( "%s: Cannot migrate from table %s because it does not have a TTL column", sql, targetTable.getTypeName())); } else { final Column ttl = ttls.iterator().next().getTtlcolumn(); final TupleValueExpression columnExpression = new TupleValueExpression( targetTable.getTypeName(), ttl.getName(), ttl.getIndex()); if (! ExpressionUtil.collectTerminals( ExpressionUtil.from(db, VoltXMLElementHelper.getFirstChild( VoltXMLElementHelper.getFirstChild(xmlSQL, "condition"), "operation"))) .contains(columnExpression)) { throw new PlanningErrorException(String.format( "%s: Cannot migrate from table %s because the WHERE caluse does not contain TTL column %s", sql, targetTable.getTypeName(), ttl.getName())); } } }
[ "private", "static", "void", "validateMigrateStmt", "(", "String", "sql", ",", "VoltXMLElement", "xmlSQL", ",", "Database", "db", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "attributes", "=", "xmlSQL", ".", "attributes", ";", "assert", "att...
Check that "MIGRATE FROM tbl WHERE..." statement is valid. @param sql SQL statement @param xmlSQL HSQL parsed tree @param db database catalog
[ "Check", "that", "MIGRATE", "FROM", "tbl", "WHERE", "...", "statement", "is", "valid", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/QueryPlanner.java#L203-L228
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/access/AccessManager.java
AccessManager.hasPermission
public final boolean hasPermission(AccessControlList acl, String permission, Identity user) throws RepositoryException { return hasPermission(acl, parseStringPermissions(permission), user); }
java
public final boolean hasPermission(AccessControlList acl, String permission, Identity user) throws RepositoryException { return hasPermission(acl, parseStringPermissions(permission), user); }
[ "public", "final", "boolean", "hasPermission", "(", "AccessControlList", "acl", ",", "String", "permission", ",", "Identity", "user", ")", "throws", "RepositoryException", "{", "return", "hasPermission", "(", "acl", ",", "parseStringPermissions", "(", "permission", ...
Has permission. @param acl access control list @param permission permission @param user user Identity @return boolean @throws RepositoryException
[ "Has", "permission", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/access/AccessManager.java#L93-L97
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/destination/subscription/DurableSubscriptionManager.java
DurableSubscriptionManager.isRegistered
public boolean isRegistered( String clientID , String subscriptionName ) { String key = clientID+"-"+subscriptionName; return subscriptions.containsKey(key); }
java
public boolean isRegistered( String clientID , String subscriptionName ) { String key = clientID+"-"+subscriptionName; return subscriptions.containsKey(key); }
[ "public", "boolean", "isRegistered", "(", "String", "clientID", ",", "String", "subscriptionName", ")", "{", "String", "key", "=", "clientID", "+", "\"-\"", "+", "subscriptionName", ";", "return", "subscriptions", ".", "containsKey", "(", "key", ")", ";", "}" ...
Test if a durable subscription exists @param clientID @param subscriptionName @return true if the subscription exists
[ "Test", "if", "a", "durable", "subscription", "exists" ]
train
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/destination/subscription/DurableSubscriptionManager.java#L73-L77
code4everything/util
src/main/java/com/zhazhapan/util/LoggerUtils.java
LoggerUtils.formatString
private static String formatString(String message, Object[] values) { if (Checker.isNotEmpty(message)) { if (Checker.isNotEmpty(values)) { return StrUtil.format(String.format(message, values), values); } return message; } return ValueConsts.EMPTY_STRING; }
java
private static String formatString(String message, Object[] values) { if (Checker.isNotEmpty(message)) { if (Checker.isNotEmpty(values)) { return StrUtil.format(String.format(message, values), values); } return message; } return ValueConsts.EMPTY_STRING; }
[ "private", "static", "String", "formatString", "(", "String", "message", ",", "Object", "[", "]", "values", ")", "{", "if", "(", "Checker", ".", "isNotEmpty", "(", "message", ")", ")", "{", "if", "(", "Checker", ".", "isNotEmpty", "(", "values", ")", "...
格式化字符串 @param message 消息 @param values 格式化参数 @return 格式化的字符串 @since 1.0.8
[ "格式化字符串" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/LoggerUtils.java#L345-L353
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.createHierarchicalEntityRoleWithServiceResponseAsync
public Observable<ServiceResponse<UUID>> createHierarchicalEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID hEntityId, CreateHierarchicalEntityRoleOptionalParameter createHierarchicalEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (hEntityId == null) { throw new IllegalArgumentException("Parameter hEntityId is required and cannot be null."); } final String name = createHierarchicalEntityRoleOptionalParameter != null ? createHierarchicalEntityRoleOptionalParameter.name() : null; return createHierarchicalEntityRoleWithServiceResponseAsync(appId, versionId, hEntityId, name); }
java
public Observable<ServiceResponse<UUID>> createHierarchicalEntityRoleWithServiceResponseAsync(UUID appId, String versionId, UUID hEntityId, CreateHierarchicalEntityRoleOptionalParameter createHierarchicalEntityRoleOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (hEntityId == null) { throw new IllegalArgumentException("Parameter hEntityId is required and cannot be null."); } final String name = createHierarchicalEntityRoleOptionalParameter != null ? createHierarchicalEntityRoleOptionalParameter.name() : null; return createHierarchicalEntityRoleWithServiceResponseAsync(appId, versionId, hEntityId, name); }
[ "public", "Observable", "<", "ServiceResponse", "<", "UUID", ">", ">", "createHierarchicalEntityRoleWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "hEntityId", ",", "CreateHierarchicalEntityRoleOptionalParameter", "createHierarchical...
Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @param createHierarchicalEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object
[ "Create", "an", "entity", "role", "for", "an", "entity", "in", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L9480-L9496
phax/ph-bdve
ph-bdve-ubl/src/main/java/com/helger/bdve/ubl/UBLValidation.java
UBLValidation.initUBL20
public static void initUBL20 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL20NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL20DocumentType e : EUBL20DocumentType.values ()) { final String sName = e.getLocalName (); final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_20); // No Schematrons here aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID, "UBL " + sName + " " + VERSION_20, bNotDeprecated, ValidationExecutorXSD.create (e))); } }
java
public static void initUBL20 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL20NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL20DocumentType e : EUBL20DocumentType.values ()) { final String sName = e.getLocalName (); final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_20); // No Schematrons here aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID, "UBL " + sName + " " + VERSION_20, bNotDeprecated, ValidationExecutorXSD.create (e))); } }
[ "public", "static", "void", "initUBL20", "(", "@", "Nonnull", "final", "ValidationExecutorSetRegistry", "aRegistry", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aRegistry", ",", "\"Registry\"", ")", ";", "// For better error messages", "LocationBeautifierSPI", ".",...
Register all standard UBL 2.0 validation execution sets to the provided registry. @param aRegistry The registry to add the artefacts. May not be <code>null</code>.
[ "Register", "all", "standard", "UBL", "2", ".", "0", "validation", "execution", "sets", "to", "the", "provided", "registry", "." ]
train
https://github.com/phax/ph-bdve/blob/2438f491174cd8989567fcdf129b273bd217e89f/ph-bdve-ubl/src/main/java/com/helger/bdve/ubl/UBLValidation.java#L342-L361
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java
PercentileDistributionSummary.computeIfAbsent
private static PercentileDistributionSummary computeIfAbsent( Registry registry, Id id, long min, long max) { Object summary = Utils.computeIfAbsent( registry.state(), id, i -> new PercentileDistributionSummary(registry, id, min, max)); return (summary instanceof PercentileDistributionSummary) ? ((PercentileDistributionSummary) summary).withRange(min, max) : new PercentileDistributionSummary(registry, id, min, max); }
java
private static PercentileDistributionSummary computeIfAbsent( Registry registry, Id id, long min, long max) { Object summary = Utils.computeIfAbsent( registry.state(), id, i -> new PercentileDistributionSummary(registry, id, min, max)); return (summary instanceof PercentileDistributionSummary) ? ((PercentileDistributionSummary) summary).withRange(min, max) : new PercentileDistributionSummary(registry, id, min, max); }
[ "private", "static", "PercentileDistributionSummary", "computeIfAbsent", "(", "Registry", "registry", ",", "Id", "id", ",", "long", "min", ",", "long", "max", ")", "{", "Object", "summary", "=", "Utils", ".", "computeIfAbsent", "(", "registry", ".", "state", "...
Only create a new instance of the counter if there is not a cached copy. The array for keeping track of the counter per bucket is quite large (1-2k depending on pointer size) and can lead to a high allocation rate if the timer is not reused in a high volume call site.
[ "Only", "create", "a", "new", "instance", "of", "the", "counter", "if", "there", "is", "not", "a", "cached", "copy", ".", "The", "array", "for", "keeping", "track", "of", "the", "counter", "per", "bucket", "is", "quite", "large", "(", "1", "-", "2k", ...
train
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java#L67-L74
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.indexOfAnyBut
public static int indexOfAnyBut(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return -1; } for (int i = 0; i < str.length(); i++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; }
java
public static int indexOfAnyBut(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return -1; } for (int i = 0; i < str.length(); i++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; }
[ "public", "static", "int", "indexOfAnyBut", "(", "String", "str", ",", "String", "searchChars", ")", "{", "if", "(", "isEmpty", "(", "str", ")", "||", "isEmpty", "(", "searchChars", ")", ")", "{", "return", "-", "1", ";", "}", "for", "(", "int", "i",...
<p>Search a String to find the first index of any character not in the given set of characters.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> search string will return <code>-1</code>.</p> <pre> GosuStringUtil.indexOfAnyBut(null, *) = -1 GosuStringUtil.indexOfAnyBut("", *) = -1 GosuStringUtil.indexOfAnyBut(*, null) = -1 GosuStringUtil.indexOfAnyBut(*, "") = -1 GosuStringUtil.indexOfAnyBut("zzabyycdxx", "za") = 3 GosuStringUtil.indexOfAnyBut("zzabyycdxx", "") = 0 GosuStringUtil.indexOfAnyBut("aba","ab") = -1 </pre> @param str the String to check, may be null @param searchChars the chars to search for, may be null @return the index of any of the chars, -1 if no match or null input @since 2.0
[ "<p", ">", "Search", "a", "String", "to", "find", "the", "first", "index", "of", "any", "character", "not", "in", "the", "given", "set", "of", "characters", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L1247-L1257
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/IllegalGuardedBy.java
IllegalGuardedBy.checkGuardedBy
public static void checkGuardedBy(boolean condition, String formatString, Object... formatArgs) { if (!condition) { throw new IllegalGuardedBy(String.format(formatString, formatArgs)); } }
java
public static void checkGuardedBy(boolean condition, String formatString, Object... formatArgs) { if (!condition) { throw new IllegalGuardedBy(String.format(formatString, formatArgs)); } }
[ "public", "static", "void", "checkGuardedBy", "(", "boolean", "condition", ",", "String", "formatString", ",", "Object", "...", "formatArgs", ")", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "IllegalGuardedBy", "(", "String", ".", "format", "...
Throws an {@link IllegalGuardedBy} exception if the given condition is false.
[ "Throws", "an", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/IllegalGuardedBy.java#L37-L41
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java
ChangeRequest.applyTo
public ChangeRequest applyTo(String zoneName, Dns.ChangeRequestOption... options) { return dns.applyChangeRequest(zoneName, this, options); }
java
public ChangeRequest applyTo(String zoneName, Dns.ChangeRequestOption... options) { return dns.applyChangeRequest(zoneName, this, options); }
[ "public", "ChangeRequest", "applyTo", "(", "String", "zoneName", ",", "Dns", ".", "ChangeRequestOption", "...", "options", ")", "{", "return", "dns", ".", "applyChangeRequest", "(", "zoneName", ",", "this", ",", "options", ")", ";", "}" ]
Applies this change request to the zone identified by {@code zoneName}. @throws DnsException upon failure or if zone is not found
[ "Applies", "this", "change", "request", "to", "the", "zone", "identified", "by", "{", "@code", "zoneName", "}", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java#L148-L150
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
LambdaToMethod.makePrivateSyntheticMethod
private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) { return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner); }
java
private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) { return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner); }
[ "private", "MethodSymbol", "makePrivateSyntheticMethod", "(", "long", "flags", ",", "Name", "name", ",", "Type", "type", ",", "Symbol", "owner", ")", "{", "return", "new", "MethodSymbol", "(", "flags", "|", "SYNTHETIC", "|", "PRIVATE", ",", "name", ",", "typ...
Create new synthetic method with given flags, name, type, owner
[ "Create", "new", "synthetic", "method", "with", "given", "flags", "name", "type", "owner" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L768-L770
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java
BinaryRowSerializer.pointTo
public void pointTo(int length, BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException { checkArgument(headerLessView.getHeaderLength() == 0); if (length < 0) { throw new IOException(String.format( "Read unexpected bytes in source of positionInSegment[%d] and limitInSegment[%d]", headerLessView.getCurrentPositionInSegment(), headerLessView.getCurrentSegmentLimit() )); } int remainInSegment = headerLessView.getCurrentSegmentLimit() - headerLessView.getCurrentPositionInSegment(); MemorySegment currSeg = headerLessView.getCurrentSegment(); int currPosInSeg = headerLessView.getCurrentPositionInSegment(); if (remainInSegment >= length) { // all in one segment, that's good. reuse.pointTo(currSeg, currPosInSeg, length); headerLessView.skipBytesToRead(length); } else { pointToMultiSegments( reuse, headerLessView, length, length - remainInSegment, currSeg, currPosInSeg ); } }
java
public void pointTo(int length, BinaryRow reuse, AbstractPagedInputView headerLessView) throws IOException { checkArgument(headerLessView.getHeaderLength() == 0); if (length < 0) { throw new IOException(String.format( "Read unexpected bytes in source of positionInSegment[%d] and limitInSegment[%d]", headerLessView.getCurrentPositionInSegment(), headerLessView.getCurrentSegmentLimit() )); } int remainInSegment = headerLessView.getCurrentSegmentLimit() - headerLessView.getCurrentPositionInSegment(); MemorySegment currSeg = headerLessView.getCurrentSegment(); int currPosInSeg = headerLessView.getCurrentPositionInSegment(); if (remainInSegment >= length) { // all in one segment, that's good. reuse.pointTo(currSeg, currPosInSeg, length); headerLessView.skipBytesToRead(length); } else { pointToMultiSegments( reuse, headerLessView, length, length - remainInSegment, currSeg, currPosInSeg ); } }
[ "public", "void", "pointTo", "(", "int", "length", ",", "BinaryRow", "reuse", ",", "AbstractPagedInputView", "headerLessView", ")", "throws", "IOException", "{", "checkArgument", "(", "headerLessView", ".", "getHeaderLength", "(", ")", "==", "0", ")", ";", "if",...
Point row to memory segments with offset(in the AbstractPagedInputView) and length. @param length row length. @param reuse reuse BinaryRow object. @param headerLessView source memory segments container.
[ "Point", "row", "to", "memory", "segments", "with", "offset", "(", "in", "the", "AbstractPagedInputView", ")", "and", "length", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/typeutils/BinaryRowSerializer.java#L224-L253
eurekaclinical/protempa
protempa-framework/src/main/java/org/protempa/proposition/PropositionUtil.java
PropositionUtil.binarySearchMinStart
private static int binarySearchMinStart( List<? extends TemporalProposition> params, long timestamp) { /* * The conditions for using index versus iterator are grabbed from the * JDK source code. */ if (params.size() < 5000 || params instanceof RandomAccess) { return minStartIndexedBinarySearch(params, timestamp); } else { return minStartIteratorBinarySearch(params, timestamp); } }
java
private static int binarySearchMinStart( List<? extends TemporalProposition> params, long timestamp) { /* * The conditions for using index versus iterator are grabbed from the * JDK source code. */ if (params.size() < 5000 || params instanceof RandomAccess) { return minStartIndexedBinarySearch(params, timestamp); } else { return minStartIteratorBinarySearch(params, timestamp); } }
[ "private", "static", "int", "binarySearchMinStart", "(", "List", "<", "?", "extends", "TemporalProposition", ">", "params", ",", "long", "timestamp", ")", "{", "/*\n * The conditions for using index versus iterator are grabbed from the\n * JDK source code.\n ...
Binary search for a primitive parameter by timestamp. @param list a <code>List</code> of <code>PrimitiveParameter</code> objects all with the same paramId, cannot be <code>null</code>. @param tstamp the timestamp we're interested in finding. @return a <code>PrimitiveParameter</code>, or null if not found.
[ "Binary", "search", "for", "a", "primitive", "parameter", "by", "timestamp", "." ]
train
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/proposition/PropositionUtil.java#L203-L214
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/metadata/MetadataDocumentWriter.java
MetadataDocumentWriter.startDocument
public void startDocument() throws ODataRenderException { outputStream = new ByteArrayOutputStream(); try { xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(outputStream, UTF_8.name()); entityTypeWriter = new MetadataDocumentEntityTypeWriter(xmlWriter, entityDataModel); complexTypeWriter = new MetadataDocumentComplexTypeWriter(xmlWriter, entityDataModel); enumTypeWriter = new MetadataDocumentEnumTypeWriter(xmlWriter); entitySetWriter = new MetadataDocumentEntitySetWriter(xmlWriter); singletonWriter = new MetadataDocumentSingletonWriter(xmlWriter); xmlWriter.writeStartDocument(UTF_8.name(), XML_VERSION); xmlWriter.setPrefix(EDMX_PREFIX, EDMX_NS); } catch (XMLStreamException e) { LOG.error("Not possible to start stream XML"); throw new ODataRenderException("Not possible to start stream XML: ", e); } }
java
public void startDocument() throws ODataRenderException { outputStream = new ByteArrayOutputStream(); try { xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(outputStream, UTF_8.name()); entityTypeWriter = new MetadataDocumentEntityTypeWriter(xmlWriter, entityDataModel); complexTypeWriter = new MetadataDocumentComplexTypeWriter(xmlWriter, entityDataModel); enumTypeWriter = new MetadataDocumentEnumTypeWriter(xmlWriter); entitySetWriter = new MetadataDocumentEntitySetWriter(xmlWriter); singletonWriter = new MetadataDocumentSingletonWriter(xmlWriter); xmlWriter.writeStartDocument(UTF_8.name(), XML_VERSION); xmlWriter.setPrefix(EDMX_PREFIX, EDMX_NS); } catch (XMLStreamException e) { LOG.error("Not possible to start stream XML"); throw new ODataRenderException("Not possible to start stream XML: ", e); } }
[ "public", "void", "startDocument", "(", ")", "throws", "ODataRenderException", "{", "outputStream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "xmlWriter", "=", "XML_OUTPUT_FACTORY", ".", "createXMLStreamWriter", "(", "outputStream", ",", "UTF_8...
Start the XML stream document by defining things like the type of encoding, and prefixes used. It needs to be used before calling any write method. @throws ODataRenderException if unable to render
[ "Start", "the", "XML", "stream", "document", "by", "defining", "things", "like", "the", "type", "of", "encoding", "and", "prefixes", "used", ".", "It", "needs", "to", "be", "used", "before", "calling", "any", "write", "method", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/metadata/MetadataDocumentWriter.java#L83-L99
jbundle/jbundle
app/program/db/src/main/java/org/jbundle/app/program/db/ClassInfoField.java
ClassInfoField.setupDefaultView
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { return this.setupTableLookup(itsLocation, targetScreen, converter, iDisplayFieldDesc, this.makeReferenceRecord(), ClassInfo.CLASS_NAME_KEY, ClassInfo.CLASS_NAME, true, true); }
java
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { return this.setupTableLookup(itsLocation, targetScreen, converter, iDisplayFieldDesc, this.makeReferenceRecord(), ClassInfo.CLASS_NAME_KEY, ClassInfo.CLASS_NAME, true, true); }
[ "public", "ScreenComponent", "setupDefaultView", "(", "ScreenLoc", "itsLocation", ",", "ComponentParent", "targetScreen", ",", "Convert", "converter", ",", "int", "iDisplayFieldDesc", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", ...
Set up the default screen control for this field. @param itsLocation Location of this component on screen (ie., GridBagConstraint). @param targetScreen Where to place this component (ie., Parent screen or GridBagLayout). @param converter The converter to set the screenfield to. @param iDisplayFieldDesc Display the label? (optional). @param properties Extra properties @return Return the component or ScreenField that is created for this field.
[ "Set", "up", "the", "default", "screen", "control", "for", "this", "field", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/db/src/main/java/org/jbundle/app/program/db/ClassInfoField.java#L75-L78
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/SiftDetector.java
SiftDetector.detectFeatures
protected void detectFeatures( int scaleIndex ) { extractor.process(dogTarget); FastQueue<NonMaxLimiter.LocalExtreme> found = extractor.getLocalExtreme(); derivXX.setImage(dogTarget); derivXY.setImage(dogTarget); derivYY.setImage(dogTarget); for (int i = 0; i < found.size; i++) { NonMaxLimiter.LocalExtreme e = found.get(i); if( e.max ) { if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), 1f)) { processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max); } } else if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), -1f)) { processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max); } } }
java
protected void detectFeatures( int scaleIndex ) { extractor.process(dogTarget); FastQueue<NonMaxLimiter.LocalExtreme> found = extractor.getLocalExtreme(); derivXX.setImage(dogTarget); derivXY.setImage(dogTarget); derivYY.setImage(dogTarget); for (int i = 0; i < found.size; i++) { NonMaxLimiter.LocalExtreme e = found.get(i); if( e.max ) { if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), 1f)) { processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max); } } else if( isScaleSpaceExtremum(e.location.x, e.location.y, e.getValue(), -1f)) { processFeatureCandidate(e.location.x,e.location.y,e.getValue(),e.max); } } }
[ "protected", "void", "detectFeatures", "(", "int", "scaleIndex", ")", "{", "extractor", ".", "process", "(", "dogTarget", ")", ";", "FastQueue", "<", "NonMaxLimiter", ".", "LocalExtreme", ">", "found", "=", "extractor", ".", "getLocalExtreme", "(", ")", ";", ...
Detect features inside the Difference-of-Gaussian image at the current scale @param scaleIndex Which scale in the octave is it detecting features inside up. Primarily provided here for use in child classes.
[ "Detect", "features", "inside", "the", "Difference", "-", "of", "-", "Gaussian", "image", "at", "the", "current", "scale" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/SiftDetector.java#L199-L218
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java
ValueRange.of
public static ValueRange of(long minSmallest, long minLargest, long maxSmallest, long maxLargest) { if (minSmallest > minLargest) { throw new IllegalArgumentException("Smallest minimum value must be less than largest minimum value"); } if (maxSmallest > maxLargest) { throw new IllegalArgumentException("Smallest maximum value must be less than largest maximum value"); } if (minLargest > maxLargest) { throw new IllegalArgumentException("Minimum value must be less than maximum value"); } return new ValueRange(minSmallest, minLargest, maxSmallest, maxLargest); }
java
public static ValueRange of(long minSmallest, long minLargest, long maxSmallest, long maxLargest) { if (minSmallest > minLargest) { throw new IllegalArgumentException("Smallest minimum value must be less than largest minimum value"); } if (maxSmallest > maxLargest) { throw new IllegalArgumentException("Smallest maximum value must be less than largest maximum value"); } if (minLargest > maxLargest) { throw new IllegalArgumentException("Minimum value must be less than maximum value"); } return new ValueRange(minSmallest, minLargest, maxSmallest, maxLargest); }
[ "public", "static", "ValueRange", "of", "(", "long", "minSmallest", ",", "long", "minLargest", ",", "long", "maxSmallest", ",", "long", "maxLargest", ")", "{", "if", "(", "minSmallest", ">", "minLargest", ")", "{", "throw", "new", "IllegalArgumentException", "...
Obtains a fully variable value range. <p> This factory obtains a range where both the minimum and maximum value may vary. @param minSmallest the smallest minimum value @param minLargest the largest minimum value @param maxSmallest the smallest maximum value @param maxLargest the largest maximum value @return the ValueRange for smallest min, largest min, smallest max, largest max, not null @throws IllegalArgumentException if the smallest minimum is greater than the smallest maximum, or the smallest maximum is greater than the largest maximum or the largest minimum is greater than the largest maximum
[ "Obtains", "a", "fully", "variable", "value", "range", ".", "<p", ">", "This", "factory", "obtains", "a", "range", "where", "both", "the", "minimum", "and", "maximum", "value", "may", "vary", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java#L165-L176
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java
ExpressRouteCircuitsInner.beginCreateOrUpdateAsync
public Observable<ExpressRouteCircuitInner> beginCreateOrUpdateAsync(String resourceGroupName, String circuitName, ExpressRouteCircuitInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, parameters).map(new Func1<ServiceResponse<ExpressRouteCircuitInner>, ExpressRouteCircuitInner>() { @Override public ExpressRouteCircuitInner call(ServiceResponse<ExpressRouteCircuitInner> response) { return response.body(); } }); }
java
public Observable<ExpressRouteCircuitInner> beginCreateOrUpdateAsync(String resourceGroupName, String circuitName, ExpressRouteCircuitInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, parameters).map(new Func1<ServiceResponse<ExpressRouteCircuitInner>, ExpressRouteCircuitInner>() { @Override public ExpressRouteCircuitInner call(ServiceResponse<ExpressRouteCircuitInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExpressRouteCircuitInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "circuitName", ",", "ExpressRouteCircuitInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "...
Creates or updates an express route circuit. @param resourceGroupName The name of the resource group. @param circuitName The name of the circuit. @param parameters Parameters supplied to the create or update express route circuit operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteCircuitInner object
[ "Creates", "or", "updates", "an", "express", "route", "circuit", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java#L497-L504
playn/playn
html/src/playn/html/HtmlInput.java
HtmlInput.getRelativeY
static float getRelativeY (NativeEvent e, Element target) { return (e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() + target.getOwnerDocument().getScrollTop()) / HtmlGraphics.experimentalScale; }
java
static float getRelativeY (NativeEvent e, Element target) { return (e.getClientY() - target.getAbsoluteTop() + target.getScrollTop() + target.getOwnerDocument().getScrollTop()) / HtmlGraphics.experimentalScale; }
[ "static", "float", "getRelativeY", "(", "NativeEvent", "e", ",", "Element", "target", ")", "{", "return", "(", "e", ".", "getClientY", "(", ")", "-", "target", ".", "getAbsoluteTop", "(", ")", "+", "target", ".", "getScrollTop", "(", ")", "+", "target", ...
Gets the event's y-position relative to a given element. @param e native event @param target the element whose coordinate system is to be used @return the relative y-position
[ "Gets", "the", "event", "s", "y", "-", "position", "relative", "to", "a", "given", "element", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/html/src/playn/html/HtmlInput.java#L323-L326
brettwooldridge/NuProcess
src/main/java/com/zaxxer/nuprocess/codec/NuAbstractCharsetHandler.java
NuAbstractCharsetHandler.onStderrChars
protected void onStderrChars(CharBuffer buffer, boolean closed, CoderResult coderResult) { // Consume the entire buffer by default. buffer.position(buffer.limit()); }
java
protected void onStderrChars(CharBuffer buffer, boolean closed, CoderResult coderResult) { // Consume the entire buffer by default. buffer.position(buffer.limit()); }
[ "protected", "void", "onStderrChars", "(", "CharBuffer", "buffer", ",", "boolean", "closed", ",", "CoderResult", "coderResult", ")", "{", "// Consume the entire buffer by default.", "buffer", ".", "position", "(", "buffer", ".", "limit", "(", ")", ")", ";", "}" ]
Override this to receive decoded Unicode Java string data read from stderr. <p> Make sure to set the {@link CharBuffer#position() position} of {@code buffer} to indicate how much data you have read before returning. @param buffer The {@link CharBuffer} receiving Unicode string data.
[ "Override", "this", "to", "receive", "decoded", "Unicode", "Java", "string", "data", "read", "from", "stderr", ".", "<p", ">", "Make", "sure", "to", "set", "the", "{", "@link", "CharBuffer#position", "()", "position", "}", "of", "{", "@code", "buffer", "}"...
train
https://github.com/brettwooldridge/NuProcess/blob/d4abdd195367fce7375a0b45cb2f5eeff1c74d03/src/main/java/com/zaxxer/nuprocess/codec/NuAbstractCharsetHandler.java#L164-L168
ixa-ehu/kaflib
src/main/java/ixa/kaflib/KAFDocument.java
KAFDocument.newChunk
public Chunk newChunk(String phrase, Span<Term> span) { String newId = idManager.getNextId(AnnotationType.CHUNK); Chunk newChunk = new Chunk(newId, span); newChunk.setPhrase(phrase); annotationContainer.add(newChunk, Layer.CHUNKS, AnnotationType.CHUNK); return newChunk; }
java
public Chunk newChunk(String phrase, Span<Term> span) { String newId = idManager.getNextId(AnnotationType.CHUNK); Chunk newChunk = new Chunk(newId, span); newChunk.setPhrase(phrase); annotationContainer.add(newChunk, Layer.CHUNKS, AnnotationType.CHUNK); return newChunk; }
[ "public", "Chunk", "newChunk", "(", "String", "phrase", ",", "Span", "<", "Term", ">", "span", ")", "{", "String", "newId", "=", "idManager", ".", "getNextId", "(", "AnnotationType", ".", "CHUNK", ")", ";", "Chunk", "newChunk", "=", "new", "Chunk", "(", ...
Creates a new chunk. It assigns an appropriate ID to it. The Chunk is added to the document object. @param head the chunk head. @param phrase type of the phrase. @param terms the list of the terms in the chunk. @return a new chunk.
[ "Creates", "a", "new", "chunk", ".", "It", "assigns", "an", "appropriate", "ID", "to", "it", ".", "The", "Chunk", "is", "added", "to", "the", "document", "object", "." ]
train
https://github.com/ixa-ehu/kaflib/blob/3921f55d9ae4621736a329418f6334fb721834b8/src/main/java/ixa/kaflib/KAFDocument.java#L718-L724
gliga/ekstazi
org.ekstazi.core/src/main/java/org/ekstazi/agent/EkstaziAgent.java
EkstaziAgent.premain
public static void premain(String options, Instrumentation instrumentation) { // Load options. Config.loadConfig(options, false); if (Config.X_ENABLED_V) { // Initialize instrumentation instance according to the // given mode. initializeMode(instrumentation); } }
java
public static void premain(String options, Instrumentation instrumentation) { // Load options. Config.loadConfig(options, false); if (Config.X_ENABLED_V) { // Initialize instrumentation instance according to the // given mode. initializeMode(instrumentation); } }
[ "public", "static", "void", "premain", "(", "String", "options", ",", "Instrumentation", "instrumentation", ")", "{", "// Load options.", "Config", ".", "loadConfig", "(", "options", ",", "false", ")", ";", "if", "(", "Config", ".", "X_ENABLED_V", ")", "{", ...
Executed if agent is invoked before the application is started (usually when specified as javaagent on command line). Note that this method has two modes: 1) starts only class transformer (multiRun mode), and 2) starts transformer and starts/ends coverage (singleRun mode). Option 2) is executed if javaagent is invoked with singleRun:runName argument, where runName is the name of the file that will be used to save coverage. If the argument is not correct or no argument is specified, option 1) is used. @param options Command line options specified for javaagent. @param instrumentation Instrumentation instance.
[ "Executed", "if", "agent", "is", "invoked", "before", "the", "application", "is", "started", "(", "usually", "when", "specified", "as", "javaagent", "on", "command", "line", ")", ".", "Note", "that", "this", "method", "has", "two", "modes", ":", "1", ")", ...
train
https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/agent/EkstaziAgent.java#L54-L63