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
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPOptionCategoryWrapper.java
CPOptionCategoryWrapper.getDescription
@Override public String getDescription(String languageId, boolean useDefault) { """ Returns the localized description of this cp option category in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized description of this cp option category """ return _cpOptionCategory.getDescription(languageId, useDefault); }
java
@Override public String getDescription(String languageId, boolean useDefault) { return _cpOptionCategory.getDescription(languageId, useDefault); }
[ "@", "Override", "public", "String", "getDescription", "(", "String", "languageId", ",", "boolean", "useDefault", ")", "{", "return", "_cpOptionCategory", ".", "getDescription", "(", "languageId", ",", "useDefault", ")", ";", "}" ]
Returns the localized description of this cp option category in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized description of this cp option category
[ "Returns", "the", "localized", "description", "of", "this", "cp", "option", "category", "in", "the", "language", "optionally", "using", "the", "default", "language", "if", "no", "localization", "exists", "for", "the", "requested", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPOptionCategoryWrapper.java#L262-L265
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java
ReUtil.contains
public static boolean contains(String regex, CharSequence content) { """ 指定内容中是否有表达式匹配的内容 @param regex 正则表达式 @param content 被查找的内容 @return 指定内容中是否有表达式匹配的内容 @since 3.3.1 """ if (null == regex || null == content) { return false; } final Pattern pattern = PatternPool.get(regex, Pattern.DOTALL); return contains(pattern, content); }
java
public static boolean contains(String regex, CharSequence content) { if (null == regex || null == content) { return false; } final Pattern pattern = PatternPool.get(regex, Pattern.DOTALL); return contains(pattern, content); }
[ "public", "static", "boolean", "contains", "(", "String", "regex", ",", "CharSequence", "content", ")", "{", "if", "(", "null", "==", "regex", "||", "null", "==", "content", ")", "{", "return", "false", ";", "}", "final", "Pattern", "pattern", "=", "PatternPool", ".", "get", "(", "regex", ",", "Pattern", ".", "DOTALL", ")", ";", "return", "contains", "(", "pattern", ",", "content", ")", ";", "}" ]
指定内容中是否有表达式匹配的内容 @param regex 正则表达式 @param content 被查找的内容 @return 指定内容中是否有表达式匹配的内容 @since 3.3.1
[ "指定内容中是否有表达式匹配的内容" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L519-L526
alkacon/opencms-core
src/org/opencms/search/solr/CmsSolrQuery.java
CmsSolrQuery.addSortFieldOrders
public void addSortFieldOrders(Map<String, ORDER> sortFields) { """ Adds the given fields/orders to the existing sort fields.<p> @param sortFields the sortFields to set """ if ((sortFields != null) && !sortFields.isEmpty()) { // add the sort fields to the query for (Map.Entry<String, ORDER> entry : sortFields.entrySet()) { addSort(entry.getKey(), entry.getValue()); } } }
java
public void addSortFieldOrders(Map<String, ORDER> sortFields) { if ((sortFields != null) && !sortFields.isEmpty()) { // add the sort fields to the query for (Map.Entry<String, ORDER> entry : sortFields.entrySet()) { addSort(entry.getKey(), entry.getValue()); } } }
[ "public", "void", "addSortFieldOrders", "(", "Map", "<", "String", ",", "ORDER", ">", "sortFields", ")", "{", "if", "(", "(", "sortFields", "!=", "null", ")", "&&", "!", "sortFields", ".", "isEmpty", "(", ")", ")", "{", "// add the sort fields to the query", "for", "(", "Map", ".", "Entry", "<", "String", ",", "ORDER", ">", "entry", ":", "sortFields", ".", "entrySet", "(", ")", ")", "{", "addSort", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
Adds the given fields/orders to the existing sort fields.<p> @param sortFields the sortFields to set
[ "Adds", "the", "given", "fields", "/", "orders", "to", "the", "existing", "sort", "fields", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/CmsSolrQuery.java#L223-L231
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/filter/QueryFilter.java
QueryFilter.getIdentityFilter
public static QueryFilter getIdentityFilter(DecoratedKey key, String cfName, long timestamp) { """ return a QueryFilter object that includes every column in the row. This is dangerous on large rows; avoid except for test code. """ return new QueryFilter(key, cfName, new IdentityQueryFilter(), timestamp); }
java
public static QueryFilter getIdentityFilter(DecoratedKey key, String cfName, long timestamp) { return new QueryFilter(key, cfName, new IdentityQueryFilter(), timestamp); }
[ "public", "static", "QueryFilter", "getIdentityFilter", "(", "DecoratedKey", "key", ",", "String", "cfName", ",", "long", "timestamp", ")", "{", "return", "new", "QueryFilter", "(", "key", ",", "cfName", ",", "new", "IdentityQueryFilter", "(", ")", ",", "timestamp", ")", ";", "}" ]
return a QueryFilter object that includes every column in the row. This is dangerous on large rows; avoid except for test code.
[ "return", "a", "QueryFilter", "object", "that", "includes", "every", "column", "in", "the", "row", ".", "This", "is", "dangerous", "on", "large", "rows", ";", "avoid", "except", "for", "test", "code", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/filter/QueryFilter.java#L225-L228
Bearded-Hen/Android-Bootstrap
AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapDrawableFactory.java
BootstrapDrawableFactory.bootstrapButton
static Drawable bootstrapButton(Context context, BootstrapBrand brand, int strokeWidth, int cornerRadius, ViewGroupPosition position, boolean showOutline, boolean rounded) { """ Generates a background drawable for a Bootstrap Button @param context the current context @param brand the bootstrap brand @param strokeWidth the stroke width in px @param cornerRadius the corner radius in px @param position the position of the button in its parent view @param showOutline whether the button should be outlined @param rounded whether the corners should be rounded @return a background drawable for the BootstrapButton """ GradientDrawable defaultGd = new GradientDrawable(); GradientDrawable activeGd = new GradientDrawable(); GradientDrawable disabledGd = new GradientDrawable(); defaultGd.setColor(showOutline ? Color.TRANSPARENT : brand.defaultFill(context)); activeGd.setColor(showOutline ? brand.activeFill(context) : brand.activeFill(context)); disabledGd.setColor(showOutline ? Color.TRANSPARENT : brand.disabledFill(context)); defaultGd.setStroke(strokeWidth, brand.defaultEdge(context)); activeGd.setStroke(strokeWidth, brand.activeEdge(context)); disabledGd.setStroke(strokeWidth, brand.disabledEdge(context)); if (showOutline && brand instanceof DefaultBootstrapBrand) { DefaultBootstrapBrand db = (DefaultBootstrapBrand) brand; if (db == DefaultBootstrapBrand.SECONDARY) { int color = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context); defaultGd.setStroke(strokeWidth, color); activeGd.setStroke(strokeWidth, color); disabledGd.setStroke(strokeWidth, color); } } setupDrawableCorners(position, rounded, cornerRadius, defaultGd, activeGd, disabledGd); return setupStateDrawable(position, strokeWidth, defaultGd, activeGd, disabledGd); }
java
static Drawable bootstrapButton(Context context, BootstrapBrand brand, int strokeWidth, int cornerRadius, ViewGroupPosition position, boolean showOutline, boolean rounded) { GradientDrawable defaultGd = new GradientDrawable(); GradientDrawable activeGd = new GradientDrawable(); GradientDrawable disabledGd = new GradientDrawable(); defaultGd.setColor(showOutline ? Color.TRANSPARENT : brand.defaultFill(context)); activeGd.setColor(showOutline ? brand.activeFill(context) : brand.activeFill(context)); disabledGd.setColor(showOutline ? Color.TRANSPARENT : brand.disabledFill(context)); defaultGd.setStroke(strokeWidth, brand.defaultEdge(context)); activeGd.setStroke(strokeWidth, brand.activeEdge(context)); disabledGd.setStroke(strokeWidth, brand.disabledEdge(context)); if (showOutline && brand instanceof DefaultBootstrapBrand) { DefaultBootstrapBrand db = (DefaultBootstrapBrand) brand; if (db == DefaultBootstrapBrand.SECONDARY) { int color = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context); defaultGd.setStroke(strokeWidth, color); activeGd.setStroke(strokeWidth, color); disabledGd.setStroke(strokeWidth, color); } } setupDrawableCorners(position, rounded, cornerRadius, defaultGd, activeGd, disabledGd); return setupStateDrawable(position, strokeWidth, defaultGd, activeGd, disabledGd); }
[ "static", "Drawable", "bootstrapButton", "(", "Context", "context", ",", "BootstrapBrand", "brand", ",", "int", "strokeWidth", ",", "int", "cornerRadius", ",", "ViewGroupPosition", "position", ",", "boolean", "showOutline", ",", "boolean", "rounded", ")", "{", "GradientDrawable", "defaultGd", "=", "new", "GradientDrawable", "(", ")", ";", "GradientDrawable", "activeGd", "=", "new", "GradientDrawable", "(", ")", ";", "GradientDrawable", "disabledGd", "=", "new", "GradientDrawable", "(", ")", ";", "defaultGd", ".", "setColor", "(", "showOutline", "?", "Color", ".", "TRANSPARENT", ":", "brand", ".", "defaultFill", "(", "context", ")", ")", ";", "activeGd", ".", "setColor", "(", "showOutline", "?", "brand", ".", "activeFill", "(", "context", ")", ":", "brand", ".", "activeFill", "(", "context", ")", ")", ";", "disabledGd", ".", "setColor", "(", "showOutline", "?", "Color", ".", "TRANSPARENT", ":", "brand", ".", "disabledFill", "(", "context", ")", ")", ";", "defaultGd", ".", "setStroke", "(", "strokeWidth", ",", "brand", ".", "defaultEdge", "(", "context", ")", ")", ";", "activeGd", ".", "setStroke", "(", "strokeWidth", ",", "brand", ".", "activeEdge", "(", "context", ")", ")", ";", "disabledGd", ".", "setStroke", "(", "strokeWidth", ",", "brand", ".", "disabledEdge", "(", "context", ")", ")", ";", "if", "(", "showOutline", "&&", "brand", "instanceof", "DefaultBootstrapBrand", ")", "{", "DefaultBootstrapBrand", "db", "=", "(", "DefaultBootstrapBrand", ")", "brand", ";", "if", "(", "db", "==", "DefaultBootstrapBrand", ".", "SECONDARY", ")", "{", "int", "color", "=", "ColorUtils", ".", "resolveColor", "(", "R", ".", "color", ".", "bootstrap_brand_secondary_border", ",", "context", ")", ";", "defaultGd", ".", "setStroke", "(", "strokeWidth", ",", "color", ")", ";", "activeGd", ".", "setStroke", "(", "strokeWidth", ",", "color", ")", ";", "disabledGd", ".", "setStroke", "(", "strokeWidth", ",", "color", ")", ";", "}", "}", "setupDrawableCorners", "(", "position", ",", "rounded", ",", "cornerRadius", ",", "defaultGd", ",", "activeGd", ",", "disabledGd", ")", ";", "return", "setupStateDrawable", "(", "position", ",", "strokeWidth", ",", "defaultGd", ",", "activeGd", ",", "disabledGd", ")", ";", "}" ]
Generates a background drawable for a Bootstrap Button @param context the current context @param brand the bootstrap brand @param strokeWidth the stroke width in px @param cornerRadius the corner radius in px @param position the position of the button in its parent view @param showOutline whether the button should be outlined @param rounded whether the corners should be rounded @return a background drawable for the BootstrapButton
[ "Generates", "a", "background", "drawable", "for", "a", "Bootstrap", "Button" ]
train
https://github.com/Bearded-Hen/Android-Bootstrap/blob/b3d62cc1847e26d420c53c92665a4fe1e6ee7ecf/AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapDrawableFactory.java#L45-L79
JodaOrg/joda-time
src/main/java/org/joda/time/format/PeriodFormatter.java
PeriodFormatter.printTo
public void printTo(StringBuffer buf, ReadablePeriod period) { """ Prints a ReadablePeriod to a StringBuffer. @param buf the formatted period is appended to this buffer @param period the period to format, not null """ checkPrinter(); checkPeriod(period); getPrinter().printTo(buf, period, iLocale); }
java
public void printTo(StringBuffer buf, ReadablePeriod period) { checkPrinter(); checkPeriod(period); getPrinter().printTo(buf, period, iLocale); }
[ "public", "void", "printTo", "(", "StringBuffer", "buf", ",", "ReadablePeriod", "period", ")", "{", "checkPrinter", "(", ")", ";", "checkPeriod", "(", "period", ")", ";", "getPrinter", "(", ")", ".", "printTo", "(", "buf", ",", "period", ",", "iLocale", ")", ";", "}" ]
Prints a ReadablePeriod to a StringBuffer. @param buf the formatted period is appended to this buffer @param period the period to format, not null
[ "Prints", "a", "ReadablePeriod", "to", "a", "StringBuffer", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/PeriodFormatter.java#L213-L218
Wadpam/guja
guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java
GeneratedDContactDaoImpl.queryByUpdatedBy
public Iterable<DContact> queryByUpdatedBy(Object parent, java.lang.String updatedBy) { """ query-by method for field updatedBy @param updatedBy the specified attribute @return an Iterable of DContacts for the specified updatedBy """ return queryByField(parent, DContactMapper.Field.UPDATEDBY.getFieldName(), updatedBy); }
java
public Iterable<DContact> queryByUpdatedBy(Object parent, java.lang.String updatedBy) { return queryByField(parent, DContactMapper.Field.UPDATEDBY.getFieldName(), updatedBy); }
[ "public", "Iterable", "<", "DContact", ">", "queryByUpdatedBy", "(", "Object", "parent", ",", "java", ".", "lang", ".", "String", "updatedBy", ")", "{", "return", "queryByField", "(", "parent", ",", "DContactMapper", ".", "Field", ".", "UPDATEDBY", ".", "getFieldName", "(", ")", ",", "updatedBy", ")", ";", "}" ]
query-by method for field updatedBy @param updatedBy the specified attribute @return an Iterable of DContacts for the specified updatedBy
[ "query", "-", "by", "method", "for", "field", "updatedBy" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L295-L297
tvesalainen/util
util/src/main/java/org/vesalainen/ui/Scaler.java
Scaler.getLevelFor
public ScaleLevel getLevelFor(Font font, FontRenderContext frc, boolean horizontal) { """ Returns highest level where drawn labels don't overlap using identity transformer @param font @param frc @param horizontal @return """ return getLevelFor(font, frc, horizontal, 0); }
java
public ScaleLevel getLevelFor(Font font, FontRenderContext frc, boolean horizontal) { return getLevelFor(font, frc, horizontal, 0); }
[ "public", "ScaleLevel", "getLevelFor", "(", "Font", "font", ",", "FontRenderContext", "frc", ",", "boolean", "horizontal", ")", "{", "return", "getLevelFor", "(", "font", ",", "frc", ",", "horizontal", ",", "0", ")", ";", "}" ]
Returns highest level where drawn labels don't overlap using identity transformer @param font @param frc @param horizontal @return
[ "Returns", "highest", "level", "where", "drawn", "labels", "don", "t", "overlap", "using", "identity", "transformer" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/ui/Scaler.java#L122-L125
jamesagnew/hapi-fhir
hapi-fhir-osgi-core/src/main/java/ca/uhn/fhir/osgi/FhirServerImpl.java
FhirServerImpl.registerOsgiProvider
@Override public void registerOsgiProvider (Object provider) throws FhirConfigurationException { """ Dynamically registers a single provider with the RestfulServer @param provider the provider to be registered @throws FhirConfigurationException """ if (null == provider) { throw new NullPointerException("FHIR Provider cannot be null"); } try { super.registerProvider(provider); log.trace("registered provider. class ["+provider.getClass().getName()+"]"); this.serverProviders.add(provider); } catch (Exception e) { log.error("Error registering FHIR Provider", e); throw new FhirConfigurationException("Error registering FHIR Provider", e); } }
java
@Override public void registerOsgiProvider (Object provider) throws FhirConfigurationException { if (null == provider) { throw new NullPointerException("FHIR Provider cannot be null"); } try { super.registerProvider(provider); log.trace("registered provider. class ["+provider.getClass().getName()+"]"); this.serverProviders.add(provider); } catch (Exception e) { log.error("Error registering FHIR Provider", e); throw new FhirConfigurationException("Error registering FHIR Provider", e); } }
[ "@", "Override", "public", "void", "registerOsgiProvider", "(", "Object", "provider", ")", "throws", "FhirConfigurationException", "{", "if", "(", "null", "==", "provider", ")", "{", "throw", "new", "NullPointerException", "(", "\"FHIR Provider cannot be null\"", ")", ";", "}", "try", "{", "super", ".", "registerProvider", "(", "provider", ")", ";", "log", ".", "trace", "(", "\"registered provider. class [\"", "+", "provider", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\"]\"", ")", ";", "this", ".", "serverProviders", ".", "add", "(", "provider", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Error registering FHIR Provider\"", ",", "e", ")", ";", "throw", "new", "FhirConfigurationException", "(", "\"Error registering FHIR Provider\"", ",", "e", ")", ";", "}", "}" ]
Dynamically registers a single provider with the RestfulServer @param provider the provider to be registered @throws FhirConfigurationException
[ "Dynamically", "registers", "a", "single", "provider", "with", "the", "RestfulServer" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-osgi-core/src/main/java/ca/uhn/fhir/osgi/FhirServerImpl.java#L60-L73
aoindustries/aoweb-framework
src/main/java/com/aoindustries/website/framework/WebSiteRequest.java
WebSiteRequest.getURL
public String getURL(WebPage page, Object optParam) throws IOException, SQLException { """ Gets the context-relative URL to a web page. Parameters should already be URL encoded but not yet XML encoded. """ List<String> finishedParams=new SortedArrayList<>(); StringBuilder SB = new StringBuilder(); SB.append(page.getURLPath()); boolean alreadyAppended=appendParams(SB, optParam, finishedParams, false); alreadyAppended=appendParams(SB, page.getURLParams(this), finishedParams, alreadyAppended); /*alreadyAppended=*/appendSettings(finishedParams, alreadyAppended, SB); return SB.toString(); }
java
public String getURL(WebPage page, Object optParam) throws IOException, SQLException { List<String> finishedParams=new SortedArrayList<>(); StringBuilder SB = new StringBuilder(); SB.append(page.getURLPath()); boolean alreadyAppended=appendParams(SB, optParam, finishedParams, false); alreadyAppended=appendParams(SB, page.getURLParams(this), finishedParams, alreadyAppended); /*alreadyAppended=*/appendSettings(finishedParams, alreadyAppended, SB); return SB.toString(); }
[ "public", "String", "getURL", "(", "WebPage", "page", ",", "Object", "optParam", ")", "throws", "IOException", ",", "SQLException", "{", "List", "<", "String", ">", "finishedParams", "=", "new", "SortedArrayList", "<>", "(", ")", ";", "StringBuilder", "SB", "=", "new", "StringBuilder", "(", ")", ";", "SB", ".", "append", "(", "page", ".", "getURLPath", "(", ")", ")", ";", "boolean", "alreadyAppended", "=", "appendParams", "(", "SB", ",", "optParam", ",", "finishedParams", ",", "false", ")", ";", "alreadyAppended", "=", "appendParams", "(", "SB", ",", "page", ".", "getURLParams", "(", "this", ")", ",", "finishedParams", ",", "alreadyAppended", ")", ";", "/*alreadyAppended=*/", "appendSettings", "(", "finishedParams", ",", "alreadyAppended", ",", "SB", ")", ";", "return", "SB", ".", "toString", "(", ")", ";", "}" ]
Gets the context-relative URL to a web page. Parameters should already be URL encoded but not yet XML encoded.
[ "Gets", "the", "context", "-", "relative", "URL", "to", "a", "web", "page", ".", "Parameters", "should", "already", "be", "URL", "encoded", "but", "not", "yet", "XML", "encoded", "." ]
train
https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L432-L442
deeplearning4j/deeplearning4j
datavec/datavec-api/src/main/java/org/datavec/api/io/WritableUtils.java
WritableUtils.writeString
public static void writeString(DataOutput out, String s) throws IOException { """ /* Write a String as a Network Int n, followed by n Bytes Alternative to 16 bit read/writeUTF. Encoding standard is... ? """ if (s != null) { byte[] buffer = s.getBytes("UTF-8"); int len = buffer.length; out.writeInt(len); out.write(buffer, 0, len); } else { out.writeInt(-1); } }
java
public static void writeString(DataOutput out, String s) throws IOException { if (s != null) { byte[] buffer = s.getBytes("UTF-8"); int len = buffer.length; out.writeInt(len); out.write(buffer, 0, len); } else { out.writeInt(-1); } }
[ "public", "static", "void", "writeString", "(", "DataOutput", "out", ",", "String", "s", ")", "throws", "IOException", "{", "if", "(", "s", "!=", "null", ")", "{", "byte", "[", "]", "buffer", "=", "s", ".", "getBytes", "(", "\"UTF-8\"", ")", ";", "int", "len", "=", "buffer", ".", "length", ";", "out", ".", "writeInt", "(", "len", ")", ";", "out", ".", "write", "(", "buffer", ",", "0", ",", "len", ")", ";", "}", "else", "{", "out", ".", "writeInt", "(", "-", "1", ")", ";", "}", "}" ]
/* Write a String as a Network Int n, followed by n Bytes Alternative to 16 bit read/writeUTF. Encoding standard is... ?
[ "/", "*" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/io/WritableUtils.java#L97-L106
alkacon/opencms-core
src-setup/org/opencms/setup/db/update6to7/CmsUpdateDBCmsUsers.java
CmsUpdateDBCmsUsers.addUserDateCreated
protected void addUserDateCreated(CmsSetupDb dbCon) throws SQLException { """ Adds the new column USER_DATECREATED to the CMS_USERS table.<p> @param dbCon the db connection interface @throws SQLException if something goes wrong """ System.out.println(new Exception().getStackTrace()[0].toString()); // Add the column to the table if necessary if (!dbCon.hasTableOrColumn(CMS_USERS_TABLE, USER_DATECREATED)) { String addUserDateCreated = readQuery(QUERY_ADD_USER_DATECREATED_COLUMN); dbCon.updateSqlStatement(addUserDateCreated, null, null); String setUserDateCreated = readQuery(QUERY_SET_USER_DATECREATED); List<Object> param = new ArrayList<Object>(); // Set the creation date to the current time param.add(new Long(System.currentTimeMillis())); dbCon.updateSqlStatement(setUserDateCreated, null, param); } else { System.out.println("column " + USER_DATECREATED + " in table " + CMS_USERS_TABLE + " already exists"); } }
java
protected void addUserDateCreated(CmsSetupDb dbCon) throws SQLException { System.out.println(new Exception().getStackTrace()[0].toString()); // Add the column to the table if necessary if (!dbCon.hasTableOrColumn(CMS_USERS_TABLE, USER_DATECREATED)) { String addUserDateCreated = readQuery(QUERY_ADD_USER_DATECREATED_COLUMN); dbCon.updateSqlStatement(addUserDateCreated, null, null); String setUserDateCreated = readQuery(QUERY_SET_USER_DATECREATED); List<Object> param = new ArrayList<Object>(); // Set the creation date to the current time param.add(new Long(System.currentTimeMillis())); dbCon.updateSqlStatement(setUserDateCreated, null, param); } else { System.out.println("column " + USER_DATECREATED + " in table " + CMS_USERS_TABLE + " already exists"); } }
[ "protected", "void", "addUserDateCreated", "(", "CmsSetupDb", "dbCon", ")", "throws", "SQLException", "{", "System", ".", "out", ".", "println", "(", "new", "Exception", "(", ")", ".", "getStackTrace", "(", ")", "[", "0", "]", ".", "toString", "(", ")", ")", ";", "// Add the column to the table if necessary", "if", "(", "!", "dbCon", ".", "hasTableOrColumn", "(", "CMS_USERS_TABLE", ",", "USER_DATECREATED", ")", ")", "{", "String", "addUserDateCreated", "=", "readQuery", "(", "QUERY_ADD_USER_DATECREATED_COLUMN", ")", ";", "dbCon", ".", "updateSqlStatement", "(", "addUserDateCreated", ",", "null", ",", "null", ")", ";", "String", "setUserDateCreated", "=", "readQuery", "(", "QUERY_SET_USER_DATECREATED", ")", ";", "List", "<", "Object", ">", "param", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "// Set the creation date to the current time", "param", ".", "add", "(", "new", "Long", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ";", "dbCon", ".", "updateSqlStatement", "(", "setUserDateCreated", ",", "null", ",", "param", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"column \"", "+", "USER_DATECREATED", "+", "\" in table \"", "+", "CMS_USERS_TABLE", "+", "\" already exists\"", ")", ";", "}", "}" ]
Adds the new column USER_DATECREATED to the CMS_USERS table.<p> @param dbCon the db connection interface @throws SQLException if something goes wrong
[ "Adds", "the", "new", "column", "USER_DATECREATED", "to", "the", "CMS_USERS", "table", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/db/update6to7/CmsUpdateDBCmsUsers.java#L216-L233
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java
Http2FrameCodec.onStreamError
@Override protected final void onStreamError(ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception.StreamException streamException) { """ Exceptions for unknown streams, that is streams that have no {@link Http2FrameStream} object attached are simply logged and replied to by sending a RST_STREAM frame. """ int streamId = streamException.streamId(); Http2Stream connectionStream = connection().stream(streamId); if (connectionStream == null) { onHttp2UnknownStreamError(ctx, cause, streamException); // Write a RST_STREAM super.onStreamError(ctx, outbound, cause, streamException); return; } Http2FrameStream stream = connectionStream.getProperty(streamKey); if (stream == null) { LOG.warn("Stream exception thrown without stream object attached.", cause); // Write a RST_STREAM super.onStreamError(ctx, outbound, cause, streamException); return; } if (!outbound) { // We only forward non outbound errors as outbound errors will already be reflected by failing the promise. onHttp2FrameStreamException(ctx, new Http2FrameStreamException(stream, streamException.error(), cause)); } }
java
@Override protected final void onStreamError(ChannelHandlerContext ctx, boolean outbound, Throwable cause, Http2Exception.StreamException streamException) { int streamId = streamException.streamId(); Http2Stream connectionStream = connection().stream(streamId); if (connectionStream == null) { onHttp2UnknownStreamError(ctx, cause, streamException); // Write a RST_STREAM super.onStreamError(ctx, outbound, cause, streamException); return; } Http2FrameStream stream = connectionStream.getProperty(streamKey); if (stream == null) { LOG.warn("Stream exception thrown without stream object attached.", cause); // Write a RST_STREAM super.onStreamError(ctx, outbound, cause, streamException); return; } if (!outbound) { // We only forward non outbound errors as outbound errors will already be reflected by failing the promise. onHttp2FrameStreamException(ctx, new Http2FrameStreamException(stream, streamException.error(), cause)); } }
[ "@", "Override", "protected", "final", "void", "onStreamError", "(", "ChannelHandlerContext", "ctx", ",", "boolean", "outbound", ",", "Throwable", "cause", ",", "Http2Exception", ".", "StreamException", "streamException", ")", "{", "int", "streamId", "=", "streamException", ".", "streamId", "(", ")", ";", "Http2Stream", "connectionStream", "=", "connection", "(", ")", ".", "stream", "(", "streamId", ")", ";", "if", "(", "connectionStream", "==", "null", ")", "{", "onHttp2UnknownStreamError", "(", "ctx", ",", "cause", ",", "streamException", ")", ";", "// Write a RST_STREAM", "super", ".", "onStreamError", "(", "ctx", ",", "outbound", ",", "cause", ",", "streamException", ")", ";", "return", ";", "}", "Http2FrameStream", "stream", "=", "connectionStream", ".", "getProperty", "(", "streamKey", ")", ";", "if", "(", "stream", "==", "null", ")", "{", "LOG", ".", "warn", "(", "\"Stream exception thrown without stream object attached.\"", ",", "cause", ")", ";", "// Write a RST_STREAM", "super", ".", "onStreamError", "(", "ctx", ",", "outbound", ",", "cause", ",", "streamException", ")", ";", "return", ";", "}", "if", "(", "!", "outbound", ")", "{", "// We only forward non outbound errors as outbound errors will already be reflected by failing the promise.", "onHttp2FrameStreamException", "(", "ctx", ",", "new", "Http2FrameStreamException", "(", "stream", ",", "streamException", ".", "error", "(", ")", ",", "cause", ")", ")", ";", "}", "}" ]
Exceptions for unknown streams, that is streams that have no {@link Http2FrameStream} object attached are simply logged and replied to by sending a RST_STREAM frame.
[ "Exceptions", "for", "unknown", "streams", "that", "is", "streams", "that", "have", "no", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java#L477-L501
vst/commons-math-extensions
src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java
EMatrixUtils.getRowRange
public static RealMatrix getRowRange (RealMatrix matrix, int start, int end) { """ Returns the row range from the matrix as a new matrix. @param matrix The input matrix @param start The index of the row to start with (inclusive) @param end The index of the row to end with (inclusive) @return A new matrix with rows specified """ return matrix.getSubMatrix(start, end, 0, matrix.getColumnDimension() - 1); }
java
public static RealMatrix getRowRange (RealMatrix matrix, int start, int end) { return matrix.getSubMatrix(start, end, 0, matrix.getColumnDimension() - 1); }
[ "public", "static", "RealMatrix", "getRowRange", "(", "RealMatrix", "matrix", ",", "int", "start", ",", "int", "end", ")", "{", "return", "matrix", ".", "getSubMatrix", "(", "start", ",", "end", ",", "0", ",", "matrix", ".", "getColumnDimension", "(", ")", "-", "1", ")", ";", "}" ]
Returns the row range from the matrix as a new matrix. @param matrix The input matrix @param start The index of the row to start with (inclusive) @param end The index of the row to end with (inclusive) @return A new matrix with rows specified
[ "Returns", "the", "row", "range", "from", "the", "matrix", "as", "a", "new", "matrix", "." ]
train
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java#L54-L56
buschmais/jqa-javaee6-plugin
src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/XmlDescriptorHelper.java
XmlDescriptorHelper.createDisplayName
public static DisplayNameDescriptor createDisplayName(DisplayNameType displayNameType, Store store) { """ Create a display name descriptor. @param displayNameType The XML display name type. @param store The store. @return The display name descriptor. """ DisplayNameDescriptor displayNameDescriptor = store.create(DisplayNameDescriptor.class); displayNameDescriptor.setLang(displayNameType.getLang()); displayNameDescriptor.setValue(displayNameType.getValue()); return displayNameDescriptor; }
java
public static DisplayNameDescriptor createDisplayName(DisplayNameType displayNameType, Store store) { DisplayNameDescriptor displayNameDescriptor = store.create(DisplayNameDescriptor.class); displayNameDescriptor.setLang(displayNameType.getLang()); displayNameDescriptor.setValue(displayNameType.getValue()); return displayNameDescriptor; }
[ "public", "static", "DisplayNameDescriptor", "createDisplayName", "(", "DisplayNameType", "displayNameType", ",", "Store", "store", ")", "{", "DisplayNameDescriptor", "displayNameDescriptor", "=", "store", ".", "create", "(", "DisplayNameDescriptor", ".", "class", ")", ";", "displayNameDescriptor", ".", "setLang", "(", "displayNameType", ".", "getLang", "(", ")", ")", ";", "displayNameDescriptor", ".", "setValue", "(", "displayNameType", ".", "getValue", "(", ")", ")", ";", "return", "displayNameDescriptor", ";", "}" ]
Create a display name descriptor. @param displayNameType The XML display name type. @param store The store. @return The display name descriptor.
[ "Create", "a", "display", "name", "descriptor", "." ]
train
https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/XmlDescriptorHelper.java#L61-L66
JodaOrg/joda-money
src/main/java/org/joda/money/Money.java
Money.ofMinor
public static Money ofMinor(CurrencyUnit currency, long amountMinor) { """ Obtains an instance of {@code Money} from an amount in minor units. <p> This allows you to create an instance with a specific currency and amount expressed in terms of the minor unit. For example, if constructing US Dollars, the input to this method represents cents. Note that when a currency has zero decimal places, the major and minor units are the same. For example, {@code ofMinor(USD, 2595)} creates the instance {@code USD 25.95}. @param currency the currency, not null @param amountMinor the amount of money in the minor division of the currency @return the new instance, never null """ return new Money(BigMoney.ofMinor(currency, amountMinor)); }
java
public static Money ofMinor(CurrencyUnit currency, long amountMinor) { return new Money(BigMoney.ofMinor(currency, amountMinor)); }
[ "public", "static", "Money", "ofMinor", "(", "CurrencyUnit", "currency", ",", "long", "amountMinor", ")", "{", "return", "new", "Money", "(", "BigMoney", ".", "ofMinor", "(", "currency", ",", "amountMinor", ")", ")", ";", "}" ]
Obtains an instance of {@code Money} from an amount in minor units. <p> This allows you to create an instance with a specific currency and amount expressed in terms of the minor unit. For example, if constructing US Dollars, the input to this method represents cents. Note that when a currency has zero decimal places, the major and minor units are the same. For example, {@code ofMinor(USD, 2595)} creates the instance {@code USD 25.95}. @param currency the currency, not null @param amountMinor the amount of money in the minor division of the currency @return the new instance, never null
[ "Obtains", "an", "instance", "of", "{", "@code", "Money", "}", "from", "an", "amount", "in", "minor", "units", ".", "<p", ">", "This", "allows", "you", "to", "create", "an", "instance", "with", "a", "specific", "currency", "and", "amount", "expressed", "in", "terms", "of", "the", "minor", "unit", ".", "For", "example", "if", "constructing", "US", "Dollars", "the", "input", "to", "this", "method", "represents", "cents", ".", "Note", "that", "when", "a", "currency", "has", "zero", "decimal", "places", "the", "major", "and", "minor", "units", "are", "the", "same", ".", "For", "example", "{", "@code", "ofMinor", "(", "USD", "2595", ")", "}", "creates", "the", "instance", "{", "@code", "USD", "25", ".", "95", "}", "." ]
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/Money.java#L179-L181
apache/incubator-druid
processing/src/main/java/org/apache/druid/segment/data/VSizeLongSerde.java
VSizeLongSerde.getNumValuesPerBlock
public static int getNumValuesPerBlock(int bitsPerValue, int blockSize) { """ Block size should be power of 2, so {@link ColumnarLongs#get(int)} can be optimized using bit operators. """ int ret = 1; while (getSerializedSize(bitsPerValue, ret) <= blockSize) { ret *= 2; } return ret / 2; }
java
public static int getNumValuesPerBlock(int bitsPerValue, int blockSize) { int ret = 1; while (getSerializedSize(bitsPerValue, ret) <= blockSize) { ret *= 2; } return ret / 2; }
[ "public", "static", "int", "getNumValuesPerBlock", "(", "int", "bitsPerValue", ",", "int", "blockSize", ")", "{", "int", "ret", "=", "1", ";", "while", "(", "getSerializedSize", "(", "bitsPerValue", ",", "ret", ")", "<=", "blockSize", ")", "{", "ret", "*=", "2", ";", "}", "return", "ret", "/", "2", ";", "}" ]
Block size should be power of 2, so {@link ColumnarLongs#get(int)} can be optimized using bit operators.
[ "Block", "size", "should", "be", "power", "of", "2", "so", "{" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/segment/data/VSizeLongSerde.java#L69-L76
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/UserApi.java
UserApi.deleteCustomAttribute
public void deleteCustomAttribute(final Object userIdOrUsername, final String key) throws GitLabApiException { """ Delete a custom attribute for the given user @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance @param key of the customAttribute to remove @throws GitLabApiException on failure while deleting customAttributes """ if (Objects.isNull(key) || key.trim().isEmpty()) { throw new IllegalArgumentException("Key can't be null or empty"); } delete(Response.Status.OK, null, "users", getUserIdOrUsername(userIdOrUsername), "custom_attributes", key); }
java
public void deleteCustomAttribute(final Object userIdOrUsername, final String key) throws GitLabApiException { if (Objects.isNull(key) || key.trim().isEmpty()) { throw new IllegalArgumentException("Key can't be null or empty"); } delete(Response.Status.OK, null, "users", getUserIdOrUsername(userIdOrUsername), "custom_attributes", key); }
[ "public", "void", "deleteCustomAttribute", "(", "final", "Object", "userIdOrUsername", ",", "final", "String", "key", ")", "throws", "GitLabApiException", "{", "if", "(", "Objects", ".", "isNull", "(", "key", ")", "||", "key", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Key can't be null or empty\"", ")", ";", "}", "delete", "(", "Response", ".", "Status", ".", "OK", ",", "null", ",", "\"users\"", ",", "getUserIdOrUsername", "(", "userIdOrUsername", ")", ",", "\"custom_attributes\"", ",", "key", ")", ";", "}" ]
Delete a custom attribute for the given user @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance @param key of the customAttribute to remove @throws GitLabApiException on failure while deleting customAttributes
[ "Delete", "a", "custom", "attribute", "for", "the", "given", "user" ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/UserApi.java#L980-L987
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.evaluateMultiple
public void evaluateMultiple(DataSetIterator iterator, Map<String,List<IEvaluation>> variableEvals) { """ Evaluation for multiple output networks - one ore more See {@link #evaluate(MultiDataSetIterator, Map, Map)} """ Map<String,Integer> map = new HashMap<>(); for(String s : variableEvals.keySet()){ map.put(s, 0); //Only 1 possible output here with DataSetIterator } evaluate(new MultiDataSetIteratorAdapter(iterator), variableEvals, map); }
java
public void evaluateMultiple(DataSetIterator iterator, Map<String,List<IEvaluation>> variableEvals){ Map<String,Integer> map = new HashMap<>(); for(String s : variableEvals.keySet()){ map.put(s, 0); //Only 1 possible output here with DataSetIterator } evaluate(new MultiDataSetIteratorAdapter(iterator), variableEvals, map); }
[ "public", "void", "evaluateMultiple", "(", "DataSetIterator", "iterator", ",", "Map", "<", "String", ",", "List", "<", "IEvaluation", ">", ">", "variableEvals", ")", "{", "Map", "<", "String", ",", "Integer", ">", "map", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "s", ":", "variableEvals", ".", "keySet", "(", ")", ")", "{", "map", ".", "put", "(", "s", ",", "0", ")", ";", "//Only 1 possible output here with DataSetIterator", "}", "evaluate", "(", "new", "MultiDataSetIteratorAdapter", "(", "iterator", ")", ",", "variableEvals", ",", "map", ")", ";", "}" ]
Evaluation for multiple output networks - one ore more See {@link #evaluate(MultiDataSetIterator, Map, Map)}
[ "Evaluation", "for", "multiple", "output", "networks", "-", "one", "ore", "more", "See", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L1778-L1784
looly/hutool
hutool-http/src/main/java/cn/hutool/http/webservice/SoapClient.java
SoapClient.setParams
public SoapClient setParams(Map<String, Object> params, boolean useMethodPrefix) { """ 批量设置参数 @param params 参数列表 @param useMethodPrefix 是否使用方法的命名空间前缀 @return this @since 4.5.6 """ for (Entry<String, Object> entry : MapUtil.wrap(params)) { setParam(entry.getKey(), entry.getValue(), useMethodPrefix); } return this; }
java
public SoapClient setParams(Map<String, Object> params, boolean useMethodPrefix) { for (Entry<String, Object> entry : MapUtil.wrap(params)) { setParam(entry.getKey(), entry.getValue(), useMethodPrefix); } return this; }
[ "public", "SoapClient", "setParams", "(", "Map", "<", "String", ",", "Object", ">", "params", ",", "boolean", "useMethodPrefix", ")", "{", "for", "(", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "MapUtil", ".", "wrap", "(", "params", ")", ")", "{", "setParam", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ",", "useMethodPrefix", ")", ";", "}", "return", "this", ";", "}" ]
批量设置参数 @param params 参数列表 @param useMethodPrefix 是否使用方法的命名空间前缀 @return this @since 4.5.6
[ "批量设置参数" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/webservice/SoapClient.java#L338-L343
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/utils/disruptor/RingBuffer.java
RingBuffer.tryPublishEvents
public <A, B> boolean tryPublishEvents(EventTranslatorTwoArg<E, A, B> translator, A[] arg0, B[] arg1) { """ Allows two user supplied arguments per event. @param translator The user specified translation for the event @param arg0 An array of user supplied arguments, one element per event. @param arg1 An array of user supplied arguments, one element per event. @return true if the value was published, false if there was insufficient capacity. @see #tryPublishEvents(com.lmax.disruptor.EventTranslator[]) """ return tryPublishEvents(translator, 0, arg0.length, arg0, arg1); }
java
public <A, B> boolean tryPublishEvents(EventTranslatorTwoArg<E, A, B> translator, A[] arg0, B[] arg1) { return tryPublishEvents(translator, 0, arg0.length, arg0, arg1); }
[ "public", "<", "A", ",", "B", ">", "boolean", "tryPublishEvents", "(", "EventTranslatorTwoArg", "<", "E", ",", "A", ",", "B", ">", "translator", ",", "A", "[", "]", "arg0", ",", "B", "[", "]", "arg1", ")", "{", "return", "tryPublishEvents", "(", "translator", ",", "0", ",", "arg0", ".", "length", ",", "arg0", ",", "arg1", ")", ";", "}" ]
Allows two user supplied arguments per event. @param translator The user specified translation for the event @param arg0 An array of user supplied arguments, one element per event. @param arg1 An array of user supplied arguments, one element per event. @return true if the value was published, false if there was insufficient capacity. @see #tryPublishEvents(com.lmax.disruptor.EventTranslator[])
[ "Allows", "two", "user", "supplied", "arguments", "per", "event", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/utils/disruptor/RingBuffer.java#L660-L662
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionCategoryPersistenceImpl.java
CPOptionCategoryPersistenceImpl.findByCompanyId
@Override public List<CPOptionCategory> findByCompanyId(long companyId, int start, int end) { """ Returns a range of all the cp option categories where companyId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPOptionCategoryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param companyId the company ID @param start the lower bound of the range of cp option categories @param end the upper bound of the range of cp option categories (not inclusive) @return the range of matching cp option categories """ return findByCompanyId(companyId, start, end, null); }
java
@Override public List<CPOptionCategory> findByCompanyId(long companyId, int start, int end) { return findByCompanyId(companyId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CPOptionCategory", ">", "findByCompanyId", "(", "long", "companyId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCompanyId", "(", "companyId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp option categories where companyId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPOptionCategoryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param companyId the company ID @param start the lower bound of the range of cp option categories @param end the upper bound of the range of cp option categories (not inclusive) @return the range of matching cp option categories
[ "Returns", "a", "range", "of", "all", "the", "cp", "option", "categories", "where", "companyId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionCategoryPersistenceImpl.java#L2044-L2048
Azure/azure-sdk-for-java
recoveryservices.backup/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_12_01/implementation/JobCancellationsInner.java
JobCancellationsInner.trigger
public void trigger(String vaultName, String resourceGroupName, String jobName) { """ Cancels a job. This is an asynchronous operation. To know the status of the cancellation, call GetCancelOperationResult API. @param vaultName The name of the recovery services vault. @param resourceGroupName The name of the resource group where the recovery services vault is present. @param jobName Name of the job to cancel. @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 """ triggerWithServiceResponseAsync(vaultName, resourceGroupName, jobName).toBlocking().single().body(); }
java
public void trigger(String vaultName, String resourceGroupName, String jobName) { triggerWithServiceResponseAsync(vaultName, resourceGroupName, jobName).toBlocking().single().body(); }
[ "public", "void", "trigger", "(", "String", "vaultName", ",", "String", "resourceGroupName", ",", "String", "jobName", ")", "{", "triggerWithServiceResponseAsync", "(", "vaultName", ",", "resourceGroupName", ",", "jobName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Cancels a job. This is an asynchronous operation. To know the status of the cancellation, call GetCancelOperationResult API. @param vaultName The name of the recovery services vault. @param resourceGroupName The name of the resource group where the recovery services vault is present. @param jobName Name of the job to cancel. @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
[ "Cancels", "a", "job", ".", "This", "is", "an", "asynchronous", "operation", ".", "To", "know", "the", "status", "of", "the", "cancellation", "call", "GetCancelOperationResult", "API", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_12_01/implementation/JobCancellationsInner.java#L70-L72
looly/hutool
hutool-core/src/main/java/cn/hutool/core/text/csv/CsvReader.java
CsvReader.read
public CsvData read(Path path, Charset charset) throws IORuntimeException { """ 读取CSV文件 @param path CSV文件 @param charset 文件编码,默认系统编码 @return {@link CsvData},包含数据列表和行信息 @throws IORuntimeException IO异常 """ Assert.notNull(path, "path must not be null"); try (Reader reader = FileUtil.getReader(path, charset)) { return read(reader); } catch (IOException e) { throw new IORuntimeException(e); } }
java
public CsvData read(Path path, Charset charset) throws IORuntimeException { Assert.notNull(path, "path must not be null"); try (Reader reader = FileUtil.getReader(path, charset)) { return read(reader); } catch (IOException e) { throw new IORuntimeException(e); } }
[ "public", "CsvData", "read", "(", "Path", "path", ",", "Charset", "charset", ")", "throws", "IORuntimeException", "{", "Assert", ".", "notNull", "(", "path", ",", "\"path must not be null\"", ")", ";", "try", "(", "Reader", "reader", "=", "FileUtil", ".", "getReader", "(", "path", ",", "charset", ")", ")", "{", "return", "read", "(", "reader", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IORuntimeException", "(", "e", ")", ";", "}", "}" ]
读取CSV文件 @param path CSV文件 @param charset 文件编码,默认系统编码 @return {@link CsvData},包含数据列表和行信息 @throws IORuntimeException IO异常
[ "读取CSV文件" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/text/csv/CsvReader.java#L131-L138
m-m-m/util
value/src/main/java/net/sf/mmm/util/value/impl/ComposedValueConverterImpl.java
ComposedValueConverterImpl.isApplicable
protected boolean isApplicable(ValueConverter<?, ?> converter, GenericType<?> targetType) { """ This method determines if the given {@code converter} is applicable for the given {@code targetType}. @see ValueConverter#getTargetType() @param converter is the {@link ValueConverter} to check. @param targetType is the {@link GenericType} to match with {@link ValueConverter#getTargetType()}. @return {@code true} if the given {@code converter} is applicable, {@code false} otherwise. """ Class<?> expectedTargetClass = targetType.getRetrievalClass(); if (expectedTargetClass.isArray()) { expectedTargetClass = expectedTargetClass.getComponentType(); } return isApplicable(converter.getTargetType(), expectedTargetClass); }
java
protected boolean isApplicable(ValueConverter<?, ?> converter, GenericType<?> targetType) { Class<?> expectedTargetClass = targetType.getRetrievalClass(); if (expectedTargetClass.isArray()) { expectedTargetClass = expectedTargetClass.getComponentType(); } return isApplicable(converter.getTargetType(), expectedTargetClass); }
[ "protected", "boolean", "isApplicable", "(", "ValueConverter", "<", "?", ",", "?", ">", "converter", ",", "GenericType", "<", "?", ">", "targetType", ")", "{", "Class", "<", "?", ">", "expectedTargetClass", "=", "targetType", ".", "getRetrievalClass", "(", ")", ";", "if", "(", "expectedTargetClass", ".", "isArray", "(", ")", ")", "{", "expectedTargetClass", "=", "expectedTargetClass", ".", "getComponentType", "(", ")", ";", "}", "return", "isApplicable", "(", "converter", ".", "getTargetType", "(", ")", ",", "expectedTargetClass", ")", ";", "}" ]
This method determines if the given {@code converter} is applicable for the given {@code targetType}. @see ValueConverter#getTargetType() @param converter is the {@link ValueConverter} to check. @param targetType is the {@link GenericType} to match with {@link ValueConverter#getTargetType()}. @return {@code true} if the given {@code converter} is applicable, {@code false} otherwise.
[ "This", "method", "determines", "if", "the", "given", "{", "@code", "converter", "}", "is", "applicable", "for", "the", "given", "{", "@code", "targetType", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/impl/ComposedValueConverterImpl.java#L220-L227
Harium/keel
src/main/java/com/harium/keel/effect/normal/SobelNormalMap.java
SobelNormalMap.apply
@Override public ImageSource apply(ImageSource input) { """ Sobel method to generate bump map from a height map @param input - A height map @return bump map """ int w = input.getWidth(); int h = input.getHeight(); MatrixSource output = new MatrixSource(input); Vector3 n = new Vector3(0, 0, 1); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (x < border || x == w - border || y < border || y == h - border) { output.setRGB(x, y, VectorHelper.Z_NORMAL); continue; } float s0 = input.getR(x - 1, y + 1); float s1 = input.getR(x, y + 1); float s2 = input.getR(x + 1, y + 1); float s3 = input.getR(x - 1, y); float s5 = input.getR(x + 1, y); float s6 = input.getR(x - 1, y - 1); float s7 = input.getR(x, y - 1); float s8 = input.getR(x + 1, y - 1); float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6); float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2); n.set(nx, ny, scale); n.nor(); int rgb = VectorHelper.vectorToColor(n); output.setRGB(x, y, rgb); } } return new MatrixSource(output); }
java
@Override public ImageSource apply(ImageSource input) { int w = input.getWidth(); int h = input.getHeight(); MatrixSource output = new MatrixSource(input); Vector3 n = new Vector3(0, 0, 1); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (x < border || x == w - border || y < border || y == h - border) { output.setRGB(x, y, VectorHelper.Z_NORMAL); continue; } float s0 = input.getR(x - 1, y + 1); float s1 = input.getR(x, y + 1); float s2 = input.getR(x + 1, y + 1); float s3 = input.getR(x - 1, y); float s5 = input.getR(x + 1, y); float s6 = input.getR(x - 1, y - 1); float s7 = input.getR(x, y - 1); float s8 = input.getR(x + 1, y - 1); float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6); float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2); n.set(nx, ny, scale); n.nor(); int rgb = VectorHelper.vectorToColor(n); output.setRGB(x, y, rgb); } } return new MatrixSource(output); }
[ "@", "Override", "public", "ImageSource", "apply", "(", "ImageSource", "input", ")", "{", "int", "w", "=", "input", ".", "getWidth", "(", ")", ";", "int", "h", "=", "input", ".", "getHeight", "(", ")", ";", "MatrixSource", "output", "=", "new", "MatrixSource", "(", "input", ")", ";", "Vector3", "n", "=", "new", "Vector3", "(", "0", ",", "0", ",", "1", ")", ";", "for", "(", "int", "y", "=", "0", ";", "y", "<", "h", ";", "y", "++", ")", "{", "for", "(", "int", "x", "=", "0", ";", "x", "<", "w", ";", "x", "++", ")", "{", "if", "(", "x", "<", "border", "||", "x", "==", "w", "-", "border", "||", "y", "<", "border", "||", "y", "==", "h", "-", "border", ")", "{", "output", ".", "setRGB", "(", "x", ",", "y", ",", "VectorHelper", ".", "Z_NORMAL", ")", ";", "continue", ";", "}", "float", "s0", "=", "input", ".", "getR", "(", "x", "-", "1", ",", "y", "+", "1", ")", ";", "float", "s1", "=", "input", ".", "getR", "(", "x", ",", "y", "+", "1", ")", ";", "float", "s2", "=", "input", ".", "getR", "(", "x", "+", "1", ",", "y", "+", "1", ")", ";", "float", "s3", "=", "input", ".", "getR", "(", "x", "-", "1", ",", "y", ")", ";", "float", "s5", "=", "input", ".", "getR", "(", "x", "+", "1", ",", "y", ")", ";", "float", "s6", "=", "input", ".", "getR", "(", "x", "-", "1", ",", "y", "-", "1", ")", ";", "float", "s7", "=", "input", ".", "getR", "(", "x", ",", "y", "-", "1", ")", ";", "float", "s8", "=", "input", ".", "getR", "(", "x", "+", "1", ",", "y", "-", "1", ")", ";", "float", "nx", "=", "-", "(", "s2", "-", "s0", "+", "2", "*", "(", "s5", "-", "s3", ")", "+", "s8", "-", "s6", ")", ";", "float", "ny", "=", "-", "(", "s6", "-", "s0", "+", "2", "*", "(", "s7", "-", "s1", ")", "+", "s8", "-", "s2", ")", ";", "n", ".", "set", "(", "nx", ",", "ny", ",", "scale", ")", ";", "n", ".", "nor", "(", ")", ";", "int", "rgb", "=", "VectorHelper", ".", "vectorToColor", "(", "n", ")", ";", "output", ".", "setRGB", "(", "x", ",", "y", ",", "rgb", ")", ";", "}", "}", "return", "new", "MatrixSource", "(", "output", ")", ";", "}" ]
Sobel method to generate bump map from a height map @param input - A height map @return bump map
[ "Sobel", "method", "to", "generate", "bump", "map", "from", "a", "height", "map" ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/effect/normal/SobelNormalMap.java#L19-L57
hdbeukel/james-core
src/main/java/org/jamesframework/core/problems/objectives/evaluations/PenalizedEvaluation.java
PenalizedEvaluation.addPenalizingValidation
public void addPenalizingValidation(Object key, PenalizingValidation penalizingValidation) { """ Add a penalty expressed by a penalizing validation object. A key is required that can be used to retrieve the validation object later. @param key key used to retrieve the validation object later @param penalizingValidation penalizing validation that indicates the assigned penalty """ initMapOnce(); penalties.put(key, penalizingValidation); // update penalized value if(!penalizingValidation.passed()){ assignedPenalties = true; double p = penalizingValidation.getPenalty(); penalizedValue += minimizing ? p : -p; } }
java
public void addPenalizingValidation(Object key, PenalizingValidation penalizingValidation){ initMapOnce(); penalties.put(key, penalizingValidation); // update penalized value if(!penalizingValidation.passed()){ assignedPenalties = true; double p = penalizingValidation.getPenalty(); penalizedValue += minimizing ? p : -p; } }
[ "public", "void", "addPenalizingValidation", "(", "Object", "key", ",", "PenalizingValidation", "penalizingValidation", ")", "{", "initMapOnce", "(", ")", ";", "penalties", ".", "put", "(", "key", ",", "penalizingValidation", ")", ";", "// update penalized value", "if", "(", "!", "penalizingValidation", ".", "passed", "(", ")", ")", "{", "assignedPenalties", "=", "true", ";", "double", "p", "=", "penalizingValidation", ".", "getPenalty", "(", ")", ";", "penalizedValue", "+=", "minimizing", "?", "p", ":", "-", "p", ";", "}", "}" ]
Add a penalty expressed by a penalizing validation object. A key is required that can be used to retrieve the validation object later. @param key key used to retrieve the validation object later @param penalizingValidation penalizing validation that indicates the assigned penalty
[ "Add", "a", "penalty", "expressed", "by", "a", "penalizing", "validation", "object", ".", "A", "key", "is", "required", "that", "can", "be", "used", "to", "retrieve", "the", "validation", "object", "later", "." ]
train
https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/problems/objectives/evaluations/PenalizedEvaluation.java#L78-L87
cdk/cdk
display/renderawt/src/main/java/org/openscience/cdk/renderer/visitor/AbstractAWTDrawVisitor.java
AbstractAWTDrawVisitor.getTextBasePoint
protected Point getTextBasePoint(String text, double xCoord, double yCoord, Graphics2D graphics) { """ Calculates the base point where text should be rendered, as text in Java is typically placed using the left-lower corner point in screen coordinates. However, because the Java coordinate system is inverted in the y-axis with respect to scientific coordinate systems (Java has 0,0 in the top left corner, while in science we have 0,0 in the lower left corner), some special action is needed, involving the size of the text. @param text the text string @param xCoord the world x-coordinate of where the text should be placed @param yCoord the world y-coordinate of where the text should be placed @param graphics the graphics to which the text is provided as output @return the screen coordinates """ FontMetrics fontMetrics = graphics.getFontMetrics(); Rectangle2D stringBounds = fontMetrics.getStringBounds(text, graphics); int[] point = this.transformPoint(xCoord, yCoord); int baseX = (int) (point[0] - (stringBounds.getWidth() / 2)); // correct the baseline by the ascent int baseY = (int) (point[1] + (fontMetrics.getAscent() - stringBounds.getHeight() / 2)); return new Point(baseX, baseY); }
java
protected Point getTextBasePoint(String text, double xCoord, double yCoord, Graphics2D graphics) { FontMetrics fontMetrics = graphics.getFontMetrics(); Rectangle2D stringBounds = fontMetrics.getStringBounds(text, graphics); int[] point = this.transformPoint(xCoord, yCoord); int baseX = (int) (point[0] - (stringBounds.getWidth() / 2)); // correct the baseline by the ascent int baseY = (int) (point[1] + (fontMetrics.getAscent() - stringBounds.getHeight() / 2)); return new Point(baseX, baseY); }
[ "protected", "Point", "getTextBasePoint", "(", "String", "text", ",", "double", "xCoord", ",", "double", "yCoord", ",", "Graphics2D", "graphics", ")", "{", "FontMetrics", "fontMetrics", "=", "graphics", ".", "getFontMetrics", "(", ")", ";", "Rectangle2D", "stringBounds", "=", "fontMetrics", ".", "getStringBounds", "(", "text", ",", "graphics", ")", ";", "int", "[", "]", "point", "=", "this", ".", "transformPoint", "(", "xCoord", ",", "yCoord", ")", ";", "int", "baseX", "=", "(", "int", ")", "(", "point", "[", "0", "]", "-", "(", "stringBounds", ".", "getWidth", "(", ")", "/", "2", ")", ")", ";", "// correct the baseline by the ascent", "int", "baseY", "=", "(", "int", ")", "(", "point", "[", "1", "]", "+", "(", "fontMetrics", ".", "getAscent", "(", ")", "-", "stringBounds", ".", "getHeight", "(", ")", "/", "2", ")", ")", ";", "return", "new", "Point", "(", "baseX", ",", "baseY", ")", ";", "}" ]
Calculates the base point where text should be rendered, as text in Java is typically placed using the left-lower corner point in screen coordinates. However, because the Java coordinate system is inverted in the y-axis with respect to scientific coordinate systems (Java has 0,0 in the top left corner, while in science we have 0,0 in the lower left corner), some special action is needed, involving the size of the text. @param text the text string @param xCoord the world x-coordinate of where the text should be placed @param yCoord the world y-coordinate of where the text should be placed @param graphics the graphics to which the text is provided as output @return the screen coordinates
[ "Calculates", "the", "base", "point", "where", "text", "should", "be", "rendered", "as", "text", "in", "Java", "is", "typically", "placed", "using", "the", "left", "-", "lower", "corner", "point", "in", "screen", "coordinates", ".", "However", "because", "the", "Java", "coordinate", "system", "is", "inverted", "in", "the", "y", "-", "axis", "with", "respect", "to", "scientific", "coordinate", "systems", "(", "Java", "has", "0", "0", "in", "the", "top", "left", "corner", "while", "in", "science", "we", "have", "0", "0", "in", "the", "lower", "left", "corner", ")", "some", "special", "action", "is", "needed", "involving", "the", "size", "of", "the", "text", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderawt/src/main/java/org/openscience/cdk/renderer/visitor/AbstractAWTDrawVisitor.java#L100-L109
belaban/JGroups
src/org/jgroups/Channel.java
Channel.startFlush
public void startFlush(List<Address> flushParticipants, boolean automatic_resume) throws Exception { """ Performs the flush of the cluster but only for the specified flush participants. <p/> All pending messages are flushed out but only for the flush participants. The remaining members in the cluster are not included in the flush. The list of flush participants should be a proper subset of the current view. <p/> If this flush is not automatically resumed it is an obligation of the application to invoke the matching {@link #stopFlush(List)} method with the same list of members used in {@link #startFlush(List, boolean)}. @param automatic_resume if true call {@link #stopFlush()} after the flush @see #startFlush(boolean) @see Util#startFlush(Channel, List, int, long, long) """ ch.startFlush(flushParticipants, automatic_resume); }
java
public void startFlush(List<Address> flushParticipants, boolean automatic_resume) throws Exception { ch.startFlush(flushParticipants, automatic_resume); }
[ "public", "void", "startFlush", "(", "List", "<", "Address", ">", "flushParticipants", ",", "boolean", "automatic_resume", ")", "throws", "Exception", "{", "ch", ".", "startFlush", "(", "flushParticipants", ",", "automatic_resume", ")", ";", "}" ]
Performs the flush of the cluster but only for the specified flush participants. <p/> All pending messages are flushed out but only for the flush participants. The remaining members in the cluster are not included in the flush. The list of flush participants should be a proper subset of the current view. <p/> If this flush is not automatically resumed it is an obligation of the application to invoke the matching {@link #stopFlush(List)} method with the same list of members used in {@link #startFlush(List, boolean)}. @param automatic_resume if true call {@link #stopFlush()} after the flush @see #startFlush(boolean) @see Util#startFlush(Channel, List, int, long, long)
[ "Performs", "the", "flush", "of", "the", "cluster", "but", "only", "for", "the", "specified", "flush", "participants", ".", "<p", "/", ">", "All", "pending", "messages", "are", "flushed", "out", "but", "only", "for", "the", "flush", "participants", ".", "The", "remaining", "members", "in", "the", "cluster", "are", "not", "included", "in", "the", "flush", ".", "The", "list", "of", "flush", "participants", "should", "be", "a", "proper", "subset", "of", "the", "current", "view", ".", "<p", "/", ">", "If", "this", "flush", "is", "not", "automatically", "resumed", "it", "is", "an", "obligation", "of", "the", "application", "to", "invoke", "the", "matching", "{", "@link", "#stopFlush", "(", "List", ")", "}", "method", "with", "the", "same", "list", "of", "members", "used", "in", "{", "@link", "#startFlush", "(", "List", "boolean", ")", "}", "." ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/Channel.java#L445-L447
FedericoPecora/meta-csp-framework
src/main/java/org/metacsp/time/SimpleDistanceConstraint.java
SimpleDistanceConstraint.removeInterval
public boolean removeInterval(Bounds i) { """ Remove an [lb,ub] interval between the two {@link TimePoint}s of this constraint. @param i The interval to remove. @return {@code true} if the interval was removed, {@code false} if this was an attempt to remove the active constraint. """ if(bs.remove(i)) { Bounds intersection = new Bounds(0, APSPSolver.INF); for(Bounds toIntersect : bs) { //intersection = intervalIntersect(intersection, toIntersect);//intervalIntersect(intersection, inter); intersection = intersection.intersect(toIntersect); } minimum = intersection.min; maximum = intersection.max; return true; } return false; }
java
public boolean removeInterval(Bounds i) { if(bs.remove(i)) { Bounds intersection = new Bounds(0, APSPSolver.INF); for(Bounds toIntersect : bs) { //intersection = intervalIntersect(intersection, toIntersect);//intervalIntersect(intersection, inter); intersection = intersection.intersect(toIntersect); } minimum = intersection.min; maximum = intersection.max; return true; } return false; }
[ "public", "boolean", "removeInterval", "(", "Bounds", "i", ")", "{", "if", "(", "bs", ".", "remove", "(", "i", ")", ")", "{", "Bounds", "intersection", "=", "new", "Bounds", "(", "0", ",", "APSPSolver", ".", "INF", ")", ";", "for", "(", "Bounds", "toIntersect", ":", "bs", ")", "{", "//intersection = intervalIntersect(intersection, toIntersect);//intervalIntersect(intersection, inter);\r", "intersection", "=", "intersection", ".", "intersect", "(", "toIntersect", ")", ";", "}", "minimum", "=", "intersection", ".", "min", ";", "maximum", "=", "intersection", ".", "max", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Remove an [lb,ub] interval between the two {@link TimePoint}s of this constraint. @param i The interval to remove. @return {@code true} if the interval was removed, {@code false} if this was an attempt to remove the active constraint.
[ "Remove", "an", "[", "lb", "ub", "]", "interval", "between", "the", "two", "{" ]
train
https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/time/SimpleDistanceConstraint.java#L156-L171
landawn/AbacusUtil
src/com/landawn/abacus/dataSource/PoolablePreparedStatement.java
PoolablePreparedStatement.setURL
@Override public void setURL(int parameterIndex, URL x) throws SQLException { """ Method setURL. @param parameterIndex @param x @throws SQLException @see java.sql.PreparedStatement#setURL(int, URL) """ internalStmt.setURL(parameterIndex, x); }
java
@Override public void setURL(int parameterIndex, URL x) throws SQLException { internalStmt.setURL(parameterIndex, x); }
[ "@", "Override", "public", "void", "setURL", "(", "int", "parameterIndex", ",", "URL", "x", ")", "throws", "SQLException", "{", "internalStmt", ".", "setURL", "(", "parameterIndex", ",", "x", ")", ";", "}" ]
Method setURL. @param parameterIndex @param x @throws SQLException @see java.sql.PreparedStatement#setURL(int, URL)
[ "Method", "setURL", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/dataSource/PoolablePreparedStatement.java#L1058-L1061
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/FieldAnnotation.java
FieldAnnotation.fromBCELField
public static FieldAnnotation fromBCELField(JavaClass jClass, Field field) { """ Factory method. Construct from class name and BCEL Field object. @param jClass the class which defines the field @param field the BCEL Field object @return the FieldAnnotation """ return new FieldAnnotation(jClass.getClassName(), field.getName(), field.getSignature(), field.isStatic()); }
java
public static FieldAnnotation fromBCELField(JavaClass jClass, Field field) { return new FieldAnnotation(jClass.getClassName(), field.getName(), field.getSignature(), field.isStatic()); }
[ "public", "static", "FieldAnnotation", "fromBCELField", "(", "JavaClass", "jClass", ",", "Field", "field", ")", "{", "return", "new", "FieldAnnotation", "(", "jClass", ".", "getClassName", "(", ")", ",", "field", ".", "getName", "(", ")", ",", "field", ".", "getSignature", "(", ")", ",", "field", ".", "isStatic", "(", ")", ")", ";", "}" ]
Factory method. Construct from class name and BCEL Field object. @param jClass the class which defines the field @param field the BCEL Field object @return the FieldAnnotation
[ "Factory", "method", ".", "Construct", "from", "class", "name", "and", "BCEL", "Field", "object", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/FieldAnnotation.java#L172-L174
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ChineseCalendar.java
ChineseCalendar.isLeapMonthBetween
private boolean isLeapMonthBetween(int newMoon1, int newMoon2) { """ Return true if there is a leap month on or after month newMoon1 and at or before month newMoon2. @param newMoon1 days after January 1, 1970 0:00 astronomical base zone of a new moon @param newMoon2 days after January 1, 1970 0:00 astronomical base zone of a new moon """ // This is only needed to debug the timeOfAngle divergence bug. // Remove this later. Liu 11/9/00 // DEBUG if (synodicMonthsBetween(newMoon1, newMoon2) >= 50) { throw new IllegalArgumentException("isLeapMonthBetween(" + newMoon1 + ", " + newMoon2 + "): Invalid parameters"); } return (newMoon2 >= newMoon1) && (isLeapMonthBetween(newMoon1, newMoonNear(newMoon2 - SYNODIC_GAP, false)) || hasNoMajorSolarTerm(newMoon2)); }
java
private boolean isLeapMonthBetween(int newMoon1, int newMoon2) { // This is only needed to debug the timeOfAngle divergence bug. // Remove this later. Liu 11/9/00 // DEBUG if (synodicMonthsBetween(newMoon1, newMoon2) >= 50) { throw new IllegalArgumentException("isLeapMonthBetween(" + newMoon1 + ", " + newMoon2 + "): Invalid parameters"); } return (newMoon2 >= newMoon1) && (isLeapMonthBetween(newMoon1, newMoonNear(newMoon2 - SYNODIC_GAP, false)) || hasNoMajorSolarTerm(newMoon2)); }
[ "private", "boolean", "isLeapMonthBetween", "(", "int", "newMoon1", ",", "int", "newMoon2", ")", "{", "// This is only needed to debug the timeOfAngle divergence bug.", "// Remove this later. Liu 11/9/00", "// DEBUG", "if", "(", "synodicMonthsBetween", "(", "newMoon1", ",", "newMoon2", ")", ">=", "50", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"isLeapMonthBetween(\"", "+", "newMoon1", "+", "\", \"", "+", "newMoon2", "+", "\"): Invalid parameters\"", ")", ";", "}", "return", "(", "newMoon2", ">=", "newMoon1", ")", "&&", "(", "isLeapMonthBetween", "(", "newMoon1", ",", "newMoonNear", "(", "newMoon2", "-", "SYNODIC_GAP", ",", "false", ")", ")", "||", "hasNoMajorSolarTerm", "(", "newMoon2", ")", ")", ";", "}" ]
Return true if there is a leap month on or after month newMoon1 and at or before month newMoon2. @param newMoon1 days after January 1, 1970 0:00 astronomical base zone of a new moon @param newMoon2 days after January 1, 1970 0:00 astronomical base zone of a new moon
[ "Return", "true", "if", "there", "is", "a", "leap", "month", "on", "or", "after", "month", "newMoon1", "and", "at", "or", "before", "month", "newMoon2", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ChineseCalendar.java#L778-L792
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/IntStream.java
IntStream.findLast
@NotNull public OptionalInt findLast() { """ Returns the last element wrapped by {@code OptionalInt} class. If stream is empty, returns {@code OptionalInt.empty()}. <p>This is a short-circuiting terminal operation. @return an {@code OptionalInt} with the last element or {@code OptionalInt.empty()} if the stream is empty @since 1.1.8 """ return reduce(new IntBinaryOperator() { @Override public int applyAsInt(int left, int right) { return right; } }); }
java
@NotNull public OptionalInt findLast() { return reduce(new IntBinaryOperator() { @Override public int applyAsInt(int left, int right) { return right; } }); }
[ "@", "NotNull", "public", "OptionalInt", "findLast", "(", ")", "{", "return", "reduce", "(", "new", "IntBinaryOperator", "(", ")", "{", "@", "Override", "public", "int", "applyAsInt", "(", "int", "left", ",", "int", "right", ")", "{", "return", "right", ";", "}", "}", ")", ";", "}" ]
Returns the last element wrapped by {@code OptionalInt} class. If stream is empty, returns {@code OptionalInt.empty()}. <p>This is a short-circuiting terminal operation. @return an {@code OptionalInt} with the last element or {@code OptionalInt.empty()} if the stream is empty @since 1.1.8
[ "Returns", "the", "last", "element", "wrapped", "by", "{", "@code", "OptionalInt", "}", "class", ".", "If", "stream", "is", "empty", "returns", "{", "@code", "OptionalInt", ".", "empty", "()", "}", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/IntStream.java#L1209-L1217
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/read/ReadFileExtensions.java
ReadFileExtensions.inputStream2String
public static String inputStream2String(final InputStream inputStream, final Charset encoding) throws IOException { """ The Method inputStream2String() reads the data from the InputStream into a String. @param inputStream The InputStream from where we read. @param encoding the encoding @return The String that we read from the InputStream. @throws IOException Signals that an I/O exception has occurred. """ return ReadFileExtensions.reader2String(new InputStreamReader(inputStream, encoding)); }
java
public static String inputStream2String(final InputStream inputStream, final Charset encoding) throws IOException { return ReadFileExtensions.reader2String(new InputStreamReader(inputStream, encoding)); }
[ "public", "static", "String", "inputStream2String", "(", "final", "InputStream", "inputStream", ",", "final", "Charset", "encoding", ")", "throws", "IOException", "{", "return", "ReadFileExtensions", ".", "reader2String", "(", "new", "InputStreamReader", "(", "inputStream", ",", "encoding", ")", ")", ";", "}" ]
The Method inputStream2String() reads the data from the InputStream into a String. @param inputStream The InputStream from where we read. @param encoding the encoding @return The String that we read from the InputStream. @throws IOException Signals that an I/O exception has occurred.
[ "The", "Method", "inputStream2String", "()", "reads", "the", "data", "from", "the", "InputStream", "into", "a", "String", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/read/ReadFileExtensions.java#L99-L103
jbundle/jbundle
base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/ExternalTrxMessage.java
ExternalTrxMessage.moveHeaderParams
public void moveHeaderParams(Map<String,Object> mapMessage, Map<String,Object> mapHeader) { """ Move the header params from the message map to the header map. """ for (int i = 0; i < m_rgstrHeaderParams.length; i++) { if (mapMessage.get(m_rgstrHeaderParams[i]) != null) if (mapHeader.get(m_rgstrHeaderParams[i]) == null) { Object objValue = mapMessage.get(m_rgstrHeaderParams[i]); mapMessage.remove(m_rgstrHeaderParams[i]); mapHeader.put(m_rgstrHeaderParams[i], objValue); } } }
java
public void moveHeaderParams(Map<String,Object> mapMessage, Map<String,Object> mapHeader) { for (int i = 0; i < m_rgstrHeaderParams.length; i++) { if (mapMessage.get(m_rgstrHeaderParams[i]) != null) if (mapHeader.get(m_rgstrHeaderParams[i]) == null) { Object objValue = mapMessage.get(m_rgstrHeaderParams[i]); mapMessage.remove(m_rgstrHeaderParams[i]); mapHeader.put(m_rgstrHeaderParams[i], objValue); } } }
[ "public", "void", "moveHeaderParams", "(", "Map", "<", "String", ",", "Object", ">", "mapMessage", ",", "Map", "<", "String", ",", "Object", ">", "mapHeader", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m_rgstrHeaderParams", ".", "length", ";", "i", "++", ")", "{", "if", "(", "mapMessage", ".", "get", "(", "m_rgstrHeaderParams", "[", "i", "]", ")", "!=", "null", ")", "if", "(", "mapHeader", ".", "get", "(", "m_rgstrHeaderParams", "[", "i", "]", ")", "==", "null", ")", "{", "Object", "objValue", "=", "mapMessage", ".", "get", "(", "m_rgstrHeaderParams", "[", "i", "]", ")", ";", "mapMessage", ".", "remove", "(", "m_rgstrHeaderParams", "[", "i", "]", ")", ";", "mapHeader", ".", "put", "(", "m_rgstrHeaderParams", "[", "i", "]", ",", "objValue", ")", ";", "}", "}", "}" ]
Move the header params from the message map to the header map.
[ "Move", "the", "header", "params", "from", "the", "message", "map", "to", "the", "header", "map", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/ExternalTrxMessage.java#L225-L237
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/map/geotools/FeaturesParser.java
FeaturesParser.autoTreat
public final SimpleFeatureCollection autoTreat(final Template template, final String features) throws IOException { """ Get the features collection from a GeoJson inline string or URL. @param template the template @param features what to parse @return the feature collection @throws IOException """ SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features); if (featuresCollection == null) { featuresCollection = treatStringAsGeoJson(features); } return featuresCollection; }
java
public final SimpleFeatureCollection autoTreat(final Template template, final String features) throws IOException { SimpleFeatureCollection featuresCollection = treatStringAsURL(template, features); if (featuresCollection == null) { featuresCollection = treatStringAsGeoJson(features); } return featuresCollection; }
[ "public", "final", "SimpleFeatureCollection", "autoTreat", "(", "final", "Template", "template", ",", "final", "String", "features", ")", "throws", "IOException", "{", "SimpleFeatureCollection", "featuresCollection", "=", "treatStringAsURL", "(", "template", ",", "features", ")", ";", "if", "(", "featuresCollection", "==", "null", ")", "{", "featuresCollection", "=", "treatStringAsGeoJson", "(", "features", ")", ";", "}", "return", "featuresCollection", ";", "}" ]
Get the features collection from a GeoJson inline string or URL. @param template the template @param features what to parse @return the feature collection @throws IOException
[ "Get", "the", "features", "collection", "from", "a", "GeoJson", "inline", "string", "or", "URL", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/map/geotools/FeaturesParser.java#L151-L158
italiangrid/voms-api-java
src/main/java/org/italiangrid/voms/util/CredentialsUtils.java
CredentialsUtils.savePrivateKeyPKCS8
private static void savePrivateKeyPKCS8(OutputStream os, PrivateKey key) throws IllegalArgumentException, IOException { """ Serializes a private key to an output stream following the pkcs8 encoding. This method just delegates to canl, but provides a much more understandable signature. @param os @param key @throws IllegalArgumentException @throws IOException """ CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, null); }
java
private static void savePrivateKeyPKCS8(OutputStream os, PrivateKey key) throws IllegalArgumentException, IOException { CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, null); }
[ "private", "static", "void", "savePrivateKeyPKCS8", "(", "OutputStream", "os", ",", "PrivateKey", "key", ")", "throws", "IllegalArgumentException", ",", "IOException", "{", "CertificateUtils", ".", "savePrivateKey", "(", "os", ",", "key", ",", "Encoding", ".", "PEM", ",", "null", ",", "null", ")", ";", "}" ]
Serializes a private key to an output stream following the pkcs8 encoding. This method just delegates to canl, but provides a much more understandable signature. @param os @param key @throws IllegalArgumentException @throws IOException
[ "Serializes", "a", "private", "key", "to", "an", "output", "stream", "following", "the", "pkcs8", "encoding", "." ]
train
https://github.com/italiangrid/voms-api-java/blob/b33d6cf98ca9449bed87b1cc307d411514589deb/src/main/java/org/italiangrid/voms/util/CredentialsUtils.java#L99-L104
alkacon/opencms-core
src/org/opencms/security/CmsPersistentLoginTokenHandler.java
CmsPersistentLoginTokenHandler.invalidateToken
public void invalidateToken(CmsUser user, String token) throws CmsException { """ Invalidates all tokens for the given user.<p> @param user the user @param token the token string @throws CmsException if something goes wrong """ Token tokenObj = new Token(token); if (tokenObj.isValid()) { String addInfoKey = tokenObj.getAdditionalInfoKey(); if (null != user.getAdditionalInfo().remove(addInfoKey)) { m_adminCms.writeUser(user); } } }
java
public void invalidateToken(CmsUser user, String token) throws CmsException { Token tokenObj = new Token(token); if (tokenObj.isValid()) { String addInfoKey = tokenObj.getAdditionalInfoKey(); if (null != user.getAdditionalInfo().remove(addInfoKey)) { m_adminCms.writeUser(user); } } }
[ "public", "void", "invalidateToken", "(", "CmsUser", "user", ",", "String", "token", ")", "throws", "CmsException", "{", "Token", "tokenObj", "=", "new", "Token", "(", "token", ")", ";", "if", "(", "tokenObj", ".", "isValid", "(", ")", ")", "{", "String", "addInfoKey", "=", "tokenObj", ".", "getAdditionalInfoKey", "(", ")", ";", "if", "(", "null", "!=", "user", ".", "getAdditionalInfo", "(", ")", ".", "remove", "(", "addInfoKey", ")", ")", "{", "m_adminCms", ".", "writeUser", "(", "user", ")", ";", "}", "}", "}" ]
Invalidates all tokens for the given user.<p> @param user the user @param token the token string @throws CmsException if something goes wrong
[ "Invalidates", "all", "tokens", "for", "the", "given", "user", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsPersistentLoginTokenHandler.java#L252-L261
super-csv/super-csv
super-csv/src/main/java/org/supercsv/util/TwoDHashMap.java
TwoDHashMap.set
public Object set(final K1 firstKey, final K2 secondKey, final V value) { """ Insert a value @param firstKey first key @param secondKey second key @param value the value to be inserted. <tt>null</tt> may be inserted as well. @return null or the value the insert is replacing. """ // existence check on inner map HashMap<K2, V> innerMap = map.get(firstKey); if( innerMap == null ) { // no inner map, create it innerMap = new HashMap<K2, V>(); map.put(firstKey, innerMap); } return innerMap.put(secondKey, value); }
java
public Object set(final K1 firstKey, final K2 secondKey, final V value) { // existence check on inner map HashMap<K2, V> innerMap = map.get(firstKey); if( innerMap == null ) { // no inner map, create it innerMap = new HashMap<K2, V>(); map.put(firstKey, innerMap); } return innerMap.put(secondKey, value); }
[ "public", "Object", "set", "(", "final", "K1", "firstKey", ",", "final", "K2", "secondKey", ",", "final", "V", "value", ")", "{", "// existence check on inner map", "HashMap", "<", "K2", ",", "V", ">", "innerMap", "=", "map", ".", "get", "(", "firstKey", ")", ";", "if", "(", "innerMap", "==", "null", ")", "{", "// no inner map, create it", "innerMap", "=", "new", "HashMap", "<", "K2", ",", "V", ">", "(", ")", ";", "map", ".", "put", "(", "firstKey", ",", "innerMap", ")", ";", "}", "return", "innerMap", ".", "put", "(", "secondKey", ",", "value", ")", ";", "}" ]
Insert a value @param firstKey first key @param secondKey second key @param value the value to be inserted. <tt>null</tt> may be inserted as well. @return null or the value the insert is replacing.
[ "Insert", "a", "value" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/util/TwoDHashMap.java#L108-L119
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/string/Strs.java
Strs.indexAny
public static int indexAny(String target, Integer fromIndex, List<String> indexWith) { """ Search target string to find the first index of any string in the given string list, starting at the specified index @param target @param fromIndex @param indexWith @return """ if (isNull(target)) { return INDEX_NONE_EXISTS; } return matcher(target).indexs(fromIndex, checkNotNull(indexWith).toArray(new String[indexWith.size()])); }
java
public static int indexAny(String target, Integer fromIndex, List<String> indexWith) { if (isNull(target)) { return INDEX_NONE_EXISTS; } return matcher(target).indexs(fromIndex, checkNotNull(indexWith).toArray(new String[indexWith.size()])); }
[ "public", "static", "int", "indexAny", "(", "String", "target", ",", "Integer", "fromIndex", ",", "List", "<", "String", ">", "indexWith", ")", "{", "if", "(", "isNull", "(", "target", ")", ")", "{", "return", "INDEX_NONE_EXISTS", ";", "}", "return", "matcher", "(", "target", ")", ".", "indexs", "(", "fromIndex", ",", "checkNotNull", "(", "indexWith", ")", ".", "toArray", "(", "new", "String", "[", "indexWith", ".", "size", "(", ")", "]", ")", ")", ";", "}" ]
Search target string to find the first index of any string in the given string list, starting at the specified index @param target @param fromIndex @param indexWith @return
[ "Search", "target", "string", "to", "find", "the", "first", "index", "of", "any", "string", "in", "the", "given", "string", "list", "starting", "at", "the", "specified", "index" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Strs.java#L288-L294
Berico-Technologies/CLAVIN
src/main/java/com/bericotech/clavin/gazetteer/query/QueryBuilder.java
QueryBuilder.removeParentIds
public QueryBuilder removeParentIds(final Integer id1, final Integer... ids) { """ Remove the provided parent IDs from the set of query constraints. @param id1 the first parent ID to remove @param ids the subsequent parent IDs to remove @return this """ parentIds.remove(id1); parentIds.removeAll(Arrays.asList(ids)); return this; }
java
public QueryBuilder removeParentIds(final Integer id1, final Integer... ids) { parentIds.remove(id1); parentIds.removeAll(Arrays.asList(ids)); return this; }
[ "public", "QueryBuilder", "removeParentIds", "(", "final", "Integer", "id1", ",", "final", "Integer", "...", "ids", ")", "{", "parentIds", ".", "remove", "(", "id1", ")", ";", "parentIds", ".", "removeAll", "(", "Arrays", ".", "asList", "(", "ids", ")", ")", ";", "return", "this", ";", "}" ]
Remove the provided parent IDs from the set of query constraints. @param id1 the first parent ID to remove @param ids the subsequent parent IDs to remove @return this
[ "Remove", "the", "provided", "parent", "IDs", "from", "the", "set", "of", "query", "constraints", "." ]
train
https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/gazetteer/query/QueryBuilder.java#L322-L326
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java
RegistriesInner.beginCreate
public RegistryInner beginCreate(String resourceGroupName, String registryName, RegistryCreateParameters registryCreateParameters) { """ Creates a container registry with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param registryCreateParameters The parameters for creating a container registry. @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 RegistryInner object if successful. """ return beginCreateWithServiceResponseAsync(resourceGroupName, registryName, registryCreateParameters).toBlocking().single().body(); }
java
public RegistryInner beginCreate(String resourceGroupName, String registryName, RegistryCreateParameters registryCreateParameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, registryName, registryCreateParameters).toBlocking().single().body(); }
[ "public", "RegistryInner", "beginCreate", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "RegistryCreateParameters", "registryCreateParameters", ")", "{", "return", "beginCreateWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "registryCreateParameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates a container registry with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param registryCreateParameters The parameters for creating a container registry. @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 RegistryInner object if successful.
[ "Creates", "a", "container", "registry", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_03_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_03_01/implementation/RegistriesInner.java#L379-L381
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/util/UrlEncoded.java
UrlEncoded.decodeString
public static String decodeString(String encoded,String charset) { """ Decode String with % encoding. This method makes the assumption that the majority of calls will need no decoding. """ return decodeString(encoded,0,encoded.length(),charset); }
java
public static String decodeString(String encoded,String charset) { return decodeString(encoded,0,encoded.length(),charset); }
[ "public", "static", "String", "decodeString", "(", "String", "encoded", ",", "String", "charset", ")", "{", "return", "decodeString", "(", "encoded", ",", "0", ",", "encoded", ".", "length", "(", ")", ",", "charset", ")", ";", "}" ]
Decode String with % encoding. This method makes the assumption that the majority of calls will need no decoding.
[ "Decode", "String", "with", "%", "encoding", ".", "This", "method", "makes", "the", "assumption", "that", "the", "majority", "of", "calls", "will", "need", "no", "decoding", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/util/UrlEncoded.java#L321-L324
IanGClifton/AndroidFloatLabel
FloatLabel/src/com/iangclifton/android/floatlabel/FloatLabel.java
FloatLabel.setText
public void setText(CharSequence text, TextView.BufferType type) { """ Sets the EditText's text with label animation @param text CharSequence to set @param type TextView.BufferType """ mEditText.setText(text, type); }
java
public void setText(CharSequence text, TextView.BufferType type) { mEditText.setText(text, type); }
[ "public", "void", "setText", "(", "CharSequence", "text", ",", "TextView", ".", "BufferType", "type", ")", "{", "mEditText", ".", "setText", "(", "text", ",", "type", ")", ";", "}" ]
Sets the EditText's text with label animation @param text CharSequence to set @param type TextView.BufferType
[ "Sets", "the", "EditText", "s", "text", "with", "label", "animation" ]
train
https://github.com/IanGClifton/AndroidFloatLabel/blob/b0a39c26f010f17d5f3648331e9784a41e025c0d/FloatLabel/src/com/iangclifton/android/floatlabel/FloatLabel.java#L270-L272
virgo47/javasimon
core/src/main/java/org/javasimon/source/CachedMonitorSource.java
CachedMonitorSource.getMonitorInformation
private MonitorInformation getMonitorInformation(L location) { """ Get monitor information for given location. First monitor information is looked up in cache. Then, when not found, delegate is called. @param location Location @return Monitor information """ final K monitorKey = getLocationKey(location); MonitorInformation monitorInformation = monitorInformations.get(monitorKey); if (monitorInformation == null) { // Not found, let's call delegate if (delegate.isMonitored(location)) { monitorInformation = new MonitorInformation(true, delegate.getMonitor(location)); } else { monitorInformation = NULL_MONITOR_INFORMATION; } monitorInformations.put(monitorKey, monitorInformation); } return monitorInformation; }
java
private MonitorInformation getMonitorInformation(L location) { final K monitorKey = getLocationKey(location); MonitorInformation monitorInformation = monitorInformations.get(monitorKey); if (monitorInformation == null) { // Not found, let's call delegate if (delegate.isMonitored(location)) { monitorInformation = new MonitorInformation(true, delegate.getMonitor(location)); } else { monitorInformation = NULL_MONITOR_INFORMATION; } monitorInformations.put(monitorKey, monitorInformation); } return monitorInformation; }
[ "private", "MonitorInformation", "getMonitorInformation", "(", "L", "location", ")", "{", "final", "K", "monitorKey", "=", "getLocationKey", "(", "location", ")", ";", "MonitorInformation", "monitorInformation", "=", "monitorInformations", ".", "get", "(", "monitorKey", ")", ";", "if", "(", "monitorInformation", "==", "null", ")", "{", "// Not found, let's call delegate", "if", "(", "delegate", ".", "isMonitored", "(", "location", ")", ")", "{", "monitorInformation", "=", "new", "MonitorInformation", "(", "true", ",", "delegate", ".", "getMonitor", "(", "location", ")", ")", ";", "}", "else", "{", "monitorInformation", "=", "NULL_MONITOR_INFORMATION", ";", "}", "monitorInformations", ".", "put", "(", "monitorKey", ",", "monitorInformation", ")", ";", "}", "return", "monitorInformation", ";", "}" ]
Get monitor information for given location. First monitor information is looked up in cache. Then, when not found, delegate is called. @param location Location @return Monitor information
[ "Get", "monitor", "information", "for", "given", "location", ".", "First", "monitor", "information", "is", "looked", "up", "in", "cache", ".", "Then", "when", "not", "found", "delegate", "is", "called", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/source/CachedMonitorSource.java#L79-L92
Netflix/spectator
spectator-ext-jvm/src/main/java/com/netflix/spectator/jvm/Jmx.java
Jmx.registerMappingsFromConfig
public static void registerMappingsFromConfig(Registry registry, Config cfg) { """ Add meters based on configured JMX queries. See the {@link JmxConfig} class for more details. @param registry Registry to use for reporting the data. @param cfg Config object with the mappings. """ registry.register(new JmxMeter(registry, JmxConfig.from(cfg))); }
java
public static void registerMappingsFromConfig(Registry registry, Config cfg) { registry.register(new JmxMeter(registry, JmxConfig.from(cfg))); }
[ "public", "static", "void", "registerMappingsFromConfig", "(", "Registry", "registry", ",", "Config", "cfg", ")", "{", "registry", ".", "register", "(", "new", "JmxMeter", "(", "registry", ",", "JmxConfig", ".", "from", "(", "cfg", ")", ")", ")", ";", "}" ]
Add meters based on configured JMX queries. See the {@link JmxConfig} class for more details. @param registry Registry to use for reporting the data. @param cfg Config object with the mappings.
[ "Add", "meters", "based", "on", "configured", "JMX", "queries", ".", "See", "the", "{", "@link", "JmxConfig", "}", "class", "for", "more", "details", "." ]
train
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-jvm/src/main/java/com/netflix/spectator/jvm/Jmx.java#L57-L59
OpenLiberty/open-liberty
dev/com.ibm.tx.core/src/com/ibm/ws/Transaction/JTA/JTAResourceBase.java
JTAResourceBase.processThrowable
protected void processThrowable(String operation, Throwable t) throws XAException { """ Trace information about an unchecked exception that was thrown by an <code>XAResource</code>. Instead of propagating the unchecked exception, this method will throw an <code>XAException</code> with an errorCode of <code>XAER_RMERR</code> in its place. @param operation the method name that caught the exception @param t the <code>Throwable</code> that was thrown """ if (tc.isEventEnabled()) { Tr.event(tc, "XAResource {0} threw an unchecked exception during {1}. The original exception was {2}.", new Object[] { _resource, operation, t } ); } FFDCFilter.processException( t, this.getClass().getName() + "." + operation, "341", this); final String msg = "XAResource threw an unchecked exception"; final XAException xae = new XAException(msg); xae.errorCode = XAException.XAER_RMERR; throw xae; }
java
protected void processThrowable(String operation, Throwable t) throws XAException { if (tc.isEventEnabled()) { Tr.event(tc, "XAResource {0} threw an unchecked exception during {1}. The original exception was {2}.", new Object[] { _resource, operation, t } ); } FFDCFilter.processException( t, this.getClass().getName() + "." + operation, "341", this); final String msg = "XAResource threw an unchecked exception"; final XAException xae = new XAException(msg); xae.errorCode = XAException.XAER_RMERR; throw xae; }
[ "protected", "void", "processThrowable", "(", "String", "operation", ",", "Throwable", "t", ")", "throws", "XAException", "{", "if", "(", "tc", ".", "isEventEnabled", "(", ")", ")", "{", "Tr", ".", "event", "(", "tc", ",", "\"XAResource {0} threw an unchecked exception during {1}. The original exception was {2}.\"", ",", "new", "Object", "[", "]", "{", "_resource", ",", "operation", ",", "t", "}", ")", ";", "}", "FFDCFilter", ".", "processException", "(", "t", ",", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".\"", "+", "operation", ",", "\"341\"", ",", "this", ")", ";", "final", "String", "msg", "=", "\"XAResource threw an unchecked exception\"", ";", "final", "XAException", "xae", "=", "new", "XAException", "(", "msg", ")", ";", "xae", ".", "errorCode", "=", "XAException", ".", "XAER_RMERR", ";", "throw", "xae", ";", "}" ]
Trace information about an unchecked exception that was thrown by an <code>XAResource</code>. Instead of propagating the unchecked exception, this method will throw an <code>XAException</code> with an errorCode of <code>XAER_RMERR</code> in its place. @param operation the method name that caught the exception @param t the <code>Throwable</code> that was thrown
[ "Trace", "information", "about", "an", "unchecked", "exception", "that", "was", "thrown", "by", "an", "<code", ">", "XAResource<", "/", "code", ">", ".", "Instead", "of", "propagating", "the", "unchecked", "exception", "this", "method", "will", "throw", "an", "<code", ">", "XAException<", "/", "code", ">", "with", "an", "errorCode", "of", "<code", ">", "XAER_RMERR<", "/", "code", ">", "in", "its", "place", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.tx.core/src/com/ibm/ws/Transaction/JTA/JTAResourceBase.java#L342-L365
radkovo/CSSBox
src/main/java/org/fit/cssbox/layout/TableColumn.java
TableColumn.setSpecifiedWidth
public void setSpecifiedWidth(String width) { """ Set the width of the column form an attribute or CSS @param width the new width """ colwidth = width; try { content = new Dimension(0, 0); content.width = Integer.parseInt(width); bounds.width = content.width; abswidth = content.width; wset = true; } catch (NumberFormatException e) { if (!width.equals("")) log.warn("Invalid width value: " + width); } }
java
public void setSpecifiedWidth(String width) { colwidth = width; try { content = new Dimension(0, 0); content.width = Integer.parseInt(width); bounds.width = content.width; abswidth = content.width; wset = true; } catch (NumberFormatException e) { if (!width.equals("")) log.warn("Invalid width value: " + width); } }
[ "public", "void", "setSpecifiedWidth", "(", "String", "width", ")", "{", "colwidth", "=", "width", ";", "try", "{", "content", "=", "new", "Dimension", "(", "0", ",", "0", ")", ";", "content", ".", "width", "=", "Integer", ".", "parseInt", "(", "width", ")", ";", "bounds", ".", "width", "=", "content", ".", "width", ";", "abswidth", "=", "content", ".", "width", ";", "wset", "=", "true", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "if", "(", "!", "width", ".", "equals", "(", "\"\"", ")", ")", "log", ".", "warn", "(", "\"Invalid width value: \"", "+", "width", ")", ";", "}", "}" ]
Set the width of the column form an attribute or CSS @param width the new width
[ "Set", "the", "width", "of", "the", "column", "form", "an", "attribute", "or", "CSS" ]
train
https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/TableColumn.java#L129-L142
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java
SftpSubsystemChannel.openFile
public SftpFile openFile(String absolutePath, int flags, SftpFileAttributes attrs) throws SftpStatusException, SshException { """ Open a file. @param absolutePath @param flags @param attrs @return SftpFile @throws SftpStatusException , SshException """ if (attrs == null) { attrs = new SftpFileAttributes(this, SftpFileAttributes.SSH_FILEXFER_TYPE_UNKNOWN); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_OPEN); msg.writeInt(requestId.longValue()); msg.writeString(absolutePath, CHARSET_ENCODING); msg.writeInt(flags); msg.write(attrs.toByteArray()); sendMessage(msg); byte[] handle = getHandleResponse(requestId); SftpFile file = new SftpFile(absolutePath, null); file.setHandle(handle); file.setSFTPSubsystem(this); EventServiceImplementation.getInstance().fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_OPENED, true)).addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, file.getAbsolutePath())); return file; } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
public SftpFile openFile(String absolutePath, int flags, SftpFileAttributes attrs) throws SftpStatusException, SshException { if (attrs == null) { attrs = new SftpFileAttributes(this, SftpFileAttributes.SSH_FILEXFER_TYPE_UNKNOWN); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_OPEN); msg.writeInt(requestId.longValue()); msg.writeString(absolutePath, CHARSET_ENCODING); msg.writeInt(flags); msg.write(attrs.toByteArray()); sendMessage(msg); byte[] handle = getHandleResponse(requestId); SftpFile file = new SftpFile(absolutePath, null); file.setHandle(handle); file.setSFTPSubsystem(this); EventServiceImplementation.getInstance().fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_OPENED, true)).addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, file.getAbsolutePath())); return file; } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
[ "public", "SftpFile", "openFile", "(", "String", "absolutePath", ",", "int", "flags", ",", "SftpFileAttributes", "attrs", ")", "throws", "SftpStatusException", ",", "SshException", "{", "if", "(", "attrs", "==", "null", ")", "{", "attrs", "=", "new", "SftpFileAttributes", "(", "this", ",", "SftpFileAttributes", ".", "SSH_FILEXFER_TYPE_UNKNOWN", ")", ";", "}", "try", "{", "UnsignedInteger32", "requestId", "=", "nextRequestId", "(", ")", ";", "Packet", "msg", "=", "createPacket", "(", ")", ";", "msg", ".", "write", "(", "SSH_FXP_OPEN", ")", ";", "msg", ".", "writeInt", "(", "requestId", ".", "longValue", "(", ")", ")", ";", "msg", ".", "writeString", "(", "absolutePath", ",", "CHARSET_ENCODING", ")", ";", "msg", ".", "writeInt", "(", "flags", ")", ";", "msg", ".", "write", "(", "attrs", ".", "toByteArray", "(", ")", ")", ";", "sendMessage", "(", "msg", ")", ";", "byte", "[", "]", "handle", "=", "getHandleResponse", "(", "requestId", ")", ";", "SftpFile", "file", "=", "new", "SftpFile", "(", "absolutePath", ",", "null", ")", ";", "file", ".", "setHandle", "(", "handle", ")", ";", "file", ".", "setSFTPSubsystem", "(", "this", ")", ";", "EventServiceImplementation", ".", "getInstance", "(", ")", ".", "fireEvent", "(", "(", "new", "Event", "(", "this", ",", "J2SSHEventCodes", ".", "EVENT_SFTP_FILE_OPENED", ",", "true", ")", ")", ".", "addAttribute", "(", "J2SSHEventCodes", ".", "ATTRIBUTE_FILE_NAME", ",", "file", ".", "getAbsolutePath", "(", ")", ")", ")", ";", "return", "file", ";", "}", "catch", "(", "SshIOException", "ex", ")", "{", "throw", "ex", ".", "getRealException", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "SshException", "(", "ex", ")", ";", "}", "}" ]
Open a file. @param absolutePath @param flags @param attrs @return SftpFile @throws SftpStatusException , SshException
[ "Open", "a", "file", "." ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java#L1542-L1577
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/support/ReflectionUtils.java
ReflectionUtils.getField
public static Object getField(Field field, Object target) { """ Get the field represented by the supplied {@link Field field object} on the specified {@link Object target object}. In accordance with {@link Field#get(Object)} semantics, the returned value is automatically wrapped if the underlying field has a primitive type. <p> Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}. @param field the field to get @param target the target object from which to get the field @return the field's current value """ try { return field.get(target); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } }
java
public static Object getField(Field field, Object target) { try { return field.get(target); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } }
[ "public", "static", "Object", "getField", "(", "Field", "field", ",", "Object", "target", ")", "{", "try", "{", "return", "field", ".", "get", "(", "target", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "handleReflectionException", "(", "ex", ")", ";", "throw", "new", "IllegalStateException", "(", "\"Unexpected reflection exception - \"", "+", "ex", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\": \"", "+", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Get the field represented by the supplied {@link Field field object} on the specified {@link Object target object}. In accordance with {@link Field#get(Object)} semantics, the returned value is automatically wrapped if the underlying field has a primitive type. <p> Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}. @param field the field to get @param target the target object from which to get the field @return the field's current value
[ "Get", "the", "field", "represented", "by", "the", "supplied", "{", "@link", "Field", "field", "object", "}", "on", "the", "specified", "{", "@link", "Object", "target", "object", "}", ".", "In", "accordance", "with", "{", "@link", "Field#get", "(", "Object", ")", "}", "semantics", "the", "returned", "value", "is", "automatically", "wrapped", "if", "the", "underlying", "field", "has", "a", "primitive", "type", ".", "<p", ">", "Thrown", "exceptions", "are", "handled", "via", "a", "call", "to", "{", "@link", "#handleReflectionException", "(", "Exception", ")", "}", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/support/ReflectionUtils.java#L44-L52
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java
RoundRobinPacking.repack
@Override public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) throws PackingException { """ Read the current packing plan with update parallelism to calculate a new packing plan. This method should determine a new number of containers based on the updated parallism while remaining the number of instances per container <= that of the old packing plan. The packing algorithm packInternal() is shared with pack() delegate to packInternal() with the new container count and component parallelism @param currentPackingPlan Existing packing plan @param componentChanges Map &lt; componentName, new component parallelism &gt; that contains the parallelism for each component whose parallelism has changed. @return new packing plan @throws PackingException """ int initialNumContainer = TopologyUtils.getNumContainers(topology); int initialNumInstance = TopologyUtils.getTotalInstance(topology); double initialNumInstancePerContainer = (double) initialNumInstance / initialNumContainer; Map<String, Integer> newComponentParallelism = getNewComponentParallelism(currentPackingPlan, componentChanges); int newNumInstance = TopologyUtils.getTotalInstance(newComponentParallelism); int newNumContainer = (int) Math.ceil(newNumInstance / initialNumInstancePerContainer); return packInternal(newNumContainer, newComponentParallelism); }
java
@Override public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) throws PackingException { int initialNumContainer = TopologyUtils.getNumContainers(topology); int initialNumInstance = TopologyUtils.getTotalInstance(topology); double initialNumInstancePerContainer = (double) initialNumInstance / initialNumContainer; Map<String, Integer> newComponentParallelism = getNewComponentParallelism(currentPackingPlan, componentChanges); int newNumInstance = TopologyUtils.getTotalInstance(newComponentParallelism); int newNumContainer = (int) Math.ceil(newNumInstance / initialNumInstancePerContainer); return packInternal(newNumContainer, newComponentParallelism); }
[ "@", "Override", "public", "PackingPlan", "repack", "(", "PackingPlan", "currentPackingPlan", ",", "Map", "<", "String", ",", "Integer", ">", "componentChanges", ")", "throws", "PackingException", "{", "int", "initialNumContainer", "=", "TopologyUtils", ".", "getNumContainers", "(", "topology", ")", ";", "int", "initialNumInstance", "=", "TopologyUtils", ".", "getTotalInstance", "(", "topology", ")", ";", "double", "initialNumInstancePerContainer", "=", "(", "double", ")", "initialNumInstance", "/", "initialNumContainer", ";", "Map", "<", "String", ",", "Integer", ">", "newComponentParallelism", "=", "getNewComponentParallelism", "(", "currentPackingPlan", ",", "componentChanges", ")", ";", "int", "newNumInstance", "=", "TopologyUtils", ".", "getTotalInstance", "(", "newComponentParallelism", ")", ";", "int", "newNumContainer", "=", "(", "int", ")", "Math", ".", "ceil", "(", "newNumInstance", "/", "initialNumInstancePerContainer", ")", ";", "return", "packInternal", "(", "newNumContainer", ",", "newComponentParallelism", ")", ";", "}" ]
Read the current packing plan with update parallelism to calculate a new packing plan. This method should determine a new number of containers based on the updated parallism while remaining the number of instances per container <= that of the old packing plan. The packing algorithm packInternal() is shared with pack() delegate to packInternal() with the new container count and component parallelism @param currentPackingPlan Existing packing plan @param componentChanges Map &lt; componentName, new component parallelism &gt; that contains the parallelism for each component whose parallelism has changed. @return new packing plan @throws PackingException
[ "Read", "the", "current", "packing", "plan", "with", "update", "parallelism", "to", "calculate", "a", "new", "packing", "plan", ".", "This", "method", "should", "determine", "a", "new", "number", "of", "containers", "based", "on", "the", "updated", "parallism", "while", "remaining", "the", "number", "of", "instances", "per", "container", "<", "=", "that", "of", "the", "old", "packing", "plan", ".", "The", "packing", "algorithm", "packInternal", "()", "is", "shared", "with", "pack", "()", "delegate", "to", "packInternal", "()", "with", "the", "new", "container", "count", "and", "component", "parallelism" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java#L478-L491
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java
SpiderTransaction.deleteTermIndexColumn
public void deleteTermIndexColumn(TableDefinition tableDef, DBObject dbObj, String fieldName, String term) { """ Un-index the given term by deleting the Terms column for the given DBObject, field name, and term. @param tableDef {@link TableDefinition} of table that owns object. @param dbObj DBObject that owns field. @param fieldName Field name. @param term Term being un-indexed. """ deleteColumn(SpiderService.termsStoreName(tableDef), SpiderService.termIndexRowKey(tableDef, dbObj, fieldName, term), dbObj.getObjectID()); }
java
public void deleteTermIndexColumn(TableDefinition tableDef, DBObject dbObj, String fieldName, String term) { deleteColumn(SpiderService.termsStoreName(tableDef), SpiderService.termIndexRowKey(tableDef, dbObj, fieldName, term), dbObj.getObjectID()); }
[ "public", "void", "deleteTermIndexColumn", "(", "TableDefinition", "tableDef", ",", "DBObject", "dbObj", ",", "String", "fieldName", ",", "String", "term", ")", "{", "deleteColumn", "(", "SpiderService", ".", "termsStoreName", "(", "tableDef", ")", ",", "SpiderService", ".", "termIndexRowKey", "(", "tableDef", ",", "dbObj", ",", "fieldName", ",", "term", ")", ",", "dbObj", ".", "getObjectID", "(", ")", ")", ";", "}" ]
Un-index the given term by deleting the Terms column for the given DBObject, field name, and term. @param tableDef {@link TableDefinition} of table that owns object. @param dbObj DBObject that owns field. @param fieldName Field name. @param term Term being un-indexed.
[ "Un", "-", "index", "the", "given", "term", "by", "deleting", "the", "Terms", "column", "for", "the", "given", "DBObject", "field", "name", "and", "term", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java#L421-L425
eurekaclinical/javautil
src/main/java/org/arp/javautil/collections/Collections.java
Collections.containsAny
public static <K> boolean containsAny(Set<K> aSet, K[] arr) { """ Checks whether any of an array's elements are also in the provided set. @param aSet a {@link Set}. @param arr an array. @return <code>true</code> or <code>false</code>. """ for (K obj : arr) { if (aSet.contains(obj)) { return true; } } return false; }
java
public static <K> boolean containsAny(Set<K> aSet, K[] arr) { for (K obj : arr) { if (aSet.contains(obj)) { return true; } } return false; }
[ "public", "static", "<", "K", ">", "boolean", "containsAny", "(", "Set", "<", "K", ">", "aSet", ",", "K", "[", "]", "arr", ")", "{", "for", "(", "K", "obj", ":", "arr", ")", "{", "if", "(", "aSet", ".", "contains", "(", "obj", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether any of an array's elements are also in the provided set. @param aSet a {@link Set}. @param arr an array. @return <code>true</code> or <code>false</code>.
[ "Checks", "whether", "any", "of", "an", "array", "s", "elements", "are", "also", "in", "the", "provided", "set", "." ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/collections/Collections.java#L130-L137
skuzzle/semantic-version
src/it/java/de/skuzzle/semantic/VersionRegEx.java
VersionRegEx.max
public static VersionRegEx max(VersionRegEx v1, VersionRegEx v2) { """ Returns the greater of the two given versions by comparing them using their natural ordering. If both versions are equal, then the first argument is returned. @param v1 The first version. @param v2 The second version. @return The greater version. @throws IllegalArgumentException If either argument is <code>null</code>. @since 0.4.0 """ require(v1 != null, "v1 is null"); require(v2 != null, "v2 is null"); return compare(v1, v2, false) < 0 ? v2 : v1; }
java
public static VersionRegEx max(VersionRegEx v1, VersionRegEx v2) { require(v1 != null, "v1 is null"); require(v2 != null, "v2 is null"); return compare(v1, v2, false) < 0 ? v2 : v1; }
[ "public", "static", "VersionRegEx", "max", "(", "VersionRegEx", "v1", ",", "VersionRegEx", "v2", ")", "{", "require", "(", "v1", "!=", "null", ",", "\"v1 is null\"", ")", ";", "require", "(", "v2", "!=", "null", ",", "\"v2 is null\"", ")", ";", "return", "compare", "(", "v1", ",", "v2", ",", "false", ")", "<", "0", "?", "v2", ":", "v1", ";", "}" ]
Returns the greater of the two given versions by comparing them using their natural ordering. If both versions are equal, then the first argument is returned. @param v1 The first version. @param v2 The second version. @return The greater version. @throws IllegalArgumentException If either argument is <code>null</code>. @since 0.4.0
[ "Returns", "the", "greater", "of", "the", "two", "given", "versions", "by", "comparing", "them", "using", "their", "natural", "ordering", ".", "If", "both", "versions", "are", "equal", "then", "the", "first", "argument", "is", "returned", "." ]
train
https://github.com/skuzzle/semantic-version/blob/2ddb66fb80244cd7f67c77ed5f8072d1132ad933/src/it/java/de/skuzzle/semantic/VersionRegEx.java#L228-L234
netty/netty
buffer/src/main/java/io/netty/buffer/ByteBufUtil.java
ByteBufUtil.writeAscii
public static ByteBuf writeAscii(ByteBufAllocator alloc, CharSequence seq) { """ Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> and write it to a {@link ByteBuf} allocated with {@code alloc}. @param alloc The allocator used to allocate a new {@link ByteBuf}. @param seq The characters to write into a buffer. @return The {@link ByteBuf} which contains the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> encoded result. """ // ASCII uses 1 byte per char ByteBuf buf = alloc.buffer(seq.length()); writeAscii(buf, seq); return buf; }
java
public static ByteBuf writeAscii(ByteBufAllocator alloc, CharSequence seq) { // ASCII uses 1 byte per char ByteBuf buf = alloc.buffer(seq.length()); writeAscii(buf, seq); return buf; }
[ "public", "static", "ByteBuf", "writeAscii", "(", "ByteBufAllocator", "alloc", ",", "CharSequence", "seq", ")", "{", "// ASCII uses 1 byte per char", "ByteBuf", "buf", "=", "alloc", ".", "buffer", "(", "seq", ".", "length", "(", ")", ")", ";", "writeAscii", "(", "buf", ",", "seq", ")", ";", "return", "buf", ";", "}" ]
Encode a {@link CharSequence} in <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> and write it to a {@link ByteBuf} allocated with {@code alloc}. @param alloc The allocator used to allocate a new {@link ByteBuf}. @param seq The characters to write into a buffer. @return The {@link ByteBuf} which contains the <a href="http://en.wikipedia.org/wiki/ASCII">ASCII</a> encoded result.
[ "Encode", "a", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java#L668-L673
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsModelPageHelper.java
CmsModelPageHelper.createModelGroupPage
public CmsResource createModelGroupPage(String name, String description, CmsUUID copyId) throws CmsException { """ Creates a new model group page.<p> @param name the page name @param description the page description @param copyId structure id of the resource to use as a model for the model page, if any (may be null) @return the new resource @throws CmsException in case something goes wrong """ CmsResource newPage = null; CmsResourceTypeConfig config = m_adeConfig.getResourceType( CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME); if ((config != null) && !config.isDisabled()) { if (copyId == null) { newPage = config.createNewElement(m_cms, m_rootResource.getRootPath()); } else { CmsResource copyResource = m_cms.readResource(copyId); newPage = config.createNewElement(m_cms, copyResource, m_rootResource.getRootPath()); } m_cms.lockResource(newPage); CmsProperty titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, name, null); CmsProperty descriptionProp = new CmsProperty( CmsPropertyDefinition.PROPERTY_DESCRIPTION, description, null); m_cms.writePropertyObject(m_cms.getSitePath(newPage), titleProp); m_cms.writePropertyObject(m_cms.getSitePath(newPage), descriptionProp); tryUnlock(newPage); } return newPage; }
java
public CmsResource createModelGroupPage(String name, String description, CmsUUID copyId) throws CmsException { CmsResource newPage = null; CmsResourceTypeConfig config = m_adeConfig.getResourceType( CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME); if ((config != null) && !config.isDisabled()) { if (copyId == null) { newPage = config.createNewElement(m_cms, m_rootResource.getRootPath()); } else { CmsResource copyResource = m_cms.readResource(copyId); newPage = config.createNewElement(m_cms, copyResource, m_rootResource.getRootPath()); } m_cms.lockResource(newPage); CmsProperty titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, name, null); CmsProperty descriptionProp = new CmsProperty( CmsPropertyDefinition.PROPERTY_DESCRIPTION, description, null); m_cms.writePropertyObject(m_cms.getSitePath(newPage), titleProp); m_cms.writePropertyObject(m_cms.getSitePath(newPage), descriptionProp); tryUnlock(newPage); } return newPage; }
[ "public", "CmsResource", "createModelGroupPage", "(", "String", "name", ",", "String", "description", ",", "CmsUUID", "copyId", ")", "throws", "CmsException", "{", "CmsResource", "newPage", "=", "null", ";", "CmsResourceTypeConfig", "config", "=", "m_adeConfig", ".", "getResourceType", "(", "CmsResourceTypeXmlContainerPage", ".", "MODEL_GROUP_TYPE_NAME", ")", ";", "if", "(", "(", "config", "!=", "null", ")", "&&", "!", "config", ".", "isDisabled", "(", ")", ")", "{", "if", "(", "copyId", "==", "null", ")", "{", "newPage", "=", "config", ".", "createNewElement", "(", "m_cms", ",", "m_rootResource", ".", "getRootPath", "(", ")", ")", ";", "}", "else", "{", "CmsResource", "copyResource", "=", "m_cms", ".", "readResource", "(", "copyId", ")", ";", "newPage", "=", "config", ".", "createNewElement", "(", "m_cms", ",", "copyResource", ",", "m_rootResource", ".", "getRootPath", "(", ")", ")", ";", "}", "m_cms", ".", "lockResource", "(", "newPage", ")", ";", "CmsProperty", "titleProp", "=", "new", "CmsProperty", "(", "CmsPropertyDefinition", ".", "PROPERTY_TITLE", ",", "name", ",", "null", ")", ";", "CmsProperty", "descriptionProp", "=", "new", "CmsProperty", "(", "CmsPropertyDefinition", ".", "PROPERTY_DESCRIPTION", ",", "description", ",", "null", ")", ";", "m_cms", ".", "writePropertyObject", "(", "m_cms", ".", "getSitePath", "(", "newPage", ")", ",", "titleProp", ")", ";", "m_cms", ".", "writePropertyObject", "(", "m_cms", ".", "getSitePath", "(", "newPage", ")", ",", "descriptionProp", ")", ";", "tryUnlock", "(", "newPage", ")", ";", "}", "return", "newPage", ";", "}" ]
Creates a new model group page.<p> @param name the page name @param description the page description @param copyId structure id of the resource to use as a model for the model page, if any (may be null) @return the new resource @throws CmsException in case something goes wrong
[ "Creates", "a", "new", "model", "group", "page", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsModelPageHelper.java#L172-L195
agmip/agmip-common-functions
src/main/java/org/agmip/common/Functions.java
Functions.substract
public static String substract(String minuend, String... subtrahends) { """ Get the difference of minuend and all subtrahends Any numeric string recognized by {@code BigDecimal} is supported. @param minuend A valid number string @param subtrahends one or more valid number strings @return <code>minuend - subtrahends[0] - subtrahends[1] - ...</code> @see BigDecimal """ if (subtrahends == null) { return minuend; } BigDecimal difference; try { difference = new BigDecimal(minuend); for (int i = 0; i < subtrahends.length; i++) { difference = difference.subtract(new BigDecimal(subtrahends[i])); } return difference.toString(); } catch (Exception e) { return null; } }
java
public static String substract(String minuend, String... subtrahends) { if (subtrahends == null) { return minuend; } BigDecimal difference; try { difference = new BigDecimal(minuend); for (int i = 0; i < subtrahends.length; i++) { difference = difference.subtract(new BigDecimal(subtrahends[i])); } return difference.toString(); } catch (Exception e) { return null; } }
[ "public", "static", "String", "substract", "(", "String", "minuend", ",", "String", "...", "subtrahends", ")", "{", "if", "(", "subtrahends", "==", "null", ")", "{", "return", "minuend", ";", "}", "BigDecimal", "difference", ";", "try", "{", "difference", "=", "new", "BigDecimal", "(", "minuend", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "subtrahends", ".", "length", ";", "i", "++", ")", "{", "difference", "=", "difference", ".", "subtract", "(", "new", "BigDecimal", "(", "subtrahends", "[", "i", "]", ")", ")", ";", "}", "return", "difference", ".", "toString", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "}" ]
Get the difference of minuend and all subtrahends Any numeric string recognized by {@code BigDecimal} is supported. @param minuend A valid number string @param subtrahends one or more valid number strings @return <code>minuend - subtrahends[0] - subtrahends[1] - ...</code> @see BigDecimal
[ "Get", "the", "difference", "of", "minuend", "and", "all", "subtrahends" ]
train
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/common/Functions.java#L291-L307
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonArray.java
JsonArray.fromParser
public static JsonArray fromParser(JsonPullParser parser) throws IOException, JsonFormatException { """ Parses the given JSON data as an array. @param parser {@link JsonPullParser} with some JSON-formatted data @return {@link JsonArray} @throws IOException @throws JsonFormatException @author vvakame """ State state = parser.getEventType(); if (state == State.VALUE_NULL) { return null; } else if (state != State.START_ARRAY) { throw new JsonFormatException("unexpected token. token=" + state, parser); } JsonArray jsonArray = new JsonArray(); while ((state = parser.lookAhead()) != State.END_ARRAY) { jsonArray.add(getValue(parser), state); } parser.getEventType(); return jsonArray; }
java
public static JsonArray fromParser(JsonPullParser parser) throws IOException, JsonFormatException { State state = parser.getEventType(); if (state == State.VALUE_NULL) { return null; } else if (state != State.START_ARRAY) { throw new JsonFormatException("unexpected token. token=" + state, parser); } JsonArray jsonArray = new JsonArray(); while ((state = parser.lookAhead()) != State.END_ARRAY) { jsonArray.add(getValue(parser), state); } parser.getEventType(); return jsonArray; }
[ "public", "static", "JsonArray", "fromParser", "(", "JsonPullParser", "parser", ")", "throws", "IOException", ",", "JsonFormatException", "{", "State", "state", "=", "parser", ".", "getEventType", "(", ")", ";", "if", "(", "state", "==", "State", ".", "VALUE_NULL", ")", "{", "return", "null", ";", "}", "else", "if", "(", "state", "!=", "State", ".", "START_ARRAY", ")", "{", "throw", "new", "JsonFormatException", "(", "\"unexpected token. token=\"", "+", "state", ",", "parser", ")", ";", "}", "JsonArray", "jsonArray", "=", "new", "JsonArray", "(", ")", ";", "while", "(", "(", "state", "=", "parser", ".", "lookAhead", "(", ")", ")", "!=", "State", ".", "END_ARRAY", ")", "{", "jsonArray", ".", "add", "(", "getValue", "(", "parser", ")", ",", "state", ")", ";", "}", "parser", ".", "getEventType", "(", ")", ";", "return", "jsonArray", ";", "}" ]
Parses the given JSON data as an array. @param parser {@link JsonPullParser} with some JSON-formatted data @return {@link JsonArray} @throws IOException @throws JsonFormatException @author vvakame
[ "Parses", "the", "given", "JSON", "data", "as", "an", "array", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonArray.java#L63-L80
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/action/ActionableHelper.java
ActionableHelper.deleteFilePathOnExit
public static void deleteFilePathOnExit(FilePath filePath) throws IOException, InterruptedException { """ Deletes a FilePath file on exit. @param filePath The FilePath to delete on exit. @throws IOException In case of a missing file. """ filePath.act(new MasterToSlaveFileCallable<Void>() { public Void invoke(File file, VirtualChannel virtualChannel) throws IOException, InterruptedException { file.deleteOnExit(); return null; } }); }
java
public static void deleteFilePathOnExit(FilePath filePath) throws IOException, InterruptedException { filePath.act(new MasterToSlaveFileCallable<Void>() { public Void invoke(File file, VirtualChannel virtualChannel) throws IOException, InterruptedException { file.deleteOnExit(); return null; } }); }
[ "public", "static", "void", "deleteFilePathOnExit", "(", "FilePath", "filePath", ")", "throws", "IOException", ",", "InterruptedException", "{", "filePath", ".", "act", "(", "new", "MasterToSlaveFileCallable", "<", "Void", ">", "(", ")", "{", "public", "Void", "invoke", "(", "File", "file", ",", "VirtualChannel", "virtualChannel", ")", "throws", "IOException", ",", "InterruptedException", "{", "file", ".", "deleteOnExit", "(", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}" ]
Deletes a FilePath file on exit. @param filePath The FilePath to delete on exit. @throws IOException In case of a missing file.
[ "Deletes", "a", "FilePath", "file", "on", "exit", "." ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/action/ActionableHelper.java#L306-L313
alkacon/opencms-core
src/org/opencms/publish/CmsPublishManager.java
CmsPublishManager.getPublishListAll
public CmsPublishList getPublishListAll( CmsObject cms, List<CmsResource> directPublishResources, boolean directPublishSiblings, boolean isUserPublishList) throws CmsException { """ Returns a publish list with all the given resources, filtered only by state.<p> @param cms the cms request context @param directPublishResources the {@link CmsResource} objects which will be directly published @param directPublishSiblings <code>true</code>, if all eventual siblings of the direct published resources should also get published @param isUserPublishList if true, the publish list consists of resources directly selected by the user to publish @return a publish list @throws CmsException if something goes wrong """ CmsPublishList pubList = new CmsPublishList(true, directPublishResources, directPublishSiblings); pubList.setUserPublishList(isUserPublishList); return m_securityManager.fillPublishList(cms.getRequestContext(), pubList); }
java
public CmsPublishList getPublishListAll( CmsObject cms, List<CmsResource> directPublishResources, boolean directPublishSiblings, boolean isUserPublishList) throws CmsException { CmsPublishList pubList = new CmsPublishList(true, directPublishResources, directPublishSiblings); pubList.setUserPublishList(isUserPublishList); return m_securityManager.fillPublishList(cms.getRequestContext(), pubList); }
[ "public", "CmsPublishList", "getPublishListAll", "(", "CmsObject", "cms", ",", "List", "<", "CmsResource", ">", "directPublishResources", ",", "boolean", "directPublishSiblings", ",", "boolean", "isUserPublishList", ")", "throws", "CmsException", "{", "CmsPublishList", "pubList", "=", "new", "CmsPublishList", "(", "true", ",", "directPublishResources", ",", "directPublishSiblings", ")", ";", "pubList", ".", "setUserPublishList", "(", "isUserPublishList", ")", ";", "return", "m_securityManager", ".", "fillPublishList", "(", "cms", ".", "getRequestContext", "(", ")", ",", "pubList", ")", ";", "}" ]
Returns a publish list with all the given resources, filtered only by state.<p> @param cms the cms request context @param directPublishResources the {@link CmsResource} objects which will be directly published @param directPublishSiblings <code>true</code>, if all eventual siblings of the direct published resources should also get published @param isUserPublishList if true, the publish list consists of resources directly selected by the user to publish @return a publish list @throws CmsException if something goes wrong
[ "Returns", "a", "publish", "list", "with", "all", "the", "given", "resources", "filtered", "only", "by", "state", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/publish/CmsPublishManager.java#L374-L384
UrielCh/ovh-java-sdk
ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java
ApiOvhIpLoadbalancing.serviceName_tcp_route_routeId_rule_POST
public OvhRouteRule serviceName_tcp_route_routeId_rule_POST(String serviceName, Long routeId, String displayName, String field, OvhRouteRuleMatchesEnum match, Boolean negate, String pattern, String subField) throws IOException { """ Add a new rule to your route REST: POST /ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule @param field [required] Name of the field to match like "protocol" or "host". See "/ipLoadbalancing/{serviceName}/availableRouteRules" for a list of available rules @param subField [required] Name of sub-field, if applicable. This may be a Cookie or Header name for instance @param pattern [required] Value to match against this match. Interpretation if this field depends on the match and field @param displayName [required] Human readable name for your rule @param match [required] Matching operator. Not all operators are available for all fields. See "/ipLoadbalancing/{serviceName}/availableRouteRules" @param negate [required] Invert the matching operator effect @param serviceName [required] The internal name of your IP load balancing @param routeId [required] Id of your route """ String qPath = "/ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule"; StringBuilder sb = path(qPath, serviceName, routeId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "displayName", displayName); addBody(o, "field", field); addBody(o, "match", match); addBody(o, "negate", negate); addBody(o, "pattern", pattern); addBody(o, "subField", subField); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhRouteRule.class); }
java
public OvhRouteRule serviceName_tcp_route_routeId_rule_POST(String serviceName, Long routeId, String displayName, String field, OvhRouteRuleMatchesEnum match, Boolean negate, String pattern, String subField) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule"; StringBuilder sb = path(qPath, serviceName, routeId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "displayName", displayName); addBody(o, "field", field); addBody(o, "match", match); addBody(o, "negate", negate); addBody(o, "pattern", pattern); addBody(o, "subField", subField); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhRouteRule.class); }
[ "public", "OvhRouteRule", "serviceName_tcp_route_routeId_rule_POST", "(", "String", "serviceName", ",", "Long", "routeId", ",", "String", "displayName", ",", "String", "field", ",", "OvhRouteRuleMatchesEnum", "match", ",", "Boolean", "negate", ",", "String", "pattern", ",", "String", "subField", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "routeId", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"displayName\"", ",", "displayName", ")", ";", "addBody", "(", "o", ",", "\"field\"", ",", "field", ")", ";", "addBody", "(", "o", ",", "\"match\"", ",", "match", ")", ";", "addBody", "(", "o", ",", "\"negate\"", ",", "negate", ")", ";", "addBody", "(", "o", ",", "\"pattern\"", ",", "pattern", ")", ";", "addBody", "(", "o", ",", "\"subField\"", ",", "subField", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhRouteRule", ".", "class", ")", ";", "}" ]
Add a new rule to your route REST: POST /ipLoadbalancing/{serviceName}/tcp/route/{routeId}/rule @param field [required] Name of the field to match like "protocol" or "host". See "/ipLoadbalancing/{serviceName}/availableRouteRules" for a list of available rules @param subField [required] Name of sub-field, if applicable. This may be a Cookie or Header name for instance @param pattern [required] Value to match against this match. Interpretation if this field depends on the match and field @param displayName [required] Human readable name for your rule @param match [required] Matching operator. Not all operators are available for all fields. See "/ipLoadbalancing/{serviceName}/availableRouteRules" @param negate [required] Invert the matching operator effect @param serviceName [required] The internal name of your IP load balancing @param routeId [required] Id of your route
[ "Add", "a", "new", "rule", "to", "your", "route" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1367-L1379
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/util/mem/Memory.java
Memory.setBytes
public void setBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count) { """ Transfers count bytes from buffer to Memory @param memoryOffset start offset in the memory @param buffer the data buffer @param bufferOffset start offset of the buffer @param count number of bytes to transfer """ if (buffer == null) throw new NullPointerException(); else if (bufferOffset < 0 || count < 0 || bufferOffset + count > buffer.length) throw new IndexOutOfBoundsException(); else if (count == 0) return; checkPosition(memoryOffset); long end = memoryOffset + count; checkPosition(end - 1); while (memoryOffset < end) { unsafe.putByte(peer + memoryOffset, buffer[bufferOffset]); memoryOffset++; bufferOffset++; } }
java
public void setBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count) { if (buffer == null) throw new NullPointerException(); else if (bufferOffset < 0 || count < 0 || bufferOffset + count > buffer.length) throw new IndexOutOfBoundsException(); else if (count == 0) return; checkPosition(memoryOffset); long end = memoryOffset + count; checkPosition(end - 1); while (memoryOffset < end) { unsafe.putByte(peer + memoryOffset, buffer[bufferOffset]); memoryOffset++; bufferOffset++; } }
[ "public", "void", "setBytes", "(", "long", "memoryOffset", ",", "byte", "[", "]", "buffer", ",", "int", "bufferOffset", ",", "int", "count", ")", "{", "if", "(", "buffer", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "else", "if", "(", "bufferOffset", "<", "0", "||", "count", "<", "0", "||", "bufferOffset", "+", "count", ">", "buffer", ".", "length", ")", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "else", "if", "(", "count", "==", "0", ")", "return", ";", "checkPosition", "(", "memoryOffset", ")", ";", "long", "end", "=", "memoryOffset", "+", "count", ";", "checkPosition", "(", "end", "-", "1", ")", ";", "while", "(", "memoryOffset", "<", "end", ")", "{", "unsafe", ".", "putByte", "(", "peer", "+", "memoryOffset", ",", "buffer", "[", "bufferOffset", "]", ")", ";", "memoryOffset", "++", ";", "bufferOffset", "++", ";", "}", "}" ]
Transfers count bytes from buffer to Memory @param memoryOffset start offset in the memory @param buffer the data buffer @param bufferOffset start offset of the buffer @param count number of bytes to transfer
[ "Transfers", "count", "bytes", "from", "buffer", "to", "Memory" ]
train
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/util/mem/Memory.java#L114-L134
stripe/stripe-android
stripe/src/main/java/com/stripe/android/CustomerSession.java
CustomerSession.initCustomerSession
public static void initCustomerSession(@NonNull Context context, @NonNull EphemeralKeyProvider keyProvider) { """ Create a CustomerSession with the provided {@link EphemeralKeyProvider}. @param context application context @param keyProvider an {@link EphemeralKeyProvider} used to get {@link CustomerEphemeralKey EphemeralKeys} as needed """ setInstance(new CustomerSession(context, keyProvider)); }
java
public static void initCustomerSession(@NonNull Context context, @NonNull EphemeralKeyProvider keyProvider) { setInstance(new CustomerSession(context, keyProvider)); }
[ "public", "static", "void", "initCustomerSession", "(", "@", "NonNull", "Context", "context", ",", "@", "NonNull", "EphemeralKeyProvider", "keyProvider", ")", "{", "setInstance", "(", "new", "CustomerSession", "(", "context", ",", "keyProvider", ")", ")", ";", "}" ]
Create a CustomerSession with the provided {@link EphemeralKeyProvider}. @param context application context @param keyProvider an {@link EphemeralKeyProvider} used to get {@link CustomerEphemeralKey EphemeralKeys} as needed
[ "Create", "a", "CustomerSession", "with", "the", "provided", "{", "@link", "EphemeralKeyProvider", "}", "." ]
train
https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/CustomerSession.java#L108-L111
elki-project/elki
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/strings/LevenshteinDistanceFunction.java
LevenshteinDistanceFunction.prefixLen
private static int prefixLen(String o1, String o2) { """ Compute the length of the prefix. @param o1 First string @param o2 Second string @return Prefix length """ final int l1 = o1.length(), l2 = o2.length(), l = l1 < l2 ? l1 : l2; int prefix = 0; while(prefix < l && (o1.charAt(prefix) == o2.charAt(prefix))) { prefix++; } return prefix; }
java
private static int prefixLen(String o1, String o2) { final int l1 = o1.length(), l2 = o2.length(), l = l1 < l2 ? l1 : l2; int prefix = 0; while(prefix < l && (o1.charAt(prefix) == o2.charAt(prefix))) { prefix++; } return prefix; }
[ "private", "static", "int", "prefixLen", "(", "String", "o1", ",", "String", "o2", ")", "{", "final", "int", "l1", "=", "o1", ".", "length", "(", ")", ",", "l2", "=", "o2", ".", "length", "(", ")", ",", "l", "=", "l1", "<", "l2", "?", "l1", ":", "l2", ";", "int", "prefix", "=", "0", ";", "while", "(", "prefix", "<", "l", "&&", "(", "o1", ".", "charAt", "(", "prefix", ")", "==", "o2", ".", "charAt", "(", "prefix", ")", ")", ")", "{", "prefix", "++", ";", "}", "return", "prefix", ";", "}" ]
Compute the length of the prefix. @param o1 First string @param o2 Second string @return Prefix length
[ "Compute", "the", "length", "of", "the", "prefix", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/strings/LevenshteinDistanceFunction.java#L115-L122
apache/flink
flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java
Configuration.updateConnectAddr
public InetSocketAddress updateConnectAddr( String hostProperty, String addressProperty, String defaultAddressValue, InetSocketAddress addr) { """ Set the socket address a client can use to connect for the <code>name</code> property as a <code>host:port</code>. The wildcard address is replaced with the local host's address. If the host and address properties are configured the host component of the address will be combined with the port component of the addr to generate the address. This is to allow optional control over which host name is used in multi-home bind-host cases where a host can have multiple names @param hostProperty the bind-host configuration name @param addressProperty the service address configuration name @param defaultAddressValue the service default address configuration value @param addr InetSocketAddress of the service listener @return InetSocketAddress for clients to connect """ final String host = get(hostProperty); final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue); if (host == null || host.isEmpty() || connectHostPort == null || connectHostPort.isEmpty()) { //not our case, fall back to original logic return updateConnectAddr(addressProperty, addr); } final String connectHost = connectHostPort.split(":")[0]; // Create connect address using client address hostname and server port. return updateConnectAddr(addressProperty, NetUtils.createSocketAddrForHost( connectHost, addr.getPort())); }
java
public InetSocketAddress updateConnectAddr( String hostProperty, String addressProperty, String defaultAddressValue, InetSocketAddress addr) { final String host = get(hostProperty); final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue); if (host == null || host.isEmpty() || connectHostPort == null || connectHostPort.isEmpty()) { //not our case, fall back to original logic return updateConnectAddr(addressProperty, addr); } final String connectHost = connectHostPort.split(":")[0]; // Create connect address using client address hostname and server port. return updateConnectAddr(addressProperty, NetUtils.createSocketAddrForHost( connectHost, addr.getPort())); }
[ "public", "InetSocketAddress", "updateConnectAddr", "(", "String", "hostProperty", ",", "String", "addressProperty", ",", "String", "defaultAddressValue", ",", "InetSocketAddress", "addr", ")", "{", "final", "String", "host", "=", "get", "(", "hostProperty", ")", ";", "final", "String", "connectHostPort", "=", "getTrimmed", "(", "addressProperty", ",", "defaultAddressValue", ")", ";", "if", "(", "host", "==", "null", "||", "host", ".", "isEmpty", "(", ")", "||", "connectHostPort", "==", "null", "||", "connectHostPort", ".", "isEmpty", "(", ")", ")", "{", "//not our case, fall back to original logic", "return", "updateConnectAddr", "(", "addressProperty", ",", "addr", ")", ";", "}", "final", "String", "connectHost", "=", "connectHostPort", ".", "split", "(", "\":\"", ")", "[", "0", "]", ";", "// Create connect address using client address hostname and server port.", "return", "updateConnectAddr", "(", "addressProperty", ",", "NetUtils", ".", "createSocketAddrForHost", "(", "connectHost", ",", "addr", ".", "getPort", "(", ")", ")", ")", ";", "}" ]
Set the socket address a client can use to connect for the <code>name</code> property as a <code>host:port</code>. The wildcard address is replaced with the local host's address. If the host and address properties are configured the host component of the address will be combined with the port component of the addr to generate the address. This is to allow optional control over which host name is used in multi-home bind-host cases where a host can have multiple names @param hostProperty the bind-host configuration name @param addressProperty the service address configuration name @param defaultAddressValue the service default address configuration value @param addr InetSocketAddress of the service listener @return InetSocketAddress for clients to connect
[ "Set", "the", "socket", "address", "a", "client", "can", "use", "to", "connect", "for", "the", "<code", ">", "name<", "/", "code", ">", "property", "as", "a", "<code", ">", "host", ":", "port<", "/", "code", ">", ".", "The", "wildcard", "address", "is", "replaced", "with", "the", "local", "host", "s", "address", ".", "If", "the", "host", "and", "address", "properties", "are", "configured", "the", "host", "component", "of", "the", "address", "will", "be", "combined", "with", "the", "port", "component", "of", "the", "addr", "to", "generate", "the", "address", ".", "This", "is", "to", "allow", "optional", "control", "over", "which", "host", "name", "is", "used", "in", "multi", "-", "home", "bind", "-", "host", "cases", "where", "a", "host", "can", "have", "multiple", "names" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java#L2330-L2348
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_upgrade_history.java
ns_conf_upgrade_history.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ ns_conf_upgrade_history_responses result = (ns_conf_upgrade_history_responses) service.get_payload_formatter().string_to_resource(ns_conf_upgrade_history_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_conf_upgrade_history_response_array); } ns_conf_upgrade_history[] result_ns_conf_upgrade_history = new ns_conf_upgrade_history[result.ns_conf_upgrade_history_response_array.length]; for(int i = 0; i < result.ns_conf_upgrade_history_response_array.length; i++) { result_ns_conf_upgrade_history[i] = result.ns_conf_upgrade_history_response_array[i].ns_conf_upgrade_history[0]; } return result_ns_conf_upgrade_history; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_conf_upgrade_history_responses result = (ns_conf_upgrade_history_responses) service.get_payload_formatter().string_to_resource(ns_conf_upgrade_history_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_conf_upgrade_history_response_array); } ns_conf_upgrade_history[] result_ns_conf_upgrade_history = new ns_conf_upgrade_history[result.ns_conf_upgrade_history_response_array.length]; for(int i = 0; i < result.ns_conf_upgrade_history_response_array.length; i++) { result_ns_conf_upgrade_history[i] = result.ns_conf_upgrade_history_response_array[i].ns_conf_upgrade_history[0]; } return result_ns_conf_upgrade_history; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "ns_conf_upgrade_history_responses", "result", "=", "(", "ns_conf_upgrade_history_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "ns_conf_upgrade_history_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "ns_conf_upgrade_history_response_array", ")", ";", "}", "ns_conf_upgrade_history", "[", "]", "result_ns_conf_upgrade_history", "=", "new", "ns_conf_upgrade_history", "[", "result", ".", "ns_conf_upgrade_history_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "ns_conf_upgrade_history_response_array", ".", "length", ";", "i", "++", ")", "{", "result_ns_conf_upgrade_history", "[", "i", "]", "=", "result", ".", "ns_conf_upgrade_history_response_array", "[", "i", "]", ".", "ns_conf_upgrade_history", "[", "0", "]", ";", "}", "return", "result_ns_conf_upgrade_history", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_upgrade_history.java#L221-L238
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java
FeatureScopes.createDynamicExtensionsScope
protected IScope createDynamicExtensionsScope( EObject featureCall, XExpression firstArgument, LightweightTypeReference firstArgumentType, boolean implicitArgument, IScope parent, IFeatureScopeSession session) { """ Create a scope that contains dynamic extension features, which are features that are contributed by an instance of a type. @param featureCall the feature call that is currently processed by the scoping infrastructure @param firstArgument an optionally available first argument expression. @param firstArgumentType optionally the type of the first argument @param implicitArgument if the argument is an implicit argument or explicitly given (in concrete syntax) @param parent the parent scope. Is never null. @param session the currently known scope session. Is never null. """ return new DynamicExtensionsScope(parent, session, firstArgument, firstArgumentType, implicitArgument, asAbstractFeatureCall(featureCall), operatorMapping); }
java
protected IScope createDynamicExtensionsScope( EObject featureCall, XExpression firstArgument, LightweightTypeReference firstArgumentType, boolean implicitArgument, IScope parent, IFeatureScopeSession session) { return new DynamicExtensionsScope(parent, session, firstArgument, firstArgumentType, implicitArgument, asAbstractFeatureCall(featureCall), operatorMapping); }
[ "protected", "IScope", "createDynamicExtensionsScope", "(", "EObject", "featureCall", ",", "XExpression", "firstArgument", ",", "LightweightTypeReference", "firstArgumentType", ",", "boolean", "implicitArgument", ",", "IScope", "parent", ",", "IFeatureScopeSession", "session", ")", "{", "return", "new", "DynamicExtensionsScope", "(", "parent", ",", "session", ",", "firstArgument", ",", "firstArgumentType", ",", "implicitArgument", ",", "asAbstractFeatureCall", "(", "featureCall", ")", ",", "operatorMapping", ")", ";", "}" ]
Create a scope that contains dynamic extension features, which are features that are contributed by an instance of a type. @param featureCall the feature call that is currently processed by the scoping infrastructure @param firstArgument an optionally available first argument expression. @param firstArgumentType optionally the type of the first argument @param implicitArgument if the argument is an implicit argument or explicitly given (in concrete syntax) @param parent the parent scope. Is never null. @param session the currently known scope session. Is never null.
[ "Create", "a", "scope", "that", "contains", "dynamic", "extension", "features", "which", "are", "features", "that", "are", "contributed", "by", "an", "instance", "of", "a", "type", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/scoping/batch/FeatureScopes.java#L548-L556
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/ForwardRateVolatilitySurfaceCurvature.java
ForwardRateVolatilitySurfaceCurvature.getValues
public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) { """ Calculates the squared curvature of the LIBOR instantaneous variance. @param evaluationTime Time at which the product is evaluated. @param model A model implementing the LIBORModelMonteCarloSimulationModel @return The squared curvature of the LIBOR instantaneous variance (reduced a possible tolerance). The return value is &ge; 0. """ if(evaluationTime > 0) { throw new RuntimeException("Forward start evaluation currently not supported."); } // Fetch the covariance model of the model LIBORCovarianceModel covarianceModel = model.getCovarianceModel(); // We sum over all forward rates int numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps(); // Accumulator RandomVariable integratedLIBORCurvature = new RandomVariableFromDoubleArray(0.0); for(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { // Integrate from 0 up to the fixing of the rate double timeEnd = covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex); int timeEndIndex = covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd); // If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint if(timeEndIndex < 0) { timeEndIndex = -timeEndIndex - 2; } // Sum squared second derivative of the variance for all components at this time step RandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0); for(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) { double timeStep1 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex); double timeStep2 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1); RandomVariable covarianceLeft = covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null); RandomVariable covarianceCenter = covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null); RandomVariable covarianceRight = covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null); // Calculate second derivative RandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft); curvatureSquared = curvatureSquared.div(timeStep1 * timeStep2); // Take square curvatureSquared = curvatureSquared.squared(); // Integrate over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1)); } // Empty intervall - skip if(timeEnd == 0) { continue; } // Average over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd); // Take square root integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt(); // Take max over all forward rates integratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate); } integratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents); return integratedLIBORCurvature.sub(tolerance).floor(0.0); }
java
public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) { if(evaluationTime > 0) { throw new RuntimeException("Forward start evaluation currently not supported."); } // Fetch the covariance model of the model LIBORCovarianceModel covarianceModel = model.getCovarianceModel(); // We sum over all forward rates int numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps(); // Accumulator RandomVariable integratedLIBORCurvature = new RandomVariableFromDoubleArray(0.0); for(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) { // Integrate from 0 up to the fixing of the rate double timeEnd = covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex); int timeEndIndex = covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd); // If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint if(timeEndIndex < 0) { timeEndIndex = -timeEndIndex - 2; } // Sum squared second derivative of the variance for all components at this time step RandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0); for(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) { double timeStep1 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex); double timeStep2 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1); RandomVariable covarianceLeft = covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null); RandomVariable covarianceCenter = covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null); RandomVariable covarianceRight = covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null); // Calculate second derivative RandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft); curvatureSquared = curvatureSquared.div(timeStep1 * timeStep2); // Take square curvatureSquared = curvatureSquared.squared(); // Integrate over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1)); } // Empty intervall - skip if(timeEnd == 0) { continue; } // Average over time integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd); // Take square root integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt(); // Take max over all forward rates integratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate); } integratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents); return integratedLIBORCurvature.sub(tolerance).floor(0.0); }
[ "public", "RandomVariable", "getValues", "(", "double", "evaluationTime", ",", "LIBORMarketModel", "model", ")", "{", "if", "(", "evaluationTime", ">", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"Forward start evaluation currently not supported.\"", ")", ";", "}", "// Fetch the covariance model of the model", "LIBORCovarianceModel", "covarianceModel", "=", "model", ".", "getCovarianceModel", "(", ")", ";", "// We sum over all forward rates", "int", "numberOfComponents", "=", "covarianceModel", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getNumberOfTimeSteps", "(", ")", ";", "// Accumulator", "RandomVariable", "integratedLIBORCurvature", "=", "new", "RandomVariableFromDoubleArray", "(", "0.0", ")", ";", "for", "(", "int", "componentIndex", "=", "0", ";", "componentIndex", "<", "numberOfComponents", ";", "componentIndex", "++", ")", "{", "// Integrate from 0 up to the fixing of the rate", "double", "timeEnd", "=", "covarianceModel", ".", "getLiborPeriodDiscretization", "(", ")", ".", "getTime", "(", "componentIndex", ")", ";", "int", "timeEndIndex", "=", "covarianceModel", ".", "getTimeDiscretization", "(", ")", ".", "getTimeIndex", "(", "timeEnd", ")", ";", "// If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint", "if", "(", "timeEndIndex", "<", "0", ")", "{", "timeEndIndex", "=", "-", "timeEndIndex", "-", "2", ";", "}", "// Sum squared second derivative of the variance for all components at this time step", "RandomVariable", "integratedLIBORCurvatureCurrentRate", "=", "new", "RandomVariableFromDoubleArray", "(", "0.0", ")", ";", "for", "(", "int", "timeIndex", "=", "0", ";", "timeIndex", "<", "timeEndIndex", "-", "2", ";", "timeIndex", "++", ")", "{", "double", "timeStep1", "=", "covarianceModel", ".", "getTimeDiscretization", "(", ")", ".", "getTimeStep", "(", "timeIndex", ")", ";", "double", "timeStep2", "=", "covarianceModel", ".", "getTimeDiscretization", "(", ")", ".", "getTimeStep", "(", "timeIndex", "+", "1", ")", ";", "RandomVariable", "covarianceLeft", "=", "covarianceModel", ".", "getCovariance", "(", "timeIndex", "+", "0", ",", "componentIndex", ",", "componentIndex", ",", "null", ")", ";", "RandomVariable", "covarianceCenter", "=", "covarianceModel", ".", "getCovariance", "(", "timeIndex", "+", "1", ",", "componentIndex", ",", "componentIndex", ",", "null", ")", ";", "RandomVariable", "covarianceRight", "=", "covarianceModel", ".", "getCovariance", "(", "timeIndex", "+", "2", ",", "componentIndex", ",", "componentIndex", ",", "null", ")", ";", "// Calculate second derivative", "RandomVariable", "curvatureSquared", "=", "covarianceRight", ".", "sub", "(", "covarianceCenter", ".", "mult", "(", "2.0", ")", ")", ".", "add", "(", "covarianceLeft", ")", ";", "curvatureSquared", "=", "curvatureSquared", ".", "div", "(", "timeStep1", "*", "timeStep2", ")", ";", "// Take square", "curvatureSquared", "=", "curvatureSquared", ".", "squared", "(", ")", ";", "// Integrate over time", "integratedLIBORCurvatureCurrentRate", "=", "integratedLIBORCurvatureCurrentRate", ".", "add", "(", "curvatureSquared", ".", "mult", "(", "timeStep1", ")", ")", ";", "}", "// Empty intervall - skip", "if", "(", "timeEnd", "==", "0", ")", "{", "continue", ";", "}", "// Average over time", "integratedLIBORCurvatureCurrentRate", "=", "integratedLIBORCurvatureCurrentRate", ".", "div", "(", "timeEnd", ")", ";", "// Take square root", "integratedLIBORCurvatureCurrentRate", "=", "integratedLIBORCurvatureCurrentRate", ".", "sqrt", "(", ")", ";", "// Take max over all forward rates", "integratedLIBORCurvature", "=", "integratedLIBORCurvature", ".", "add", "(", "integratedLIBORCurvatureCurrentRate", ")", ";", "}", "integratedLIBORCurvature", "=", "integratedLIBORCurvature", ".", "div", "(", "numberOfComponents", ")", ";", "return", "integratedLIBORCurvature", ".", "sub", "(", "tolerance", ")", ".", "floor", "(", "0.0", ")", ";", "}" ]
Calculates the squared curvature of the LIBOR instantaneous variance. @param evaluationTime Time at which the product is evaluated. @param model A model implementing the LIBORModelMonteCarloSimulationModel @return The squared curvature of the LIBOR instantaneous variance (reduced a possible tolerance). The return value is &ge; 0.
[ "Calculates", "the", "squared", "curvature", "of", "the", "LIBOR", "instantaneous", "variance", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/ForwardRateVolatilitySurfaceCurvature.java#L117-L179
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.containsOnly
public static boolean containsOnly(final CharSequence cs, final char... valid) { """ <p>Checks if the CharSequence contains only certain characters.</p> <p>A {@code null} CharSequence will return {@code false}. A {@code null} valid character array will return {@code false}. An empty CharSequence (length()=0) always returns {@code true}.</p> <pre> StringUtils.containsOnly(null, *) = false StringUtils.containsOnly(*, null) = false StringUtils.containsOnly("", *) = true StringUtils.containsOnly("ab", '') = false StringUtils.containsOnly("abab", 'abc') = true StringUtils.containsOnly("ab1", 'abc') = false StringUtils.containsOnly("abz", 'abc') = false </pre> @param cs the String to check, may be null @param valid an array of valid chars, may be null @return true if it only contains valid chars and is non-null @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...) """ // All these pre-checks are to maintain API with an older version if (valid == null || cs == null) { return false; } if (cs.length() == 0) { return true; } if (valid.length == 0) { return false; } return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND; }
java
public static boolean containsOnly(final CharSequence cs, final char... valid) { // All these pre-checks are to maintain API with an older version if (valid == null || cs == null) { return false; } if (cs.length() == 0) { return true; } if (valid.length == 0) { return false; } return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND; }
[ "public", "static", "boolean", "containsOnly", "(", "final", "CharSequence", "cs", ",", "final", "char", "...", "valid", ")", "{", "// All these pre-checks are to maintain API with an older version", "if", "(", "valid", "==", "null", "||", "cs", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "cs", ".", "length", "(", ")", "==", "0", ")", "{", "return", "true", ";", "}", "if", "(", "valid", ".", "length", "==", "0", ")", "{", "return", "false", ";", "}", "return", "indexOfAnyBut", "(", "cs", ",", "valid", ")", "==", "INDEX_NOT_FOUND", ";", "}" ]
<p>Checks if the CharSequence contains only certain characters.</p> <p>A {@code null} CharSequence will return {@code false}. A {@code null} valid character array will return {@code false}. An empty CharSequence (length()=0) always returns {@code true}.</p> <pre> StringUtils.containsOnly(null, *) = false StringUtils.containsOnly(*, null) = false StringUtils.containsOnly("", *) = true StringUtils.containsOnly("ab", '') = false StringUtils.containsOnly("abab", 'abc') = true StringUtils.containsOnly("ab1", 'abc') = false StringUtils.containsOnly("abz", 'abc') = false </pre> @param cs the String to check, may be null @param valid an array of valid chars, may be null @return true if it only contains valid chars and is non-null @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...)
[ "<p", ">", "Checks", "if", "the", "CharSequence", "contains", "only", "certain", "characters", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L2383-L2395
datacleaner/AnalyzerBeans
core/src/main/java/org/eobjects/analyzer/beans/transform/AbstractWrappedAnalysisJobTransformer.java
AbstractWrappedAnalysisJobTransformer.reInitialize
protected boolean reInitialize(AnalysisJob wrappedAnalysisJob, List<InputColumn<?>> outputColumns) { """ Determines if the transformer should reinitialize it's {@link ConsumeRowHandler}, output columns etc. based on a set of existing values. The default implementation returns false when non-null values are available @param wrappedAnalysisJob @param outputColumns @return """ if (wrappedAnalysisJob != null && outputColumns != null && !outputColumns.isEmpty()) { return false; } return true; }
java
protected boolean reInitialize(AnalysisJob wrappedAnalysisJob, List<InputColumn<?>> outputColumns) { if (wrappedAnalysisJob != null && outputColumns != null && !outputColumns.isEmpty()) { return false; } return true; }
[ "protected", "boolean", "reInitialize", "(", "AnalysisJob", "wrappedAnalysisJob", ",", "List", "<", "InputColumn", "<", "?", ">", ">", "outputColumns", ")", "{", "if", "(", "wrappedAnalysisJob", "!=", "null", "&&", "outputColumns", "!=", "null", "&&", "!", "outputColumns", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determines if the transformer should reinitialize it's {@link ConsumeRowHandler}, output columns etc. based on a set of existing values. The default implementation returns false when non-null values are available @param wrappedAnalysisJob @param outputColumns @return
[ "Determines", "if", "the", "transformer", "should", "reinitialize", "it", "s", "{", "@link", "ConsumeRowHandler", "}", "output", "columns", "etc", ".", "based", "on", "a", "set", "of", "existing", "values", "." ]
train
https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/core/src/main/java/org/eobjects/analyzer/beans/transform/AbstractWrappedAnalysisJobTransformer.java#L114-L119
foundation-runtime/configuration
configuration-api/src/main/java/com/cisco/oss/foundation/configuration/ConfigUtil.java
ConfigUtil.createCompositeConfiguration
public static Configuration createCompositeConfiguration(final Class<?> clazz, final Configuration configuration) { """ create a composite configuration that wraps the configuration sent by the user. this util will also load the "defaultConfig.properties" file loaded relative to the given "clazz" parameter @param clazz - the class that acts as referenced location of "defaultConfig.properties". @param configuration - the configuration supplied by the user that may override values in "defaultConfig.properties". If null is ignored. @return the created compsite configuration. """ final CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); final Configuration defaultConfiguration = ConfigurationFactory.getDefaultConfiguration(); if (configuration != null) { compositeConfiguration.addConfiguration(configuration); } compositeConfiguration.addConfiguration(defaultConfiguration); return compositeConfiguration; }
java
public static Configuration createCompositeConfiguration(final Class<?> clazz, final Configuration configuration) { final CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); final Configuration defaultConfiguration = ConfigurationFactory.getDefaultConfiguration(); if (configuration != null) { compositeConfiguration.addConfiguration(configuration); } compositeConfiguration.addConfiguration(defaultConfiguration); return compositeConfiguration; }
[ "public", "static", "Configuration", "createCompositeConfiguration", "(", "final", "Class", "<", "?", ">", "clazz", ",", "final", "Configuration", "configuration", ")", "{", "final", "CompositeConfiguration", "compositeConfiguration", "=", "new", "CompositeConfiguration", "(", ")", ";", "final", "Configuration", "defaultConfiguration", "=", "ConfigurationFactory", ".", "getDefaultConfiguration", "(", ")", ";", "if", "(", "configuration", "!=", "null", ")", "{", "compositeConfiguration", ".", "addConfiguration", "(", "configuration", ")", ";", "}", "compositeConfiguration", ".", "addConfiguration", "(", "defaultConfiguration", ")", ";", "return", "compositeConfiguration", ";", "}" ]
create a composite configuration that wraps the configuration sent by the user. this util will also load the "defaultConfig.properties" file loaded relative to the given "clazz" parameter @param clazz - the class that acts as referenced location of "defaultConfig.properties". @param configuration - the configuration supplied by the user that may override values in "defaultConfig.properties". If null is ignored. @return the created compsite configuration.
[ "create", "a", "composite", "configuration", "that", "wraps", "the", "configuration", "sent", "by", "the", "user", ".", "this", "util", "will", "also", "load", "the", "defaultConfig", ".", "properties", "file", "loaded", "relative", "to", "the", "given", "clazz", "parameter" ]
train
https://github.com/foundation-runtime/configuration/blob/c5bd171a2cca0dc1c8d568f987843ca47c6d1eed/configuration-api/src/main/java/com/cisco/oss/foundation/configuration/ConfigUtil.java#L88-L96
h2oai/h2o-3
h2o-core/src/main/java/water/parser/SVMLightParser.java
SVMLightParser.guessSetup
public static ParseSetup guessSetup(byte [] bits) { """ Try to parse the bytes as svm light format, return a ParseSetupHandler with type SVMLight if the input is in svm light format, throw an exception otherwise. """ int lastNewline = bits.length-1; while(lastNewline > 0 && !CsvParser.isEOL(bits[lastNewline]))lastNewline--; if(lastNewline > 0) bits = Arrays.copyOf(bits,lastNewline+1); SVMLightParser p = new SVMLightParser(new ParseSetup(SVMLight_INFO, ParseSetup.GUESS_SEP, false,ParseSetup.GUESS_HEADER,ParseSetup.GUESS_COL_CNT, null,null,null,null,null), null); SVMLightInspectParseWriter dout = new SVMLightInspectParseWriter(); p.parseChunk(0,new ByteAryData(bits,0), dout); if (dout._ncols > 0 && dout._nlines > 0 && dout._nlines > dout._invalidLines) return new ParseSetup(SVMLight_INFO, ParseSetup.GUESS_SEP, false,ParseSetup.NO_HEADER,dout._ncols,null,dout.guessTypes(),null,null,dout._data, dout.removeErrors()); else throw new ParseDataset.H2OParseException("Could not parse file as an SVMLight file."); }
java
public static ParseSetup guessSetup(byte [] bits) { int lastNewline = bits.length-1; while(lastNewline > 0 && !CsvParser.isEOL(bits[lastNewline]))lastNewline--; if(lastNewline > 0) bits = Arrays.copyOf(bits,lastNewline+1); SVMLightParser p = new SVMLightParser(new ParseSetup(SVMLight_INFO, ParseSetup.GUESS_SEP, false,ParseSetup.GUESS_HEADER,ParseSetup.GUESS_COL_CNT, null,null,null,null,null), null); SVMLightInspectParseWriter dout = new SVMLightInspectParseWriter(); p.parseChunk(0,new ByteAryData(bits,0), dout); if (dout._ncols > 0 && dout._nlines > 0 && dout._nlines > dout._invalidLines) return new ParseSetup(SVMLight_INFO, ParseSetup.GUESS_SEP, false,ParseSetup.NO_HEADER,dout._ncols,null,dout.guessTypes(),null,null,dout._data, dout.removeErrors()); else throw new ParseDataset.H2OParseException("Could not parse file as an SVMLight file."); }
[ "public", "static", "ParseSetup", "guessSetup", "(", "byte", "[", "]", "bits", ")", "{", "int", "lastNewline", "=", "bits", ".", "length", "-", "1", ";", "while", "(", "lastNewline", ">", "0", "&&", "!", "CsvParser", ".", "isEOL", "(", "bits", "[", "lastNewline", "]", ")", ")", "lastNewline", "--", ";", "if", "(", "lastNewline", ">", "0", ")", "bits", "=", "Arrays", ".", "copyOf", "(", "bits", ",", "lastNewline", "+", "1", ")", ";", "SVMLightParser", "p", "=", "new", "SVMLightParser", "(", "new", "ParseSetup", "(", "SVMLight_INFO", ",", "ParseSetup", ".", "GUESS_SEP", ",", "false", ",", "ParseSetup", ".", "GUESS_HEADER", ",", "ParseSetup", ".", "GUESS_COL_CNT", ",", "null", ",", "null", ",", "null", ",", "null", ",", "null", ")", ",", "null", ")", ";", "SVMLightInspectParseWriter", "dout", "=", "new", "SVMLightInspectParseWriter", "(", ")", ";", "p", ".", "parseChunk", "(", "0", ",", "new", "ByteAryData", "(", "bits", ",", "0", ")", ",", "dout", ")", ";", "if", "(", "dout", ".", "_ncols", ">", "0", "&&", "dout", ".", "_nlines", ">", "0", "&&", "dout", ".", "_nlines", ">", "dout", ".", "_invalidLines", ")", "return", "new", "ParseSetup", "(", "SVMLight_INFO", ",", "ParseSetup", ".", "GUESS_SEP", ",", "false", ",", "ParseSetup", ".", "NO_HEADER", ",", "dout", ".", "_ncols", ",", "null", ",", "dout", ".", "guessTypes", "(", ")", ",", "null", ",", "null", ",", "dout", ".", "_data", ",", "dout", ".", "removeErrors", "(", ")", ")", ";", "else", "throw", "new", "ParseDataset", ".", "H2OParseException", "(", "\"Could not parse file as an SVMLight file.\"", ")", ";", "}" ]
Try to parse the bytes as svm light format, return a ParseSetupHandler with type SVMLight if the input is in svm light format, throw an exception otherwise.
[ "Try", "to", "parse", "the", "bytes", "as", "svm", "light", "format", "return", "a", "ParseSetupHandler", "with", "type", "SVMLight", "if", "the", "input", "is", "in", "svm", "light", "format", "throw", "an", "exception", "otherwise", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/parser/SVMLightParser.java#L27-L40
belaban/JGroups
src/org/jgroups/jmx/ResourceDMBean.java
ResourceDMBean.findSetter
public static Accessor findSetter(Object target, String attr_name) { """ Finds an accessor for an attribute. Tries to find setAttrName(), attrName() methods. If not found, tries to use reflection to set the value of attr_name. If still not found, creates a NullAccessor. """ final String name=Util.attributeNameToMethodName(attr_name); final String fluent_name=toLowerCase(name); Class<?> clazz=target.getClass(); Class<?> field_type=null; Field field=Util.getField(clazz, attr_name); field_type=field != null? field.getType() : null; String setter_name="set" + name; if(field_type != null) { Method method=Util.findMethod(target, Arrays.asList(fluent_name, setter_name), field_type); if(method != null && isSetMethod(method)) return new MethodAccessor(method, target); } // Find all methods but don't include methods from Object class List<Method> methods=new ArrayList<>(Arrays.asList(clazz.getMethods())); methods.removeAll(OBJECT_METHODS); for(Method method: methods) { String method_name=method.getName(); if((method_name.equals(name) || method_name.equals(fluent_name) || method_name.equals(setter_name)) && isSetMethod(method)) return new MethodAccessor(method, target); } // Find a field last_name if(field != null) return new FieldAccessor(field, target); return null; }
java
public static Accessor findSetter(Object target, String attr_name) { final String name=Util.attributeNameToMethodName(attr_name); final String fluent_name=toLowerCase(name); Class<?> clazz=target.getClass(); Class<?> field_type=null; Field field=Util.getField(clazz, attr_name); field_type=field != null? field.getType() : null; String setter_name="set" + name; if(field_type != null) { Method method=Util.findMethod(target, Arrays.asList(fluent_name, setter_name), field_type); if(method != null && isSetMethod(method)) return new MethodAccessor(method, target); } // Find all methods but don't include methods from Object class List<Method> methods=new ArrayList<>(Arrays.asList(clazz.getMethods())); methods.removeAll(OBJECT_METHODS); for(Method method: methods) { String method_name=method.getName(); if((method_name.equals(name) || method_name.equals(fluent_name) || method_name.equals(setter_name)) && isSetMethod(method)) return new MethodAccessor(method, target); } // Find a field last_name if(field != null) return new FieldAccessor(field, target); return null; }
[ "public", "static", "Accessor", "findSetter", "(", "Object", "target", ",", "String", "attr_name", ")", "{", "final", "String", "name", "=", "Util", ".", "attributeNameToMethodName", "(", "attr_name", ")", ";", "final", "String", "fluent_name", "=", "toLowerCase", "(", "name", ")", ";", "Class", "<", "?", ">", "clazz", "=", "target", ".", "getClass", "(", ")", ";", "Class", "<", "?", ">", "field_type", "=", "null", ";", "Field", "field", "=", "Util", ".", "getField", "(", "clazz", ",", "attr_name", ")", ";", "field_type", "=", "field", "!=", "null", "?", "field", ".", "getType", "(", ")", ":", "null", ";", "String", "setter_name", "=", "\"set\"", "+", "name", ";", "if", "(", "field_type", "!=", "null", ")", "{", "Method", "method", "=", "Util", ".", "findMethod", "(", "target", ",", "Arrays", ".", "asList", "(", "fluent_name", ",", "setter_name", ")", ",", "field_type", ")", ";", "if", "(", "method", "!=", "null", "&&", "isSetMethod", "(", "method", ")", ")", "return", "new", "MethodAccessor", "(", "method", ",", "target", ")", ";", "}", "// Find all methods but don't include methods from Object class", "List", "<", "Method", ">", "methods", "=", "new", "ArrayList", "<>", "(", "Arrays", ".", "asList", "(", "clazz", ".", "getMethods", "(", ")", ")", ")", ";", "methods", ".", "removeAll", "(", "OBJECT_METHODS", ")", ";", "for", "(", "Method", "method", ":", "methods", ")", "{", "String", "method_name", "=", "method", ".", "getName", "(", ")", ";", "if", "(", "(", "method_name", ".", "equals", "(", "name", ")", "||", "method_name", ".", "equals", "(", "fluent_name", ")", "||", "method_name", ".", "equals", "(", "setter_name", ")", ")", "&&", "isSetMethod", "(", "method", ")", ")", "return", "new", "MethodAccessor", "(", "method", ",", "target", ")", ";", "}", "// Find a field last_name", "if", "(", "field", "!=", "null", ")", "return", "new", "FieldAccessor", "(", "field", ",", "target", ")", ";", "return", "null", ";", "}" ]
Finds an accessor for an attribute. Tries to find setAttrName(), attrName() methods. If not found, tries to use reflection to set the value of attr_name. If still not found, creates a NullAccessor.
[ "Finds", "an", "accessor", "for", "an", "attribute", ".", "Tries", "to", "find", "setAttrName", "()", "attrName", "()", "methods", ".", "If", "not", "found", "tries", "to", "use", "reflection", "to", "set", "the", "value", "of", "attr_name", ".", "If", "still", "not", "found", "creates", "a", "NullAccessor", "." ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/jmx/ResourceDMBean.java#L353-L383
srikalyc/Sql4D
Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/Joiner4Bean.java
Joiner4Bean.mapPkToRow
private Tuple2<Object, T> mapPkToRow(String timestamp, JSONObject jsonRow, List<String> joinFields) { """ Extract fields(k,v) from json k = primary field(s), i.e could be composite key as well. v = all fields . The first field is always timestamp. @param timestamp @param jsonRow @param joinFields @return """ Object joinValue = null; T rowValues = null; try { rowValues = rowMapper.newInstance(); rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp); for (Object key : jsonRow.keySet()) { String colValue = key.toString(); Util.applyKVToBean(rowValues, colValue, jsonRow.get(colValue)); if (joinFields.contains(colValue)) { joinValue = (joinValue == null)?jsonRow.get(colValue):(joinValue + "\u0001" + jsonRow.get(colValue)); } } if (joinFields.contains("timestamp")) {// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way) joinValue = (joinValue == null)?timestamp:(joinValue + "\u0001" + timestamp); } } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(Joiner4Bean.class.getName()).log(Level.SEVERE, null, ex); } return new Tuple2<>(joinValue, rowValues); }
java
private Tuple2<Object, T> mapPkToRow(String timestamp, JSONObject jsonRow, List<String> joinFields) { Object joinValue = null; T rowValues = null; try { rowValues = rowMapper.newInstance(); rowValues.getClass().getMethod("setTimestamp", String.class).invoke(rowValues, timestamp); for (Object key : jsonRow.keySet()) { String colValue = key.toString(); Util.applyKVToBean(rowValues, colValue, jsonRow.get(colValue)); if (joinFields.contains(colValue)) { joinValue = (joinValue == null)?jsonRow.get(colValue):(joinValue + "\u0001" + jsonRow.get(colValue)); } } if (joinFields.contains("timestamp")) {// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way) joinValue = (joinValue == null)?timestamp:(joinValue + "\u0001" + timestamp); } } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(Joiner4Bean.class.getName()).log(Level.SEVERE, null, ex); } return new Tuple2<>(joinValue, rowValues); }
[ "private", "Tuple2", "<", "Object", ",", "T", ">", "mapPkToRow", "(", "String", "timestamp", ",", "JSONObject", "jsonRow", ",", "List", "<", "String", ">", "joinFields", ")", "{", "Object", "joinValue", "=", "null", ";", "T", "rowValues", "=", "null", ";", "try", "{", "rowValues", "=", "rowMapper", ".", "newInstance", "(", ")", ";", "rowValues", ".", "getClass", "(", ")", ".", "getMethod", "(", "\"setTimestamp\"", ",", "String", ".", "class", ")", ".", "invoke", "(", "rowValues", ",", "timestamp", ")", ";", "for", "(", "Object", "key", ":", "jsonRow", ".", "keySet", "(", ")", ")", "{", "String", "colValue", "=", "key", ".", "toString", "(", ")", ";", "Util", ".", "applyKVToBean", "(", "rowValues", ",", "colValue", ",", "jsonRow", ".", "get", "(", "colValue", ")", ")", ";", "if", "(", "joinFields", ".", "contains", "(", "colValue", ")", ")", "{", "joinValue", "=", "(", "joinValue", "==", "null", ")", "?", "jsonRow", ".", "get", "(", "colValue", ")", ":", "(", "joinValue", "+", "\"\\u0001\"", "+", "jsonRow", ".", "get", "(", "colValue", ")", ")", ";", "}", "}", "if", "(", "joinFields", ".", "contains", "(", "\"timestamp\"", ")", ")", "{", "// Join field could contain timestamp(timestamp can be out of the actual data JSON, so we try this way)", "joinValue", "=", "(", "joinValue", "==", "null", ")", "?", "timestamp", ":", "(", "joinValue", "+", "\"\\u0001\"", "+", "timestamp", ")", ";", "}", "}", "catch", "(", "InstantiationException", "|", "IllegalAccessException", "|", "NoSuchMethodException", "|", "SecurityException", "|", "IllegalArgumentException", "|", "InvocationTargetException", "ex", ")", "{", "Logger", ".", "getLogger", "(", "Joiner4Bean", ".", "class", ".", "getName", "(", ")", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "null", ",", "ex", ")", ";", "}", "return", "new", "Tuple2", "<>", "(", "joinValue", ",", "rowValues", ")", ";", "}" ]
Extract fields(k,v) from json k = primary field(s), i.e could be composite key as well. v = all fields . The first field is always timestamp. @param timestamp @param jsonRow @param joinFields @return
[ "Extract", "fields", "(", "k", "v", ")", "from", "json", "k", "=", "primary", "field", "(", "s", ")", "i", ".", "e", "could", "be", "composite", "key", "as", "well", ".", "v", "=", "all", "fields", ".", "The", "first", "field", "is", "always", "timestamp", "." ]
train
https://github.com/srikalyc/Sql4D/blob/2c052fe60ead5a16277c798a3440de7d4f6f24f6/Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/Joiner4Bean.java#L112-L132
bmwcarit/joynr
java/core/libjoynr/src/main/java/io/joynr/runtime/JoynrRuntimeImpl.java
JoynrRuntimeImpl.registerProvider
@Override public Future<Void> registerProvider(String domain, Object provider, ProviderQos providerQos) { """ Registers a provider in the joynr framework @param domain The domain the provider should be registered for. Has to be identical at the client to be able to find the provider. @param provider Instance of the provider implementation (has to extend a generated ...AbstractProvider). @param providerQos the provider's quality of service settings @return Returns a Future which can be used to check the registration status. """ final boolean awaitGlobalRegistration = false; return registerProvider(domain, provider, providerQos, awaitGlobalRegistration); }
java
@Override public Future<Void> registerProvider(String domain, Object provider, ProviderQos providerQos) { final boolean awaitGlobalRegistration = false; return registerProvider(domain, provider, providerQos, awaitGlobalRegistration); }
[ "@", "Override", "public", "Future", "<", "Void", ">", "registerProvider", "(", "String", "domain", ",", "Object", "provider", ",", "ProviderQos", "providerQos", ")", "{", "final", "boolean", "awaitGlobalRegistration", "=", "false", ";", "return", "registerProvider", "(", "domain", ",", "provider", ",", "providerQos", ",", "awaitGlobalRegistration", ")", ";", "}" ]
Registers a provider in the joynr framework @param domain The domain the provider should be registered for. Has to be identical at the client to be able to find the provider. @param provider Instance of the provider implementation (has to extend a generated ...AbstractProvider). @param providerQos the provider's quality of service settings @return Returns a Future which can be used to check the registration status.
[ "Registers", "a", "provider", "in", "the", "joynr", "framework" ]
train
https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/core/libjoynr/src/main/java/io/joynr/runtime/JoynrRuntimeImpl.java#L160-L164
brianwhu/xillium
data/src/main/java/org/xillium/data/validation/Validator.java
Validator.preValidate
public void preValidate(String text) throws DataValidationException { """ Performs all data validation that is based on the string representation of the value before it is converted. @param text - the string representation of the data value @throws DataValidationException if any of the data constraints are violated """ // size Trace.g.std.note(Validator.class, "preValidate: size = " + _size); if (_size > 0 && text.length() > _size) { throw new DataValidationException("SIZE", _name, text); } // pattern Trace.g.std.note(Validator.class, "preValidate: pattern = " + _pattern); if (_pattern != null && !_pattern.matcher(text).matches()) { throw new DataValidationException("PATTERN", _name, text); } }
java
public void preValidate(String text) throws DataValidationException { // size Trace.g.std.note(Validator.class, "preValidate: size = " + _size); if (_size > 0 && text.length() > _size) { throw new DataValidationException("SIZE", _name, text); } // pattern Trace.g.std.note(Validator.class, "preValidate: pattern = " + _pattern); if (_pattern != null && !_pattern.matcher(text).matches()) { throw new DataValidationException("PATTERN", _name, text); } }
[ "public", "void", "preValidate", "(", "String", "text", ")", "throws", "DataValidationException", "{", "// size\r", "Trace", ".", "g", ".", "std", ".", "note", "(", "Validator", ".", "class", ",", "\"preValidate: size = \"", "+", "_size", ")", ";", "if", "(", "_size", ">", "0", "&&", "text", ".", "length", "(", ")", ">", "_size", ")", "{", "throw", "new", "DataValidationException", "(", "\"SIZE\"", ",", "_name", ",", "text", ")", ";", "}", "// pattern\r", "Trace", ".", "g", ".", "std", ".", "note", "(", "Validator", ".", "class", ",", "\"preValidate: pattern = \"", "+", "_pattern", ")", ";", "if", "(", "_pattern", "!=", "null", "&&", "!", "_pattern", ".", "matcher", "(", "text", ")", ".", "matches", "(", ")", ")", "{", "throw", "new", "DataValidationException", "(", "\"PATTERN\"", ",", "_name", ",", "text", ")", ";", "}", "}" ]
Performs all data validation that is based on the string representation of the value before it is converted. @param text - the string representation of the data value @throws DataValidationException if any of the data constraints are violated
[ "Performs", "all", "data", "validation", "that", "is", "based", "on", "the", "string", "representation", "of", "the", "value", "before", "it", "is", "converted", "." ]
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/data/src/main/java/org/xillium/data/validation/Validator.java#L117-L129
box/box-java-sdk
src/main/java/com/box/sdk/BoxFile.java
BoxFile.uploadVersion
@Deprecated public void uploadVersion(InputStream fileContent, String fileContentSHA1) { """ Uploads a new version of this file, replacing the current version. Note that only users with premium accounts will be able to view and recover previous versions of the file. @param fileContent a stream containing the new file contents. @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. @deprecated use uploadNewVersion() instead. """ this.uploadVersion(fileContent, fileContentSHA1, null); }
java
@Deprecated public void uploadVersion(InputStream fileContent, String fileContentSHA1) { this.uploadVersion(fileContent, fileContentSHA1, null); }
[ "@", "Deprecated", "public", "void", "uploadVersion", "(", "InputStream", "fileContent", ",", "String", "fileContentSHA1", ")", "{", "this", ".", "uploadVersion", "(", "fileContent", ",", "fileContentSHA1", ",", "null", ")", ";", "}" ]
Uploads a new version of this file, replacing the current version. Note that only users with premium accounts will be able to view and recover previous versions of the file. @param fileContent a stream containing the new file contents. @param fileContentSHA1 a string containing the SHA1 hash of the new file contents. @deprecated use uploadNewVersion() instead.
[ "Uploads", "a", "new", "version", "of", "this", "file", "replacing", "the", "current", "version", ".", "Note", "that", "only", "users", "with", "premium", "accounts", "will", "be", "able", "to", "view", "and", "recover", "previous", "versions", "of", "the", "file", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFile.java#L737-L740
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/Parameters.java
Parameters.setString
@NonNull public Parameters setString(@NonNull String name, String value) { """ Set an String value to the query parameter referenced by the given name. A query parameter is defined by using the Expression's parameter(String name) function. @param name The parameter name. @param value The String value. @return The self object. """ return setValue(name, value); }
java
@NonNull public Parameters setString(@NonNull String name, String value) { return setValue(name, value); }
[ "@", "NonNull", "public", "Parameters", "setString", "(", "@", "NonNull", "String", "name", ",", "String", "value", ")", "{", "return", "setValue", "(", "name", ",", "value", ")", ";", "}" ]
Set an String value to the query parameter referenced by the given name. A query parameter is defined by using the Expression's parameter(String name) function. @param name The parameter name. @param value The String value. @return The self object.
[ "Set", "an", "String", "value", "to", "the", "query", "parameter", "referenced", "by", "the", "given", "name", ".", "A", "query", "parameter", "is", "defined", "by", "using", "the", "Expression", "s", "parameter", "(", "String", "name", ")", "function", "." ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/Parameters.java#L79-L82
facebookarchive/hadoop-20
src/core/org/apache/hadoop/raid/GaloisField.java
GaloisField.getInstance
public static GaloisField getInstance(int fieldSize, int primitivePolynomial) { """ Get the object performs Galois field arithmetics @param fieldSize size of the field @param primitivePolynomial a primitive polynomial corresponds to the size """ int key = ((fieldSize << 16) & 0xFFFF0000) + (primitivePolynomial & 0x0000FFFF); GaloisField gf; synchronized (instances) { gf = instances.get(key); if (gf == null) { gf = new GaloisField(fieldSize, primitivePolynomial); instances.put(key, gf); } } return gf; }
java
public static GaloisField getInstance(int fieldSize, int primitivePolynomial) { int key = ((fieldSize << 16) & 0xFFFF0000) + (primitivePolynomial & 0x0000FFFF); GaloisField gf; synchronized (instances) { gf = instances.get(key); if (gf == null) { gf = new GaloisField(fieldSize, primitivePolynomial); instances.put(key, gf); } } return gf; }
[ "public", "static", "GaloisField", "getInstance", "(", "int", "fieldSize", ",", "int", "primitivePolynomial", ")", "{", "int", "key", "=", "(", "(", "fieldSize", "<<", "16", ")", "&", "0xFFFF0000", ")", "+", "(", "primitivePolynomial", "&", "0x0000FFFF", ")", ";", "GaloisField", "gf", ";", "synchronized", "(", "instances", ")", "{", "gf", "=", "instances", ".", "get", "(", "key", ")", ";", "if", "(", "gf", "==", "null", ")", "{", "gf", "=", "new", "GaloisField", "(", "fieldSize", ",", "primitivePolynomial", ")", ";", "instances", ".", "put", "(", "key", ",", "gf", ")", ";", "}", "}", "return", "gf", ";", "}" ]
Get the object performs Galois field arithmetics @param fieldSize size of the field @param primitivePolynomial a primitive polynomial corresponds to the size
[ "Get", "the", "object", "performs", "Galois", "field", "arithmetics" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/raid/GaloisField.java#L51-L63
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java
ArrayFunctions.arrayConcat
public static Expression arrayConcat(JsonArray array1, JsonArray array2) { """ Returned expression results in new array with the concatenation of the input arrays. """ return arrayConcat(x(array1), x(array2)); }
java
public static Expression arrayConcat(JsonArray array1, JsonArray array2) { return arrayConcat(x(array1), x(array2)); }
[ "public", "static", "Expression", "arrayConcat", "(", "JsonArray", "array1", ",", "JsonArray", "array2", ")", "{", "return", "arrayConcat", "(", "x", "(", "array1", ")", ",", "x", "(", "array2", ")", ")", ";", "}" ]
Returned expression results in new array with the concatenation of the input arrays.
[ "Returned", "expression", "results", "in", "new", "array", "with", "the", "concatenation", "of", "the", "input", "arrays", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L104-L106
cdk/cdk
misc/extra/src/main/java/org/openscience/cdk/tools/GridGenerator.java
GridGenerator.setDimension
public void setDimension(double minx, double maxx, double miny, double maxy, double minz, double maxz) { """ Method sets the maximal 3d dimensions to given min and max values. """ this.minx = minx; this.maxx = maxx; this.miny = miny; this.maxy = maxy; this.minz = minz; this.maxz = maxz; }
java
public void setDimension(double minx, double maxx, double miny, double maxy, double minz, double maxz) { this.minx = minx; this.maxx = maxx; this.miny = miny; this.maxy = maxy; this.minz = minz; this.maxz = maxz; }
[ "public", "void", "setDimension", "(", "double", "minx", ",", "double", "maxx", ",", "double", "miny", ",", "double", "maxy", ",", "double", "minz", ",", "double", "maxz", ")", "{", "this", ".", "minx", "=", "minx", ";", "this", ".", "maxx", "=", "maxx", ";", "this", ".", "miny", "=", "miny", ";", "this", ".", "maxy", "=", "maxy", ";", "this", ".", "minz", "=", "minz", ";", "this", ".", "maxz", "=", "maxz", ";", "}" ]
Method sets the maximal 3d dimensions to given min and max values.
[ "Method", "sets", "the", "maximal", "3d", "dimensions", "to", "given", "min", "and", "max", "values", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/misc/extra/src/main/java/org/openscience/cdk/tools/GridGenerator.java#L111-L118
fnklabs/draenei
src/main/java/com/fnklabs/draenei/CassandraClient.java
CassandraClient.executeAsync
@NotNull public ResultSetFuture executeAsync(@NotNull String keyspace, @NotNull Statement statement) { """ Execute statement asynchronously @param statement Statement that must be executed @return ResultSetFuture """ Timer time = getMetricsFactory().getTimer(MetricsType.CASSANDRA_EXECUTE_ASYNC.name()); getMetricsFactory().getCounter(MetricsType.CASSANDRA_PROCESSING_QUERIES.name()).inc(); ResultSetFuture resultSetFuture = getOrCreateSession(keyspace).executeAsync(statement); String query = (statement instanceof BoundStatement) ? ((BoundStatement) statement).preparedStatement().getQueryString() : statement.toString(); Futures.addCallback(resultSetFuture, new StatementExecutionCallback(keyspace, query)); monitorFuture(time, resultSetFuture); return resultSetFuture; }
java
@NotNull public ResultSetFuture executeAsync(@NotNull String keyspace, @NotNull Statement statement) { Timer time = getMetricsFactory().getTimer(MetricsType.CASSANDRA_EXECUTE_ASYNC.name()); getMetricsFactory().getCounter(MetricsType.CASSANDRA_PROCESSING_QUERIES.name()).inc(); ResultSetFuture resultSetFuture = getOrCreateSession(keyspace).executeAsync(statement); String query = (statement instanceof BoundStatement) ? ((BoundStatement) statement).preparedStatement().getQueryString() : statement.toString(); Futures.addCallback(resultSetFuture, new StatementExecutionCallback(keyspace, query)); monitorFuture(time, resultSetFuture); return resultSetFuture; }
[ "@", "NotNull", "public", "ResultSetFuture", "executeAsync", "(", "@", "NotNull", "String", "keyspace", ",", "@", "NotNull", "Statement", "statement", ")", "{", "Timer", "time", "=", "getMetricsFactory", "(", ")", ".", "getTimer", "(", "MetricsType", ".", "CASSANDRA_EXECUTE_ASYNC", ".", "name", "(", ")", ")", ";", "getMetricsFactory", "(", ")", ".", "getCounter", "(", "MetricsType", ".", "CASSANDRA_PROCESSING_QUERIES", ".", "name", "(", ")", ")", ".", "inc", "(", ")", ";", "ResultSetFuture", "resultSetFuture", "=", "getOrCreateSession", "(", "keyspace", ")", ".", "executeAsync", "(", "statement", ")", ";", "String", "query", "=", "(", "statement", "instanceof", "BoundStatement", ")", "?", "(", "(", "BoundStatement", ")", "statement", ")", ".", "preparedStatement", "(", ")", ".", "getQueryString", "(", ")", ":", "statement", ".", "toString", "(", ")", ";", "Futures", ".", "addCallback", "(", "resultSetFuture", ",", "new", "StatementExecutionCallback", "(", "keyspace", ",", "query", ")", ")", ";", "monitorFuture", "(", "time", ",", "resultSetFuture", ")", ";", "return", "resultSetFuture", ";", "}" ]
Execute statement asynchronously @param statement Statement that must be executed @return ResultSetFuture
[ "Execute", "statement", "asynchronously" ]
train
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/CassandraClient.java#L240-L254
mabe02/lanterna
src/main/java/com/googlecode/lanterna/terminal/swing/GraphicalTerminalImplementation.java
GraphicalTerminalImplementation.paintComponent
synchronized void paintComponent(Graphics componentGraphics) { """ Updates the back buffer (if necessary) and draws it to the component's surface @param componentGraphics Object to use when drawing to the component's surface """ int width = getWidth(); int height = getHeight(); this.scrollController.updateModel( virtualTerminal.getBufferLineCount() * getFontHeight(), height); boolean needToUpdateBackBuffer = // User has used the scrollbar, we need to update the back buffer to reflect this lastBufferUpdateScrollPosition != scrollController.getScrollingOffset() || // There is blinking text to update hasBlinkingText || // We simply have a hint that we should update everything needFullRedraw; // Detect resize if(width != lastComponentWidth || height != lastComponentHeight) { int columns = width / getFontWidth(); int rows = height / getFontHeight(); TerminalSize terminalSize = virtualTerminal.getTerminalSize().withColumns(columns).withRows(rows); virtualTerminal.setTerminalSize(terminalSize); // Back buffer needs to be updated since the component size has changed needToUpdateBackBuffer = true; } if(needToUpdateBackBuffer) { updateBackBuffer(scrollController.getScrollingOffset()); } ensureGraphicBufferHasRightSize(); Rectangle clipBounds = componentGraphics.getClipBounds(); if(clipBounds == null) { clipBounds = new Rectangle(0, 0, getWidth(), getHeight()); } componentGraphics.drawImage( backbuffer, // Destination coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, // Source coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, null); // Take care of the left-over area at the bottom and right of the component where no character can fit //int leftoverHeight = getHeight() % getFontHeight(); int leftoverWidth = getWidth() % getFontWidth(); componentGraphics.setColor(Color.BLACK); if(leftoverWidth > 0) { componentGraphics.fillRect(getWidth() - leftoverWidth, 0, leftoverWidth, getHeight()); } //0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(), null); this.lastComponentWidth = width; this.lastComponentHeight = height; componentGraphics.dispose(); notifyAll(); }
java
synchronized void paintComponent(Graphics componentGraphics) { int width = getWidth(); int height = getHeight(); this.scrollController.updateModel( virtualTerminal.getBufferLineCount() * getFontHeight(), height); boolean needToUpdateBackBuffer = // User has used the scrollbar, we need to update the back buffer to reflect this lastBufferUpdateScrollPosition != scrollController.getScrollingOffset() || // There is blinking text to update hasBlinkingText || // We simply have a hint that we should update everything needFullRedraw; // Detect resize if(width != lastComponentWidth || height != lastComponentHeight) { int columns = width / getFontWidth(); int rows = height / getFontHeight(); TerminalSize terminalSize = virtualTerminal.getTerminalSize().withColumns(columns).withRows(rows); virtualTerminal.setTerminalSize(terminalSize); // Back buffer needs to be updated since the component size has changed needToUpdateBackBuffer = true; } if(needToUpdateBackBuffer) { updateBackBuffer(scrollController.getScrollingOffset()); } ensureGraphicBufferHasRightSize(); Rectangle clipBounds = componentGraphics.getClipBounds(); if(clipBounds == null) { clipBounds = new Rectangle(0, 0, getWidth(), getHeight()); } componentGraphics.drawImage( backbuffer, // Destination coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, // Source coordinates clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height, null); // Take care of the left-over area at the bottom and right of the component where no character can fit //int leftoverHeight = getHeight() % getFontHeight(); int leftoverWidth = getWidth() % getFontWidth(); componentGraphics.setColor(Color.BLACK); if(leftoverWidth > 0) { componentGraphics.fillRect(getWidth() - leftoverWidth, 0, leftoverWidth, getHeight()); } //0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(), null); this.lastComponentWidth = width; this.lastComponentHeight = height; componentGraphics.dispose(); notifyAll(); }
[ "synchronized", "void", "paintComponent", "(", "Graphics", "componentGraphics", ")", "{", "int", "width", "=", "getWidth", "(", ")", ";", "int", "height", "=", "getHeight", "(", ")", ";", "this", ".", "scrollController", ".", "updateModel", "(", "virtualTerminal", ".", "getBufferLineCount", "(", ")", "*", "getFontHeight", "(", ")", ",", "height", ")", ";", "boolean", "needToUpdateBackBuffer", "=", "// User has used the scrollbar, we need to update the back buffer to reflect this", "lastBufferUpdateScrollPosition", "!=", "scrollController", ".", "getScrollingOffset", "(", ")", "||", "// There is blinking text to update", "hasBlinkingText", "||", "// We simply have a hint that we should update everything", "needFullRedraw", ";", "// Detect resize", "if", "(", "width", "!=", "lastComponentWidth", "||", "height", "!=", "lastComponentHeight", ")", "{", "int", "columns", "=", "width", "/", "getFontWidth", "(", ")", ";", "int", "rows", "=", "height", "/", "getFontHeight", "(", ")", ";", "TerminalSize", "terminalSize", "=", "virtualTerminal", ".", "getTerminalSize", "(", ")", ".", "withColumns", "(", "columns", ")", ".", "withRows", "(", "rows", ")", ";", "virtualTerminal", ".", "setTerminalSize", "(", "terminalSize", ")", ";", "// Back buffer needs to be updated since the component size has changed", "needToUpdateBackBuffer", "=", "true", ";", "}", "if", "(", "needToUpdateBackBuffer", ")", "{", "updateBackBuffer", "(", "scrollController", ".", "getScrollingOffset", "(", ")", ")", ";", "}", "ensureGraphicBufferHasRightSize", "(", ")", ";", "Rectangle", "clipBounds", "=", "componentGraphics", ".", "getClipBounds", "(", ")", ";", "if", "(", "clipBounds", "==", "null", ")", "{", "clipBounds", "=", "new", "Rectangle", "(", "0", ",", "0", ",", "getWidth", "(", ")", ",", "getHeight", "(", ")", ")", ";", "}", "componentGraphics", ".", "drawImage", "(", "backbuffer", ",", "// Destination coordinates", "clipBounds", ".", "x", ",", "clipBounds", ".", "y", ",", "clipBounds", ".", "width", ",", "clipBounds", ".", "height", ",", "// Source coordinates", "clipBounds", ".", "x", ",", "clipBounds", ".", "y", ",", "clipBounds", ".", "width", ",", "clipBounds", ".", "height", ",", "null", ")", ";", "// Take care of the left-over area at the bottom and right of the component where no character can fit", "//int leftoverHeight = getHeight() % getFontHeight();", "int", "leftoverWidth", "=", "getWidth", "(", ")", "%", "getFontWidth", "(", ")", ";", "componentGraphics", ".", "setColor", "(", "Color", ".", "BLACK", ")", ";", "if", "(", "leftoverWidth", ">", "0", ")", "{", "componentGraphics", ".", "fillRect", "(", "getWidth", "(", ")", "-", "leftoverWidth", ",", "0", ",", "leftoverWidth", ",", "getHeight", "(", ")", ")", ";", "}", "//0, 0, getWidth(), getHeight(), 0, 0, getWidth(), getHeight(), null);", "this", ".", "lastComponentWidth", "=", "width", ";", "this", ".", "lastComponentHeight", "=", "height", ";", "componentGraphics", ".", "dispose", "(", ")", ";", "notifyAll", "(", ")", ";", "}" ]
Updates the back buffer (if necessary) and draws it to the component's surface @param componentGraphics Object to use when drawing to the component's surface
[ "Updates", "the", "back", "buffer", "(", "if", "necessary", ")", "and", "draws", "it", "to", "the", "component", "s", "surface" ]
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/terminal/swing/GraphicalTerminalImplementation.java#L247-L310
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.setOrtho
public Matrix4d setOrtho(double left, double right, double bottom, double top, double zNear, double zFar, boolean zZeroToOne) { """ Set this matrix to be an orthographic projection transformation for a right-handed coordinate system using the given NDC z range. <p> In order to apply the orthographic projection to an already existing transformation, use {@link #ortho(double, double, double, double, double, double, boolean) ortho()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #ortho(double, double, double, double, double, double, boolean) @param left the distance from the center to the left frustum edge @param right the distance from the center to the right frustum edge @param bottom the distance from the center to the bottom frustum edge @param top the distance from the center to the top frustum edge @param zNear near clipping plane distance @param zFar far clipping plane distance @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return this """ if ((properties & PROPERTY_IDENTITY) == 0) _identity(); m00 = 2.0 / (right - left); m11 = 2.0 / (top - bottom); m22 = (zZeroToOne ? 1.0 : 2.0) / (zNear - zFar); m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); properties = PROPERTY_AFFINE; return this; }
java
public Matrix4d setOrtho(double left, double right, double bottom, double top, double zNear, double zFar, boolean zZeroToOne) { if ((properties & PROPERTY_IDENTITY) == 0) _identity(); m00 = 2.0 / (right - left); m11 = 2.0 / (top - bottom); m22 = (zZeroToOne ? 1.0 : 2.0) / (zNear - zFar); m30 = (right + left) / (left - right); m31 = (top + bottom) / (bottom - top); m32 = (zZeroToOne ? zNear : (zFar + zNear)) / (zNear - zFar); properties = PROPERTY_AFFINE; return this; }
[ "public", "Matrix4d", "setOrtho", "(", "double", "left", ",", "double", "right", ",", "double", "bottom", ",", "double", "top", ",", "double", "zNear", ",", "double", "zFar", ",", "boolean", "zZeroToOne", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "==", "0", ")", "_identity", "(", ")", ";", "m00", "=", "2.0", "/", "(", "right", "-", "left", ")", ";", "m11", "=", "2.0", "/", "(", "top", "-", "bottom", ")", ";", "m22", "=", "(", "zZeroToOne", "?", "1.0", ":", "2.0", ")", "/", "(", "zNear", "-", "zFar", ")", ";", "m30", "=", "(", "right", "+", "left", ")", "/", "(", "left", "-", "right", ")", ";", "m31", "=", "(", "top", "+", "bottom", ")", "/", "(", "bottom", "-", "top", ")", ";", "m32", "=", "(", "zZeroToOne", "?", "zNear", ":", "(", "zFar", "+", "zNear", ")", ")", "/", "(", "zNear", "-", "zFar", ")", ";", "properties", "=", "PROPERTY_AFFINE", ";", "return", "this", ";", "}" ]
Set this matrix to be an orthographic projection transformation for a right-handed coordinate system using the given NDC z range. <p> In order to apply the orthographic projection to an already existing transformation, use {@link #ortho(double, double, double, double, double, double, boolean) ortho()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #ortho(double, double, double, double, double, double, boolean) @param left the distance from the center to the left frustum edge @param right the distance from the center to the right frustum edge @param bottom the distance from the center to the bottom frustum edge @param top the distance from the center to the top frustum edge @param zNear near clipping plane distance @param zFar far clipping plane distance @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return this
[ "Set", "this", "matrix", "to", "be", "an", "orthographic", "projection", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "using", "the", "given", "NDC", "z", "range", ".", "<p", ">", "In", "order", "to", "apply", "the", "orthographic", "projection", "to", "an", "already", "existing", "transformation", "use", "{", "@link", "#ortho", "(", "double", "double", "double", "double", "double", "double", "boolean", ")", "ortho", "()", "}", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "www", ".", "songho", ".", "ca", "/", "opengl", "/", "gl_projectionmatrix", ".", "html#ortho", ">", "http", ":", "//", "www", ".", "songho", ".", "ca<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L9944-L9955
uoa-group-applications/morc
src/main/java/nz/ac/auckland/morc/MorcBuilder.java
MorcBuilder.processorMultiplier
public Builder processorMultiplier(int count, Processor... processors) { """ Replay the same processor for the specified number of times (requests or inputs) @param count The number of times to repeat these processors (separate requests) @param processors A collection of processors that will be applied to an exchange before it is sent """ for (int i = 0; i < count; i++) { addProcessors(processors); } return self(); }
java
public Builder processorMultiplier(int count, Processor... processors) { for (int i = 0; i < count; i++) { addProcessors(processors); } return self(); }
[ "public", "Builder", "processorMultiplier", "(", "int", "count", ",", "Processor", "...", "processors", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "addProcessors", "(", "processors", ")", ";", "}", "return", "self", "(", ")", ";", "}" ]
Replay the same processor for the specified number of times (requests or inputs) @param count The number of times to repeat these processors (separate requests) @param processors A collection of processors that will be applied to an exchange before it is sent
[ "Replay", "the", "same", "processor", "for", "the", "specified", "number", "of", "times", "(", "requests", "or", "inputs", ")" ]
train
https://github.com/uoa-group-applications/morc/blob/3add6308b1fbfc98187364ac73007c83012ea8ba/src/main/java/nz/ac/auckland/morc/MorcBuilder.java#L94-L99
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/sequences/SequenceGibbsSampler.java
SequenceGibbsSampler.sampleSequenceRepeatedly
public void sampleSequenceRepeatedly(SequenceModel model, int[] sequence, int numSamples) { """ Samples the sequence repeatedly, making numSamples passes over the entire sequence. """ sequence = copy(sequence); // so we don't change the initial, or the one we just stored listener.setInitialSequence(sequence); for (int iter=0; iter<numSamples; iter++) { sampleSequenceForward(model, sequence); } }
java
public void sampleSequenceRepeatedly(SequenceModel model, int[] sequence, int numSamples) { sequence = copy(sequence); // so we don't change the initial, or the one we just stored listener.setInitialSequence(sequence); for (int iter=0; iter<numSamples; iter++) { sampleSequenceForward(model, sequence); } }
[ "public", "void", "sampleSequenceRepeatedly", "(", "SequenceModel", "model", ",", "int", "[", "]", "sequence", ",", "int", "numSamples", ")", "{", "sequence", "=", "copy", "(", "sequence", ")", ";", "// so we don't change the initial, or the one we just stored\r", "listener", ".", "setInitialSequence", "(", "sequence", ")", ";", "for", "(", "int", "iter", "=", "0", ";", "iter", "<", "numSamples", ";", "iter", "++", ")", "{", "sampleSequenceForward", "(", "model", ",", "sequence", ")", ";", "}", "}" ]
Samples the sequence repeatedly, making numSamples passes over the entire sequence.
[ "Samples", "the", "sequence", "repeatedly", "making", "numSamples", "passes", "over", "the", "entire", "sequence", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/sequences/SequenceGibbsSampler.java#L167-L173
roboconf/roboconf-platform
miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java
ProjectUtils.createMavenProject
private static void createMavenProject( File targetDirectory, CreationBean creationBean ) throws IOException { """ Creates a Maven project for Roboconf. @param targetDirectory the directory into which the Roboconf files must be copied @param creationBean the creation properties @throws IOException if something went wrong """ // Create the directory structure File rootDir = new File( targetDirectory, Constants.MAVEN_SRC_MAIN_MODEL ); String[] directoriesToCreate = creationBean.isReusableRecipe() ? RR_DIRECTORIES : ALL_DIRECTORIES; for( String s : directoriesToCreate ) { File dir = new File( rootDir, s ); Utils.createDirectory( dir ); } // Create a POM? InputStream in; if( Utils.isEmptyOrWhitespaces( creationBean.getCustomPomLocation())) in = ProjectUtils.class.getResourceAsStream( "/pom-skeleton.xml" ); else in = new FileInputStream( creationBean.getCustomPomLocation()); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); String tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_POM_GROUP, creationBean.getGroupId()) .replace( TPL_POM_PLUGIN_VERSION, creationBean.getPluginVersion()) .replace( TPL_VERSION, creationBean.getProjectVersion()) .replace( TPL_POM_ARTIFACT, creationBean.getArtifactId()) .replace( TPL_DESCRIPTION, creationBean.getProjectDescription()); File pomFile = new File( targetDirectory, "pom.xml" ); Utils.copyStream( new ByteArrayInputStream( tpl.getBytes( StandardCharsets.UTF_8 )), pomFile ); // Create the descriptor in = ProjectUtils.class.getResourceAsStream( "/application-skeleton.props" ); out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_DESCRIPTION, "${project.description}" ); // If for some reason, the project version is already a Maven expression, // keep it untouched. Such a thing may cause troubles with a real POM, // as versions should not reference properties. But it may be used for tests anyway. if( ! creationBean.getProjectVersion().contains( "$" )) tpl = tpl.replace( TPL_VERSION, "${project.version}" ); else tpl = tpl.replace( TPL_VERSION, creationBean.getProjectVersion()); // Create the rest of the project completeProjectCreation( rootDir, tpl, creationBean ); }
java
private static void createMavenProject( File targetDirectory, CreationBean creationBean ) throws IOException { // Create the directory structure File rootDir = new File( targetDirectory, Constants.MAVEN_SRC_MAIN_MODEL ); String[] directoriesToCreate = creationBean.isReusableRecipe() ? RR_DIRECTORIES : ALL_DIRECTORIES; for( String s : directoriesToCreate ) { File dir = new File( rootDir, s ); Utils.createDirectory( dir ); } // Create a POM? InputStream in; if( Utils.isEmptyOrWhitespaces( creationBean.getCustomPomLocation())) in = ProjectUtils.class.getResourceAsStream( "/pom-skeleton.xml" ); else in = new FileInputStream( creationBean.getCustomPomLocation()); ByteArrayOutputStream out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); String tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_POM_GROUP, creationBean.getGroupId()) .replace( TPL_POM_PLUGIN_VERSION, creationBean.getPluginVersion()) .replace( TPL_VERSION, creationBean.getProjectVersion()) .replace( TPL_POM_ARTIFACT, creationBean.getArtifactId()) .replace( TPL_DESCRIPTION, creationBean.getProjectDescription()); File pomFile = new File( targetDirectory, "pom.xml" ); Utils.copyStream( new ByteArrayInputStream( tpl.getBytes( StandardCharsets.UTF_8 )), pomFile ); // Create the descriptor in = ProjectUtils.class.getResourceAsStream( "/application-skeleton.props" ); out = new ByteArrayOutputStream(); Utils.copyStreamSafely( in, out ); tpl = out.toString( "UTF-8" ) .replace( TPL_NAME, creationBean.getProjectName()) .replace( TPL_DESCRIPTION, "${project.description}" ); // If for some reason, the project version is already a Maven expression, // keep it untouched. Such a thing may cause troubles with a real POM, // as versions should not reference properties. But it may be used for tests anyway. if( ! creationBean.getProjectVersion().contains( "$" )) tpl = tpl.replace( TPL_VERSION, "${project.version}" ); else tpl = tpl.replace( TPL_VERSION, creationBean.getProjectVersion()); // Create the rest of the project completeProjectCreation( rootDir, tpl, creationBean ); }
[ "private", "static", "void", "createMavenProject", "(", "File", "targetDirectory", ",", "CreationBean", "creationBean", ")", "throws", "IOException", "{", "// Create the directory structure", "File", "rootDir", "=", "new", "File", "(", "targetDirectory", ",", "Constants", ".", "MAVEN_SRC_MAIN_MODEL", ")", ";", "String", "[", "]", "directoriesToCreate", "=", "creationBean", ".", "isReusableRecipe", "(", ")", "?", "RR_DIRECTORIES", ":", "ALL_DIRECTORIES", ";", "for", "(", "String", "s", ":", "directoriesToCreate", ")", "{", "File", "dir", "=", "new", "File", "(", "rootDir", ",", "s", ")", ";", "Utils", ".", "createDirectory", "(", "dir", ")", ";", "}", "// Create a POM?", "InputStream", "in", ";", "if", "(", "Utils", ".", "isEmptyOrWhitespaces", "(", "creationBean", ".", "getCustomPomLocation", "(", ")", ")", ")", "in", "=", "ProjectUtils", ".", "class", ".", "getResourceAsStream", "(", "\"/pom-skeleton.xml\"", ")", ";", "else", "in", "=", "new", "FileInputStream", "(", "creationBean", ".", "getCustomPomLocation", "(", ")", ")", ";", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "Utils", ".", "copyStreamSafely", "(", "in", ",", "out", ")", ";", "String", "tpl", "=", "out", ".", "toString", "(", "\"UTF-8\"", ")", ".", "replace", "(", "TPL_NAME", ",", "creationBean", ".", "getProjectName", "(", ")", ")", ".", "replace", "(", "TPL_POM_GROUP", ",", "creationBean", ".", "getGroupId", "(", ")", ")", ".", "replace", "(", "TPL_POM_PLUGIN_VERSION", ",", "creationBean", ".", "getPluginVersion", "(", ")", ")", ".", "replace", "(", "TPL_VERSION", ",", "creationBean", ".", "getProjectVersion", "(", ")", ")", ".", "replace", "(", "TPL_POM_ARTIFACT", ",", "creationBean", ".", "getArtifactId", "(", ")", ")", ".", "replace", "(", "TPL_DESCRIPTION", ",", "creationBean", ".", "getProjectDescription", "(", ")", ")", ";", "File", "pomFile", "=", "new", "File", "(", "targetDirectory", ",", "\"pom.xml\"", ")", ";", "Utils", ".", "copyStream", "(", "new", "ByteArrayInputStream", "(", "tpl", ".", "getBytes", "(", "StandardCharsets", ".", "UTF_8", ")", ")", ",", "pomFile", ")", ";", "// Create the descriptor", "in", "=", "ProjectUtils", ".", "class", ".", "getResourceAsStream", "(", "\"/application-skeleton.props\"", ")", ";", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "Utils", ".", "copyStreamSafely", "(", "in", ",", "out", ")", ";", "tpl", "=", "out", ".", "toString", "(", "\"UTF-8\"", ")", ".", "replace", "(", "TPL_NAME", ",", "creationBean", ".", "getProjectName", "(", ")", ")", ".", "replace", "(", "TPL_DESCRIPTION", ",", "\"${project.description}\"", ")", ";", "// If for some reason, the project version is already a Maven expression,", "// keep it untouched. Such a thing may cause troubles with a real POM,", "// as versions should not reference properties. But it may be used for tests anyway.", "if", "(", "!", "creationBean", ".", "getProjectVersion", "(", ")", ".", "contains", "(", "\"$\"", ")", ")", "tpl", "=", "tpl", ".", "replace", "(", "TPL_VERSION", ",", "\"${project.version}\"", ")", ";", "else", "tpl", "=", "tpl", ".", "replace", "(", "TPL_VERSION", ",", "creationBean", ".", "getProjectVersion", "(", ")", ")", ";", "// Create the rest of the project", "completeProjectCreation", "(", "rootDir", ",", "tpl", ",", "creationBean", ")", ";", "}" ]
Creates a Maven project for Roboconf. @param targetDirectory the directory into which the Roboconf files must be copied @param creationBean the creation properties @throws IOException if something went wrong
[ "Creates", "a", "Maven", "project", "for", "Roboconf", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-tooling-core/src/main/java/net/roboconf/tooling/core/ProjectUtils.java#L168-L216
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.canRegister
protected boolean canRegister(Route route, ControllerHandler handler) { """ Determines if this controller handler can be registered in the Swagger specification. @param route @param handler @return true if the controller handler can be registered in the Swagger specification """ if (!METHODS.contains(route.getRequestMethod().toUpperCase())) { log.debug("Skip {} {}, {} Swagger does not support specified HTTP method", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } List<String> produces = handler.getDeclaredProduces(); if (produces.isEmpty()) { log.debug("Skip {} {}, {} does not declare @Produces", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getDeclaredReturns().isEmpty()) { log.debug("Skip {} {}, {} does not declare expected @Returns", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getControllerMethod().isAnnotationPresent(Undocumented.class) || handler.getControllerMethod().getDeclaringClass().isAnnotationPresent(Undocumented.class)) { log.debug("Skip {} {}, {} is annotated as @Undocumented", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (!route.getUriPattern().startsWith(relativeSwaggerBasePath)) { log.debug("Skip {} {}, {} route is not within Swagger basePath '{}'", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod()), relativeSwaggerBasePath); return false; } return true; }
java
protected boolean canRegister(Route route, ControllerHandler handler) { if (!METHODS.contains(route.getRequestMethod().toUpperCase())) { log.debug("Skip {} {}, {} Swagger does not support specified HTTP method", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } List<String> produces = handler.getDeclaredProduces(); if (produces.isEmpty()) { log.debug("Skip {} {}, {} does not declare @Produces", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getDeclaredReturns().isEmpty()) { log.debug("Skip {} {}, {} does not declare expected @Returns", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getControllerMethod().isAnnotationPresent(Undocumented.class) || handler.getControllerMethod().getDeclaringClass().isAnnotationPresent(Undocumented.class)) { log.debug("Skip {} {}, {} is annotated as @Undocumented", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (!route.getUriPattern().startsWith(relativeSwaggerBasePath)) { log.debug("Skip {} {}, {} route is not within Swagger basePath '{}'", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod()), relativeSwaggerBasePath); return false; } return true; }
[ "protected", "boolean", "canRegister", "(", "Route", "route", ",", "ControllerHandler", "handler", ")", "{", "if", "(", "!", "METHODS", ".", "contains", "(", "route", ".", "getRequestMethod", "(", ")", ".", "toUpperCase", "(", ")", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} Swagger does not support specified HTTP method\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "List", "<", "String", ">", "produces", "=", "handler", ".", "getDeclaredProduces", "(", ")", ";", "if", "(", "produces", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} does not declare @Produces\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "if", "(", "handler", ".", "getDeclaredReturns", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} does not declare expected @Returns\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "if", "(", "handler", ".", "getControllerMethod", "(", ")", ".", "isAnnotationPresent", "(", "Undocumented", ".", "class", ")", "||", "handler", ".", "getControllerMethod", "(", ")", ".", "getDeclaringClass", "(", ")", ".", "isAnnotationPresent", "(", "Undocumented", ".", "class", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} is annotated as @Undocumented\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "if", "(", "!", "route", ".", "getUriPattern", "(", ")", ".", "startsWith", "(", "relativeSwaggerBasePath", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} route is not within Swagger basePath '{}'\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ",", "relativeSwaggerBasePath", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determines if this controller handler can be registered in the Swagger specification. @param route @param handler @return true if the controller handler can be registered in the Swagger specification
[ "Determines", "if", "this", "controller", "handler", "can", "be", "registered", "in", "the", "Swagger", "specification", "." ]
train
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L273-L309
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/spelling/symspell/implementation/SymSpell.java
SymSpell.loadDictionary
public boolean loadDictionary(String corpus, int termIndex, int countIndex) { """ / <returns>True if file loaded, or false if file not found.</returns> """ File file = new File(corpus); if (!file.exists()) { return false; } BufferedReader br = null; try { br = Files.newBufferedReader(Paths.get(corpus), StandardCharsets.UTF_8); } catch (IOException ex) { System.out.println(ex.getMessage()); } if (br == null) { return false; } return loadDictionary(br, termIndex, countIndex); }
java
public boolean loadDictionary(String corpus, int termIndex, int countIndex) { File file = new File(corpus); if (!file.exists()) { return false; } BufferedReader br = null; try { br = Files.newBufferedReader(Paths.get(corpus), StandardCharsets.UTF_8); } catch (IOException ex) { System.out.println(ex.getMessage()); } if (br == null) { return false; } return loadDictionary(br, termIndex, countIndex); }
[ "public", "boolean", "loadDictionary", "(", "String", "corpus", ",", "int", "termIndex", ",", "int", "countIndex", ")", "{", "File", "file", "=", "new", "File", "(", "corpus", ")", ";", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "return", "false", ";", "}", "BufferedReader", "br", "=", "null", ";", "try", "{", "br", "=", "Files", ".", "newBufferedReader", "(", "Paths", ".", "get", "(", "corpus", ")", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "System", ".", "out", ".", "println", "(", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "if", "(", "br", "==", "null", ")", "{", "return", "false", ";", "}", "return", "loadDictionary", "(", "br", ",", "termIndex", ",", "countIndex", ")", ";", "}" ]
/ <returns>True if file loaded, or false if file not found.</returns>
[ "/", "<returns", ">", "True", "if", "file", "loaded", "or", "false", "if", "file", "not", "found", ".", "<", "/", "returns", ">" ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/spelling/symspell/implementation/SymSpell.java#L185-L201
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java
Utils.processReplyContent
public static void processReplyContent(MultipartBody multipartBody, ReplyingOptions replyingOptions) { """ This does generic processing of ReplyingOptions objects when sending a request to the API @param multipartBody The MultipartBody that the ReplyingOptions content should be appended to @param replyingOptions The ReplyingOptions that were used in this request """ if (replyingOptions.getReplyTo() != 0) multipartBody.field("reply_to_message_id", String.valueOf(replyingOptions.getReplyTo()), "application/json; charset=utf8;"); if (replyingOptions.getReplyMarkup() != null) { switch (replyingOptions.getReplyMarkup().getType()) { case FORCE_REPLY: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ForceReply.class), "application/json; charset=utf8;"); break; case KEYBOARD_HIDE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardHide.class), "application/json; charset=utf8;"); break; case KEYBOARD_REMOVE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardRemove.class), "application/json; charset=utf8;"); break; case KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardMarkup.class), "application/json; charset=utf8;"); break; case INLINE_KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), InlineKeyboardMarkup.class), "application/json; charset=utf8;"); break; } } }
java
public static void processReplyContent(MultipartBody multipartBody, ReplyingOptions replyingOptions) { if (replyingOptions.getReplyTo() != 0) multipartBody.field("reply_to_message_id", String.valueOf(replyingOptions.getReplyTo()), "application/json; charset=utf8;"); if (replyingOptions.getReplyMarkup() != null) { switch (replyingOptions.getReplyMarkup().getType()) { case FORCE_REPLY: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ForceReply.class), "application/json; charset=utf8;"); break; case KEYBOARD_HIDE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardHide.class), "application/json; charset=utf8;"); break; case KEYBOARD_REMOVE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardRemove.class), "application/json; charset=utf8;"); break; case KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardMarkup.class), "application/json; charset=utf8;"); break; case INLINE_KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), InlineKeyboardMarkup.class), "application/json; charset=utf8;"); break; } } }
[ "public", "static", "void", "processReplyContent", "(", "MultipartBody", "multipartBody", ",", "ReplyingOptions", "replyingOptions", ")", "{", "if", "(", "replyingOptions", ".", "getReplyTo", "(", ")", "!=", "0", ")", "multipartBody", ".", "field", "(", "\"reply_to_message_id\"", ",", "String", ".", "valueOf", "(", "replyingOptions", ".", "getReplyTo", "(", ")", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "if", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", "!=", "null", ")", "{", "switch", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ".", "getType", "(", ")", ")", "{", "case", "FORCE_REPLY", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ForceReply", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "KEYBOARD_HIDE", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ReplyKeyboardHide", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "KEYBOARD_REMOVE", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ReplyKeyboardRemove", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "KEYBOARD_MARKUP", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ReplyKeyboardMarkup", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "INLINE_KEYBOARD_MARKUP", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "InlineKeyboardMarkup", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "}", "}", "}" ]
This does generic processing of ReplyingOptions objects when sending a request to the API @param multipartBody The MultipartBody that the ReplyingOptions content should be appended to @param replyingOptions The ReplyingOptions that were used in this request
[ "This", "does", "generic", "processing", "of", "ReplyingOptions", "objects", "when", "sending", "a", "request", "to", "the", "API" ]
train
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java#L95-L120
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsConfigurationReader.java
CmsConfigurationReader.getBoolean
protected boolean getBoolean(I_CmsXmlContentLocation parent, String name) { """ Helper method to read a boolean value from the XML.<p> If the element is not found in the XML, false is returned.<p> @param parent the parent node @param name the name of the XML content value @return the boolean value """ I_CmsXmlContentValueLocation location = parent.getSubValue(name); if (location == null) { return false; } String value = location.getValue().getStringValue(m_cms); return Boolean.parseBoolean(value); }
java
protected boolean getBoolean(I_CmsXmlContentLocation parent, String name) { I_CmsXmlContentValueLocation location = parent.getSubValue(name); if (location == null) { return false; } String value = location.getValue().getStringValue(m_cms); return Boolean.parseBoolean(value); }
[ "protected", "boolean", "getBoolean", "(", "I_CmsXmlContentLocation", "parent", ",", "String", "name", ")", "{", "I_CmsXmlContentValueLocation", "location", "=", "parent", ".", "getSubValue", "(", "name", ")", ";", "if", "(", "location", "==", "null", ")", "{", "return", "false", ";", "}", "String", "value", "=", "location", ".", "getValue", "(", ")", ".", "getStringValue", "(", "m_cms", ")", ";", "return", "Boolean", ".", "parseBoolean", "(", "value", ")", ";", "}" ]
Helper method to read a boolean value from the XML.<p> If the element is not found in the XML, false is returned.<p> @param parent the parent node @param name the name of the XML content value @return the boolean value
[ "Helper", "method", "to", "read", "a", "boolean", "value", "from", "the", "XML", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsConfigurationReader.java#L788-L796
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.isNotSame
public static <T> void isNotSame( final T argument, String argumentName, final T object, String objectName ) { """ Asserts that the specified first object is not the same as (==) the specified second object. @param <T> @param argument The argument to assert as not the same as <code>object</code>. @param argumentName The name that will be used within the exception message for the argument should an exception be thrown @param object The object to assert as not the same as <code>argument</code>. @param objectName The name that will be used within the exception message for <code>object</code> should an exception be thrown; if <code>null</code> and <code>object</code> is not <code>null</code>, <code>object.toString()</code> will be used. @throws IllegalArgumentException If the specified objects are the same. """ if (argument == object) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustNotBeSameAs.text(argumentName, objectName)); } }
java
public static <T> void isNotSame( final T argument, String argumentName, final T object, String objectName ) { if (argument == object) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustNotBeSameAs.text(argumentName, objectName)); } }
[ "public", "static", "<", "T", ">", "void", "isNotSame", "(", "final", "T", "argument", ",", "String", "argumentName", ",", "final", "T", "object", ",", "String", "objectName", ")", "{", "if", "(", "argument", "==", "object", ")", "{", "if", "(", "objectName", "==", "null", ")", "objectName", "=", "getObjectName", "(", "object", ")", ";", "throw", "new", "IllegalArgumentException", "(", "CommonI18n", ".", "argumentMustNotBeSameAs", ".", "text", "(", "argumentName", ",", "objectName", ")", ")", ";", "}", "}" ]
Asserts that the specified first object is not the same as (==) the specified second object. @param <T> @param argument The argument to assert as not the same as <code>object</code>. @param argumentName The name that will be used within the exception message for the argument should an exception be thrown @param object The object to assert as not the same as <code>argument</code>. @param objectName The name that will be used within the exception message for <code>object</code> should an exception be thrown; if <code>null</code> and <code>object</code> is not <code>null</code>, <code>object.toString()</code> will be used. @throws IllegalArgumentException If the specified objects are the same.
[ "Asserts", "that", "the", "specified", "first", "object", "is", "not", "the", "same", "as", "(", "==", ")", "the", "specified", "second", "object", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L494-L502
ykrasik/jaci
jaci-utils/src/main/java/com/github/ykrasik/jaci/util/string/StringUtils.java
StringUtils.removeLeadingDelimiter
public static String removeLeadingDelimiter(String str, String delimiter) { """ Removes the leading delimiter from a string. @param str String to process. @param delimiter Delimiter to remove. @return The string with the leading delimiter removed. """ if (!str.startsWith(delimiter)) { return str; } else { return str.substring(delimiter.length(), str.length()); } }
java
public static String removeLeadingDelimiter(String str, String delimiter) { if (!str.startsWith(delimiter)) { return str; } else { return str.substring(delimiter.length(), str.length()); } }
[ "public", "static", "String", "removeLeadingDelimiter", "(", "String", "str", ",", "String", "delimiter", ")", "{", "if", "(", "!", "str", ".", "startsWith", "(", "delimiter", ")", ")", "{", "return", "str", ";", "}", "else", "{", "return", "str", ".", "substring", "(", "delimiter", ".", "length", "(", ")", ",", "str", ".", "length", "(", ")", ")", ";", "}", "}" ]
Removes the leading delimiter from a string. @param str String to process. @param delimiter Delimiter to remove. @return The string with the leading delimiter removed.
[ "Removes", "the", "leading", "delimiter", "from", "a", "string", "." ]
train
https://github.com/ykrasik/jaci/blob/4615edef7c76288ad5ea8d678132b161645ca1e3/jaci-utils/src/main/java/com/github/ykrasik/jaci/util/string/StringUtils.java#L75-L81
h2oai/h2o-3
h2o-genmodel/src/main/java/hex/genmodel/AbstractMojoWriter.java
AbstractMojoWriter.writeln
protected final void writeln(String s, boolean escapeNewlines) { """ Write a single line of text to a previously opened text file, escape new line characters if enabled. """ assert tmpfile != null : "No text file is currently being written"; tmpfile.append(escapeNewlines ? StringEscapeUtils.escapeNewlines(s) : s); tmpfile.append('\n'); }
java
protected final void writeln(String s, boolean escapeNewlines) { assert tmpfile != null : "No text file is currently being written"; tmpfile.append(escapeNewlines ? StringEscapeUtils.escapeNewlines(s) : s); tmpfile.append('\n'); }
[ "protected", "final", "void", "writeln", "(", "String", "s", ",", "boolean", "escapeNewlines", ")", "{", "assert", "tmpfile", "!=", "null", ":", "\"No text file is currently being written\"", ";", "tmpfile", ".", "append", "(", "escapeNewlines", "?", "StringEscapeUtils", ".", "escapeNewlines", "(", "s", ")", ":", "s", ")", ";", "tmpfile", ".", "append", "(", "'", "'", ")", ";", "}" ]
Write a single line of text to a previously opened text file, escape new line characters if enabled.
[ "Write", "a", "single", "line", "of", "text", "to", "a", "previously", "opened", "text", "file", "escape", "new", "line", "characters", "if", "enabled", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-genmodel/src/main/java/hex/genmodel/AbstractMojoWriter.java#L102-L106
nguillaumin/slick2d-maven
slick2d-peditor/src/main/java/org/newdawn/slick/tools/peditor/WhiskasPanel.java
WhiskasPanel.addEnableControl
private void addEnableControl(String text, ItemListener listener) { """ Add a control for enablement @param text The label to be associated with the check box @param listener The listener to be notified of updates to the new control """ JCheckBox enableControl = new JCheckBox("Enable " + text); enableControl.setBounds(10, offset, 200, 20); enableControl.addItemListener(listener); add(enableControl); controlToValueName.put(enableControl, text); valueNameToControl.put(text, enableControl); offset += 25; }
java
private void addEnableControl(String text, ItemListener listener) { JCheckBox enableControl = new JCheckBox("Enable " + text); enableControl.setBounds(10, offset, 200, 20); enableControl.addItemListener(listener); add(enableControl); controlToValueName.put(enableControl, text); valueNameToControl.put(text, enableControl); offset += 25; }
[ "private", "void", "addEnableControl", "(", "String", "text", ",", "ItemListener", "listener", ")", "{", "JCheckBox", "enableControl", "=", "new", "JCheckBox", "(", "\"Enable \"", "+", "text", ")", ";", "enableControl", ".", "setBounds", "(", "10", ",", "offset", ",", "200", ",", "20", ")", ";", "enableControl", ".", "addItemListener", "(", "listener", ")", ";", "add", "(", "enableControl", ")", ";", "controlToValueName", ".", "put", "(", "enableControl", ",", "text", ")", ";", "valueNameToControl", ".", "put", "(", "text", ",", "enableControl", ")", ";", "offset", "+=", "25", ";", "}" ]
Add a control for enablement @param text The label to be associated with the check box @param listener The listener to be notified of updates to the new control
[ "Add", "a", "control", "for", "enablement" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-peditor/src/main/java/org/newdawn/slick/tools/peditor/WhiskasPanel.java#L79-L88
VoltDB/voltdb
third_party/java/src/com/google_voltpatches/common/io/Files.java
Files.readLines
public static List<String> readLines(File file, Charset charset) throws IOException { """ Reads all of the lines from a file. The lines do not include line-termination characters, but do include other leading and trailing whitespace. <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code Files.asCharSource(file, charset).readLines()}. @param file the file to read from @param charset the charset used to decode the input stream; see {@link StandardCharsets} for helpful predefined constants @return a mutable {@link List} containing all the lines @throws IOException if an I/O error occurs """ // don't use asCharSource(file, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return readLines( file, charset, new LineProcessor<List<String>>() { final List<String> result = Lists.newArrayList(); @Override public boolean processLine(String line) { result.add(line); return true; } @Override public List<String> getResult() { return result; } }); }
java
public static List<String> readLines(File file, Charset charset) throws IOException { // don't use asCharSource(file, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return readLines( file, charset, new LineProcessor<List<String>>() { final List<String> result = Lists.newArrayList(); @Override public boolean processLine(String line) { result.add(line); return true; } @Override public List<String> getResult() { return result; } }); }
[ "public", "static", "List", "<", "String", ">", "readLines", "(", "File", "file", ",", "Charset", "charset", ")", "throws", "IOException", "{", "// don't use asCharSource(file, charset).readLines() because that returns", "// an immutable list, which would change the behavior of this method", "return", "readLines", "(", "file", ",", "charset", ",", "new", "LineProcessor", "<", "List", "<", "String", ">", ">", "(", ")", "{", "final", "List", "<", "String", ">", "result", "=", "Lists", ".", "newArrayList", "(", ")", ";", "@", "Override", "public", "boolean", "processLine", "(", "String", "line", ")", "{", "result", ".", "add", "(", "line", ")", ";", "return", "true", ";", "}", "@", "Override", "public", "List", "<", "String", ">", "getResult", "(", ")", "{", "return", "result", ";", "}", "}", ")", ";", "}" ]
Reads all of the lines from a file. The lines do not include line-termination characters, but do include other leading and trailing whitespace. <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code Files.asCharSource(file, charset).readLines()}. @param file the file to read from @param charset the charset used to decode the input stream; see {@link StandardCharsets} for helpful predefined constants @return a mutable {@link List} containing all the lines @throws IOException if an I/O error occurs
[ "Reads", "all", "of", "the", "lines", "from", "a", "file", ".", "The", "lines", "do", "not", "include", "line", "-", "termination", "characters", "but", "do", "include", "other", "leading", "and", "trailing", "whitespace", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/io/Files.java#L517-L537
craftercms/core
src/main/java/org/craftercms/core/cache/impl/CacheRefresherImpl.java
CacheRefresherImpl.refreshItem
protected void refreshItem(CacheItem item, Cache cache) throws Exception { """ Refreshes only one item. To refresh the item, its {@link CacheLoader} is called to get a new value of the item. If the value returned by the loader is null, the item is removed from the cache instead. @throws Exception """ CacheLoader loader = item.getLoader(); Object[] loaderParams = item.getLoaderParams(); if (loader == null) { throw new InternalCacheEngineException("No cache loader for " + getScopeAndKeyString(item)); } if (logger.isDebugEnabled()) { logger.debug("Refreshing " + getScopeAndKeyString(item)); } Object newValue = loader.load(loaderParams); if (newValue != null) { cache.put(item.getScope(), item.getKey(), newValue, item.getTicksToExpire(), item.getTicksToRefresh(), item.getLoader(), item.getLoaderParams()); } else { // If newValue returned is null, remove the item from the cache cache.remove(item.getScope(), item.getKey()); } }
java
protected void refreshItem(CacheItem item, Cache cache) throws Exception { CacheLoader loader = item.getLoader(); Object[] loaderParams = item.getLoaderParams(); if (loader == null) { throw new InternalCacheEngineException("No cache loader for " + getScopeAndKeyString(item)); } if (logger.isDebugEnabled()) { logger.debug("Refreshing " + getScopeAndKeyString(item)); } Object newValue = loader.load(loaderParams); if (newValue != null) { cache.put(item.getScope(), item.getKey(), newValue, item.getTicksToExpire(), item.getTicksToRefresh(), item.getLoader(), item.getLoaderParams()); } else { // If newValue returned is null, remove the item from the cache cache.remove(item.getScope(), item.getKey()); } }
[ "protected", "void", "refreshItem", "(", "CacheItem", "item", ",", "Cache", "cache", ")", "throws", "Exception", "{", "CacheLoader", "loader", "=", "item", ".", "getLoader", "(", ")", ";", "Object", "[", "]", "loaderParams", "=", "item", ".", "getLoaderParams", "(", ")", ";", "if", "(", "loader", "==", "null", ")", "{", "throw", "new", "InternalCacheEngineException", "(", "\"No cache loader for \"", "+", "getScopeAndKeyString", "(", "item", ")", ")", ";", "}", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Refreshing \"", "+", "getScopeAndKeyString", "(", "item", ")", ")", ";", "}", "Object", "newValue", "=", "loader", ".", "load", "(", "loaderParams", ")", ";", "if", "(", "newValue", "!=", "null", ")", "{", "cache", ".", "put", "(", "item", ".", "getScope", "(", ")", ",", "item", ".", "getKey", "(", ")", ",", "newValue", ",", "item", ".", "getTicksToExpire", "(", ")", ",", "item", ".", "getTicksToRefresh", "(", ")", ",", "item", ".", "getLoader", "(", ")", ",", "item", ".", "getLoaderParams", "(", ")", ")", ";", "}", "else", "{", "// If newValue returned is null, remove the item from the cache", "cache", ".", "remove", "(", "item", ".", "getScope", "(", ")", ",", "item", ".", "getKey", "(", ")", ")", ";", "}", "}" ]
Refreshes only one item. To refresh the item, its {@link CacheLoader} is called to get a new value of the item. If the value returned by the loader is null, the item is removed from the cache instead. @throws Exception
[ "Refreshes", "only", "one", "item", ".", "To", "refresh", "the", "item", "its", "{", "@link", "CacheLoader", "}", "is", "called", "to", "get", "a", "new", "value", "of", "the", "item", ".", "If", "the", "value", "returned", "by", "the", "loader", "is", "null", "the", "item", "is", "removed", "from", "the", "cache", "instead", "." ]
train
https://github.com/craftercms/core/blob/d3ec74d669d3f8cfcf995177615d5f126edfa237/src/main/java/org/craftercms/core/cache/impl/CacheRefresherImpl.java#L56-L76
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbooksInner.java
RunbooksInner.createOrUpdateAsync
public Observable<RunbookInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookCreateOrUpdateParameters parameters) { """ Create the runbook identified by runbook name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param runbookName The runbook name. @param parameters The create or update parameters for runbook. Provide either content link for a published runbook or draft, not both. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RunbookInner object """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).map(new Func1<ServiceResponse<RunbookInner>, RunbookInner>() { @Override public RunbookInner call(ServiceResponse<RunbookInner> response) { return response.body(); } }); }
java
public Observable<RunbookInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookCreateOrUpdateParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).map(new Func1<ServiceResponse<RunbookInner>, RunbookInner>() { @Override public RunbookInner call(ServiceResponse<RunbookInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RunbookInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "runbookName", ",", "RunbookCreateOrUpdateParameters", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "runbookName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RunbookInner", ">", ",", "RunbookInner", ">", "(", ")", "{", "@", "Override", "public", "RunbookInner", "call", "(", "ServiceResponse", "<", "RunbookInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create the runbook identified by runbook name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param runbookName The runbook name. @param parameters The create or update parameters for runbook. Provide either content link for a published runbook or draft, not both. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RunbookInner object
[ "Create", "the", "runbook", "identified", "by", "runbook", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbooksInner.java#L321-L328
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/AbstractBaseModel.java
AbstractBaseModel.attachParentListener
protected void attachParentListener() { """ Attach a custom listener that will release the mode when the rootNode is removed from its parent. """ final AutoRelease ar = ClassUtility.getLastClassAnnotation(this.getClass(), AutoRelease.class); // Only manage automatic release when the annotation exists with true value if (ar != null && ar.value() && node() != null) { // TODO check rootnode null when using NullView // Allow to release the model if the root business object doesn't exist anymore node().parentProperty().addListener(new ChangeListener<Node>() { @Override public void changed(final ObservableValue<? extends Node> observable, final Node oldValue, final Node newValue) { if (newValue != null) { AbstractBaseModel.this.hasBeenAttached = true; } if (newValue == null && AbstractBaseModel.this.hasBeenAttached) { AbstractBaseModel.this.hasBeenAttached = false; release(); node().parentProperty().removeListener(this); } } }); } }
java
protected void attachParentListener() { final AutoRelease ar = ClassUtility.getLastClassAnnotation(this.getClass(), AutoRelease.class); // Only manage automatic release when the annotation exists with true value if (ar != null && ar.value() && node() != null) { // TODO check rootnode null when using NullView // Allow to release the model if the root business object doesn't exist anymore node().parentProperty().addListener(new ChangeListener<Node>() { @Override public void changed(final ObservableValue<? extends Node> observable, final Node oldValue, final Node newValue) { if (newValue != null) { AbstractBaseModel.this.hasBeenAttached = true; } if (newValue == null && AbstractBaseModel.this.hasBeenAttached) { AbstractBaseModel.this.hasBeenAttached = false; release(); node().parentProperty().removeListener(this); } } }); } }
[ "protected", "void", "attachParentListener", "(", ")", "{", "final", "AutoRelease", "ar", "=", "ClassUtility", ".", "getLastClassAnnotation", "(", "this", ".", "getClass", "(", ")", ",", "AutoRelease", ".", "class", ")", ";", "// Only manage automatic release when the annotation exists with true value", "if", "(", "ar", "!=", "null", "&&", "ar", ".", "value", "(", ")", "&&", "node", "(", ")", "!=", "null", ")", "{", "// TODO check rootnode null when using NullView", "// Allow to release the model if the root business object doesn't exist anymore", "node", "(", ")", ".", "parentProperty", "(", ")", ".", "addListener", "(", "new", "ChangeListener", "<", "Node", ">", "(", ")", "{", "@", "Override", "public", "void", "changed", "(", "final", "ObservableValue", "<", "?", "extends", "Node", ">", "observable", ",", "final", "Node", "oldValue", ",", "final", "Node", "newValue", ")", "{", "if", "(", "newValue", "!=", "null", ")", "{", "AbstractBaseModel", ".", "this", ".", "hasBeenAttached", "=", "true", ";", "}", "if", "(", "newValue", "==", "null", "&&", "AbstractBaseModel", ".", "this", ".", "hasBeenAttached", ")", "{", "AbstractBaseModel", ".", "this", ".", "hasBeenAttached", "=", "false", ";", "release", "(", ")", ";", "node", "(", ")", ".", "parentProperty", "(", ")", ".", "removeListener", "(", "this", ")", ";", "}", "}", "}", ")", ";", "}", "}" ]
Attach a custom listener that will release the mode when the rootNode is removed from its parent.
[ "Attach", "a", "custom", "listener", "that", "will", "release", "the", "mode", "when", "the", "rootNode", "is", "removed", "from", "its", "parent", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/ui/AbstractBaseModel.java#L230-L254