repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
apache/groovy
src/main/groovy/groovy/time/TimeCategory.java
TimeCategory.getRelativeDaylightSavingsOffset
public static Duration getRelativeDaylightSavingsOffset(Date self, Date other) { """ Return a Duration representing the DST difference (if any) between two dates. i.e. if one date is before the DST changeover, and the other date is after, the resulting duration will represent the DST offset. @param self a Date @param other another Date @return a Duration """ Duration d1 = getDaylightSavingsOffset(self); Duration d2 = getDaylightSavingsOffset(other); return new TimeDuration(0, 0, 0, (int) (d2.toMilliseconds() - d1.toMilliseconds())); }
java
public static Duration getRelativeDaylightSavingsOffset(Date self, Date other) { Duration d1 = getDaylightSavingsOffset(self); Duration d2 = getDaylightSavingsOffset(other); return new TimeDuration(0, 0, 0, (int) (d2.toMilliseconds() - d1.toMilliseconds())); }
[ "public", "static", "Duration", "getRelativeDaylightSavingsOffset", "(", "Date", "self", ",", "Date", "other", ")", "{", "Duration", "d1", "=", "getDaylightSavingsOffset", "(", "self", ")", ";", "Duration", "d2", "=", "getDaylightSavingsOffset", "(", "other", ")", ";", "return", "new", "TimeDuration", "(", "0", ",", "0", ",", "0", ",", "(", "int", ")", "(", "d2", ".", "toMilliseconds", "(", ")", "-", "d1", ".", "toMilliseconds", "(", ")", ")", ")", ";", "}" ]
Return a Duration representing the DST difference (if any) between two dates. i.e. if one date is before the DST changeover, and the other date is after, the resulting duration will represent the DST offset. @param self a Date @param other another Date @return a Duration
[ "Return", "a", "Duration", "representing", "the", "DST", "difference", "(", "if", "any", ")", "between", "two", "dates", ".", "i", ".", "e", ".", "if", "one", "date", "is", "before", "the", "DST", "changeover", "and", "the", "other", "date", "is", "after", "the", "resulting", "duration", "will", "represent", "the", "DST", "offset", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/time/TimeCategory.java#L105-L109
cybazeitalia/emaze-dysfunctional
src/main/java/net/emaze/dysfunctional/Consumers.java
Consumers.dict
public static <M extends Map<K, V>, K, V> M dict(Iterator<Pair<K, V>> iterator, Supplier<M> supplier) { """ Yields all elements of the iterator (in a map created by the supplier). @param <M> the returned map type @param <K> the map key type @param <V> the map value type @param iterator the iterator that will be consumed @param supplier the factory used to get the returned map @return a map filled with iterator values """ final Function<Iterator<Pair<K, V>>, M> consumer = new ConsumeIntoMap<>(supplier); return consumer.apply(iterator); }
java
public static <M extends Map<K, V>, K, V> M dict(Iterator<Pair<K, V>> iterator, Supplier<M> supplier) { final Function<Iterator<Pair<K, V>>, M> consumer = new ConsumeIntoMap<>(supplier); return consumer.apply(iterator); }
[ "public", "static", "<", "M", "extends", "Map", "<", "K", ",", "V", ">", ",", "K", ",", "V", ">", "M", "dict", "(", "Iterator", "<", "Pair", "<", "K", ",", "V", ">", ">", "iterator", ",", "Supplier", "<", "M", ">", "supplier", ")", "{", "final", "Function", "<", "Iterator", "<", "Pair", "<", "K", ",", "V", ">", ">", ",", "M", ">", "consumer", "=", "new", "ConsumeIntoMap", "<>", "(", "supplier", ")", ";", "return", "consumer", ".", "apply", "(", "iterator", ")", ";", "}" ]
Yields all elements of the iterator (in a map created by the supplier). @param <M> the returned map type @param <K> the map key type @param <V> the map value type @param iterator the iterator that will be consumed @param supplier the factory used to get the returned map @return a map filled with iterator values
[ "Yields", "all", "elements", "of", "the", "iterator", "(", "in", "a", "map", "created", "by", "the", "supplier", ")", "." ]
train
https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Consumers.java#L228-L231
xebia-france/xebia-management-extras
src/main/java/fr/xebia/management/statistics/ServiceStatistics.java
ServiceStatistics.incrementExceptionCount
public void incrementExceptionCount(Throwable throwable) { """ Increment the {@link #communicationExceptionCounter} if the given throwable or one of its cause is an instance of on of {@link #communicationExceptionsTypes} ; otherwise, increment {@link #otherExceptionCounter}. """ if (throwable instanceof ServiceUnavailableException) { serviceUnavailableExceptionCounter.incrementAndGet(); } else if (containsThrowableOfType(throwable, communicationExceptionsTypes)) { communicationExceptionCounter.incrementAndGet(); } else if (containsThrowableOfType(throwable, businessExceptionsTypes)) { businessExceptionCounter.incrementAndGet(); } else { otherExceptionCounter.incrementAndGet(); } }
java
public void incrementExceptionCount(Throwable throwable) { if (throwable instanceof ServiceUnavailableException) { serviceUnavailableExceptionCounter.incrementAndGet(); } else if (containsThrowableOfType(throwable, communicationExceptionsTypes)) { communicationExceptionCounter.incrementAndGet(); } else if (containsThrowableOfType(throwable, businessExceptionsTypes)) { businessExceptionCounter.incrementAndGet(); } else { otherExceptionCounter.incrementAndGet(); } }
[ "public", "void", "incrementExceptionCount", "(", "Throwable", "throwable", ")", "{", "if", "(", "throwable", "instanceof", "ServiceUnavailableException", ")", "{", "serviceUnavailableExceptionCounter", ".", "incrementAndGet", "(", ")", ";", "}", "else", "if", "(", "containsThrowableOfType", "(", "throwable", ",", "communicationExceptionsTypes", ")", ")", "{", "communicationExceptionCounter", ".", "incrementAndGet", "(", ")", ";", "}", "else", "if", "(", "containsThrowableOfType", "(", "throwable", ",", "businessExceptionsTypes", ")", ")", "{", "businessExceptionCounter", ".", "incrementAndGet", "(", ")", ";", "}", "else", "{", "otherExceptionCounter", ".", "incrementAndGet", "(", ")", ";", "}", "}" ]
Increment the {@link #communicationExceptionCounter} if the given throwable or one of its cause is an instance of on of {@link #communicationExceptionsTypes} ; otherwise, increment {@link #otherExceptionCounter}.
[ "Increment", "the", "{" ]
train
https://github.com/xebia-france/xebia-management-extras/blob/09f52a0ddb898e402a04f0adfacda74a5d0556e8/src/main/java/fr/xebia/management/statistics/ServiceStatistics.java#L346-L357
dynjs/dynjs
src/main/java/org/dynjs/runtime/BoundFunction.java
BoundFunction.hasInstance
@Override public boolean hasInstance(ExecutionContext context, Object v) { """ /* @Override public Object call(ExecutionContext context, Object self, Object... args) { 15.3.4.5.1 System.err.println( "called args: " + args.length + " // " + Arrays.asList( args ) ); Object[] allArgs = new Object[boundArgs.length + args.length]; for (int i = 0; i < boundArgs.length; ++i) { allArgs[i] = boundArgs[i]; } for (int i = boundArgs.length, j = 0; i < boundArgs.length + args.length; ++i, ++j) { allArgs[i] = args[j]; } if (self != Types.UNDEFINED) { return context.call(this.target, self, allArgs); } else { return context.call(this.target, this.boundThis, allArgs); } } """ // 15.3.4.5.3 return target.hasInstance(context, v); }
java
@Override public boolean hasInstance(ExecutionContext context, Object v) { // 15.3.4.5.3 return target.hasInstance(context, v); }
[ "@", "Override", "public", "boolean", "hasInstance", "(", "ExecutionContext", "context", ",", "Object", "v", ")", "{", "// 15.3.4.5.3", "return", "target", ".", "hasInstance", "(", "context", ",", "v", ")", ";", "}" ]
/* @Override public Object call(ExecutionContext context, Object self, Object... args) { 15.3.4.5.1 System.err.println( "called args: " + args.length + " // " + Arrays.asList( args ) ); Object[] allArgs = new Object[boundArgs.length + args.length]; for (int i = 0; i < boundArgs.length; ++i) { allArgs[i] = boundArgs[i]; } for (int i = boundArgs.length, j = 0; i < boundArgs.length + args.length; ++i, ++j) { allArgs[i] = args[j]; } if (self != Types.UNDEFINED) { return context.call(this.target, self, allArgs); } else { return context.call(this.target, this.boundThis, allArgs); } }
[ "/", "*", "@Override", "public", "Object", "call", "(", "ExecutionContext", "context", "Object", "self", "Object", "...", "args", ")", "{", "15", ".", "3", ".", "4", ".", "5", ".", "1", "System", ".", "err", ".", "println", "(", "called", "args", ":", "+", "args", ".", "length", "+", "//", "+", "Arrays", ".", "asList", "(", "args", ")", ")", ";", "Object", "[]", "allArgs", "=", "new", "Object", "[", "boundArgs", ".", "length", "+", "args", ".", "length", "]", ";" ]
train
https://github.com/dynjs/dynjs/blob/4bc6715eff8768f8cd92c6a167d621bbfc1e1a91/src/main/java/org/dynjs/runtime/BoundFunction.java#L79-L83
apache/reef
lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/REEFLauncher.java
REEFLauncher.main
@SuppressWarnings("checkstyle:illegalcatch") public static void main(final String[] args) { """ Launches a REEF client process (Driver or Evaluator). @param args Command-line arguments. Must be a single element containing local path to the configuration file. """ LOG.log(Level.INFO, "Entering REEFLauncher.main()."); LOG.log(Level.FINE, "REEFLauncher started with user name [{0}]", System.getProperty("user.name")); LOG.log(Level.FINE, "REEFLauncher started. Assertions are {0} in this process.", EnvironmentUtils.areAssertionsEnabled() ? "ENABLED" : "DISABLED"); if (args.length != 1) { final String message = "REEFLauncher have one and only one argument to specify the runtime clock " + "configuration path"; throw fatal(message, new IllegalArgumentException(message)); } final REEFLauncher launcher = getREEFLauncher(args[0]); Thread.setDefaultUncaughtExceptionHandler(new REEFUncaughtExceptionHandler(launcher.envConfig)); try (final REEFEnvironment reef = REEFEnvironment.fromConfiguration(launcher.envConfig)) { reef.run(); } catch (final Throwable ex) { throw fatal("Unable to configure and start REEFEnvironment.", ex); } ThreadLogger.logThreads(LOG, Level.FINEST, "Threads running after REEFEnvironment.close():"); LOG.log(Level.INFO, "Exiting REEFLauncher.main()"); System.exit(0); // TODO[REEF-1715]: Should be able to exit cleanly at the end of main() }
java
@SuppressWarnings("checkstyle:illegalcatch") public static void main(final String[] args) { LOG.log(Level.INFO, "Entering REEFLauncher.main()."); LOG.log(Level.FINE, "REEFLauncher started with user name [{0}]", System.getProperty("user.name")); LOG.log(Level.FINE, "REEFLauncher started. Assertions are {0} in this process.", EnvironmentUtils.areAssertionsEnabled() ? "ENABLED" : "DISABLED"); if (args.length != 1) { final String message = "REEFLauncher have one and only one argument to specify the runtime clock " + "configuration path"; throw fatal(message, new IllegalArgumentException(message)); } final REEFLauncher launcher = getREEFLauncher(args[0]); Thread.setDefaultUncaughtExceptionHandler(new REEFUncaughtExceptionHandler(launcher.envConfig)); try (final REEFEnvironment reef = REEFEnvironment.fromConfiguration(launcher.envConfig)) { reef.run(); } catch (final Throwable ex) { throw fatal("Unable to configure and start REEFEnvironment.", ex); } ThreadLogger.logThreads(LOG, Level.FINEST, "Threads running after REEFEnvironment.close():"); LOG.log(Level.INFO, "Exiting REEFLauncher.main()"); System.exit(0); // TODO[REEF-1715]: Should be able to exit cleanly at the end of main() }
[ "@", "SuppressWarnings", "(", "\"checkstyle:illegalcatch\"", ")", "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "{", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Entering REEFLauncher.main().\"", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"REEFLauncher started with user name [{0}]\"", ",", "System", ".", "getProperty", "(", "\"user.name\"", ")", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"REEFLauncher started. Assertions are {0} in this process.\"", ",", "EnvironmentUtils", ".", "areAssertionsEnabled", "(", ")", "?", "\"ENABLED\"", ":", "\"DISABLED\"", ")", ";", "if", "(", "args", ".", "length", "!=", "1", ")", "{", "final", "String", "message", "=", "\"REEFLauncher have one and only one argument to specify the runtime clock \"", "+", "\"configuration path\"", ";", "throw", "fatal", "(", "message", ",", "new", "IllegalArgumentException", "(", "message", ")", ")", ";", "}", "final", "REEFLauncher", "launcher", "=", "getREEFLauncher", "(", "args", "[", "0", "]", ")", ";", "Thread", ".", "setDefaultUncaughtExceptionHandler", "(", "new", "REEFUncaughtExceptionHandler", "(", "launcher", ".", "envConfig", ")", ")", ";", "try", "(", "final", "REEFEnvironment", "reef", "=", "REEFEnvironment", ".", "fromConfiguration", "(", "launcher", ".", "envConfig", ")", ")", "{", "reef", ".", "run", "(", ")", ";", "}", "catch", "(", "final", "Throwable", "ex", ")", "{", "throw", "fatal", "(", "\"Unable to configure and start REEFEnvironment.\"", ",", "ex", ")", ";", "}", "ThreadLogger", ".", "logThreads", "(", "LOG", ",", "Level", ".", "FINEST", ",", "\"Threads running after REEFEnvironment.close():\"", ")", ";", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Exiting REEFLauncher.main()\"", ")", ";", "System", ".", "exit", "(", "0", ")", ";", "// TODO[REEF-1715]: Should be able to exit cleanly at the end of main()", "}" ]
Launches a REEF client process (Driver or Evaluator). @param args Command-line arguments. Must be a single element containing local path to the configuration file.
[ "Launches", "a", "REEF", "client", "process", "(", "Driver", "or", "Evaluator", ")", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/REEFLauncher.java#L160-L191
Crab2died/Excel4J
src/main/java/com/github/crab2died/ExcelUtils.java
ExcelUtils.simpleSheet2Excel
public void simpleSheet2Excel(List<SimpleSheetWrapper> sheets, boolean isXSSF, OutputStream os) throws IOException { """ 无模板、无注解、多sheet数据 @param sheets 待导出sheet数据 @param isXSSF 导出的Excel是否为Excel2007及以上版本(默认是) @param os 生成的Excel待输出数据流 @throws IOException 异常 """ try (Workbook workbook = exportExcelBySimpleHandler(sheets, isXSSF)) { workbook.write(os); } }
java
public void simpleSheet2Excel(List<SimpleSheetWrapper> sheets, boolean isXSSF, OutputStream os) throws IOException { try (Workbook workbook = exportExcelBySimpleHandler(sheets, isXSSF)) { workbook.write(os); } }
[ "public", "void", "simpleSheet2Excel", "(", "List", "<", "SimpleSheetWrapper", ">", "sheets", ",", "boolean", "isXSSF", ",", "OutputStream", "os", ")", "throws", "IOException", "{", "try", "(", "Workbook", "workbook", "=", "exportExcelBySimpleHandler", "(", "sheets", ",", "isXSSF", ")", ")", "{", "workbook", ".", "write", "(", "os", ")", ";", "}", "}" ]
无模板、无注解、多sheet数据 @param sheets 待导出sheet数据 @param isXSSF 导出的Excel是否为Excel2007及以上版本(默认是) @param os 生成的Excel待输出数据流 @throws IOException 异常
[ "无模板、无注解、多sheet数据" ]
train
https://github.com/Crab2died/Excel4J/blob/2ab0a3b8226a69ff868c3ead6e724f3a774f5f77/src/main/java/com/github/crab2died/ExcelUtils.java#L1435-L1441
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/CFFFontSubset.java
CFFFontSubset.BuildFDSubrsOffsets
protected void BuildFDSubrsOffsets(int Font,int FD) { """ The function finds for the FD array processed the local subr offset and its offset array. @param Font the font @param FD The FDARRAY processed """ // Initiate to -1 to indicate lsubr operator present fonts[Font].PrivateSubrsOffset[FD] = -1; // Goto beginning of objects seek(fonts[Font].fdprivateOffsets[FD]); // While in the same object: while (getPosition() < fonts[Font].fdprivateOffsets[FD]+fonts[Font].fdprivateLengths[FD]) { getDictItem(); // If the dictItem is the "Subrs" then find and store offset, if (key=="Subrs") fonts[Font].PrivateSubrsOffset[FD] = ((Integer)args[0]).intValue()+fonts[Font].fdprivateOffsets[FD]; } //Read the lsubr index if the lsubr was found if (fonts[Font].PrivateSubrsOffset[FD] >= 0) fonts[Font].PrivateSubrsOffsetsArray[FD] = getIndex(fonts[Font].PrivateSubrsOffset[FD]); }
java
protected void BuildFDSubrsOffsets(int Font,int FD) { // Initiate to -1 to indicate lsubr operator present fonts[Font].PrivateSubrsOffset[FD] = -1; // Goto beginning of objects seek(fonts[Font].fdprivateOffsets[FD]); // While in the same object: while (getPosition() < fonts[Font].fdprivateOffsets[FD]+fonts[Font].fdprivateLengths[FD]) { getDictItem(); // If the dictItem is the "Subrs" then find and store offset, if (key=="Subrs") fonts[Font].PrivateSubrsOffset[FD] = ((Integer)args[0]).intValue()+fonts[Font].fdprivateOffsets[FD]; } //Read the lsubr index if the lsubr was found if (fonts[Font].PrivateSubrsOffset[FD] >= 0) fonts[Font].PrivateSubrsOffsetsArray[FD] = getIndex(fonts[Font].PrivateSubrsOffset[FD]); }
[ "protected", "void", "BuildFDSubrsOffsets", "(", "int", "Font", ",", "int", "FD", ")", "{", "// Initiate to -1 to indicate lsubr operator present", "fonts", "[", "Font", "]", ".", "PrivateSubrsOffset", "[", "FD", "]", "=", "-", "1", ";", "// Goto beginning of objects", "seek", "(", "fonts", "[", "Font", "]", ".", "fdprivateOffsets", "[", "FD", "]", ")", ";", "// While in the same object:", "while", "(", "getPosition", "(", ")", "<", "fonts", "[", "Font", "]", ".", "fdprivateOffsets", "[", "FD", "]", "+", "fonts", "[", "Font", "]", ".", "fdprivateLengths", "[", "FD", "]", ")", "{", "getDictItem", "(", ")", ";", "// If the dictItem is the \"Subrs\" then find and store offset, ", "if", "(", "key", "==", "\"Subrs\"", ")", "fonts", "[", "Font", "]", ".", "PrivateSubrsOffset", "[", "FD", "]", "=", "(", "(", "Integer", ")", "args", "[", "0", "]", ")", ".", "intValue", "(", ")", "+", "fonts", "[", "Font", "]", ".", "fdprivateOffsets", "[", "FD", "]", ";", "}", "//Read the lsubr index if the lsubr was found", "if", "(", "fonts", "[", "Font", "]", ".", "PrivateSubrsOffset", "[", "FD", "]", ">=", "0", ")", "fonts", "[", "Font", "]", ".", "PrivateSubrsOffsetsArray", "[", "FD", "]", "=", "getIndex", "(", "fonts", "[", "Font", "]", ".", "PrivateSubrsOffset", "[", "FD", "]", ")", ";", "}" ]
The function finds for the FD array processed the local subr offset and its offset array. @param Font the font @param FD The FDARRAY processed
[ "The", "function", "finds", "for", "the", "FD", "array", "processed", "the", "local", "subr", "offset", "and", "its", "offset", "array", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/CFFFontSubset.java#L500-L517
exoplatform/jcr
exo.jcr.framework.command/src/main/java/org/exoplatform/frameworks/jcr/command/web/fckeditor/AbstractFCKConnector.java
AbstractFCKConnector.makeRESTPath
protected String makeRESTPath(String repoName, String workspace, String resource) { """ Compile REST path of the given resource. @param workspace @param resource , we assume that path starts with '/' @return """ final StringBuilder sb = new StringBuilder(512); ExoContainer container = ExoContainerContext.getCurrentContainerIfPresent(); if (container instanceof PortalContainer) { PortalContainer pContainer = (PortalContainer)container; sb.append('/').append(pContainer.getRestContextName()).append('/'); } else { sb.append('/').append(PortalContainer.DEFAULT_REST_CONTEXT_NAME).append('/'); } return sb.append("jcr/").append(repoName).append('/').append(workspace).append(resource).toString(); }
java
protected String makeRESTPath(String repoName, String workspace, String resource) { final StringBuilder sb = new StringBuilder(512); ExoContainer container = ExoContainerContext.getCurrentContainerIfPresent(); if (container instanceof PortalContainer) { PortalContainer pContainer = (PortalContainer)container; sb.append('/').append(pContainer.getRestContextName()).append('/'); } else { sb.append('/').append(PortalContainer.DEFAULT_REST_CONTEXT_NAME).append('/'); } return sb.append("jcr/").append(repoName).append('/').append(workspace).append(resource).toString(); }
[ "protected", "String", "makeRESTPath", "(", "String", "repoName", ",", "String", "workspace", ",", "String", "resource", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "512", ")", ";", "ExoContainer", "container", "=", "ExoContainerContext", ".", "getCurrentContainerIfPresent", "(", ")", ";", "if", "(", "container", "instanceof", "PortalContainer", ")", "{", "PortalContainer", "pContainer", "=", "(", "PortalContainer", ")", "container", ";", "sb", ".", "append", "(", "'", "'", ")", ".", "append", "(", "pContainer", ".", "getRestContextName", "(", ")", ")", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "'", "'", ")", ".", "append", "(", "PortalContainer", ".", "DEFAULT_REST_CONTEXT_NAME", ")", ".", "append", "(", "'", "'", ")", ";", "}", "return", "sb", ".", "append", "(", "\"jcr/\"", ")", ".", "append", "(", "repoName", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "workspace", ")", ".", "append", "(", "resource", ")", ".", "toString", "(", ")", ";", "}" ]
Compile REST path of the given resource. @param workspace @param resource , we assume that path starts with '/' @return
[ "Compile", "REST", "path", "of", "the", "given", "resource", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.framework.command/src/main/java/org/exoplatform/frameworks/jcr/command/web/fckeditor/AbstractFCKConnector.java#L69-L83
defei/codelogger-utils
src/main/java/org/codelogger/utils/DateUtils.java
DateUtils.subYears
public static long subYears(final Date date1, final Date date2) { """ Get how many years between two date. @param date1 date to be tested. @param date2 date to be tested. @return how many years between two date. """ return Math.abs(getYear(date1) - getYear(date2)); }
java
public static long subYears(final Date date1, final Date date2) { return Math.abs(getYear(date1) - getYear(date2)); }
[ "public", "static", "long", "subYears", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ")", "{", "return", "Math", ".", "abs", "(", "getYear", "(", "date1", ")", "-", "getYear", "(", "date2", ")", ")", ";", "}" ]
Get how many years between two date. @param date1 date to be tested. @param date2 date to be tested. @return how many years between two date.
[ "Get", "how", "many", "years", "between", "two", "date", "." ]
train
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/DateUtils.java#L524-L527
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/ImagesInner.java
ImagesInner.beginCreateOrUpdate
public ImageInner beginCreateOrUpdate(String resourceGroupName, String imageName, ImageInner parameters) { """ Create or update an image. @param resourceGroupName The name of the resource group. @param imageName The name of the image. @param parameters Parameters supplied to the Create Image operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ImageInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, imageName, parameters).toBlocking().single().body(); }
java
public ImageInner beginCreateOrUpdate(String resourceGroupName, String imageName, ImageInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, imageName, parameters).toBlocking().single().body(); }
[ "public", "ImageInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "imageName", ",", "ImageInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "imageName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update an image. @param resourceGroupName The name of the resource group. @param imageName The name of the image. @param parameters Parameters supplied to the Create Image operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ImageInner object if successful.
[ "Create", "or", "update", "an", "image", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/ImagesInner.java#L193-L195
Graylog2/graylog2-server
graylog2-server/src/main/java/org/graylog2/alarmcallbacks/EmailAlarmCallback.java
EmailAlarmCallback.getConfigurationRequest
private ConfigurationRequest getConfigurationRequest(Map<String, String> userNames) { """ I am truly sorry about this, but leaking the user list is not okay... """ ConfigurationRequest configurationRequest = new ConfigurationRequest(); configurationRequest.addField(new TextField("sender", "Sender", "[email protected]", "The sender of sent out mail alerts", ConfigurationField.Optional.OPTIONAL)); configurationRequest.addField(new TextField("subject", "E-Mail Subject", "Graylog alert for stream: ${stream.title}: ${check_result.resultDescription}", "The subject of sent out mail alerts", ConfigurationField.Optional.NOT_OPTIONAL)); configurationRequest.addField(new TextField("body", "E-Mail Body", FormattedEmailAlertSender.bodyTemplate, "The template to generate the body from", ConfigurationField.Optional.OPTIONAL, TextField.Attribute.TEXTAREA)); configurationRequest.addField(new ListField(CK_USER_RECEIVERS, "User Receivers", Collections.emptyList(), userNames, "Graylog usernames that should receive this alert", ConfigurationField.Optional.OPTIONAL)); configurationRequest.addField(new ListField(CK_EMAIL_RECEIVERS, "E-Mail Receivers", Collections.emptyList(), Collections.emptyMap(), "E-Mail addresses that should receive this alert", ConfigurationField.Optional.OPTIONAL, ListField.Attribute.ALLOW_CREATE)); return configurationRequest; }
java
private ConfigurationRequest getConfigurationRequest(Map<String, String> userNames) { ConfigurationRequest configurationRequest = new ConfigurationRequest(); configurationRequest.addField(new TextField("sender", "Sender", "[email protected]", "The sender of sent out mail alerts", ConfigurationField.Optional.OPTIONAL)); configurationRequest.addField(new TextField("subject", "E-Mail Subject", "Graylog alert for stream: ${stream.title}: ${check_result.resultDescription}", "The subject of sent out mail alerts", ConfigurationField.Optional.NOT_OPTIONAL)); configurationRequest.addField(new TextField("body", "E-Mail Body", FormattedEmailAlertSender.bodyTemplate, "The template to generate the body from", ConfigurationField.Optional.OPTIONAL, TextField.Attribute.TEXTAREA)); configurationRequest.addField(new ListField(CK_USER_RECEIVERS, "User Receivers", Collections.emptyList(), userNames, "Graylog usernames that should receive this alert", ConfigurationField.Optional.OPTIONAL)); configurationRequest.addField(new ListField(CK_EMAIL_RECEIVERS, "E-Mail Receivers", Collections.emptyList(), Collections.emptyMap(), "E-Mail addresses that should receive this alert", ConfigurationField.Optional.OPTIONAL, ListField.Attribute.ALLOW_CREATE)); return configurationRequest; }
[ "private", "ConfigurationRequest", "getConfigurationRequest", "(", "Map", "<", "String", ",", "String", ">", "userNames", ")", "{", "ConfigurationRequest", "configurationRequest", "=", "new", "ConfigurationRequest", "(", ")", ";", "configurationRequest", ".", "addField", "(", "new", "TextField", "(", "\"sender\"", ",", "\"Sender\"", ",", "\"[email protected]\"", ",", "\"The sender of sent out mail alerts\"", ",", "ConfigurationField", ".", "Optional", ".", "OPTIONAL", ")", ")", ";", "configurationRequest", ".", "addField", "(", "new", "TextField", "(", "\"subject\"", ",", "\"E-Mail Subject\"", ",", "\"Graylog alert for stream: ${stream.title}: ${check_result.resultDescription}\"", ",", "\"The subject of sent out mail alerts\"", ",", "ConfigurationField", ".", "Optional", ".", "NOT_OPTIONAL", ")", ")", ";", "configurationRequest", ".", "addField", "(", "new", "TextField", "(", "\"body\"", ",", "\"E-Mail Body\"", ",", "FormattedEmailAlertSender", ".", "bodyTemplate", ",", "\"The template to generate the body from\"", ",", "ConfigurationField", ".", "Optional", ".", "OPTIONAL", ",", "TextField", ".", "Attribute", ".", "TEXTAREA", ")", ")", ";", "configurationRequest", ".", "addField", "(", "new", "ListField", "(", "CK_USER_RECEIVERS", ",", "\"User Receivers\"", ",", "Collections", ".", "emptyList", "(", ")", ",", "userNames", ",", "\"Graylog usernames that should receive this alert\"", ",", "ConfigurationField", ".", "Optional", ".", "OPTIONAL", ")", ")", ";", "configurationRequest", ".", "addField", "(", "new", "ListField", "(", "CK_EMAIL_RECEIVERS", ",", "\"E-Mail Receivers\"", ",", "Collections", ".", "emptyList", "(", ")", ",", "Collections", ".", "emptyMap", "(", ")", ",", "\"E-Mail addresses that should receive this alert\"", ",", "ConfigurationField", ".", "Optional", ".", "OPTIONAL", ",", "ListField", ".", "Attribute", ".", "ALLOW_CREATE", ")", ")", ";", "return", "configurationRequest", ";", "}" ]
I am truly sorry about this, but leaking the user list is not okay...
[ "I", "am", "truly", "sorry", "about", "this", "but", "leaking", "the", "user", "list", "is", "not", "okay", "..." ]
train
https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/alarmcallbacks/EmailAlarmCallback.java#L173-L210
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/AssetsInner.java
AssetsInner.createOrUpdate
public AssetInner createOrUpdate(String resourceGroupName, String accountName, String assetName, AssetInner parameters) { """ Create or update an Asset. Creates or updates an Asset in the Media Services account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param assetName The Asset name. @param parameters The request parameters @throws IllegalArgumentException thrown if parameters fail the validation @throws ApiErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AssetInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, assetName, parameters).toBlocking().single().body(); }
java
public AssetInner createOrUpdate(String resourceGroupName, String accountName, String assetName, AssetInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, assetName, parameters).toBlocking().single().body(); }
[ "public", "AssetInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "assetName", ",", "AssetInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "assetName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update an Asset. Creates or updates an Asset in the Media Services account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param assetName The Asset name. @param parameters The request parameters @throws IllegalArgumentException thrown if parameters fail the validation @throws ApiErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the AssetInner object if successful.
[ "Create", "or", "update", "an", "Asset", ".", "Creates", "or", "updates", "an", "Asset", "in", "the", "Media", "Services", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/AssetsInner.java#L479-L481
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java
Calc.getCenterVector
public static final Atom getCenterVector(Atom[] atomSet, Atom centroid) { """ Returns the Vector that needs to be applied to shift a set of atoms to the Centroid, if the centroid is already known @param atomSet array of Atoms @return the vector needed to shift the set of atoms to its geometric center """ double[] coords = new double[3]; coords[0] = 0 - centroid.getX(); coords[1] = 0 - centroid.getY(); coords[2] = 0 - centroid.getZ(); Atom shiftVec = new AtomImpl(); shiftVec.setCoords(coords); return shiftVec; }
java
public static final Atom getCenterVector(Atom[] atomSet, Atom centroid){ double[] coords = new double[3]; coords[0] = 0 - centroid.getX(); coords[1] = 0 - centroid.getY(); coords[2] = 0 - centroid.getZ(); Atom shiftVec = new AtomImpl(); shiftVec.setCoords(coords); return shiftVec; }
[ "public", "static", "final", "Atom", "getCenterVector", "(", "Atom", "[", "]", "atomSet", ",", "Atom", "centroid", ")", "{", "double", "[", "]", "coords", "=", "new", "double", "[", "3", "]", ";", "coords", "[", "0", "]", "=", "0", "-", "centroid", ".", "getX", "(", ")", ";", "coords", "[", "1", "]", "=", "0", "-", "centroid", ".", "getY", "(", ")", ";", "coords", "[", "2", "]", "=", "0", "-", "centroid", ".", "getZ", "(", ")", ";", "Atom", "shiftVec", "=", "new", "AtomImpl", "(", ")", ";", "shiftVec", ".", "setCoords", "(", "coords", ")", ";", "return", "shiftVec", ";", "}" ]
Returns the Vector that needs to be applied to shift a set of atoms to the Centroid, if the centroid is already known @param atomSet array of Atoms @return the vector needed to shift the set of atoms to its geometric center
[ "Returns", "the", "Vector", "that", "needs", "to", "be", "applied", "to", "shift", "a", "set", "of", "atoms", "to", "the", "Centroid", "if", "the", "centroid", "is", "already", "known" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java#L917-L928
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/UnsignedUtils.java
UnsignedUtils.parseLong
public static long parseLong(String s, int radix) throws NumberFormatException { """ Returns the unsigned {@code long} value represented by a string with the given radix. @param s the string containing the unsigned {@code long} representation to be parsed. @param radix the radix to use while parsing {@code s} @throws NumberFormatException if the string does not contain a valid unsigned {@code long} with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} and {@link MAX_RADIX}. """ if (s == null || s.length() == 0 || s.trim().length() == 0) { throw new NumberFormatException("Null or empty string"); } if (radix < Character.MIN_RADIX || radix > MAX_RADIX) { throw new NumberFormatException("Illegal radix [" + radix + "]"); } int max_safe_pos = maxSafeDigits[radix] - 1; long value = 0; for (int pos = 0; pos < s.length(); pos++) { int digit = digit(s.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(s); } if (pos > max_safe_pos && overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + s); } value = (value * radix) + digit; } return value; }
java
public static long parseLong(String s, int radix) throws NumberFormatException { if (s == null || s.length() == 0 || s.trim().length() == 0) { throw new NumberFormatException("Null or empty string"); } if (radix < Character.MIN_RADIX || radix > MAX_RADIX) { throw new NumberFormatException("Illegal radix [" + radix + "]"); } int max_safe_pos = maxSafeDigits[radix] - 1; long value = 0; for (int pos = 0; pos < s.length(); pos++) { int digit = digit(s.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(s); } if (pos > max_safe_pos && overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + s); } value = (value * radix) + digit; } return value; }
[ "public", "static", "long", "parseLong", "(", "String", "s", ",", "int", "radix", ")", "throws", "NumberFormatException", "{", "if", "(", "s", "==", "null", "||", "s", ".", "length", "(", ")", "==", "0", "||", "s", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "NumberFormatException", "(", "\"Null or empty string\"", ")", ";", "}", "if", "(", "radix", "<", "Character", ".", "MIN_RADIX", "||", "radix", ">", "MAX_RADIX", ")", "{", "throw", "new", "NumberFormatException", "(", "\"Illegal radix [\"", "+", "radix", "+", "\"]\"", ")", ";", "}", "int", "max_safe_pos", "=", "maxSafeDigits", "[", "radix", "]", "-", "1", ";", "long", "value", "=", "0", ";", "for", "(", "int", "pos", "=", "0", ";", "pos", "<", "s", ".", "length", "(", ")", ";", "pos", "++", ")", "{", "int", "digit", "=", "digit", "(", "s", ".", "charAt", "(", "pos", ")", ",", "radix", ")", ";", "if", "(", "digit", "==", "-", "1", ")", "{", "throw", "new", "NumberFormatException", "(", "s", ")", ";", "}", "if", "(", "pos", ">", "max_safe_pos", "&&", "overflowInParse", "(", "value", ",", "digit", ",", "radix", ")", ")", "{", "throw", "new", "NumberFormatException", "(", "\"Too large for unsigned long: \"", "+", "s", ")", ";", "}", "value", "=", "(", "value", "*", "radix", ")", "+", "digit", ";", "}", "return", "value", ";", "}" ]
Returns the unsigned {@code long} value represented by a string with the given radix. @param s the string containing the unsigned {@code long} representation to be parsed. @param radix the radix to use while parsing {@code s} @throws NumberFormatException if the string does not contain a valid unsigned {@code long} with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} and {@link MAX_RADIX}.
[ "Returns", "the", "unsigned", "{", "@code", "long", "}", "value", "represented", "by", "a", "string", "with", "the", "given", "radix", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/UnsignedUtils.java#L151-L174
OpenLiberty/open-liberty
dev/com.ibm.ws.injection/src/com/ibm/ws/injectionengine/osgi/internal/OSGiInjectionScopeData.java
OSGiInjectionScopeData.getInjectionBinding
public InjectionBinding<?> getInjectionBinding(NamingConstants.JavaColonNamespace namespace, String name) throws NamingException { """ Gets the injection binding for a JNDI name. The caller is responsible for calling {@link #processDeferredReferenceData}. """ if (namespace == NamingConstants.JavaColonNamespace.COMP) { return lookup(compLock, compBindings, name); } if (namespace == NamingConstants.JavaColonNamespace.COMP_ENV) { return lookup(compLock, compEnvBindings, name); } if (namespace == this.namespace) { NonCompBinding nonCompBinding = lookup(nonCompEnvLock, nonCompBindings, name); return nonCompBinding == null ? null : nonCompBinding.binding; } return null; }
java
public InjectionBinding<?> getInjectionBinding(NamingConstants.JavaColonNamespace namespace, String name) throws NamingException { if (namespace == NamingConstants.JavaColonNamespace.COMP) { return lookup(compLock, compBindings, name); } if (namespace == NamingConstants.JavaColonNamespace.COMP_ENV) { return lookup(compLock, compEnvBindings, name); } if (namespace == this.namespace) { NonCompBinding nonCompBinding = lookup(nonCompEnvLock, nonCompBindings, name); return nonCompBinding == null ? null : nonCompBinding.binding; } return null; }
[ "public", "InjectionBinding", "<", "?", ">", "getInjectionBinding", "(", "NamingConstants", ".", "JavaColonNamespace", "namespace", ",", "String", "name", ")", "throws", "NamingException", "{", "if", "(", "namespace", "==", "NamingConstants", ".", "JavaColonNamespace", ".", "COMP", ")", "{", "return", "lookup", "(", "compLock", ",", "compBindings", ",", "name", ")", ";", "}", "if", "(", "namespace", "==", "NamingConstants", ".", "JavaColonNamespace", ".", "COMP_ENV", ")", "{", "return", "lookup", "(", "compLock", ",", "compEnvBindings", ",", "name", ")", ";", "}", "if", "(", "namespace", "==", "this", ".", "namespace", ")", "{", "NonCompBinding", "nonCompBinding", "=", "lookup", "(", "nonCompEnvLock", ",", "nonCompBindings", ",", "name", ")", ";", "return", "nonCompBinding", "==", "null", "?", "null", ":", "nonCompBinding", ".", "binding", ";", "}", "return", "null", ";", "}" ]
Gets the injection binding for a JNDI name. The caller is responsible for calling {@link #processDeferredReferenceData}.
[ "Gets", "the", "injection", "binding", "for", "a", "JNDI", "name", ".", "The", "caller", "is", "responsible", "for", "calling", "{" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.injection/src/com/ibm/ws/injectionengine/osgi/internal/OSGiInjectionScopeData.java#L376-L388
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java
JDBC4DatabaseMetaData.getSuperTypes
@Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { """ Retrieves a description of the user-defined type (UDT) hierarchies defined in a particular schema in this database. """ checkClosed(); throw SQLError.noSupport(); }
java
@Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "ResultSet", "getSuperTypes", "(", "String", "catalog", ",", "String", "schemaPattern", ",", "String", "typeNamePattern", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Retrieves a description of the user-defined type (UDT) hierarchies defined in a particular schema in this database.
[ "Retrieves", "a", "description", "of", "the", "user", "-", "defined", "type", "(", "UDT", ")", "hierarchies", "defined", "in", "a", "particular", "schema", "in", "this", "database", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java#L772-L777
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/EnvelopeSchemaConverter.java
EnvelopeSchemaConverter.getPayload
public byte[] getPayload(GenericRecord inputRecord, String payloadFieldName) { """ Get payload field from GenericRecord and convert to byte array """ ByteBuffer bb = (ByteBuffer) inputRecord.get(payloadFieldName); byte[] payloadBytes; if (bb.hasArray()) { payloadBytes = bb.array(); } else { payloadBytes = new byte[bb.remaining()]; bb.get(payloadBytes); } String hexString = new String(payloadBytes, StandardCharsets.UTF_8); return DatatypeConverter.parseHexBinary(hexString); }
java
public byte[] getPayload(GenericRecord inputRecord, String payloadFieldName) { ByteBuffer bb = (ByteBuffer) inputRecord.get(payloadFieldName); byte[] payloadBytes; if (bb.hasArray()) { payloadBytes = bb.array(); } else { payloadBytes = new byte[bb.remaining()]; bb.get(payloadBytes); } String hexString = new String(payloadBytes, StandardCharsets.UTF_8); return DatatypeConverter.parseHexBinary(hexString); }
[ "public", "byte", "[", "]", "getPayload", "(", "GenericRecord", "inputRecord", ",", "String", "payloadFieldName", ")", "{", "ByteBuffer", "bb", "=", "(", "ByteBuffer", ")", "inputRecord", ".", "get", "(", "payloadFieldName", ")", ";", "byte", "[", "]", "payloadBytes", ";", "if", "(", "bb", ".", "hasArray", "(", ")", ")", "{", "payloadBytes", "=", "bb", ".", "array", "(", ")", ";", "}", "else", "{", "payloadBytes", "=", "new", "byte", "[", "bb", ".", "remaining", "(", ")", "]", ";", "bb", ".", "get", "(", "payloadBytes", ")", ";", "}", "String", "hexString", "=", "new", "String", "(", "payloadBytes", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "return", "DatatypeConverter", ".", "parseHexBinary", "(", "hexString", ")", ";", "}" ]
Get payload field from GenericRecord and convert to byte array
[ "Get", "payload", "field", "from", "GenericRecord", "and", "convert", "to", "byte", "array" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/EnvelopeSchemaConverter.java#L134-L145
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.unescapeUriQueryParam
public static void unescapeUriQueryParam(final char[] text, final int offset, final int len, final Writer writer) throws IOException { """ <p> Perform am URI query parameter (name or value) <strong>unescape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use <tt>UTF-8</tt> in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be unescaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs """ unescapeUriQueryParam(text, offset, len, writer, DEFAULT_ENCODING); }
java
public static void unescapeUriQueryParam(final char[] text, final int offset, final int len, final Writer writer) throws IOException { unescapeUriQueryParam(text, offset, len, writer, DEFAULT_ENCODING); }
[ "public", "static", "void", "unescapeUriQueryParam", "(", "final", "char", "[", "]", "text", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "unescapeUriQueryParam", "(", "text", ",", "offset", ",", "len", ",", "writer", ",", "DEFAULT_ENCODING", ")", ";", "}" ]
<p> Perform am URI query parameter (name or value) <strong>unescape</strong> operation on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding. </p> <p> This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use <tt>UTF-8</tt> in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be unescaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs
[ "<p", ">", "Perform", "am", "URI", "query", "parameter", "(", "name", "or", "value", ")", "<strong", ">", "unescape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "char", "[]", "<", "/", "tt", ">", "input", "using", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "as", "encoding", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "will", "unescape", "every", "percent", "-", "encoded", "(", "<tt", ">", "%HH<", "/", "tt", ">", ")", "sequences", "present", "in", "input", "even", "for", "those", "characters", "that", "do", "not", "need", "to", "be", "percent", "-", "encoded", "in", "this", "context", "(", "unreserved", "characters", "can", "be", "percent", "-", "encoded", "even", "if", "/", "when", "this", "is", "not", "required", "though", "it", "is", "not", "generally", "considered", "a", "good", "practice", ")", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "will", "use", "<tt", ">", "UTF", "-", "8<", "/", "tt", ">", "in", "order", "to", "determine", "the", "characters", "specified", "in", "the", "percent", "-", "encoded", "byte", "sequences", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2592-L2595
XDean/Java-EX
src/main/java/xdean/jex/util/reflect/ReflectUtil.java
ReflectUtil.getFieldValue
@SuppressWarnings("unchecked") public static <T, O> O getFieldValue(Class<T> clz, T t, String fieldName) throws NoSuchFieldException { """ Get field value by name @param clz @param t @param fieldName @return @throws NoSuchFieldException """ Field field = clz.getDeclaredField(fieldName); field.setAccessible(true); try { return (O) field.get(t); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } }
java
@SuppressWarnings("unchecked") public static <T, O> O getFieldValue(Class<T> clz, T t, String fieldName) throws NoSuchFieldException { Field field = clz.getDeclaredField(fieldName); field.setAccessible(true); try { return (O) field.get(t); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ",", "O", ">", "O", "getFieldValue", "(", "Class", "<", "T", ">", "clz", ",", "T", "t", ",", "String", "fieldName", ")", "throws", "NoSuchFieldException", "{", "Field", "field", "=", "clz", ".", "getDeclaredField", "(", "fieldName", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "return", "(", "O", ")", "field", ".", "get", "(", "t", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "}" ]
Get field value by name @param clz @param t @param fieldName @return @throws NoSuchFieldException
[ "Get", "field", "value", "by", "name" ]
train
https://github.com/XDean/Java-EX/blob/9208ba71c5b2af9f9bd979d01fab2ff5e433b3e7/src/main/java/xdean/jex/util/reflect/ReflectUtil.java#L96-L105
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java
SqlBuilderHelper.forEachMethods
public static void forEachMethods(TypeElement typeElement, MethodFoundListener listener) { """ Iterate over methods. @param typeElement the type element @param listener the listener """ Elements elementUtils = BaseProcessor.elementUtils; List<? extends Element> list = elementUtils.getAllMembers(typeElement); for (Element item : list) { if (item.getKind() == ElementKind.METHOD) { listener.onMethod((ExecutableElement) item); } } }
java
public static void forEachMethods(TypeElement typeElement, MethodFoundListener listener) { Elements elementUtils = BaseProcessor.elementUtils; List<? extends Element> list = elementUtils.getAllMembers(typeElement); for (Element item : list) { if (item.getKind() == ElementKind.METHOD) { listener.onMethod((ExecutableElement) item); } } }
[ "public", "static", "void", "forEachMethods", "(", "TypeElement", "typeElement", ",", "MethodFoundListener", "listener", ")", "{", "Elements", "elementUtils", "=", "BaseProcessor", ".", "elementUtils", ";", "List", "<", "?", "extends", "Element", ">", "list", "=", "elementUtils", ".", "getAllMembers", "(", "typeElement", ")", ";", "for", "(", "Element", "item", ":", "list", ")", "{", "if", "(", "item", ".", "getKind", "(", ")", "==", "ElementKind", ".", "METHOD", ")", "{", "listener", ".", "onMethod", "(", "(", "ExecutableElement", ")", "item", ")", ";", "}", "}", "}" ]
Iterate over methods. @param typeElement the type element @param listener the listener
[ "Iterate", "over", "methods", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java#L347-L356
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/UsersApi.java
UsersApi.getUserDevices
public DevicesEnvelope getUserDevices(String userId, Integer offset, Integer count, Boolean includeProperties, String owner, Boolean includeShareInfo, String dtid) throws ApiException { """ Get User Devices Retrieve User&#39;s Devices @param userId User ID (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set (optional) @param includeProperties Optional. Boolean (true/false) - If false, only return the user&#39;s device types. If true, also return device types shared by other users. (optional) @param owner Return owned and/or shared devices. Default to ALL. (optional) @param includeShareInfo Include share info (optional) @param dtid Return only devices of this device type. If empty, assumes all device types allowed by the authorization. (optional) @return DevicesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<DevicesEnvelope> resp = getUserDevicesWithHttpInfo(userId, offset, count, includeProperties, owner, includeShareInfo, dtid); return resp.getData(); }
java
public DevicesEnvelope getUserDevices(String userId, Integer offset, Integer count, Boolean includeProperties, String owner, Boolean includeShareInfo, String dtid) throws ApiException { ApiResponse<DevicesEnvelope> resp = getUserDevicesWithHttpInfo(userId, offset, count, includeProperties, owner, includeShareInfo, dtid); return resp.getData(); }
[ "public", "DevicesEnvelope", "getUserDevices", "(", "String", "userId", ",", "Integer", "offset", ",", "Integer", "count", ",", "Boolean", "includeProperties", ",", "String", "owner", ",", "Boolean", "includeShareInfo", ",", "String", "dtid", ")", "throws", "ApiException", "{", "ApiResponse", "<", "DevicesEnvelope", ">", "resp", "=", "getUserDevicesWithHttpInfo", "(", "userId", ",", "offset", ",", "count", ",", "includeProperties", ",", "owner", ",", "includeShareInfo", ",", "dtid", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Get User Devices Retrieve User&#39;s Devices @param userId User ID (required) @param offset Offset for pagination. (optional) @param count Desired count of items in the result set (optional) @param includeProperties Optional. Boolean (true/false) - If false, only return the user&#39;s device types. If true, also return device types shared by other users. (optional) @param owner Return owned and/or shared devices. Default to ALL. (optional) @param includeShareInfo Include share info (optional) @param dtid Return only devices of this device type. If empty, assumes all device types allowed by the authorization. (optional) @return DevicesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "User", "Devices", "Retrieve", "User&#39", ";", "s", "Devices" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/UsersApi.java#L648-L651
protostuff/protostuff
protostuff-runtime/src/main/java/io/protostuff/runtime/DefaultIdStrategy.java
DefaultIdStrategy.registerDelegate
public <T> boolean registerDelegate(String className, Delegate<T> delegate) { """ Registers a delegate by specifying the class name. Returns true if registration is successful. """ return null == delegateMapping.putIfAbsent(className, new HasDelegate<T>(delegate, this)); }
java
public <T> boolean registerDelegate(String className, Delegate<T> delegate) { return null == delegateMapping.putIfAbsent(className, new HasDelegate<T>(delegate, this)); }
[ "public", "<", "T", ">", "boolean", "registerDelegate", "(", "String", "className", ",", "Delegate", "<", "T", ">", "delegate", ")", "{", "return", "null", "==", "delegateMapping", ".", "putIfAbsent", "(", "className", ",", "new", "HasDelegate", "<", "T", ">", "(", "delegate", ",", "this", ")", ")", ";", "}" ]
Registers a delegate by specifying the class name. Returns true if registration is successful.
[ "Registers", "a", "delegate", "by", "specifying", "the", "class", "name", ".", "Returns", "true", "if", "registration", "is", "successful", "." ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-runtime/src/main/java/io/protostuff/runtime/DefaultIdStrategy.java#L110-L113
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/sarlapp/FixedFatJarExportPage.java
FixedFatJarExportPage.createLibraryHandlingGroup
protected void createLibraryHandlingGroup(Composite parent) { """ Create the export options specification widgets. @param parent org.eclipse.swt.widgets.Composite """ fLibraryHandlingGroup= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); fLibraryHandlingGroup.setLayout(layout); fLibraryHandlingGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); createLabel(fLibraryHandlingGroup, FatJarPackagerMessages.FatJarPackageWizardPage_libraryHandlingGroupTitle, false); fExtractJarsRadioButton= new Button(fLibraryHandlingGroup, SWT.RADIO | SWT.LEFT); fExtractJarsRadioButton.setText(FatJarPackagerMessages.FatJarPackageWizardPage_extractJars_text); fExtractJarsRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fExtractJarsRadioButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if (((Button)event.widget).getSelection()) fLibraryHandler= new ExtractLibraryHandler(); } }); fPackageJarsRadioButton= new Button(fLibraryHandlingGroup, SWT.RADIO | SWT.LEFT); fPackageJarsRadioButton.setText(FatJarPackagerMessages.FatJarPackageWizardPage_packageJars_text); fPackageJarsRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fPackageJarsRadioButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if (((Button)event.widget).getSelection()) fLibraryHandler= new PackageLibraryHandler(); } }); fCopyJarFilesRadioButton= new Button(fLibraryHandlingGroup, SWT.RADIO | SWT.LEFT); fCopyJarFilesRadioButton.setText(FatJarPackagerMessages.FatJarPackageWizardPage_copyJarFiles_text); fCopyJarFilesRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fCopyJarFilesRadioButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if (((Button)event.widget).getSelection()) fLibraryHandler= new CopyLibraryHandler(); } }); // set default for first selection (no previous widget settings to restore) setLibraryHandler(new ExtractLibraryHandler()); }
java
protected void createLibraryHandlingGroup(Composite parent) { fLibraryHandlingGroup= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); fLibraryHandlingGroup.setLayout(layout); fLibraryHandlingGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); createLabel(fLibraryHandlingGroup, FatJarPackagerMessages.FatJarPackageWizardPage_libraryHandlingGroupTitle, false); fExtractJarsRadioButton= new Button(fLibraryHandlingGroup, SWT.RADIO | SWT.LEFT); fExtractJarsRadioButton.setText(FatJarPackagerMessages.FatJarPackageWizardPage_extractJars_text); fExtractJarsRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fExtractJarsRadioButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if (((Button)event.widget).getSelection()) fLibraryHandler= new ExtractLibraryHandler(); } }); fPackageJarsRadioButton= new Button(fLibraryHandlingGroup, SWT.RADIO | SWT.LEFT); fPackageJarsRadioButton.setText(FatJarPackagerMessages.FatJarPackageWizardPage_packageJars_text); fPackageJarsRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fPackageJarsRadioButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if (((Button)event.widget).getSelection()) fLibraryHandler= new PackageLibraryHandler(); } }); fCopyJarFilesRadioButton= new Button(fLibraryHandlingGroup, SWT.RADIO | SWT.LEFT); fCopyJarFilesRadioButton.setText(FatJarPackagerMessages.FatJarPackageWizardPage_copyJarFiles_text); fCopyJarFilesRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fCopyJarFilesRadioButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if (((Button)event.widget).getSelection()) fLibraryHandler= new CopyLibraryHandler(); } }); // set default for first selection (no previous widget settings to restore) setLibraryHandler(new ExtractLibraryHandler()); }
[ "protected", "void", "createLibraryHandlingGroup", "(", "Composite", "parent", ")", "{", "fLibraryHandlingGroup", "=", "new", "Composite", "(", "parent", ",", "SWT", ".", "NONE", ")", ";", "GridLayout", "layout", "=", "new", "GridLayout", "(", ")", ";", "fLibraryHandlingGroup", ".", "setLayout", "(", "layout", ")", ";", "fLibraryHandlingGroup", ".", "setLayoutData", "(", "new", "GridData", "(", "GridData", ".", "HORIZONTAL_ALIGN_FILL", "|", "GridData", ".", "VERTICAL_ALIGN_FILL", "|", "GridData", ".", "GRAB_HORIZONTAL", ")", ")", ";", "createLabel", "(", "fLibraryHandlingGroup", ",", "FatJarPackagerMessages", ".", "FatJarPackageWizardPage_libraryHandlingGroupTitle", ",", "false", ")", ";", "fExtractJarsRadioButton", "=", "new", "Button", "(", "fLibraryHandlingGroup", ",", "SWT", ".", "RADIO", "|", "SWT", ".", "LEFT", ")", ";", "fExtractJarsRadioButton", ".", "setText", "(", "FatJarPackagerMessages", ".", "FatJarPackageWizardPage_extractJars_text", ")", ";", "fExtractJarsRadioButton", ".", "setLayoutData", "(", "new", "GridData", "(", "GridData", ".", "FILL_HORIZONTAL", ")", ")", ";", "fExtractJarsRadioButton", ".", "addListener", "(", "SWT", ".", "Selection", ",", "new", "Listener", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "Event", "event", ")", "{", "if", "(", "(", "(", "Button", ")", "event", ".", "widget", ")", ".", "getSelection", "(", ")", ")", "fLibraryHandler", "=", "new", "ExtractLibraryHandler", "(", ")", ";", "}", "}", ")", ";", "fPackageJarsRadioButton", "=", "new", "Button", "(", "fLibraryHandlingGroup", ",", "SWT", ".", "RADIO", "|", "SWT", ".", "LEFT", ")", ";", "fPackageJarsRadioButton", ".", "setText", "(", "FatJarPackagerMessages", ".", "FatJarPackageWizardPage_packageJars_text", ")", ";", "fPackageJarsRadioButton", ".", "setLayoutData", "(", "new", "GridData", "(", "GridData", ".", "FILL_HORIZONTAL", ")", ")", ";", "fPackageJarsRadioButton", ".", "addListener", "(", "SWT", ".", "Selection", ",", "new", "Listener", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "Event", "event", ")", "{", "if", "(", "(", "(", "Button", ")", "event", ".", "widget", ")", ".", "getSelection", "(", ")", ")", "fLibraryHandler", "=", "new", "PackageLibraryHandler", "(", ")", ";", "}", "}", ")", ";", "fCopyJarFilesRadioButton", "=", "new", "Button", "(", "fLibraryHandlingGroup", ",", "SWT", ".", "RADIO", "|", "SWT", ".", "LEFT", ")", ";", "fCopyJarFilesRadioButton", ".", "setText", "(", "FatJarPackagerMessages", ".", "FatJarPackageWizardPage_copyJarFiles_text", ")", ";", "fCopyJarFilesRadioButton", ".", "setLayoutData", "(", "new", "GridData", "(", "GridData", ".", "FILL_HORIZONTAL", ")", ")", ";", "fCopyJarFilesRadioButton", ".", "addListener", "(", "SWT", ".", "Selection", ",", "new", "Listener", "(", ")", "{", "@", "Override", "public", "void", "handleEvent", "(", "Event", "event", ")", "{", "if", "(", "(", "(", "Button", ")", "event", ".", "widget", ")", ".", "getSelection", "(", ")", ")", "fLibraryHandler", "=", "new", "CopyLibraryHandler", "(", ")", ";", "}", "}", ")", ";", "// set default for first selection (no previous widget settings to restore)", "setLibraryHandler", "(", "new", "ExtractLibraryHandler", "(", ")", ")", ";", "}" ]
Create the export options specification widgets. @param parent org.eclipse.swt.widgets.Composite
[ "Create", "the", "export", "options", "specification", "widgets", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/sarlapp/FixedFatJarExportPage.java#L330-L373
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/ExpressionUtils.java
ExpressionUtils.createRootVariable
public static String createRootVariable(Path<?> path, int suffix) { """ Create a new root variable based on the given path and suffix @param path base path @param suffix suffix for variable name @return path expression """ String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES); return variable + "_" + suffix; }
java
public static String createRootVariable(Path<?> path, int suffix) { String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES); return variable + "_" + suffix; }
[ "public", "static", "String", "createRootVariable", "(", "Path", "<", "?", ">", "path", ",", "int", "suffix", ")", "{", "String", "variable", "=", "path", ".", "accept", "(", "ToStringVisitor", ".", "DEFAULT", ",", "TEMPLATES", ")", ";", "return", "variable", "+", "\"_\"", "+", "suffix", ";", "}" ]
Create a new root variable based on the given path and suffix @param path base path @param suffix suffix for variable name @return path expression
[ "Create", "a", "new", "root", "variable", "based", "on", "the", "given", "path", "and", "suffix" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/ExpressionUtils.java#L861-L864
apereo/cas
support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java
LdapUtils.getString
public static String getString(final LdapEntry entry, final String attribute, final String nullValue) { """ Reads a String value from the LdapEntry. @param entry the ldap entry @param attribute the attribute name @param nullValue the value which should be returning in case of a null value @return the string """ val attr = entry.getAttribute(attribute); if (attr == null) { return nullValue; } val v = attr.isBinary() ? new String(attr.getBinaryValue(), StandardCharsets.UTF_8) : attr.getStringValue(); if (StringUtils.isNotBlank(v)) { return v; } return nullValue; }
java
public static String getString(final LdapEntry entry, final String attribute, final String nullValue) { val attr = entry.getAttribute(attribute); if (attr == null) { return nullValue; } val v = attr.isBinary() ? new String(attr.getBinaryValue(), StandardCharsets.UTF_8) : attr.getStringValue(); if (StringUtils.isNotBlank(v)) { return v; } return nullValue; }
[ "public", "static", "String", "getString", "(", "final", "LdapEntry", "entry", ",", "final", "String", "attribute", ",", "final", "String", "nullValue", ")", "{", "val", "attr", "=", "entry", ".", "getAttribute", "(", "attribute", ")", ";", "if", "(", "attr", "==", "null", ")", "{", "return", "nullValue", ";", "}", "val", "v", "=", "attr", ".", "isBinary", "(", ")", "?", "new", "String", "(", "attr", ".", "getBinaryValue", "(", ")", ",", "StandardCharsets", ".", "UTF_8", ")", ":", "attr", ".", "getStringValue", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "v", ")", ")", "{", "return", "v", ";", "}", "return", "nullValue", ";", "}" ]
Reads a String value from the LdapEntry. @param entry the ldap entry @param attribute the attribute name @param nullValue the value which should be returning in case of a null value @return the string
[ "Reads", "a", "String", "value", "from", "the", "LdapEntry", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L202-L216
JetBrains/xodus
entity-store/src/main/java/jetbrains/exodus/entitystore/tables/PropertiesTable.java
PropertiesTable.put
public void put(@NotNull final PersistentStoreTransaction txn, final long localId, @NotNull final ByteIterable value, @Nullable final ByteIterable oldValue, final int propertyId, @NotNull final ComparableValueType type) { """ Setter for property value. Doesn't affect entity version and doesn't invalidate any of the cached entity iterables. @param localId entity local id. @param value property value. @param oldValue property old value @param propertyId property id """ final Store valueIdx = getOrCreateValueIndex(txn, propertyId); final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId)); final Transaction envTxn = txn.getEnvironmentTransaction(); primaryStore.put(envTxn, key, value); final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId); boolean success; if (oldValue == null) { success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue); } else { success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type)); } if (success) { for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) { valueIdx.put(envTxn, secondaryKey, secondaryValue); } } checkStatus(success, "Failed to put"); }
java
public void put(@NotNull final PersistentStoreTransaction txn, final long localId, @NotNull final ByteIterable value, @Nullable final ByteIterable oldValue, final int propertyId, @NotNull final ComparableValueType type) { final Store valueIdx = getOrCreateValueIndex(txn, propertyId); final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId)); final Transaction envTxn = txn.getEnvironmentTransaction(); primaryStore.put(envTxn, key, value); final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId); boolean success; if (oldValue == null) { success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue); } else { success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type)); } if (success) { for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) { valueIdx.put(envTxn, secondaryKey, secondaryValue); } } checkStatus(success, "Failed to put"); }
[ "public", "void", "put", "(", "@", "NotNull", "final", "PersistentStoreTransaction", "txn", ",", "final", "long", "localId", ",", "@", "NotNull", "final", "ByteIterable", "value", ",", "@", "Nullable", "final", "ByteIterable", "oldValue", ",", "final", "int", "propertyId", ",", "@", "NotNull", "final", "ComparableValueType", "type", ")", "{", "final", "Store", "valueIdx", "=", "getOrCreateValueIndex", "(", "txn", ",", "propertyId", ")", ";", "final", "ByteIterable", "key", "=", "PropertyKey", ".", "propertyKeyToEntry", "(", "new", "PropertyKey", "(", "localId", ",", "propertyId", ")", ")", ";", "final", "Transaction", "envTxn", "=", "txn", ".", "getEnvironmentTransaction", "(", ")", ";", "primaryStore", ".", "put", "(", "envTxn", ",", "key", ",", "value", ")", ";", "final", "ByteIterable", "secondaryValue", "=", "LongBinding", ".", "longToCompressedEntry", "(", "localId", ")", ";", "boolean", "success", ";", "if", "(", "oldValue", "==", "null", ")", "{", "success", "=", "allPropsIndex", ".", "put", "(", "envTxn", ",", "IntegerBinding", ".", "intToCompressedEntry", "(", "propertyId", ")", ",", "secondaryValue", ")", ";", "}", "else", "{", "success", "=", "deleteFromStore", "(", "envTxn", ",", "valueIdx", ",", "secondaryValue", ",", "createSecondaryKeys", "(", "store", ".", "getPropertyTypes", "(", ")", ",", "oldValue", ",", "type", ")", ")", ";", "}", "if", "(", "success", ")", "{", "for", "(", "final", "ByteIterable", "secondaryKey", ":", "createSecondaryKeys", "(", "store", ".", "getPropertyTypes", "(", ")", ",", "value", ",", "type", ")", ")", "{", "valueIdx", ".", "put", "(", "envTxn", ",", "secondaryKey", ",", "secondaryValue", ")", ";", "}", "}", "checkStatus", "(", "success", ",", "\"Failed to put\"", ")", ";", "}" ]
Setter for property value. Doesn't affect entity version and doesn't invalidate any of the cached entity iterables. @param localId entity local id. @param value property value. @param oldValue property old value @param propertyId property id
[ "Setter", "for", "property", "value", ".", "Doesn", "t", "affect", "entity", "version", "and", "doesn", "t", "invalidate", "any", "of", "the", "cached", "entity", "iterables", "." ]
train
https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/entity-store/src/main/java/jetbrains/exodus/entitystore/tables/PropertiesTable.java#L74-L97
OpenLiberty/open-liberty
dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ThreadContextBuilderImpl.java
ThreadContextBuilderImpl.failOnUnknownContextTypes
static void failOnUnknownContextTypes(HashSet<String> unknown, ArrayList<ThreadContextProvider> contextProviders) { """ Fail with error identifying unknown context type(s) that were specified. @param unknown set of unknown context types(s) that were specified. @param contextProviders """ Set<String> known = new TreeSet<>(); // alphabetize for readability of message known.addAll(Arrays.asList(ThreadContext.ALL_REMAINING, ThreadContext.APPLICATION, ThreadContext.CDI, ThreadContext.SECURITY, ThreadContext.TRANSACTION)); for (ThreadContextProvider provider : contextProviders) { String contextType = provider.getThreadContextType(); known.add(contextType); } throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1155.unknown.context", new TreeSet<String>(unknown), known)); }
java
static void failOnUnknownContextTypes(HashSet<String> unknown, ArrayList<ThreadContextProvider> contextProviders) { Set<String> known = new TreeSet<>(); // alphabetize for readability of message known.addAll(Arrays.asList(ThreadContext.ALL_REMAINING, ThreadContext.APPLICATION, ThreadContext.CDI, ThreadContext.SECURITY, ThreadContext.TRANSACTION)); for (ThreadContextProvider provider : contextProviders) { String contextType = provider.getThreadContextType(); known.add(contextType); } throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1155.unknown.context", new TreeSet<String>(unknown), known)); }
[ "static", "void", "failOnUnknownContextTypes", "(", "HashSet", "<", "String", ">", "unknown", ",", "ArrayList", "<", "ThreadContextProvider", ">", "contextProviders", ")", "{", "Set", "<", "String", ">", "known", "=", "new", "TreeSet", "<>", "(", ")", ";", "// alphabetize for readability of message", "known", ".", "addAll", "(", "Arrays", ".", "asList", "(", "ThreadContext", ".", "ALL_REMAINING", ",", "ThreadContext", ".", "APPLICATION", ",", "ThreadContext", ".", "CDI", ",", "ThreadContext", ".", "SECURITY", ",", "ThreadContext", ".", "TRANSACTION", ")", ")", ";", "for", "(", "ThreadContextProvider", "provider", ":", "contextProviders", ")", "{", "String", "contextType", "=", "provider", ".", "getThreadContextType", "(", ")", ";", "known", ".", "add", "(", "contextType", ")", ";", "}", "throw", "new", "IllegalStateException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"CWWKC1155.unknown.context\"", ",", "new", "TreeSet", "<", "String", ">", "(", "unknown", ")", ",", "known", ")", ")", ";", "}" ]
Fail with error identifying unknown context type(s) that were specified. @param unknown set of unknown context types(s) that were specified. @param contextProviders
[ "Fail", "with", "error", "identifying", "unknown", "context", "type", "(", "s", ")", "that", "were", "specified", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ThreadContextBuilderImpl.java#L156-L165
alkacon/opencms-core
src/org/opencms/db/generic/CmsUserDriver.java
CmsUserDriver.internalValidateResourceForOrgUnit
protected void internalValidateResourceForOrgUnit(CmsDbContext dbc, CmsOrganizationalUnit orgUnit, String rootPath) throws CmsException { """ Validates the given root path to be in the scope of the resources of the given organizational unit.<p> @param dbc the current db context @param orgUnit the organizational unit @param rootPath the root path to check @throws CmsException if something goes wrong """ CmsResource parentResource = m_driverManager.readResource( dbc, ORGUNIT_BASE_FOLDER + orgUnit.getName(), CmsResourceFilter.ALL); // assume not in scope boolean found = false; // iterate parent paths Iterator<String> itParentPaths = internalResourcesForOrgUnit(dbc, parentResource).iterator(); // until the given resource is found in scope while (!found && itParentPaths.hasNext()) { String parentPath = itParentPaths.next(); // check the scope if (rootPath.startsWith(parentPath)) { found = true; } } // if not in scope throw exception if (!found) { throw new CmsException( Messages.get().container( Messages.ERR_PATH_NOT_IN_PARENT_ORGUNIT_SCOPE_2, orgUnit.getName(), dbc.removeSiteRoot(rootPath))); } }
java
protected void internalValidateResourceForOrgUnit(CmsDbContext dbc, CmsOrganizationalUnit orgUnit, String rootPath) throws CmsException { CmsResource parentResource = m_driverManager.readResource( dbc, ORGUNIT_BASE_FOLDER + orgUnit.getName(), CmsResourceFilter.ALL); // assume not in scope boolean found = false; // iterate parent paths Iterator<String> itParentPaths = internalResourcesForOrgUnit(dbc, parentResource).iterator(); // until the given resource is found in scope while (!found && itParentPaths.hasNext()) { String parentPath = itParentPaths.next(); // check the scope if (rootPath.startsWith(parentPath)) { found = true; } } // if not in scope throw exception if (!found) { throw new CmsException( Messages.get().container( Messages.ERR_PATH_NOT_IN_PARENT_ORGUNIT_SCOPE_2, orgUnit.getName(), dbc.removeSiteRoot(rootPath))); } }
[ "protected", "void", "internalValidateResourceForOrgUnit", "(", "CmsDbContext", "dbc", ",", "CmsOrganizationalUnit", "orgUnit", ",", "String", "rootPath", ")", "throws", "CmsException", "{", "CmsResource", "parentResource", "=", "m_driverManager", ".", "readResource", "(", "dbc", ",", "ORGUNIT_BASE_FOLDER", "+", "orgUnit", ".", "getName", "(", ")", ",", "CmsResourceFilter", ".", "ALL", ")", ";", "// assume not in scope", "boolean", "found", "=", "false", ";", "// iterate parent paths", "Iterator", "<", "String", ">", "itParentPaths", "=", "internalResourcesForOrgUnit", "(", "dbc", ",", "parentResource", ")", ".", "iterator", "(", ")", ";", "// until the given resource is found in scope", "while", "(", "!", "found", "&&", "itParentPaths", ".", "hasNext", "(", ")", ")", "{", "String", "parentPath", "=", "itParentPaths", ".", "next", "(", ")", ";", "// check the scope", "if", "(", "rootPath", ".", "startsWith", "(", "parentPath", ")", ")", "{", "found", "=", "true", ";", "}", "}", "// if not in scope throw exception", "if", "(", "!", "found", ")", "{", "throw", "new", "CmsException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_PATH_NOT_IN_PARENT_ORGUNIT_SCOPE_2", ",", "orgUnit", ".", "getName", "(", ")", ",", "dbc", ".", "removeSiteRoot", "(", "rootPath", ")", ")", ")", ";", "}", "}" ]
Validates the given root path to be in the scope of the resources of the given organizational unit.<p> @param dbc the current db context @param orgUnit the organizational unit @param rootPath the root path to check @throws CmsException if something goes wrong
[ "Validates", "the", "given", "root", "path", "to", "be", "in", "the", "scope", "of", "the", "resources", "of", "the", "given", "organizational", "unit", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserDriver.java#L2843-L2870
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/persister/MapTilePersisterModel.java
MapTilePersisterModel.countTiles
private int countTiles(int widthInTile, int step, int s) { """ Count the active tiles. @param widthInTile The horizontal tiles. @param step The step number. @param s The s value. @return The active tiles. """ int count = 0; for (int tx = 0; tx < widthInTile; tx++) { for (int ty = 0; ty < map.getInTileHeight(); ty++) { if (map.getTile(tx + s * step, ty) != null) { count++; } } } return count; }
java
private int countTiles(int widthInTile, int step, int s) { int count = 0; for (int tx = 0; tx < widthInTile; tx++) { for (int ty = 0; ty < map.getInTileHeight(); ty++) { if (map.getTile(tx + s * step, ty) != null) { count++; } } } return count; }
[ "private", "int", "countTiles", "(", "int", "widthInTile", ",", "int", "step", ",", "int", "s", ")", "{", "int", "count", "=", "0", ";", "for", "(", "int", "tx", "=", "0", ";", "tx", "<", "widthInTile", ";", "tx", "++", ")", "{", "for", "(", "int", "ty", "=", "0", ";", "ty", "<", "map", ".", "getInTileHeight", "(", ")", ";", "ty", "++", ")", "{", "if", "(", "map", ".", "getTile", "(", "tx", "+", "s", "*", "step", ",", "ty", ")", "!=", "null", ")", "{", "count", "++", ";", "}", "}", "}", "return", "count", ";", "}" ]
Count the active tiles. @param widthInTile The horizontal tiles. @param step The step number. @param s The s value. @return The active tiles.
[ "Count", "the", "active", "tiles", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/persister/MapTilePersisterModel.java#L119-L133
unic/neba
spring/src/main/java/io/neba/spring/mvc/NebaViewResolver.java
NebaViewResolver.resolveViewName
@Override public View resolveViewName(String viewName, Locale locale) { """ Resolves a {@link View} from the provided view name. @param viewName must not be <code>null</code>. """ if (viewName == null) { throw new IllegalArgumentException("Method argument viewName must not be null."); } if (viewName.startsWith(REDIRECT_URL_PREFIX)) { String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length()); return new SlingRedirectView(redirectUrl, true, true); } if (viewName.startsWith(FORWARD_URL_PREFIX)) { String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length()); return new InternalResourceView(forwardUrl); } return resolveScriptingView(viewName); }
java
@Override public View resolveViewName(String viewName, Locale locale) { if (viewName == null) { throw new IllegalArgumentException("Method argument viewName must not be null."); } if (viewName.startsWith(REDIRECT_URL_PREFIX)) { String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length()); return new SlingRedirectView(redirectUrl, true, true); } if (viewName.startsWith(FORWARD_URL_PREFIX)) { String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length()); return new InternalResourceView(forwardUrl); } return resolveScriptingView(viewName); }
[ "@", "Override", "public", "View", "resolveViewName", "(", "String", "viewName", ",", "Locale", "locale", ")", "{", "if", "(", "viewName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Method argument viewName must not be null.\"", ")", ";", "}", "if", "(", "viewName", ".", "startsWith", "(", "REDIRECT_URL_PREFIX", ")", ")", "{", "String", "redirectUrl", "=", "viewName", ".", "substring", "(", "REDIRECT_URL_PREFIX", ".", "length", "(", ")", ")", ";", "return", "new", "SlingRedirectView", "(", "redirectUrl", ",", "true", ",", "true", ")", ";", "}", "if", "(", "viewName", ".", "startsWith", "(", "FORWARD_URL_PREFIX", ")", ")", "{", "String", "forwardUrl", "=", "viewName", ".", "substring", "(", "FORWARD_URL_PREFIX", ".", "length", "(", ")", ")", ";", "return", "new", "InternalResourceView", "(", "forwardUrl", ")", ";", "}", "return", "resolveScriptingView", "(", "viewName", ")", ";", "}" ]
Resolves a {@link View} from the provided view name. @param viewName must not be <code>null</code>.
[ "Resolves", "a", "{", "@link", "View", "}", "from", "the", "provided", "view", "name", "." ]
train
https://github.com/unic/neba/blob/4d762e60112a1fcb850926a56a9843d5aa424c4b/spring/src/main/java/io/neba/spring/mvc/NebaViewResolver.java#L59-L76
apache/incubator-druid
core/src/main/java/org/apache/druid/utils/CloseableUtils.java
CloseableUtils.closeBoth
public static void closeBoth(Closeable first, Closeable second) throws IOException { """ Call method instead of code like first.close(); second.close(); to have safety of {@link org.apache.druid.java.util.common.io.Closer}, but without associated boilerplate code of creating a Closer and registering objects in it. """ //noinspection EmptyTryBlock try (Closeable ignore1 = second; Closeable ignore2 = first) { // piggy-back try-with-resources semantics } }
java
public static void closeBoth(Closeable first, Closeable second) throws IOException { //noinspection EmptyTryBlock try (Closeable ignore1 = second; Closeable ignore2 = first) { // piggy-back try-with-resources semantics } }
[ "public", "static", "void", "closeBoth", "(", "Closeable", "first", ",", "Closeable", "second", ")", "throws", "IOException", "{", "//noinspection EmptyTryBlock", "try", "(", "Closeable", "ignore1", "=", "second", ";", "Closeable", "ignore2", "=", "first", ")", "{", "// piggy-back try-with-resources semantics", "}", "}" ]
Call method instead of code like first.close(); second.close(); to have safety of {@link org.apache.druid.java.util.common.io.Closer}, but without associated boilerplate code of creating a Closer and registering objects in it.
[ "Call", "method", "instead", "of", "code", "like" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/utils/CloseableUtils.java#L40-L46
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java
ManagedInstanceKeysInner.listByInstanceWithServiceResponseAsync
public Observable<ServiceResponse<Page<ManagedInstanceKeyInner>>> listByInstanceWithServiceResponseAsync(final String resourceGroupName, final String managedInstanceName, final String filter) { """ Gets a list of managed instance keys. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param filter An OData filter expression that filters elements in the collection. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ManagedInstanceKeyInner&gt; object """ return listByInstanceSinglePageAsync(resourceGroupName, managedInstanceName, filter) .concatMap(new Func1<ServiceResponse<Page<ManagedInstanceKeyInner>>, Observable<ServiceResponse<Page<ManagedInstanceKeyInner>>>>() { @Override public Observable<ServiceResponse<Page<ManagedInstanceKeyInner>>> call(ServiceResponse<Page<ManagedInstanceKeyInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByInstanceNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<ManagedInstanceKeyInner>>> listByInstanceWithServiceResponseAsync(final String resourceGroupName, final String managedInstanceName, final String filter) { return listByInstanceSinglePageAsync(resourceGroupName, managedInstanceName, filter) .concatMap(new Func1<ServiceResponse<Page<ManagedInstanceKeyInner>>, Observable<ServiceResponse<Page<ManagedInstanceKeyInner>>>>() { @Override public Observable<ServiceResponse<Page<ManagedInstanceKeyInner>>> call(ServiceResponse<Page<ManagedInstanceKeyInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByInstanceNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "ManagedInstanceKeyInner", ">", ">", ">", "listByInstanceWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "managedInstanceName", ",", "final", "String", "filter", ")", "{", "return", "listByInstanceSinglePageAsync", "(", "resourceGroupName", ",", "managedInstanceName", ",", "filter", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "ManagedInstanceKeyInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "ManagedInstanceKeyInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "ManagedInstanceKeyInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "ManagedInstanceKeyInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listByInstanceNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Gets a list of managed instance keys. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param filter An OData filter expression that filters elements in the collection. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ManagedInstanceKeyInner&gt; object
[ "Gets", "a", "list", "of", "managed", "instance", "keys", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java#L282-L294
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.setFeatureStyle
public static boolean setFeatureStyle(PolygonOptions polygonOptions, GeoPackage geoPackage, FeatureRow featureRow, float density) { """ Set the feature row style into the polygon options @param polygonOptions polygon options @param geoPackage GeoPackage @param featureRow feature row @param density display density: {@link android.util.DisplayMetrics#density} @return true if style was set into the polygon options """ FeatureStyleExtension featureStyleExtension = new FeatureStyleExtension(geoPackage); return setFeatureStyle(polygonOptions, featureStyleExtension, featureRow, density); }
java
public static boolean setFeatureStyle(PolygonOptions polygonOptions, GeoPackage geoPackage, FeatureRow featureRow, float density) { FeatureStyleExtension featureStyleExtension = new FeatureStyleExtension(geoPackage); return setFeatureStyle(polygonOptions, featureStyleExtension, featureRow, density); }
[ "public", "static", "boolean", "setFeatureStyle", "(", "PolygonOptions", "polygonOptions", ",", "GeoPackage", "geoPackage", ",", "FeatureRow", "featureRow", ",", "float", "density", ")", "{", "FeatureStyleExtension", "featureStyleExtension", "=", "new", "FeatureStyleExtension", "(", "geoPackage", ")", ";", "return", "setFeatureStyle", "(", "polygonOptions", ",", "featureStyleExtension", ",", "featureRow", ",", "density", ")", ";", "}" ]
Set the feature row style into the polygon options @param polygonOptions polygon options @param geoPackage GeoPackage @param featureRow feature row @param density display density: {@link android.util.DisplayMetrics#density} @return true if style was set into the polygon options
[ "Set", "the", "feature", "row", "style", "into", "the", "polygon", "options" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L505-L510
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java
ReflectUtil.getField
public static Field getField(Class<?> beanClass, String name) throws SecurityException { """ 查找指定类中的所有字段(包括非public字段),也包括父类和Object类的字段, 字段不存在则返回<code>null</code> @param beanClass 被查找字段的类,不能为null @param name 字段名 @return 字段 @throws SecurityException 安全异常 """ final Field[] fields = getFields(beanClass); if (ArrayUtil.isNotEmpty(fields)) { for (Field field : fields) { if ((name.equals(field.getName()))) { return field; } } } return null; }
java
public static Field getField(Class<?> beanClass, String name) throws SecurityException { final Field[] fields = getFields(beanClass); if (ArrayUtil.isNotEmpty(fields)) { for (Field field : fields) { if ((name.equals(field.getName()))) { return field; } } } return null; }
[ "public", "static", "Field", "getField", "(", "Class", "<", "?", ">", "beanClass", ",", "String", "name", ")", "throws", "SecurityException", "{", "final", "Field", "[", "]", "fields", "=", "getFields", "(", "beanClass", ")", ";", "if", "(", "ArrayUtil", ".", "isNotEmpty", "(", "fields", ")", ")", "{", "for", "(", "Field", "field", ":", "fields", ")", "{", "if", "(", "(", "name", ".", "equals", "(", "field", ".", "getName", "(", ")", ")", ")", ")", "{", "return", "field", ";", "}", "}", "}", "return", "null", ";", "}" ]
查找指定类中的所有字段(包括非public字段),也包括父类和Object类的字段, 字段不存在则返回<code>null</code> @param beanClass 被查找字段的类,不能为null @param name 字段名 @return 字段 @throws SecurityException 安全异常
[ "查找指定类中的所有字段(包括非public字段),也包括父类和Object类的字段,", "字段不存在则返回<code", ">", "null<", "/", "code", ">" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java#L115-L125
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/DashboardResources.java
DashboardResources.createDashboard
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Description("Creates a dashboard.") public DashboardDto createDashboard(@Context HttpServletRequest req, DashboardDto dashboardDto) { """ Creates a dashboard. @param req The HTTP request. @param dashboardDto The dashboard to create. @return The corresponding updated DTO for the created dashboard. @throws WebApplicationException If an error occurs. """ if (dashboardDto == null) { throw new WebApplicationException("Null dashboard object cannot be created.", Status.BAD_REQUEST); } PrincipalUser owner = validateAndGetOwner(req, dashboardDto.getOwnerName()); Dashboard dashboard = new Dashboard(getRemoteUser(req), dashboardDto.getName(), owner); copyProperties(dashboard, dashboardDto); return DashboardDto.transformToDto(dService.updateDashboard(dashboard)); }
java
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Description("Creates a dashboard.") public DashboardDto createDashboard(@Context HttpServletRequest req, DashboardDto dashboardDto) { if (dashboardDto == null) { throw new WebApplicationException("Null dashboard object cannot be created.", Status.BAD_REQUEST); } PrincipalUser owner = validateAndGetOwner(req, dashboardDto.getOwnerName()); Dashboard dashboard = new Dashboard(getRemoteUser(req), dashboardDto.getName(), owner); copyProperties(dashboard, dashboardDto); return DashboardDto.transformToDto(dService.updateDashboard(dashboard)); }
[ "@", "POST", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Description", "(", "\"Creates a dashboard.\"", ")", "public", "DashboardDto", "createDashboard", "(", "@", "Context", "HttpServletRequest", "req", ",", "DashboardDto", "dashboardDto", ")", "{", "if", "(", "dashboardDto", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Null dashboard object cannot be created.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "PrincipalUser", "owner", "=", "validateAndGetOwner", "(", "req", ",", "dashboardDto", ".", "getOwnerName", "(", ")", ")", ";", "Dashboard", "dashboard", "=", "new", "Dashboard", "(", "getRemoteUser", "(", "req", ")", ",", "dashboardDto", ".", "getName", "(", ")", ",", "owner", ")", ";", "copyProperties", "(", "dashboard", ",", "dashboardDto", ")", ";", "return", "DashboardDto", ".", "transformToDto", "(", "dService", ".", "updateDashboard", "(", "dashboard", ")", ")", ";", "}" ]
Creates a dashboard. @param req The HTTP request. @param dashboardDto The dashboard to create. @return The corresponding updated DTO for the created dashboard. @throws WebApplicationException If an error occurs.
[ "Creates", "a", "dashboard", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/DashboardResources.java#L285-L299
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java
BNFHeadersImpl.getElement
private HeaderElement getElement(HeaderKeys key) { """ Get an empty object for the new header name/value instance. @param key @return HeaderElement """ HeaderElement elem = this.headerElements; if (null != elem) { // disconnect it from the rest of the free list this.headerElements = elem.nextInstance; elem.nextInstance = null; elem.init(key); } else { elem = new HeaderElement(key, this); } return elem; }
java
private HeaderElement getElement(HeaderKeys key) { HeaderElement elem = this.headerElements; if (null != elem) { // disconnect it from the rest of the free list this.headerElements = elem.nextInstance; elem.nextInstance = null; elem.init(key); } else { elem = new HeaderElement(key, this); } return elem; }
[ "private", "HeaderElement", "getElement", "(", "HeaderKeys", "key", ")", "{", "HeaderElement", "elem", "=", "this", ".", "headerElements", ";", "if", "(", "null", "!=", "elem", ")", "{", "// disconnect it from the rest of the free list", "this", ".", "headerElements", "=", "elem", ".", "nextInstance", ";", "elem", ".", "nextInstance", "=", "null", ";", "elem", ".", "init", "(", "key", ")", ";", "}", "else", "{", "elem", "=", "new", "HeaderElement", "(", "key", ",", "this", ")", ";", "}", "return", "elem", ";", "}" ]
Get an empty object for the new header name/value instance. @param key @return HeaderElement
[ "Get", "an", "empty", "object", "for", "the", "new", "header", "name", "/", "value", "instance", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java#L2137-L2148
threerings/playn
core/src/playn/core/util/TextBlock.java
TextBlock.toImage
public CanvasImage toImage(Align align, int fillColor) { """ Creates a canvas image large enough to accommodate this text block and renders the lines into it. The image will include padding around the edge to ensure that antialiasing has a bit of extra space to do its work. """ float pad = pad(); CanvasImage image = graphics().createImage(bounds.width()+2*pad, bounds.height()+2*pad); image.canvas().setFillColor(fillColor); fill(image.canvas(), align, pad, pad); return image; }
java
public CanvasImage toImage(Align align, int fillColor) { float pad = pad(); CanvasImage image = graphics().createImage(bounds.width()+2*pad, bounds.height()+2*pad); image.canvas().setFillColor(fillColor); fill(image.canvas(), align, pad, pad); return image; }
[ "public", "CanvasImage", "toImage", "(", "Align", "align", ",", "int", "fillColor", ")", "{", "float", "pad", "=", "pad", "(", ")", ";", "CanvasImage", "image", "=", "graphics", "(", ")", ".", "createImage", "(", "bounds", ".", "width", "(", ")", "+", "2", "*", "pad", ",", "bounds", ".", "height", "(", ")", "+", "2", "*", "pad", ")", ";", "image", ".", "canvas", "(", ")", ".", "setFillColor", "(", "fillColor", ")", ";", "fill", "(", "image", ".", "canvas", "(", ")", ",", "align", ",", "pad", ",", "pad", ")", ";", "return", "image", ";", "}" ]
Creates a canvas image large enough to accommodate this text block and renders the lines into it. The image will include padding around the edge to ensure that antialiasing has a bit of extra space to do its work.
[ "Creates", "a", "canvas", "image", "large", "enough", "to", "accommodate", "this", "text", "block", "and", "renders", "the", "lines", "into", "it", ".", "The", "image", "will", "include", "padding", "around", "the", "edge", "to", "ensure", "that", "antialiasing", "has", "a", "bit", "of", "extra", "space", "to", "do", "its", "work", "." ]
train
https://github.com/threerings/playn/blob/c266eeb39188dcada4b00992a0d1199759e03d42/core/src/playn/core/util/TextBlock.java#L148-L154
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/sink/SocketClientSink.java
SocketClientSink.open
@Override public void open(Configuration parameters) throws Exception { """ Initialize the connection with the Socket in the server. @param parameters Configuration. """ try { synchronized (lock) { createConnection(); } } catch (IOException e) { throw new IOException("Cannot connect to socket server at " + hostName + ":" + port, e); } }
java
@Override public void open(Configuration parameters) throws Exception { try { synchronized (lock) { createConnection(); } } catch (IOException e) { throw new IOException("Cannot connect to socket server at " + hostName + ":" + port, e); } }
[ "@", "Override", "public", "void", "open", "(", "Configuration", "parameters", ")", "throws", "Exception", "{", "try", "{", "synchronized", "(", "lock", ")", "{", "createConnection", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Cannot connect to socket server at \"", "+", "hostName", "+", "\":\"", "+", "port", ",", "e", ")", ";", "}", "}" ]
Initialize the connection with the Socket in the server. @param parameters Configuration.
[ "Initialize", "the", "connection", "with", "the", "Socket", "in", "the", "server", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/sink/SocketClientSink.java#L125-L135
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/ScanResult.java
ScanResult.withItems
public ScanResult withItems(java.util.Collection<java.util.Map<String, AttributeValue>> items) { """ <p> An array of item attributes that match the scan criteria. Each element in this array consists of an attribute name and the value for that attribute. </p> @param items An array of item attributes that match the scan criteria. Each element in this array consists of an attribute name and the value for that attribute. @return Returns a reference to this object so that method calls can be chained together. """ setItems(items); return this; }
java
public ScanResult withItems(java.util.Collection<java.util.Map<String, AttributeValue>> items) { setItems(items); return this; }
[ "public", "ScanResult", "withItems", "(", "java", ".", "util", ".", "Collection", "<", "java", ".", "util", ".", "Map", "<", "String", ",", "AttributeValue", ">", ">", "items", ")", "{", "setItems", "(", "items", ")", ";", "return", "this", ";", "}" ]
<p> An array of item attributes that match the scan criteria. Each element in this array consists of an attribute name and the value for that attribute. </p> @param items An array of item attributes that match the scan criteria. Each element in this array consists of an attribute name and the value for that attribute. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "An", "array", "of", "item", "attributes", "that", "match", "the", "scan", "criteria", ".", "Each", "element", "in", "this", "array", "consists", "of", "an", "attribute", "name", "and", "the", "value", "for", "that", "attribute", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/ScanResult.java#L164-L167
alkacon/opencms-core
src/org/opencms/cmis/CmsCmisResourceHelper.java
CmsCmisResourceHelper.collectAllowableActions
protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) { """ Compiles the allowable actions for a file or folder. @param cms the current CMS context @param file the resource for which we want the allowable actions @return the allowable actions for the given resource """ try { if (file == null) { throw new IllegalArgumentException("File must not be null!"); } CmsLock lock = cms.getLock(file); CmsUser user = cms.getRequestContext().getCurrentUser(); boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject() && (lock.isOwnedBy(user) || lock.isLockableBy(user)) && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT); boolean isReadOnly = !canWrite; boolean isFolder = file.isFolder(); boolean isRoot = file.getRootPath().length() <= 1; Set<Action> aas = new LinkedHashSet<Action>(); addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot); addAction(aas, Action.CAN_GET_PROPERTIES, true); addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly); addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot); addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot); if (isFolder) { addAction(aas, Action.CAN_GET_DESCENDANTS, true); addAction(aas, Action.CAN_GET_CHILDREN, true); addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot); addAction(aas, Action.CAN_GET_FOLDER_TREE, true); addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly); addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly); addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly); } else { addAction(aas, Action.CAN_GET_CONTENT_STREAM, true); addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly); addAction(aas, Action.CAN_GET_ALL_VERSIONS, true); } AllowableActionsImpl result = new AllowableActionsImpl(); result.setAllowableActions(aas); return result; } catch (CmsException e) { handleCmsException(e); return null; } }
java
protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) { try { if (file == null) { throw new IllegalArgumentException("File must not be null!"); } CmsLock lock = cms.getLock(file); CmsUser user = cms.getRequestContext().getCurrentUser(); boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject() && (lock.isOwnedBy(user) || lock.isLockableBy(user)) && cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT); boolean isReadOnly = !canWrite; boolean isFolder = file.isFolder(); boolean isRoot = file.getRootPath().length() <= 1; Set<Action> aas = new LinkedHashSet<Action>(); addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot); addAction(aas, Action.CAN_GET_PROPERTIES, true); addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly); addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot); addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot); if (isFolder) { addAction(aas, Action.CAN_GET_DESCENDANTS, true); addAction(aas, Action.CAN_GET_CHILDREN, true); addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot); addAction(aas, Action.CAN_GET_FOLDER_TREE, true); addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly); addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly); addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly); } else { addAction(aas, Action.CAN_GET_CONTENT_STREAM, true); addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly); addAction(aas, Action.CAN_GET_ALL_VERSIONS, true); } AllowableActionsImpl result = new AllowableActionsImpl(); result.setAllowableActions(aas); return result; } catch (CmsException e) { handleCmsException(e); return null; } }
[ "protected", "AllowableActions", "collectAllowableActions", "(", "CmsObject", "cms", ",", "CmsResource", "file", ")", "{", "try", "{", "if", "(", "file", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"File must not be null!\"", ")", ";", "}", "CmsLock", "lock", "=", "cms", ".", "getLock", "(", "file", ")", ";", "CmsUser", "user", "=", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ";", "boolean", "canWrite", "=", "!", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentProject", "(", ")", ".", "isOnlineProject", "(", ")", "&&", "(", "lock", ".", "isOwnedBy", "(", "user", ")", "||", "lock", ".", "isLockableBy", "(", "user", ")", ")", "&&", "cms", ".", "hasPermissions", "(", "file", ",", "CmsPermissionSet", ".", "ACCESS_WRITE", ",", "false", ",", "CmsResourceFilter", ".", "DEFAULT", ")", ";", "boolean", "isReadOnly", "=", "!", "canWrite", ";", "boolean", "isFolder", "=", "file", ".", "isFolder", "(", ")", ";", "boolean", "isRoot", "=", "file", ".", "getRootPath", "(", ")", ".", "length", "(", ")", "<=", "1", ";", "Set", "<", "Action", ">", "aas", "=", "new", "LinkedHashSet", "<", "Action", ">", "(", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_OBJECT_PARENTS", ",", "!", "isRoot", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_PROPERTIES", ",", "true", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_UPDATE_PROPERTIES", ",", "!", "isReadOnly", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_MOVE_OBJECT", ",", "!", "isReadOnly", "&&", "!", "isRoot", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_DELETE_OBJECT", ",", "!", "isReadOnly", "&&", "!", "isRoot", ")", ";", "if", "(", "isFolder", ")", "{", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_DESCENDANTS", ",", "true", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_CHILDREN", ",", "true", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_FOLDER_PARENT", ",", "!", "isRoot", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_FOLDER_TREE", ",", "true", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_CREATE_DOCUMENT", ",", "!", "isReadOnly", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_CREATE_FOLDER", ",", "!", "isReadOnly", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_DELETE_TREE", ",", "!", "isReadOnly", ")", ";", "}", "else", "{", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_CONTENT_STREAM", ",", "true", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_SET_CONTENT_STREAM", ",", "!", "isReadOnly", ")", ";", "addAction", "(", "aas", ",", "Action", ".", "CAN_GET_ALL_VERSIONS", ",", "true", ")", ";", "}", "AllowableActionsImpl", "result", "=", "new", "AllowableActionsImpl", "(", ")", ";", "result", ".", "setAllowableActions", "(", "aas", ")", ";", "return", "result", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "handleCmsException", "(", "e", ")", ";", "return", "null", ";", "}", "}" ]
Compiles the allowable actions for a file or folder. @param cms the current CMS context @param file the resource for which we want the allowable actions @return the allowable actions for the given resource
[ "Compiles", "the", "allowable", "actions", "for", "a", "file", "or", "folder", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cmis/CmsCmisResourceHelper.java#L276-L318
kenyee/android-ddp-client
src/com/keysolutions/ddpclient/android/DDPStateSingleton.java
DDPStateSingleton.handleLoginResult
@SuppressWarnings("unchecked") public void handleLoginResult(Map<String, Object> jsonFields) { """ Handles callback from login command @param jsonFields fields from result """ if (jsonFields.containsKey("result")) { Map<String, Object> result = (Map<String, Object>) jsonFields .get(DdpMessageField.RESULT); mResumeToken = (String) result.get("token"); saveResumeToken(mResumeToken); mUserId = (String) result.get("id"); mDDPState = DDPSTATE.LoggedIn; broadcastConnectionState(mDDPState); } else if (jsonFields.containsKey("error")) { Map<String, Object> error = (Map<String, Object>) jsonFields .get(DdpMessageField.ERROR); broadcastDDPError((String) error.get("message")); } }
java
@SuppressWarnings("unchecked") public void handleLoginResult(Map<String, Object> jsonFields) { if (jsonFields.containsKey("result")) { Map<String, Object> result = (Map<String, Object>) jsonFields .get(DdpMessageField.RESULT); mResumeToken = (String) result.get("token"); saveResumeToken(mResumeToken); mUserId = (String) result.get("id"); mDDPState = DDPSTATE.LoggedIn; broadcastConnectionState(mDDPState); } else if (jsonFields.containsKey("error")) { Map<String, Object> error = (Map<String, Object>) jsonFields .get(DdpMessageField.ERROR); broadcastDDPError((String) error.get("message")); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "void", "handleLoginResult", "(", "Map", "<", "String", ",", "Object", ">", "jsonFields", ")", "{", "if", "(", "jsonFields", ".", "containsKey", "(", "\"result\"", ")", ")", "{", "Map", "<", "String", ",", "Object", ">", "result", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "jsonFields", ".", "get", "(", "DdpMessageField", ".", "RESULT", ")", ";", "mResumeToken", "=", "(", "String", ")", "result", ".", "get", "(", "\"token\"", ")", ";", "saveResumeToken", "(", "mResumeToken", ")", ";", "mUserId", "=", "(", "String", ")", "result", ".", "get", "(", "\"id\"", ")", ";", "mDDPState", "=", "DDPSTATE", ".", "LoggedIn", ";", "broadcastConnectionState", "(", "mDDPState", ")", ";", "}", "else", "if", "(", "jsonFields", ".", "containsKey", "(", "\"error\"", ")", ")", "{", "Map", "<", "String", ",", "Object", ">", "error", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "jsonFields", ".", "get", "(", "DdpMessageField", ".", "ERROR", ")", ";", "broadcastDDPError", "(", "(", "String", ")", "error", ".", "get", "(", "\"message\"", ")", ")", ";", "}", "}" ]
Handles callback from login command @param jsonFields fields from result
[ "Handles", "callback", "from", "login", "command" ]
train
https://github.com/kenyee/android-ddp-client/blob/6ab416e415570a03f96c383497144dd742de3f08/src/com/keysolutions/ddpclient/android/DDPStateSingleton.java#L389-L404
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/VoiceApi.java
VoiceApi.pauseRecording
public ApiSuccessResponse pauseRecording(String id, PauseRecordingBody pauseRecordingBody) throws ApiException { """ Pause recording on a call Pause recording on the specified call. @param id The connection ID of the call. (required) @param pauseRecordingBody Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = pauseRecordingWithHttpInfo(id, pauseRecordingBody); return resp.getData(); }
java
public ApiSuccessResponse pauseRecording(String id, PauseRecordingBody pauseRecordingBody) throws ApiException { ApiResponse<ApiSuccessResponse> resp = pauseRecordingWithHttpInfo(id, pauseRecordingBody); return resp.getData(); }
[ "public", "ApiSuccessResponse", "pauseRecording", "(", "String", "id", ",", "PauseRecordingBody", "pauseRecordingBody", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "pauseRecordingWithHttpInfo", "(", "id", ",", "pauseRecordingBody", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Pause recording on a call Pause recording on the specified call. @param id The connection ID of the call. (required) @param pauseRecordingBody Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Pause", "recording", "on", "a", "call", "Pause", "recording", "on", "the", "specified", "call", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L2584-L2587
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.readResource
public CmsResource readResource(CmsRequestContext context, CmsUUID structureID, CmsResourceFilter filter) throws CmsException { """ Reads a resource from the VFS, using the specified resource filter.<p> A resource may be of type <code>{@link CmsFile}</code> or <code>{@link CmsFolder}</code>. In case of a file, the resource will not contain the binary file content. Since reading the binary content is a cost-expensive database operation, it's recommended to work with resources if possible, and only read the file content when absolutely required. To "upgrade" a resource to a file, use <code>{@link CmsObject#readFile(CmsResource)}</code>.<p> The specified filter controls what kind of resources should be "found" during the read operation. This will depend on the application. For example, using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> will ignore the date release / date expired information of the resource.<p> @param context the current request context @param structureID the ID of the structure which will be used) @param filter the resource filter to use while reading @return the resource that was read @throws CmsException if the resource could not be read for any reason @see CmsObject#readResource(CmsUUID, CmsResourceFilter) @see CmsObject#readResource(CmsUUID) @see CmsObject#readFile(CmsResource) """ CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readResource(dbc, structureID, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_RESOURCE_FOR_ID_1, structureID), e); } finally { dbc.clear(); } return result; }
java
public CmsResource readResource(CmsRequestContext context, CmsUUID structureID, CmsResourceFilter filter) throws CmsException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readResource(dbc, structureID, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_RESOURCE_FOR_ID_1, structureID), e); } finally { dbc.clear(); } return result; }
[ "public", "CmsResource", "readResource", "(", "CmsRequestContext", "context", ",", "CmsUUID", "structureID", ",", "CmsResourceFilter", "filter", ")", "throws", "CmsException", "{", "CmsResource", "result", "=", "null", ";", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "try", "{", "result", "=", "readResource", "(", "dbc", ",", "structureID", ",", "filter", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "dbc", ".", "report", "(", "null", ",", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_READ_RESOURCE_FOR_ID_1", ",", "structureID", ")", ",", "e", ")", ";", "}", "finally", "{", "dbc", ".", "clear", "(", ")", ";", "}", "return", "result", ";", "}" ]
Reads a resource from the VFS, using the specified resource filter.<p> A resource may be of type <code>{@link CmsFile}</code> or <code>{@link CmsFolder}</code>. In case of a file, the resource will not contain the binary file content. Since reading the binary content is a cost-expensive database operation, it's recommended to work with resources if possible, and only read the file content when absolutely required. To "upgrade" a resource to a file, use <code>{@link CmsObject#readFile(CmsResource)}</code>.<p> The specified filter controls what kind of resources should be "found" during the read operation. This will depend on the application. For example, using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> will ignore the date release / date expired information of the resource.<p> @param context the current request context @param structureID the ID of the structure which will be used) @param filter the resource filter to use while reading @return the resource that was read @throws CmsException if the resource could not be read for any reason @see CmsObject#readResource(CmsUUID, CmsResourceFilter) @see CmsObject#readResource(CmsUUID) @see CmsObject#readFile(CmsResource)
[ "Reads", "a", "resource", "from", "the", "VFS", "using", "the", "specified", "resource", "filter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L5017-L5030
rundeck/rundeck
core/src/main/java/com/dtolabs/launcher/Setup.java
Setup.getTemplateFile
private File getTemplateFile(String filename) throws IOException { """ Look for template in the jar resources, otherwise look for it on filepath @param filename template name @return file @throws java.io.IOException on io error """ File templateFile=null; final String resource = TEMPLATE_RESOURCES_PATH + "/" + filename; InputStream is = Setup.class.getClassLoader().getResourceAsStream(resource); if (null == is) { throw new RuntimeException("Unable to load required template: " + resource); } templateFile = File.createTempFile("temp", filename); templateFile.deleteOnExit(); try { return copyToNativeLineEndings(is, templateFile); } finally { is.close(); } }
java
private File getTemplateFile(String filename) throws IOException { File templateFile=null; final String resource = TEMPLATE_RESOURCES_PATH + "/" + filename; InputStream is = Setup.class.getClassLoader().getResourceAsStream(resource); if (null == is) { throw new RuntimeException("Unable to load required template: " + resource); } templateFile = File.createTempFile("temp", filename); templateFile.deleteOnExit(); try { return copyToNativeLineEndings(is, templateFile); } finally { is.close(); } }
[ "private", "File", "getTemplateFile", "(", "String", "filename", ")", "throws", "IOException", "{", "File", "templateFile", "=", "null", ";", "final", "String", "resource", "=", "TEMPLATE_RESOURCES_PATH", "+", "\"/\"", "+", "filename", ";", "InputStream", "is", "=", "Setup", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "resource", ")", ";", "if", "(", "null", "==", "is", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to load required template: \"", "+", "resource", ")", ";", "}", "templateFile", "=", "File", ".", "createTempFile", "(", "\"temp\"", ",", "filename", ")", ";", "templateFile", ".", "deleteOnExit", "(", ")", ";", "try", "{", "return", "copyToNativeLineEndings", "(", "is", ",", "templateFile", ")", ";", "}", "finally", "{", "is", ".", "close", "(", ")", ";", "}", "}" ]
Look for template in the jar resources, otherwise look for it on filepath @param filename template name @return file @throws java.io.IOException on io error
[ "Look", "for", "template", "in", "the", "jar", "resources", "otherwise", "look", "for", "it", "on", "filepath" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/launcher/Setup.java#L215-L229
apache/incubator-atlas
repository/src/main/java/org/apache/atlas/gremlin/optimizer/GremlinQueryOptimizer.java
GremlinQueryOptimizer.visitCallHierarchy
public static void visitCallHierarchy(GroovyExpression expr, CallHierarchyVisitor visitor) { """ Visits all expressions in the call hierarchy of an expression. For example, in the expression g.V().has('x','y'), the order would be <ol> <li>pre-visit has('x','y')</li> <li>pre-visit V()</li> <li>visit g (non-function caller)</li> <li>post-visit V()</li> <li>post-visit has('x','y')</li> </ol> @param expr @param visitor """ if (expr == null) { visitor.visitNullCaller(); return; } if (expr instanceof AbstractFunctionExpression) { AbstractFunctionExpression functionCall = (AbstractFunctionExpression)expr; if (!visitor.preVisitFunctionCaller(functionCall)) { return; } GroovyExpression caller = functionCall.getCaller(); visitCallHierarchy(caller, visitor); if (!visitor.postVisitFunctionCaller(functionCall)) { return; } } else { visitor.visitNonFunctionCaller(expr); } }
java
public static void visitCallHierarchy(GroovyExpression expr, CallHierarchyVisitor visitor) { if (expr == null) { visitor.visitNullCaller(); return; } if (expr instanceof AbstractFunctionExpression) { AbstractFunctionExpression functionCall = (AbstractFunctionExpression)expr; if (!visitor.preVisitFunctionCaller(functionCall)) { return; } GroovyExpression caller = functionCall.getCaller(); visitCallHierarchy(caller, visitor); if (!visitor.postVisitFunctionCaller(functionCall)) { return; } } else { visitor.visitNonFunctionCaller(expr); } }
[ "public", "static", "void", "visitCallHierarchy", "(", "GroovyExpression", "expr", ",", "CallHierarchyVisitor", "visitor", ")", "{", "if", "(", "expr", "==", "null", ")", "{", "visitor", ".", "visitNullCaller", "(", ")", ";", "return", ";", "}", "if", "(", "expr", "instanceof", "AbstractFunctionExpression", ")", "{", "AbstractFunctionExpression", "functionCall", "=", "(", "AbstractFunctionExpression", ")", "expr", ";", "if", "(", "!", "visitor", ".", "preVisitFunctionCaller", "(", "functionCall", ")", ")", "{", "return", ";", "}", "GroovyExpression", "caller", "=", "functionCall", ".", "getCaller", "(", ")", ";", "visitCallHierarchy", "(", "caller", ",", "visitor", ")", ";", "if", "(", "!", "visitor", ".", "postVisitFunctionCaller", "(", "functionCall", ")", ")", "{", "return", ";", "}", "}", "else", "{", "visitor", ".", "visitNonFunctionCaller", "(", "expr", ")", ";", "}", "}" ]
Visits all expressions in the call hierarchy of an expression. For example, in the expression g.V().has('x','y'), the order would be <ol> <li>pre-visit has('x','y')</li> <li>pre-visit V()</li> <li>visit g (non-function caller)</li> <li>post-visit V()</li> <li>post-visit has('x','y')</li> </ol> @param expr @param visitor
[ "Visits", "all", "expressions", "in", "the", "call", "hierarchy", "of", "an", "expression", ".", "For", "example", "in", "the", "expression", "g", ".", "V", "()", ".", "has", "(", "x", "y", ")", "the", "order", "would", "be", "<ol", ">", "<li", ">", "pre", "-", "visit", "has", "(", "x", "y", ")", "<", "/", "li", ">", "<li", ">", "pre", "-", "visit", "V", "()", "<", "/", "li", ">", "<li", ">", "visit", "g", "(", "non", "-", "function", "caller", ")", "<", "/", "li", ">", "<li", ">", "post", "-", "visit", "V", "()", "<", "/", "li", ">", "<li", ">", "post", "-", "visit", "has", "(", "x", "y", ")", "<", "/", "li", ">", "<", "/", "ol", ">" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/gremlin/optimizer/GremlinQueryOptimizer.java#L166-L185
hap-java/HAP-Java
src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java
HomekitSRP6Routines.createRandomBigIntegerInRange
protected static BigInteger createRandomBigIntegerInRange( final BigInteger min, final BigInteger max, final SecureRandom random) { """ Returns a random big integer in the specified range [min, max]. @param min The least value that may be generated. Must not be {@code null}. @param max The greatest value that may be generated. Must not be {@code null}. @param random Source of randomness. Must not be {@code null}. @return A random big integer in the range [min, max]. """ final int cmp = min.compareTo(max); if (cmp >= 0) { if (cmp > 0) throw new IllegalArgumentException("'min' may not be greater than 'max'"); return min; } if (min.bitLength() > max.bitLength() / 2) return createRandomBigIntegerInRange(BigInteger.ZERO, max.subtract(min), random).add(min); final int MAX_ITERATIONS = 1000; for (int i = 0; i < MAX_ITERATIONS; ++i) { BigInteger x = new BigInteger(max.bitLength(), random); if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0) return x; } // fall back to a faster (restricted) method return new BigInteger(max.subtract(min).bitLength() - 1, random).add(min); }
java
protected static BigInteger createRandomBigIntegerInRange( final BigInteger min, final BigInteger max, final SecureRandom random) { final int cmp = min.compareTo(max); if (cmp >= 0) { if (cmp > 0) throw new IllegalArgumentException("'min' may not be greater than 'max'"); return min; } if (min.bitLength() > max.bitLength() / 2) return createRandomBigIntegerInRange(BigInteger.ZERO, max.subtract(min), random).add(min); final int MAX_ITERATIONS = 1000; for (int i = 0; i < MAX_ITERATIONS; ++i) { BigInteger x = new BigInteger(max.bitLength(), random); if (x.compareTo(min) >= 0 && x.compareTo(max) <= 0) return x; } // fall back to a faster (restricted) method return new BigInteger(max.subtract(min).bitLength() - 1, random).add(min); }
[ "protected", "static", "BigInteger", "createRandomBigIntegerInRange", "(", "final", "BigInteger", "min", ",", "final", "BigInteger", "max", ",", "final", "SecureRandom", "random", ")", "{", "final", "int", "cmp", "=", "min", ".", "compareTo", "(", "max", ")", ";", "if", "(", "cmp", ">=", "0", ")", "{", "if", "(", "cmp", ">", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"'min' may not be greater than 'max'\"", ")", ";", "return", "min", ";", "}", "if", "(", "min", ".", "bitLength", "(", ")", ">", "max", ".", "bitLength", "(", ")", "/", "2", ")", "return", "createRandomBigIntegerInRange", "(", "BigInteger", ".", "ZERO", ",", "max", ".", "subtract", "(", "min", ")", ",", "random", ")", ".", "add", "(", "min", ")", ";", "final", "int", "MAX_ITERATIONS", "=", "1000", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "MAX_ITERATIONS", ";", "++", "i", ")", "{", "BigInteger", "x", "=", "new", "BigInteger", "(", "max", ".", "bitLength", "(", ")", ",", "random", ")", ";", "if", "(", "x", ".", "compareTo", "(", "min", ")", ">=", "0", "&&", "x", ".", "compareTo", "(", "max", ")", "<=", "0", ")", "return", "x", ";", "}", "// fall back to a faster (restricted) method", "return", "new", "BigInteger", "(", "max", ".", "subtract", "(", "min", ")", ".", "bitLength", "(", ")", "-", "1", ",", "random", ")", ".", "add", "(", "min", ")", ";", "}" ]
Returns a random big integer in the specified range [min, max]. @param min The least value that may be generated. Must not be {@code null}. @param max The greatest value that may be generated. Must not be {@code null}. @param random Source of randomness. Must not be {@code null}. @return A random big integer in the range [min, max].
[ "Returns", "a", "random", "big", "integer", "in", "the", "specified", "range", "[", "min", "max", "]", "." ]
train
https://github.com/hap-java/HAP-Java/blob/d2b2f4f1579580a2b5958af3a192128345843db9/src/main/java/io/github/hapjava/impl/pairing/HomekitSRP6Routines.java#L31-L57
kaazing/gateway
service/update.check/src/main/java/org/kaazing/gateway/service/update/check/GatewayVersion.java
GatewayVersion.parseGatewayVersion
public static GatewayVersion parseGatewayVersion(String version) throws Exception { """ Parses a GatewayVersion from a String @param version @return @throws Exception """ if ("develop-SNAPSHOT".equals(version)) { return new GatewayVersion(0, 0, 0); } else { String regex = "(?<major>[0-9]+)\\.(?<minor>[0-9]+)\\.(?<patch>[0-9]+)-?(?<rc>[RC0-9{3}]*)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(version); if (matcher.matches()) { int major = Integer.parseInt(matcher.group("major")); int minor = Integer.parseInt(matcher.group("minor")); int patch = Integer.parseInt(matcher.group("patch")); String rc = matcher.group("rc"); return new GatewayVersion(major, minor, patch, rc); } else { throw new IllegalArgumentException(String.format("version String is not of form %s", regex)); } } }
java
public static GatewayVersion parseGatewayVersion(String version) throws Exception { if ("develop-SNAPSHOT".equals(version)) { return new GatewayVersion(0, 0, 0); } else { String regex = "(?<major>[0-9]+)\\.(?<minor>[0-9]+)\\.(?<patch>[0-9]+)-?(?<rc>[RC0-9{3}]*)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(version); if (matcher.matches()) { int major = Integer.parseInt(matcher.group("major")); int minor = Integer.parseInt(matcher.group("minor")); int patch = Integer.parseInt(matcher.group("patch")); String rc = matcher.group("rc"); return new GatewayVersion(major, minor, patch, rc); } else { throw new IllegalArgumentException(String.format("version String is not of form %s", regex)); } } }
[ "public", "static", "GatewayVersion", "parseGatewayVersion", "(", "String", "version", ")", "throws", "Exception", "{", "if", "(", "\"develop-SNAPSHOT\"", ".", "equals", "(", "version", ")", ")", "{", "return", "new", "GatewayVersion", "(", "0", ",", "0", ",", "0", ")", ";", "}", "else", "{", "String", "regex", "=", "\"(?<major>[0-9]+)\\\\.(?<minor>[0-9]+)\\\\.(?<patch>[0-9]+)-?(?<rc>[RC0-9{3}]*)\"", ";", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "regex", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "version", ")", ";", "if", "(", "matcher", ".", "matches", "(", ")", ")", "{", "int", "major", "=", "Integer", ".", "parseInt", "(", "matcher", ".", "group", "(", "\"major\"", ")", ")", ";", "int", "minor", "=", "Integer", ".", "parseInt", "(", "matcher", ".", "group", "(", "\"minor\"", ")", ")", ";", "int", "patch", "=", "Integer", ".", "parseInt", "(", "matcher", ".", "group", "(", "\"patch\"", ")", ")", ";", "String", "rc", "=", "matcher", ".", "group", "(", "\"rc\"", ")", ";", "return", "new", "GatewayVersion", "(", "major", ",", "minor", ",", "patch", ",", "rc", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"version String is not of form %s\"", ",", "regex", ")", ")", ";", "}", "}", "}" ]
Parses a GatewayVersion from a String @param version @return @throws Exception
[ "Parses", "a", "GatewayVersion", "from", "a", "String" ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/service/update.check/src/main/java/org/kaazing/gateway/service/update/check/GatewayVersion.java#L92-L109
pmwmedia/tinylog
tinylog-impl/src/main/java/org/tinylog/path/CountSegment.java
CountSegment.parseDigits
private static Long parseDigits(final String text, final int start) { """ Parses digits from a defined position in a text. Following non-numeric characters will be ignored. @param text Text that potentially contains digits @param start Position in text from which digits should be parsed @return Parsed digits or {@code null} if there is no valid number at the defined position """ for (int i = start; i < text.length(); ++i) { char character = text.charAt(i); if (character < '0' || character > '9') { return parseLong(text.substring(start, i)); } } return parseLong(text.substring(start)); }
java
private static Long parseDigits(final String text, final int start) { for (int i = start; i < text.length(); ++i) { char character = text.charAt(i); if (character < '0' || character > '9') { return parseLong(text.substring(start, i)); } } return parseLong(text.substring(start)); }
[ "private", "static", "Long", "parseDigits", "(", "final", "String", "text", ",", "final", "int", "start", ")", "{", "for", "(", "int", "i", "=", "start", ";", "i", "<", "text", ".", "length", "(", ")", ";", "++", "i", ")", "{", "char", "character", "=", "text", ".", "charAt", "(", "i", ")", ";", "if", "(", "character", "<", "'", "'", "||", "character", ">", "'", "'", ")", "{", "return", "parseLong", "(", "text", ".", "substring", "(", "start", ",", "i", ")", ")", ";", "}", "}", "return", "parseLong", "(", "text", ".", "substring", "(", "start", ")", ")", ";", "}" ]
Parses digits from a defined position in a text. Following non-numeric characters will be ignored. @param text Text that potentially contains digits @param start Position in text from which digits should be parsed @return Parsed digits or {@code null} if there is no valid number at the defined position
[ "Parses", "digits", "from", "a", "defined", "position", "in", "a", "text", ".", "Following", "non", "-", "numeric", "characters", "will", "be", "ignored", "." ]
train
https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/path/CountSegment.java#L87-L96
mikepenz/MaterialDrawer
library/src/main/java/com/mikepenz/materialdrawer/Drawer.java
Drawer.setSelectionAtPosition
public boolean setSelectionAtPosition(int position, boolean fireOnClick) { """ /* set the current selection in the drawer NOTE: this also deselects all other selections. if you do not want this. use the direct api of the adater .getAdapter().select(position, fireOnClick) NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; @param position @param fireOnClick @return true if the event was consumed """ if (mDrawerBuilder.mRecyclerView != null) { SelectExtension<IDrawerItem> select = getAdapter().getExtension(SelectExtension.class); if (select != null) { select.deselect(); select.select(position, false); notifySelect(position, fireOnClick); } } return false; }
java
public boolean setSelectionAtPosition(int position, boolean fireOnClick) { if (mDrawerBuilder.mRecyclerView != null) { SelectExtension<IDrawerItem> select = getAdapter().getExtension(SelectExtension.class); if (select != null) { select.deselect(); select.select(position, false); notifySelect(position, fireOnClick); } } return false; }
[ "public", "boolean", "setSelectionAtPosition", "(", "int", "position", ",", "boolean", "fireOnClick", ")", "{", "if", "(", "mDrawerBuilder", ".", "mRecyclerView", "!=", "null", ")", "{", "SelectExtension", "<", "IDrawerItem", ">", "select", "=", "getAdapter", "(", ")", ".", "getExtension", "(", "SelectExtension", ".", "class", ")", ";", "if", "(", "select", "!=", "null", ")", "{", "select", ".", "deselect", "(", ")", ";", "select", ".", "select", "(", "position", ",", "false", ")", ";", "notifySelect", "(", "position", ",", "fireOnClick", ")", ";", "}", "}", "return", "false", ";", "}" ]
/* set the current selection in the drawer NOTE: this also deselects all other selections. if you do not want this. use the direct api of the adater .getAdapter().select(position, fireOnClick) NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true; @param position @param fireOnClick @return true if the event was consumed
[ "/", "*", "set", "the", "current", "selection", "in", "the", "drawer", "NOTE", ":", "this", "also", "deselects", "all", "other", "selections", ".", "if", "you", "do", "not", "want", "this", ".", "use", "the", "direct", "api", "of", "the", "adater", ".", "getAdapter", "()", ".", "select", "(", "position", "fireOnClick", ")", "NOTE", ":", "This", "will", "trigger", "onDrawerItemSelected", "without", "a", "view", "if", "you", "pass", "fireOnClick", "=", "true", ";" ]
train
https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java#L598-L608
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java
ChatController.synchroniseConversations
private Observable<ChatResult> synchroniseConversations() { """ Updates all conversation states. @return Result of synchronisation with services. """ return checkState().flatMap(client -> client.service().messaging() .getConversations(false) .flatMap(result -> persistenceController.loadAllConversations() .map(chatConversationBases -> compare(result.isSuccessful(), result.getResult(), chatConversationBases))) .flatMap(this::updateLocalConversationList) .flatMap(result -> lookForMissingEvents(client, result)) .map(result -> new ChatResult(result.isSuccessful, null))); }
java
private Observable<ChatResult> synchroniseConversations() { return checkState().flatMap(client -> client.service().messaging() .getConversations(false) .flatMap(result -> persistenceController.loadAllConversations() .map(chatConversationBases -> compare(result.isSuccessful(), result.getResult(), chatConversationBases))) .flatMap(this::updateLocalConversationList) .flatMap(result -> lookForMissingEvents(client, result)) .map(result -> new ChatResult(result.isSuccessful, null))); }
[ "private", "Observable", "<", "ChatResult", ">", "synchroniseConversations", "(", ")", "{", "return", "checkState", "(", ")", ".", "flatMap", "(", "client", "->", "client", ".", "service", "(", ")", ".", "messaging", "(", ")", ".", "getConversations", "(", "false", ")", ".", "flatMap", "(", "result", "->", "persistenceController", ".", "loadAllConversations", "(", ")", ".", "map", "(", "chatConversationBases", "->", "compare", "(", "result", ".", "isSuccessful", "(", ")", ",", "result", ".", "getResult", "(", ")", ",", "chatConversationBases", ")", ")", ")", ".", "flatMap", "(", "this", "::", "updateLocalConversationList", ")", ".", "flatMap", "(", "result", "->", "lookForMissingEvents", "(", "client", ",", "result", ")", ")", ".", "map", "(", "result", "->", "new", "ChatResult", "(", "result", ".", "isSuccessful", ",", "null", ")", ")", ")", ";", "}" ]
Updates all conversation states. @return Result of synchronisation with services.
[ "Updates", "all", "conversation", "states", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java#L465-L474
openbase/jul
pattern/default/src/main/java/org/openbase/jul/pattern/CompletableFutureLite.java
CompletableFutureLite.get
@Override public V get(final long timeout, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { """ Method blocks until the future is done. The method return the result if the future was normally completed. If the future was exceptionally completed or canceled an exception is thrown. @param timeout the maximal time to wait for completion. @param timeUnit the unit of the given timeout. @return the result of the task. @throws InterruptedException is thrown if the thread was externally interrupted. @throws ExecutionException is thrown if the task was canceled or exceptionally completed. @throws TimeoutException in thrown if the timeout was reached and the task is still not done. """ synchronized (lock) { if (value != null) { return value; } lock.wait(timeUnit.toMillis(timeout)); if (value != null) { return value; } if (throwable != null) { throw new ExecutionException(throwable); } throw new TimeoutException(); } }
java
@Override public V get(final long timeout, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { synchronized (lock) { if (value != null) { return value; } lock.wait(timeUnit.toMillis(timeout)); if (value != null) { return value; } if (throwable != null) { throw new ExecutionException(throwable); } throw new TimeoutException(); } }
[ "@", "Override", "public", "V", "get", "(", "final", "long", "timeout", ",", "final", "TimeUnit", "timeUnit", ")", "throws", "InterruptedException", ",", "ExecutionException", ",", "TimeoutException", "{", "synchronized", "(", "lock", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "return", "value", ";", "}", "lock", ".", "wait", "(", "timeUnit", ".", "toMillis", "(", "timeout", ")", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "value", ";", "}", "if", "(", "throwable", "!=", "null", ")", "{", "throw", "new", "ExecutionException", "(", "throwable", ")", ";", "}", "throw", "new", "TimeoutException", "(", ")", ";", "}", "}" ]
Method blocks until the future is done. The method return the result if the future was normally completed. If the future was exceptionally completed or canceled an exception is thrown. @param timeout the maximal time to wait for completion. @param timeUnit the unit of the given timeout. @return the result of the task. @throws InterruptedException is thrown if the thread was externally interrupted. @throws ExecutionException is thrown if the task was canceled or exceptionally completed. @throws TimeoutException in thrown if the timeout was reached and the task is still not done.
[ "Method", "blocks", "until", "the", "future", "is", "done", ".", "The", "method", "return", "the", "result", "if", "the", "future", "was", "normally", "completed", ".", "If", "the", "future", "was", "exceptionally", "completed", "or", "canceled", "an", "exception", "is", "thrown", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/pattern/default/src/main/java/org/openbase/jul/pattern/CompletableFutureLite.java#L188-L205
zaproxy/zaproxy
src/org/zaproxy/zap/spider/filters/HttpPrefixFetchFilter.java
HttpPrefixFetchFilter.startsWith
private static boolean startsWith(char[] array, char[] prefix) { """ Tells whether or not the given {@code array} starts with the given {@code prefix}. <p> The {@code prefix} might be {@code null} in which case it's considered that the {@code array} starts with the prefix. @param array the array that will be tested if starts with the prefix, might be {@code null} @param prefix the array used as prefix, might be {@code null} @return {@code true} if the {@code array} starts with the {@code prefix}, {@code false} otherwise """ if (prefix == null) { return true; } if (array == null) { return false; } int length = prefix.length; if (array.length < length) { return false; } for (int i = 0; i < length; i++) { if (prefix[i] != array[i]) { return false; } } return true; }
java
private static boolean startsWith(char[] array, char[] prefix) { if (prefix == null) { return true; } if (array == null) { return false; } int length = prefix.length; if (array.length < length) { return false; } for (int i = 0; i < length; i++) { if (prefix[i] != array[i]) { return false; } } return true; }
[ "private", "static", "boolean", "startsWith", "(", "char", "[", "]", "array", ",", "char", "[", "]", "prefix", ")", "{", "if", "(", "prefix", "==", "null", ")", "{", "return", "true", ";", "}", "if", "(", "array", "==", "null", ")", "{", "return", "false", ";", "}", "int", "length", "=", "prefix", ".", "length", ";", "if", "(", "array", ".", "length", "<", "length", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "prefix", "[", "i", "]", "!=", "array", "[", "i", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Tells whether or not the given {@code array} starts with the given {@code prefix}. <p> The {@code prefix} might be {@code null} in which case it's considered that the {@code array} starts with the prefix. @param array the array that will be tested if starts with the prefix, might be {@code null} @param prefix the array used as prefix, might be {@code null} @return {@code true} if the {@code array} starts with the {@code prefix}, {@code false} otherwise
[ "Tells", "whether", "or", "not", "the", "given", "{", "@code", "array", "}", "starts", "with", "the", "given", "{", "@code", "prefix", "}", ".", "<p", ">", "The", "{", "@code", "prefix", "}", "might", "be", "{", "@code", "null", "}", "in", "which", "case", "it", "s", "considered", "that", "the", "{", "@code", "array", "}", "starts", "with", "the", "prefix", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/spider/filters/HttpPrefixFetchFilter.java#L298-L319
jMetal/jMetal
jmetal-exec/src/main/java/org/uma/jmetal/experiment/ZDTStudy2.java
ZDTStudy2.configureAlgorithmList
static List<ExperimentAlgorithm<DoubleSolution, List<DoubleSolution>>> configureAlgorithmList( List<ExperimentProblem<DoubleSolution>> problemList) { """ The algorithm list is composed of pairs {@link Algorithm} + {@link Problem} which form part of a {@link ExperimentAlgorithm}, which is a decorator for class {@link Algorithm}. """ List<ExperimentAlgorithm<DoubleSolution, List<DoubleSolution>>> algorithms = new ArrayList<>(); for (int run = 0; run < INDEPENDENT_RUNS; run++) { for (int i = 0; i < problemList.size(); i++) { double mutationProbability = 1.0 / problemList.get(i).getProblem().getNumberOfVariables(); double mutationDistributionIndex = 20.0; Algorithm<List<DoubleSolution>> algorithm = new SMPSOBuilder( (DoubleProblem) problemList.get(i).getProblem(), new CrowdingDistanceArchive<DoubleSolution>(100)) .setMutation(new PolynomialMutation(mutationProbability, mutationDistributionIndex)) .setMaxIterations(250) .setSwarmSize(100) .setSolutionListEvaluator(new SequentialSolutionListEvaluator<DoubleSolution>()) .build(); algorithms.add(new ExperimentAlgorithm<>(algorithm, problemList.get(i), run)); } for (int i = 0; i < problemList.size(); i++) { Algorithm<List<DoubleSolution>> algorithm = new NSGAIIBuilder<DoubleSolution>( problemList.get(i).getProblem(), new SBXCrossover(1.0, 20.0), new PolynomialMutation(1.0 / problemList.get(i).getProblem().getNumberOfVariables(), 20.0), 100) .build(); algorithms.add(new ExperimentAlgorithm<>(algorithm, problemList.get(i), run)); } for (int i = 0; i < problemList.size(); i++) { Algorithm<List<DoubleSolution>> algorithm = new MOEADBuilder(problemList.get(i).getProblem(), MOEADBuilder.Variant.MOEAD) .setCrossover(new DifferentialEvolutionCrossover(1.0, 0.5, "rand/1/bin")) .setMutation(new PolynomialMutation(1.0 / problemList.get(i).getProblem().getNumberOfVariables(), 20.0)) .setMaxEvaluations(25000) .setPopulationSize(100) .setResultPopulationSize(100) .setNeighborhoodSelectionProbability(0.9) .setMaximumNumberOfReplacedSolutions(2) .setNeighborSize(20) .setFunctionType(AbstractMOEAD.FunctionType.TCHE) .build(); algorithms.add(new ExperimentAlgorithm<>(algorithm, problemList.get(i), run)); } } return algorithms; }
java
static List<ExperimentAlgorithm<DoubleSolution, List<DoubleSolution>>> configureAlgorithmList( List<ExperimentProblem<DoubleSolution>> problemList) { List<ExperimentAlgorithm<DoubleSolution, List<DoubleSolution>>> algorithms = new ArrayList<>(); for (int run = 0; run < INDEPENDENT_RUNS; run++) { for (int i = 0; i < problemList.size(); i++) { double mutationProbability = 1.0 / problemList.get(i).getProblem().getNumberOfVariables(); double mutationDistributionIndex = 20.0; Algorithm<List<DoubleSolution>> algorithm = new SMPSOBuilder( (DoubleProblem) problemList.get(i).getProblem(), new CrowdingDistanceArchive<DoubleSolution>(100)) .setMutation(new PolynomialMutation(mutationProbability, mutationDistributionIndex)) .setMaxIterations(250) .setSwarmSize(100) .setSolutionListEvaluator(new SequentialSolutionListEvaluator<DoubleSolution>()) .build(); algorithms.add(new ExperimentAlgorithm<>(algorithm, problemList.get(i), run)); } for (int i = 0; i < problemList.size(); i++) { Algorithm<List<DoubleSolution>> algorithm = new NSGAIIBuilder<DoubleSolution>( problemList.get(i).getProblem(), new SBXCrossover(1.0, 20.0), new PolynomialMutation(1.0 / problemList.get(i).getProblem().getNumberOfVariables(), 20.0), 100) .build(); algorithms.add(new ExperimentAlgorithm<>(algorithm, problemList.get(i), run)); } for (int i = 0; i < problemList.size(); i++) { Algorithm<List<DoubleSolution>> algorithm = new MOEADBuilder(problemList.get(i).getProblem(), MOEADBuilder.Variant.MOEAD) .setCrossover(new DifferentialEvolutionCrossover(1.0, 0.5, "rand/1/bin")) .setMutation(new PolynomialMutation(1.0 / problemList.get(i).getProblem().getNumberOfVariables(), 20.0)) .setMaxEvaluations(25000) .setPopulationSize(100) .setResultPopulationSize(100) .setNeighborhoodSelectionProbability(0.9) .setMaximumNumberOfReplacedSolutions(2) .setNeighborSize(20) .setFunctionType(AbstractMOEAD.FunctionType.TCHE) .build(); algorithms.add(new ExperimentAlgorithm<>(algorithm, problemList.get(i), run)); } } return algorithms; }
[ "static", "List", "<", "ExperimentAlgorithm", "<", "DoubleSolution", ",", "List", "<", "DoubleSolution", ">", ">", ">", "configureAlgorithmList", "(", "List", "<", "ExperimentProblem", "<", "DoubleSolution", ">", ">", "problemList", ")", "{", "List", "<", "ExperimentAlgorithm", "<", "DoubleSolution", ",", "List", "<", "DoubleSolution", ">", ">", ">", "algorithms", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "run", "=", "0", ";", "run", "<", "INDEPENDENT_RUNS", ";", "run", "++", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "problemList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "double", "mutationProbability", "=", "1.0", "/", "problemList", ".", "get", "(", "i", ")", ".", "getProblem", "(", ")", ".", "getNumberOfVariables", "(", ")", ";", "double", "mutationDistributionIndex", "=", "20.0", ";", "Algorithm", "<", "List", "<", "DoubleSolution", ">", ">", "algorithm", "=", "new", "SMPSOBuilder", "(", "(", "DoubleProblem", ")", "problemList", ".", "get", "(", "i", ")", ".", "getProblem", "(", ")", ",", "new", "CrowdingDistanceArchive", "<", "DoubleSolution", ">", "(", "100", ")", ")", ".", "setMutation", "(", "new", "PolynomialMutation", "(", "mutationProbability", ",", "mutationDistributionIndex", ")", ")", ".", "setMaxIterations", "(", "250", ")", ".", "setSwarmSize", "(", "100", ")", ".", "setSolutionListEvaluator", "(", "new", "SequentialSolutionListEvaluator", "<", "DoubleSolution", ">", "(", ")", ")", ".", "build", "(", ")", ";", "algorithms", ".", "add", "(", "new", "ExperimentAlgorithm", "<>", "(", "algorithm", ",", "problemList", ".", "get", "(", "i", ")", ",", "run", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "problemList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Algorithm", "<", "List", "<", "DoubleSolution", ">>", "algorithm", "=", "new", "NSGAIIBuilder", "<", "DoubleSolution", ">", "(", "problemList", ".", "get", "(", "i", ")", ".", "getProblem", "(", ")", ",", "new", "SBXCrossover", "(", "1.0", ",", "20.0", ")", ",", "new", "PolynomialMutation", "(", "1.0", "/", "problemList", ".", "get", "(", "i", ")", ".", "getProblem", "(", ")", ".", "getNumberOfVariables", "(", ")", ",", "20.0", ")", ",", "100", ")", ".", "build", "(", ")", ";", "algorithms", ".", "add", "(", "new", "ExperimentAlgorithm", "<>", "(", "algorithm", ",", "problemList", ".", "get", "(", "i", ")", ",", "run", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "problemList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Algorithm", "<", "List", "<", "DoubleSolution", ">>", "algorithm", "=", "new", "MOEADBuilder", "(", "problemList", ".", "get", "(", "i", ")", ".", "getProblem", "(", ")", ",", "MOEADBuilder", ".", "Variant", ".", "MOEAD", ")", ".", "setCrossover", "(", "new", "DifferentialEvolutionCrossover", "(", "1.0", ",", "0.5", ",", "\"rand/1/bin\"", ")", ")", ".", "setMutation", "(", "new", "PolynomialMutation", "(", "1.0", "/", "problemList", ".", "get", "(", "i", ")", ".", "getProblem", "(", ")", ".", "getNumberOfVariables", "(", ")", ",", "20.0", ")", ")", ".", "setMaxEvaluations", "(", "25000", ")", ".", "setPopulationSize", "(", "100", ")", ".", "setResultPopulationSize", "(", "100", ")", ".", "setNeighborhoodSelectionProbability", "(", "0.9", ")", ".", "setMaximumNumberOfReplacedSolutions", "(", "2", ")", ".", "setNeighborSize", "(", "20", ")", ".", "setFunctionType", "(", "AbstractMOEAD", ".", "FunctionType", ".", "TCHE", ")", ".", "build", "(", ")", ";", "algorithms", ".", "add", "(", "new", "ExperimentAlgorithm", "<>", "(", "algorithm", ",", "problemList", ".", "get", "(", "i", ")", ",", "run", ")", ")", ";", "}", "}", "return", "algorithms", ";", "}" ]
The algorithm list is composed of pairs {@link Algorithm} + {@link Problem} which form part of a {@link ExperimentAlgorithm}, which is a decorator for class {@link Algorithm}.
[ "The", "algorithm", "list", "is", "composed", "of", "pairs", "{" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-exec/src/main/java/org/uma/jmetal/experiment/ZDTStudy2.java#L106-L154
looly/hutool
hutool-db/src/main/java/cn/hutool/db/ds/simple/SimpleDataSource.java
SimpleDataSource.init
public void init(String url, String user, String pass, String driver) { """ 初始化 @param url jdbc url @param user 用户名 @param pass 密码 @param driver JDBC驱动类,传入空则自动识别驱动类 @since 3.1.2 """ this.driver = StrUtil.isNotBlank(driver) ? driver : DriverUtil.identifyDriver(url); try { Class.forName(this.driver); } catch (ClassNotFoundException e) { throw new DbRuntimeException(e, "Get jdbc driver [{}] error!", driver); } this.url = url; this.user = user; this.pass = pass; }
java
public void init(String url, String user, String pass, String driver) { this.driver = StrUtil.isNotBlank(driver) ? driver : DriverUtil.identifyDriver(url); try { Class.forName(this.driver); } catch (ClassNotFoundException e) { throw new DbRuntimeException(e, "Get jdbc driver [{}] error!", driver); } this.url = url; this.user = user; this.pass = pass; }
[ "public", "void", "init", "(", "String", "url", ",", "String", "user", ",", "String", "pass", ",", "String", "driver", ")", "{", "this", ".", "driver", "=", "StrUtil", ".", "isNotBlank", "(", "driver", ")", "?", "driver", ":", "DriverUtil", ".", "identifyDriver", "(", "url", ")", ";", "try", "{", "Class", ".", "forName", "(", "this", ".", "driver", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "throw", "new", "DbRuntimeException", "(", "e", ",", "\"Get jdbc driver [{}] error!\"", ",", "driver", ")", ";", "}", "this", ".", "url", "=", "url", ";", "this", ".", "user", "=", "user", ";", "this", ".", "pass", "=", "pass", ";", "}" ]
初始化 @param url jdbc url @param user 用户名 @param pass 密码 @param driver JDBC驱动类,传入空则自动识别驱动类 @since 3.1.2
[ "初始化" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/ds/simple/SimpleDataSource.java#L137-L147
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.getClosedListEntityRole
public EntityRole getClosedListEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) { """ Get one entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId entity ID. @param roleId entity role ID. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the EntityRole object if successful. """ return getClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body(); }
java
public EntityRole getClosedListEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) { return getClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body(); }
[ "public", "EntityRole", "getClosedListEntityRole", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ")", "{", "return", "getClosedListEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "roleId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Get one entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId entity ID. @param roleId entity role ID. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the EntityRole object if successful.
[ "Get", "one", "entity", "role", "for", "a", "given", "entity", "." ]
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#L11548-L11550
geomajas/geomajas-project-client-gwt
plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/MultiLayerFeaturesList.java
MultiLayerFeaturesList.addFeature
private boolean addFeature(Feature feature, Layer<?> layer) { """ Adds a new feature to the grid list. A {@link VectorLayer} must have been set first, and the feature must belong to that VectorLayer. @param feature The feature to be added to the grid list. @return Returns true in case of success, and false if the feature is null or if the feature does not belong to the correct layer or if the layer has not yet been set. """ // Basic checks: if (feature == null || layer == null ) { return false; } // Feature checks out, add it to the grid: ListGridRecord record = new ListGridRecord(); if (layer instanceof VectorLayer) { record.setAttribute(LABEL, getLabel(feature)); } else if (layer instanceof RasterLayer) { record.setAttribute(LABEL, feature.getId()); } record.setAttribute(FEATURE_ID, getFullFeatureId(feature, layer)); record.setAttribute(LAYER_ID, layer.getId()); record.setAttribute(LAYER_LABEL, layer.getLabel()); addData(record); return true; }
java
private boolean addFeature(Feature feature, Layer<?> layer) { // Basic checks: if (feature == null || layer == null ) { return false; } // Feature checks out, add it to the grid: ListGridRecord record = new ListGridRecord(); if (layer instanceof VectorLayer) { record.setAttribute(LABEL, getLabel(feature)); } else if (layer instanceof RasterLayer) { record.setAttribute(LABEL, feature.getId()); } record.setAttribute(FEATURE_ID, getFullFeatureId(feature, layer)); record.setAttribute(LAYER_ID, layer.getId()); record.setAttribute(LAYER_LABEL, layer.getLabel()); addData(record); return true; }
[ "private", "boolean", "addFeature", "(", "Feature", "feature", ",", "Layer", "<", "?", ">", "layer", ")", "{", "// Basic checks:", "if", "(", "feature", "==", "null", "||", "layer", "==", "null", ")", "{", "return", "false", ";", "}", "// Feature checks out, add it to the grid:", "ListGridRecord", "record", "=", "new", "ListGridRecord", "(", ")", ";", "if", "(", "layer", "instanceof", "VectorLayer", ")", "{", "record", ".", "setAttribute", "(", "LABEL", ",", "getLabel", "(", "feature", ")", ")", ";", "}", "else", "if", "(", "layer", "instanceof", "RasterLayer", ")", "{", "record", ".", "setAttribute", "(", "LABEL", ",", "feature", ".", "getId", "(", ")", ")", ";", "}", "record", ".", "setAttribute", "(", "FEATURE_ID", ",", "getFullFeatureId", "(", "feature", ",", "layer", ")", ")", ";", "record", ".", "setAttribute", "(", "LAYER_ID", ",", "layer", ".", "getId", "(", ")", ")", ";", "record", ".", "setAttribute", "(", "LAYER_LABEL", ",", "layer", ".", "getLabel", "(", ")", ")", ";", "addData", "(", "record", ")", ";", "return", "true", ";", "}" ]
Adds a new feature to the grid list. A {@link VectorLayer} must have been set first, and the feature must belong to that VectorLayer. @param feature The feature to be added to the grid list. @return Returns true in case of success, and false if the feature is null or if the feature does not belong to the correct layer or if the layer has not yet been set.
[ "Adds", "a", "new", "feature", "to", "the", "grid", "list", ".", "A", "{", "@link", "VectorLayer", "}", "must", "have", "been", "set", "first", "and", "the", "feature", "must", "belong", "to", "that", "VectorLayer", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/plugin/widget-featureinfo/featureinfo-gwt/src/main/java/org/geomajas/widget/featureinfo/client/widget/MultiLayerFeaturesList.java#L163-L180
logic-ng/LogicNG
src/main/java/org/logicng/formulas/printer/SortedStringRepresentation.java
SortedStringRepresentation.naryOperator
@Override protected String naryOperator(final NAryOperator operator, final String opString) { """ Returns the sorted string representation of an n-ary operator. @param operator the n-ary operator @param opString the operator string @return the string representation """ final List<Formula> operands = new ArrayList<>(); for (final Formula op : operator) { operands.add(op); } final int size = operator.numberOfOperands(); Collections.sort(operands, this.comparator); final StringBuilder sb = new StringBuilder(); int count = 0; Formula last = null; for (final Formula op : operands) { if (++count == size) { last = op; } else { sb.append(operator.type().precedence() < op.type().precedence() ? toString(op) : bracket(op)); sb.append(opString); } } if (last != null) { sb.append(operator.type().precedence() < last.type().precedence() ? toString(last) : bracket(last)); } return sb.toString(); }
java
@Override protected String naryOperator(final NAryOperator operator, final String opString) { final List<Formula> operands = new ArrayList<>(); for (final Formula op : operator) { operands.add(op); } final int size = operator.numberOfOperands(); Collections.sort(operands, this.comparator); final StringBuilder sb = new StringBuilder(); int count = 0; Formula last = null; for (final Formula op : operands) { if (++count == size) { last = op; } else { sb.append(operator.type().precedence() < op.type().precedence() ? toString(op) : bracket(op)); sb.append(opString); } } if (last != null) { sb.append(operator.type().precedence() < last.type().precedence() ? toString(last) : bracket(last)); } return sb.toString(); }
[ "@", "Override", "protected", "String", "naryOperator", "(", "final", "NAryOperator", "operator", ",", "final", "String", "opString", ")", "{", "final", "List", "<", "Formula", ">", "operands", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "final", "Formula", "op", ":", "operator", ")", "{", "operands", ".", "add", "(", "op", ")", ";", "}", "final", "int", "size", "=", "operator", ".", "numberOfOperands", "(", ")", ";", "Collections", ".", "sort", "(", "operands", ",", "this", ".", "comparator", ")", ";", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "count", "=", "0", ";", "Formula", "last", "=", "null", ";", "for", "(", "final", "Formula", "op", ":", "operands", ")", "{", "if", "(", "++", "count", "==", "size", ")", "{", "last", "=", "op", ";", "}", "else", "{", "sb", ".", "append", "(", "operator", ".", "type", "(", ")", ".", "precedence", "(", ")", "<", "op", ".", "type", "(", ")", ".", "precedence", "(", ")", "?", "toString", "(", "op", ")", ":", "bracket", "(", "op", ")", ")", ";", "sb", ".", "append", "(", "opString", ")", ";", "}", "}", "if", "(", "last", "!=", "null", ")", "{", "sb", ".", "append", "(", "operator", ".", "type", "(", ")", ".", "precedence", "(", ")", "<", "last", ".", "type", "(", ")", ".", "precedence", "(", ")", "?", "toString", "(", "last", ")", ":", "bracket", "(", "last", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns the sorted string representation of an n-ary operator. @param operator the n-ary operator @param opString the operator string @return the string representation
[ "Returns", "the", "sorted", "string", "representation", "of", "an", "n", "-", "ary", "operator", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/formulas/printer/SortedStringRepresentation.java#L142-L165
Netflix/suro
suro-server/src/main/java/com/netflix/suro/SuroControl.java
SuroControl.respond
private void respond(BufferedWriter out, String response) throws IOException { """ Writes line-based response. @param out the channel used to write back response @param response A string that ends with a new line @throws IOException """ out.append(response); out.append("\n"); out.flush(); }
java
private void respond(BufferedWriter out, String response) throws IOException { out.append(response); out.append("\n"); out.flush(); }
[ "private", "void", "respond", "(", "BufferedWriter", "out", ",", "String", "response", ")", "throws", "IOException", "{", "out", ".", "append", "(", "response", ")", ";", "out", ".", "append", "(", "\"\\n\"", ")", ";", "out", ".", "flush", "(", ")", ";", "}" ]
Writes line-based response. @param out the channel used to write back response @param response A string that ends with a new line @throws IOException
[ "Writes", "line", "-", "based", "response", "." ]
train
https://github.com/Netflix/suro/blob/e73d1a2e5b0492e41feb5a57d9e2a2e741a38453/suro-server/src/main/java/com/netflix/suro/SuroControl.java#L133-L137
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/Jdt2Ecore.java
Jdt2Ecore.getJvmOperation
public JvmOperation getJvmOperation(IMethod method, XtendTypeDeclaration context) throws JavaModelException { """ Create the JvmOperation for the given JDT method. @param method the JDT method. @param context the context of the constructor. @return the JvmOperation @throws JavaModelException if the Java model is invalid. """ if (!method.isConstructor() && !method.isLambdaMethod() && !method.isMainMethod()) { final JvmType type = this.typeReferences.findDeclaredType( method.getDeclaringType().getFullyQualifiedName(), context); return getJvmOperation(method, type); } return null; }
java
public JvmOperation getJvmOperation(IMethod method, XtendTypeDeclaration context) throws JavaModelException { if (!method.isConstructor() && !method.isLambdaMethod() && !method.isMainMethod()) { final JvmType type = this.typeReferences.findDeclaredType( method.getDeclaringType().getFullyQualifiedName(), context); return getJvmOperation(method, type); } return null; }
[ "public", "JvmOperation", "getJvmOperation", "(", "IMethod", "method", ",", "XtendTypeDeclaration", "context", ")", "throws", "JavaModelException", "{", "if", "(", "!", "method", ".", "isConstructor", "(", ")", "&&", "!", "method", ".", "isLambdaMethod", "(", ")", "&&", "!", "method", ".", "isMainMethod", "(", ")", ")", "{", "final", "JvmType", "type", "=", "this", ".", "typeReferences", ".", "findDeclaredType", "(", "method", ".", "getDeclaringType", "(", ")", ".", "getFullyQualifiedName", "(", ")", ",", "context", ")", ";", "return", "getJvmOperation", "(", "method", ",", "type", ")", ";", "}", "return", "null", ";", "}" ]
Create the JvmOperation for the given JDT method. @param method the JDT method. @param context the context of the constructor. @return the JvmOperation @throws JavaModelException if the Java model is invalid.
[ "Create", "the", "JvmOperation", "for", "the", "given", "JDT", "method", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/Jdt2Ecore.java#L396-L405
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/codec/HexUtils.java
HexUtils.hexToBits
public static void hexToBits(String s, BitSet ba, int length) { """ Read a hex string of bits and write it into a bitset @param s hex string of the stored bits @param ba the bitset to store the bits in @param length the maximum number of bits to store """ byte[] b = hexToBytes(s); bytesToBits(b, ba, length); }
java
public static void hexToBits(String s, BitSet ba, int length) { byte[] b = hexToBytes(s); bytesToBits(b, ba, length); }
[ "public", "static", "void", "hexToBits", "(", "String", "s", ",", "BitSet", "ba", ",", "int", "length", ")", "{", "byte", "[", "]", "b", "=", "hexToBytes", "(", "s", ")", ";", "bytesToBits", "(", "b", ",", "ba", ",", "length", ")", ";", "}" ]
Read a hex string of bits and write it into a bitset @param s hex string of the stored bits @param ba the bitset to store the bits in @param length the maximum number of bits to store
[ "Read", "a", "hex", "string", "of", "bits", "and", "write", "it", "into", "a", "bitset" ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/codec/HexUtils.java#L134-L137
tango-controls/JTango
server/src/main/java/org/tango/server/build/BuilderUtils.java
BuilderUtils.setEnumLabelProperty
static AttributePropertiesImpl setEnumLabelProperty(final Class<?> type, final AttributePropertiesImpl props) throws DevFailed { """ Set enum label for Enum types @param type @param props @throws DevFailed """ // if is is an enum set enum values in properties if (AttributeTangoType.getTypeFromClass(type).equals(AttributeTangoType.DEVENUM)) { // final Class<Enum<?>> enumType = (Class<Enum<?>>) field.getType(); final Object[] enumValues = type.getEnumConstants(); final String[] enumLabels = new String[enumValues.length]; for (int i = 0; i < enumLabels.length; i++) { enumLabels[i] = enumValues[i].toString(); } props.setEnumLabels(enumLabels, false); } return props; }
java
static AttributePropertiesImpl setEnumLabelProperty(final Class<?> type, final AttributePropertiesImpl props) throws DevFailed { // if is is an enum set enum values in properties if (AttributeTangoType.getTypeFromClass(type).equals(AttributeTangoType.DEVENUM)) { // final Class<Enum<?>> enumType = (Class<Enum<?>>) field.getType(); final Object[] enumValues = type.getEnumConstants(); final String[] enumLabels = new String[enumValues.length]; for (int i = 0; i < enumLabels.length; i++) { enumLabels[i] = enumValues[i].toString(); } props.setEnumLabels(enumLabels, false); } return props; }
[ "static", "AttributePropertiesImpl", "setEnumLabelProperty", "(", "final", "Class", "<", "?", ">", "type", ",", "final", "AttributePropertiesImpl", "props", ")", "throws", "DevFailed", "{", "// if is is an enum set enum values in properties", "if", "(", "AttributeTangoType", ".", "getTypeFromClass", "(", "type", ")", ".", "equals", "(", "AttributeTangoType", ".", "DEVENUM", ")", ")", "{", "// final Class<Enum<?>> enumType = (Class<Enum<?>>) field.getType();", "final", "Object", "[", "]", "enumValues", "=", "type", ".", "getEnumConstants", "(", ")", ";", "final", "String", "[", "]", "enumLabels", "=", "new", "String", "[", "enumValues", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "enumLabels", ".", "length", ";", "i", "++", ")", "{", "enumLabels", "[", "i", "]", "=", "enumValues", "[", "i", "]", ".", "toString", "(", ")", ";", "}", "props", ".", "setEnumLabels", "(", "enumLabels", ",", "false", ")", ";", "}", "return", "props", ";", "}" ]
Set enum label for Enum types @param type @param props @throws DevFailed
[ "Set", "enum", "label", "for", "Enum", "types" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/build/BuilderUtils.java#L174-L187
aehrc/snorocket
snorocket-core/src/main/java/au/csiro/snorocket/core/NormalisedOntology.java
NormalisedOntology.isChild
private boolean isChild(Node cn, Node cn2) { """ Indicates if cn is a child of cn2. @param cn @param cn2 @return """ if (cn == cn2) return false; Queue<Node> toProcess = new LinkedList<Node>(); toProcess.addAll(cn.getParents()); while (!toProcess.isEmpty()) { Node tcn = toProcess.poll(); if (tcn.equals(cn2)) return true; Set<Node> parents = tcn.getParents(); if (parents != null && !parents.isEmpty()) toProcess.addAll(parents); } return false; }
java
private boolean isChild(Node cn, Node cn2) { if (cn == cn2) return false; Queue<Node> toProcess = new LinkedList<Node>(); toProcess.addAll(cn.getParents()); while (!toProcess.isEmpty()) { Node tcn = toProcess.poll(); if (tcn.equals(cn2)) return true; Set<Node> parents = tcn.getParents(); if (parents != null && !parents.isEmpty()) toProcess.addAll(parents); } return false; }
[ "private", "boolean", "isChild", "(", "Node", "cn", ",", "Node", "cn2", ")", "{", "if", "(", "cn", "==", "cn2", ")", "return", "false", ";", "Queue", "<", "Node", ">", "toProcess", "=", "new", "LinkedList", "<", "Node", ">", "(", ")", ";", "toProcess", ".", "addAll", "(", "cn", ".", "getParents", "(", ")", ")", ";", "while", "(", "!", "toProcess", ".", "isEmpty", "(", ")", ")", "{", "Node", "tcn", "=", "toProcess", ".", "poll", "(", ")", ";", "if", "(", "tcn", ".", "equals", "(", "cn2", ")", ")", "return", "true", ";", "Set", "<", "Node", ">", "parents", "=", "tcn", ".", "getParents", "(", ")", ";", "if", "(", "parents", "!=", "null", "&&", "!", "parents", ".", "isEmpty", "(", ")", ")", "toProcess", ".", "addAll", "(", "parents", ")", ";", "}", "return", "false", ";", "}" ]
Indicates if cn is a child of cn2. @param cn @param cn2 @return
[ "Indicates", "if", "cn", "is", "a", "child", "of", "cn2", "." ]
train
https://github.com/aehrc/snorocket/blob/e33c1e216f8a66d6502e3a14e80876811feedd8b/snorocket-core/src/main/java/au/csiro/snorocket/core/NormalisedOntology.java#L2339-L2356
huahin/huahin-core
src/main/java/org/huahinframework/core/SimpleJobTool.java
SimpleJobTool.addBigJoinJob
private SimpleJob addBigJoinJob(SimpleJob job) throws IOException { """ create big join SimpleJob @param job job that big join is set. @return big join {@link SimpleJob} @throws IOException """ Configuration conf = job.getConfiguration(); String[] labels = conf.getStrings(SimpleJob.LABELS); String separator = conf.get(SimpleJob.SEPARATOR); boolean regex = conf.getBoolean(SimpleJob.SEPARATOR_REGEX, false); boolean formatIgnored = conf.getBoolean(SimpleJob.FORMAT_IGNORED, false); SimpleJob joinJob = new SimpleJob(conf, jobName, true); setConfiguration(joinJob, labels, separator, formatIgnored, regex); int type = conf.getInt(SimpleJob.READER_TYPE, -1); Configuration joinConf = joinJob.getConfiguration(); joinConf.setInt(SimpleJob.READER_TYPE, type); joinConf.setStrings(SimpleJob.MASTER_LABELS, conf.getStrings(SimpleJob.MASTER_LABELS)); if (type == SimpleJob.SINGLE_COLUMN_JOIN_READER) { joinConf.set(SimpleJob.JOIN_MASTER_COLUMN, conf.get(SimpleJob.JOIN_MASTER_COLUMN)); joinConf.set(SimpleJob.JOIN_DATA_COLUMN, conf.get(SimpleJob.JOIN_DATA_COLUMN)); } else if (type == SimpleJob.SOME_COLUMN_JOIN_READER) { joinConf.setStrings(SimpleJob.JOIN_MASTER_COLUMN, conf.getStrings(SimpleJob.JOIN_MASTER_COLUMN)); joinConf.setStrings(SimpleJob.JOIN_DATA_COLUMN, conf.getStrings(SimpleJob.JOIN_DATA_COLUMN)); } joinConf.set(SimpleJob.MASTER_PATH, conf.get(SimpleJob.MASTER_PATH)); joinConf.set(SimpleJob.MASTER_SEPARATOR, conf.get(SimpleJob.MASTER_SEPARATOR)); joinJob.setMapOutputKeyClass(Key.class); joinJob.setMapOutputValueClass(Value.class); joinJob.setPartitionerClass(SimplePartitioner.class); joinJob.setGroupingComparatorClass(SimpleGroupingComparator.class); joinJob.setSortComparatorClass(SimpleSortComparator.class); joinJob.setSummarizer(JoinSummarizer.class); if (!job.isMapper() && !job.isReducer()) { joinConf.setBoolean(SimpleJob.ONLY_JOIN, true); joinJob.setOutputKeyClass(Value.class); joinJob.setOutputValueClass(NullWritable.class); } else { joinJob.setOutputKeyClass(Key.class); joinJob.setOutputValueClass(Value.class); } return joinJob; }
java
private SimpleJob addBigJoinJob(SimpleJob job) throws IOException { Configuration conf = job.getConfiguration(); String[] labels = conf.getStrings(SimpleJob.LABELS); String separator = conf.get(SimpleJob.SEPARATOR); boolean regex = conf.getBoolean(SimpleJob.SEPARATOR_REGEX, false); boolean formatIgnored = conf.getBoolean(SimpleJob.FORMAT_IGNORED, false); SimpleJob joinJob = new SimpleJob(conf, jobName, true); setConfiguration(joinJob, labels, separator, formatIgnored, regex); int type = conf.getInt(SimpleJob.READER_TYPE, -1); Configuration joinConf = joinJob.getConfiguration(); joinConf.setInt(SimpleJob.READER_TYPE, type); joinConf.setStrings(SimpleJob.MASTER_LABELS, conf.getStrings(SimpleJob.MASTER_LABELS)); if (type == SimpleJob.SINGLE_COLUMN_JOIN_READER) { joinConf.set(SimpleJob.JOIN_MASTER_COLUMN, conf.get(SimpleJob.JOIN_MASTER_COLUMN)); joinConf.set(SimpleJob.JOIN_DATA_COLUMN, conf.get(SimpleJob.JOIN_DATA_COLUMN)); } else if (type == SimpleJob.SOME_COLUMN_JOIN_READER) { joinConf.setStrings(SimpleJob.JOIN_MASTER_COLUMN, conf.getStrings(SimpleJob.JOIN_MASTER_COLUMN)); joinConf.setStrings(SimpleJob.JOIN_DATA_COLUMN, conf.getStrings(SimpleJob.JOIN_DATA_COLUMN)); } joinConf.set(SimpleJob.MASTER_PATH, conf.get(SimpleJob.MASTER_PATH)); joinConf.set(SimpleJob.MASTER_SEPARATOR, conf.get(SimpleJob.MASTER_SEPARATOR)); joinJob.setMapOutputKeyClass(Key.class); joinJob.setMapOutputValueClass(Value.class); joinJob.setPartitionerClass(SimplePartitioner.class); joinJob.setGroupingComparatorClass(SimpleGroupingComparator.class); joinJob.setSortComparatorClass(SimpleSortComparator.class); joinJob.setSummarizer(JoinSummarizer.class); if (!job.isMapper() && !job.isReducer()) { joinConf.setBoolean(SimpleJob.ONLY_JOIN, true); joinJob.setOutputKeyClass(Value.class); joinJob.setOutputValueClass(NullWritable.class); } else { joinJob.setOutputKeyClass(Key.class); joinJob.setOutputValueClass(Value.class); } return joinJob; }
[ "private", "SimpleJob", "addBigJoinJob", "(", "SimpleJob", "job", ")", "throws", "IOException", "{", "Configuration", "conf", "=", "job", ".", "getConfiguration", "(", ")", ";", "String", "[", "]", "labels", "=", "conf", ".", "getStrings", "(", "SimpleJob", ".", "LABELS", ")", ";", "String", "separator", "=", "conf", ".", "get", "(", "SimpleJob", ".", "SEPARATOR", ")", ";", "boolean", "regex", "=", "conf", ".", "getBoolean", "(", "SimpleJob", ".", "SEPARATOR_REGEX", ",", "false", ")", ";", "boolean", "formatIgnored", "=", "conf", ".", "getBoolean", "(", "SimpleJob", ".", "FORMAT_IGNORED", ",", "false", ")", ";", "SimpleJob", "joinJob", "=", "new", "SimpleJob", "(", "conf", ",", "jobName", ",", "true", ")", ";", "setConfiguration", "(", "joinJob", ",", "labels", ",", "separator", ",", "formatIgnored", ",", "regex", ")", ";", "int", "type", "=", "conf", ".", "getInt", "(", "SimpleJob", ".", "READER_TYPE", ",", "-", "1", ")", ";", "Configuration", "joinConf", "=", "joinJob", ".", "getConfiguration", "(", ")", ";", "joinConf", ".", "setInt", "(", "SimpleJob", ".", "READER_TYPE", ",", "type", ")", ";", "joinConf", ".", "setStrings", "(", "SimpleJob", ".", "MASTER_LABELS", ",", "conf", ".", "getStrings", "(", "SimpleJob", ".", "MASTER_LABELS", ")", ")", ";", "if", "(", "type", "==", "SimpleJob", ".", "SINGLE_COLUMN_JOIN_READER", ")", "{", "joinConf", ".", "set", "(", "SimpleJob", ".", "JOIN_MASTER_COLUMN", ",", "conf", ".", "get", "(", "SimpleJob", ".", "JOIN_MASTER_COLUMN", ")", ")", ";", "joinConf", ".", "set", "(", "SimpleJob", ".", "JOIN_DATA_COLUMN", ",", "conf", ".", "get", "(", "SimpleJob", ".", "JOIN_DATA_COLUMN", ")", ")", ";", "}", "else", "if", "(", "type", "==", "SimpleJob", ".", "SOME_COLUMN_JOIN_READER", ")", "{", "joinConf", ".", "setStrings", "(", "SimpleJob", ".", "JOIN_MASTER_COLUMN", ",", "conf", ".", "getStrings", "(", "SimpleJob", ".", "JOIN_MASTER_COLUMN", ")", ")", ";", "joinConf", ".", "setStrings", "(", "SimpleJob", ".", "JOIN_DATA_COLUMN", ",", "conf", ".", "getStrings", "(", "SimpleJob", ".", "JOIN_DATA_COLUMN", ")", ")", ";", "}", "joinConf", ".", "set", "(", "SimpleJob", ".", "MASTER_PATH", ",", "conf", ".", "get", "(", "SimpleJob", ".", "MASTER_PATH", ")", ")", ";", "joinConf", ".", "set", "(", "SimpleJob", ".", "MASTER_SEPARATOR", ",", "conf", ".", "get", "(", "SimpleJob", ".", "MASTER_SEPARATOR", ")", ")", ";", "joinJob", ".", "setMapOutputKeyClass", "(", "Key", ".", "class", ")", ";", "joinJob", ".", "setMapOutputValueClass", "(", "Value", ".", "class", ")", ";", "joinJob", ".", "setPartitionerClass", "(", "SimplePartitioner", ".", "class", ")", ";", "joinJob", ".", "setGroupingComparatorClass", "(", "SimpleGroupingComparator", ".", "class", ")", ";", "joinJob", ".", "setSortComparatorClass", "(", "SimpleSortComparator", ".", "class", ")", ";", "joinJob", ".", "setSummarizer", "(", "JoinSummarizer", ".", "class", ")", ";", "if", "(", "!", "job", ".", "isMapper", "(", ")", "&&", "!", "job", ".", "isReducer", "(", ")", ")", "{", "joinConf", ".", "setBoolean", "(", "SimpleJob", ".", "ONLY_JOIN", ",", "true", ")", ";", "joinJob", ".", "setOutputKeyClass", "(", "Value", ".", "class", ")", ";", "joinJob", ".", "setOutputValueClass", "(", "NullWritable", ".", "class", ")", ";", "}", "else", "{", "joinJob", ".", "setOutputKeyClass", "(", "Key", ".", "class", ")", ";", "joinJob", ".", "setOutputValueClass", "(", "Value", ".", "class", ")", ";", "}", "return", "joinJob", ";", "}" ]
create big join SimpleJob @param job job that big join is set. @return big join {@link SimpleJob} @throws IOException
[ "create", "big", "join", "SimpleJob" ]
train
https://github.com/huahin/huahin-core/blob/a87921b5a12be92a822f753c075ab2431036e6f5/src/main/java/org/huahinframework/core/SimpleJobTool.java#L407-L451
mojohaus/aspectj-maven-plugin
src/main/java/org/codehaus/mojo/aspectj/EclipseAjcMojo.java
EclipseAjcMojo.writeDocument
private void writeDocument( Document document, File file ) throws TransformerException, FileNotFoundException { """ write document to the file @param document @param file @throws TransformerException @throws FileNotFoundException """ document.normalize(); DOMSource source = new DOMSource( document ); StreamResult result = new StreamResult( new FileOutputStream( file ) ); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); transformer.transform( source, result ); }
java
private void writeDocument( Document document, File file ) throws TransformerException, FileNotFoundException { document.normalize(); DOMSource source = new DOMSource( document ); StreamResult result = new StreamResult( new FileOutputStream( file ) ); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); transformer.transform( source, result ); }
[ "private", "void", "writeDocument", "(", "Document", "document", ",", "File", "file", ")", "throws", "TransformerException", ",", "FileNotFoundException", "{", "document", ".", "normalize", "(", ")", ";", "DOMSource", "source", "=", "new", "DOMSource", "(", "document", ")", ";", "StreamResult", "result", "=", "new", "StreamResult", "(", "new", "FileOutputStream", "(", "file", ")", ")", ";", "Transformer", "transformer", "=", "TransformerFactory", ".", "newInstance", "(", ")", ".", "newTransformer", "(", ")", ";", "transformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "INDENT", ",", "\"yes\"", ")", ";", "transformer", ".", "transform", "(", "source", ",", "result", ")", ";", "}" ]
write document to the file @param document @param file @throws TransformerException @throws FileNotFoundException
[ "write", "document", "to", "the", "file" ]
train
https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/EclipseAjcMojo.java#L319-L328
pinterest/secor
src/main/java/com/pinterest/secor/util/ProtobufUtil.java
ProtobufUtil.decodeProtobufOrJsonMessage
public Message decodeProtobufOrJsonMessage(String topic, byte[] payload) { """ Decodes protobuf message If the secor.topic.message.format property is set to "JSON" for "topic" assume "payload" is JSON @param topic Kafka topic name @param payload Byte array containing encoded protobuf or JSON message @return protobuf message instance @throws RuntimeException when there's problem decoding protobuf or JSON message """ try { if (shouldDecodeFromJsonMessage(topic)) { return decodeJsonMessage(topic, payload); } } catch (InvalidProtocolBufferException e) { //When trimming files, the Uploader will read and then decode messages in protobuf format LOG.debug("Unable to translate JSON string {} to protobuf message", new String(payload, Charsets.UTF_8)); } return decodeProtobufMessage(topic, payload); }
java
public Message decodeProtobufOrJsonMessage(String topic, byte[] payload) { try { if (shouldDecodeFromJsonMessage(topic)) { return decodeJsonMessage(topic, payload); } } catch (InvalidProtocolBufferException e) { //When trimming files, the Uploader will read and then decode messages in protobuf format LOG.debug("Unable to translate JSON string {} to protobuf message", new String(payload, Charsets.UTF_8)); } return decodeProtobufMessage(topic, payload); }
[ "public", "Message", "decodeProtobufOrJsonMessage", "(", "String", "topic", ",", "byte", "[", "]", "payload", ")", "{", "try", "{", "if", "(", "shouldDecodeFromJsonMessage", "(", "topic", ")", ")", "{", "return", "decodeJsonMessage", "(", "topic", ",", "payload", ")", ";", "}", "}", "catch", "(", "InvalidProtocolBufferException", "e", ")", "{", "//When trimming files, the Uploader will read and then decode messages in protobuf format", "LOG", ".", "debug", "(", "\"Unable to translate JSON string {} to protobuf message\"", ",", "new", "String", "(", "payload", ",", "Charsets", ".", "UTF_8", ")", ")", ";", "}", "return", "decodeProtobufMessage", "(", "topic", ",", "payload", ")", ";", "}" ]
Decodes protobuf message If the secor.topic.message.format property is set to "JSON" for "topic" assume "payload" is JSON @param topic Kafka topic name @param payload Byte array containing encoded protobuf or JSON message @return protobuf message instance @throws RuntimeException when there's problem decoding protobuf or JSON message
[ "Decodes", "protobuf", "message", "If", "the", "secor", ".", "topic", ".", "message", ".", "format", "property", "is", "set", "to", "JSON", "for", "topic", "assume", "payload", "is", "JSON" ]
train
https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/ProtobufUtil.java#L208-L218
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/ServerRequest.java
ServerRequest.fromJSON
public static ServerRequest fromJSON(JSONObject json, Context context) { """ <p>Converts a {@link JSONObject} object containing keys stored as key-value pairs into a {@link ServerRequest}.</p> @param json A {@link JSONObject} object containing post data stored as key-value pairs @param context Application context. @return A {@link ServerRequest} object with the {@link #POST_KEY} values set if not null; this can be one or the other. If both values in the supplied {@link JSONObject} are null, null is returned instead of an object. """ JSONObject post = null; String requestPath = ""; try { if (json.has(POST_KEY)) { post = json.getJSONObject(POST_KEY); } } catch (JSONException e) { // it's OK for post to be null } try { if (json.has(POST_PATH_KEY)) { requestPath = json.getString(POST_PATH_KEY); } } catch (JSONException e) { // it's OK for post to be null } if (requestPath != null && requestPath.length() > 0) { return getExtendedServerRequest(requestPath, post, context); } return null; }
java
public static ServerRequest fromJSON(JSONObject json, Context context) { JSONObject post = null; String requestPath = ""; try { if (json.has(POST_KEY)) { post = json.getJSONObject(POST_KEY); } } catch (JSONException e) { // it's OK for post to be null } try { if (json.has(POST_PATH_KEY)) { requestPath = json.getString(POST_PATH_KEY); } } catch (JSONException e) { // it's OK for post to be null } if (requestPath != null && requestPath.length() > 0) { return getExtendedServerRequest(requestPath, post, context); } return null; }
[ "public", "static", "ServerRequest", "fromJSON", "(", "JSONObject", "json", ",", "Context", "context", ")", "{", "JSONObject", "post", "=", "null", ";", "String", "requestPath", "=", "\"\"", ";", "try", "{", "if", "(", "json", ".", "has", "(", "POST_KEY", ")", ")", "{", "post", "=", "json", ".", "getJSONObject", "(", "POST_KEY", ")", ";", "}", "}", "catch", "(", "JSONException", "e", ")", "{", "// it's OK for post to be null", "}", "try", "{", "if", "(", "json", ".", "has", "(", "POST_PATH_KEY", ")", ")", "{", "requestPath", "=", "json", ".", "getString", "(", "POST_PATH_KEY", ")", ";", "}", "}", "catch", "(", "JSONException", "e", ")", "{", "// it's OK for post to be null", "}", "if", "(", "requestPath", "!=", "null", "&&", "requestPath", ".", "length", "(", ")", ">", "0", ")", "{", "return", "getExtendedServerRequest", "(", "requestPath", ",", "post", ",", "context", ")", ";", "}", "return", "null", ";", "}" ]
<p>Converts a {@link JSONObject} object containing keys stored as key-value pairs into a {@link ServerRequest}.</p> @param json A {@link JSONObject} object containing post data stored as key-value pairs @param context Application context. @return A {@link ServerRequest} object with the {@link #POST_KEY} values set if not null; this can be one or the other. If both values in the supplied {@link JSONObject} are null, null is returned instead of an object.
[ "<p", ">", "Converts", "a", "{", "@link", "JSONObject", "}", "object", "containing", "keys", "stored", "as", "key", "-", "value", "pairs", "into", "a", "{", "@link", "ServerRequest", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ServerRequest.java#L302-L325
ebean-orm/ebean-mocker
src/main/java/io/ebean/MockiEbean.java
MockiEbean.start
public static MockiEbean start(EbeanServer mock) { """ Set a mock implementation of EbeanServer as the default server. <p> Typically the mock instance passed in is created by Mockito or similar tool. <p> The default EbeanSever is the instance returned by {@link Ebean#getServer(String)} when the server name is null. @param mock the mock instance that becomes the default EbeanServer @return The MockiEbean with a {@link #restoreOriginal()} method that can be used to restore the original EbeanServer implementation. """ // using $mock as the server name EbeanServer original = Ebean.mock("$mock", mock, true); if (mock instanceof DelegateAwareEbeanServer) { ((DelegateAwareEbeanServer)mock).withDelegateIfRequired(original); } return new MockiEbean(mock, original); }
java
public static MockiEbean start(EbeanServer mock) { // using $mock as the server name EbeanServer original = Ebean.mock("$mock", mock, true); if (mock instanceof DelegateAwareEbeanServer) { ((DelegateAwareEbeanServer)mock).withDelegateIfRequired(original); } return new MockiEbean(mock, original); }
[ "public", "static", "MockiEbean", "start", "(", "EbeanServer", "mock", ")", "{", "// using $mock as the server name", "EbeanServer", "original", "=", "Ebean", ".", "mock", "(", "\"$mock\"", ",", "mock", ",", "true", ")", ";", "if", "(", "mock", "instanceof", "DelegateAwareEbeanServer", ")", "{", "(", "(", "DelegateAwareEbeanServer", ")", "mock", ")", ".", "withDelegateIfRequired", "(", "original", ")", ";", "}", "return", "new", "MockiEbean", "(", "mock", ",", "original", ")", ";", "}" ]
Set a mock implementation of EbeanServer as the default server. <p> Typically the mock instance passed in is created by Mockito or similar tool. <p> The default EbeanSever is the instance returned by {@link Ebean#getServer(String)} when the server name is null. @param mock the mock instance that becomes the default EbeanServer @return The MockiEbean with a {@link #restoreOriginal()} method that can be used to restore the original EbeanServer implementation.
[ "Set", "a", "mock", "implementation", "of", "EbeanServer", "as", "the", "default", "server", ".", "<p", ">", "Typically", "the", "mock", "instance", "passed", "in", "is", "created", "by", "Mockito", "or", "similar", "tool", ".", "<p", ">", "The", "default", "EbeanSever", "is", "the", "instance", "returned", "by", "{", "@link", "Ebean#getServer", "(", "String", ")", "}", "when", "the", "server", "name", "is", "null", "." ]
train
https://github.com/ebean-orm/ebean-mocker/blob/98c14a58253e8cd40b2a0c9b49526a307079389a/src/main/java/io/ebean/MockiEbean.java#L78-L88
landawn/AbacusUtil
src/com/landawn/abacus/util/CSVUtil.java
CSVUtil.loadCSV
@SuppressWarnings("rawtypes") public static <E extends Exception> DataSet loadCSV(final InputStream csvInputStream, final long offset, final long count, final Try.Predicate<String[], E> filter, final Map<String, ? extends Type> columnTypeMap) throws UncheckedIOException, E { """ Load the data from CSV. @param csvInputStream @param offset @param count @param filter @param columnTypeMap @return """ final Reader csvReader = new InputStreamReader(csvInputStream); return loadCSV(csvReader, offset, count, filter, columnTypeMap); }
java
@SuppressWarnings("rawtypes") public static <E extends Exception> DataSet loadCSV(final InputStream csvInputStream, final long offset, final long count, final Try.Predicate<String[], E> filter, final Map<String, ? extends Type> columnTypeMap) throws UncheckedIOException, E { final Reader csvReader = new InputStreamReader(csvInputStream); return loadCSV(csvReader, offset, count, filter, columnTypeMap); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "static", "<", "E", "extends", "Exception", ">", "DataSet", "loadCSV", "(", "final", "InputStream", "csvInputStream", ",", "final", "long", "offset", ",", "final", "long", "count", ",", "final", "Try", ".", "Predicate", "<", "String", "[", "]", ",", "E", ">", "filter", ",", "final", "Map", "<", "String", ",", "?", "extends", "Type", ">", "columnTypeMap", ")", "throws", "UncheckedIOException", ",", "E", "{", "final", "Reader", "csvReader", "=", "new", "InputStreamReader", "(", "csvInputStream", ")", ";", "return", "loadCSV", "(", "csvReader", ",", "offset", ",", "count", ",", "filter", ",", "columnTypeMap", ")", ";", "}" ]
Load the data from CSV. @param csvInputStream @param offset @param count @param filter @param columnTypeMap @return
[ "Load", "the", "data", "from", "CSV", ".", "@param", "csvInputStream", "@param", "offset", "@param", "count", "@param", "filter", "@param", "columnTypeMap" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CSVUtil.java#L441-L447
ops4j/org.ops4j.base
ops4j-base-util/src/main/java/org/ops4j/util/i18n/Resources.java
Resources.getChar
public char getChar( String key, char defaultValue ) throws MissingResourceException { """ Retrieve a char from bundle. @param key the key of resource @param defaultValue the default value if key is missing @return the resource char @throws MissingResourceException if the requested key is unknown """ try { return getChar( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
java
public char getChar( String key, char defaultValue ) throws MissingResourceException { try { return getChar( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
[ "public", "char", "getChar", "(", "String", "key", ",", "char", "defaultValue", ")", "throws", "MissingResourceException", "{", "try", "{", "return", "getChar", "(", "key", ")", ";", "}", "catch", "(", "MissingResourceException", "mre", ")", "{", "return", "defaultValue", ";", "}", "}" ]
Retrieve a char from bundle. @param key the key of resource @param defaultValue the default value if key is missing @return the resource char @throws MissingResourceException if the requested key is unknown
[ "Retrieve", "a", "char", "from", "bundle", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/Resources.java#L226-L237
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/style/stylers/Image.java
Image.shouldStyle
@Override public boolean shouldStyle(Object data, Object element) { """ calls {@link #doStyle()} and the super @param data @param element the value of element @return """ if (!doStyle()) { log.warning(String.format("not styling becasue parameter %s is false. %s, key: %s", DOSTYLE, getClass().getName(), getStyleClass())); } return doStyle() && super.shouldStyle(data, element); }
java
@Override public boolean shouldStyle(Object data, Object element) { if (!doStyle()) { log.warning(String.format("not styling becasue parameter %s is false. %s, key: %s", DOSTYLE, getClass().getName(), getStyleClass())); } return doStyle() && super.shouldStyle(data, element); }
[ "@", "Override", "public", "boolean", "shouldStyle", "(", "Object", "data", ",", "Object", "element", ")", "{", "if", "(", "!", "doStyle", "(", ")", ")", "{", "log", ".", "warning", "(", "String", ".", "format", "(", "\"not styling becasue parameter %s is false. %s, key: %s\"", ",", "DOSTYLE", ",", "getClass", "(", ")", ".", "getName", "(", ")", ",", "getStyleClass", "(", ")", ")", ")", ";", "}", "return", "doStyle", "(", ")", "&&", "super", ".", "shouldStyle", "(", "data", ",", "element", ")", ";", "}" ]
calls {@link #doStyle()} and the super @param data @param element the value of element @return
[ "calls", "{", "@link", "#doStyle", "()", "}", "and", "the", "super" ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/stylers/Image.java#L353-L359
james-hu/jabb-core
src/main/java/net/sf/jabb/util/parallel/BackoffStrategies.java
BackoffStrategies.exponentialBackoff
public static BackoffStrategy exponentialBackoff(long maximumTime, TimeUnit maximumTimeUnit) { """ Returns a strategy which waits for an exponential amount of time after the first failed attempt, and in exponentially incrementing amounts after each failed attempt up to the maximumTime. @param maximumTime the maximum time to wait @param maximumTimeUnit the unit of the maximum time @return a backoff strategy that increments with each failed attempt using exponential backoff """ Preconditions.checkNotNull(maximumTimeUnit, "The maximum time unit may not be null"); return new ExponentialBackoffStrategy(1, maximumTimeUnit.toMillis(maximumTime)); }
java
public static BackoffStrategy exponentialBackoff(long maximumTime, TimeUnit maximumTimeUnit) { Preconditions.checkNotNull(maximumTimeUnit, "The maximum time unit may not be null"); return new ExponentialBackoffStrategy(1, maximumTimeUnit.toMillis(maximumTime)); }
[ "public", "static", "BackoffStrategy", "exponentialBackoff", "(", "long", "maximumTime", ",", "TimeUnit", "maximumTimeUnit", ")", "{", "Preconditions", ".", "checkNotNull", "(", "maximumTimeUnit", ",", "\"The maximum time unit may not be null\"", ")", ";", "return", "new", "ExponentialBackoffStrategy", "(", "1", ",", "maximumTimeUnit", ".", "toMillis", "(", "maximumTime", ")", ")", ";", "}" ]
Returns a strategy which waits for an exponential amount of time after the first failed attempt, and in exponentially incrementing amounts after each failed attempt up to the maximumTime. @param maximumTime the maximum time to wait @param maximumTimeUnit the unit of the maximum time @return a backoff strategy that increments with each failed attempt using exponential backoff
[ "Returns", "a", "strategy", "which", "waits", "for", "an", "exponential", "amount", "of", "time", "after", "the", "first", "failed", "attempt", "and", "in", "exponentially", "incrementing", "amounts", "after", "each", "failed", "attempt", "up", "to", "the", "maximumTime", "." ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/parallel/BackoffStrategies.java#L185-L188
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/metrics/Monitors.java
Monitors.createCompoundJvmMonitor
public static Monitor createCompoundJvmMonitor(Map<String, String[]> dimensions) { """ Creates a JVM monitor, configured with the given dimensions, that gathers all currently available JVM-wide monitors. Emitted events have default feed {@link FeedDefiningMonitor#DEFAULT_METRICS_FEED} See: {@link Monitors#createCompoundJvmMonitor(Map, String)} @param dimensions common dimensions to configure the JVM monitor with @return a universally useful JVM-wide monitor """ return createCompoundJvmMonitor(dimensions, FeedDefiningMonitor.DEFAULT_METRICS_FEED); }
java
public static Monitor createCompoundJvmMonitor(Map<String, String[]> dimensions) { return createCompoundJvmMonitor(dimensions, FeedDefiningMonitor.DEFAULT_METRICS_FEED); }
[ "public", "static", "Monitor", "createCompoundJvmMonitor", "(", "Map", "<", "String", ",", "String", "[", "]", ">", "dimensions", ")", "{", "return", "createCompoundJvmMonitor", "(", "dimensions", ",", "FeedDefiningMonitor", ".", "DEFAULT_METRICS_FEED", ")", ";", "}" ]
Creates a JVM monitor, configured with the given dimensions, that gathers all currently available JVM-wide monitors. Emitted events have default feed {@link FeedDefiningMonitor#DEFAULT_METRICS_FEED} See: {@link Monitors#createCompoundJvmMonitor(Map, String)} @param dimensions common dimensions to configure the JVM monitor with @return a universally useful JVM-wide monitor
[ "Creates", "a", "JVM", "monitor", "configured", "with", "the", "given", "dimensions", "that", "gathers", "all", "currently", "available", "JVM", "-", "wide", "monitors", ".", "Emitted", "events", "have", "default", "feed", "{", "@link", "FeedDefiningMonitor#DEFAULT_METRICS_FEED", "}", "See", ":", "{", "@link", "Monitors#createCompoundJvmMonitor", "(", "Map", "String", ")", "}" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/metrics/Monitors.java#L36-L39
looly/hutool
hutool-log/src/main/java/cn/hutool/log/dialect/log4j2/Log4j2Log.java
Log4j2Log.logIfEnabled
private boolean logIfEnabled(String fqcn, Level level, Throwable t, String msgTemplate, Object... arguments) { """ 打印日志<br> 此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题 @param fqcn 完全限定类名(Fully Qualified Class Name),用于纠正定位错误行号 @param level 日志级别,使用org.apache.logging.log4j.Level中的常量 @param t 异常 @param msgTemplate 消息模板 @param arguments 参数 @return 是否支持 LocationAwareLogger对象,如果不支持需要日志方法调用被包装类的相应方法 """ if(this.logger instanceof AbstractLogger){ ((AbstractLogger)this.logger).logIfEnabled(fqcn, level, null, StrUtil.format(msgTemplate, arguments), t); return true; }else{ return false; } }
java
private boolean logIfEnabled(String fqcn, Level level, Throwable t, String msgTemplate, Object... arguments) { if(this.logger instanceof AbstractLogger){ ((AbstractLogger)this.logger).logIfEnabled(fqcn, level, null, StrUtil.format(msgTemplate, arguments), t); return true; }else{ return false; } }
[ "private", "boolean", "logIfEnabled", "(", "String", "fqcn", ",", "Level", "level", ",", "Throwable", "t", ",", "String", "msgTemplate", ",", "Object", "...", "arguments", ")", "{", "if", "(", "this", ".", "logger", "instanceof", "AbstractLogger", ")", "{", "(", "(", "AbstractLogger", ")", "this", ".", "logger", ")", ".", "logIfEnabled", "(", "fqcn", ",", "level", ",", "null", ",", "StrUtil", ".", "format", "(", "msgTemplate", ",", "arguments", ")", ",", "t", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
打印日志<br> 此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题 @param fqcn 完全限定类名(Fully Qualified Class Name),用于纠正定位错误行号 @param level 日志级别,使用org.apache.logging.log4j.Level中的常量 @param t 异常 @param msgTemplate 消息模板 @param arguments 参数 @return 是否支持 LocationAwareLogger对象,如果不支持需要日志方法调用被包装类的相应方法
[ "打印日志<br", ">", "此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-log/src/main/java/cn/hutool/log/dialect/log4j2/Log4j2Log.java#L192-L199
geomajas/geomajas-project-client-gwt2
common-gwt/common-gwt/src/main/java/org/geomajas/gwt/client/util/impl/DomImplIE.java
DomImplIE.setTransform
public void setTransform(Element element, String transform) { """ Only very limited support for transformations, so {@link #supportsTransformations()} still returns false. @param element @param transform """ if (transform.contains("scale")) { try { String scaleValue = transform.substring(transform.indexOf("scale(") + 6); scaleValue = scaleValue.substring(0, scaleValue.indexOf(")")); Dom.setStyleAttribute(element, "zoom", scaleValue); } catch (Exception e) { } } }
java
public void setTransform(Element element, String transform) { if (transform.contains("scale")) { try { String scaleValue = transform.substring(transform.indexOf("scale(") + 6); scaleValue = scaleValue.substring(0, scaleValue.indexOf(")")); Dom.setStyleAttribute(element, "zoom", scaleValue); } catch (Exception e) { } } }
[ "public", "void", "setTransform", "(", "Element", "element", ",", "String", "transform", ")", "{", "if", "(", "transform", ".", "contains", "(", "\"scale\"", ")", ")", "{", "try", "{", "String", "scaleValue", "=", "transform", ".", "substring", "(", "transform", ".", "indexOf", "(", "\"scale(\"", ")", "+", "6", ")", ";", "scaleValue", "=", "scaleValue", ".", "substring", "(", "0", ",", "scaleValue", ".", "indexOf", "(", "\")\"", ")", ")", ";", "Dom", ".", "setStyleAttribute", "(", "element", ",", "\"zoom\"", ",", "scaleValue", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "}" ]
Only very limited support for transformations, so {@link #supportsTransformations()} still returns false. @param element @param transform
[ "Only", "very", "limited", "support", "for", "transformations", "so", "{", "@link", "#supportsTransformations", "()", "}", "still", "returns", "false", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/common-gwt/common-gwt/src/main/java/org/geomajas/gwt/client/util/impl/DomImplIE.java#L97-L106
samskivert/pythagoras
src/main/java/pythagoras/d/Quaternion.java
Quaternion.fromVectorFromNegativeZ
public Quaternion fromVectorFromNegativeZ (double tx, double ty, double tz) { """ Sets this quaternion to the rotation of (0, 0, -1) onto the supplied normalized vector. @return a reference to the quaternion, for chaining. """ double angle = Math.acos(-tz); if (angle < MathUtil.EPSILON) { return set(IDENTITY); } if (angle > Math.PI - MathUtil.EPSILON) { return set(0f, 1f, 0f, 0f); // 180 degrees about y } double len = Math.hypot(tx, ty); return fromAngleAxis(angle, ty/len, -tx/len, 0f); }
java
public Quaternion fromVectorFromNegativeZ (double tx, double ty, double tz) { double angle = Math.acos(-tz); if (angle < MathUtil.EPSILON) { return set(IDENTITY); } if (angle > Math.PI - MathUtil.EPSILON) { return set(0f, 1f, 0f, 0f); // 180 degrees about y } double len = Math.hypot(tx, ty); return fromAngleAxis(angle, ty/len, -tx/len, 0f); }
[ "public", "Quaternion", "fromVectorFromNegativeZ", "(", "double", "tx", ",", "double", "ty", ",", "double", "tz", ")", "{", "double", "angle", "=", "Math", ".", "acos", "(", "-", "tz", ")", ";", "if", "(", "angle", "<", "MathUtil", ".", "EPSILON", ")", "{", "return", "set", "(", "IDENTITY", ")", ";", "}", "if", "(", "angle", ">", "Math", ".", "PI", "-", "MathUtil", ".", "EPSILON", ")", "{", "return", "set", "(", "0f", ",", "1f", ",", "0f", ",", "0f", ")", ";", "// 180 degrees about y", "}", "double", "len", "=", "Math", ".", "hypot", "(", "tx", ",", "ty", ")", ";", "return", "fromAngleAxis", "(", "angle", ",", "ty", "/", "len", ",", "-", "tx", "/", "len", ",", "0f", ")", ";", "}" ]
Sets this quaternion to the rotation of (0, 0, -1) onto the supplied normalized vector. @return a reference to the quaternion, for chaining.
[ "Sets", "this", "quaternion", "to", "the", "rotation", "of", "(", "0", "0", "-", "1", ")", "onto", "the", "supplied", "normalized", "vector", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/Quaternion.java#L120-L130
cogroo/cogroo4
cogroo-gc/src/main/java/org/cogroo/tools/checker/checkers/SpaceChecker.java
SpaceChecker.getsSupposedError
private String getsSupposedError(String text, int position) { """ Analyze a sentence and gets the word which contains the position of the error in the parameter @param text the entire sentence to be analyzed @param position where in the sentence the supposed error was found @return the word which contains the supposed error """ int ini; boolean end = false; String word = text; // Indicates where the position of the supposed word begin for (ini = position; ini >= 0; ini--) if (Character.isWhitespace(text.charAt(ini)) || isOpenBracket(text.charAt(ini))) break; // Indicates where the supposed word should end for (int i = position + 1; i < text.length() && end == false; i++) { switch (text.charAt(i)) { // Indicates the end of the supposed error case ' ': case '!': case '?': case ',': case ';': case ')': case ']': case '}': case '”': case '\n': // The supposed e-mail is attributed in its proper variable word = word.substring(ini + 1, i); end = true; break; // Possible end of sentence or just part of the supposed error case '.': if (Character.isWhitespace(text.charAt(i + 1))) { word = word.substring(ini + 1, i); end = true; break; } // Character or digit that is part of the supposed error default: break; } } return word; }
java
private String getsSupposedError(String text, int position) { int ini; boolean end = false; String word = text; // Indicates where the position of the supposed word begin for (ini = position; ini >= 0; ini--) if (Character.isWhitespace(text.charAt(ini)) || isOpenBracket(text.charAt(ini))) break; // Indicates where the supposed word should end for (int i = position + 1; i < text.length() && end == false; i++) { switch (text.charAt(i)) { // Indicates the end of the supposed error case ' ': case '!': case '?': case ',': case ';': case ')': case ']': case '}': case '”': case '\n': // The supposed e-mail is attributed in its proper variable word = word.substring(ini + 1, i); end = true; break; // Possible end of sentence or just part of the supposed error case '.': if (Character.isWhitespace(text.charAt(i + 1))) { word = word.substring(ini + 1, i); end = true; break; } // Character or digit that is part of the supposed error default: break; } } return word; }
[ "private", "String", "getsSupposedError", "(", "String", "text", ",", "int", "position", ")", "{", "int", "ini", ";", "boolean", "end", "=", "false", ";", "String", "word", "=", "text", ";", "// Indicates where the position of the supposed word begin\r", "for", "(", "ini", "=", "position", ";", "ini", ">=", "0", ";", "ini", "--", ")", "if", "(", "Character", ".", "isWhitespace", "(", "text", ".", "charAt", "(", "ini", ")", ")", "||", "isOpenBracket", "(", "text", ".", "charAt", "(", "ini", ")", ")", ")", "break", ";", "// Indicates where the supposed word should end\r", "for", "(", "int", "i", "=", "position", "+", "1", ";", "i", "<", "text", ".", "length", "(", ")", "&&", "end", "==", "false", ";", "i", "++", ")", "{", "switch", "(", "text", ".", "charAt", "(", "i", ")", ")", "{", "// Indicates the end of the supposed error\r", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "\r", "", "case", "'", "'", ":", "// The supposed e-mail is attributed in its proper variable\r", "word", "=", "word", ".", "substring", "(", "ini", "+", "1", ",", "i", ")", ";", "end", "=", "true", ";", "break", ";", "// Possible end of sentence or just part of the supposed error\r", "case", "'", "'", ":", "if", "(", "Character", ".", "isWhitespace", "(", "text", ".", "charAt", "(", "i", "+", "1", ")", ")", ")", "{", "word", "=", "word", ".", "substring", "(", "ini", "+", "1", ",", "i", ")", ";", "end", "=", "true", ";", "break", ";", "}", "// Character or digit that is part of the supposed error\r", "default", ":", "break", ";", "}", "}", "return", "word", ";", "}" ]
Analyze a sentence and gets the word which contains the position of the error in the parameter @param text the entire sentence to be analyzed @param position where in the sentence the supposed error was found @return the word which contains the supposed error
[ "Analyze", "a", "sentence", "and", "gets", "the", "word", "which", "contains", "the", "position", "of", "the", "error", "in", "the", "parameter" ]
train
https://github.com/cogroo/cogroo4/blob/b6228900c20c6b37eac10a03708a9669dd562f52/cogroo-gc/src/main/java/org/cogroo/tools/checker/checkers/SpaceChecker.java#L227-L273
facebookarchive/hadoop-20
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java
AvatarNodeZkUtil.writeToZooKeeperAfterFailover
static long writeToZooKeeperAfterFailover(Configuration startupConf, Configuration confg) throws IOException { """ Performs some operations after failover such as writing a new session id and registering to zookeeper as the new primary. @param startupConf the startup configuration @param confg the current configuration @return the session id for the new node after failover @throws IOException """ AvatarZooKeeperClient zk = null; // Register client port address. String address = startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); String realAddress = confg.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3); for (int i = 0; i < maxTries; i++) { try { zk = new AvatarZooKeeperClient(confg, null, false); LOG.info("Failover: Registering to ZK as primary"); final boolean toOverwrite = true; zk.registerPrimary(address, realAddress, toOverwrite); registerClientProtocolAddress(zk, startupConf, confg, toOverwrite); registerDnProtocolAddress(zk, startupConf, confg, toOverwrite); registerHttpAddress(zk, startupConf, confg, toOverwrite); LOG.info("Failover: Writting session id to ZK"); return writeSessionIdToZK(startupConf, zk); } catch (Exception e) { LOG.error("Got Exception registering the new primary " + "with ZooKeeper. Will retry...", e); } finally { shutdownZkClient(zk); } } throw new IOException("Cannot connect to zk"); }
java
static long writeToZooKeeperAfterFailover(Configuration startupConf, Configuration confg) throws IOException { AvatarZooKeeperClient zk = null; // Register client port address. String address = startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); String realAddress = confg.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY); int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3); for (int i = 0; i < maxTries; i++) { try { zk = new AvatarZooKeeperClient(confg, null, false); LOG.info("Failover: Registering to ZK as primary"); final boolean toOverwrite = true; zk.registerPrimary(address, realAddress, toOverwrite); registerClientProtocolAddress(zk, startupConf, confg, toOverwrite); registerDnProtocolAddress(zk, startupConf, confg, toOverwrite); registerHttpAddress(zk, startupConf, confg, toOverwrite); LOG.info("Failover: Writting session id to ZK"); return writeSessionIdToZK(startupConf, zk); } catch (Exception e) { LOG.error("Got Exception registering the new primary " + "with ZooKeeper. Will retry...", e); } finally { shutdownZkClient(zk); } } throw new IOException("Cannot connect to zk"); }
[ "static", "long", "writeToZooKeeperAfterFailover", "(", "Configuration", "startupConf", ",", "Configuration", "confg", ")", "throws", "IOException", "{", "AvatarZooKeeperClient", "zk", "=", "null", ";", "// Register client port address.", "String", "address", "=", "startupConf", ".", "get", "(", "NameNode", ".", "DFS_NAMENODE_RPC_ADDRESS_KEY", ")", ";", "String", "realAddress", "=", "confg", ".", "get", "(", "NameNode", ".", "DFS_NAMENODE_RPC_ADDRESS_KEY", ")", ";", "int", "maxTries", "=", "startupConf", ".", "getInt", "(", "\"dfs.avatarnode.zk.retries\"", ",", "3", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxTries", ";", "i", "++", ")", "{", "try", "{", "zk", "=", "new", "AvatarZooKeeperClient", "(", "confg", ",", "null", ",", "false", ")", ";", "LOG", ".", "info", "(", "\"Failover: Registering to ZK as primary\"", ")", ";", "final", "boolean", "toOverwrite", "=", "true", ";", "zk", ".", "registerPrimary", "(", "address", ",", "realAddress", ",", "toOverwrite", ")", ";", "registerClientProtocolAddress", "(", "zk", ",", "startupConf", ",", "confg", ",", "toOverwrite", ")", ";", "registerDnProtocolAddress", "(", "zk", ",", "startupConf", ",", "confg", ",", "toOverwrite", ")", ";", "registerHttpAddress", "(", "zk", ",", "startupConf", ",", "confg", ",", "toOverwrite", ")", ";", "LOG", ".", "info", "(", "\"Failover: Writting session id to ZK\"", ")", ";", "return", "writeSessionIdToZK", "(", "startupConf", ",", "zk", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Got Exception registering the new primary \"", "+", "\"with ZooKeeper. Will retry...\"", ",", "e", ")", ";", "}", "finally", "{", "shutdownZkClient", "(", "zk", ")", ";", "}", "}", "throw", "new", "IOException", "(", "\"Cannot connect to zk\"", ")", ";", "}" ]
Performs some operations after failover such as writing a new session id and registering to zookeeper as the new primary. @param startupConf the startup configuration @param confg the current configuration @return the session id for the new node after failover @throws IOException
[ "Performs", "some", "operations", "after", "failover", "such", "as", "writing", "a", "new", "session", "id", "and", "registering", "to", "zookeeper", "as", "the", "new", "primary", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNodeZkUtil.java#L111-L138
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/util/ArchiveUtils.java
ArchiveUtils.tarGzExtractSingleFile
public static void tarGzExtractSingleFile(File tarGz, File destination, String pathInTarGz) throws IOException { """ Extract a single file from a tar.gz file. Does not support directories. NOTE: This should not be used for batch extraction of files, due to the need to iterate over the entries until the specified entry is found. Use {@link #unzipFileTo(String, String)} for batch extraction instead @param tarGz A tar.gz file @param destination The destination file to extract to @param pathInTarGz The path in the tar.gz file to extract """ try(TarArchiveInputStream tin = new TarArchiveInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(tarGz))))) { ArchiveEntry entry; List<String> out = new ArrayList<>(); boolean extracted = false; while((entry = tin.getNextTarEntry()) != null){ String name = entry.getName(); if(pathInTarGz.equals(name)){ try(OutputStream os = new BufferedOutputStream(new FileOutputStream(destination))){ IOUtils.copy(tin, os); } extracted = true; } } Preconditions.checkState(extracted, "No file was extracted. File not found? %s", pathInTarGz); } }
java
public static void tarGzExtractSingleFile(File tarGz, File destination, String pathInTarGz) throws IOException { try(TarArchiveInputStream tin = new TarArchiveInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(tarGz))))) { ArchiveEntry entry; List<String> out = new ArrayList<>(); boolean extracted = false; while((entry = tin.getNextTarEntry()) != null){ String name = entry.getName(); if(pathInTarGz.equals(name)){ try(OutputStream os = new BufferedOutputStream(new FileOutputStream(destination))){ IOUtils.copy(tin, os); } extracted = true; } } Preconditions.checkState(extracted, "No file was extracted. File not found? %s", pathInTarGz); } }
[ "public", "static", "void", "tarGzExtractSingleFile", "(", "File", "tarGz", ",", "File", "destination", ",", "String", "pathInTarGz", ")", "throws", "IOException", "{", "try", "(", "TarArchiveInputStream", "tin", "=", "new", "TarArchiveInputStream", "(", "new", "GZIPInputStream", "(", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "tarGz", ")", ")", ")", ")", ")", "{", "ArchiveEntry", "entry", ";", "List", "<", "String", ">", "out", "=", "new", "ArrayList", "<>", "(", ")", ";", "boolean", "extracted", "=", "false", ";", "while", "(", "(", "entry", "=", "tin", ".", "getNextTarEntry", "(", ")", ")", "!=", "null", ")", "{", "String", "name", "=", "entry", ".", "getName", "(", ")", ";", "if", "(", "pathInTarGz", ".", "equals", "(", "name", ")", ")", "{", "try", "(", "OutputStream", "os", "=", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "destination", ")", ")", ")", "{", "IOUtils", ".", "copy", "(", "tin", ",", "os", ")", ";", "}", "extracted", "=", "true", ";", "}", "}", "Preconditions", ".", "checkState", "(", "extracted", ",", "\"No file was extracted. File not found? %s\"", ",", "pathInTarGz", ")", ";", "}", "}" ]
Extract a single file from a tar.gz file. Does not support directories. NOTE: This should not be used for batch extraction of files, due to the need to iterate over the entries until the specified entry is found. Use {@link #unzipFileTo(String, String)} for batch extraction instead @param tarGz A tar.gz file @param destination The destination file to extract to @param pathInTarGz The path in the tar.gz file to extract
[ "Extract", "a", "single", "file", "from", "a", "tar", ".", "gz", "file", ".", "Does", "not", "support", "directories", ".", "NOTE", ":", "This", "should", "not", "be", "used", "for", "batch", "extraction", "of", "files", "due", "to", "the", "need", "to", "iterate", "over", "the", "entries", "until", "the", "specified", "entry", "is", "found", ".", "Use", "{", "@link", "#unzipFileTo", "(", "String", "String", ")", "}", "for", "batch", "extraction", "instead" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-common/src/main/java/org/nd4j/util/ArchiveUtils.java#L218-L234
haifengl/smile
core/src/main/java/smile/validation/Validation.java
Validation.loocv
public static <T> double loocv(ClassifierTrainer<T> trainer, T[] x, int[] y) { """ Leave-one-out cross validation of a classification model. @param <T> the data type of input objects. @param trainer a classifier trainer that is properly parameterized. @param x the test data set. @param y the test data labels. @return the accuracy on test dataset """ int m = 0; int n = x.length; LOOCV loocv = new LOOCV(n); for (int i = 0; i < n; i++) { T[] trainx = Math.slice(x, loocv.train[i]); int[] trainy = Math.slice(y, loocv.train[i]); Classifier<T> classifier = trainer.train(trainx, trainy); if (classifier.predict(x[loocv.test[i]]) == y[loocv.test[i]]) { m++; } } return (double) m / n; }
java
public static <T> double loocv(ClassifierTrainer<T> trainer, T[] x, int[] y) { int m = 0; int n = x.length; LOOCV loocv = new LOOCV(n); for (int i = 0; i < n; i++) { T[] trainx = Math.slice(x, loocv.train[i]); int[] trainy = Math.slice(y, loocv.train[i]); Classifier<T> classifier = trainer.train(trainx, trainy); if (classifier.predict(x[loocv.test[i]]) == y[loocv.test[i]]) { m++; } } return (double) m / n; }
[ "public", "static", "<", "T", ">", "double", "loocv", "(", "ClassifierTrainer", "<", "T", ">", "trainer", ",", "T", "[", "]", "x", ",", "int", "[", "]", "y", ")", "{", "int", "m", "=", "0", ";", "int", "n", "=", "x", ".", "length", ";", "LOOCV", "loocv", "=", "new", "LOOCV", "(", "n", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "T", "[", "]", "trainx", "=", "Math", ".", "slice", "(", "x", ",", "loocv", ".", "train", "[", "i", "]", ")", ";", "int", "[", "]", "trainy", "=", "Math", ".", "slice", "(", "y", ",", "loocv", ".", "train", "[", "i", "]", ")", ";", "Classifier", "<", "T", ">", "classifier", "=", "trainer", ".", "train", "(", "trainx", ",", "trainy", ")", ";", "if", "(", "classifier", ".", "predict", "(", "x", "[", "loocv", ".", "test", "[", "i", "]", "]", ")", "==", "y", "[", "loocv", ".", "test", "[", "i", "]", "]", ")", "{", "m", "++", ";", "}", "}", "return", "(", "double", ")", "m", "/", "n", ";", "}" ]
Leave-one-out cross validation of a classification model. @param <T> the data type of input objects. @param trainer a classifier trainer that is properly parameterized. @param x the test data set. @param y the test data labels. @return the accuracy on test dataset
[ "Leave", "-", "one", "-", "out", "cross", "validation", "of", "a", "classification", "model", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/validation/Validation.java#L169-L186
vkostyukov/la4j
src/main/java/org/la4j/Matrix.java
Matrix.updateAt
public void updateAt(int i, int j, MatrixFunction function) { """ Updates the specified element of this matrix by applying given {@code function}. @param i the row index @param j the column index @param function the matrix function """ set(i, j, function.evaluate(i, j, get(i, j))); }
java
public void updateAt(int i, int j, MatrixFunction function) { set(i, j, function.evaluate(i, j, get(i, j))); }
[ "public", "void", "updateAt", "(", "int", "i", ",", "int", "j", ",", "MatrixFunction", "function", ")", "{", "set", "(", "i", ",", "j", ",", "function", ".", "evaluate", "(", "i", ",", "j", ",", "get", "(", "i", ",", "j", ")", ")", ")", ";", "}" ]
Updates the specified element of this matrix by applying given {@code function}. @param i the row index @param j the column index @param function the matrix function
[ "Updates", "the", "specified", "element", "of", "this", "matrix", "by", "applying", "given", "{", "@code", "function", "}", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Matrix.java#L1560-L1562
graphhopper/graphhopper
core/src/main/java/com/graphhopper/util/Downloader.java
Downloader.fetch
public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException { """ This method initiates a connect call of the provided connection and returns the response stream. It only returns the error stream if it is available and readErrorStreamNoException is true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream to decompress it if the connection content encoding is specified. """ // create connection but before reading get the correct inputstream based on the compression and if error connection.connect(); InputStream is; if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null) is = connection.getErrorStream(); else is = connection.getInputStream(); if (is == null) throw new IOException("Stream is null. Message:" + connection.getResponseMessage()); // wrap try { String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(is); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(is, new Inflater(true)); } catch (IOException ex) { } return is; }
java
public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException { // create connection but before reading get the correct inputstream based on the compression and if error connection.connect(); InputStream is; if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null) is = connection.getErrorStream(); else is = connection.getInputStream(); if (is == null) throw new IOException("Stream is null. Message:" + connection.getResponseMessage()); // wrap try { String encoding = connection.getContentEncoding(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(is); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(is, new Inflater(true)); } catch (IOException ex) { } return is; }
[ "public", "InputStream", "fetch", "(", "HttpURLConnection", "connection", ",", "boolean", "readErrorStreamNoException", ")", "throws", "IOException", "{", "// create connection but before reading get the correct inputstream based on the compression and if error", "connection", ".", "connect", "(", ")", ";", "InputStream", "is", ";", "if", "(", "readErrorStreamNoException", "&&", "connection", ".", "getResponseCode", "(", ")", ">=", "400", "&&", "connection", ".", "getErrorStream", "(", ")", "!=", "null", ")", "is", "=", "connection", ".", "getErrorStream", "(", ")", ";", "else", "is", "=", "connection", ".", "getInputStream", "(", ")", ";", "if", "(", "is", "==", "null", ")", "throw", "new", "IOException", "(", "\"Stream is null. Message:\"", "+", "connection", ".", "getResponseMessage", "(", ")", ")", ";", "// wrap", "try", "{", "String", "encoding", "=", "connection", ".", "getContentEncoding", "(", ")", ";", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "equalsIgnoreCase", "(", "\"gzip\"", ")", ")", "is", "=", "new", "GZIPInputStream", "(", "is", ")", ";", "else", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "equalsIgnoreCase", "(", "\"deflate\"", ")", ")", "is", "=", "new", "InflaterInputStream", "(", "is", ",", "new", "Inflater", "(", "true", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "}", "return", "is", ";", "}" ]
This method initiates a connect call of the provided connection and returns the response stream. It only returns the error stream if it is available and readErrorStreamNoException is true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream to decompress it if the connection content encoding is specified.
[ "This", "method", "initiates", "a", "connect", "call", "of", "the", "provided", "connection", "and", "returns", "the", "response", "stream", ".", "It", "only", "returns", "the", "error", "stream", "if", "it", "is", "available", "and", "readErrorStreamNoException", "is", "true", "otherwise", "it", "throws", "an", "IOException", "if", "an", "error", "happens", ".", "Furthermore", "it", "wraps", "the", "stream", "to", "decompress", "it", "if", "the", "connection", "content", "encoding", "is", "specified", "." ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/util/Downloader.java#L66-L90
apache/incubator-shardingsphere
sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/ShardingAlgorithmFactory.java
ShardingAlgorithmFactory.newInstance
@SneakyThrows @SuppressWarnings("unchecked") public static <T extends ShardingAlgorithm> T newInstance(final String shardingAlgorithmClassName, final Class<T> superShardingAlgorithmClass) { """ Create sharding algorithm. @param shardingAlgorithmClassName sharding algorithm class name @param superShardingAlgorithmClass sharding algorithm super class @param <T> class generic type @return sharding algorithm instance """ Class<?> result = Class.forName(shardingAlgorithmClassName); if (!superShardingAlgorithmClass.isAssignableFrom(result)) { throw new ShardingException("Class %s should be implement %s", shardingAlgorithmClassName, superShardingAlgorithmClass.getName()); } return (T) result.newInstance(); }
java
@SneakyThrows @SuppressWarnings("unchecked") public static <T extends ShardingAlgorithm> T newInstance(final String shardingAlgorithmClassName, final Class<T> superShardingAlgorithmClass) { Class<?> result = Class.forName(shardingAlgorithmClassName); if (!superShardingAlgorithmClass.isAssignableFrom(result)) { throw new ShardingException("Class %s should be implement %s", shardingAlgorithmClassName, superShardingAlgorithmClass.getName()); } return (T) result.newInstance(); }
[ "@", "SneakyThrows", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "ShardingAlgorithm", ">", "T", "newInstance", "(", "final", "String", "shardingAlgorithmClassName", ",", "final", "Class", "<", "T", ">", "superShardingAlgorithmClass", ")", "{", "Class", "<", "?", ">", "result", "=", "Class", ".", "forName", "(", "shardingAlgorithmClassName", ")", ";", "if", "(", "!", "superShardingAlgorithmClass", ".", "isAssignableFrom", "(", "result", ")", ")", "{", "throw", "new", "ShardingException", "(", "\"Class %s should be implement %s\"", ",", "shardingAlgorithmClassName", ",", "superShardingAlgorithmClass", ".", "getName", "(", ")", ")", ";", "}", "return", "(", "T", ")", "result", ".", "newInstance", "(", ")", ";", "}" ]
Create sharding algorithm. @param shardingAlgorithmClassName sharding algorithm class name @param superShardingAlgorithmClass sharding algorithm super class @param <T> class generic type @return sharding algorithm instance
[ "Create", "sharding", "algorithm", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/ShardingAlgorithmFactory.java#L42-L50
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/join/CompositeInputFormat.java
CompositeInputFormat.compose
public static String compose(Class<? extends InputFormat> inf, String path) { """ Convenience method for constructing composite formats. Given InputFormat class (inf), path (p) return: {@code tbl(<inf>, <p>) } """ return compose(inf.getName().intern(), path, new StringBuffer()).toString(); }
java
public static String compose(Class<? extends InputFormat> inf, String path) { return compose(inf.getName().intern(), path, new StringBuffer()).toString(); }
[ "public", "static", "String", "compose", "(", "Class", "<", "?", "extends", "InputFormat", ">", "inf", ",", "String", "path", ")", "{", "return", "compose", "(", "inf", ".", "getName", "(", ")", ".", "intern", "(", ")", ",", "path", ",", "new", "StringBuffer", "(", ")", ")", ".", "toString", "(", ")", ";", "}" ]
Convenience method for constructing composite formats. Given InputFormat class (inf), path (p) return: {@code tbl(<inf>, <p>) }
[ "Convenience", "method", "for", "constructing", "composite", "formats", ".", "Given", "InputFormat", "class", "(", "inf", ")", "path", "(", "p", ")", "return", ":", "{" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/join/CompositeInputFormat.java#L138-L140
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java
FileSystemUtil.getTableName
@Nullable public static String getTableName(Path rootPath, Path path) { """ Gets the table name from a path, or null if the path is the root path. """ path = qualified(rootPath, path); if (rootPath.equals(path)) { // Path is root, no table return null; } Path tablePath; Path parent = path.getParent(); if (Objects.equals(parent, rootPath)) { // The path itself represents a table (e.g.; emodb://ci.us/mytable) tablePath = path; } else if (parent != null && Objects.equals(parent.getParent(), rootPath)) { // The path is a split (e.g.; emodb://ci.us/mytable/split-id) tablePath = parent; } else { throw new IllegalArgumentException( format("Path does not represent a table, split, or root (path=%s, root=%s)", path, rootPath)); } return decode(tablePath.getName()); }
java
@Nullable public static String getTableName(Path rootPath, Path path) { path = qualified(rootPath, path); if (rootPath.equals(path)) { // Path is root, no table return null; } Path tablePath; Path parent = path.getParent(); if (Objects.equals(parent, rootPath)) { // The path itself represents a table (e.g.; emodb://ci.us/mytable) tablePath = path; } else if (parent != null && Objects.equals(parent.getParent(), rootPath)) { // The path is a split (e.g.; emodb://ci.us/mytable/split-id) tablePath = parent; } else { throw new IllegalArgumentException( format("Path does not represent a table, split, or root (path=%s, root=%s)", path, rootPath)); } return decode(tablePath.getName()); }
[ "@", "Nullable", "public", "static", "String", "getTableName", "(", "Path", "rootPath", ",", "Path", "path", ")", "{", "path", "=", "qualified", "(", "rootPath", ",", "path", ")", ";", "if", "(", "rootPath", ".", "equals", "(", "path", ")", ")", "{", "// Path is root, no table", "return", "null", ";", "}", "Path", "tablePath", ";", "Path", "parent", "=", "path", ".", "getParent", "(", ")", ";", "if", "(", "Objects", ".", "equals", "(", "parent", ",", "rootPath", ")", ")", "{", "// The path itself represents a table (e.g.; emodb://ci.us/mytable)", "tablePath", "=", "path", ";", "}", "else", "if", "(", "parent", "!=", "null", "&&", "Objects", ".", "equals", "(", "parent", ".", "getParent", "(", ")", ",", "rootPath", ")", ")", "{", "// The path is a split (e.g.; emodb://ci.us/mytable/split-id)", "tablePath", "=", "parent", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "format", "(", "\"Path does not represent a table, split, or root (path=%s, root=%s)\"", ",", "path", ",", "rootPath", ")", ")", ";", "}", "return", "decode", "(", "tablePath", ".", "getName", "(", ")", ")", ";", "}" ]
Gets the table name from a path, or null if the path is the root path.
[ "Gets", "the", "table", "name", "from", "a", "path", "or", "null", "if", "the", "path", "is", "the", "root", "path", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L63-L84
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/VersionsImpl.java
VersionsImpl.deleteUnlabelledUtteranceAsync
public Observable<OperationStatus> deleteUnlabelledUtteranceAsync(UUID appId, String versionId, String utterance) { """ Deleted an unlabelled utterance. @param appId The application ID. @param versionId The version ID. @param utterance The utterance text to delete. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object """ return deleteUnlabelledUtteranceWithServiceResponseAsync(appId, versionId, utterance).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> deleteUnlabelledUtteranceAsync(UUID appId, String versionId, String utterance) { return deleteUnlabelledUtteranceWithServiceResponseAsync(appId, versionId, utterance).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "deleteUnlabelledUtteranceAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "String", "utterance", ")", "{", "return", "deleteUnlabelledUtteranceWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "utterance", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatus", ">", ",", "OperationStatus", ">", "(", ")", "{", "@", "Override", "public", "OperationStatus", "call", "(", "ServiceResponse", "<", "OperationStatus", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deleted an unlabelled utterance. @param appId The application ID. @param versionId The version ID. @param utterance The utterance text to delete. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Deleted", "an", "unlabelled", "utterance", "." ]
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/VersionsImpl.java#L1071-L1078
atomix/atomix
protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java
CrdtSetDelegate.updateElements
private void updateElements(Map<String, SetElement> elements) { """ Updates the set elements. @param elements the elements to update """ for (SetElement element : elements.values()) { if (element.isTombstone()) { if (remove(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.REMOVE, decode(element.value())))); } } else { if (add(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.ADD, decode(element.value())))); } } } }
java
private void updateElements(Map<String, SetElement> elements) { for (SetElement element : elements.values()) { if (element.isTombstone()) { if (remove(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.REMOVE, decode(element.value())))); } } else { if (add(element)) { eventListeners.forEach(listener -> listener.event(new SetDelegateEvent<>(SetDelegateEvent.Type.ADD, decode(element.value())))); } } } }
[ "private", "void", "updateElements", "(", "Map", "<", "String", ",", "SetElement", ">", "elements", ")", "{", "for", "(", "SetElement", "element", ":", "elements", ".", "values", "(", ")", ")", "{", "if", "(", "element", ".", "isTombstone", "(", ")", ")", "{", "if", "(", "remove", "(", "element", ")", ")", "{", "eventListeners", ".", "forEach", "(", "listener", "->", "listener", ".", "event", "(", "new", "SetDelegateEvent", "<>", "(", "SetDelegateEvent", ".", "Type", ".", "REMOVE", ",", "decode", "(", "element", ".", "value", "(", ")", ")", ")", ")", ")", ";", "}", "}", "else", "{", "if", "(", "add", "(", "element", ")", ")", "{", "eventListeners", ".", "forEach", "(", "listener", "->", "listener", ".", "event", "(", "new", "SetDelegateEvent", "<>", "(", "SetDelegateEvent", ".", "Type", ".", "ADD", ",", "decode", "(", "element", ".", "value", "(", ")", ")", ")", ")", ")", ";", "}", "}", "}", "}" ]
Updates the set elements. @param elements the elements to update
[ "Updates", "the", "set", "elements", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/set/CrdtSetDelegate.java#L226-L238
apache/incubator-shardingsphere
sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/sql/statement/tcl/TCLStatement.java
TCLStatement.isTCLUnsafe
public static boolean isTCLUnsafe(final DatabaseType databaseType, final TokenType tokenType, final LexerEngine lexerEngine) { """ Is TCL statement. @param databaseType database type @param tokenType token type @param lexerEngine lexer engine @return is TCL or not """ if (DefaultKeyword.SET.equals(tokenType) || DatabaseType.SQLServer.equals(databaseType) && DefaultKeyword.IF.equals(tokenType)) { lexerEngine.skipUntil(DefaultKeyword.TRANSACTION, DefaultKeyword.AUTOCOMMIT, DefaultKeyword.IMPLICIT_TRANSACTIONS); if (!lexerEngine.isEnd()) { return true; } } return false; }
java
public static boolean isTCLUnsafe(final DatabaseType databaseType, final TokenType tokenType, final LexerEngine lexerEngine) { if (DefaultKeyword.SET.equals(tokenType) || DatabaseType.SQLServer.equals(databaseType) && DefaultKeyword.IF.equals(tokenType)) { lexerEngine.skipUntil(DefaultKeyword.TRANSACTION, DefaultKeyword.AUTOCOMMIT, DefaultKeyword.IMPLICIT_TRANSACTIONS); if (!lexerEngine.isEnd()) { return true; } } return false; }
[ "public", "static", "boolean", "isTCLUnsafe", "(", "final", "DatabaseType", "databaseType", ",", "final", "TokenType", "tokenType", ",", "final", "LexerEngine", "lexerEngine", ")", "{", "if", "(", "DefaultKeyword", ".", "SET", ".", "equals", "(", "tokenType", ")", "||", "DatabaseType", ".", "SQLServer", ".", "equals", "(", "databaseType", ")", "&&", "DefaultKeyword", ".", "IF", ".", "equals", "(", "tokenType", ")", ")", "{", "lexerEngine", ".", "skipUntil", "(", "DefaultKeyword", ".", "TRANSACTION", ",", "DefaultKeyword", ".", "AUTOCOMMIT", ",", "DefaultKeyword", ".", "IMPLICIT_TRANSACTIONS", ")", ";", "if", "(", "!", "lexerEngine", ".", "isEnd", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Is TCL statement. @param databaseType database type @param tokenType token type @param lexerEngine lexer engine @return is TCL or not
[ "Is", "TCL", "statement", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/sql/statement/tcl/TCLStatement.java#L65-L73
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/AppEventsLogger.java
AppEventsLogger.logEvent
public void logEvent(String eventName, Bundle parameters) { """ Log an app event with the specified name and set of parameters. @param eventName eventName used to denote the event. Choose amongst the EVENT_NAME_* constants in {@link AppEventsConstants} when possible. Or create your own if none of the EVENT_NAME_* constants are applicable. Event names should be 40 characters or less, alphanumeric, and can include spaces, underscores or hyphens, but mustn't have a space or hyphen as the first character. Any given app should have no more than ~300 distinct event names. @param parameters A Bundle of parameters to log with the event. Insights will allow looking at the logs of these events via different parameter values. You can log on the order of 10 parameters with each distinct eventName. It's advisable to keep the number of unique values provided for each parameter in the, at most, thousands. As an example, don't attempt to provide a unique parameter value for each unique user in your app. You won't get meaningful aggregate reporting on so many parameter values. The values in the bundles should be Strings or numeric values. """ logEvent(eventName, null, parameters, false); }
java
public void logEvent(String eventName, Bundle parameters) { logEvent(eventName, null, parameters, false); }
[ "public", "void", "logEvent", "(", "String", "eventName", ",", "Bundle", "parameters", ")", "{", "logEvent", "(", "eventName", ",", "null", ",", "parameters", ",", "false", ")", ";", "}" ]
Log an app event with the specified name and set of parameters. @param eventName eventName used to denote the event. Choose amongst the EVENT_NAME_* constants in {@link AppEventsConstants} when possible. Or create your own if none of the EVENT_NAME_* constants are applicable. Event names should be 40 characters or less, alphanumeric, and can include spaces, underscores or hyphens, but mustn't have a space or hyphen as the first character. Any given app should have no more than ~300 distinct event names. @param parameters A Bundle of parameters to log with the event. Insights will allow looking at the logs of these events via different parameter values. You can log on the order of 10 parameters with each distinct eventName. It's advisable to keep the number of unique values provided for each parameter in the, at most, thousands. As an example, don't attempt to provide a unique parameter value for each unique user in your app. You won't get meaningful aggregate reporting on so many parameter values. The values in the bundles should be Strings or numeric values.
[ "Log", "an", "app", "event", "with", "the", "specified", "name", "and", "set", "of", "parameters", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/AppEventsLogger.java#L470-L472
drapostolos/rdp4j
src/main/java/com/github/drapostolos/rdp4j/DirectoryPollerFuture.java
DirectoryPollerFuture.get
public DirectoryPoller get() { """ Retrieves the {@link DirectoryPoller} instance. This method will block until all {@link BeforeStartEvent} events has been fired (and processed by all listeners.) @return a started {@link DirectoryPoller} instance. """ try { return future.get(); } catch (Exception e) { String message = "get() method threw exception!"; throw new UnsupportedOperationException(message, e); } }
java
public DirectoryPoller get() { try { return future.get(); } catch (Exception e) { String message = "get() method threw exception!"; throw new UnsupportedOperationException(message, e); } }
[ "public", "DirectoryPoller", "get", "(", ")", "{", "try", "{", "return", "future", ".", "get", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "message", "=", "\"get() method threw exception!\"", ";", "throw", "new", "UnsupportedOperationException", "(", "message", ",", "e", ")", ";", "}", "}" ]
Retrieves the {@link DirectoryPoller} instance. This method will block until all {@link BeforeStartEvent} events has been fired (and processed by all listeners.) @return a started {@link DirectoryPoller} instance.
[ "Retrieves", "the", "{", "@link", "DirectoryPoller", "}", "instance", ".", "This", "method", "will", "block", "until", "all", "{", "@link", "BeforeStartEvent", "}", "events", "has", "been", "fired", "(", "and", "processed", "by", "all", "listeners", ".", ")" ]
train
https://github.com/drapostolos/rdp4j/blob/ec1db2444d245b7ccd6607182bb56a027fa66d6b/src/main/java/com/github/drapostolos/rdp4j/DirectoryPollerFuture.java#L28-L35
crnk-project/crnk-framework
crnk-gen/crnk-gen-typescript/src/main/java/io/crnk/gen/typescript/internal/TypescriptUtils.java
TypescriptUtils.getNestedTypeContainer
public static TSModule getNestedTypeContainer(TSType type, boolean create) { """ Creates a module if the same name as the provided type used to hold nested types. """ TSContainerElement parent = (TSContainerElement) type.getParent(); if (parent == null) { return null; } int insertionIndex = parent.getElements().indexOf(type); return getModule(parent, type.getName(), insertionIndex, create); }
java
public static TSModule getNestedTypeContainer(TSType type, boolean create) { TSContainerElement parent = (TSContainerElement) type.getParent(); if (parent == null) { return null; } int insertionIndex = parent.getElements().indexOf(type); return getModule(parent, type.getName(), insertionIndex, create); }
[ "public", "static", "TSModule", "getNestedTypeContainer", "(", "TSType", "type", ",", "boolean", "create", ")", "{", "TSContainerElement", "parent", "=", "(", "TSContainerElement", ")", "type", ".", "getParent", "(", ")", ";", "if", "(", "parent", "==", "null", ")", "{", "return", "null", ";", "}", "int", "insertionIndex", "=", "parent", ".", "getElements", "(", ")", ".", "indexOf", "(", "type", ")", ";", "return", "getModule", "(", "parent", ",", "type", ".", "getName", "(", ")", ",", "insertionIndex", ",", "create", ")", ";", "}" ]
Creates a module if the same name as the provided type used to hold nested types.
[ "Creates", "a", "module", "if", "the", "same", "name", "as", "the", "provided", "type", "used", "to", "hold", "nested", "types", "." ]
train
https://github.com/crnk-project/crnk-framework/blob/2fd3ef9a991788d46fd2e83b43c8ea37cbaf8681/crnk-gen/crnk-gen-typescript/src/main/java/io/crnk/gen/typescript/internal/TypescriptUtils.java#L90-L97
languagetool-org/languagetool
languagetool-office-extension/src/main/java/org/languagetool/openoffice/LinguisticServices.java
LinguisticServices.getNumberOfSyllables
@Override public int getNumberOfSyllables(String word, Language lang) { """ Returns the number of syllable of a word Returns -1 if the word was not found or anything goes wrong """ return getNumberOfSyllables(word, getLocale(lang)); }
java
@Override public int getNumberOfSyllables(String word, Language lang) { return getNumberOfSyllables(word, getLocale(lang)); }
[ "@", "Override", "public", "int", "getNumberOfSyllables", "(", "String", "word", ",", "Language", "lang", ")", "{", "return", "getNumberOfSyllables", "(", "word", ",", "getLocale", "(", "lang", ")", ")", ";", "}" ]
Returns the number of syllable of a word Returns -1 if the word was not found or anything goes wrong
[ "Returns", "the", "number", "of", "syllable", "of", "a", "word", "Returns", "-", "1", "if", "the", "word", "was", "not", "found", "or", "anything", "goes", "wrong" ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-office-extension/src/main/java/org/languagetool/openoffice/LinguisticServices.java#L222-L225
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/PropertiesField.java
PropertiesField.setProperty
public void setProperty(String strProperty, String strValue) { """ Set this property in the user's property area. @param strProperty The property key. @param strValue The property value. """ this.setProperty(strProperty, strValue, DBConstants.DISPLAY, DBConstants.SCREEN_MOVE); }
java
public void setProperty(String strProperty, String strValue) { this.setProperty(strProperty, strValue, DBConstants.DISPLAY, DBConstants.SCREEN_MOVE); }
[ "public", "void", "setProperty", "(", "String", "strProperty", ",", "String", "strValue", ")", "{", "this", ".", "setProperty", "(", "strProperty", ",", "strValue", ",", "DBConstants", ".", "DISPLAY", ",", "DBConstants", ".", "SCREEN_MOVE", ")", ";", "}" ]
Set this property in the user's property area. @param strProperty The property key. @param strValue The property value.
[ "Set", "this", "property", "in", "the", "user", "s", "property", "area", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/PropertiesField.java#L128-L131
LMAX-Exchange/disruptor
src/main/java/com/lmax/disruptor/RingBuffer.java
RingBuffer.createMultiProducer
public static <E> RingBuffer<E> createMultiProducer(EventFactory<E> factory, int bufferSize) { """ Create a new multiple producer RingBuffer using the default wait strategy {@link BlockingWaitStrategy}. @param <E> Class of the event stored in the ring buffer. @param factory used to create the events within the ring buffer. @param bufferSize number of elements to create within the ring buffer. @return a constructed ring buffer. @throws IllegalArgumentException if <code>bufferSize</code> is less than 1 or not a power of 2 @see MultiProducerSequencer """ return createMultiProducer(factory, bufferSize, new BlockingWaitStrategy()); }
java
public static <E> RingBuffer<E> createMultiProducer(EventFactory<E> factory, int bufferSize) { return createMultiProducer(factory, bufferSize, new BlockingWaitStrategy()); }
[ "public", "static", "<", "E", ">", "RingBuffer", "<", "E", ">", "createMultiProducer", "(", "EventFactory", "<", "E", ">", "factory", ",", "int", "bufferSize", ")", "{", "return", "createMultiProducer", "(", "factory", ",", "bufferSize", ",", "new", "BlockingWaitStrategy", "(", ")", ")", ";", "}" ]
Create a new multiple producer RingBuffer using the default wait strategy {@link BlockingWaitStrategy}. @param <E> Class of the event stored in the ring buffer. @param factory used to create the events within the ring buffer. @param bufferSize number of elements to create within the ring buffer. @return a constructed ring buffer. @throws IllegalArgumentException if <code>bufferSize</code> is less than 1 or not a power of 2 @see MultiProducerSequencer
[ "Create", "a", "new", "multiple", "producer", "RingBuffer", "using", "the", "default", "wait", "strategy", "{", "@link", "BlockingWaitStrategy", "}", "." ]
train
https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/RingBuffer.java#L153-L156
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/isomorphism/mcss/RGraph.java
RGraph.isContainedIn
private boolean isContainedIn(BitSet A, BitSet B) { """ Test if set A is contained in set B. @param A a bitSet @param B a bitSet @return true if A is contained in B """ boolean result = false; if (A.isEmpty()) { return true; } BitSet setA = (BitSet) A.clone(); setA.and(B); if (setA.equals(A)) { result = true; } return result; }
java
private boolean isContainedIn(BitSet A, BitSet B) { boolean result = false; if (A.isEmpty()) { return true; } BitSet setA = (BitSet) A.clone(); setA.and(B); if (setA.equals(A)) { result = true; } return result; }
[ "private", "boolean", "isContainedIn", "(", "BitSet", "A", ",", "BitSet", "B", ")", "{", "boolean", "result", "=", "false", ";", "if", "(", "A", ".", "isEmpty", "(", ")", ")", "{", "return", "true", ";", "}", "BitSet", "setA", "=", "(", "BitSet", ")", "A", ".", "clone", "(", ")", ";", "setA", ".", "and", "(", "B", ")", ";", "if", "(", "setA", ".", "equals", "(", "A", ")", ")", "{", "result", "=", "true", ";", "}", "return", "result", ";", "}" ]
Test if set A is contained in set B. @param A a bitSet @param B a bitSet @return true if A is contained in B
[ "Test", "if", "set", "A", "is", "contained", "in", "set", "B", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/isomorphism/mcss/RGraph.java#L559-L574
walkmod/walkmod-core
src/main/java/org/walkmod/util/location/LocationAttributes.java
LocationAttributes.getLocation
public static Location getLocation(Attributes attrs, String description) { """ Returns the {@link Location} of an element (SAX flavor). @param attrs the element's attributes that hold the location information @param description a description for the location (can be null) @return a {@link Location} object """ String src = attrs.getValue(URI, SRC_ATTR); if (src == null) { return LocationImpl.UNKNOWN; } return new LocationImpl(description, src, getLine(attrs), getColumn(attrs)); }
java
public static Location getLocation(Attributes attrs, String description) { String src = attrs.getValue(URI, SRC_ATTR); if (src == null) { return LocationImpl.UNKNOWN; } return new LocationImpl(description, src, getLine(attrs), getColumn(attrs)); }
[ "public", "static", "Location", "getLocation", "(", "Attributes", "attrs", ",", "String", "description", ")", "{", "String", "src", "=", "attrs", ".", "getValue", "(", "URI", ",", "SRC_ATTR", ")", ";", "if", "(", "src", "==", "null", ")", "{", "return", "LocationImpl", ".", "UNKNOWN", ";", "}", "return", "new", "LocationImpl", "(", "description", ",", "src", ",", "getLine", "(", "attrs", ")", ",", "getColumn", "(", "attrs", ")", ")", ";", "}" ]
Returns the {@link Location} of an element (SAX flavor). @param attrs the element's attributes that hold the location information @param description a description for the location (can be null) @return a {@link Location} object
[ "Returns", "the", "{", "@link", "Location", "}", "of", "an", "element", "(", "SAX", "flavor", ")", "." ]
train
https://github.com/walkmod/walkmod-core/blob/fa79b836894fa00ca4b3e2bd26326a44b778f46f/src/main/java/org/walkmod/util/location/LocationAttributes.java#L85-L91
alkacon/opencms-core
src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java
CmsEditablePositionCalculator.handleCollision
protected void handleCollision(CmsPositionBean p1, CmsPositionBean p2) { """ Handles a collision by moving the lower position down.<p> @param p1 the first position @param p2 the second position """ CmsPositionBean positionToChange = p1; if (p1.getTop() <= p2.getTop()) { positionToChange = p2; } positionToChange.setTop(positionToChange.getTop() + 25); }
java
protected void handleCollision(CmsPositionBean p1, CmsPositionBean p2) { CmsPositionBean positionToChange = p1; if (p1.getTop() <= p2.getTop()) { positionToChange = p2; } positionToChange.setTop(positionToChange.getTop() + 25); }
[ "protected", "void", "handleCollision", "(", "CmsPositionBean", "p1", ",", "CmsPositionBean", "p2", ")", "{", "CmsPositionBean", "positionToChange", "=", "p1", ";", "if", "(", "p1", ".", "getTop", "(", ")", "<=", "p2", ".", "getTop", "(", ")", ")", "{", "positionToChange", "=", "p2", ";", "}", "positionToChange", ".", "setTop", "(", "positionToChange", ".", "getTop", "(", ")", "+", "25", ")", ";", "}" ]
Handles a collision by moving the lower position down.<p> @param p1 the first position @param p2 the second position
[ "Handles", "a", "collision", "by", "moving", "the", "lower", "position", "down", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java#L140-L147
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/sockets/SocketFactory.java
SocketFactory.createSocket
SocketInterface createSocket(@NonNull final String token, @NonNull final WeakReference<SocketStateListener> stateListenerWeakReference) { """ Creates and configures web socket instance. @param token Authentication token. @param stateListenerWeakReference Weak reference to socket connection state callbacks. """ WebSocket socket = null; WebSocketFactory factory = new WebSocketFactory(); // Configure proxy if provided if (proxyAddress != null) { ProxySettings settings = factory.getProxySettings(); settings.setServer(proxyAddress); } try { socket = factory.createSocket(uri, TIMEOUT); } catch (IOException e) { log.f("Creating socket failed", e); } if (socket != null) { String header = AuthManager.AUTH_PREFIX + token; socket.addHeader("Authorization", header); socket.addListener(createWebSocketAdapter(stateListenerWeakReference)); socket.setPingInterval(PING_INTERVAL); return new SocketWrapperImpl(socket); } return null; }
java
SocketInterface createSocket(@NonNull final String token, @NonNull final WeakReference<SocketStateListener> stateListenerWeakReference) { WebSocket socket = null; WebSocketFactory factory = new WebSocketFactory(); // Configure proxy if provided if (proxyAddress != null) { ProxySettings settings = factory.getProxySettings(); settings.setServer(proxyAddress); } try { socket = factory.createSocket(uri, TIMEOUT); } catch (IOException e) { log.f("Creating socket failed", e); } if (socket != null) { String header = AuthManager.AUTH_PREFIX + token; socket.addHeader("Authorization", header); socket.addListener(createWebSocketAdapter(stateListenerWeakReference)); socket.setPingInterval(PING_INTERVAL); return new SocketWrapperImpl(socket); } return null; }
[ "SocketInterface", "createSocket", "(", "@", "NonNull", "final", "String", "token", ",", "@", "NonNull", "final", "WeakReference", "<", "SocketStateListener", ">", "stateListenerWeakReference", ")", "{", "WebSocket", "socket", "=", "null", ";", "WebSocketFactory", "factory", "=", "new", "WebSocketFactory", "(", ")", ";", "// Configure proxy if provided", "if", "(", "proxyAddress", "!=", "null", ")", "{", "ProxySettings", "settings", "=", "factory", ".", "getProxySettings", "(", ")", ";", "settings", ".", "setServer", "(", "proxyAddress", ")", ";", "}", "try", "{", "socket", "=", "factory", ".", "createSocket", "(", "uri", ",", "TIMEOUT", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "log", ".", "f", "(", "\"Creating socket failed\"", ",", "e", ")", ";", "}", "if", "(", "socket", "!=", "null", ")", "{", "String", "header", "=", "AuthManager", ".", "AUTH_PREFIX", "+", "token", ";", "socket", ".", "addHeader", "(", "\"Authorization\"", ",", "header", ")", ";", "socket", ".", "addListener", "(", "createWebSocketAdapter", "(", "stateListenerWeakReference", ")", ")", ";", "socket", ".", "setPingInterval", "(", "PING_INTERVAL", ")", ";", "return", "new", "SocketWrapperImpl", "(", "socket", ")", ";", "}", "return", "null", ";", "}" ]
Creates and configures web socket instance. @param token Authentication token. @param stateListenerWeakReference Weak reference to socket connection state callbacks.
[ "Creates", "and", "configures", "web", "socket", "instance", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/sockets/SocketFactory.java#L97-L128
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPlot.java
SVGPlot.svgElement
public Element svgElement(String name, String cssclass) { """ Create a SVG element in the SVG namespace. Non-static version. @param name node name @param cssclass CSS class @return new SVG element. """ Element elem = SVGUtil.svgElement(document, name); if(cssclass != null) { elem.setAttribute(SVGConstants.SVG_CLASS_ATTRIBUTE, cssclass); } return elem; }
java
public Element svgElement(String name, String cssclass) { Element elem = SVGUtil.svgElement(document, name); if(cssclass != null) { elem.setAttribute(SVGConstants.SVG_CLASS_ATTRIBUTE, cssclass); } return elem; }
[ "public", "Element", "svgElement", "(", "String", "name", ",", "String", "cssclass", ")", "{", "Element", "elem", "=", "SVGUtil", ".", "svgElement", "(", "document", ",", "name", ")", ";", "if", "(", "cssclass", "!=", "null", ")", "{", "elem", ".", "setAttribute", "(", "SVGConstants", ".", "SVG_CLASS_ATTRIBUTE", ",", "cssclass", ")", ";", "}", "return", "elem", ";", "}" ]
Create a SVG element in the SVG namespace. Non-static version. @param name node name @param cssclass CSS class @return new SVG element.
[ "Create", "a", "SVG", "element", "in", "the", "SVG", "namespace", ".", "Non", "-", "static", "version", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPlot.java#L237-L243
carewebframework/carewebframework-vista
org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Request.java
Request.addParameter
public void addParameter(String name, Object value) { """ Adds a parameter to the request. @param name Parameter name (optionally with subscripts). @param value Parameter value. """ String subscript = ""; if (name.contains("(")) { String[] pcs = name.split("\\(", 2); name = pcs[0]; subscript = pcs[1]; if (subscript.endsWith(")")) { subscript = subscript.substring(0, subscript.length() - 1); } } addParameter(name, subscript, value); }
java
public void addParameter(String name, Object value) { String subscript = ""; if (name.contains("(")) { String[] pcs = name.split("\\(", 2); name = pcs[0]; subscript = pcs[1]; if (subscript.endsWith(")")) { subscript = subscript.substring(0, subscript.length() - 1); } } addParameter(name, subscript, value); }
[ "public", "void", "addParameter", "(", "String", "name", ",", "Object", "value", ")", "{", "String", "subscript", "=", "\"\"", ";", "if", "(", "name", ".", "contains", "(", "\"(\"", ")", ")", "{", "String", "[", "]", "pcs", "=", "name", ".", "split", "(", "\"\\\\(\"", ",", "2", ")", ";", "name", "=", "pcs", "[", "0", "]", ";", "subscript", "=", "pcs", "[", "1", "]", ";", "if", "(", "subscript", ".", "endsWith", "(", "\")\"", ")", ")", "{", "subscript", "=", "subscript", ".", "substring", "(", "0", ",", "subscript", ".", "length", "(", ")", "-", "1", ")", ";", "}", "}", "addParameter", "(", "name", ",", "subscript", ",", "value", ")", ";", "}" ]
Adds a parameter to the request. @param name Parameter name (optionally with subscripts). @param value Parameter value.
[ "Adds", "a", "parameter", "to", "the", "request", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Request.java#L178-L192
BigBadaboom/androidsvg
androidsvg/src/main/java/com/caverock/androidsvg/SVG.java
SVG.getFromResource
@SuppressWarnings("WeakerAccess") public static SVG getFromResource(Resources resources, int resourceId) throws SVGParseException { """ Read and parse an SVG from the given resource location. @param resources the set of Resources in which to locate the file. @param resourceId the resource identifier of the SVG document. @return an SVG instance on which you can call one of the render methods. @throws SVGParseException if there is an error parsing the document. @since 1.2.1 """ SVGParser parser = new SVGParser(); InputStream is = resources.openRawResource(resourceId); try { return parser.parse(is, enableInternalEntities); } finally { try { is.close(); } catch (IOException e) { // Do nothing } } }
java
@SuppressWarnings("WeakerAccess") public static SVG getFromResource(Resources resources, int resourceId) throws SVGParseException { SVGParser parser = new SVGParser(); InputStream is = resources.openRawResource(resourceId); try { return parser.parse(is, enableInternalEntities); } finally { try { is.close(); } catch (IOException e) { // Do nothing } } }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "static", "SVG", "getFromResource", "(", "Resources", "resources", ",", "int", "resourceId", ")", "throws", "SVGParseException", "{", "SVGParser", "parser", "=", "new", "SVGParser", "(", ")", ";", "InputStream", "is", "=", "resources", ".", "openRawResource", "(", "resourceId", ")", ";", "try", "{", "return", "parser", ".", "parse", "(", "is", ",", "enableInternalEntities", ")", ";", "}", "finally", "{", "try", "{", "is", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Do nothing\r", "}", "}", "}" ]
Read and parse an SVG from the given resource location. @param resources the set of Resources in which to locate the file. @param resourceId the resource identifier of the SVG document. @return an SVG instance on which you can call one of the render methods. @throws SVGParseException if there is an error parsing the document. @since 1.2.1
[ "Read", "and", "parse", "an", "SVG", "from", "the", "given", "resource", "location", "." ]
train
https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SVG.java#L193-L207