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
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/markup/AnnotatedTextBuilder.java
AnnotatedTextBuilder.addGlobalMetaData
public AnnotatedTextBuilder addGlobalMetaData(String key, String value) { """ Add any global meta data about the document to be checked. Some rules may use this information. Unless you're using your own rules for which you know useful keys, you probably want to use {@link #addGlobalMetaData(AnnotatedText.MetaDataKey, String)}. @since 3.9 """ customMetaData.put(key, value); return this; }
java
public AnnotatedTextBuilder addGlobalMetaData(String key, String value) { customMetaData.put(key, value); return this; }
[ "public", "AnnotatedTextBuilder", "addGlobalMetaData", "(", "String", "key", ",", "String", "value", ")", "{", "customMetaData", ".", "put", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Add any global meta data about the document to be checked. Some rules may use this information. Unless you're using your own rules for which you know useful keys, you probably want to use {@link #addGlobalMetaData(AnnotatedText.MetaDataKey, String)}. @since 3.9
[ "Add", "any", "global", "meta", "data", "about", "the", "document", "to", "be", "checked", ".", "Some", "rules", "may", "use", "this", "information", ".", "Unless", "you", "re", "using", "your", "own", "rules", "for", "which", "you", "know", "useful", "keys", "you", "probably", "want", "to", "use", "{" ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/markup/AnnotatedTextBuilder.java#L75-L78
nakamura5akihito/six-util
src/main/java/jp/go/aist/six/util/search/RelationalBinding.java
RelationalBinding.equalBinding
public static RelationalBinding equalBinding( final String property, final Object value ) { """ Creates an 'EQUAL' binding. @param property the property. @param value the value to which the property should be related. @return an 'EQUAL' binding. """ return (new RelationalBinding( property, Relation.EQUAL, value )); }
java
public static RelationalBinding equalBinding( final String property, final Object value ) { return (new RelationalBinding( property, Relation.EQUAL, value )); }
[ "public", "static", "RelationalBinding", "equalBinding", "(", "final", "String", "property", ",", "final", "Object", "value", ")", "{", "return", "(", "new", "RelationalBinding", "(", "property", ",", "Relation", ".", "EQUAL", ",", "value", ")", ")", ";", "}" ]
Creates an 'EQUAL' binding. @param property the property. @param value the value to which the property should be related. @return an 'EQUAL' binding.
[ "Creates", "an", "EQUAL", "binding", "." ]
train
https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/search/RelationalBinding.java#L50-L56
sagiegurari/fax4j
src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java
HylaFaxClientSpi.suspendFaxJobImpl
@Override protected void suspendFaxJobImpl(FaxJob faxJob) { """ This function will suspend an existing fax job. @param faxJob The fax job object containing the needed information """ //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.suspendFaxJob(hylaFaxJob,client); } catch(FaxException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } }
java
@Override protected void suspendFaxJobImpl(FaxJob faxJob) { //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.suspendFaxJob(hylaFaxJob,client); } catch(FaxException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } }
[ "@", "Override", "protected", "void", "suspendFaxJobImpl", "(", "FaxJob", "faxJob", ")", "{", "//get fax job", "HylaFaxJob", "hylaFaxJob", "=", "(", "HylaFaxJob", ")", "faxJob", ";", "//get client", "HylaFAXClient", "client", "=", "this", ".", "getHylaFAXClient", "(", ")", ";", "try", "{", "this", ".", "suspendFaxJob", "(", "hylaFaxJob", ",", "client", ")", ";", "}", "catch", "(", "FaxException", "exception", ")", "{", "throw", "exception", ";", "}", "catch", "(", "Exception", "exception", ")", "{", "throw", "new", "FaxException", "(", "\"General error.\"", ",", "exception", ")", ";", "}", "}" ]
This function will suspend an existing fax job. @param faxJob The fax job object containing the needed information
[ "This", "function", "will", "suspend", "an", "existing", "fax", "job", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java#L334-L355
samskivert/samskivert
src/main/java/com/samskivert/util/QuickSort.java
QuickSort.rsort
public static <T> void rsort (List<T> a, Comparator<? super T> comp) { """ Sort the elements in the specified List according to the reverse ordering imposed by the specified Comparator. """ sort(a, Collections.reverseOrder(comp)); }
java
public static <T> void rsort (List<T> a, Comparator<? super T> comp) { sort(a, Collections.reverseOrder(comp)); }
[ "public", "static", "<", "T", ">", "void", "rsort", "(", "List", "<", "T", ">", "a", ",", "Comparator", "<", "?", "super", "T", ">", "comp", ")", "{", "sort", "(", "a", ",", "Collections", ".", "reverseOrder", "(", "comp", ")", ")", ";", "}" ]
Sort the elements in the specified List according to the reverse ordering imposed by the specified Comparator.
[ "Sort", "the", "elements", "in", "the", "specified", "List", "according", "to", "the", "reverse", "ordering", "imposed", "by", "the", "specified", "Comparator", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/QuickSort.java#L354-L357
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.createFormatter
private TypeSpec createFormatter(DateTimeData dateTimeData, TimeZoneData timeZoneData, String className) { """ Create a Java class that captures all data formats for a given locale. """ LocaleID id = dateTimeData.id; MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC); constructor.addStatement("this.bundleId = $T.$L", CLDR_LOCALE_IF, id.safe); constructor.addStatement("this.firstDay = $L", dateTimeData.firstDay); constructor.addStatement("this.minDays = $L", dateTimeData.minDays); variantsFieldInit(constructor, "this.eras", dateTimeData.eras); variantsFieldInit(constructor, "this.quartersFormat", dateTimeData.quartersFormat); variantsFieldInit(constructor, "this.quartersStandalone", dateTimeData.quartersStandalone); variantsFieldInit(constructor, "this.monthsFormat", dateTimeData.monthsFormat); variantsFieldInit(constructor, "this.monthsStandalone", dateTimeData.monthsStandalone); variantsFieldInit(constructor, "this.weekdaysFormat", dateTimeData.weekdaysFormat); variantsFieldInit(constructor, "this.weekdaysStandalone", dateTimeData.weekdaysStandalone); variantsFieldInit(constructor, "this.dayPeriodsFormat", dateTimeData.dayPeriodsFormat); variantsFieldInit(constructor, "this.dayPeriodsStandalone", dateTimeData.dayPeriodsStandalone); buildTimeZoneExemplarCities(constructor, timeZoneData); buildTimeZoneNames(constructor, timeZoneData); buildMetaZoneNames(constructor, timeZoneData); TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(CALENDAR_FORMATTER) .addModifiers(PUBLIC) .addJavadoc( "Locale \"" + dateTimeData.id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n") .addMethod(constructor.build()); MethodSpec dateMethod = buildTypedPatternMethod("formatDate", CALENDAR_FORMAT, dateTimeData.dateFormats); MethodSpec timeMethod = buildTypedPatternMethod("formatTime", CALENDAR_FORMAT, dateTimeData.timeFormats); MethodSpec wrapperMethod = buildWrapperMethod(dateTimeData.dateTimeFormats); MethodSpec skeletonMethod = buildSkeletonFormatter(dateTimeData.dateTimeSkeletons); MethodSpec intervalMethod = buildIntervalMethod(dateTimeData.intervalFormats, dateTimeData.intervalFallbackFormat); MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod(timeZoneData); MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod(timeZoneData); return type .addMethod(dateMethod) .addMethod(timeMethod) .addMethod(wrapperMethod) .addMethod(skeletonMethod) .addMethod(intervalMethod) .addMethod(gmtMethod) .addMethod(regionFormatMethod) .build(); }
java
private TypeSpec createFormatter(DateTimeData dateTimeData, TimeZoneData timeZoneData, String className) { LocaleID id = dateTimeData.id; MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC); constructor.addStatement("this.bundleId = $T.$L", CLDR_LOCALE_IF, id.safe); constructor.addStatement("this.firstDay = $L", dateTimeData.firstDay); constructor.addStatement("this.minDays = $L", dateTimeData.minDays); variantsFieldInit(constructor, "this.eras", dateTimeData.eras); variantsFieldInit(constructor, "this.quartersFormat", dateTimeData.quartersFormat); variantsFieldInit(constructor, "this.quartersStandalone", dateTimeData.quartersStandalone); variantsFieldInit(constructor, "this.monthsFormat", dateTimeData.monthsFormat); variantsFieldInit(constructor, "this.monthsStandalone", dateTimeData.monthsStandalone); variantsFieldInit(constructor, "this.weekdaysFormat", dateTimeData.weekdaysFormat); variantsFieldInit(constructor, "this.weekdaysStandalone", dateTimeData.weekdaysStandalone); variantsFieldInit(constructor, "this.dayPeriodsFormat", dateTimeData.dayPeriodsFormat); variantsFieldInit(constructor, "this.dayPeriodsStandalone", dateTimeData.dayPeriodsStandalone); buildTimeZoneExemplarCities(constructor, timeZoneData); buildTimeZoneNames(constructor, timeZoneData); buildMetaZoneNames(constructor, timeZoneData); TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(CALENDAR_FORMATTER) .addModifiers(PUBLIC) .addJavadoc( "Locale \"" + dateTimeData.id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n") .addMethod(constructor.build()); MethodSpec dateMethod = buildTypedPatternMethod("formatDate", CALENDAR_FORMAT, dateTimeData.dateFormats); MethodSpec timeMethod = buildTypedPatternMethod("formatTime", CALENDAR_FORMAT, dateTimeData.timeFormats); MethodSpec wrapperMethod = buildWrapperMethod(dateTimeData.dateTimeFormats); MethodSpec skeletonMethod = buildSkeletonFormatter(dateTimeData.dateTimeSkeletons); MethodSpec intervalMethod = buildIntervalMethod(dateTimeData.intervalFormats, dateTimeData.intervalFallbackFormat); MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod(timeZoneData); MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod(timeZoneData); return type .addMethod(dateMethod) .addMethod(timeMethod) .addMethod(wrapperMethod) .addMethod(skeletonMethod) .addMethod(intervalMethod) .addMethod(gmtMethod) .addMethod(regionFormatMethod) .build(); }
[ "private", "TypeSpec", "createFormatter", "(", "DateTimeData", "dateTimeData", ",", "TimeZoneData", "timeZoneData", ",", "String", "className", ")", "{", "LocaleID", "id", "=", "dateTimeData", ".", "id", ";", "MethodSpec", ".", "Builder", "constructor", "=", "MethodSpec", ".", "constructorBuilder", "(", ")", ".", "addModifiers", "(", "PUBLIC", ")", ";", "constructor", ".", "addStatement", "(", "\"this.bundleId = $T.$L\"", ",", "CLDR_LOCALE_IF", ",", "id", ".", "safe", ")", ";", "constructor", ".", "addStatement", "(", "\"this.firstDay = $L\"", ",", "dateTimeData", ".", "firstDay", ")", ";", "constructor", ".", "addStatement", "(", "\"this.minDays = $L\"", ",", "dateTimeData", ".", "minDays", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.eras\"", ",", "dateTimeData", ".", "eras", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.quartersFormat\"", ",", "dateTimeData", ".", "quartersFormat", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.quartersStandalone\"", ",", "dateTimeData", ".", "quartersStandalone", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.monthsFormat\"", ",", "dateTimeData", ".", "monthsFormat", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.monthsStandalone\"", ",", "dateTimeData", ".", "monthsStandalone", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.weekdaysFormat\"", ",", "dateTimeData", ".", "weekdaysFormat", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.weekdaysStandalone\"", ",", "dateTimeData", ".", "weekdaysStandalone", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.dayPeriodsFormat\"", ",", "dateTimeData", ".", "dayPeriodsFormat", ")", ";", "variantsFieldInit", "(", "constructor", ",", "\"this.dayPeriodsStandalone\"", ",", "dateTimeData", ".", "dayPeriodsStandalone", ")", ";", "buildTimeZoneExemplarCities", "(", "constructor", ",", "timeZoneData", ")", ";", "buildTimeZoneNames", "(", "constructor", ",", "timeZoneData", ")", ";", "buildMetaZoneNames", "(", "constructor", ",", "timeZoneData", ")", ";", "TypeSpec", ".", "Builder", "type", "=", "TypeSpec", ".", "classBuilder", "(", "className", ")", ".", "superclass", "(", "CALENDAR_FORMATTER", ")", ".", "addModifiers", "(", "PUBLIC", ")", ".", "addJavadoc", "(", "\"Locale \\\"\"", "+", "dateTimeData", ".", "id", "+", "\"\\\"\\n\"", "+", "\"See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\\n\"", ")", ".", "addMethod", "(", "constructor", ".", "build", "(", ")", ")", ";", "MethodSpec", "dateMethod", "=", "buildTypedPatternMethod", "(", "\"formatDate\"", ",", "CALENDAR_FORMAT", ",", "dateTimeData", ".", "dateFormats", ")", ";", "MethodSpec", "timeMethod", "=", "buildTypedPatternMethod", "(", "\"formatTime\"", ",", "CALENDAR_FORMAT", ",", "dateTimeData", ".", "timeFormats", ")", ";", "MethodSpec", "wrapperMethod", "=", "buildWrapperMethod", "(", "dateTimeData", ".", "dateTimeFormats", ")", ";", "MethodSpec", "skeletonMethod", "=", "buildSkeletonFormatter", "(", "dateTimeData", ".", "dateTimeSkeletons", ")", ";", "MethodSpec", "intervalMethod", "=", "buildIntervalMethod", "(", "dateTimeData", ".", "intervalFormats", ",", "dateTimeData", ".", "intervalFallbackFormat", ")", ";", "MethodSpec", "gmtMethod", "=", "buildWrapTimeZoneGMTMethod", "(", "timeZoneData", ")", ";", "MethodSpec", "regionFormatMethod", "=", "buildWrapTimeZoneRegionMethod", "(", "timeZoneData", ")", ";", "return", "type", ".", "addMethod", "(", "dateMethod", ")", ".", "addMethod", "(", "timeMethod", ")", ".", "addMethod", "(", "wrapperMethod", ")", ".", "addMethod", "(", "skeletonMethod", ")", ".", "addMethod", "(", "intervalMethod", ")", ".", "addMethod", "(", "gmtMethod", ")", ".", "addMethod", "(", "regionFormatMethod", ")", ".", "build", "(", ")", ";", "}" ]
Create a Java class that captures all data formats for a given locale.
[ "Create", "a", "Java", "class", "that", "captures", "all", "data", "formats", "for", "a", "given", "locale", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L204-L253
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/clustering/LinkClustering.java
LinkClustering.calculateEdgeSimMatrix
private Matrix calculateEdgeSimMatrix( final List<Edge> edgeList, final SparseMatrix sm) { """ Calculates the similarity matrix for the edges. The similarity matrix is symmetric. @param edgeList the list of all edges known to the system @param sm a square matrix whose values denote edges between the rows. @return the similarity matrix """ final int numEdges = edgeList.size(); final Matrix edgeSimMatrix = new SparseSymmetricMatrix( new SparseHashMatrix(numEdges, numEdges)); Object key = workQueue.registerTaskGroup(numEdges); for (int i = 0; i < numEdges; ++i) { final int row = i; workQueue.add(key, new Runnable() { public void run() { for (int j = row; j < numEdges; ++j) { Edge e1 = edgeList.get(row); Edge e2 = edgeList.get(j); double sim = getEdgeSimilarity(sm, e1, e2); if (sim > 0) { // The symmetric matrix handles the (j,i) case edgeSimMatrix.set(row, j, sim); } } } }); } workQueue.await(key); return edgeSimMatrix; }
java
private Matrix calculateEdgeSimMatrix( final List<Edge> edgeList, final SparseMatrix sm) { final int numEdges = edgeList.size(); final Matrix edgeSimMatrix = new SparseSymmetricMatrix( new SparseHashMatrix(numEdges, numEdges)); Object key = workQueue.registerTaskGroup(numEdges); for (int i = 0; i < numEdges; ++i) { final int row = i; workQueue.add(key, new Runnable() { public void run() { for (int j = row; j < numEdges; ++j) { Edge e1 = edgeList.get(row); Edge e2 = edgeList.get(j); double sim = getEdgeSimilarity(sm, e1, e2); if (sim > 0) { // The symmetric matrix handles the (j,i) case edgeSimMatrix.set(row, j, sim); } } } }); } workQueue.await(key); return edgeSimMatrix; }
[ "private", "Matrix", "calculateEdgeSimMatrix", "(", "final", "List", "<", "Edge", ">", "edgeList", ",", "final", "SparseMatrix", "sm", ")", "{", "final", "int", "numEdges", "=", "edgeList", ".", "size", "(", ")", ";", "final", "Matrix", "edgeSimMatrix", "=", "new", "SparseSymmetricMatrix", "(", "new", "SparseHashMatrix", "(", "numEdges", ",", "numEdges", ")", ")", ";", "Object", "key", "=", "workQueue", ".", "registerTaskGroup", "(", "numEdges", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numEdges", ";", "++", "i", ")", "{", "final", "int", "row", "=", "i", ";", "workQueue", ".", "add", "(", "key", ",", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "for", "(", "int", "j", "=", "row", ";", "j", "<", "numEdges", ";", "++", "j", ")", "{", "Edge", "e1", "=", "edgeList", ".", "get", "(", "row", ")", ";", "Edge", "e2", "=", "edgeList", ".", "get", "(", "j", ")", ";", "double", "sim", "=", "getEdgeSimilarity", "(", "sm", ",", "e1", ",", "e2", ")", ";", "if", "(", "sim", ">", "0", ")", "{", "// The symmetric matrix handles the (j,i) case", "edgeSimMatrix", ".", "set", "(", "row", ",", "j", ",", "sim", ")", ";", "}", "}", "}", "}", ")", ";", "}", "workQueue", ".", "await", "(", "key", ")", ";", "return", "edgeSimMatrix", ";", "}" ]
Calculates the similarity matrix for the edges. The similarity matrix is symmetric. @param edgeList the list of all edges known to the system @param sm a square matrix whose values denote edges between the rows. @return the similarity matrix
[ "Calculates", "the", "similarity", "matrix", "for", "the", "edges", ".", "The", "similarity", "matrix", "is", "symmetric", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/clustering/LinkClustering.java#L373-L402
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.getFieldAccessorName
private String getFieldAccessorName(TypeToken<?> recordType, String fieldName) { """ Generates the name of the class field for storing {@link FieldAccessor} for the given record field. @param recordType Type of the record. @param fieldName name of the field. @return name of the class field. """ return String.format("%s$%s", normalizeTypeName(recordType), fieldName); }
java
private String getFieldAccessorName(TypeToken<?> recordType, String fieldName) { return String.format("%s$%s", normalizeTypeName(recordType), fieldName); }
[ "private", "String", "getFieldAccessorName", "(", "TypeToken", "<", "?", ">", "recordType", ",", "String", "fieldName", ")", "{", "return", "String", ".", "format", "(", "\"%s$%s\"", ",", "normalizeTypeName", "(", "recordType", ")", ",", "fieldName", ")", ";", "}" ]
Generates the name of the class field for storing {@link FieldAccessor} for the given record field. @param recordType Type of the record. @param fieldName name of the field. @return name of the class field.
[ "Generates", "the", "name", "of", "the", "class", "field", "for", "storing", "{" ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L954-L956
grycap/coreutils
coreutils-fiber/src/main/java/es/upv/grycap/coreutils/fiber/http/Http2Client.java
Http2Client.asyncPost
public void asyncPost(final String url, final String mediaType, final Supplier<String> supplier, final Callback callback) { """ Posts data to a server via a HTTP POST request. @param url - URL target of this request @param mediaType - Content-Type header for this request @param supplier - supplies the content of this request @param callback - is called back when the response is readable """ requireNonNull(supplier, "A valid supplier expected"); asyncPostBytes(url, mediaType, () -> ofNullable(supplier.get()).orElse("").getBytes(), callback); }
java
public void asyncPost(final String url, final String mediaType, final Supplier<String> supplier, final Callback callback) { requireNonNull(supplier, "A valid supplier expected"); asyncPostBytes(url, mediaType, () -> ofNullable(supplier.get()).orElse("").getBytes(), callback); }
[ "public", "void", "asyncPost", "(", "final", "String", "url", ",", "final", "String", "mediaType", ",", "final", "Supplier", "<", "String", ">", "supplier", ",", "final", "Callback", "callback", ")", "{", "requireNonNull", "(", "supplier", ",", "\"A valid supplier expected\"", ")", ";", "asyncPostBytes", "(", "url", ",", "mediaType", ",", "(", ")", "->", "ofNullable", "(", "supplier", ".", "get", "(", ")", ")", ".", "orElse", "(", "\"\"", ")", ".", "getBytes", "(", ")", ",", "callback", ")", ";", "}" ]
Posts data to a server via a HTTP POST request. @param url - URL target of this request @param mediaType - Content-Type header for this request @param supplier - supplies the content of this request @param callback - is called back when the response is readable
[ "Posts", "data", "to", "a", "server", "via", "a", "HTTP", "POST", "request", "." ]
train
https://github.com/grycap/coreutils/blob/e6db61dc50b49ea7276c0c29c7401204681a10c2/coreutils-fiber/src/main/java/es/upv/grycap/coreutils/fiber/http/Http2Client.java#L114-L117
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.addEntries
public Jar addEntries(Path path, ZipInputStream zip) throws IOException { """ Adds the contents of the zip/JAR contained in the given byte array to this JAR. @param path the path within the JAR where the root of the zip will be placed, or {@code null} for the JAR's root @param zip the contents of the zip/JAR file @return {@code this} """ return addEntries(path, zip, null); }
java
public Jar addEntries(Path path, ZipInputStream zip) throws IOException { return addEntries(path, zip, null); }
[ "public", "Jar", "addEntries", "(", "Path", "path", ",", "ZipInputStream", "zip", ")", "throws", "IOException", "{", "return", "addEntries", "(", "path", ",", "zip", ",", "null", ")", ";", "}" ]
Adds the contents of the zip/JAR contained in the given byte array to this JAR. @param path the path within the JAR where the root of the zip will be placed, or {@code null} for the JAR's root @param zip the contents of the zip/JAR file @return {@code this}
[ "Adds", "the", "contents", "of", "the", "zip", "/", "JAR", "contained", "in", "the", "given", "byte", "array", "to", "this", "JAR", "." ]
train
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L444-L446
JoeKerouac/utils
src/main/java/com/joe/utils/poi/WorkBookAccesser.java
WorkBookAccesser.getCell
public Cell getCell(int column, int row) { """ 获取指定sheet的指定行列单元格 @param column 单元格所在列 @param row 单元格所在行 @return 指定行列的单元格 """ return this.workbook.getSheetAt(sheetIndex).getRow(row).getCell(column); }
java
public Cell getCell(int column, int row) { return this.workbook.getSheetAt(sheetIndex).getRow(row).getCell(column); }
[ "public", "Cell", "getCell", "(", "int", "column", ",", "int", "row", ")", "{", "return", "this", ".", "workbook", ".", "getSheetAt", "(", "sheetIndex", ")", ".", "getRow", "(", "row", ")", ".", "getCell", "(", "column", ")", ";", "}" ]
获取指定sheet的指定行列单元格 @param column 单元格所在列 @param row 单元格所在行 @return 指定行列的单元格
[ "获取指定sheet的指定行列单元格" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/poi/WorkBookAccesser.java#L44-L46
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Scanner.java
Scanner.hasNextBigInteger
public boolean hasNextBigInteger(int radix) { """ Returns true if the next token in this scanner's input can be interpreted as a <code>BigInteger</code> in the specified radix using the {@link #nextBigInteger} method. The scanner does not advance past any input. @param radix the radix used to interpret the token as an integer @return true if and only if this scanner's next token is a valid <code>BigInteger</code> @throws IllegalStateException if this scanner is closed """ setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = new BigInteger(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; }
java
public boolean hasNextBigInteger(int radix) { setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = new BigInteger(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; }
[ "public", "boolean", "hasNextBigInteger", "(", "int", "radix", ")", "{", "setRadix", "(", "radix", ")", ";", "boolean", "result", "=", "hasNext", "(", "integerPattern", "(", ")", ")", ";", "if", "(", "result", ")", "{", "// Cache it", "try", "{", "String", "s", "=", "(", "matcher", ".", "group", "(", "SIMPLE_GROUP_INDEX", ")", "==", "null", ")", "?", "processIntegerToken", "(", "hasNextResult", ")", ":", "hasNextResult", ";", "typeCache", "=", "new", "BigInteger", "(", "s", ",", "radix", ")", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "result", "=", "false", ";", "}", "}", "return", "result", ";", "}" ]
Returns true if the next token in this scanner's input can be interpreted as a <code>BigInteger</code> in the specified radix using the {@link #nextBigInteger} method. The scanner does not advance past any input. @param radix the radix used to interpret the token as an integer @return true if and only if this scanner's next token is a valid <code>BigInteger</code> @throws IllegalStateException if this scanner is closed
[ "Returns", "true", "if", "the", "next", "token", "in", "this", "scanner", "s", "input", "can", "be", "interpreted", "as", "a", "<code", ">", "BigInteger<", "/", "code", ">", "in", "the", "specified", "radix", "using", "the", "{", "@link", "#nextBigInteger", "}", "method", ".", "The", "scanner", "does", "not", "advance", "past", "any", "input", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Scanner.java#L2422-L2436
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubManager.java
PubSubManager.getNode
public Node getNode(String id) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAPubSubNodeException { """ Retrieves the requested node, if it exists. It will throw an exception if it does not. @param id - The unique id of the node @return the node @throws XMPPErrorException The node does not exist @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException @throws NotAPubSubNodeException """ Node node = nodeMap.get(id); if (node == null) { DiscoverInfo info = new DiscoverInfo(); info.setTo(pubSubService); info.setNode(id); DiscoverInfo infoReply = connection().createStanzaCollectorAndSend(info).nextResultOrThrow(); if (infoReply.hasIdentity(PubSub.ELEMENT, "leaf")) { node = new LeafNode(this, id); } else if (infoReply.hasIdentity(PubSub.ELEMENT, "collection")) { node = new CollectionNode(this, id); } else { throw new PubSubException.NotAPubSubNodeException(id, infoReply); } nodeMap.put(id, node); } return node; }
java
public Node getNode(String id) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotAPubSubNodeException { Node node = nodeMap.get(id); if (node == null) { DiscoverInfo info = new DiscoverInfo(); info.setTo(pubSubService); info.setNode(id); DiscoverInfo infoReply = connection().createStanzaCollectorAndSend(info).nextResultOrThrow(); if (infoReply.hasIdentity(PubSub.ELEMENT, "leaf")) { node = new LeafNode(this, id); } else if (infoReply.hasIdentity(PubSub.ELEMENT, "collection")) { node = new CollectionNode(this, id); } else { throw new PubSubException.NotAPubSubNodeException(id, infoReply); } nodeMap.put(id, node); } return node; }
[ "public", "Node", "getNode", "(", "String", "id", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", ",", "NotAPubSubNodeException", "{", "Node", "node", "=", "nodeMap", ".", "get", "(", "id", ")", ";", "if", "(", "node", "==", "null", ")", "{", "DiscoverInfo", "info", "=", "new", "DiscoverInfo", "(", ")", ";", "info", ".", "setTo", "(", "pubSubService", ")", ";", "info", ".", "setNode", "(", "id", ")", ";", "DiscoverInfo", "infoReply", "=", "connection", "(", ")", ".", "createStanzaCollectorAndSend", "(", "info", ")", ".", "nextResultOrThrow", "(", ")", ";", "if", "(", "infoReply", ".", "hasIdentity", "(", "PubSub", ".", "ELEMENT", ",", "\"leaf\"", ")", ")", "{", "node", "=", "new", "LeafNode", "(", "this", ",", "id", ")", ";", "}", "else", "if", "(", "infoReply", ".", "hasIdentity", "(", "PubSub", ".", "ELEMENT", ",", "\"collection\"", ")", ")", "{", "node", "=", "new", "CollectionNode", "(", "this", ",", "id", ")", ";", "}", "else", "{", "throw", "new", "PubSubException", ".", "NotAPubSubNodeException", "(", "id", ",", "infoReply", ")", ";", "}", "nodeMap", ".", "put", "(", "id", ",", "node", ")", ";", "}", "return", "node", ";", "}" ]
Retrieves the requested node, if it exists. It will throw an exception if it does not. @param id - The unique id of the node @return the node @throws XMPPErrorException The node does not exist @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException @throws NotAPubSubNodeException
[ "Retrieves", "the", "requested", "node", "if", "it", "exists", ".", "It", "will", "throw", "an", "exception", "if", "it", "does", "not", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/PubSubManager.java#L270-L292
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/tools/BTools.java
BTools.getSDbl
public static String getSDbl( double Value, int DecPrec ) { """ <b>getSDbl</b><br> public static String getSDbl( double Value, int DecPrec )<br> Returns double converted to string.<br> If Value is Double.NaN returns "NaN".<br> If DecPrec is < 0 is DecPrec set 0.<br> @param Value - value @param DecPrec - decimal precision @return double as string """ // String Result = ""; // if ( Double.isNaN( Value ) ) return "NaN"; // if ( DecPrec < 0 ) DecPrec = 0; // String DFS = "###,###,##0"; // if ( DecPrec > 0 ) { int idx = 0; DFS += "."; while ( idx < DecPrec ) { DFS = DFS + "0"; idx ++; if ( idx > 100 ) break; } } // // Locale locale = new Locale("en", "UK"); // DecimalFormatSymbols DcmFrmSmb = new DecimalFormatSymbols( Locale.getDefault()); DcmFrmSmb.setDecimalSeparator('.'); DcmFrmSmb.setGroupingSeparator(' '); // DecimalFormat DcmFrm; // DcmFrm = new DecimalFormat( DFS, DcmFrmSmb ); // // DcmFrm.setGroupingSize( 3 ); // Result = DcmFrm.format( Value ); // return Result; }
java
public static String getSDbl( double Value, int DecPrec ) { // String Result = ""; // if ( Double.isNaN( Value ) ) return "NaN"; // if ( DecPrec < 0 ) DecPrec = 0; // String DFS = "###,###,##0"; // if ( DecPrec > 0 ) { int idx = 0; DFS += "."; while ( idx < DecPrec ) { DFS = DFS + "0"; idx ++; if ( idx > 100 ) break; } } // // Locale locale = new Locale("en", "UK"); // DecimalFormatSymbols DcmFrmSmb = new DecimalFormatSymbols( Locale.getDefault()); DcmFrmSmb.setDecimalSeparator('.'); DcmFrmSmb.setGroupingSeparator(' '); // DecimalFormat DcmFrm; // DcmFrm = new DecimalFormat( DFS, DcmFrmSmb ); // // DcmFrm.setGroupingSize( 3 ); // Result = DcmFrm.format( Value ); // return Result; }
[ "public", "static", "String", "getSDbl", "(", "double", "Value", ",", "int", "DecPrec", ")", "{", "//", "String", "Result", "=", "\"\"", ";", "//", "if", "(", "Double", ".", "isNaN", "(", "Value", ")", ")", "return", "\"NaN\"", ";", "//", "if", "(", "DecPrec", "<", "0", ")", "DecPrec", "=", "0", ";", "//", "String", "DFS", "=", "\"###,###,##0\"", ";", "//", "if", "(", "DecPrec", ">", "0", ")", "{", "int", "idx", "=", "0", ";", "DFS", "+=", "\".\"", ";", "while", "(", "idx", "<", "DecPrec", ")", "{", "DFS", "=", "DFS", "+", "\"0\"", ";", "idx", "++", ";", "if", "(", "idx", ">", "100", ")", "break", ";", "}", "}", "//", "//\t\tLocale locale = new Locale(\"en\", \"UK\");", "//", "DecimalFormatSymbols", "DcmFrmSmb", "=", "new", "DecimalFormatSymbols", "(", "Locale", ".", "getDefault", "(", ")", ")", ";", "DcmFrmSmb", ".", "setDecimalSeparator", "(", "'", "'", ")", ";", "DcmFrmSmb", ".", "setGroupingSeparator", "(", "'", "'", ")", ";", "//", "DecimalFormat", "DcmFrm", ";", "//", "DcmFrm", "=", "new", "DecimalFormat", "(", "DFS", ",", "DcmFrmSmb", ")", ";", "//", "//\tDcmFrm.setGroupingSize( 3 );", "//", "Result", "=", "DcmFrm", ".", "format", "(", "Value", ")", ";", "//", "return", "Result", ";", "}" ]
<b>getSDbl</b><br> public static String getSDbl( double Value, int DecPrec )<br> Returns double converted to string.<br> If Value is Double.NaN returns "NaN".<br> If DecPrec is < 0 is DecPrec set 0.<br> @param Value - value @param DecPrec - decimal precision @return double as string
[ "<b", ">", "getSDbl<", "/", "b", ">", "<br", ">", "public", "static", "String", "getSDbl", "(", "double", "Value", "int", "DecPrec", ")", "<br", ">", "Returns", "double", "converted", "to", "string", ".", "<br", ">", "If", "Value", "is", "Double", ".", "NaN", "returns", "NaN", ".", "<br", ">", "If", "DecPrec", "is", "<", "0", "is", "DecPrec", "set", "0", ".", "<br", ">" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-common/src/main/java/org/nd4j/tools/BTools.java#L142-L177
UrielCh/ovh-java-sdk
ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java
ApiOvhIp.ip_arp_ipBlocked_unblock_POST
public void ip_arp_ipBlocked_unblock_POST(String ip, String ipBlocked) throws IOException { """ Unblock this IP REST: POST /ip/{ip}/arp/{ipBlocked}/unblock @param ip [required] @param ipBlocked [required] your IP """ String qPath = "/ip/{ip}/arp/{ipBlocked}/unblock"; StringBuilder sb = path(qPath, ip, ipBlocked); exec(qPath, "POST", sb.toString(), null); }
java
public void ip_arp_ipBlocked_unblock_POST(String ip, String ipBlocked) throws IOException { String qPath = "/ip/{ip}/arp/{ipBlocked}/unblock"; StringBuilder sb = path(qPath, ip, ipBlocked); exec(qPath, "POST", sb.toString(), null); }
[ "public", "void", "ip_arp_ipBlocked_unblock_POST", "(", "String", "ip", ",", "String", "ipBlocked", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ip/{ip}/arp/{ipBlocked}/unblock\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "ip", ",", "ipBlocked", ")", ";", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "}" ]
Unblock this IP REST: POST /ip/{ip}/arp/{ipBlocked}/unblock @param ip [required] @param ipBlocked [required] your IP
[ "Unblock", "this", "IP" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L286-L290
amzn/ion-java
src/com/amazon/ion/impl/IonReaderTextRawTokensX.java
IonReaderTextRawTokensX.load_digits
private final int load_digits(StringBuilder sb, int c) throws IOException { """ Accumulates digits into the buffer, starting with the given character. @return the first non-digit character on the input. Could be the given character if its not a digit. @see IonTokenConstsX#isDigit(int) """ if (!IonTokenConstsX.isDigit(c)) { return c; } sb.append((char) c); return readNumeric(sb, Radix.DECIMAL, NumericState.DIGIT); }
java
private final int load_digits(StringBuilder sb, int c) throws IOException { if (!IonTokenConstsX.isDigit(c)) { return c; } sb.append((char) c); return readNumeric(sb, Radix.DECIMAL, NumericState.DIGIT); }
[ "private", "final", "int", "load_digits", "(", "StringBuilder", "sb", ",", "int", "c", ")", "throws", "IOException", "{", "if", "(", "!", "IonTokenConstsX", ".", "isDigit", "(", "c", ")", ")", "{", "return", "c", ";", "}", "sb", ".", "append", "(", "(", "char", ")", "c", ")", ";", "return", "readNumeric", "(", "sb", ",", "Radix", ".", "DECIMAL", ",", "NumericState", ".", "DIGIT", ")", ";", "}" ]
Accumulates digits into the buffer, starting with the given character. @return the first non-digit character on the input. Could be the given character if its not a digit. @see IonTokenConstsX#isDigit(int)
[ "Accumulates", "digits", "into", "the", "buffer", "starting", "with", "the", "given", "character", "." ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/IonReaderTextRawTokensX.java#L1682-L1691
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getTagAsync
public Observable<Tag> getTagAsync(UUID projectId, UUID tagId, GetTagOptionalParameter getTagOptionalParameter) { """ Get information about a specific tag. @param projectId The project this tag belongs to @param tagId The tag id @param getTagOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Tag object """ return getTagWithServiceResponseAsync(projectId, tagId, getTagOptionalParameter).map(new Func1<ServiceResponse<Tag>, Tag>() { @Override public Tag call(ServiceResponse<Tag> response) { return response.body(); } }); }
java
public Observable<Tag> getTagAsync(UUID projectId, UUID tagId, GetTagOptionalParameter getTagOptionalParameter) { return getTagWithServiceResponseAsync(projectId, tagId, getTagOptionalParameter).map(new Func1<ServiceResponse<Tag>, Tag>() { @Override public Tag call(ServiceResponse<Tag> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Tag", ">", "getTagAsync", "(", "UUID", "projectId", ",", "UUID", "tagId", ",", "GetTagOptionalParameter", "getTagOptionalParameter", ")", "{", "return", "getTagWithServiceResponseAsync", "(", "projectId", ",", "tagId", ",", "getTagOptionalParameter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Tag", ">", ",", "Tag", ">", "(", ")", "{", "@", "Override", "public", "Tag", "call", "(", "ServiceResponse", "<", "Tag", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get information about a specific tag. @param projectId The project this tag belongs to @param tagId The tag id @param getTagOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Tag object
[ "Get", "information", "about", "a", "specific", "tag", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L804-L811
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/UsersApi.java
UsersApi.getUserRules
public RulesEnvelope getUserRules(String userId, Boolean excludeDisabled, Integer count, Integer offset, String owner) throws ApiException { """ Get User Rules Retrieve User&#39;s Rules @param userId User ID. (required) @param excludeDisabled Exclude disabled rules in the result. (optional) @param count Desired count of items in the result set. (optional) @param offset Offset for pagination. (optional) @param owner Rule owner (optional) @return RulesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<RulesEnvelope> resp = getUserRulesWithHttpInfo(userId, excludeDisabled, count, offset, owner); return resp.getData(); }
java
public RulesEnvelope getUserRules(String userId, Boolean excludeDisabled, Integer count, Integer offset, String owner) throws ApiException { ApiResponse<RulesEnvelope> resp = getUserRulesWithHttpInfo(userId, excludeDisabled, count, offset, owner); return resp.getData(); }
[ "public", "RulesEnvelope", "getUserRules", "(", "String", "userId", ",", "Boolean", "excludeDisabled", ",", "Integer", "count", ",", "Integer", "offset", ",", "String", "owner", ")", "throws", "ApiException", "{", "ApiResponse", "<", "RulesEnvelope", ">", "resp", "=", "getUserRulesWithHttpInfo", "(", "userId", ",", "excludeDisabled", ",", "count", ",", "offset", ",", "owner", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Get User Rules Retrieve User&#39;s Rules @param userId User ID. (required) @param excludeDisabled Exclude disabled rules in the result. (optional) @param count Desired count of items in the result set. (optional) @param offset Offset for pagination. (optional) @param owner Rule owner (optional) @return RulesEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "User", "Rules", "Retrieve", "User&#39", ";", "s", "Rules" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/UsersApi.java#L915-L918
deephacks/confit
api-model/src/main/java/org/deephacks/confit/model/Bean.java
Bean.addProperty
public void addProperty(final String propertyName, final Collection<String> values) { """ Add a list of value to a property on this bean. @param propertyName name of the property as defined by the bean's schema. @param values final String representations of the parameterized type of the collection that conforms to its type as defined by the bean's schema. """ Preconditions.checkNotNull(values); Preconditions.checkNotNull(propertyName); List<String> list = properties.get(propertyName); if (list == null) { properties.put(propertyName, new ArrayList<>(values)); } else { list.addAll(values); } }
java
public void addProperty(final String propertyName, final Collection<String> values) { Preconditions.checkNotNull(values); Preconditions.checkNotNull(propertyName); List<String> list = properties.get(propertyName); if (list == null) { properties.put(propertyName, new ArrayList<>(values)); } else { list.addAll(values); } }
[ "public", "void", "addProperty", "(", "final", "String", "propertyName", ",", "final", "Collection", "<", "String", ">", "values", ")", "{", "Preconditions", ".", "checkNotNull", "(", "values", ")", ";", "Preconditions", ".", "checkNotNull", "(", "propertyName", ")", ";", "List", "<", "String", ">", "list", "=", "properties", ".", "get", "(", "propertyName", ")", ";", "if", "(", "list", "==", "null", ")", "{", "properties", ".", "put", "(", "propertyName", ",", "new", "ArrayList", "<>", "(", "values", ")", ")", ";", "}", "else", "{", "list", ".", "addAll", "(", "values", ")", ";", "}", "}" ]
Add a list of value to a property on this bean. @param propertyName name of the property as defined by the bean's schema. @param values final String representations of the parameterized type of the collection that conforms to its type as defined by the bean's schema.
[ "Add", "a", "list", "of", "value", "to", "a", "property", "on", "this", "bean", "." ]
train
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-model/src/main/java/org/deephacks/confit/model/Bean.java#L145-L154
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java
CeCPMain.postProcessAlignment
public static AFPChain postProcessAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2m,CECalculator calculator ) throws StructureException { """ Circular permutation specific code to be run after the standard CE alignment @param afpChain The finished alignment @param ca1 CA atoms of the first protein @param ca2m A duplicated copy of the second protein @param calculator The CECalculator used to create afpChain @throws StructureException """ return postProcessAlignment(afpChain, ca1, ca2m, calculator, null); }
java
public static AFPChain postProcessAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2m,CECalculator calculator ) throws StructureException{ return postProcessAlignment(afpChain, ca1, ca2m, calculator, null); }
[ "public", "static", "AFPChain", "postProcessAlignment", "(", "AFPChain", "afpChain", ",", "Atom", "[", "]", "ca1", ",", "Atom", "[", "]", "ca2m", ",", "CECalculator", "calculator", ")", "throws", "StructureException", "{", "return", "postProcessAlignment", "(", "afpChain", ",", "ca1", ",", "ca2m", ",", "calculator", ",", "null", ")", ";", "}" ]
Circular permutation specific code to be run after the standard CE alignment @param afpChain The finished alignment @param ca1 CA atoms of the first protein @param ca2m A duplicated copy of the second protein @param calculator The CECalculator used to create afpChain @throws StructureException
[ "Circular", "permutation", "specific", "code", "to", "be", "run", "after", "the", "standard", "CE", "alignment" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java#L191-L193
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ReloadableType.java
ReloadableType.getCurrentMethod
public MethodMember getCurrentMethod(String name, String descriptor) { """ Gets the method corresponding to given name and descriptor, taking into consideration changes that have happened by reloading. @param name the member name @param descriptor the member descriptor (e.g. (Ljava/lang/String;)I) @return the MethodMember for that name and descriptor. Null if not found on a live version, or an exception if there is no live version and it cannot be found. """ if (liveVersion == null) { return getMethod(name, descriptor); } else { return liveVersion.getReloadableMethod(name, descriptor); } }
java
public MethodMember getCurrentMethod(String name, String descriptor) { if (liveVersion == null) { return getMethod(name, descriptor); } else { return liveVersion.getReloadableMethod(name, descriptor); } }
[ "public", "MethodMember", "getCurrentMethod", "(", "String", "name", ",", "String", "descriptor", ")", "{", "if", "(", "liveVersion", "==", "null", ")", "{", "return", "getMethod", "(", "name", ",", "descriptor", ")", ";", "}", "else", "{", "return", "liveVersion", ".", "getReloadableMethod", "(", "name", ",", "descriptor", ")", ";", "}", "}" ]
Gets the method corresponding to given name and descriptor, taking into consideration changes that have happened by reloading. @param name the member name @param descriptor the member descriptor (e.g. (Ljava/lang/String;)I) @return the MethodMember for that name and descriptor. Null if not found on a live version, or an exception if there is no live version and it cannot be found.
[ "Gets", "the", "method", "corresponding", "to", "given", "name", "and", "descriptor", "taking", "into", "consideration", "changes", "that", "have", "happened", "by", "reloading", "." ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ReloadableType.java#L878-L885
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeLockList.java
InodeLockList.downgradeEdgeToInode
public void downgradeEdgeToInode(Inode inode, LockMode mode) { """ Downgrades from edge write-locking to inode write-locking. This reduces the scope of the write lock by pushing it forward one entry. For example, if the lock list is in write mode with entries [a, a->b, b, b->c], downgradeEdgeToInode(c, mode) will change the list to [a, a->b, b, b->c, c], with b->c downgraded to a read lock. c will be locked according to the mode. The read lock on the final edge is taken before releasing the write lock. @param inode the next inode in the lock list @param mode the mode to downgrade to """ Preconditions.checkState(!endsInInode()); Preconditions.checkState(!mEntries.isEmpty()); Preconditions.checkState(mLockMode == LockMode.WRITE); EdgeEntry last = (EdgeEntry) mEntries.get(mEntries.size() - 1); LockResource inodeLock = mInodeLockManager.lockInode(inode, mode); LockResource edgeLock = mInodeLockManager.lockEdge(last.mEdge, LockMode.READ); last.getLock().close(); mEntries.set(mEntries.size() - 1, new EdgeEntry(edgeLock, last.getEdge())); mEntries.add(new InodeEntry(inodeLock, inode)); mLockedInodes.add(inode); mLockMode = mode; }
java
public void downgradeEdgeToInode(Inode inode, LockMode mode) { Preconditions.checkState(!endsInInode()); Preconditions.checkState(!mEntries.isEmpty()); Preconditions.checkState(mLockMode == LockMode.WRITE); EdgeEntry last = (EdgeEntry) mEntries.get(mEntries.size() - 1); LockResource inodeLock = mInodeLockManager.lockInode(inode, mode); LockResource edgeLock = mInodeLockManager.lockEdge(last.mEdge, LockMode.READ); last.getLock().close(); mEntries.set(mEntries.size() - 1, new EdgeEntry(edgeLock, last.getEdge())); mEntries.add(new InodeEntry(inodeLock, inode)); mLockedInodes.add(inode); mLockMode = mode; }
[ "public", "void", "downgradeEdgeToInode", "(", "Inode", "inode", ",", "LockMode", "mode", ")", "{", "Preconditions", ".", "checkState", "(", "!", "endsInInode", "(", ")", ")", ";", "Preconditions", ".", "checkState", "(", "!", "mEntries", ".", "isEmpty", "(", ")", ")", ";", "Preconditions", ".", "checkState", "(", "mLockMode", "==", "LockMode", ".", "WRITE", ")", ";", "EdgeEntry", "last", "=", "(", "EdgeEntry", ")", "mEntries", ".", "get", "(", "mEntries", ".", "size", "(", ")", "-", "1", ")", ";", "LockResource", "inodeLock", "=", "mInodeLockManager", ".", "lockInode", "(", "inode", ",", "mode", ")", ";", "LockResource", "edgeLock", "=", "mInodeLockManager", ".", "lockEdge", "(", "last", ".", "mEdge", ",", "LockMode", ".", "READ", ")", ";", "last", ".", "getLock", "(", ")", ".", "close", "(", ")", ";", "mEntries", ".", "set", "(", "mEntries", ".", "size", "(", ")", "-", "1", ",", "new", "EdgeEntry", "(", "edgeLock", ",", "last", ".", "getEdge", "(", ")", ")", ")", ";", "mEntries", ".", "add", "(", "new", "InodeEntry", "(", "inodeLock", ",", "inode", ")", ")", ";", "mLockedInodes", ".", "add", "(", "inode", ")", ";", "mLockMode", "=", "mode", ";", "}" ]
Downgrades from edge write-locking to inode write-locking. This reduces the scope of the write lock by pushing it forward one entry. For example, if the lock list is in write mode with entries [a, a->b, b, b->c], downgradeEdgeToInode(c, mode) will change the list to [a, a->b, b, b->c, c], with b->c downgraded to a read lock. c will be locked according to the mode. The read lock on the final edge is taken before releasing the write lock. @param inode the next inode in the lock list @param mode the mode to downgrade to
[ "Downgrades", "from", "edge", "write", "-", "locking", "to", "inode", "write", "-", "locking", ".", "This", "reduces", "the", "scope", "of", "the", "write", "lock", "by", "pushing", "it", "forward", "one", "entry", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeLockList.java#L244-L257
jayantk/jklol
src/com/jayantkrish/jklol/ccg/lexinduct/vote/VotingLexiconInduction.java
VotingLexiconInduction.createParser
private static ParserInfo createParser(LexiconInductionCcgParserFactory factory, SufficientStatistics currentParameters, Collection<LexiconEntry> currentLexicon) { """ Creates a CCG parser given parameters and a lexicon. @param factory @param currentParameters @param currentLexicon @return """ ParametricCcgParser family = factory.getParametricCcgParser(currentLexicon); SufficientStatistics newParameters = family.getNewSufficientStatistics(); if (currentParameters != null) { newParameters.transferParameters(currentParameters); } return new ParserInfo(currentLexicon, family, newParameters, family.getModelFromParameters(newParameters)); }
java
private static ParserInfo createParser(LexiconInductionCcgParserFactory factory, SufficientStatistics currentParameters, Collection<LexiconEntry> currentLexicon) { ParametricCcgParser family = factory.getParametricCcgParser(currentLexicon); SufficientStatistics newParameters = family.getNewSufficientStatistics(); if (currentParameters != null) { newParameters.transferParameters(currentParameters); } return new ParserInfo(currentLexicon, family, newParameters, family.getModelFromParameters(newParameters)); }
[ "private", "static", "ParserInfo", "createParser", "(", "LexiconInductionCcgParserFactory", "factory", ",", "SufficientStatistics", "currentParameters", ",", "Collection", "<", "LexiconEntry", ">", "currentLexicon", ")", "{", "ParametricCcgParser", "family", "=", "factory", ".", "getParametricCcgParser", "(", "currentLexicon", ")", ";", "SufficientStatistics", "newParameters", "=", "family", ".", "getNewSufficientStatistics", "(", ")", ";", "if", "(", "currentParameters", "!=", "null", ")", "{", "newParameters", ".", "transferParameters", "(", "currentParameters", ")", ";", "}", "return", "new", "ParserInfo", "(", "currentLexicon", ",", "family", ",", "newParameters", ",", "family", ".", "getModelFromParameters", "(", "newParameters", ")", ")", ";", "}" ]
Creates a CCG parser given parameters and a lexicon. @param factory @param currentParameters @param currentLexicon @return
[ "Creates", "a", "CCG", "parser", "given", "parameters", "and", "a", "lexicon", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/lexinduct/vote/VotingLexiconInduction.java#L179-L189
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/patterns/Match.java
Match.createState
public MatchState createState(Synthesizer synthesizer, AnalyzedTokenReadings[] tokens, int index, int next) { """ Creates a state used for actually matching a token. @since 2.3 """ MatchState state = new MatchState(this, synthesizer); state.setToken(tokens, index, next); return state; }
java
public MatchState createState(Synthesizer synthesizer, AnalyzedTokenReadings[] tokens, int index, int next) { MatchState state = new MatchState(this, synthesizer); state.setToken(tokens, index, next); return state; }
[ "public", "MatchState", "createState", "(", "Synthesizer", "synthesizer", ",", "AnalyzedTokenReadings", "[", "]", "tokens", ",", "int", "index", ",", "int", "next", ")", "{", "MatchState", "state", "=", "new", "MatchState", "(", "this", ",", "synthesizer", ")", ";", "state", ".", "setToken", "(", "tokens", ",", "index", ",", "next", ")", ";", "return", "state", ";", "}" ]
Creates a state used for actually matching a token. @since 2.3
[ "Creates", "a", "state", "used", "for", "actually", "matching", "a", "token", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/Match.java#L102-L106
apache/groovy
src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
StaticTypeCheckingVisitor.inferReturnTypeGenerics
protected ClassNode inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments) { """ If a method call returns a parameterized type, then we can perform additional inference on the return type, so that the type gets actual type parameters. For example, the method Arrays.asList(T...) is generified with type T which can be deduced from actual type arguments. @param method the method node @param arguments the method call arguments @return parameterized, infered, class node """ return inferReturnTypeGenerics(receiver, method, arguments, null); }
java
protected ClassNode inferReturnTypeGenerics(ClassNode receiver, MethodNode method, Expression arguments) { return inferReturnTypeGenerics(receiver, method, arguments, null); }
[ "protected", "ClassNode", "inferReturnTypeGenerics", "(", "ClassNode", "receiver", ",", "MethodNode", "method", ",", "Expression", "arguments", ")", "{", "return", "inferReturnTypeGenerics", "(", "receiver", ",", "method", ",", "arguments", ",", "null", ")", ";", "}" ]
If a method call returns a parameterized type, then we can perform additional inference on the return type, so that the type gets actual type parameters. For example, the method Arrays.asList(T...) is generified with type T which can be deduced from actual type arguments. @param method the method node @param arguments the method call arguments @return parameterized, infered, class node
[ "If", "a", "method", "call", "returns", "a", "parameterized", "type", "then", "we", "can", "perform", "additional", "inference", "on", "the", "return", "type", "so", "that", "the", "type", "gets", "actual", "type", "parameters", ".", "For", "example", "the", "method", "Arrays", ".", "asList", "(", "T", "...", ")", "is", "generified", "with", "type", "T", "which", "can", "be", "deduced", "from", "actual", "type", "arguments", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java#L5204-L5206
heinrichreimer/material-drawer
library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerItem.java
DrawerItem.setTextSecondary
public DrawerItem setTextSecondary(String textSecondary, int textMode) { """ Sets a secondary text with a given text mode to the drawer item @param textSecondary Secondary text to set @param textMode Text mode to set """ mTextSecondary = textSecondary; setTextMode(textMode); notifyDataChanged(); return this; }
java
public DrawerItem setTextSecondary(String textSecondary, int textMode) { mTextSecondary = textSecondary; setTextMode(textMode); notifyDataChanged(); return this; }
[ "public", "DrawerItem", "setTextSecondary", "(", "String", "textSecondary", ",", "int", "textMode", ")", "{", "mTextSecondary", "=", "textSecondary", ";", "setTextMode", "(", "textMode", ")", ";", "notifyDataChanged", "(", ")", ";", "return", "this", ";", "}" ]
Sets a secondary text with a given text mode to the drawer item @param textSecondary Secondary text to set @param textMode Text mode to set
[ "Sets", "a", "secondary", "text", "with", "a", "given", "text", "mode", "to", "the", "drawer", "item" ]
train
https://github.com/heinrichreimer/material-drawer/blob/7c2406812d73f710ef8bb73d4a0f4bbef3b275ce/library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerItem.java#L363-L368
threerings/nenya
core/src/main/java/com/threerings/miso/client/MisoScenePanel.java
MisoScenePanel.getPath
public Path getPath (Sprite sprite, int x, int y, boolean loose) { """ Computes a path for the specified sprite to the specified tile coordinates. @param loose if true, an approximate path will be returned if a complete path cannot be located. This path will navigate the sprite "legally" as far as possible and then walk the sprite in a straight line to its final destination. This is generally only useful if the the path goes "off screen". """ // sanity check if (sprite == null) { throw new IllegalArgumentException( "Can't get path for null sprite [x=" + x + ", y=" + y + "."); } // get the destination tile coordinates Point src = MisoUtil.screenToTile( _metrics, sprite.getX(), sprite.getY(), new Point()); Point dest = MisoUtil.screenToTile(_metrics, x, y, new Point()); // compute our longest path from the screen size int longestPath = 3 * (getWidth() / _metrics.tilewid); // get a reasonable tile path through the scene long start = System.currentTimeMillis(); List<Point> points = AStarPathUtil.getPath( this, sprite, longestPath, src.x, src.y, dest.x, dest.y, loose); long duration = System.currentTimeMillis() - start; // sanity check the number of nodes searched so that we can keep an eye out for bogosity if (duration > 500L) { int considered = AStarPathUtil.getConsidered(); log.warning("Considered " + considered + " nodes for path from " + StringUtil.toString(src) + " to " + StringUtil.toString(dest) + " [duration=" + duration + "]."); } // construct a path object to guide the sprite on its merry way return (points == null) ? null : new TilePath(_metrics, sprite, points, x, y); }
java
public Path getPath (Sprite sprite, int x, int y, boolean loose) { // sanity check if (sprite == null) { throw new IllegalArgumentException( "Can't get path for null sprite [x=" + x + ", y=" + y + "."); } // get the destination tile coordinates Point src = MisoUtil.screenToTile( _metrics, sprite.getX(), sprite.getY(), new Point()); Point dest = MisoUtil.screenToTile(_metrics, x, y, new Point()); // compute our longest path from the screen size int longestPath = 3 * (getWidth() / _metrics.tilewid); // get a reasonable tile path through the scene long start = System.currentTimeMillis(); List<Point> points = AStarPathUtil.getPath( this, sprite, longestPath, src.x, src.y, dest.x, dest.y, loose); long duration = System.currentTimeMillis() - start; // sanity check the number of nodes searched so that we can keep an eye out for bogosity if (duration > 500L) { int considered = AStarPathUtil.getConsidered(); log.warning("Considered " + considered + " nodes for path from " + StringUtil.toString(src) + " to " + StringUtil.toString(dest) + " [duration=" + duration + "]."); } // construct a path object to guide the sprite on its merry way return (points == null) ? null : new TilePath(_metrics, sprite, points, x, y); }
[ "public", "Path", "getPath", "(", "Sprite", "sprite", ",", "int", "x", ",", "int", "y", ",", "boolean", "loose", ")", "{", "// sanity check", "if", "(", "sprite", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Can't get path for null sprite [x=\"", "+", "x", "+", "\", y=\"", "+", "y", "+", "\".\"", ")", ";", "}", "// get the destination tile coordinates", "Point", "src", "=", "MisoUtil", ".", "screenToTile", "(", "_metrics", ",", "sprite", ".", "getX", "(", ")", ",", "sprite", ".", "getY", "(", ")", ",", "new", "Point", "(", ")", ")", ";", "Point", "dest", "=", "MisoUtil", ".", "screenToTile", "(", "_metrics", ",", "x", ",", "y", ",", "new", "Point", "(", ")", ")", ";", "// compute our longest path from the screen size", "int", "longestPath", "=", "3", "*", "(", "getWidth", "(", ")", "/", "_metrics", ".", "tilewid", ")", ";", "// get a reasonable tile path through the scene", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "List", "<", "Point", ">", "points", "=", "AStarPathUtil", ".", "getPath", "(", "this", ",", "sprite", ",", "longestPath", ",", "src", ".", "x", ",", "src", ".", "y", ",", "dest", ".", "x", ",", "dest", ".", "y", ",", "loose", ")", ";", "long", "duration", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "// sanity check the number of nodes searched so that we can keep an eye out for bogosity", "if", "(", "duration", ">", "500L", ")", "{", "int", "considered", "=", "AStarPathUtil", ".", "getConsidered", "(", ")", ";", "log", ".", "warning", "(", "\"Considered \"", "+", "considered", "+", "\" nodes for path from \"", "+", "StringUtil", ".", "toString", "(", "src", ")", "+", "\" to \"", "+", "StringUtil", ".", "toString", "(", "dest", ")", "+", "\" [duration=\"", "+", "duration", "+", "\"].\"", ")", ";", "}", "// construct a path object to guide the sprite on its merry way", "return", "(", "points", "==", "null", ")", "?", "null", ":", "new", "TilePath", "(", "_metrics", ",", "sprite", ",", "points", ",", "x", ",", "y", ")", ";", "}" ]
Computes a path for the specified sprite to the specified tile coordinates. @param loose if true, an approximate path will be returned if a complete path cannot be located. This path will navigate the sprite "legally" as far as possible and then walk the sprite in a straight line to its final destination. This is generally only useful if the the path goes "off screen".
[ "Computes", "a", "path", "for", "the", "specified", "sprite", "to", "the", "specified", "tile", "coordinates", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L280-L314
mgormley/pacaya
src/main/java/edu/jhu/pacaya/gm/model/globalfac/ProjDepTreeFactor.java
ProjDepTreeFactor.hasOneParentPerToken
public static boolean hasOneParentPerToken(int n, VarConfig vc) { """ Returns whether this variable assignment specifies one parent per token. """ int[] parents = new int[n]; Arrays.fill(parents, -2); for (Var v : vc.getVars()) { if (v instanceof LinkVar) { LinkVar link = (LinkVar) v; if (vc.getState(v) == LinkVar.TRUE) { if (parents[link.getChild()] != -2) { // Multiple parents defined for the same child. return false; } parents[link.getChild()] = link.getParent(); } } } return !ArrayUtils.contains(parents, -2); }
java
public static boolean hasOneParentPerToken(int n, VarConfig vc) { int[] parents = new int[n]; Arrays.fill(parents, -2); for (Var v : vc.getVars()) { if (v instanceof LinkVar) { LinkVar link = (LinkVar) v; if (vc.getState(v) == LinkVar.TRUE) { if (parents[link.getChild()] != -2) { // Multiple parents defined for the same child. return false; } parents[link.getChild()] = link.getParent(); } } } return !ArrayUtils.contains(parents, -2); }
[ "public", "static", "boolean", "hasOneParentPerToken", "(", "int", "n", ",", "VarConfig", "vc", ")", "{", "int", "[", "]", "parents", "=", "new", "int", "[", "n", "]", ";", "Arrays", ".", "fill", "(", "parents", ",", "-", "2", ")", ";", "for", "(", "Var", "v", ":", "vc", ".", "getVars", "(", ")", ")", "{", "if", "(", "v", "instanceof", "LinkVar", ")", "{", "LinkVar", "link", "=", "(", "LinkVar", ")", "v", ";", "if", "(", "vc", ".", "getState", "(", "v", ")", "==", "LinkVar", ".", "TRUE", ")", "{", "if", "(", "parents", "[", "link", ".", "getChild", "(", ")", "]", "!=", "-", "2", ")", "{", "// Multiple parents defined for the same child.", "return", "false", ";", "}", "parents", "[", "link", ".", "getChild", "(", ")", "]", "=", "link", ".", "getParent", "(", ")", ";", "}", "}", "}", "return", "!", "ArrayUtils", ".", "contains", "(", "parents", ",", "-", "2", ")", ";", "}" ]
Returns whether this variable assignment specifies one parent per token.
[ "Returns", "whether", "this", "variable", "assignment", "specifies", "one", "parent", "per", "token", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/model/globalfac/ProjDepTreeFactor.java#L229-L245
glyptodon/guacamole-client
guacamole/src/main/java/org/apache/guacamole/tunnel/OutputStreamInterceptingFilter.java
OutputStreamInterceptingFilter.sendAck
private void sendAck(String index, String message, GuacamoleStatus status) { """ Injects an "ack" instruction into the outbound Guacamole protocol stream, as if sent by the connected client. "ack" instructions are used to acknowledge the receipt of a stream and its subsequent blobs, and are the only means of communicating success/failure status. @param index The index of the stream that this "ack" instruction relates to. @param message An arbitrary human-readable message to include within the "ack" instruction. @param status The status of the stream operation being acknowledged via the "ack" instruction. Error statuses will implicitly close the stream via closeStream(). """ // Error "ack" instructions implicitly close the stream if (status != GuacamoleStatus.SUCCESS) closeInterceptedStream(index); sendInstruction(new GuacamoleInstruction("ack", index, message, Integer.toString(status.getGuacamoleStatusCode()))); }
java
private void sendAck(String index, String message, GuacamoleStatus status) { // Error "ack" instructions implicitly close the stream if (status != GuacamoleStatus.SUCCESS) closeInterceptedStream(index); sendInstruction(new GuacamoleInstruction("ack", index, message, Integer.toString(status.getGuacamoleStatusCode()))); }
[ "private", "void", "sendAck", "(", "String", "index", ",", "String", "message", ",", "GuacamoleStatus", "status", ")", "{", "// Error \"ack\" instructions implicitly close the stream", "if", "(", "status", "!=", "GuacamoleStatus", ".", "SUCCESS", ")", "closeInterceptedStream", "(", "index", ")", ";", "sendInstruction", "(", "new", "GuacamoleInstruction", "(", "\"ack\"", ",", "index", ",", "message", ",", "Integer", ".", "toString", "(", "status", ".", "getGuacamoleStatusCode", "(", ")", ")", ")", ")", ";", "}" ]
Injects an "ack" instruction into the outbound Guacamole protocol stream, as if sent by the connected client. "ack" instructions are used to acknowledge the receipt of a stream and its subsequent blobs, and are the only means of communicating success/failure status. @param index The index of the stream that this "ack" instruction relates to. @param message An arbitrary human-readable message to include within the "ack" instruction. @param status The status of the stream operation being acknowledged via the "ack" instruction. Error statuses will implicitly close the stream via closeStream().
[ "Injects", "an", "ack", "instruction", "into", "the", "outbound", "Guacamole", "protocol", "stream", "as", "if", "sent", "by", "the", "connected", "client", ".", "ack", "instructions", "are", "used", "to", "acknowledge", "the", "receipt", "of", "a", "stream", "and", "its", "subsequent", "blobs", "and", "are", "the", "only", "means", "of", "communicating", "success", "/", "failure", "status", "." ]
train
https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole/src/main/java/org/apache/guacamole/tunnel/OutputStreamInterceptingFilter.java#L87-L96
agmip/agmip-common-functions
src/main/java/org/agmip/functions/PTSaxton2006.java
PTSaxton2006.calcSaturatedMoisture
public static String calcSaturatedMoisture(String slsnd, String slcly, String omPct) { """ Equation 5 for calculating Saturated moisture (0 kPa), normal density, %v @param slsnd Sand weight percentage by layer ([0,100]%) @param slcly Clay weight percentage by layer ([0,100]%) @param omPct Organic matter weight percentage by layer ([0,100]%), (= SLOC * 1.72) """ String mt33 = calcMoisture33Kpa(slsnd, slcly, omPct); String mtSAT33 = calcMoistureSAT33Kpa(slsnd, slcly, omPct); String ret = sum(mt33, mtSAT33, product(slsnd, "-0.097"), "4.3"); LOG.debug("Calculate result for Saturated moisture (0 kPa), normal density, %v is {}", ret); return ret; }
java
public static String calcSaturatedMoisture(String slsnd, String slcly, String omPct) { String mt33 = calcMoisture33Kpa(slsnd, slcly, omPct); String mtSAT33 = calcMoistureSAT33Kpa(slsnd, slcly, omPct); String ret = sum(mt33, mtSAT33, product(slsnd, "-0.097"), "4.3"); LOG.debug("Calculate result for Saturated moisture (0 kPa), normal density, %v is {}", ret); return ret; }
[ "public", "static", "String", "calcSaturatedMoisture", "(", "String", "slsnd", ",", "String", "slcly", ",", "String", "omPct", ")", "{", "String", "mt33", "=", "calcMoisture33Kpa", "(", "slsnd", ",", "slcly", ",", "omPct", ")", ";", "String", "mtSAT33", "=", "calcMoistureSAT33Kpa", "(", "slsnd", ",", "slcly", ",", "omPct", ")", ";", "String", "ret", "=", "sum", "(", "mt33", ",", "mtSAT33", ",", "product", "(", "slsnd", ",", "\"-0.097\"", ")", ",", "\"4.3\"", ")", ";", "LOG", ".", "debug", "(", "\"Calculate result for Saturated moisture (0 kPa), normal density, %v is {}\"", ",", "ret", ")", ";", "return", "ret", ";", "}" ]
Equation 5 for calculating Saturated moisture (0 kPa), normal density, %v @param slsnd Sand weight percentage by layer ([0,100]%) @param slcly Clay weight percentage by layer ([0,100]%) @param omPct Organic matter weight percentage by layer ([0,100]%), (= SLOC * 1.72)
[ "Equation", "5", "for", "calculating", "Saturated", "moisture", "(", "0", "kPa", ")", "normal", "density", "%v" ]
train
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/PTSaxton2006.java#L207-L215
Azure/azure-sdk-for-java
marketplaceordering/resource-manager/v2015_06_01/src/main/java/com/microsoft/azure/management/marketplaceordering/v2015_06_01/implementation/MarketplaceAgreementsInner.java
MarketplaceAgreementsInner.getAgreement
public AgreementTermsInner getAgreement(String publisherId, String offerId, String planId) { """ Get marketplace agreement. @param publisherId Publisher identifier string of image being deployed. @param offerId Offer identifier string of image being deployed. @param planId Plan identifier string of image being deployed. @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 AgreementTermsInner object if successful. """ return getAgreementWithServiceResponseAsync(publisherId, offerId, planId).toBlocking().single().body(); }
java
public AgreementTermsInner getAgreement(String publisherId, String offerId, String planId) { return getAgreementWithServiceResponseAsync(publisherId, offerId, planId).toBlocking().single().body(); }
[ "public", "AgreementTermsInner", "getAgreement", "(", "String", "publisherId", ",", "String", "offerId", ",", "String", "planId", ")", "{", "return", "getAgreementWithServiceResponseAsync", "(", "publisherId", ",", "offerId", ",", "planId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Get marketplace agreement. @param publisherId Publisher identifier string of image being deployed. @param offerId Offer identifier string of image being deployed. @param planId Plan identifier string of image being deployed. @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 AgreementTermsInner object if successful.
[ "Get", "marketplace", "agreement", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/marketplaceordering/resource-manager/v2015_06_01/src/main/java/com/microsoft/azure/management/marketplaceordering/v2015_06_01/implementation/MarketplaceAgreementsInner.java#L481-L483
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/utils/JaxWsUtils.java
JaxWsUtils.matchesQName
public static boolean matchesQName(QName regQName, QName targetQName, boolean ignorePrefix) { """ Check whether the regQName matches the targetQName Only the localPart of the regQName supports the * match, it means only the name space and prefix is all matched, then the localPart will be compared considering the * When the ignorePrefix is true, the prefix will be ignored. @param regQName @param targetQName @param ignorePrefix @return """ if (regQName == null || targetQName == null) { return false; } if ("*".equals(getQNameString(regQName))) { return true; } // if the name space or the prefix is not equal, just return false; if (!(regQName.getNamespaceURI().equals(targetQName.getNamespaceURI())) || !(ignorePrefix || regQName.getPrefix().equals(targetQName.getPrefix()))) { return false; } if (regQName.getLocalPart().contains("*")) { return Pattern.matches(mapPattern(regQName.getLocalPart()), targetQName.getLocalPart()); } else if (regQName.getLocalPart().equals(targetQName.getLocalPart())) { return true; } return false; }
java
public static boolean matchesQName(QName regQName, QName targetQName, boolean ignorePrefix) { if (regQName == null || targetQName == null) { return false; } if ("*".equals(getQNameString(regQName))) { return true; } // if the name space or the prefix is not equal, just return false; if (!(regQName.getNamespaceURI().equals(targetQName.getNamespaceURI())) || !(ignorePrefix || regQName.getPrefix().equals(targetQName.getPrefix()))) { return false; } if (regQName.getLocalPart().contains("*")) { return Pattern.matches(mapPattern(regQName.getLocalPart()), targetQName.getLocalPart()); } else if (regQName.getLocalPart().equals(targetQName.getLocalPart())) { return true; } return false; }
[ "public", "static", "boolean", "matchesQName", "(", "QName", "regQName", ",", "QName", "targetQName", ",", "boolean", "ignorePrefix", ")", "{", "if", "(", "regQName", "==", "null", "||", "targetQName", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "\"*\"", ".", "equals", "(", "getQNameString", "(", "regQName", ")", ")", ")", "{", "return", "true", ";", "}", "// if the name space or the prefix is not equal, just return false;", "if", "(", "!", "(", "regQName", ".", "getNamespaceURI", "(", ")", ".", "equals", "(", "targetQName", ".", "getNamespaceURI", "(", ")", ")", ")", "||", "!", "(", "ignorePrefix", "||", "regQName", ".", "getPrefix", "(", ")", ".", "equals", "(", "targetQName", ".", "getPrefix", "(", ")", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "regQName", ".", "getLocalPart", "(", ")", ".", "contains", "(", "\"*\"", ")", ")", "{", "return", "Pattern", ".", "matches", "(", "mapPattern", "(", "regQName", ".", "getLocalPart", "(", ")", ")", ",", "targetQName", ".", "getLocalPart", "(", ")", ")", ";", "}", "else", "if", "(", "regQName", ".", "getLocalPart", "(", ")", ".", "equals", "(", "targetQName", ".", "getLocalPart", "(", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check whether the regQName matches the targetQName Only the localPart of the regQName supports the * match, it means only the name space and prefix is all matched, then the localPart will be compared considering the * When the ignorePrefix is true, the prefix will be ignored. @param regQName @param targetQName @param ignorePrefix @return
[ "Check", "whether", "the", "regQName", "matches", "the", "targetQName" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/utils/JaxWsUtils.java#L490-L509
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkGatewayConnectionsInner.java
VirtualNetworkGatewayConnectionsInner.setSharedKey
public ConnectionSharedKeyInner setSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) { """ The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The virtual network gateway connection name. @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider. @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 ConnectionSharedKeyInner object if successful. """ return setSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().last().body(); }
java
public ConnectionSharedKeyInner setSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) { return setSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().last().body(); }
[ "public", "ConnectionSharedKeyInner", "setSharedKey", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayConnectionName", ",", "ConnectionSharedKeyInner", "parameters", ")", "{", "return", "setSharedKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayConnectionName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The virtual network gateway connection name. @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider. @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 ConnectionSharedKeyInner object if successful.
[ "The", "Put", "VirtualNetworkGatewayConnectionSharedKey", "operation", "sets", "the", "virtual", "network", "gateway", "connection", "shared", "key", "for", "passed", "virtual", "network", "gateway", "connection", "in", "the", "specified", "resource", "group", "through", "Network", "resource", "provider", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkGatewayConnectionsInner.java#L856-L858
lightblueseas/vintage-time
src/main/java/de/alpharogroup/date/ParseDateExtensions.java
ParseDateExtensions.parseDate
public static Date parseDate(final String date, final List<String> patterns) { """ Tries to convert the given String to a Date. @param date The date to convert as String. @param patterns The date patterns to convert the String to a date-object. @return Gives a Date if the convertion was successfull otherwise null. """ for (final String pattern : patterns) { final SimpleDateFormat formatter = new SimpleDateFormat(pattern); try { return formatter.parse(date); } catch (final ParseException e) { // Do nothing... } } return null; }
java
public static Date parseDate(final String date, final List<String> patterns) { for (final String pattern : patterns) { final SimpleDateFormat formatter = new SimpleDateFormat(pattern); try { return formatter.parse(date); } catch (final ParseException e) { // Do nothing... } } return null; }
[ "public", "static", "Date", "parseDate", "(", "final", "String", "date", ",", "final", "List", "<", "String", ">", "patterns", ")", "{", "for", "(", "final", "String", "pattern", ":", "patterns", ")", "{", "final", "SimpleDateFormat", "formatter", "=", "new", "SimpleDateFormat", "(", "pattern", ")", ";", "try", "{", "return", "formatter", ".", "parse", "(", "date", ")", ";", "}", "catch", "(", "final", "ParseException", "e", ")", "{", "// Do nothing...", "}", "}", "return", "null", ";", "}" ]
Tries to convert the given String to a Date. @param date The date to convert as String. @param patterns The date patterns to convert the String to a date-object. @return Gives a Date if the convertion was successfull otherwise null.
[ "Tries", "to", "convert", "the", "given", "String", "to", "a", "Date", "." ]
train
https://github.com/lightblueseas/vintage-time/blob/fbf201e679d9f9b92e7b5771f3eea1413cc2e113/src/main/java/de/alpharogroup/date/ParseDateExtensions.java#L56-L71
OpenFeign/feign
core/src/main/java/feign/Request.java
Request.create
public static Request create(HttpMethod httpMethod, String url, Map<String, Collection<String>> headers, Body body) { """ Builds a Request. All parameters must be effectively immutable, via safe copies. @param httpMethod for the request. @param url for the request. @param headers to include. @param body of the request, can be {@literal null} @return a Request """ return new Request(httpMethod, url, headers, body); }
java
public static Request create(HttpMethod httpMethod, String url, Map<String, Collection<String>> headers, Body body) { return new Request(httpMethod, url, headers, body); }
[ "public", "static", "Request", "create", "(", "HttpMethod", "httpMethod", ",", "String", "url", ",", "Map", "<", "String", ",", "Collection", "<", "String", ">", ">", "headers", ",", "Body", "body", ")", "{", "return", "new", "Request", "(", "httpMethod", ",", "url", ",", "headers", ",", "body", ")", ";", "}" ]
Builds a Request. All parameters must be effectively immutable, via safe copies. @param httpMethod for the request. @param url for the request. @param headers to include. @param body of the request, can be {@literal null} @return a Request
[ "Builds", "a", "Request", ".", "All", "parameters", "must", "be", "effectively", "immutable", "via", "safe", "copies", "." ]
train
https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/Request.java#L134-L139
apache/incubator-heron
heron/api/src/java/org/apache/heron/streamlet/impl/streamlets/CustomStreamlet.java
CustomStreamlet.doBuild
@Override public boolean doBuild(TopologyBuilder bldr, Set<String> stageNames) { """ Connect this streamlet to TopologyBuilder. @param bldr The TopologyBuilder for the topology @param stageNames The existing stage names @return True if successful """ // Create and set bolt BoltDeclarer declarer; if (operator instanceof IStreamletBasicOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM, stageNames); IStreamletBasicOperator<R, T> op = (IStreamletBasicOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletRichOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_BASIC, stageNames); IStreamletRichOperator<R, T> op = (IStreamletRichOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletWindowOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_WINDOW, stageNames); IStreamletWindowOperator<R, T> op = (IStreamletWindowOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else { throw new RuntimeException("Unhandled operator class is found!"); } return true; }
java
@Override public boolean doBuild(TopologyBuilder bldr, Set<String> stageNames) { // Create and set bolt BoltDeclarer declarer; if (operator instanceof IStreamletBasicOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM, stageNames); IStreamletBasicOperator<R, T> op = (IStreamletBasicOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletRichOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_BASIC, stageNames); IStreamletRichOperator<R, T> op = (IStreamletRichOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletWindowOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_WINDOW, stageNames); IStreamletWindowOperator<R, T> op = (IStreamletWindowOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else { throw new RuntimeException("Unhandled operator class is found!"); } return true; }
[ "@", "Override", "public", "boolean", "doBuild", "(", "TopologyBuilder", "bldr", ",", "Set", "<", "String", ">", "stageNames", ")", "{", "// Create and set bolt", "BoltDeclarer", "declarer", ";", "if", "(", "operator", "instanceof", "IStreamletBasicOperator", ")", "{", "setDefaultNameIfNone", "(", "StreamletNamePrefix", ".", "CUSTOM", ",", "stageNames", ")", ";", "IStreamletBasicOperator", "<", "R", ",", "T", ">", "op", "=", "(", "IStreamletBasicOperator", "<", "R", ",", "T", ">", ")", "operator", ";", "bldr", ".", "setBolt", "(", "getName", "(", ")", ",", "op", ",", "getNumPartitions", "(", ")", ")", ".", "grouping", "(", "parent", ".", "getName", "(", ")", ",", "parent", ".", "getStreamId", "(", ")", ",", "grouper", ")", ";", "}", "else", "if", "(", "operator", "instanceof", "IStreamletRichOperator", ")", "{", "setDefaultNameIfNone", "(", "StreamletNamePrefix", ".", "CUSTOM_BASIC", ",", "stageNames", ")", ";", "IStreamletRichOperator", "<", "R", ",", "T", ">", "op", "=", "(", "IStreamletRichOperator", "<", "R", ",", "T", ">", ")", "operator", ";", "bldr", ".", "setBolt", "(", "getName", "(", ")", ",", "op", ",", "getNumPartitions", "(", ")", ")", ".", "grouping", "(", "parent", ".", "getName", "(", ")", ",", "parent", ".", "getStreamId", "(", ")", ",", "grouper", ")", ";", "}", "else", "if", "(", "operator", "instanceof", "IStreamletWindowOperator", ")", "{", "setDefaultNameIfNone", "(", "StreamletNamePrefix", ".", "CUSTOM_WINDOW", ",", "stageNames", ")", ";", "IStreamletWindowOperator", "<", "R", ",", "T", ">", "op", "=", "(", "IStreamletWindowOperator", "<", "R", ",", "T", ">", ")", "operator", ";", "bldr", ".", "setBolt", "(", "getName", "(", ")", ",", "op", ",", "getNumPartitions", "(", ")", ")", ".", "grouping", "(", "parent", ".", "getName", "(", ")", ",", "parent", ".", "getStreamId", "(", ")", ",", "grouper", ")", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Unhandled operator class is found!\"", ")", ";", "}", "return", "true", ";", "}" ]
Connect this streamlet to TopologyBuilder. @param bldr The TopologyBuilder for the topology @param stageNames The existing stage names @return True if successful
[ "Connect", "this", "streamlet", "to", "TopologyBuilder", "." ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/streamlets/CustomStreamlet.java#L63-L87
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addSuccessUploadDesignFile
public FessMessages addSuccessUploadDesignFile(String property, String arg0) { """ Add the created action message for the key 'success.upload_design_file' with parameters. <pre> message: Uploaded {0}. </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @return this. (NotNull) """ assertPropertyNotNull(property); add(property, new UserMessage(SUCCESS_upload_design_file, arg0)); return this; }
java
public FessMessages addSuccessUploadDesignFile(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(SUCCESS_upload_design_file, arg0)); return this; }
[ "public", "FessMessages", "addSuccessUploadDesignFile", "(", "String", "property", ",", "String", "arg0", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "SUCCESS_upload_design_file", ",", "arg0", ")", ")", ";", "return", "this", ";", "}" ]
Add the created action message for the key 'success.upload_design_file' with parameters. <pre> message: Uploaded {0}. </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "success", ".", "upload_design_file", "with", "parameters", ".", "<pre", ">", "message", ":", "Uploaded", "{", "0", "}", ".", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L2331-L2335
NoraUi/NoraUi
src/main/java/com/github/noraui/browser/steps/BrowserSteps.java
BrowserSteps.closeWindowAndSwitchTo
@Conditioned @Lorsque("Je ferme la fenêtre actuelle et passe à la fenêtre '(.*)'[\\.|\\?]") @Then("I close current window and switch to '(.*)' window[\\.|\\?]") public void closeWindowAndSwitchTo(String key, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException { """ Closes window and switches to target window with conditions. @param key is the key of application (Ex: SALTO). @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_CLOSE_APP} message (with screenshot, no exception) @throws FailureException if the scenario encounters a functional error """ closeWindowAndSwitchTo(key); }
java
@Conditioned @Lorsque("Je ferme la fenêtre actuelle et passe à la fenêtre '(.*)'[\\.|\\?]") @Then("I close current window and switch to '(.*)' window[\\.|\\?]") public void closeWindowAndSwitchTo(String key, List<GherkinStepCondition> conditions) throws TechnicalException, FailureException { closeWindowAndSwitchTo(key); }
[ "@", "Conditioned", "@", "Lorsque", "(", "\"Je ferme la fenêtre actuelle et passe à la fenêtre '(.*)'[\\\\.|\\\\?]\")\r", "", "@", "Then", "(", "\"I close current window and switch to '(.*)' window[\\\\.|\\\\?]\"", ")", "public", "void", "closeWindowAndSwitchTo", "(", "String", "key", ",", "List", "<", "GherkinStepCondition", ">", "conditions", ")", "throws", "TechnicalException", ",", "FailureException", "{", "closeWindowAndSwitchTo", "(", "key", ")", ";", "}" ]
Closes window and switches to target window with conditions. @param key is the key of application (Ex: SALTO). @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_CLOSE_APP} message (with screenshot, no exception) @throws FailureException if the scenario encounters a functional error
[ "Closes", "window", "and", "switches", "to", "target", "window", "with", "conditions", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/browser/steps/BrowserSteps.java#L146-L151
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/categories/date.java
date.formatDate
public static String formatDate(long date, String format, String timeZone) { """ Gets a date with a desired format as a String @param date date to be formated @param format desired format (e.g. "yyyy-MM-dd HH:mm:ss") @param timeZone specify the intended timezone (e.g. "GMT", "UTC", etc.) @return returns a date with the given format """ return formatDateBase(date, format, timeZone); }
java
public static String formatDate(long date, String format, String timeZone) { return formatDateBase(date, format, timeZone); }
[ "public", "static", "String", "formatDate", "(", "long", "date", ",", "String", "format", ",", "String", "timeZone", ")", "{", "return", "formatDateBase", "(", "date", ",", "format", ",", "timeZone", ")", ";", "}" ]
Gets a date with a desired format as a String @param date date to be formated @param format desired format (e.g. "yyyy-MM-dd HH:mm:ss") @param timeZone specify the intended timezone (e.g. "GMT", "UTC", etc.) @return returns a date with the given format
[ "Gets", "a", "date", "with", "a", "desired", "format", "as", "a", "String" ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/date.java#L111-L114
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/zip/ZipExtensions.java
ZipExtensions.addFile
private static void addFile(final File file, final File dirToZip, final ZipOutputStream zos) throws IOException { """ Adds the file. @param file the file @param dirToZip the dir to zip @param zos the zos @throws IOException Signals that an I/O exception has occurred. """ final String absolutePath = file.getAbsolutePath(); final int index = absolutePath.indexOf(dirToZip.getName()); final String zipEntryName = absolutePath.substring(index, absolutePath.length()); final byte[] b = new byte[(int)file.length()]; final ZipEntry cpZipEntry = new ZipEntry(zipEntryName); zos.putNextEntry(cpZipEntry); zos.write(b, 0, (int)file.length()); zos.closeEntry(); }
java
private static void addFile(final File file, final File dirToZip, final ZipOutputStream zos) throws IOException { final String absolutePath = file.getAbsolutePath(); final int index = absolutePath.indexOf(dirToZip.getName()); final String zipEntryName = absolutePath.substring(index, absolutePath.length()); final byte[] b = new byte[(int)file.length()]; final ZipEntry cpZipEntry = new ZipEntry(zipEntryName); zos.putNextEntry(cpZipEntry); zos.write(b, 0, (int)file.length()); zos.closeEntry(); }
[ "private", "static", "void", "addFile", "(", "final", "File", "file", ",", "final", "File", "dirToZip", ",", "final", "ZipOutputStream", "zos", ")", "throws", "IOException", "{", "final", "String", "absolutePath", "=", "file", ".", "getAbsolutePath", "(", ")", ";", "final", "int", "index", "=", "absolutePath", ".", "indexOf", "(", "dirToZip", ".", "getName", "(", ")", ")", ";", "final", "String", "zipEntryName", "=", "absolutePath", ".", "substring", "(", "index", ",", "absolutePath", ".", "length", "(", ")", ")", ";", "final", "byte", "[", "]", "b", "=", "new", "byte", "[", "(", "int", ")", "file", ".", "length", "(", ")", "]", ";", "final", "ZipEntry", "cpZipEntry", "=", "new", "ZipEntry", "(", "zipEntryName", ")", ";", "zos", ".", "putNextEntry", "(", "cpZipEntry", ")", ";", "zos", ".", "write", "(", "b", ",", "0", ",", "(", "int", ")", "file", ".", "length", "(", ")", ")", ";", "zos", ".", "closeEntry", "(", ")", ";", "}" ]
Adds the file. @param file the file @param dirToZip the dir to zip @param zos the zos @throws IOException Signals that an I/O exception has occurred.
[ "Adds", "the", "file", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/zip/ZipExtensions.java#L69-L80
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/QuantityFormatter.java
QuantityFormatter.addIfAbsent
public void addIfAbsent(CharSequence variant, String template) { """ Adds a template if there is none yet for the plural form. @param variant the plural variant, e.g "zero", "one", "two", "few", "many", "other" @param template the text for that plural variant with "{0}" as the quantity. For example, in English, the template for the "one" variant may be "{0} apple" while the template for the "other" variant may be "{0} apples" @throws IllegalArgumentException if variant is not recognized or if template has more than just the {0} placeholder. """ int idx = StandardPlural.indexFromString(variant); if (templates[idx] != null) { return; } templates[idx] = SimpleFormatter.compileMinMaxArguments(template, 0, 1); }
java
public void addIfAbsent(CharSequence variant, String template) { int idx = StandardPlural.indexFromString(variant); if (templates[idx] != null) { return; } templates[idx] = SimpleFormatter.compileMinMaxArguments(template, 0, 1); }
[ "public", "void", "addIfAbsent", "(", "CharSequence", "variant", ",", "String", "template", ")", "{", "int", "idx", "=", "StandardPlural", ".", "indexFromString", "(", "variant", ")", ";", "if", "(", "templates", "[", "idx", "]", "!=", "null", ")", "{", "return", ";", "}", "templates", "[", "idx", "]", "=", "SimpleFormatter", ".", "compileMinMaxArguments", "(", "template", ",", "0", ",", "1", ")", ";", "}" ]
Adds a template if there is none yet for the plural form. @param variant the plural variant, e.g "zero", "one", "two", "few", "many", "other" @param template the text for that plural variant with "{0}" as the quantity. For example, in English, the template for the "one" variant may be "{0} apple" while the template for the "other" variant may be "{0} apples" @throws IllegalArgumentException if variant is not recognized or if template has more than just the {0} placeholder.
[ "Adds", "a", "template", "if", "there", "is", "none", "yet", "for", "the", "plural", "form", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/QuantityFormatter.java#L42-L48
cdapio/netty-http
src/main/java/io/cdap/http/NettyHttpService.java
NettyHttpService.createEventExecutorGroup
@Nullable private EventExecutorGroup createEventExecutorGroup(int size) { """ Create {@link EventExecutorGroup} for executing handle methods. @param size size of threadPool @return instance of {@link EventExecutorGroup} or {@code null} if {@code size} is {@code <= 0}. """ if (size <= 0) { return null; } ThreadFactory threadFactory = new ThreadFactory() { private final ThreadGroup threadGroup = new ThreadGroup(serviceName + "-executor-thread"); private final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(threadGroup, r, String.format("%s-executor-%d", serviceName, count.getAndIncrement())); t.setDaemon(true); return t; } }; UnorderedThreadPoolEventExecutor executor = new UnorderedThreadPoolEventExecutor(size, threadFactory, rejectedExecutionHandler); if (execThreadKeepAliveSecs > 0) { executor.setKeepAliveTime(execThreadKeepAliveSecs, TimeUnit.SECONDS); executor.allowCoreThreadTimeOut(true); } return new NonStickyEventExecutorGroup(executor); }
java
@Nullable private EventExecutorGroup createEventExecutorGroup(int size) { if (size <= 0) { return null; } ThreadFactory threadFactory = new ThreadFactory() { private final ThreadGroup threadGroup = new ThreadGroup(serviceName + "-executor-thread"); private final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(threadGroup, r, String.format("%s-executor-%d", serviceName, count.getAndIncrement())); t.setDaemon(true); return t; } }; UnorderedThreadPoolEventExecutor executor = new UnorderedThreadPoolEventExecutor(size, threadFactory, rejectedExecutionHandler); if (execThreadKeepAliveSecs > 0) { executor.setKeepAliveTime(execThreadKeepAliveSecs, TimeUnit.SECONDS); executor.allowCoreThreadTimeOut(true); } return new NonStickyEventExecutorGroup(executor); }
[ "@", "Nullable", "private", "EventExecutorGroup", "createEventExecutorGroup", "(", "int", "size", ")", "{", "if", "(", "size", "<=", "0", ")", "{", "return", "null", ";", "}", "ThreadFactory", "threadFactory", "=", "new", "ThreadFactory", "(", ")", "{", "private", "final", "ThreadGroup", "threadGroup", "=", "new", "ThreadGroup", "(", "serviceName", "+", "\"-executor-thread\"", ")", ";", "private", "final", "AtomicLong", "count", "=", "new", "AtomicLong", "(", "0", ")", ";", "@", "Override", "public", "Thread", "newThread", "(", "Runnable", "r", ")", "{", "Thread", "t", "=", "new", "Thread", "(", "threadGroup", ",", "r", ",", "String", ".", "format", "(", "\"%s-executor-%d\"", ",", "serviceName", ",", "count", ".", "getAndIncrement", "(", ")", ")", ")", ";", "t", ".", "setDaemon", "(", "true", ")", ";", "return", "t", ";", "}", "}", ";", "UnorderedThreadPoolEventExecutor", "executor", "=", "new", "UnorderedThreadPoolEventExecutor", "(", "size", ",", "threadFactory", ",", "rejectedExecutionHandler", ")", ";", "if", "(", "execThreadKeepAliveSecs", ">", "0", ")", "{", "executor", ".", "setKeepAliveTime", "(", "execThreadKeepAliveSecs", ",", "TimeUnit", ".", "SECONDS", ")", ";", "executor", ".", "allowCoreThreadTimeOut", "(", "true", ")", ";", "}", "return", "new", "NonStickyEventExecutorGroup", "(", "executor", ")", ";", "}" ]
Create {@link EventExecutorGroup} for executing handle methods. @param size size of threadPool @return instance of {@link EventExecutorGroup} or {@code null} if {@code size} is {@code <= 0}.
[ "Create", "{", "@link", "EventExecutorGroup", "}", "for", "executing", "handle", "methods", "." ]
train
https://github.com/cdapio/netty-http/blob/02fdbb45bdd51d3dd58c0efbb2f27195d265cd0f/src/main/java/io/cdap/http/NettyHttpService.java#L270-L295
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementPlugin.java
ElementPlugin.unregisterListener
public void unregisterListener(IPluginEventListener listener) { """ Unregisters a listener for the IPluginEvent callback event. @param listener Listener to be unregistered. """ if (pluginEventListeners2 != null && pluginEventListeners2.contains(listener)) { pluginEventListeners2.remove(listener); listener.onPluginEvent(new PluginEvent(this, PluginAction.UNSUBSCRIBE)); } }
java
public void unregisterListener(IPluginEventListener listener) { if (pluginEventListeners2 != null && pluginEventListeners2.contains(listener)) { pluginEventListeners2.remove(listener); listener.onPluginEvent(new PluginEvent(this, PluginAction.UNSUBSCRIBE)); } }
[ "public", "void", "unregisterListener", "(", "IPluginEventListener", "listener", ")", "{", "if", "(", "pluginEventListeners2", "!=", "null", "&&", "pluginEventListeners2", ".", "contains", "(", "listener", ")", ")", "{", "pluginEventListeners2", ".", "remove", "(", "listener", ")", ";", "listener", ".", "onPluginEvent", "(", "new", "PluginEvent", "(", "this", ",", "PluginAction", ".", "UNSUBSCRIBE", ")", ")", ";", "}", "}" ]
Unregisters a listener for the IPluginEvent callback event. @param listener Listener to be unregistered.
[ "Unregisters", "a", "listener", "for", "the", "IPluginEvent", "callback", "event", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementPlugin.java#L690-L695
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressPersistenceImpl.java
CommerceAddressPersistenceImpl.removeByC_C
@Override public void removeByC_C(long classNameId, long classPK) { """ Removes all the commerce addresses where classNameId = &#63; and classPK = &#63; from the database. @param classNameId the class name ID @param classPK the class pk """ for (CommerceAddress commerceAddress : findByC_C(classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceAddress); } }
java
@Override public void removeByC_C(long classNameId, long classPK) { for (CommerceAddress commerceAddress : findByC_C(classNameId, classPK, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceAddress); } }
[ "@", "Override", "public", "void", "removeByC_C", "(", "long", "classNameId", ",", "long", "classPK", ")", "{", "for", "(", "CommerceAddress", "commerceAddress", ":", "findByC_C", "(", "classNameId", ",", "classPK", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "commerceAddress", ")", ";", "}", "}" ]
Removes all the commerce addresses where classNameId = &#63; and classPK = &#63; from the database. @param classNameId the class name ID @param classPK the class pk
[ "Removes", "all", "the", "commerce", "addresses", "where", "classNameId", "=", "&#63", ";", "and", "classPK", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressPersistenceImpl.java#L1615-L1621
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/ZoneId.java
ZoneId.getDisplayName
public String getDisplayName(TextStyle style, Locale locale) { """ Gets the textual representation of the zone, such as 'British Time' or '+02:00'. <p> This returns the textual name used to identify the time-zone ID, suitable for presentation to the user. The parameters control the style of the returned text and the locale. <p> If no textual mapping is found then the {@link #getId() full ID} is returned. @param style the length of the text required, not null @param locale the locale to use, not null @return the text value of the zone, not null """ return new DateTimeFormatterBuilder().appendZoneText(style).toFormatter(locale).format(toTemporal()); }
java
public String getDisplayName(TextStyle style, Locale locale) { return new DateTimeFormatterBuilder().appendZoneText(style).toFormatter(locale).format(toTemporal()); }
[ "public", "String", "getDisplayName", "(", "TextStyle", "style", ",", "Locale", "locale", ")", "{", "return", "new", "DateTimeFormatterBuilder", "(", ")", ".", "appendZoneText", "(", "style", ")", ".", "toFormatter", "(", "locale", ")", ".", "format", "(", "toTemporal", "(", ")", ")", ";", "}" ]
Gets the textual representation of the zone, such as 'British Time' or '+02:00'. <p> This returns the textual name used to identify the time-zone ID, suitable for presentation to the user. The parameters control the style of the returned text and the locale. <p> If no textual mapping is found then the {@link #getId() full ID} is returned. @param style the length of the text required, not null @param locale the locale to use, not null @return the text value of the zone, not null
[ "Gets", "the", "textual", "representation", "of", "the", "zone", "such", "as", "British", "Time", "or", "+", "02", ":", "00", ".", "<p", ">", "This", "returns", "the", "textual", "name", "used", "to", "identify", "the", "time", "-", "zone", "ID", "suitable", "for", "presentation", "to", "the", "user", ".", "The", "parameters", "control", "the", "style", "of", "the", "returned", "text", "and", "the", "locale", ".", "<p", ">", "If", "no", "textual", "mapping", "is", "found", "then", "the", "{", "@link", "#getId", "()", "full", "ID", "}", "is", "returned", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/ZoneId.java#L515-L517
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/sftp/SftpFsHelper.java
SftpFsHelper.getFileStream
@Override public InputStream getFileStream(String file) throws FileBasedHelperException { """ Executes a get SftpCommand and returns an input stream to the file @param cmd is the command to execute @param sftp is the channel to execute the command on @throws SftpException """ SftpGetMonitor monitor = new SftpGetMonitor(); try { ChannelSftp channel = getSftpChannel(); return new SftpFsFileInputStream(channel.get(file, monitor), channel); } catch (SftpException e) { throw new FileBasedHelperException("Cannot download file " + file + " due to " + e.getMessage(), e); } }
java
@Override public InputStream getFileStream(String file) throws FileBasedHelperException { SftpGetMonitor monitor = new SftpGetMonitor(); try { ChannelSftp channel = getSftpChannel(); return new SftpFsFileInputStream(channel.get(file, monitor), channel); } catch (SftpException e) { throw new FileBasedHelperException("Cannot download file " + file + " due to " + e.getMessage(), e); } }
[ "@", "Override", "public", "InputStream", "getFileStream", "(", "String", "file", ")", "throws", "FileBasedHelperException", "{", "SftpGetMonitor", "monitor", "=", "new", "SftpGetMonitor", "(", ")", ";", "try", "{", "ChannelSftp", "channel", "=", "getSftpChannel", "(", ")", ";", "return", "new", "SftpFsFileInputStream", "(", "channel", ".", "get", "(", "file", ",", "monitor", ")", ",", "channel", ")", ";", "}", "catch", "(", "SftpException", "e", ")", "{", "throw", "new", "FileBasedHelperException", "(", "\"Cannot download file \"", "+", "file", "+", "\" due to \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Executes a get SftpCommand and returns an input stream to the file @param cmd is the command to execute @param sftp is the channel to execute the command on @throws SftpException
[ "Executes", "a", "get", "SftpCommand", "and", "returns", "an", "input", "stream", "to", "the", "file" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/sftp/SftpFsHelper.java#L209-L218
alkacon/opencms-core
src/org/opencms/widgets/CmsMultiSelectGroupWidget.java
CmsMultiSelectGroupWidget.parseConfiguration
private void parseConfiguration(CmsObject cms, CmsMessages widgetDialog) { """ Parses the widget configuration string.<p> @param cms the current users OpenCms context @param widgetDialog the dialog of this widget """ String configString = CmsMacroResolver.resolveMacros(getConfiguration(), cms, widgetDialog); Map<String, String> config = CmsStringUtil.splitAsMap(configString, "|", "="); // get the list of group names to show String groups = config.get(CONFIGURATION_GROUPS); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(groups)) { m_groupNames = CmsStringUtil.splitAsList(groups, ',', true); } // get the regular expression to filter the groups String filter = config.get(CONFIGURATION_GROUPFILTER); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) { try { m_groupFilter = Pattern.compile(filter); } catch (PatternSyntaxException e) { // log pattern syntax errors LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_WIDGET_SELECTGROUP_PATTERN_1, filter)); } } // get the OU to read the groups from m_ouFqn = config.get(CONFIGURATION_OUFQN); if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_ouFqn)) { m_ouFqn = ""; } else if (!m_ouFqn.endsWith(CmsOrganizationalUnit.SEPARATOR)) { m_ouFqn += CmsOrganizationalUnit.SEPARATOR; } // set the flag to include sub OUs m_includeSubOus = Boolean.parseBoolean(config.get(CONFIGURATION_INCLUDESUBOUS)); m_defaultAllAvailable = Boolean.parseBoolean(config.get(CONFIGURATION_DEFAULT_ALL)); }
java
private void parseConfiguration(CmsObject cms, CmsMessages widgetDialog) { String configString = CmsMacroResolver.resolveMacros(getConfiguration(), cms, widgetDialog); Map<String, String> config = CmsStringUtil.splitAsMap(configString, "|", "="); // get the list of group names to show String groups = config.get(CONFIGURATION_GROUPS); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(groups)) { m_groupNames = CmsStringUtil.splitAsList(groups, ',', true); } // get the regular expression to filter the groups String filter = config.get(CONFIGURATION_GROUPFILTER); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) { try { m_groupFilter = Pattern.compile(filter); } catch (PatternSyntaxException e) { // log pattern syntax errors LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_WIDGET_SELECTGROUP_PATTERN_1, filter)); } } // get the OU to read the groups from m_ouFqn = config.get(CONFIGURATION_OUFQN); if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_ouFqn)) { m_ouFqn = ""; } else if (!m_ouFqn.endsWith(CmsOrganizationalUnit.SEPARATOR)) { m_ouFqn += CmsOrganizationalUnit.SEPARATOR; } // set the flag to include sub OUs m_includeSubOus = Boolean.parseBoolean(config.get(CONFIGURATION_INCLUDESUBOUS)); m_defaultAllAvailable = Boolean.parseBoolean(config.get(CONFIGURATION_DEFAULT_ALL)); }
[ "private", "void", "parseConfiguration", "(", "CmsObject", "cms", ",", "CmsMessages", "widgetDialog", ")", "{", "String", "configString", "=", "CmsMacroResolver", ".", "resolveMacros", "(", "getConfiguration", "(", ")", ",", "cms", ",", "widgetDialog", ")", ";", "Map", "<", "String", ",", "String", ">", "config", "=", "CmsStringUtil", ".", "splitAsMap", "(", "configString", ",", "\"|\"", ",", "\"=\"", ")", ";", "// get the list of group names to show\r", "String", "groups", "=", "config", ".", "get", "(", "CONFIGURATION_GROUPS", ")", ";", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "groups", ")", ")", "{", "m_groupNames", "=", "CmsStringUtil", ".", "splitAsList", "(", "groups", ",", "'", "'", ",", "true", ")", ";", "}", "// get the regular expression to filter the groups\r", "String", "filter", "=", "config", ".", "get", "(", "CONFIGURATION_GROUPFILTER", ")", ";", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "filter", ")", ")", "{", "try", "{", "m_groupFilter", "=", "Pattern", ".", "compile", "(", "filter", ")", ";", "}", "catch", "(", "PatternSyntaxException", "e", ")", "{", "// log pattern syntax errors\r", "LOG", ".", "error", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_ERR_WIDGET_SELECTGROUP_PATTERN_1", ",", "filter", ")", ")", ";", "}", "}", "// get the OU to read the groups from\r", "m_ouFqn", "=", "config", ".", "get", "(", "CONFIGURATION_OUFQN", ")", ";", "if", "(", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "m_ouFqn", ")", ")", "{", "m_ouFqn", "=", "\"\"", ";", "}", "else", "if", "(", "!", "m_ouFqn", ".", "endsWith", "(", "CmsOrganizationalUnit", ".", "SEPARATOR", ")", ")", "{", "m_ouFqn", "+=", "CmsOrganizationalUnit", ".", "SEPARATOR", ";", "}", "// set the flag to include sub OUs\r", "m_includeSubOus", "=", "Boolean", ".", "parseBoolean", "(", "config", ".", "get", "(", "CONFIGURATION_INCLUDESUBOUS", ")", ")", ";", "m_defaultAllAvailable", "=", "Boolean", ".", "parseBoolean", "(", "config", ".", "get", "(", "CONFIGURATION_DEFAULT_ALL", ")", ")", ";", "}" ]
Parses the widget configuration string.<p> @param cms the current users OpenCms context @param widgetDialog the dialog of this widget
[ "Parses", "the", "widget", "configuration", "string", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/CmsMultiSelectGroupWidget.java#L477-L506
looly/hutool
hutool-core/src/main/java/cn/hutool/core/convert/ConverterRegistry.java
ConverterRegistry.putCustom
public ConverterRegistry putCustom(Type type, Class<? extends Converter<?>> converterClass) { """ 登记自定义转换器 @param type 转换的目标类型 @param converterClass 转换器类,必须有默认构造方法 @return {@link ConverterRegistry} """ return putCustom(type, ReflectUtil.newInstance(converterClass)); }
java
public ConverterRegistry putCustom(Type type, Class<? extends Converter<?>> converterClass) { return putCustom(type, ReflectUtil.newInstance(converterClass)); }
[ "public", "ConverterRegistry", "putCustom", "(", "Type", "type", ",", "Class", "<", "?", "extends", "Converter", "<", "?", ">", ">", "converterClass", ")", "{", "return", "putCustom", "(", "type", ",", "ReflectUtil", ".", "newInstance", "(", "converterClass", ")", ")", ";", "}" ]
登记自定义转换器 @param type 转换的目标类型 @param converterClass 转换器类,必须有默认构造方法 @return {@link ConverterRegistry}
[ "登记自定义转换器" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/ConverterRegistry.java#L103-L105
mlhartme/jasmin
src/main/java/net/oneandone/jasmin/model/Repository.java
Repository.removeCompanionOpt
private static Ref removeCompanionOpt(List<Ref> refs, Ref cmp) { """ companion: Ref with same module and variant, but different minimization """ Iterator<Ref> iter; Ref ref; iter = refs.iterator(); while (iter.hasNext()) { ref = iter.next(); if (ref.module.equals(cmp.module) && Util.eq(ref.variant, cmp.variant)) { iter.remove(); return ref; } } return null; }
java
private static Ref removeCompanionOpt(List<Ref> refs, Ref cmp) { Iterator<Ref> iter; Ref ref; iter = refs.iterator(); while (iter.hasNext()) { ref = iter.next(); if (ref.module.equals(cmp.module) && Util.eq(ref.variant, cmp.variant)) { iter.remove(); return ref; } } return null; }
[ "private", "static", "Ref", "removeCompanionOpt", "(", "List", "<", "Ref", ">", "refs", ",", "Ref", "cmp", ")", "{", "Iterator", "<", "Ref", ">", "iter", ";", "Ref", "ref", ";", "iter", "=", "refs", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "ref", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "ref", ".", "module", ".", "equals", "(", "cmp", ".", "module", ")", "&&", "Util", ".", "eq", "(", "ref", ".", "variant", ",", "cmp", ".", "variant", ")", ")", "{", "iter", ".", "remove", "(", ")", ";", "return", "ref", ";", "}", "}", "return", "null", ";", "}" ]
companion: Ref with same module and variant, but different minimization
[ "companion", ":", "Ref", "with", "same", "module", "and", "variant", "but", "different", "minimization" ]
train
https://github.com/mlhartme/jasmin/blob/1c44339a2555ae7ffb7d40fd3a7d80d81c3fc39d/src/main/java/net/oneandone/jasmin/model/Repository.java#L430-L443
fcrepo3/fcrepo
fcrepo-common/src/main/java/org/fcrepo/utilities/xml/DefaultNamespaceContext.java
DefaultNamespaceContext.setNameSpace
public void setNameSpace(String namespaceURL, String prefix) throws IllegalArgumentException { """ <p>Set or add a namespace to the context and associated it with a prefix. </p><p> A given prefix can only be associated with one namespace in the context. A namespace can have multiple prefixes. </p> The prefixes: {@code xml}, and {@code xmlns} are reserved and predefined in any context. @param namespaceURL the namespace uri @param prefix the prefix to register with the uri @throws IllegalArgumentException thrown when trying to assign a namespace to a reserved prefix """ Collection<String> s = namespace.get(namespaceURL); if (s == null) { s = new HashSet<String>(); } s.add(prefix); namespace.put(namespaceURL, s); this.prefixes.put(prefix, namespaceURL); }
java
public void setNameSpace(String namespaceURL, String prefix) throws IllegalArgumentException { Collection<String> s = namespace.get(namespaceURL); if (s == null) { s = new HashSet<String>(); } s.add(prefix); namespace.put(namespaceURL, s); this.prefixes.put(prefix, namespaceURL); }
[ "public", "void", "setNameSpace", "(", "String", "namespaceURL", ",", "String", "prefix", ")", "throws", "IllegalArgumentException", "{", "Collection", "<", "String", ">", "s", "=", "namespace", ".", "get", "(", "namespaceURL", ")", ";", "if", "(", "s", "==", "null", ")", "{", "s", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "}", "s", ".", "add", "(", "prefix", ")", ";", "namespace", ".", "put", "(", "namespaceURL", ",", "s", ")", ";", "this", ".", "prefixes", ".", "put", "(", "prefix", ",", "namespaceURL", ")", ";", "}" ]
<p>Set or add a namespace to the context and associated it with a prefix. </p><p> A given prefix can only be associated with one namespace in the context. A namespace can have multiple prefixes. </p> The prefixes: {@code xml}, and {@code xmlns} are reserved and predefined in any context. @param namespaceURL the namespace uri @param prefix the prefix to register with the uri @throws IllegalArgumentException thrown when trying to assign a namespace to a reserved prefix
[ "<p", ">", "Set", "or", "add", "a", "namespace", "to", "the", "context", "and", "associated", "it", "with", "a", "prefix", ".", "<", "/", "p", ">", "<p", ">", "A", "given", "prefix", "can", "only", "be", "associated", "with", "one", "namespace", "in", "the", "context", ".", "A", "namespace", "can", "have", "multiple", "prefixes", ".", "<", "/", "p", ">", "The", "prefixes", ":", "{", "@code", "xml", "}", "and", "{", "@code", "xmlns", "}", "are", "reserved", "and", "predefined", "in", "any", "context", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/utilities/xml/DefaultNamespaceContext.java#L87-L98
undertow-io/undertow
core/src/main/java/io/undertow/server/protocol/http/ALPNOfferedClientHelloExplorer.java
ALPNOfferedClientHelloExplorer.exploreExtensions
private static List<Integer> exploreExtensions(ByteBuffer input, List<Integer> ciphers) throws SSLException { """ /* struct { ExtensionType extension_type; opaque extension_data<0..2^16-1>; } Extension; enum { server_name(0), max_fragment_length(1), client_certificate_url(2), trusted_ca_keys(3), truncated_hmac(4), status_request(5), (65535) } ExtensionType; """ int length = getInt16(input); // length of extensions while (length > 0) { int extType = getInt16(input); // extenson type int extLen = getInt16(input); // length of extension data if (extType == 16) { // 0x00: ty return ciphers; } else { // ignore other extensions processByteVector(input, extLen); } length -= extLen + 4; } return null; }
java
private static List<Integer> exploreExtensions(ByteBuffer input, List<Integer> ciphers) throws SSLException { int length = getInt16(input); // length of extensions while (length > 0) { int extType = getInt16(input); // extenson type int extLen = getInt16(input); // length of extension data if (extType == 16) { // 0x00: ty return ciphers; } else { // ignore other extensions processByteVector(input, extLen); } length -= extLen + 4; } return null; }
[ "private", "static", "List", "<", "Integer", ">", "exploreExtensions", "(", "ByteBuffer", "input", ",", "List", "<", "Integer", ">", "ciphers", ")", "throws", "SSLException", "{", "int", "length", "=", "getInt16", "(", "input", ")", ";", "// length of extensions", "while", "(", "length", ">", "0", ")", "{", "int", "extType", "=", "getInt16", "(", "input", ")", ";", "// extenson type", "int", "extLen", "=", "getInt16", "(", "input", ")", ";", "// length of extension data", "if", "(", "extType", "==", "16", ")", "{", "// 0x00: ty", "return", "ciphers", ";", "}", "else", "{", "// ignore other extensions", "processByteVector", "(", "input", ",", "extLen", ")", ";", "}", "length", "-=", "extLen", "+", "4", ";", "}", "return", "null", ";", "}" ]
/* struct { ExtensionType extension_type; opaque extension_data<0..2^16-1>; } Extension; enum { server_name(0), max_fragment_length(1), client_certificate_url(2), trusted_ca_keys(3), truncated_hmac(4), status_request(5), (65535) } ExtensionType;
[ "/", "*", "struct", "{", "ExtensionType", "extension_type", ";", "opaque", "extension_data<0", "..", "2^16", "-", "1", ">", ";", "}", "Extension", ";" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http/ALPNOfferedClientHelloExplorer.java#L247-L262
alkacon/opencms-core
src/org/opencms/jsp/search/config/parser/CmsJSONSearchConfigurationParser.java
CmsJSONSearchConfigurationParser.parseOptionalIntValue
protected static Integer parseOptionalIntValue(JSONObject json, String key) { """ Helper for reading an optional Integer value - returning <code>null</code> if parsing fails. @param json The JSON object where the value should be read from. @param key The key of the value to read. @return The value from the JSON, or <code>null</code> if the value does not exist, or is no Integer. """ try { return Integer.valueOf(json.getInt(key)); } catch (JSONException e) { LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_INTEGER_MISSING_1, key), e); return null; } }
java
protected static Integer parseOptionalIntValue(JSONObject json, String key) { try { return Integer.valueOf(json.getInt(key)); } catch (JSONException e) { LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_INTEGER_MISSING_1, key), e); return null; } }
[ "protected", "static", "Integer", "parseOptionalIntValue", "(", "JSONObject", "json", ",", "String", "key", ")", "{", "try", "{", "return", "Integer", ".", "valueOf", "(", "json", ".", "getInt", "(", "key", ")", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "LOG", ".", "info", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_OPTIONAL_INTEGER_MISSING_1", ",", "key", ")", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Helper for reading an optional Integer value - returning <code>null</code> if parsing fails. @param json The JSON object where the value should be read from. @param key The key of the value to read. @return The value from the JSON, or <code>null</code> if the value does not exist, or is no Integer.
[ "Helper", "for", "reading", "an", "optional", "Integer", "value", "-", "returning", "<code", ">", "null<", "/", "code", ">", "if", "parsing", "fails", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/search/config/parser/CmsJSONSearchConfigurationParser.java#L284-L292
linkedin/PalDB
paldb/src/main/java/com/linkedin/paldb/api/Configuration.java
Configuration.getList
public List<String> getList(String key) { """ Gets the string list value <code>key</code>. @param key key to get value for @throws java.lang.IllegalArgumentException if the key is not found @return value """ if (!containsKey(key)) { throw new IllegalArgumentException("Missing key " + key + "."); } return getList(key, null); }
java
public List<String> getList(String key) { if (!containsKey(key)) { throw new IllegalArgumentException("Missing key " + key + "."); } return getList(key, null); }
[ "public", "List", "<", "String", ">", "getList", "(", "String", "key", ")", "{", "if", "(", "!", "containsKey", "(", "key", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Missing key \"", "+", "key", "+", "\".\"", ")", ";", "}", "return", "getList", "(", "key", ",", "null", ")", ";", "}" ]
Gets the string list value <code>key</code>. @param key key to get value for @throws java.lang.IllegalArgumentException if the key is not found @return value
[ "Gets", "the", "string", "list", "value", "<code", ">", "key<", "/", "code", ">", "." ]
train
https://github.com/linkedin/PalDB/blob/d05ccdd3f67855eb2675dbd82599f19aa7a9f650/paldb/src/main/java/com/linkedin/paldb/api/Configuration.java#L365-L370
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRPointLight.java
GVRPointLight.setAttenuation
public void setAttenuation(float constant, float linear, float quadratic) { """ Set the three attenuation constants to control how light falls off based on distance from the light source. {@code 1 / (attenuation_constant + attenuation_linear * D * attenuation_quadratic * D ** 2)} @param constant constant attenuation factor @param linear linear attenuation factor @param quadratic quadratic attenuation factor """ setFloat("attenuation_constant", constant); setFloat("attenuation_linear", linear); setFloat("attenuation_quadratic", quadratic); }
java
public void setAttenuation(float constant, float linear, float quadratic) { setFloat("attenuation_constant", constant); setFloat("attenuation_linear", linear); setFloat("attenuation_quadratic", quadratic); }
[ "public", "void", "setAttenuation", "(", "float", "constant", ",", "float", "linear", ",", "float", "quadratic", ")", "{", "setFloat", "(", "\"attenuation_constant\"", ",", "constant", ")", ";", "setFloat", "(", "\"attenuation_linear\"", ",", "linear", ")", ";", "setFloat", "(", "\"attenuation_quadratic\"", ",", "quadratic", ")", ";", "}" ]
Set the three attenuation constants to control how light falls off based on distance from the light source. {@code 1 / (attenuation_constant + attenuation_linear * D * attenuation_quadratic * D ** 2)} @param constant constant attenuation factor @param linear linear attenuation factor @param quadratic quadratic attenuation factor
[ "Set", "the", "three", "attenuation", "constants", "to", "control", "how", "light", "falls", "off", "based", "on", "distance", "from", "the", "light", "source", ".", "{" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRPointLight.java#L253-L257
vkostyukov/la4j
src/main/java/org/la4j/matrix/SparseMatrix.java
SparseMatrix.nonZeroRowMajorIterator
public RowMajorMatrixIterator nonZeroRowMajorIterator() { """ Returns a non-zero row-major matrix iterator. @return a non-zero row-major matrix iterator. """ return new RowMajorMatrixIterator(rows, columns) { private long limit = (long) rows * columns; private long i = -1; @Override public int rowIndex() { return (int) (i / columns); } @Override public int columnIndex() { return (int) (i - ((i / columns) * columns)); } @Override public double get() { return SparseMatrix.this.get(rowIndex(), columnIndex()); } @Override public void set(double value) { SparseMatrix.this.set(rowIndex(), columnIndex(), value); } @Override public boolean hasNext() { while (i + 1 < limit) { i++; if (SparseMatrix.this.nonZeroAt(rowIndex(), columnIndex())) { i--; break; } } return i + 1 < limit; } @Override public Double next() { if(!hasNext()) { throw new NoSuchElementException(); } i++; return get(); } }; }
java
public RowMajorMatrixIterator nonZeroRowMajorIterator() { return new RowMajorMatrixIterator(rows, columns) { private long limit = (long) rows * columns; private long i = -1; @Override public int rowIndex() { return (int) (i / columns); } @Override public int columnIndex() { return (int) (i - ((i / columns) * columns)); } @Override public double get() { return SparseMatrix.this.get(rowIndex(), columnIndex()); } @Override public void set(double value) { SparseMatrix.this.set(rowIndex(), columnIndex(), value); } @Override public boolean hasNext() { while (i + 1 < limit) { i++; if (SparseMatrix.this.nonZeroAt(rowIndex(), columnIndex())) { i--; break; } } return i + 1 < limit; } @Override public Double next() { if(!hasNext()) { throw new NoSuchElementException(); } i++; return get(); } }; }
[ "public", "RowMajorMatrixIterator", "nonZeroRowMajorIterator", "(", ")", "{", "return", "new", "RowMajorMatrixIterator", "(", "rows", ",", "columns", ")", "{", "private", "long", "limit", "=", "(", "long", ")", "rows", "*", "columns", ";", "private", "long", "i", "=", "-", "1", ";", "@", "Override", "public", "int", "rowIndex", "(", ")", "{", "return", "(", "int", ")", "(", "i", "/", "columns", ")", ";", "}", "@", "Override", "public", "int", "columnIndex", "(", ")", "{", "return", "(", "int", ")", "(", "i", "-", "(", "(", "i", "/", "columns", ")", "*", "columns", ")", ")", ";", "}", "@", "Override", "public", "double", "get", "(", ")", "{", "return", "SparseMatrix", ".", "this", ".", "get", "(", "rowIndex", "(", ")", ",", "columnIndex", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "set", "(", "double", "value", ")", "{", "SparseMatrix", ".", "this", ".", "set", "(", "rowIndex", "(", ")", ",", "columnIndex", "(", ")", ",", "value", ")", ";", "}", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "while", "(", "i", "+", "1", "<", "limit", ")", "{", "i", "++", ";", "if", "(", "SparseMatrix", ".", "this", ".", "nonZeroAt", "(", "rowIndex", "(", ")", ",", "columnIndex", "(", ")", ")", ")", "{", "i", "--", ";", "break", ";", "}", "}", "return", "i", "+", "1", "<", "limit", ";", "}", "@", "Override", "public", "Double", "next", "(", ")", "{", "if", "(", "!", "hasNext", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", ")", ";", "}", "i", "++", ";", "return", "get", "(", ")", ";", "}", "}", ";", "}" ]
Returns a non-zero row-major matrix iterator. @return a non-zero row-major matrix iterator.
[ "Returns", "a", "non", "-", "zero", "row", "-", "major", "matrix", "iterator", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/matrix/SparseMatrix.java#L419-L466
lessthanoptimal/BoofCV
main/boofcv-types/src/main/java/boofcv/struct/image/ImageType.java
ImageType.createImage
public T createImage( int width , int height ) { """ Creates a new image. @param width Number of columns in the image. @param height Number of rows in the image. @return New instance of the image. """ switch( family ) { case GRAY: return (T)GeneralizedImageOps.createSingleBand(getImageClass(),width,height); case INTERLEAVED: return (T)GeneralizedImageOps.createInterleaved(getImageClass(), width, height, numBands); case PLANAR: return (T)new Planar(getImageClass(),width,height,numBands); default: throw new IllegalArgumentException("Type not yet supported"); } }
java
public T createImage( int width , int height ) { switch( family ) { case GRAY: return (T)GeneralizedImageOps.createSingleBand(getImageClass(),width,height); case INTERLEAVED: return (T)GeneralizedImageOps.createInterleaved(getImageClass(), width, height, numBands); case PLANAR: return (T)new Planar(getImageClass(),width,height,numBands); default: throw new IllegalArgumentException("Type not yet supported"); } }
[ "public", "T", "createImage", "(", "int", "width", ",", "int", "height", ")", "{", "switch", "(", "family", ")", "{", "case", "GRAY", ":", "return", "(", "T", ")", "GeneralizedImageOps", ".", "createSingleBand", "(", "getImageClass", "(", ")", ",", "width", ",", "height", ")", ";", "case", "INTERLEAVED", ":", "return", "(", "T", ")", "GeneralizedImageOps", ".", "createInterleaved", "(", "getImageClass", "(", ")", ",", "width", ",", "height", ",", "numBands", ")", ";", "case", "PLANAR", ":", "return", "(", "T", ")", "new", "Planar", "(", "getImageClass", "(", ")", ",", "width", ",", "height", ",", "numBands", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Type not yet supported\"", ")", ";", "}", "}" ]
Creates a new image. @param width Number of columns in the image. @param height Number of rows in the image. @return New instance of the image.
[ "Creates", "a", "new", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/image/ImageType.java#L87-L101
alkacon/opencms-core
src/org/opencms/main/OpenCmsCore.java
OpenCmsCore.initCmsObject
private CmsObject initCmsObject(HttpServletRequest req, HttpServletResponse res) throws IOException, CmsException { """ Handles the user authentification for each request sent to OpenCms.<p> User authentification is done in three steps: <ol> <li>Session authentification: OpenCms stores information of all authentificated users in an internal storage based on the users session.</li> <li>Authorization handler authentification: If the session authentification fails, the current configured authorization handler is called.</li> <li>Default user: When both authentification methods fail, the user is set to the default (Guest) user.</li> </ol> @param req the current http request @param res the current http response @return the initialized cms context @throws IOException if user authentication fails @throws CmsException in case something goes wrong """ return initCmsObject(req, res, true); }
java
private CmsObject initCmsObject(HttpServletRequest req, HttpServletResponse res) throws IOException, CmsException { return initCmsObject(req, res, true); }
[ "private", "CmsObject", "initCmsObject", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "IOException", ",", "CmsException", "{", "return", "initCmsObject", "(", "req", ",", "res", ",", "true", ")", ";", "}" ]
Handles the user authentification for each request sent to OpenCms.<p> User authentification is done in three steps: <ol> <li>Session authentification: OpenCms stores information of all authentificated users in an internal storage based on the users session.</li> <li>Authorization handler authentification: If the session authentification fails, the current configured authorization handler is called.</li> <li>Default user: When both authentification methods fail, the user is set to the default (Guest) user.</li> </ol> @param req the current http request @param res the current http response @return the initialized cms context @throws IOException if user authentication fails @throws CmsException in case something goes wrong
[ "Handles", "the", "user", "authentification", "for", "each", "request", "sent", "to", "OpenCms", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/OpenCmsCore.java#L2969-L2972
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.multOuter
public static void multOuter(DMatrix1Row a , DMatrix1Row c ) { """ <p>Computes the matrix multiplication outer product:<br> <br> c = a * a<sup>T</sup> <br> <br> c<sub>ij</sub> = &sum;<sub>k=1:m</sub> { a<sub>ik</sub> * a<sub>jk</sub>} </p> <p> Is faster than using a generic matrix multiplication by taking advantage of symmetry. </p> @param a The matrix being multiplied. Not modified. @param c Where the results of the operation are stored. Modified. """ c.reshape(a.numRows,a.numRows); MatrixMultProduct_DDRM.outer(a, c); }
java
public static void multOuter(DMatrix1Row a , DMatrix1Row c ) { c.reshape(a.numRows,a.numRows); MatrixMultProduct_DDRM.outer(a, c); }
[ "public", "static", "void", "multOuter", "(", "DMatrix1Row", "a", ",", "DMatrix1Row", "c", ")", "{", "c", ".", "reshape", "(", "a", ".", "numRows", ",", "a", ".", "numRows", ")", ";", "MatrixMultProduct_DDRM", ".", "outer", "(", "a", ",", "c", ")", ";", "}" ]
<p>Computes the matrix multiplication outer product:<br> <br> c = a * a<sup>T</sup> <br> <br> c<sub>ij</sub> = &sum;<sub>k=1:m</sub> { a<sub>ik</sub> * a<sub>jk</sub>} </p> <p> Is faster than using a generic matrix multiplication by taking advantage of symmetry. </p> @param a The matrix being multiplied. Not modified. @param c Where the results of the operation are stored. Modified.
[ "<p", ">", "Computes", "the", "matrix", "multiplication", "outer", "product", ":", "<br", ">", "<br", ">", "c", "=", "a", "*", "a<sup", ">", "T<", "/", "sup", ">", "<br", ">", "<br", ">", "c<sub", ">", "ij<", "/", "sub", ">", "=", "&sum", ";", "<sub", ">", "k", "=", "1", ":", "m<", "/", "sub", ">", "{", "a<sub", ">", "ik<", "/", "sub", ">", "*", "a<sub", ">", "jk<", "/", "sub", ">", "}", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L314-L319
ogaclejapan/SmartTabLayout
utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/Bundler.java
Bundler.putParcelableArray
public Bundler putParcelableArray(String key, Parcelable[] value) { """ Inserts an array of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an array of Parcelable objects, or null @return this """ bundle.putParcelableArray(key, value); return this; }
java
public Bundler putParcelableArray(String key, Parcelable[] value) { bundle.putParcelableArray(key, value); return this; }
[ "public", "Bundler", "putParcelableArray", "(", "String", "key", ",", "Parcelable", "[", "]", "value", ")", "{", "bundle", ".", "putParcelableArray", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts an array of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an array of Parcelable objects, or null @return this
[ "Inserts", "an", "array", "of", "Parcelable", "values", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/ogaclejapan/SmartTabLayout/blob/712e81a92f1e12a3c33dcbda03d813e0162e8589/utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/Bundler.java#L182-L185
jbake-org/jbake
jbake-core/src/main/java/org/jbake/template/TemplateEngines.java
TemplateEngines.loadEngines
private void loadEngines(final JBakeConfiguration config, final ContentStore db) { """ This method is used internally to load markup engines. Markup engines are found using descriptor files on classpath, so adding an engine is as easy as adding a jar on classpath with the descriptor file included. """ try { ClassLoader cl = TemplateEngines.class.getClassLoader(); Enumeration<URL> resources = cl.getResources("META-INF/org.jbake.parser.TemplateEngines.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); Properties props = new Properties(); props.load(url.openStream()); for (Map.Entry<Object, Object> entry : props.entrySet()) { String className = (String) entry.getKey(); String[] extensions = ((String) entry.getValue()).split(","); registerEngine(config, db, className, extensions); } } } catch (IOException e) { LOGGER.error("Error loading engines", e); } }
java
private void loadEngines(final JBakeConfiguration config, final ContentStore db) { try { ClassLoader cl = TemplateEngines.class.getClassLoader(); Enumeration<URL> resources = cl.getResources("META-INF/org.jbake.parser.TemplateEngines.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); Properties props = new Properties(); props.load(url.openStream()); for (Map.Entry<Object, Object> entry : props.entrySet()) { String className = (String) entry.getKey(); String[] extensions = ((String) entry.getValue()).split(","); registerEngine(config, db, className, extensions); } } } catch (IOException e) { LOGGER.error("Error loading engines", e); } }
[ "private", "void", "loadEngines", "(", "final", "JBakeConfiguration", "config", ",", "final", "ContentStore", "db", ")", "{", "try", "{", "ClassLoader", "cl", "=", "TemplateEngines", ".", "class", ".", "getClassLoader", "(", ")", ";", "Enumeration", "<", "URL", ">", "resources", "=", "cl", ".", "getResources", "(", "\"META-INF/org.jbake.parser.TemplateEngines.properties\"", ")", ";", "while", "(", "resources", ".", "hasMoreElements", "(", ")", ")", "{", "URL", "url", "=", "resources", ".", "nextElement", "(", ")", ";", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "props", ".", "load", "(", "url", ".", "openStream", "(", ")", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "props", ".", "entrySet", "(", ")", ")", "{", "String", "className", "=", "(", "String", ")", "entry", ".", "getKey", "(", ")", ";", "String", "[", "]", "extensions", "=", "(", "(", "String", ")", "entry", ".", "getValue", "(", ")", ")", ".", "split", "(", "\",\"", ")", ";", "registerEngine", "(", "config", ",", "db", ",", "className", ",", "extensions", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Error loading engines\"", ",", "e", ")", ";", "}", "}" ]
This method is used internally to load markup engines. Markup engines are found using descriptor files on classpath, so adding an engine is as easy as adding a jar on classpath with the descriptor file included.
[ "This", "method", "is", "used", "internally", "to", "load", "markup", "engines", ".", "Markup", "engines", "are", "found", "using", "descriptor", "files", "on", "classpath", "so", "adding", "an", "engine", "is", "as", "easy", "as", "adding", "a", "jar", "on", "classpath", "with", "the", "descriptor", "file", "included", "." ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/template/TemplateEngines.java#L91-L108
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/msvc/MsvcProjectWriter.java
MsvcProjectWriter.getBaseCompilerConfiguration
private CommandLineCompilerConfiguration getBaseCompilerConfiguration(final Map<String, TargetInfo> targets) { """ Gets the first recognized compiler from the compilation targets. @param targets compilation targets @return representative (hopefully) compiler configuration """ // // find first target with an DevStudio C compilation // CommandLineCompilerConfiguration compilerConfig; // // get the first target and assume that it is representative // for (final TargetInfo targetInfo : targets.values()) { final ProcessorConfiguration config = targetInfo.getConfiguration(); // // for the first cl compiler // if (config instanceof CommandLineCompilerConfiguration) { compilerConfig = (CommandLineCompilerConfiguration) config; if (compilerConfig.getCompiler() instanceof MsvcCCompiler) { return compilerConfig; } } } return null; }
java
private CommandLineCompilerConfiguration getBaseCompilerConfiguration(final Map<String, TargetInfo> targets) { // // find first target with an DevStudio C compilation // CommandLineCompilerConfiguration compilerConfig; // // get the first target and assume that it is representative // for (final TargetInfo targetInfo : targets.values()) { final ProcessorConfiguration config = targetInfo.getConfiguration(); // // for the first cl compiler // if (config instanceof CommandLineCompilerConfiguration) { compilerConfig = (CommandLineCompilerConfiguration) config; if (compilerConfig.getCompiler() instanceof MsvcCCompiler) { return compilerConfig; } } } return null; }
[ "private", "CommandLineCompilerConfiguration", "getBaseCompilerConfiguration", "(", "final", "Map", "<", "String", ",", "TargetInfo", ">", "targets", ")", "{", "//", "// find first target with an DevStudio C compilation", "//", "CommandLineCompilerConfiguration", "compilerConfig", ";", "//", "// get the first target and assume that it is representative", "//", "for", "(", "final", "TargetInfo", "targetInfo", ":", "targets", ".", "values", "(", ")", ")", "{", "final", "ProcessorConfiguration", "config", "=", "targetInfo", ".", "getConfiguration", "(", ")", ";", "//", "// for the first cl compiler", "//", "if", "(", "config", "instanceof", "CommandLineCompilerConfiguration", ")", "{", "compilerConfig", "=", "(", "CommandLineCompilerConfiguration", ")", "config", ";", "if", "(", "compilerConfig", ".", "getCompiler", "(", ")", "instanceof", "MsvcCCompiler", ")", "{", "return", "compilerConfig", ";", "}", "}", "}", "return", "null", ";", "}" ]
Gets the first recognized compiler from the compilation targets. @param targets compilation targets @return representative (hopefully) compiler configuration
[ "Gets", "the", "first", "recognized", "compiler", "from", "the", "compilation", "targets", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/msvc/MsvcProjectWriter.java#L133-L154
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/AnnotationTypeBuilder.java
AnnotationTypeBuilder.buildAnnotationTypeSignature
public void buildAnnotationTypeSignature(XMLNode node, Content annotationInfoTree) { """ Build the signature of the current annotation type. @param node the XML element that specifies which components to document @param annotationInfoTree the content tree to which the documentation will be added """ StringBuilder modifiers = new StringBuilder( annotationTypeDoc.modifiers() + " "); writer.addAnnotationTypeSignature(Util.replaceText( modifiers.toString(), "interface", "@interface"), annotationInfoTree); }
java
public void buildAnnotationTypeSignature(XMLNode node, Content annotationInfoTree) { StringBuilder modifiers = new StringBuilder( annotationTypeDoc.modifiers() + " "); writer.addAnnotationTypeSignature(Util.replaceText( modifiers.toString(), "interface", "@interface"), annotationInfoTree); }
[ "public", "void", "buildAnnotationTypeSignature", "(", "XMLNode", "node", ",", "Content", "annotationInfoTree", ")", "{", "StringBuilder", "modifiers", "=", "new", "StringBuilder", "(", "annotationTypeDoc", ".", "modifiers", "(", ")", "+", "\" \"", ")", ";", "writer", ".", "addAnnotationTypeSignature", "(", "Util", ".", "replaceText", "(", "modifiers", ".", "toString", "(", ")", ",", "\"interface\"", ",", "\"@interface\"", ")", ",", "annotationInfoTree", ")", ";", "}" ]
Build the signature of the current annotation type. @param node the XML element that specifies which components to document @param annotationInfoTree the content tree to which the documentation will be added
[ "Build", "the", "signature", "of", "the", "current", "annotation", "type", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/AnnotationTypeBuilder.java#L175-L180
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/FeatureResolverImpl.java
FeatureResolverImpl.resolveFeatures
@Override public Result resolveFeatures(Repository repository, Collection<ProvisioningFeatureDefinition> kernelFeatures, Collection<String> rootFeatures, Set<String> preResolved, boolean allowMultipleVersions, EnumSet<ProcessType> supportedProcessTypes) { """ /* (non-Javadoc) @see com.ibm.ws.kernel.feature.resolver.FeatureResolver#resolveFeatures(com.ibm.ws.kernel.feature.resolver.FeatureResolver.Repository, java.util.Collection, java.util.Collection, java.util.Set, boolean, java.util.EnumSet) Here are the steps this uses to resolve: 1) Primes the selected features with the pre-resolved and the root features (conflicts are reported, but no permutations for backtracking) 2) Resolve the root features 3) Check if there are any auto features to resolve; if so return to step 2 and resolve the auto-features as root features """ SelectionContext selectionContext = new SelectionContext(repository, allowMultipleVersions, supportedProcessTypes); // this checks if the pre-resolved exists in the repo; // if one does not exist then we start over with an empty set of pre-resolved preResolved = checkPreResolvedExistAndSetFullName(preResolved, selectionContext); // check that the root features exist and are public; remove them if not; also get the full name rootFeatures = checkRootsAreAccessibleAndSetFullName(new ArrayList<String>(rootFeatures), selectionContext, preResolved); // Always prime the selected with the pre-resolved and the root features. // This will ensure that the root and pre-resolved features do not conflict selectionContext.primeSelected(preResolved); selectionContext.primeSelected(rootFeatures); // Even if the feature set hasn't changed, we still need to process the auto features and add any features that need to be // installed/uninstalled to the list. This recursively iterates over the auto Features, as previously installed features // may satisfy other auto features. Set<String> autoFeaturesToInstall = Collections.<String> emptySet(); Set<String> seenAutoFeatures = new HashSet<String>(); Set<String> resolved = Collections.emptySet(); do { if (!!!autoFeaturesToInstall.isEmpty()) { // this is after the first pass; use the autoFeaturesToInstall as the roots rootFeatures = autoFeaturesToInstall; // Need to prime the auto features as selected selectionContext.primeSelected(autoFeaturesToInstall); // and use the resolved as the preResolved preResolved = resolved; // A new resolution process will happen now along with the auto-features that match; // need to save off the current conflicts to be the pre resolved conflicts // otherwise they would get lost selectionContext.saveCurrentPreResolvedConflicts(); } resolved = doResolveFeatures(rootFeatures, preResolved, selectionContext); } while (!!!(autoFeaturesToInstall = processAutoFeatures(kernelFeatures, resolved, seenAutoFeatures, selectionContext)).isEmpty()); // Finally return the selected result return selectionContext.getResult(); }
java
@Override public Result resolveFeatures(Repository repository, Collection<ProvisioningFeatureDefinition> kernelFeatures, Collection<String> rootFeatures, Set<String> preResolved, boolean allowMultipleVersions, EnumSet<ProcessType> supportedProcessTypes) { SelectionContext selectionContext = new SelectionContext(repository, allowMultipleVersions, supportedProcessTypes); // this checks if the pre-resolved exists in the repo; // if one does not exist then we start over with an empty set of pre-resolved preResolved = checkPreResolvedExistAndSetFullName(preResolved, selectionContext); // check that the root features exist and are public; remove them if not; also get the full name rootFeatures = checkRootsAreAccessibleAndSetFullName(new ArrayList<String>(rootFeatures), selectionContext, preResolved); // Always prime the selected with the pre-resolved and the root features. // This will ensure that the root and pre-resolved features do not conflict selectionContext.primeSelected(preResolved); selectionContext.primeSelected(rootFeatures); // Even if the feature set hasn't changed, we still need to process the auto features and add any features that need to be // installed/uninstalled to the list. This recursively iterates over the auto Features, as previously installed features // may satisfy other auto features. Set<String> autoFeaturesToInstall = Collections.<String> emptySet(); Set<String> seenAutoFeatures = new HashSet<String>(); Set<String> resolved = Collections.emptySet(); do { if (!!!autoFeaturesToInstall.isEmpty()) { // this is after the first pass; use the autoFeaturesToInstall as the roots rootFeatures = autoFeaturesToInstall; // Need to prime the auto features as selected selectionContext.primeSelected(autoFeaturesToInstall); // and use the resolved as the preResolved preResolved = resolved; // A new resolution process will happen now along with the auto-features that match; // need to save off the current conflicts to be the pre resolved conflicts // otherwise they would get lost selectionContext.saveCurrentPreResolvedConflicts(); } resolved = doResolveFeatures(rootFeatures, preResolved, selectionContext); } while (!!!(autoFeaturesToInstall = processAutoFeatures(kernelFeatures, resolved, seenAutoFeatures, selectionContext)).isEmpty()); // Finally return the selected result return selectionContext.getResult(); }
[ "@", "Override", "public", "Result", "resolveFeatures", "(", "Repository", "repository", ",", "Collection", "<", "ProvisioningFeatureDefinition", ">", "kernelFeatures", ",", "Collection", "<", "String", ">", "rootFeatures", ",", "Set", "<", "String", ">", "preResolved", ",", "boolean", "allowMultipleVersions", ",", "EnumSet", "<", "ProcessType", ">", "supportedProcessTypes", ")", "{", "SelectionContext", "selectionContext", "=", "new", "SelectionContext", "(", "repository", ",", "allowMultipleVersions", ",", "supportedProcessTypes", ")", ";", "// this checks if the pre-resolved exists in the repo;", "// if one does not exist then we start over with an empty set of pre-resolved", "preResolved", "=", "checkPreResolvedExistAndSetFullName", "(", "preResolved", ",", "selectionContext", ")", ";", "// check that the root features exist and are public; remove them if not; also get the full name", "rootFeatures", "=", "checkRootsAreAccessibleAndSetFullName", "(", "new", "ArrayList", "<", "String", ">", "(", "rootFeatures", ")", ",", "selectionContext", ",", "preResolved", ")", ";", "// Always prime the selected with the pre-resolved and the root features.", "// This will ensure that the root and pre-resolved features do not conflict", "selectionContext", ".", "primeSelected", "(", "preResolved", ")", ";", "selectionContext", ".", "primeSelected", "(", "rootFeatures", ")", ";", "// Even if the feature set hasn't changed, we still need to process the auto features and add any features that need to be", "// installed/uninstalled to the list. This recursively iterates over the auto Features, as previously installed features", "// may satisfy other auto features.", "Set", "<", "String", ">", "autoFeaturesToInstall", "=", "Collections", ".", "<", "String", ">", "emptySet", "(", ")", ";", "Set", "<", "String", ">", "seenAutoFeatures", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "Set", "<", "String", ">", "resolved", "=", "Collections", ".", "emptySet", "(", ")", ";", "do", "{", "if", "(", "!", "!", "!", "autoFeaturesToInstall", ".", "isEmpty", "(", ")", ")", "{", "// this is after the first pass; use the autoFeaturesToInstall as the roots", "rootFeatures", "=", "autoFeaturesToInstall", ";", "// Need to prime the auto features as selected", "selectionContext", ".", "primeSelected", "(", "autoFeaturesToInstall", ")", ";", "// and use the resolved as the preResolved", "preResolved", "=", "resolved", ";", "// A new resolution process will happen now along with the auto-features that match;", "// need to save off the current conflicts to be the pre resolved conflicts", "// otherwise they would get lost", "selectionContext", ".", "saveCurrentPreResolvedConflicts", "(", ")", ";", "}", "resolved", "=", "doResolveFeatures", "(", "rootFeatures", ",", "preResolved", ",", "selectionContext", ")", ";", "}", "while", "(", "!", "!", "!", "(", "autoFeaturesToInstall", "=", "processAutoFeatures", "(", "kernelFeatures", ",", "resolved", ",", "seenAutoFeatures", ",", "selectionContext", ")", ")", ".", "isEmpty", "(", ")", ")", ";", "// Finally return the selected result", "return", "selectionContext", ".", "getResult", "(", ")", ";", "}" ]
/* (non-Javadoc) @see com.ibm.ws.kernel.feature.resolver.FeatureResolver#resolveFeatures(com.ibm.ws.kernel.feature.resolver.FeatureResolver.Repository, java.util.Collection, java.util.Collection, java.util.Set, boolean, java.util.EnumSet) Here are the steps this uses to resolve: 1) Primes the selected features with the pre-resolved and the root features (conflicts are reported, but no permutations for backtracking) 2) Resolve the root features 3) Check if there are any auto features to resolve; if so return to step 2 and resolve the auto-features as root features
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/FeatureResolverImpl.java#L124-L166
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/AbstractRegionPainter.java
AbstractRegionPainter.createGradient
protected final LinearGradientPaint createGradient(float x1, float y1, float x2, float y2, float[] midpoints, Color[] colors) { """ Given parameters for creating a LinearGradientPaint, this method will create and return a linear gradient paint. One primary purpose for this method is to avoid creating a LinearGradientPaint where the start and end points are equal. In such a case, the end y point is slightly increased to avoid the overlap. @param x1 @param y1 @param x2 @param y2 @param midpoints @param colors @return a valid LinearGradientPaint. This method never returns null. """ if (x1 == x2 && y1 == y2) { y2 += .00001f; } return new LinearGradientPaint(x1, y1, x2, y2, midpoints, colors); }
java
protected final LinearGradientPaint createGradient(float x1, float y1, float x2, float y2, float[] midpoints, Color[] colors) { if (x1 == x2 && y1 == y2) { y2 += .00001f; } return new LinearGradientPaint(x1, y1, x2, y2, midpoints, colors); }
[ "protected", "final", "LinearGradientPaint", "createGradient", "(", "float", "x1", ",", "float", "y1", ",", "float", "x2", ",", "float", "y2", ",", "float", "[", "]", "midpoints", ",", "Color", "[", "]", "colors", ")", "{", "if", "(", "x1", "==", "x2", "&&", "y1", "==", "y2", ")", "{", "y2", "+=", ".00001f", ";", "}", "return", "new", "LinearGradientPaint", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "midpoints", ",", "colors", ")", ";", "}" ]
Given parameters for creating a LinearGradientPaint, this method will create and return a linear gradient paint. One primary purpose for this method is to avoid creating a LinearGradientPaint where the start and end points are equal. In such a case, the end y point is slightly increased to avoid the overlap. @param x1 @param y1 @param x2 @param y2 @param midpoints @param colors @return a valid LinearGradientPaint. This method never returns null.
[ "Given", "parameters", "for", "creating", "a", "LinearGradientPaint", "this", "method", "will", "create", "and", "return", "a", "linear", "gradient", "paint", ".", "One", "primary", "purpose", "for", "this", "method", "is", "to", "avoid", "creating", "a", "LinearGradientPaint", "where", "the", "start", "and", "end", "points", "are", "equal", ".", "In", "such", "a", "case", "the", "end", "y", "point", "is", "slightly", "increased", "to", "avoid", "the", "overlap", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/AbstractRegionPainter.java#L336-L342
easymock/objenesis
main/src/main/java/org/objenesis/instantiator/util/ClassDefinitionUtils.java
ClassDefinitionUtils.writeClass
public static void writeClass(String fileName, byte[] bytes) throws IOException { """ Write all class bytes to a file. @param fileName file where the bytes will be written @param bytes bytes representing the class @throws IOException if we fail to write the class """ try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName))) { out.write(bytes); } }
java
public static void writeClass(String fileName, byte[] bytes) throws IOException { try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName))) { out.write(bytes); } }
[ "public", "static", "void", "writeClass", "(", "String", "fileName", ",", "byte", "[", "]", "bytes", ")", "throws", "IOException", "{", "try", "(", "BufferedOutputStream", "out", "=", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "fileName", ")", ")", ")", "{", "out", ".", "write", "(", "bytes", ")", ";", "}", "}" ]
Write all class bytes to a file. @param fileName file where the bytes will be written @param bytes bytes representing the class @throws IOException if we fail to write the class
[ "Write", "all", "class", "bytes", "to", "a", "file", "." ]
train
https://github.com/easymock/objenesis/blob/8f601c8ba1aa20bbc640e2c2bc48d55df52c489f/main/src/main/java/org/objenesis/instantiator/util/ClassDefinitionUtils.java#L133-L137
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.saveElementValue
protected void saveElementValue(String field, String targetKey, Page page) throws TechnicalException, FailureException { """ Save value in memory. @param field is name of the field to retrieve. @param targetKey is the key to save value to @param page is target page. @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT} message (with screenshot, with exception) or with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error """ logger.debug("saveValueInStep: {} to {} in {}.", field, targetKey, page.getApplication()); String txt = ""; try { final WebElement elem = Utilities.findElement(page, field); txt = elem.getAttribute(VALUE) != null ? elem.getAttribute(VALUE) : elem.getText(); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, page.getCallBack()); } try { Context.saveValue(targetKey, txt); Context.getCurrentScenario().write("SAVE " + targetKey + "=" + txt); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE), page.getPageElementByKey(field), page.getApplication()), true, page.getCallBack()); } }
java
protected void saveElementValue(String field, String targetKey, Page page) throws TechnicalException, FailureException { logger.debug("saveValueInStep: {} to {} in {}.", field, targetKey, page.getApplication()); String txt = ""; try { final WebElement elem = Utilities.findElement(page, field); txt = elem.getAttribute(VALUE) != null ? elem.getAttribute(VALUE) : elem.getText(); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, page.getCallBack()); } try { Context.saveValue(targetKey, txt); Context.getCurrentScenario().write("SAVE " + targetKey + "=" + txt); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE), page.getPageElementByKey(field), page.getApplication()), true, page.getCallBack()); } }
[ "protected", "void", "saveElementValue", "(", "String", "field", ",", "String", "targetKey", ",", "Page", "page", ")", "throws", "TechnicalException", ",", "FailureException", "{", "logger", ".", "debug", "(", "\"saveValueInStep: {} to {} in {}.\"", ",", "field", ",", "targetKey", ",", "page", ".", "getApplication", "(", ")", ")", ";", "String", "txt", "=", "\"\"", ";", "try", "{", "final", "WebElement", "elem", "=", "Utilities", ".", "findElement", "(", "page", ",", "field", ")", ";", "txt", "=", "elem", ".", "getAttribute", "(", "VALUE", ")", "!=", "null", "?", "elem", ".", "getAttribute", "(", "VALUE", ")", ":", "elem", ".", "getText", "(", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "new", "Result", ".", "Failure", "<>", "(", "e", ".", "getMessage", "(", ")", ",", "Messages", ".", "getMessage", "(", "Messages", ".", "FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT", ")", ",", "true", ",", "page", ".", "getCallBack", "(", ")", ")", ";", "}", "try", "{", "Context", ".", "saveValue", "(", "targetKey", ",", "txt", ")", ";", "Context", ".", "getCurrentScenario", "(", ")", ".", "write", "(", "\"SAVE \"", "+", "targetKey", "+", "\"=\"", "+", "txt", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "new", "Result", ".", "Failure", "<>", "(", "e", ".", "getMessage", "(", ")", ",", "Messages", ".", "format", "(", "Messages", ".", "getMessage", "(", "Messages", ".", "FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE", ")", ",", "page", ".", "getPageElementByKey", "(", "field", ")", ",", "page", ".", "getApplication", "(", ")", ")", ",", "true", ",", "page", ".", "getCallBack", "(", ")", ")", ";", "}", "}" ]
Save value in memory. @param field is name of the field to retrieve. @param targetKey is the key to save value to @param page is target page. @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT} message (with screenshot, with exception) or with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error
[ "Save", "value", "in", "memory", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L568-L584
codeprimate-software/cp-elements
src/main/java/org/cp/elements/util/zip/ZipUtils.java
ZipUtils.zipEntry
static ZipOutputStream zipEntry(ZipEntry entry, ZipOutputStream outputStream) { """ Zips the contents of the individual {@link ZipEntry} to the supplied {@link ZipOutputStream}. @param entry {@link ZipEntry} to compress and add to the supplied {@link ZipOutputStream}. @param outputStream {@link ZipOutputStream} used to zip the contents of the given {@link ZipEntry}. @return the given {@link ZipOutputStream}. @throws SystemException if {@link ZipEntry} could not be compressed and added to the supplied {@link ZipOutputStream}. @see java.util.zip.ZipOutputStream @see java.util.zip.ZipEntry """ try { outputStream.putNextEntry(entry); } catch (IOException cause) { throw newSystemException(cause,"Failed to zip entry [%s]", entry.getName()); } IOUtils.doSafeIo(outputStream::closeEntry); return outputStream; }
java
static ZipOutputStream zipEntry(ZipEntry entry, ZipOutputStream outputStream) { try { outputStream.putNextEntry(entry); } catch (IOException cause) { throw newSystemException(cause,"Failed to zip entry [%s]", entry.getName()); } IOUtils.doSafeIo(outputStream::closeEntry); return outputStream; }
[ "static", "ZipOutputStream", "zipEntry", "(", "ZipEntry", "entry", ",", "ZipOutputStream", "outputStream", ")", "{", "try", "{", "outputStream", ".", "putNextEntry", "(", "entry", ")", ";", "}", "catch", "(", "IOException", "cause", ")", "{", "throw", "newSystemException", "(", "cause", ",", "\"Failed to zip entry [%s]\"", ",", "entry", ".", "getName", "(", ")", ")", ";", "}", "IOUtils", ".", "doSafeIo", "(", "outputStream", "::", "closeEntry", ")", ";", "return", "outputStream", ";", "}" ]
Zips the contents of the individual {@link ZipEntry} to the supplied {@link ZipOutputStream}. @param entry {@link ZipEntry} to compress and add to the supplied {@link ZipOutputStream}. @param outputStream {@link ZipOutputStream} used to zip the contents of the given {@link ZipEntry}. @return the given {@link ZipOutputStream}. @throws SystemException if {@link ZipEntry} could not be compressed and added to the supplied {@link ZipOutputStream}. @see java.util.zip.ZipOutputStream @see java.util.zip.ZipEntry
[ "Zips", "the", "contents", "of", "the", "individual", "{", "@link", "ZipEntry", "}", "to", "the", "supplied", "{", "@link", "ZipOutputStream", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/zip/ZipUtils.java#L255-L267
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/recurrent/BaseRecurrentLayer.java
BaseRecurrentLayer.rnnSetPreviousState
@Override public void rnnSetPreviousState(Map<String, INDArray> stateMap) { """ Set the state map. Values set using this method will be used in next call to rnnTimeStep() """ this.stateMap.clear(); this.stateMap.putAll(stateMap); }
java
@Override public void rnnSetPreviousState(Map<String, INDArray> stateMap) { this.stateMap.clear(); this.stateMap.putAll(stateMap); }
[ "@", "Override", "public", "void", "rnnSetPreviousState", "(", "Map", "<", "String", ",", "INDArray", ">", "stateMap", ")", "{", "this", ".", "stateMap", ".", "clear", "(", ")", ";", "this", ".", "stateMap", ".", "putAll", "(", "stateMap", ")", ";", "}" ]
Set the state map. Values set using this method will be used in next call to rnnTimeStep()
[ "Set", "the", "state", "map", ".", "Values", "set", "using", "this", "method", "will", "be", "used", "in", "next", "call", "to", "rnnTimeStep", "()" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/recurrent/BaseRecurrentLayer.java#L60-L64
mfornos/humanize
humanize-slim/src/main/java/humanize/Humanize.java
Humanize.unmask
public static String unmask(final String mask, final String value) throws ParseException { """ <p> Parses the given text with the mask specified. </p> @param mask The pattern mask. @param value The text to be parsed @return The parsed text @throws ParseException @see MaskFormat """ return maskFormat(mask).parse(value); }
java
public static String unmask(final String mask, final String value) throws ParseException { return maskFormat(mask).parse(value); }
[ "public", "static", "String", "unmask", "(", "final", "String", "mask", ",", "final", "String", "value", ")", "throws", "ParseException", "{", "return", "maskFormat", "(", "mask", ")", ".", "parse", "(", "value", ")", ";", "}" ]
<p> Parses the given text with the mask specified. </p> @param mask The pattern mask. @param value The text to be parsed @return The parsed text @throws ParseException @see MaskFormat
[ "<p", ">", "Parses", "the", "given", "text", "with", "the", "mask", "specified", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L2879-L2882
CloudSlang/cs-actions
cs-commons/src/main/java/io/cloudslang/content/utils/NumberUtilities.java
NumberUtilities.isValidInt
public static boolean isValidInt(@Nullable final String integerStr, final int lowerBound, final int upperBound, final boolean includeLowerBound, final boolean includeUpperBound) { """ Given an integer string, it checks if it's a valid integer (base on apaches NumberUtils.createInteger) and if it's between the lowerBound and upperBound. @param integerStr the integer string to check @param lowerBound the lower bound of the interval @param upperBound the upper bound of the interval @param includeLowerBound boolean if to include the lower bound of the interval @param includeUpperBound boolean if to include the upper bound of the interval @return true if the integer string is valid and in between the lowerBound and upperBound, false otherwise @throws IllegalArgumentException if the lowerBound is not less than the upperBound """ if (lowerBound > upperBound) { throw new IllegalArgumentException(ExceptionValues.INVALID_BOUNDS); } else if (!isValidInt(integerStr)) { return false; } final int aInteger = toInteger(integerStr); final boolean respectsLowerBound = includeLowerBound ? lowerBound <= aInteger : lowerBound < aInteger; final boolean respectsUpperBound = includeUpperBound ? aInteger <= upperBound : aInteger < upperBound; return respectsLowerBound && respectsUpperBound; }
java
public static boolean isValidInt(@Nullable final String integerStr, final int lowerBound, final int upperBound, final boolean includeLowerBound, final boolean includeUpperBound) { if (lowerBound > upperBound) { throw new IllegalArgumentException(ExceptionValues.INVALID_BOUNDS); } else if (!isValidInt(integerStr)) { return false; } final int aInteger = toInteger(integerStr); final boolean respectsLowerBound = includeLowerBound ? lowerBound <= aInteger : lowerBound < aInteger; final boolean respectsUpperBound = includeUpperBound ? aInteger <= upperBound : aInteger < upperBound; return respectsLowerBound && respectsUpperBound; }
[ "public", "static", "boolean", "isValidInt", "(", "@", "Nullable", "final", "String", "integerStr", ",", "final", "int", "lowerBound", ",", "final", "int", "upperBound", ",", "final", "boolean", "includeLowerBound", ",", "final", "boolean", "includeUpperBound", ")", "{", "if", "(", "lowerBound", ">", "upperBound", ")", "{", "throw", "new", "IllegalArgumentException", "(", "ExceptionValues", ".", "INVALID_BOUNDS", ")", ";", "}", "else", "if", "(", "!", "isValidInt", "(", "integerStr", ")", ")", "{", "return", "false", ";", "}", "final", "int", "aInteger", "=", "toInteger", "(", "integerStr", ")", ";", "final", "boolean", "respectsLowerBound", "=", "includeLowerBound", "?", "lowerBound", "<=", "aInteger", ":", "lowerBound", "<", "aInteger", ";", "final", "boolean", "respectsUpperBound", "=", "includeUpperBound", "?", "aInteger", "<=", "upperBound", ":", "aInteger", "<", "upperBound", ";", "return", "respectsLowerBound", "&&", "respectsUpperBound", ";", "}" ]
Given an integer string, it checks if it's a valid integer (base on apaches NumberUtils.createInteger) and if it's between the lowerBound and upperBound. @param integerStr the integer string to check @param lowerBound the lower bound of the interval @param upperBound the upper bound of the interval @param includeLowerBound boolean if to include the lower bound of the interval @param includeUpperBound boolean if to include the upper bound of the interval @return true if the integer string is valid and in between the lowerBound and upperBound, false otherwise @throws IllegalArgumentException if the lowerBound is not less than the upperBound
[ "Given", "an", "integer", "string", "it", "checks", "if", "it", "s", "a", "valid", "integer", "(", "base", "on", "apaches", "NumberUtils", ".", "createInteger", ")", "and", "if", "it", "s", "between", "the", "lowerBound", "and", "upperBound", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/NumberUtilities.java#L84-L94
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.extractCameraMatrices
public static void extractCameraMatrices( TrifocalTensor tensor , DMatrixRMaj P2 , DMatrixRMaj P3 ) { """ <p> Extract the camera matrices up to a common projective transform. </p> <p> NOTE: The camera matrix for the first view is assumed to be P1 = [I|0]. </p> @see TrifocalExtractGeometries @param tensor Trifocal tensor. Not modified. @param P2 Output: 3x4 camera matrix for views 1 to 2. Modified. @param P3 Output: 3x4 camera matrix for views 1 to 3. Modified. """ TrifocalExtractGeometries e = new TrifocalExtractGeometries(); e.setTensor(tensor); e.extractCamera(P2,P3); }
java
public static void extractCameraMatrices( TrifocalTensor tensor , DMatrixRMaj P2 , DMatrixRMaj P3 ) { TrifocalExtractGeometries e = new TrifocalExtractGeometries(); e.setTensor(tensor); e.extractCamera(P2,P3); }
[ "public", "static", "void", "extractCameraMatrices", "(", "TrifocalTensor", "tensor", ",", "DMatrixRMaj", "P2", ",", "DMatrixRMaj", "P3", ")", "{", "TrifocalExtractGeometries", "e", "=", "new", "TrifocalExtractGeometries", "(", ")", ";", "e", ".", "setTensor", "(", "tensor", ")", ";", "e", ".", "extractCamera", "(", "P2", ",", "P3", ")", ";", "}" ]
<p> Extract the camera matrices up to a common projective transform. </p> <p> NOTE: The camera matrix for the first view is assumed to be P1 = [I|0]. </p> @see TrifocalExtractGeometries @param tensor Trifocal tensor. Not modified. @param P2 Output: 3x4 camera matrix for views 1 to 2. Modified. @param P3 Output: 3x4 camera matrix for views 1 to 3. Modified.
[ "<p", ">", "Extract", "the", "camera", "matrices", "up", "to", "a", "common", "projective", "transform", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L647-L651
sebastiangraf/jSCSI
bundles/commons/src/main/java/org/jscsi/parser/ProtocolDataUnit.java
ProtocolDataUnit.serializeDataSegment
public final int serializeDataSegment (final ByteBuffer dst, final int offset) throws InternetSCSIException { """ Serializes the data segment (binary or key-value pairs) to a destination array, staring from offset to write. @param dst The array to write in. @param offset The start offset to start from in <code>dst</code>. @return The written length. @throws InternetSCSIException If any violation of the iSCSI-Standard emerge. """ dataSegment.rewind(); dst.position(offset); dst.put(dataSegment); return dataSegment.limit(); }
java
public final int serializeDataSegment (final ByteBuffer dst, final int offset) throws InternetSCSIException { dataSegment.rewind(); dst.position(offset); dst.put(dataSegment); return dataSegment.limit(); }
[ "public", "final", "int", "serializeDataSegment", "(", "final", "ByteBuffer", "dst", ",", "final", "int", "offset", ")", "throws", "InternetSCSIException", "{", "dataSegment", ".", "rewind", "(", ")", ";", "dst", ".", "position", "(", "offset", ")", ";", "dst", ".", "put", "(", "dataSegment", ")", ";", "return", "dataSegment", ".", "limit", "(", ")", ";", "}" ]
Serializes the data segment (binary or key-value pairs) to a destination array, staring from offset to write. @param dst The array to write in. @param offset The start offset to start from in <code>dst</code>. @return The written length. @throws InternetSCSIException If any violation of the iSCSI-Standard emerge.
[ "Serializes", "the", "data", "segment", "(", "binary", "or", "key", "-", "value", "pairs", ")", "to", "a", "destination", "array", "staring", "from", "offset", "to", "write", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/commons/src/main/java/org/jscsi/parser/ProtocolDataUnit.java#L268-L275
aws/aws-sdk-java
aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateIntegrationResult.java
UpdateIntegrationResult.withRequestParameters
public UpdateIntegrationResult withRequestParameters(java.util.Map<String, String> requestParameters) { """ <p> A key-value map specifying request parameters that are passed from the method request to the backend. The key is an integration request parameter name and the associated value is a method request parameter value or static value that must be enclosed within single quotes and pre-encoded as required by the backend. The method request parameter value must match the pattern of method.request.{location}.{name} , where {location} is querystring, path, or header; and {name} must be a valid and unique method request parameter name. </p> @param requestParameters A key-value map specifying request parameters that are passed from the method request to the backend. The key is an integration request parameter name and the associated value is a method request parameter value or static value that must be enclosed within single quotes and pre-encoded as required by the backend. The method request parameter value must match the pattern of method.request.{location}.{name} , where {location} is querystring, path, or header; and {name} must be a valid and unique method request parameter name. @return Returns a reference to this object so that method calls can be chained together. """ setRequestParameters(requestParameters); return this; }
java
public UpdateIntegrationResult withRequestParameters(java.util.Map<String, String> requestParameters) { setRequestParameters(requestParameters); return this; }
[ "public", "UpdateIntegrationResult", "withRequestParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "requestParameters", ")", "{", "setRequestParameters", "(", "requestParameters", ")", ";", "return", "this", ";", "}" ]
<p> A key-value map specifying request parameters that are passed from the method request to the backend. The key is an integration request parameter name and the associated value is a method request parameter value or static value that must be enclosed within single quotes and pre-encoded as required by the backend. The method request parameter value must match the pattern of method.request.{location}.{name} , where {location} is querystring, path, or header; and {name} must be a valid and unique method request parameter name. </p> @param requestParameters A key-value map specifying request parameters that are passed from the method request to the backend. The key is an integration request parameter name and the associated value is a method request parameter value or static value that must be enclosed within single quotes and pre-encoded as required by the backend. The method request parameter value must match the pattern of method.request.{location}.{name} , where {location} is querystring, path, or header; and {name} must be a valid and unique method request parameter name. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "key", "-", "value", "map", "specifying", "request", "parameters", "that", "are", "passed", "from", "the", "method", "request", "to", "the", "backend", ".", "The", "key", "is", "an", "integration", "request", "parameter", "name", "and", "the", "associated", "value", "is", "a", "method", "request", "parameter", "value", "or", "static", "value", "that", "must", "be", "enclosed", "within", "single", "quotes", "and", "pre", "-", "encoded", "as", "required", "by", "the", "backend", ".", "The", "method", "request", "parameter", "value", "must", "match", "the", "pattern", "of", "method", ".", "request", ".", "{", "location", "}", ".", "{", "name", "}", "where", "{", "location", "}", "is", "querystring", "path", "or", "header", ";", "and", "{", "name", "}", "must", "be", "a", "valid", "and", "unique", "method", "request", "parameter", "name", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateIntegrationResult.java#L1146-L1149
phax/ph-commons
ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java
JAXBContextCache.getFromCache
@Nullable public JAXBContext getFromCache (@Nonnull final Package aPackage, @Nullable final ClassLoader aClassLoader) { """ Special overload with package and {@link ClassLoader}. In this case the resulting value is NOT cached! @param aPackage Package to load. May not be <code>null</code>. @param aClassLoader Class loader to use. May be <code>null</code> in which case the default class loader is used. @return <code>null</code> if package is <code>null</code>. """ return getFromCache (new JAXBContextCacheKey (aPackage, aClassLoader)); }
java
@Nullable public JAXBContext getFromCache (@Nonnull final Package aPackage, @Nullable final ClassLoader aClassLoader) { return getFromCache (new JAXBContextCacheKey (aPackage, aClassLoader)); }
[ "@", "Nullable", "public", "JAXBContext", "getFromCache", "(", "@", "Nonnull", "final", "Package", "aPackage", ",", "@", "Nullable", "final", "ClassLoader", "aClassLoader", ")", "{", "return", "getFromCache", "(", "new", "JAXBContextCacheKey", "(", "aPackage", ",", "aClassLoader", ")", ")", ";", "}" ]
Special overload with package and {@link ClassLoader}. In this case the resulting value is NOT cached! @param aPackage Package to load. May not be <code>null</code>. @param aClassLoader Class loader to use. May be <code>null</code> in which case the default class loader is used. @return <code>null</code> if package is <code>null</code>.
[ "Special", "overload", "with", "package", "and", "{", "@link", "ClassLoader", "}", ".", "In", "this", "case", "the", "resulting", "value", "is", "NOT", "cached!" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java#L132-L136
jayantk/jklol
src/com/jayantkrish/jklol/ccg/chart/CcgBeamSearchChart.java
CcgBeamSearchChart.offerEntry
private final void offerEntry(ChartEntry entry, double probability, int spanStart, int spanEnd) { """ Adds a chart entry to the heap for {@code spanStart} to {@code spanEnd}. This operation implements beam truncation by discarding the minimum probability entry when a heap reaches the beam size. """ HeapUtils.offer(chart[spanStart][spanEnd], probabilities[spanStart][spanEnd], chartSizes[spanEnd + (numTerminals * spanStart)], entry, probability); chartSizes[spanEnd + (numTerminals * spanStart)]++; totalChartSize++; if (chartSizes[spanEnd + (numTerminals * spanStart)] > beamSize) { HeapUtils.removeMin(chart[spanStart][spanEnd], probabilities[spanStart][spanEnd], chartSizes[spanEnd + (numTerminals * spanStart)]); chartSizes[spanEnd + (numTerminals * spanStart)]--; totalChartSize--; } }
java
private final void offerEntry(ChartEntry entry, double probability, int spanStart, int spanEnd) { HeapUtils.offer(chart[spanStart][spanEnd], probabilities[spanStart][spanEnd], chartSizes[spanEnd + (numTerminals * spanStart)], entry, probability); chartSizes[spanEnd + (numTerminals * spanStart)]++; totalChartSize++; if (chartSizes[spanEnd + (numTerminals * spanStart)] > beamSize) { HeapUtils.removeMin(chart[spanStart][spanEnd], probabilities[spanStart][spanEnd], chartSizes[spanEnd + (numTerminals * spanStart)]); chartSizes[spanEnd + (numTerminals * spanStart)]--; totalChartSize--; } }
[ "private", "final", "void", "offerEntry", "(", "ChartEntry", "entry", ",", "double", "probability", ",", "int", "spanStart", ",", "int", "spanEnd", ")", "{", "HeapUtils", ".", "offer", "(", "chart", "[", "spanStart", "]", "[", "spanEnd", "]", ",", "probabilities", "[", "spanStart", "]", "[", "spanEnd", "]", ",", "chartSizes", "[", "spanEnd", "+", "(", "numTerminals", "*", "spanStart", ")", "]", ",", "entry", ",", "probability", ")", ";", "chartSizes", "[", "spanEnd", "+", "(", "numTerminals", "*", "spanStart", ")", "]", "++", ";", "totalChartSize", "++", ";", "if", "(", "chartSizes", "[", "spanEnd", "+", "(", "numTerminals", "*", "spanStart", ")", "]", ">", "beamSize", ")", "{", "HeapUtils", ".", "removeMin", "(", "chart", "[", "spanStart", "]", "[", "spanEnd", "]", ",", "probabilities", "[", "spanStart", "]", "[", "spanEnd", "]", ",", "chartSizes", "[", "spanEnd", "+", "(", "numTerminals", "*", "spanStart", ")", "]", ")", ";", "chartSizes", "[", "spanEnd", "+", "(", "numTerminals", "*", "spanStart", ")", "]", "--", ";", "totalChartSize", "--", ";", "}", "}" ]
Adds a chart entry to the heap for {@code spanStart} to {@code spanEnd}. This operation implements beam truncation by discarding the minimum probability entry when a heap reaches the beam size.
[ "Adds", "a", "chart", "entry", "to", "the", "heap", "for", "{" ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/chart/CcgBeamSearchChart.java#L214-L226
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restoreconfig.java
br_restoreconfig.restoreconfig
public static br_restoreconfig restoreconfig(nitro_service client, br_restoreconfig resource) throws Exception { """ <pre> Use this operation to restore config from file on Repeater Instances. </pre> """ return ((br_restoreconfig[]) resource.perform_operation(client, "restoreconfig"))[0]; }
java
public static br_restoreconfig restoreconfig(nitro_service client, br_restoreconfig resource) throws Exception { return ((br_restoreconfig[]) resource.perform_operation(client, "restoreconfig"))[0]; }
[ "public", "static", "br_restoreconfig", "restoreconfig", "(", "nitro_service", "client", ",", "br_restoreconfig", "resource", ")", "throws", "Exception", "{", "return", "(", "(", "br_restoreconfig", "[", "]", ")", "resource", ".", "perform_operation", "(", "client", ",", "\"restoreconfig\"", ")", ")", "[", "0", "]", ";", "}" ]
<pre> Use this operation to restore config from file on Repeater Instances. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "restore", "config", "from", "file", "on", "Repeater", "Instances", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restoreconfig.java#L105-L108
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.expectMax
public void expectMax(String name, double maxLength, String message) { """ Validates a given field to have a maximum length @param name The field to check @param maxLength The maximum length @param message A custom error message instead of the default one """ String value = Optional.ofNullable(get(name)).orElse(""); if (StringUtils.isNumeric(value)) { if (Double.parseDouble(value) > maxLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MAX_KEY.name(), name, maxLength))); } } else { if (value.length() > maxLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MAX_KEY.name(), name, maxLength))); } } }
java
public void expectMax(String name, double maxLength, String message) { String value = Optional.ofNullable(get(name)).orElse(""); if (StringUtils.isNumeric(value)) { if (Double.parseDouble(value) > maxLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MAX_KEY.name(), name, maxLength))); } } else { if (value.length() > maxLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MAX_KEY.name(), name, maxLength))); } } }
[ "public", "void", "expectMax", "(", "String", "name", ",", "double", "maxLength", ",", "String", "message", ")", "{", "String", "value", "=", "Optional", ".", "ofNullable", "(", "get", "(", "name", ")", ")", ".", "orElse", "(", "\"\"", ")", ";", "if", "(", "StringUtils", ".", "isNumeric", "(", "value", ")", ")", "{", "if", "(", "Double", ".", "parseDouble", "(", "value", ")", ">", "maxLength", ")", "{", "addError", "(", "name", ",", "Optional", ".", "ofNullable", "(", "message", ")", ".", "orElse", "(", "messages", ".", "get", "(", "Validation", ".", "MAX_KEY", ".", "name", "(", ")", ",", "name", ",", "maxLength", ")", ")", ")", ";", "}", "}", "else", "{", "if", "(", "value", ".", "length", "(", ")", ">", "maxLength", ")", "{", "addError", "(", "name", ",", "Optional", ".", "ofNullable", "(", "message", ")", ".", "orElse", "(", "messages", ".", "get", "(", "Validation", ".", "MAX_KEY", ".", "name", "(", ")", ",", "name", ",", "maxLength", ")", ")", ")", ";", "}", "}", "}" ]
Validates a given field to have a maximum length @param name The field to check @param maxLength The maximum length @param message A custom error message instead of the default one
[ "Validates", "a", "given", "field", "to", "have", "a", "maximum", "length" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L151-L163
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java
Types.asEnclosingSuper
public Type asEnclosingSuper(Type t, Symbol sym) { """ Return the base type of t or any of its enclosing types that starts with the given symbol. If none exists, return null. @param t a type @param sym a symbol """ switch (t.getTag()) { case CLASS: do { Type s = asSuper(t, sym); if (s != null) return s; Type outer = t.getEnclosingType(); t = (outer.hasTag(CLASS)) ? outer : (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type : Type.noType; } while (t.hasTag(CLASS)); return null; case ARRAY: return isSubtype(t, sym.type) ? sym.type : null; case TYPEVAR: return asSuper(t, sym); case ERROR: return t; default: return null; } }
java
public Type asEnclosingSuper(Type t, Symbol sym) { switch (t.getTag()) { case CLASS: do { Type s = asSuper(t, sym); if (s != null) return s; Type outer = t.getEnclosingType(); t = (outer.hasTag(CLASS)) ? outer : (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type : Type.noType; } while (t.hasTag(CLASS)); return null; case ARRAY: return isSubtype(t, sym.type) ? sym.type : null; case TYPEVAR: return asSuper(t, sym); case ERROR: return t; default: return null; } }
[ "public", "Type", "asEnclosingSuper", "(", "Type", "t", ",", "Symbol", "sym", ")", "{", "switch", "(", "t", ".", "getTag", "(", ")", ")", "{", "case", "CLASS", ":", "do", "{", "Type", "s", "=", "asSuper", "(", "t", ",", "sym", ")", ";", "if", "(", "s", "!=", "null", ")", "return", "s", ";", "Type", "outer", "=", "t", ".", "getEnclosingType", "(", ")", ";", "t", "=", "(", "outer", ".", "hasTag", "(", "CLASS", ")", ")", "?", "outer", ":", "(", "t", ".", "tsym", ".", "owner", ".", "enclClass", "(", ")", "!=", "null", ")", "?", "t", ".", "tsym", ".", "owner", ".", "enclClass", "(", ")", ".", "type", ":", "Type", ".", "noType", ";", "}", "while", "(", "t", ".", "hasTag", "(", "CLASS", ")", ")", ";", "return", "null", ";", "case", "ARRAY", ":", "return", "isSubtype", "(", "t", ",", "sym", ".", "type", ")", "?", "sym", ".", "type", ":", "null", ";", "case", "TYPEVAR", ":", "return", "asSuper", "(", "t", ",", "sym", ")", ";", "case", "ERROR", ":", "return", "t", ";", "default", ":", "return", "null", ";", "}", "}" ]
Return the base type of t or any of its enclosing types that starts with the given symbol. If none exists, return null. @param t a type @param sym a symbol
[ "Return", "the", "base", "type", "of", "t", "or", "any", "of", "its", "enclosing", "types", "that", "starts", "with", "the", "given", "symbol", ".", "If", "none", "exists", "return", "null", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java#L1950-L1971
google/truth
core/src/main/java/com/google/common/truth/SubjectUtils.java
SubjectUtils.hasMatchingToStringPair
static boolean hasMatchingToStringPair(Iterable<?> items1, Iterable<?> items2) { """ Returns true if there is a pair of an item from {@code items1} and one in {@code items2} that has the same {@code toString()} value without being equal. <p>Example: {@code hasMatchingToStringPair([1L, 2L], [1]) == true} """ if (isEmpty(items1) || isEmpty(items2)) { return false; // Bail early to avoid calling hashCode() on the elements unnecessarily. } return !retainMatchingToString(items1, items2).isEmpty(); }
java
static boolean hasMatchingToStringPair(Iterable<?> items1, Iterable<?> items2) { if (isEmpty(items1) || isEmpty(items2)) { return false; // Bail early to avoid calling hashCode() on the elements unnecessarily. } return !retainMatchingToString(items1, items2).isEmpty(); }
[ "static", "boolean", "hasMatchingToStringPair", "(", "Iterable", "<", "?", ">", "items1", ",", "Iterable", "<", "?", ">", "items2", ")", "{", "if", "(", "isEmpty", "(", "items1", ")", "||", "isEmpty", "(", "items2", ")", ")", "{", "return", "false", ";", "// Bail early to avoid calling hashCode() on the elements unnecessarily.", "}", "return", "!", "retainMatchingToString", "(", "items1", ",", "items2", ")", ".", "isEmpty", "(", ")", ";", "}" ]
Returns true if there is a pair of an item from {@code items1} and one in {@code items2} that has the same {@code toString()} value without being equal. <p>Example: {@code hasMatchingToStringPair([1L, 2L], [1]) == true}
[ "Returns", "true", "if", "there", "is", "a", "pair", "of", "an", "item", "from", "{", "@code", "items1", "}", "and", "one", "in", "{", "@code", "items2", "}", "that", "has", "the", "same", "{", "@code", "toString", "()", "}", "value", "without", "being", "equal", "." ]
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/SubjectUtils.java#L288-L293
Hygieia/Hygieia
api/src/main/java/com/capitalone/dashboard/service/DynamicPipelineServiceImpl.java
DynamicPipelineServiceImpl.getComponentRepoBranch
protected RepoBranch getComponentRepoBranch(Component component) { """ Determine the SCM url and branch that is set for the component. Information is gathered with the assumption that the data is stored in options.url and options.branch. @param component @return the {@link RepoBranch} that the component uses """ CollectorItem item = component.getFirstCollectorItemForType(CollectorType.SCM); if (item == null) { logger.warn("Error encountered building pipeline: could not find scm collector item for dashboard."); return new RepoBranch("", "", RepoType.Unknown); } // TODO find a better way? String url = (String)item.getOptions().get("url"); String branch = (String)item.getOptions().get("branch"); return new RepoBranch(url, branch, RepoType.Unknown); }
java
protected RepoBranch getComponentRepoBranch(Component component) { CollectorItem item = component.getFirstCollectorItemForType(CollectorType.SCM); if (item == null) { logger.warn("Error encountered building pipeline: could not find scm collector item for dashboard."); return new RepoBranch("", "", RepoType.Unknown); } // TODO find a better way? String url = (String)item.getOptions().get("url"); String branch = (String)item.getOptions().get("branch"); return new RepoBranch(url, branch, RepoType.Unknown); }
[ "protected", "RepoBranch", "getComponentRepoBranch", "(", "Component", "component", ")", "{", "CollectorItem", "item", "=", "component", ".", "getFirstCollectorItemForType", "(", "CollectorType", ".", "SCM", ")", ";", "if", "(", "item", "==", "null", ")", "{", "logger", ".", "warn", "(", "\"Error encountered building pipeline: could not find scm collector item for dashboard.\"", ")", ";", "return", "new", "RepoBranch", "(", "\"\"", ",", "\"\"", ",", "RepoType", ".", "Unknown", ")", ";", "}", "// TODO find a better way?\r", "String", "url", "=", "(", "String", ")", "item", ".", "getOptions", "(", ")", ".", "get", "(", "\"url\"", ")", ";", "String", "branch", "=", "(", "String", ")", "item", ".", "getOptions", "(", ")", ".", "get", "(", "\"branch\"", ")", ";", "return", "new", "RepoBranch", "(", "url", ",", "branch", ",", "RepoType", ".", "Unknown", ")", ";", "}" ]
Determine the SCM url and branch that is set for the component. Information is gathered with the assumption that the data is stored in options.url and options.branch. @param component @return the {@link RepoBranch} that the component uses
[ "Determine", "the", "SCM", "url", "and", "branch", "that", "is", "set", "for", "the", "component", ".", "Information", "is", "gathered", "with", "the", "assumption", "that", "the", "data", "is", "stored", "in", "options", ".", "url", "and", "options", ".", "branch", "." ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/DynamicPipelineServiceImpl.java#L635-L647
osglworks/java-mvc
src/main/java/org/osgl/mvc/result/Forbidden.java
Forbidden.of
public static Forbidden of(int errorCode, Throwable cause) { """ Returns a static Forbidden instance and set the {@link #payload} thread local with error code and cause specified When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param errorCode the app defined error code @return a static Forbidden instance as described above """ touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; }
java
public static Forbidden of(int errorCode, Throwable cause) { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; }
[ "public", "static", "Forbidden", "of", "(", "int", "errorCode", ",", "Throwable", "cause", ")", "{", "touchPayload", "(", ")", ".", "errorCode", "(", "errorCode", ")", ".", "cause", "(", "cause", ")", ";", "return", "_INSTANCE", ";", "}" ]
Returns a static Forbidden instance and set the {@link #payload} thread local with error code and cause specified When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param errorCode the app defined error code @return a static Forbidden instance as described above
[ "Returns", "a", "static", "Forbidden", "instance", "and", "set", "the", "{", "@link", "#payload", "}", "thread", "local", "with", "error", "code", "and", "cause", "specified" ]
train
https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/Forbidden.java#L191-L194
groupon/robo-remote
RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Utils.java
Utils.getEnv
public static String getEnv(String name, String defaultValue) { """ returns values for a key in the following order: 1. First checks environment variables 2. Falls back to system properties @param name @param defaultValue @return """ Map<String, String> env = System.getenv(); // try to get value from environment variables if (env.get(name) != null) { return env.get(name); } // fall back to system properties return System.getProperty(name, defaultValue); }
java
public static String getEnv(String name, String defaultValue) { Map<String, String> env = System.getenv(); // try to get value from environment variables if (env.get(name) != null) { return env.get(name); } // fall back to system properties return System.getProperty(name, defaultValue); }
[ "public", "static", "String", "getEnv", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "Map", "<", "String", ",", "String", ">", "env", "=", "System", ".", "getenv", "(", ")", ";", "// try to get value from environment variables", "if", "(", "env", ".", "get", "(", "name", ")", "!=", "null", ")", "{", "return", "env", ".", "get", "(", "name", ")", ";", "}", "// fall back to system properties", "return", "System", ".", "getProperty", "(", "name", ",", "defaultValue", ")", ";", "}" ]
returns values for a key in the following order: 1. First checks environment variables 2. Falls back to system properties @param name @param defaultValue @return
[ "returns", "values", "for", "a", "key", "in", "the", "following", "order", ":", "1", ".", "First", "checks", "environment", "variables", "2", ".", "Falls", "back", "to", "system", "properties" ]
train
https://github.com/groupon/robo-remote/blob/12d242faad50bf90f98657ca9a0c0c3ae1993f07/RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Utils.java#L69-L79
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailArchiver.java
MailArchiver.archiveMessage
public File archiveMessage(final MailMessage message) { """ Saves a message's test content (including headers) in the current module archive in the specified sub-directory relative to the archive root. File names are prefixed with a left-padded four-digit integer counter (format: {@code %04d_%s.txt}). @param message the message @return the file the e-mail was written to """ try { String subject = message.getSubject(); String fileName = subject == null ? "no_subject" : INVALID_FILE_NAME_CHARS.matcher(subject).replaceAll("_"); MutableInt counter = counterProvider.get(); File dir = new File("e-mails", "unread"); File file = new File(dir, String.format(FILE_NAME_FORMAT, counter.intValue(), fileName)); file = new File(moduleArchiveDirProvider.get(), file.getPath()); createParentDirs(file); log.debug("Archiving e-mail: {}", file); StrBuilder sb = new StrBuilder(500); for (Entry<String, String> header : message.getHeaders().entries()) { sb.append(header.getKey()).append('=').appendln(header.getValue()); } sb.appendln(""); sb.append(message.getText()); write(sb.toString(), file, Charsets.UTF_8); counter.increment(); return file; } catch (IOException ex) { throw new MailException("Error archiving mail.", ex); } }
java
public File archiveMessage(final MailMessage message) { try { String subject = message.getSubject(); String fileName = subject == null ? "no_subject" : INVALID_FILE_NAME_CHARS.matcher(subject).replaceAll("_"); MutableInt counter = counterProvider.get(); File dir = new File("e-mails", "unread"); File file = new File(dir, String.format(FILE_NAME_FORMAT, counter.intValue(), fileName)); file = new File(moduleArchiveDirProvider.get(), file.getPath()); createParentDirs(file); log.debug("Archiving e-mail: {}", file); StrBuilder sb = new StrBuilder(500); for (Entry<String, String> header : message.getHeaders().entries()) { sb.append(header.getKey()).append('=').appendln(header.getValue()); } sb.appendln(""); sb.append(message.getText()); write(sb.toString(), file, Charsets.UTF_8); counter.increment(); return file; } catch (IOException ex) { throw new MailException("Error archiving mail.", ex); } }
[ "public", "File", "archiveMessage", "(", "final", "MailMessage", "message", ")", "{", "try", "{", "String", "subject", "=", "message", ".", "getSubject", "(", ")", ";", "String", "fileName", "=", "subject", "==", "null", "?", "\"no_subject\"", ":", "INVALID_FILE_NAME_CHARS", ".", "matcher", "(", "subject", ")", ".", "replaceAll", "(", "\"_\"", ")", ";", "MutableInt", "counter", "=", "counterProvider", ".", "get", "(", ")", ";", "File", "dir", "=", "new", "File", "(", "\"e-mails\"", ",", "\"unread\"", ")", ";", "File", "file", "=", "new", "File", "(", "dir", ",", "String", ".", "format", "(", "FILE_NAME_FORMAT", ",", "counter", ".", "intValue", "(", ")", ",", "fileName", ")", ")", ";", "file", "=", "new", "File", "(", "moduleArchiveDirProvider", ".", "get", "(", ")", ",", "file", ".", "getPath", "(", ")", ")", ";", "createParentDirs", "(", "file", ")", ";", "log", ".", "debug", "(", "\"Archiving e-mail: {}\"", ",", "file", ")", ";", "StrBuilder", "sb", "=", "new", "StrBuilder", "(", "500", ")", ";", "for", "(", "Entry", "<", "String", ",", "String", ">", "header", ":", "message", ".", "getHeaders", "(", ")", ".", "entries", "(", ")", ")", "{", "sb", ".", "append", "(", "header", ".", "getKey", "(", ")", ")", ".", "append", "(", "'", "'", ")", ".", "appendln", "(", "header", ".", "getValue", "(", ")", ")", ";", "}", "sb", ".", "appendln", "(", "\"\"", ")", ";", "sb", ".", "append", "(", "message", ".", "getText", "(", ")", ")", ";", "write", "(", "sb", ".", "toString", "(", ")", ",", "file", ",", "Charsets", ".", "UTF_8", ")", ";", "counter", ".", "increment", "(", ")", ";", "return", "file", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MailException", "(", "\"Error archiving mail.\"", ",", "ex", ")", ";", "}", "}" ]
Saves a message's test content (including headers) in the current module archive in the specified sub-directory relative to the archive root. File names are prefixed with a left-padded four-digit integer counter (format: {@code %04d_%s.txt}). @param message the message @return the file the e-mail was written to
[ "Saves", "a", "message", "s", "test", "content", "(", "including", "headers", ")", "in", "the", "current", "module", "archive", "in", "the", "specified", "sub", "-", "directory", "relative", "to", "the", "archive", "root", ".", "File", "names", "are", "prefixed", "with", "a", "left", "-", "padded", "four", "-", "digit", "integer", "counter", "(", "format", ":", "{", "@code", "%04d_%s", ".", "txt", "}", ")", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailArchiver.java#L69-L97
google/closure-compiler
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
PeepholeFoldConstants.tryFoldGetProp
private Node tryFoldGetProp(Node n, Node left, Node right) { """ Try to fold array-length. e.g [1, 2, 3].length ==> 3, [x, y].length ==> 2 """ checkArgument(n.isGetProp()); if (left.isObjectLit()) { return tryFoldObjectPropAccess(n, left, right); } if (right.isString() && right.getString().equals("length")) { int knownLength = -1; switch (left.getToken()) { case ARRAYLIT: if (mayHaveSideEffects(left)) { // Nope, can't fold this, without handling the side-effects. return n; } knownLength = left.getChildCount(); break; case STRING: knownLength = left.getString().length(); break; default: // Not a foldable case, forget it. return n; } checkState(knownLength != -1); Node lengthNode = IR.number(knownLength); reportChangeToEnclosingScope(n); n.replaceWith(lengthNode); return lengthNode; } return n; }
java
private Node tryFoldGetProp(Node n, Node left, Node right) { checkArgument(n.isGetProp()); if (left.isObjectLit()) { return tryFoldObjectPropAccess(n, left, right); } if (right.isString() && right.getString().equals("length")) { int knownLength = -1; switch (left.getToken()) { case ARRAYLIT: if (mayHaveSideEffects(left)) { // Nope, can't fold this, without handling the side-effects. return n; } knownLength = left.getChildCount(); break; case STRING: knownLength = left.getString().length(); break; default: // Not a foldable case, forget it. return n; } checkState(knownLength != -1); Node lengthNode = IR.number(knownLength); reportChangeToEnclosingScope(n); n.replaceWith(lengthNode); return lengthNode; } return n; }
[ "private", "Node", "tryFoldGetProp", "(", "Node", "n", ",", "Node", "left", ",", "Node", "right", ")", "{", "checkArgument", "(", "n", ".", "isGetProp", "(", ")", ")", ";", "if", "(", "left", ".", "isObjectLit", "(", ")", ")", "{", "return", "tryFoldObjectPropAccess", "(", "n", ",", "left", ",", "right", ")", ";", "}", "if", "(", "right", ".", "isString", "(", ")", "&&", "right", ".", "getString", "(", ")", ".", "equals", "(", "\"length\"", ")", ")", "{", "int", "knownLength", "=", "-", "1", ";", "switch", "(", "left", ".", "getToken", "(", ")", ")", "{", "case", "ARRAYLIT", ":", "if", "(", "mayHaveSideEffects", "(", "left", ")", ")", "{", "// Nope, can't fold this, without handling the side-effects.", "return", "n", ";", "}", "knownLength", "=", "left", ".", "getChildCount", "(", ")", ";", "break", ";", "case", "STRING", ":", "knownLength", "=", "left", ".", "getString", "(", ")", ".", "length", "(", ")", ";", "break", ";", "default", ":", "// Not a foldable case, forget it.", "return", "n", ";", "}", "checkState", "(", "knownLength", "!=", "-", "1", ")", ";", "Node", "lengthNode", "=", "IR", ".", "number", "(", "knownLength", ")", ";", "reportChangeToEnclosingScope", "(", "n", ")", ";", "n", ".", "replaceWith", "(", "lengthNode", ")", ";", "return", "lengthNode", ";", "}", "return", "n", ";", "}" ]
Try to fold array-length. e.g [1, 2, 3].length ==> 3, [x, y].length ==> 2
[ "Try", "to", "fold", "array", "-", "length", ".", "e", ".", "g", "[", "1", "2", "3", "]", ".", "length", "==", ">", "3", "[", "x", "y", "]", ".", "length", "==", ">", "2" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PeepholeFoldConstants.java#L1321-L1356
trellis-ldp/trellis
components/webdav/src/main/java/org/trellisldp/webdav/TrellisWebDAV.java
TrellisWebDAV.moveResource
@MOVE @Timed public void moveResource(@Suspended final AsyncResponse response, @Context final Request request, @Context final UriInfo uriInfo, @Context final HttpHeaders headers, @Context final SecurityContext security) { """ Move a resource. @param response the async response @param request the request @param uriInfo the URI info @param headers the headers @param security the security context """ final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security); final String baseUrl = getBaseUrl(req); final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath()); final IRI destination = getDestination(headers, baseUrl); final Session session = getSession(req.getPrincipalName()); getParent(destination) .thenCombine(services.getResourceService().get(destination), this::checkResources) .thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier())) .thenCompose(future -> services.getResourceService().get(identifier)) .thenApply(this::checkResource) // Note: all MOVE operations are recursive (Depth: infinity), hence recursiveCopy .thenAccept(res -> recursiveCopy(services, session, res, destination, baseUrl)) .thenAccept(future -> recursiveDelete(services, session, identifier, baseUrl)) .thenCompose(future -> services.getResourceService().delete(Metadata.builder(identifier) .interactionModel(LDP.Resource).build())) .thenCompose(future -> { final TrellisDataset immutable = TrellisDataset.createDataset(); services.getAuditService().creation(identifier, session).stream() .map(skolemizeQuads(services.getResourceService(), baseUrl)).forEachOrdered(immutable::add); return services.getResourceService().add(identifier, immutable.asDataset()) .whenComplete((a, b) -> immutable.close()); }) .thenAccept(future -> services.getEventService().emit(new SimpleEvent(externalUrl(identifier, baseUrl), session.getAgent(), asList(PROV.Activity, AS.Delete), singletonList(LDP.Resource)))) .thenApply(future -> status(NO_CONTENT).build()) .exceptionally(this::handleException).thenApply(response::resume); }
java
@MOVE @Timed public void moveResource(@Suspended final AsyncResponse response, @Context final Request request, @Context final UriInfo uriInfo, @Context final HttpHeaders headers, @Context final SecurityContext security) { final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security); final String baseUrl = getBaseUrl(req); final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath()); final IRI destination = getDestination(headers, baseUrl); final Session session = getSession(req.getPrincipalName()); getParent(destination) .thenCombine(services.getResourceService().get(destination), this::checkResources) .thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier())) .thenCompose(future -> services.getResourceService().get(identifier)) .thenApply(this::checkResource) // Note: all MOVE operations are recursive (Depth: infinity), hence recursiveCopy .thenAccept(res -> recursiveCopy(services, session, res, destination, baseUrl)) .thenAccept(future -> recursiveDelete(services, session, identifier, baseUrl)) .thenCompose(future -> services.getResourceService().delete(Metadata.builder(identifier) .interactionModel(LDP.Resource).build())) .thenCompose(future -> { final TrellisDataset immutable = TrellisDataset.createDataset(); services.getAuditService().creation(identifier, session).stream() .map(skolemizeQuads(services.getResourceService(), baseUrl)).forEachOrdered(immutable::add); return services.getResourceService().add(identifier, immutable.asDataset()) .whenComplete((a, b) -> immutable.close()); }) .thenAccept(future -> services.getEventService().emit(new SimpleEvent(externalUrl(identifier, baseUrl), session.getAgent(), asList(PROV.Activity, AS.Delete), singletonList(LDP.Resource)))) .thenApply(future -> status(NO_CONTENT).build()) .exceptionally(this::handleException).thenApply(response::resume); }
[ "@", "MOVE", "@", "Timed", "public", "void", "moveResource", "(", "@", "Suspended", "final", "AsyncResponse", "response", ",", "@", "Context", "final", "Request", "request", ",", "@", "Context", "final", "UriInfo", "uriInfo", ",", "@", "Context", "final", "HttpHeaders", "headers", ",", "@", "Context", "final", "SecurityContext", "security", ")", "{", "final", "TrellisRequest", "req", "=", "new", "TrellisRequest", "(", "request", ",", "uriInfo", ",", "headers", ",", "security", ")", ";", "final", "String", "baseUrl", "=", "getBaseUrl", "(", "req", ")", ";", "final", "IRI", "identifier", "=", "rdf", ".", "createIRI", "(", "TRELLIS_DATA_PREFIX", "+", "req", ".", "getPath", "(", ")", ")", ";", "final", "IRI", "destination", "=", "getDestination", "(", "headers", ",", "baseUrl", ")", ";", "final", "Session", "session", "=", "getSession", "(", "req", ".", "getPrincipalName", "(", ")", ")", ";", "getParent", "(", "destination", ")", ".", "thenCombine", "(", "services", ".", "getResourceService", "(", ")", ".", "get", "(", "destination", ")", ",", "this", "::", "checkResources", ")", ".", "thenCompose", "(", "parent", "->", "services", ".", "getResourceService", "(", ")", ".", "touch", "(", "parent", ".", "getIdentifier", "(", ")", ")", ")", ".", "thenCompose", "(", "future", "->", "services", ".", "getResourceService", "(", ")", ".", "get", "(", "identifier", ")", ")", ".", "thenApply", "(", "this", "::", "checkResource", ")", "// Note: all MOVE operations are recursive (Depth: infinity), hence recursiveCopy", ".", "thenAccept", "(", "res", "->", "recursiveCopy", "(", "services", ",", "session", ",", "res", ",", "destination", ",", "baseUrl", ")", ")", ".", "thenAccept", "(", "future", "->", "recursiveDelete", "(", "services", ",", "session", ",", "identifier", ",", "baseUrl", ")", ")", ".", "thenCompose", "(", "future", "->", "services", ".", "getResourceService", "(", ")", ".", "delete", "(", "Metadata", ".", "builder", "(", "identifier", ")", ".", "interactionModel", "(", "LDP", ".", "Resource", ")", ".", "build", "(", ")", ")", ")", ".", "thenCompose", "(", "future", "->", "{", "final", "TrellisDataset", "immutable", "=", "TrellisDataset", ".", "createDataset", "(", ")", ";", "services", ".", "getAuditService", "(", ")", ".", "creation", "(", "identifier", ",", "session", ")", ".", "stream", "(", ")", ".", "map", "(", "skolemizeQuads", "(", "services", ".", "getResourceService", "(", ")", ",", "baseUrl", ")", ")", ".", "forEachOrdered", "(", "immutable", "::", "add", ")", ";", "return", "services", ".", "getResourceService", "(", ")", ".", "add", "(", "identifier", ",", "immutable", ".", "asDataset", "(", ")", ")", ".", "whenComplete", "(", "(", "a", ",", "b", ")", "->", "immutable", ".", "close", "(", ")", ")", ";", "}", ")", ".", "thenAccept", "(", "future", "->", "services", ".", "getEventService", "(", ")", ".", "emit", "(", "new", "SimpleEvent", "(", "externalUrl", "(", "identifier", ",", "baseUrl", ")", ",", "session", ".", "getAgent", "(", ")", ",", "asList", "(", "PROV", ".", "Activity", ",", "AS", ".", "Delete", ")", ",", "singletonList", "(", "LDP", ".", "Resource", ")", ")", ")", ")", ".", "thenApply", "(", "future", "->", "status", "(", "NO_CONTENT", ")", ".", "build", "(", ")", ")", ".", "exceptionally", "(", "this", "::", "handleException", ")", ".", "thenApply", "(", "response", "::", "resume", ")", ";", "}" ]
Move a resource. @param response the async response @param request the request @param uriInfo the URI info @param headers the headers @param security the security context
[ "Move", "a", "resource", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/webdav/src/main/java/org/trellisldp/webdav/TrellisWebDAV.java#L195-L227
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java
GenericType.where
@NonNull public final <X> GenericType<T> where( @NonNull GenericTypeParameter<X> freeVariable, @NonNull Class<X> actualType) { """ Substitutes a free type variable with an actual type. See {@link GenericType this class's javadoc} for an example. """ return where(freeVariable, GenericType.of(actualType)); }
java
@NonNull public final <X> GenericType<T> where( @NonNull GenericTypeParameter<X> freeVariable, @NonNull Class<X> actualType) { return where(freeVariable, GenericType.of(actualType)); }
[ "@", "NonNull", "public", "final", "<", "X", ">", "GenericType", "<", "T", ">", "where", "(", "@", "NonNull", "GenericTypeParameter", "<", "X", ">", "freeVariable", ",", "@", "NonNull", "Class", "<", "X", ">", "actualType", ")", "{", "return", "where", "(", "freeVariable", ",", "GenericType", ".", "of", "(", "actualType", ")", ")", ";", "}" ]
Substitutes a free type variable with an actual type. See {@link GenericType this class's javadoc} for an example.
[ "Substitutes", "a", "free", "type", "variable", "with", "an", "actual", "type", ".", "See", "{" ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java#L249-L253
mbenson/therian
core/src/main/java/therian/TherianContext.java
TherianContext.supports
public synchronized <RESULT> boolean supports(final Operation<RESULT> operation, Hint... hints) { """ Learn whether {@code operation} is supported by this context. @param operation @return boolean @throws NullPointerException on {@code null} input """ final Frame<RESULT> frame = new Frame<>(Phase.SUPPORT_CHECK, operation, hints); try { return handle(frame); } catch (Frame.RecursionException e) { return false; } }
java
public synchronized <RESULT> boolean supports(final Operation<RESULT> operation, Hint... hints) { final Frame<RESULT> frame = new Frame<>(Phase.SUPPORT_CHECK, operation, hints); try { return handle(frame); } catch (Frame.RecursionException e) { return false; } }
[ "public", "synchronized", "<", "RESULT", ">", "boolean", "supports", "(", "final", "Operation", "<", "RESULT", ">", "operation", ",", "Hint", "...", "hints", ")", "{", "final", "Frame", "<", "RESULT", ">", "frame", "=", "new", "Frame", "<>", "(", "Phase", ".", "SUPPORT_CHECK", ",", "operation", ",", "hints", ")", ";", "try", "{", "return", "handle", "(", "frame", ")", ";", "}", "catch", "(", "Frame", ".", "RecursionException", "e", ")", "{", "return", "false", ";", "}", "}" ]
Learn whether {@code operation} is supported by this context. @param operation @return boolean @throws NullPointerException on {@code null} input
[ "Learn", "whether", "{", "@code", "operation", "}", "is", "supported", "by", "this", "context", "." ]
train
https://github.com/mbenson/therian/blob/0653505f73e2a6f5b0abc394ea6d83af03408254/core/src/main/java/therian/TherianContext.java#L359-L366
ReactiveX/RxJavaAsyncUtil
src/main/java/rx/util/async/operators/Functionals.java
Functionals.fromRunnable
public static Action0 fromRunnable(Runnable run, Worker inner) { """ Converts a runnable instance into an Action0 instance. @param run the Runnable to run when the Action0 is called @return the Action0 wrapping the Runnable """ if (run == null) { throw new NullPointerException("run"); } return new ActionWrappingRunnable(run, inner); }
java
public static Action0 fromRunnable(Runnable run, Worker inner) { if (run == null) { throw new NullPointerException("run"); } return new ActionWrappingRunnable(run, inner); }
[ "public", "static", "Action0", "fromRunnable", "(", "Runnable", "run", ",", "Worker", "inner", ")", "{", "if", "(", "run", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"run\"", ")", ";", "}", "return", "new", "ActionWrappingRunnable", "(", "run", ",", "inner", ")", ";", "}" ]
Converts a runnable instance into an Action0 instance. @param run the Runnable to run when the Action0 is called @return the Action0 wrapping the Runnable
[ "Converts", "a", "runnable", "instance", "into", "an", "Action0", "instance", "." ]
train
https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/operators/Functionals.java#L69-L74
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addConstraintsTypeAnyMessage
public FessMessages addConstraintsTypeAnyMessage(String property, String propertyType) { """ Add the created action message for the key 'constraints.TypeAny.message' with parameters. <pre> message: {item} cannot convert as {propertyType}. </pre> @param property The property name for the message. (NotNull) @param propertyType The parameter propertyType for message. (NotNull) @return this. (NotNull) """ assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeAny_MESSAGE, propertyType)); return this; }
java
public FessMessages addConstraintsTypeAnyMessage(String property, String propertyType) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeAny_MESSAGE, propertyType)); return this; }
[ "public", "FessMessages", "addConstraintsTypeAnyMessage", "(", "String", "property", ",", "String", "propertyType", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "CONSTRAINTS_TypeAny_MESSAGE", ",", "propertyType", ")", ")", ";", "return", "this", ";", "}" ]
Add the created action message for the key 'constraints.TypeAny.message' with parameters. <pre> message: {item} cannot convert as {propertyType}. </pre> @param property The property name for the message. (NotNull) @param propertyType The parameter propertyType for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "constraints", ".", "TypeAny", ".", "message", "with", "parameters", ".", "<pre", ">", "message", ":", "{", "item", "}", "cannot", "convert", "as", "{", "propertyType", "}", ".", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L1092-L1096
bwkimmel/java-util
src/main/java/ca/eandb/util/FloatArray.java
FloatArray.addAll
public boolean addAll(int index, FloatArray items) { """ Inserts values into the array at the specified index. @param index The index at which to insert the new values. @param items A <code>FloatArray</code> containing the values to insert. @return A value indicating if the array has changed. @throws IndexOutOfBoundsException if <code>index &lt; 0 || index &gt; size()</code>. """ if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } ensureCapacity(size + items.size); if (index < size) { for (int i = size - 1; i >= index; i--) { elements[i + items.size] = elements[i]; } } for (int i = 0; i < items.size; i++) { elements[index++] = items.elements[i]; } size += items.size; return items.size > 0; }
java
public boolean addAll(int index, FloatArray items) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } ensureCapacity(size + items.size); if (index < size) { for (int i = size - 1; i >= index; i--) { elements[i + items.size] = elements[i]; } } for (int i = 0; i < items.size; i++) { elements[index++] = items.elements[i]; } size += items.size; return items.size > 0; }
[ "public", "boolean", "addAll", "(", "int", "index", ",", "FloatArray", "items", ")", "{", "if", "(", "index", "<", "0", "||", "index", ">", "size", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "ensureCapacity", "(", "size", "+", "items", ".", "size", ")", ";", "if", "(", "index", "<", "size", ")", "{", "for", "(", "int", "i", "=", "size", "-", "1", ";", "i", ">=", "index", ";", "i", "--", ")", "{", "elements", "[", "i", "+", "items", ".", "size", "]", "=", "elements", "[", "i", "]", ";", "}", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "items", ".", "size", ";", "i", "++", ")", "{", "elements", "[", "index", "++", "]", "=", "items", ".", "elements", "[", "i", "]", ";", "}", "size", "+=", "items", ".", "size", ";", "return", "items", ".", "size", ">", "0", ";", "}" ]
Inserts values into the array at the specified index. @param index The index at which to insert the new values. @param items A <code>FloatArray</code> containing the values to insert. @return A value indicating if the array has changed. @throws IndexOutOfBoundsException if <code>index &lt; 0 || index &gt; size()</code>.
[ "Inserts", "values", "into", "the", "array", "at", "the", "specified", "index", "." ]
train
https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/FloatArray.java#L457-L472
hypercube1024/firefly
firefly/src/main/java/com/firefly/codec/http2/encode/UrlEncoded.java
UrlEncoded.decodeTo
public static void decodeTo(InputStream in, MultiMap<String> map, String charset, int maxLength, int maxKeys) throws IOException { """ Decoded parameters to Map. @param in the stream containing the encoded parameters @param map the MultiMap to decode into @param charset the charset to use for decoding @param maxLength the maximum length of the form to decode @param maxKeys the maximum number of keys to decode @throws IOException if unable to decode input stream """ if (charset == null) { if (ENCODING.equals(StandardCharsets.UTF_8)) decodeUtf8To(in, map, maxLength, maxKeys); else decodeTo(in, map, ENCODING, maxLength, maxKeys); } else if (StringUtils.__UTF8.equalsIgnoreCase(charset)) decodeUtf8To(in, map, maxLength, maxKeys); else if (StringUtils.__ISO_8859_1.equalsIgnoreCase(charset)) decode88591To(in, map, maxLength, maxKeys); else if (StringUtils.__UTF16.equalsIgnoreCase(charset)) decodeUtf16To(in, map, maxLength, maxKeys); else decodeTo(in, map, Charset.forName(charset), maxLength, maxKeys); }
java
public static void decodeTo(InputStream in, MultiMap<String> map, String charset, int maxLength, int maxKeys) throws IOException { if (charset == null) { if (ENCODING.equals(StandardCharsets.UTF_8)) decodeUtf8To(in, map, maxLength, maxKeys); else decodeTo(in, map, ENCODING, maxLength, maxKeys); } else if (StringUtils.__UTF8.equalsIgnoreCase(charset)) decodeUtf8To(in, map, maxLength, maxKeys); else if (StringUtils.__ISO_8859_1.equalsIgnoreCase(charset)) decode88591To(in, map, maxLength, maxKeys); else if (StringUtils.__UTF16.equalsIgnoreCase(charset)) decodeUtf16To(in, map, maxLength, maxKeys); else decodeTo(in, map, Charset.forName(charset), maxLength, maxKeys); }
[ "public", "static", "void", "decodeTo", "(", "InputStream", "in", ",", "MultiMap", "<", "String", ">", "map", ",", "String", "charset", ",", "int", "maxLength", ",", "int", "maxKeys", ")", "throws", "IOException", "{", "if", "(", "charset", "==", "null", ")", "{", "if", "(", "ENCODING", ".", "equals", "(", "StandardCharsets", ".", "UTF_8", ")", ")", "decodeUtf8To", "(", "in", ",", "map", ",", "maxLength", ",", "maxKeys", ")", ";", "else", "decodeTo", "(", "in", ",", "map", ",", "ENCODING", ",", "maxLength", ",", "maxKeys", ")", ";", "}", "else", "if", "(", "StringUtils", ".", "__UTF8", ".", "equalsIgnoreCase", "(", "charset", ")", ")", "decodeUtf8To", "(", "in", ",", "map", ",", "maxLength", ",", "maxKeys", ")", ";", "else", "if", "(", "StringUtils", ".", "__ISO_8859_1", ".", "equalsIgnoreCase", "(", "charset", ")", ")", "decode88591To", "(", "in", ",", "map", ",", "maxLength", ",", "maxKeys", ")", ";", "else", "if", "(", "StringUtils", ".", "__UTF16", ".", "equalsIgnoreCase", "(", "charset", ")", ")", "decodeUtf16To", "(", "in", ",", "map", ",", "maxLength", ",", "maxKeys", ")", ";", "else", "decodeTo", "(", "in", ",", "map", ",", "Charset", ".", "forName", "(", "charset", ")", ",", "maxLength", ",", "maxKeys", ")", ";", "}" ]
Decoded parameters to Map. @param in the stream containing the encoded parameters @param map the MultiMap to decode into @param charset the charset to use for decoding @param maxLength the maximum length of the form to decode @param maxKeys the maximum number of keys to decode @throws IOException if unable to decode input stream
[ "Decoded", "parameters", "to", "Map", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/encode/UrlEncoded.java#L484-L499
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java
DirectoryServiceClient.setUserPassword
public void setUserPassword(String userName, String password) { """ Set user password. @param userName the user name. @param password the user password. """ ProtocolHeader header = new ProtocolHeader(); header.setType(ProtocolType.SetUserPassword); byte[] secret = null; if(password != null && ! password.isEmpty()){ secret = ObfuscatUtil.base64Encode(password.getBytes()); } SetUserPasswordProtocol p = new SetUserPasswordProtocol(userName, secret); connection.submitRequest(header, p, null); }
java
public void setUserPassword(String userName, String password) { ProtocolHeader header = new ProtocolHeader(); header.setType(ProtocolType.SetUserPassword); byte[] secret = null; if(password != null && ! password.isEmpty()){ secret = ObfuscatUtil.base64Encode(password.getBytes()); } SetUserPasswordProtocol p = new SetUserPasswordProtocol(userName, secret); connection.submitRequest(header, p, null); }
[ "public", "void", "setUserPassword", "(", "String", "userName", ",", "String", "password", ")", "{", "ProtocolHeader", "header", "=", "new", "ProtocolHeader", "(", ")", ";", "header", ".", "setType", "(", "ProtocolType", ".", "SetUserPassword", ")", ";", "byte", "[", "]", "secret", "=", "null", ";", "if", "(", "password", "!=", "null", "&&", "!", "password", ".", "isEmpty", "(", ")", ")", "{", "secret", "=", "ObfuscatUtil", ".", "base64Encode", "(", "password", ".", "getBytes", "(", ")", ")", ";", "}", "SetUserPasswordProtocol", "p", "=", "new", "SetUserPasswordProtocol", "(", "userName", ",", "secret", ")", ";", "connection", ".", "submitRequest", "(", "header", ",", "p", ",", "null", ")", ";", "}" ]
Set user password. @param userName the user name. @param password the user password.
[ "Set", "user", "password", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java#L232-L244
Coveros/selenified
src/main/java/com/coveros/selenified/application/WaitFor.java
WaitFor.promptEquals
public void promptEquals(double seconds, String expectedPromptText) { """ Waits up to the provided wait time for a prompt present on the page has content equal to the expected text. This information will be logged and recorded, with a screenshot for traceability and added debugging support. @param expectedPromptText the expected text of the prompt @param seconds the number of seconds to wait """ try { double timeTook = popup(seconds); timeTook = popupEquals(seconds - timeTook, expectedPromptText); checkPromptEquals(expectedPromptText, seconds, timeTook); } catch (TimeoutException e) { checkPromptEquals(expectedPromptText, seconds, seconds); } }
java
public void promptEquals(double seconds, String expectedPromptText) { try { double timeTook = popup(seconds); timeTook = popupEquals(seconds - timeTook, expectedPromptText); checkPromptEquals(expectedPromptText, seconds, timeTook); } catch (TimeoutException e) { checkPromptEquals(expectedPromptText, seconds, seconds); } }
[ "public", "void", "promptEquals", "(", "double", "seconds", ",", "String", "expectedPromptText", ")", "{", "try", "{", "double", "timeTook", "=", "popup", "(", "seconds", ")", ";", "timeTook", "=", "popupEquals", "(", "seconds", "-", "timeTook", ",", "expectedPromptText", ")", ";", "checkPromptEquals", "(", "expectedPromptText", ",", "seconds", ",", "timeTook", ")", ";", "}", "catch", "(", "TimeoutException", "e", ")", "{", "checkPromptEquals", "(", "expectedPromptText", ",", "seconds", ",", "seconds", ")", ";", "}", "}" ]
Waits up to the provided wait time for a prompt present on the page has content equal to the expected text. This information will be logged and recorded, with a screenshot for traceability and added debugging support. @param expectedPromptText the expected text of the prompt @param seconds the number of seconds to wait
[ "Waits", "up", "to", "the", "provided", "wait", "time", "for", "a", "prompt", "present", "on", "the", "page", "has", "content", "equal", "to", "the", "expected", "text", ".", "This", "information", "will", "be", "logged", "and", "recorded", "with", "a", "screenshot", "for", "traceability", "and", "added", "debugging", "support", "." ]
train
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/WaitFor.java#L628-L636
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java
UCharacter.toUpperCase
public static String toUpperCase(Locale locale, String str) { """ Returns the uppercase version of the argument string. Casing is dependent on the argument locale and context-sensitive. @param locale which string is to be converted in @param str source string to be performed on @return uppercase version of the argument string """ return toUpperCase(getCaseLocale(locale), str); }
java
public static String toUpperCase(Locale locale, String str) { return toUpperCase(getCaseLocale(locale), str); }
[ "public", "static", "String", "toUpperCase", "(", "Locale", "locale", ",", "String", "str", ")", "{", "return", "toUpperCase", "(", "getCaseLocale", "(", "locale", ")", ",", "str", ")", ";", "}" ]
Returns the uppercase version of the argument string. Casing is dependent on the argument locale and context-sensitive. @param locale which string is to be converted in @param str source string to be performed on @return uppercase version of the argument string
[ "Returns", "the", "uppercase", "version", "of", "the", "argument", "string", ".", "Casing", "is", "dependent", "on", "the", "argument", "locale", "and", "context", "-", "sensitive", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java#L4409-L4412
hankcs/HanLP
src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java
MDAG.getStrings
private void getStrings(HashSet<String> strHashSet, SearchCondition searchCondition, String searchConditionString, String prefixString, TreeMap<Character, MDAGNode> transitionTreeMap) { """ Retrieves Strings corresponding to all valid _transition paths from a given node that satisfy a given condition. @param strHashSet a HashSet of Strings to contain all those in the MDAG satisfying {@code searchCondition} with {@code conditionString} @param searchCondition the SearchCondition enum field describing the type of relationship that Strings contained in the MDAG must have with {@code conditionString} in order to be included in the result set @param searchConditionString the String that all Strings in the MDAG must be related with in the fashion denoted by {@code searchCondition} in order to be included in the result set @param prefixString the String corresponding to the currently traversed _transition path @param transitionTreeMap a TreeMap of Characters to MDAGNodes collectively representing an MDAGNode's _transition set """ //Traverse all the valid _transition paths beginning from each _transition in transitionTreeMap, inserting the //corresponding Strings in to strHashSet that have the relationship with conditionString denoted by searchCondition for (Entry<Character, MDAGNode> transitionKeyValuePair : transitionTreeMap.entrySet()) { String newPrefixString = prefixString + transitionKeyValuePair.getKey(); MDAGNode currentNode = transitionKeyValuePair.getValue(); if (currentNode.isAcceptNode() && searchCondition.satisfiesCondition(newPrefixString, searchConditionString)) strHashSet.add(newPrefixString); //Recursively call this to traverse all the valid _transition paths from currentNode getStrings(strHashSet, searchCondition, searchConditionString, newPrefixString, currentNode.getOutgoingTransitions()); } ///// }
java
private void getStrings(HashSet<String> strHashSet, SearchCondition searchCondition, String searchConditionString, String prefixString, TreeMap<Character, MDAGNode> transitionTreeMap) { //Traverse all the valid _transition paths beginning from each _transition in transitionTreeMap, inserting the //corresponding Strings in to strHashSet that have the relationship with conditionString denoted by searchCondition for (Entry<Character, MDAGNode> transitionKeyValuePair : transitionTreeMap.entrySet()) { String newPrefixString = prefixString + transitionKeyValuePair.getKey(); MDAGNode currentNode = transitionKeyValuePair.getValue(); if (currentNode.isAcceptNode() && searchCondition.satisfiesCondition(newPrefixString, searchConditionString)) strHashSet.add(newPrefixString); //Recursively call this to traverse all the valid _transition paths from currentNode getStrings(strHashSet, searchCondition, searchConditionString, newPrefixString, currentNode.getOutgoingTransitions()); } ///// }
[ "private", "void", "getStrings", "(", "HashSet", "<", "String", ">", "strHashSet", ",", "SearchCondition", "searchCondition", ",", "String", "searchConditionString", ",", "String", "prefixString", ",", "TreeMap", "<", "Character", ",", "MDAGNode", ">", "transitionTreeMap", ")", "{", "//Traverse all the valid _transition paths beginning from each _transition in transitionTreeMap, inserting the", "//corresponding Strings in to strHashSet that have the relationship with conditionString denoted by searchCondition", "for", "(", "Entry", "<", "Character", ",", "MDAGNode", ">", "transitionKeyValuePair", ":", "transitionTreeMap", ".", "entrySet", "(", ")", ")", "{", "String", "newPrefixString", "=", "prefixString", "+", "transitionKeyValuePair", ".", "getKey", "(", ")", ";", "MDAGNode", "currentNode", "=", "transitionKeyValuePair", ".", "getValue", "(", ")", ";", "if", "(", "currentNode", ".", "isAcceptNode", "(", ")", "&&", "searchCondition", ".", "satisfiesCondition", "(", "newPrefixString", ",", "searchConditionString", ")", ")", "strHashSet", ".", "add", "(", "newPrefixString", ")", ";", "//Recursively call this to traverse all the valid _transition paths from currentNode", "getStrings", "(", "strHashSet", ",", "searchCondition", ",", "searchConditionString", ",", "newPrefixString", ",", "currentNode", ".", "getOutgoingTransitions", "(", ")", ")", ";", "}", "/////", "}" ]
Retrieves Strings corresponding to all valid _transition paths from a given node that satisfy a given condition. @param strHashSet a HashSet of Strings to contain all those in the MDAG satisfying {@code searchCondition} with {@code conditionString} @param searchCondition the SearchCondition enum field describing the type of relationship that Strings contained in the MDAG must have with {@code conditionString} in order to be included in the result set @param searchConditionString the String that all Strings in the MDAG must be related with in the fashion denoted by {@code searchCondition} in order to be included in the result set @param prefixString the String corresponding to the currently traversed _transition path @param transitionTreeMap a TreeMap of Characters to MDAGNodes collectively representing an MDAGNode's _transition set
[ "Retrieves", "Strings", "corresponding", "to", "all", "valid", "_transition", "paths", "from", "a", "given", "node", "that", "satisfy", "a", "given", "condition", "." ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/collection/MDAG/MDAG.java#L861-L877
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/registry/VisitRegistry.java
VisitRegistry.isVisited
public boolean isVisited(int from, int upTo) { """ Check if the interval and its boundaries were visited. @param from The interval start (inclusive). @param upTo The interval end (exclusive). @return True if visited. """ if (checkBounds(from) && checkBounds(upTo - 1)) { // perform the visit check // for (int i = from; i < upTo; i++) { if (ONE == this.registry[i]) { return true; } } return false; } else { throw new RuntimeException("The location " + from + "," + upTo + " out of bounds [0," + (this.registry.length - 1) + "]"); } }
java
public boolean isVisited(int from, int upTo) { if (checkBounds(from) && checkBounds(upTo - 1)) { // perform the visit check // for (int i = from; i < upTo; i++) { if (ONE == this.registry[i]) { return true; } } return false; } else { throw new RuntimeException("The location " + from + "," + upTo + " out of bounds [0," + (this.registry.length - 1) + "]"); } }
[ "public", "boolean", "isVisited", "(", "int", "from", ",", "int", "upTo", ")", "{", "if", "(", "checkBounds", "(", "from", ")", "&&", "checkBounds", "(", "upTo", "-", "1", ")", ")", "{", "// perform the visit check", "//", "for", "(", "int", "i", "=", "from", ";", "i", "<", "upTo", ";", "i", "++", ")", "{", "if", "(", "ONE", "==", "this", ".", "registry", "[", "i", "]", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"The location \"", "+", "from", "+", "\",\"", "+", "upTo", "+", "\" out of bounds [0,\"", "+", "(", "this", ".", "registry", ".", "length", "-", "1", ")", "+", "\"]\"", ")", ";", "}", "}" ]
Check if the interval and its boundaries were visited. @param from The interval start (inclusive). @param upTo The interval end (exclusive). @return True if visited.
[ "Check", "if", "the", "interval", "and", "its", "boundaries", "were", "visited", "." ]
train
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/registry/VisitRegistry.java#L124-L139
FasterXML/woodstox
src/main/java/com/ctc/wstx/sr/BasicStreamReader.java
BasicStreamReader.skipEquals
protected final char skipEquals(String name, String eofMsg) throws XMLStreamException { """ Method that checks that input following is of form '[S]* '=' [S]*' (as per XML specs, production #25). Will push back non-white space characters as necessary, in case no equals char is encountered. """ char c = getNextInCurrAfterWS(eofMsg); if (c != '=') { throwUnexpectedChar(c, " in xml declaration; expected '=' to follow pseudo-attribute '"+name+"'"); } // trailing space? return getNextInCurrAfterWS(eofMsg); }
java
protected final char skipEquals(String name, String eofMsg) throws XMLStreamException { char c = getNextInCurrAfterWS(eofMsg); if (c != '=') { throwUnexpectedChar(c, " in xml declaration; expected '=' to follow pseudo-attribute '"+name+"'"); } // trailing space? return getNextInCurrAfterWS(eofMsg); }
[ "protected", "final", "char", "skipEquals", "(", "String", "name", ",", "String", "eofMsg", ")", "throws", "XMLStreamException", "{", "char", "c", "=", "getNextInCurrAfterWS", "(", "eofMsg", ")", ";", "if", "(", "c", "!=", "'", "'", ")", "{", "throwUnexpectedChar", "(", "c", ",", "\" in xml declaration; expected '=' to follow pseudo-attribute '\"", "+", "name", "+", "\"'\"", ")", ";", "}", "// trailing space?", "return", "getNextInCurrAfterWS", "(", "eofMsg", ")", ";", "}" ]
Method that checks that input following is of form '[S]* '=' [S]*' (as per XML specs, production #25). Will push back non-white space characters as necessary, in case no equals char is encountered.
[ "Method", "that", "checks", "that", "input", "following", "is", "of", "form", "[", "S", "]", "*", "=", "[", "S", "]", "*", "(", "as", "per", "XML", "specs", "production", "#25", ")", ".", "Will", "push", "back", "non", "-", "white", "space", "characters", "as", "necessary", "in", "case", "no", "equals", "char", "is", "encountered", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/BasicStreamReader.java#L2395-L2404
igniterealtime/Smack
smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleManager.java
JingleManager.triggerSessionRequested
void triggerSessionRequested(Jingle initJin) { """ Activates the listenerJingles on a Jingle session request. @param initJin the stanza that must be passed to the jingleSessionRequestListener. """ JingleSessionRequestListener[] jingleSessionRequestListeners; // Make a synchronized copy of the listenerJingles synchronized (this.jingleSessionRequestListeners) { jingleSessionRequestListeners = new JingleSessionRequestListener[this.jingleSessionRequestListeners.size()]; this.jingleSessionRequestListeners.toArray(jingleSessionRequestListeners); } // ... and let them know of the event JingleSessionRequest request = new JingleSessionRequest(this, initJin); for (int i = 0; i < jingleSessionRequestListeners.length; i++) { jingleSessionRequestListeners[i].sessionRequested(request); } }
java
void triggerSessionRequested(Jingle initJin) { JingleSessionRequestListener[] jingleSessionRequestListeners; // Make a synchronized copy of the listenerJingles synchronized (this.jingleSessionRequestListeners) { jingleSessionRequestListeners = new JingleSessionRequestListener[this.jingleSessionRequestListeners.size()]; this.jingleSessionRequestListeners.toArray(jingleSessionRequestListeners); } // ... and let them know of the event JingleSessionRequest request = new JingleSessionRequest(this, initJin); for (int i = 0; i < jingleSessionRequestListeners.length; i++) { jingleSessionRequestListeners[i].sessionRequested(request); } }
[ "void", "triggerSessionRequested", "(", "Jingle", "initJin", ")", "{", "JingleSessionRequestListener", "[", "]", "jingleSessionRequestListeners", ";", "// Make a synchronized copy of the listenerJingles", "synchronized", "(", "this", ".", "jingleSessionRequestListeners", ")", "{", "jingleSessionRequestListeners", "=", "new", "JingleSessionRequestListener", "[", "this", ".", "jingleSessionRequestListeners", ".", "size", "(", ")", "]", ";", "this", ".", "jingleSessionRequestListeners", ".", "toArray", "(", "jingleSessionRequestListeners", ")", ";", "}", "// ... and let them know of the event", "JingleSessionRequest", "request", "=", "new", "JingleSessionRequest", "(", "this", ",", "initJin", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "jingleSessionRequestListeners", ".", "length", ";", "i", "++", ")", "{", "jingleSessionRequestListeners", "[", "i", "]", ".", "sessionRequested", "(", "request", ")", ";", "}", "}" ]
Activates the listenerJingles on a Jingle session request. @param initJin the stanza that must be passed to the jingleSessionRequestListener.
[ "Activates", "the", "listenerJingles", "on", "a", "Jingle", "session", "request", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/JingleManager.java#L495-L510
haifengl/smile
core/src/main/java/smile/util/SmileUtils.java
SmileUtils.learnGaussianRadialBasis
public static GaussianRadialBasis learnGaussianRadialBasis(double[][] x, double[][] centers) { """ Learns Gaussian RBF function and centers from data. The centers are chosen as the centroids of K-Means. Let d<sub>max</sub> be the maximum distance between the chosen centers, the standard deviation (i.e. width) of Gaussian radial basis function is d<sub>max</sub> / sqrt(2*k), where k is number of centers. This choice would be close to the optimal solution if the data were uniformly distributed in the input space, leading to a uniform distribution of centroids. @param x the training dataset. @param centers an array to store centers on output. Its length is used as k of k-means. @return a Gaussian RBF function with parameter learned from data. """ int k = centers.length; KMeans kmeans = new KMeans(x, k, 10); System.arraycopy(kmeans.centroids(), 0, centers, 0, k); double r0 = 0.0; for (int i = 0; i < k; i++) { for (int j = 0; j < i; j++) { double d = Math.distance(centers[i], centers[j]); if (r0 < d) { r0 = d; } } } r0 /= Math.sqrt(2*k); return new GaussianRadialBasis(r0); }
java
public static GaussianRadialBasis learnGaussianRadialBasis(double[][] x, double[][] centers) { int k = centers.length; KMeans kmeans = new KMeans(x, k, 10); System.arraycopy(kmeans.centroids(), 0, centers, 0, k); double r0 = 0.0; for (int i = 0; i < k; i++) { for (int j = 0; j < i; j++) { double d = Math.distance(centers[i], centers[j]); if (r0 < d) { r0 = d; } } } r0 /= Math.sqrt(2*k); return new GaussianRadialBasis(r0); }
[ "public", "static", "GaussianRadialBasis", "learnGaussianRadialBasis", "(", "double", "[", "]", "[", "]", "x", ",", "double", "[", "]", "[", "]", "centers", ")", "{", "int", "k", "=", "centers", ".", "length", ";", "KMeans", "kmeans", "=", "new", "KMeans", "(", "x", ",", "k", ",", "10", ")", ";", "System", ".", "arraycopy", "(", "kmeans", ".", "centroids", "(", ")", ",", "0", ",", "centers", ",", "0", ",", "k", ")", ";", "double", "r0", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "k", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "i", ";", "j", "++", ")", "{", "double", "d", "=", "Math", ".", "distance", "(", "centers", "[", "i", "]", ",", "centers", "[", "j", "]", ")", ";", "if", "(", "r0", "<", "d", ")", "{", "r0", "=", "d", ";", "}", "}", "}", "r0", "/=", "Math", ".", "sqrt", "(", "2", "*", "k", ")", ";", "return", "new", "GaussianRadialBasis", "(", "r0", ")", ";", "}" ]
Learns Gaussian RBF function and centers from data. The centers are chosen as the centroids of K-Means. Let d<sub>max</sub> be the maximum distance between the chosen centers, the standard deviation (i.e. width) of Gaussian radial basis function is d<sub>max</sub> / sqrt(2*k), where k is number of centers. This choice would be close to the optimal solution if the data were uniformly distributed in the input space, leading to a uniform distribution of centroids. @param x the training dataset. @param centers an array to store centers on output. Its length is used as k of k-means. @return a Gaussian RBF function with parameter learned from data.
[ "Learns", "Gaussian", "RBF", "function", "and", "centers", "from", "data", ".", "The", "centers", "are", "chosen", "as", "the", "centroids", "of", "K", "-", "Means", ".", "Let", "d<sub", ">", "max<", "/", "sub", ">", "be", "the", "maximum", "distance", "between", "the", "chosen", "centers", "the", "standard", "deviation", "(", "i", ".", "e", ".", "width", ")", "of", "Gaussian", "radial", "basis", "function", "is", "d<sub", ">", "max<", "/", "sub", ">", "/", "sqrt", "(", "2", "*", "k", ")", "where", "k", "is", "number", "of", "centers", ".", "This", "choice", "would", "be", "close", "to", "the", "optimal", "solution", "if", "the", "data", "were", "uniformly", "distributed", "in", "the", "input", "space", "leading", "to", "a", "uniform", "distribution", "of", "centroids", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/util/SmileUtils.java#L80-L97
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java
SqlFunctionUtils.regexpExtract
public static String regexpExtract(String str, String regex, int extractIndex) { """ Returns a string extracted with a specified regular expression and a regex match group index. """ if (extractIndex < 0) { return null; } try { Matcher m = REGEXP_PATTERN_CACHE.get(regex).matcher(str); if (m.find()) { MatchResult mr = m.toMatchResult(); return mr.group(extractIndex); } return null; } catch (Exception e) { LOG.error( String.format("Exception in regexpExtract('%s', '%s', '%d')", str, regex, extractIndex), e); return null; } }
java
public static String regexpExtract(String str, String regex, int extractIndex) { if (extractIndex < 0) { return null; } try { Matcher m = REGEXP_PATTERN_CACHE.get(regex).matcher(str); if (m.find()) { MatchResult mr = m.toMatchResult(); return mr.group(extractIndex); } return null; } catch (Exception e) { LOG.error( String.format("Exception in regexpExtract('%s', '%s', '%d')", str, regex, extractIndex), e); return null; } }
[ "public", "static", "String", "regexpExtract", "(", "String", "str", ",", "String", "regex", ",", "int", "extractIndex", ")", "{", "if", "(", "extractIndex", "<", "0", ")", "{", "return", "null", ";", "}", "try", "{", "Matcher", "m", "=", "REGEXP_PATTERN_CACHE", ".", "get", "(", "regex", ")", ".", "matcher", "(", "str", ")", ";", "if", "(", "m", ".", "find", "(", ")", ")", "{", "MatchResult", "mr", "=", "m", ".", "toMatchResult", "(", ")", ";", "return", "mr", ".", "group", "(", "extractIndex", ")", ";", "}", "return", "null", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"Exception in regexpExtract('%s', '%s', '%d')\"", ",", "str", ",", "regex", ",", "extractIndex", ")", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Returns a string extracted with a specified regular expression and a regex match group index.
[ "Returns", "a", "string", "extracted", "with", "a", "specified", "regular", "expression", "and", "a", "regex", "match", "group", "index", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java#L372-L390
weld/core
impl/src/main/java/org/jboss/weld/bean/ContextualInstance.java
ContextualInstance.getIfExists
public static <T> T getIfExists(Bean<T> bean, BeanManagerImpl manager) { """ Shortcut for obtaining contextual instances with semantics equivalent to: <code> manager.getContext(bean.getScope()).get(bean); </code> @param bean the given bean @param manager the beanManager @return contextual instance of a given bean or null if none exists """ return getStrategy(bean).getIfExists(bean, manager); }
java
public static <T> T getIfExists(Bean<T> bean, BeanManagerImpl manager) { return getStrategy(bean).getIfExists(bean, manager); }
[ "public", "static", "<", "T", ">", "T", "getIfExists", "(", "Bean", "<", "T", ">", "bean", ",", "BeanManagerImpl", "manager", ")", "{", "return", "getStrategy", "(", "bean", ")", ".", "getIfExists", "(", "bean", ",", "manager", ")", ";", "}" ]
Shortcut for obtaining contextual instances with semantics equivalent to: <code> manager.getContext(bean.getScope()).get(bean); </code> @param bean the given bean @param manager the beanManager @return contextual instance of a given bean or null if none exists
[ "Shortcut", "for", "obtaining", "contextual", "instances", "with", "semantics", "equivalent", "to", ":", "<code", ">", "manager", ".", "getContext", "(", "bean", ".", "getScope", "()", ")", ".", "get", "(", "bean", ")", ";", "<", "/", "code", ">" ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/bean/ContextualInstance.java#L62-L64