repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
alkacon/opencms-core
src/org/opencms/db/generic/CmsVfsDriver.java
CmsVfsDriver.internalReadParentId
protected String internalReadParentId(CmsDbContext dbc, CmsUUID projectId, String resourcename) throws CmsDataAccessException { if ("/".equalsIgnoreCase(resourcename)) { return CmsUUID.getNullUUID().toString(); } String parent = CmsResource.getParentFolder(resourcename); parent = CmsFileUtil.removeTrailingSeparator(parent); ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; String parentId = null; try { conn = m_sqlManager.getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READ_PARENT_STRUCTURE_ID"); stmt.setString(1, parent); res = stmt.executeQuery(); if (res.next()) { parentId = res.getString(1); while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } else { throw new CmsVfsResourceNotFoundException( Messages.get().container(Messages.ERR_READ_PARENT_ID_1, dbc.removeSiteRoot(resourcename))); } } catch (SQLException e) { throw new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } finally { m_sqlManager.closeAll(dbc, conn, stmt, res); } return parentId; }
java
protected String internalReadParentId(CmsDbContext dbc, CmsUUID projectId, String resourcename) throws CmsDataAccessException { if ("/".equalsIgnoreCase(resourcename)) { return CmsUUID.getNullUUID().toString(); } String parent = CmsResource.getParentFolder(resourcename); parent = CmsFileUtil.removeTrailingSeparator(parent); ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; String parentId = null; try { conn = m_sqlManager.getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_RESOURCES_READ_PARENT_STRUCTURE_ID"); stmt.setString(1, parent); res = stmt.executeQuery(); if (res.next()) { parentId = res.getString(1); while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } else { throw new CmsVfsResourceNotFoundException( Messages.get().container(Messages.ERR_READ_PARENT_ID_1, dbc.removeSiteRoot(resourcename))); } } catch (SQLException e) { throw new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } finally { m_sqlManager.closeAll(dbc, conn, stmt, res); } return parentId; }
[ "protected", "String", "internalReadParentId", "(", "CmsDbContext", "dbc", ",", "CmsUUID", "projectId", ",", "String", "resourcename", ")", "throws", "CmsDataAccessException", "{", "if", "(", "\"/\"", ".", "equalsIgnoreCase", "(", "resourcename", ")", ")", "{", "r...
Returns the parent id of the given resource.<p> @param dbc the current database context @param projectId the current project id @param resourcename the resource name to read the parent id for @return the parent id of the given resource @throws CmsDataAccessException if something goes wrong
[ "Returns", "the", "parent", "id", "of", "the", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsVfsDriver.java#L3838-L3877
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/client/JsonPathLinkDiscoverer.java
JsonPathLinkDiscoverer.extractLink
protected Link extractLink(Object element, LinkRelation rel) { return new Link(element.toString(), rel); }
java
protected Link extractLink(Object element, LinkRelation rel) { return new Link(element.toString(), rel); }
[ "protected", "Link", "extractLink", "(", "Object", "element", ",", "LinkRelation", "rel", ")", "{", "return", "new", "Link", "(", "element", ".", "toString", "(", ")", ",", "rel", ")", ";", "}" ]
Callback for each {@link LinkDiscoverer} to extract relevant attributes and generate a {@link Link}. @param element @param rel @return link
[ "Callback", "for", "each", "{", "@link", "LinkDiscoverer", "}", "to", "extract", "relevant", "attributes", "and", "generate", "a", "{", "@link", "Link", "}", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/client/JsonPathLinkDiscoverer.java#L142-L144
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/BindDataSourceSubProcessor.java
BindDataSourceSubProcessor.processSecondRound
public boolean processSecondRound(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (SQLiteDatabaseSchema schema : schemas) { // Analyze beans BEFORE daos, because beans are needed for DAO // definition for (String daoName : schema.getDaoNameSet()) { // check dao into bean definition if (globalDaoGenerated.contains(daoName)) { createSQLEntityFromDao(schema, schema.getElement(), daoName); createSQLDaoDefinition(schema, globalBeanElements, globalDaoElements, daoName); } } // end foreach bean } // end foreach dataSource return true; }
java
public boolean processSecondRound(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (SQLiteDatabaseSchema schema : schemas) { // Analyze beans BEFORE daos, because beans are needed for DAO // definition for (String daoName : schema.getDaoNameSet()) { // check dao into bean definition if (globalDaoGenerated.contains(daoName)) { createSQLEntityFromDao(schema, schema.getElement(), daoName); createSQLDaoDefinition(schema, globalBeanElements, globalDaoElements, daoName); } } // end foreach bean } // end foreach dataSource return true; }
[ "public", "boolean", "processSecondRound", "(", "Set", "<", "?", "extends", "TypeElement", ">", "annotations", ",", "RoundEnvironment", "roundEnv", ")", "{", "for", "(", "SQLiteDatabaseSchema", "schema", ":", "schemas", ")", "{", "// Analyze beans BEFORE daos, because...
Process second round. @param annotations the annotations @param roundEnv the round env @return true, if successful
[ "Process", "second", "round", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/BindDataSourceSubProcessor.java#L534-L550
google/closure-templates
java/src/com/google/template/soy/conformance/ValidatedConformanceConfig.java
ValidatedConformanceConfig.createCustomRule
private static Rule<?> createCustomRule(String javaClass, SoyErrorKind error) { Class<? extends Rule<?>> customRuleClass; try { @SuppressWarnings("unchecked") Class<? extends Rule<?>> asSubclass = (Class<? extends Rule<?>>) Class.forName(javaClass).asSubclass(Rule.class); customRuleClass = asSubclass; } catch (ClassNotFoundException e) { throw new IllegalArgumentException("custom rule class " + javaClass + " not found", e); } try { // It is ok for the constructor to be non-public as long as it is defined in this package // if it is non public and defined in another package, this will throw an // IllegalAccessException which seems about right. Constructor<? extends Rule<?>> ctor = customRuleClass.getDeclaredConstructor(SoyErrorKind.class); return ctor.newInstance(error); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException( "unable to construct custom rule class: " + javaClass + ": " + e.getMessage(), e); } }
java
private static Rule<?> createCustomRule(String javaClass, SoyErrorKind error) { Class<? extends Rule<?>> customRuleClass; try { @SuppressWarnings("unchecked") Class<? extends Rule<?>> asSubclass = (Class<? extends Rule<?>>) Class.forName(javaClass).asSubclass(Rule.class); customRuleClass = asSubclass; } catch (ClassNotFoundException e) { throw new IllegalArgumentException("custom rule class " + javaClass + " not found", e); } try { // It is ok for the constructor to be non-public as long as it is defined in this package // if it is non public and defined in another package, this will throw an // IllegalAccessException which seems about right. Constructor<? extends Rule<?>> ctor = customRuleClass.getDeclaredConstructor(SoyErrorKind.class); return ctor.newInstance(error); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException( "unable to construct custom rule class: " + javaClass + ": " + e.getMessage(), e); } }
[ "private", "static", "Rule", "<", "?", ">", "createCustomRule", "(", "String", "javaClass", ",", "SoyErrorKind", "error", ")", "{", "Class", "<", "?", "extends", "Rule", "<", "?", ">", ">", "customRuleClass", ";", "try", "{", "@", "SuppressWarnings", "(", ...
Instantiates a custom conformance check from its fully-qualified class name, specified in the conformance protobuf. <p>Custom conformance checks must extend {@link Rule}. They must also have a binary constructor with {@link ErrorReporter} and {@link SoyErrorKind} parameters.
[ "Instantiates", "a", "custom", "conformance", "check", "from", "its", "fully", "-", "qualified", "class", "name", "specified", "in", "the", "conformance", "protobuf", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/conformance/ValidatedConformanceConfig.java#L113-L134
elastic/elasticsearch-hadoop
hive/src/main/java/org/elasticsearch/hadoop/hive/EsStorageHandler.java
EsStorageHandler.init
private void init(TableDesc tableDesc, boolean read) { Configuration cfg = getConf(); // NB: we can't just merge the table properties in, we need to save them per input/output otherwise clashes occur which confuse Hive Settings settings = HadoopSettingsManager.loadFrom(cfg); //settings.setProperty((read ? HiveConstants.INPUT_TBL_PROPERTIES : HiveConstants.OUTPUT_TBL_PROPERTIES), IOUtils.propsToString(tableDesc.getProperties())); if (read) { // no generic setting } else { // replace the default committer when using the old API HadoopCfgUtils.setOutputCommitterClass(cfg, EsOutputFormat.EsOutputCommitter.class.getName()); } Assert.hasText(tableDesc.getProperties().getProperty(TABLE_LOCATION), String.format( "no table location [%s] declared by Hive resulting in abnormal execution;", TABLE_LOCATION)); }
java
private void init(TableDesc tableDesc, boolean read) { Configuration cfg = getConf(); // NB: we can't just merge the table properties in, we need to save them per input/output otherwise clashes occur which confuse Hive Settings settings = HadoopSettingsManager.loadFrom(cfg); //settings.setProperty((read ? HiveConstants.INPUT_TBL_PROPERTIES : HiveConstants.OUTPUT_TBL_PROPERTIES), IOUtils.propsToString(tableDesc.getProperties())); if (read) { // no generic setting } else { // replace the default committer when using the old API HadoopCfgUtils.setOutputCommitterClass(cfg, EsOutputFormat.EsOutputCommitter.class.getName()); } Assert.hasText(tableDesc.getProperties().getProperty(TABLE_LOCATION), String.format( "no table location [%s] declared by Hive resulting in abnormal execution;", TABLE_LOCATION)); }
[ "private", "void", "init", "(", "TableDesc", "tableDesc", ",", "boolean", "read", ")", "{", "Configuration", "cfg", "=", "getConf", "(", ")", ";", "// NB: we can't just merge the table properties in, we need to save them per input/output otherwise clashes occur which confuse Hive...
NB: save the table properties in a special place but nothing else; otherwise the settings might trip on each other
[ "NB", ":", "save", "the", "table", "properties", "in", "a", "special", "place", "but", "nothing", "else", ";", "otherwise", "the", "settings", "might", "trip", "on", "each", "other" ]
train
https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/hive/src/main/java/org/elasticsearch/hadoop/hive/EsStorageHandler.java#L110-L126
lightblue-platform/lightblue-migrator
jiff/src/main/java/jcmp/DocCompare.java
DocCompare.compareArraysWithId
public Difference<BaseType> compareArraysWithId(List<String> field1, ArrayType node1, List<String> field2, ArrayType node2, IdentityExtractor idex) throws InvalidArrayIdentity, DuplicateArrayIdentity { Difference<BaseType> ret = new Difference<>(); // Build a map of identity -> index for both arrays final Map<Object, Integer> identities1 = getIdentityMap(field1, node1, idex); final Map<Object, Integer> identities2 = getIdentityMap(field2, node2, idex); // Iterate all elements of array 1 for (Map.Entry<Object, Integer> entry1 : identities1.entrySet()) { // Append index to the field name field1.add(Integer.toString(entry1.getValue())); // If array2 doesn't have an element with the same ID, this is a deletion Integer index2 = identities2.get(entry1.getKey()); if (index2 == null) { ret.add(new Removal(field1, getElement(node1, entry1.getValue()))); } else { field2.add(Integer.toString(index2)); // array2 has the same element // If it is at a different index, this is a move if (index2 != entry1.getValue()) { ret.add(new Move(field1, field2, getElement(node1, entry1.getValue()))); } // Recursively compare contents to get detailed diff ret.add(compareNodes(field1, getElement(node1, entry1.getValue()), field2, getElement(node2, index2))); pop(field2); } pop(field1); } // Now check elements of array 2 that are not in array 1 for (Map.Entry<Object, Integer> entry2 : identities2.entrySet()) { if (!identities1.containsKey(entry2.getKey())) { // entry2 is not in array 1: addition field2.add(Integer.toString(entry2.getValue())); ret.add(new Addition(field2, getElement(node2, entry2.getValue()))); pop(field2); } } return ret; }
java
public Difference<BaseType> compareArraysWithId(List<String> field1, ArrayType node1, List<String> field2, ArrayType node2, IdentityExtractor idex) throws InvalidArrayIdentity, DuplicateArrayIdentity { Difference<BaseType> ret = new Difference<>(); // Build a map of identity -> index for both arrays final Map<Object, Integer> identities1 = getIdentityMap(field1, node1, idex); final Map<Object, Integer> identities2 = getIdentityMap(field2, node2, idex); // Iterate all elements of array 1 for (Map.Entry<Object, Integer> entry1 : identities1.entrySet()) { // Append index to the field name field1.add(Integer.toString(entry1.getValue())); // If array2 doesn't have an element with the same ID, this is a deletion Integer index2 = identities2.get(entry1.getKey()); if (index2 == null) { ret.add(new Removal(field1, getElement(node1, entry1.getValue()))); } else { field2.add(Integer.toString(index2)); // array2 has the same element // If it is at a different index, this is a move if (index2 != entry1.getValue()) { ret.add(new Move(field1, field2, getElement(node1, entry1.getValue()))); } // Recursively compare contents to get detailed diff ret.add(compareNodes(field1, getElement(node1, entry1.getValue()), field2, getElement(node2, index2))); pop(field2); } pop(field1); } // Now check elements of array 2 that are not in array 1 for (Map.Entry<Object, Integer> entry2 : identities2.entrySet()) { if (!identities1.containsKey(entry2.getKey())) { // entry2 is not in array 1: addition field2.add(Integer.toString(entry2.getValue())); ret.add(new Addition(field2, getElement(node2, entry2.getValue()))); pop(field2); } } return ret; }
[ "public", "Difference", "<", "BaseType", ">", "compareArraysWithId", "(", "List", "<", "String", ">", "field1", ",", "ArrayType", "node1", ",", "List", "<", "String", ">", "field2", ",", "ArrayType", "node2", ",", "IdentityExtractor", "idex", ")", "throws", ...
Computes difference between arrays whose elements can be identitied by a unique identifier
[ "Computes", "difference", "between", "arrays", "whose", "elements", "can", "be", "identitied", "by", "a", "unique", "identifier" ]
train
https://github.com/lightblue-platform/lightblue-migrator/blob/ec20748557b40d1f7851e1816d1b76dae48d2027/jiff/src/main/java/jcmp/DocCompare.java#L585-L629
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/CFFFontSubset.java
CFFFontSubset.BuildNewLGSubrs
protected void BuildNewLGSubrs(int Font)throws IOException { // If the font is CID then the lsubrs are divided into FontDicts. // for each FD array the lsubrs will be subsetted. if(fonts[Font].isCID) { // Init the hashmap-array and the arraylist-array to hold the subrs used // in each private dict. hSubrsUsed = new HashMap[fonts[Font].fdprivateOffsets.length]; lSubrsUsed = new ArrayList[fonts[Font].fdprivateOffsets.length]; // A [][] which will store the byte array for each new FD Array lsubs index NewLSubrsIndex = new byte[fonts[Font].fdprivateOffsets.length][]; // An array to hold the offset for each Lsubr index fonts[Font].PrivateSubrsOffset = new int[fonts[Font].fdprivateOffsets.length]; // A [][] which will store the offset array for each lsubr index fonts[Font].PrivateSubrsOffsetsArray = new int[fonts[Font].fdprivateOffsets.length][]; // Put the FDarrayUsed into a list ArrayList FDInList = new ArrayList(FDArrayUsed.keySet()); // For each FD array which is used subset the lsubr for (int j=0;j<FDInList.size();j++) { // The FDArray index, Hash Map, Array List to work on int FD = ((Integer)FDInList.get(j)).intValue(); hSubrsUsed[FD] = new HashMap(); lSubrsUsed[FD] = new ArrayList(); //Reads the private dicts looking for the subr operator and // store both the offset for the index and its offset array BuildFDSubrsOffsets(Font,FD); // Verify that FDPrivate has a LSubrs index if(fonts[Font].PrivateSubrsOffset[FD]>=0) { //Scans the Charstring data storing the used Local and Global subroutines // by the glyphs. Scans the Subrs recursively. BuildSubrUsed(Font,FD,fonts[Font].PrivateSubrsOffset[FD],fonts[Font].PrivateSubrsOffsetsArray[FD],hSubrsUsed[FD],lSubrsUsed[FD]); // Builds the New Local Subrs index NewLSubrsIndex[FD] = BuildNewIndex(fonts[Font].PrivateSubrsOffsetsArray[FD],hSubrsUsed[FD],RETURN_OP); } } } // If the font is not CID && the Private Subr exists then subset: else if (fonts[Font].privateSubrs>=0) { // Build the subrs offsets; fonts[Font].SubrsOffsets = getIndex(fonts[Font].privateSubrs); //Scans the Charstring data storing the used Local and Global subroutines // by the glyphs. Scans the Subrs recursively. BuildSubrUsed(Font,-1,fonts[Font].privateSubrs,fonts[Font].SubrsOffsets,hSubrsUsedNonCID,lSubrsUsedNonCID); } // For all fonts subset the Global Subroutines // Scan the Global Subr Hashmap recursively on the Gsubrs BuildGSubrsUsed(Font); if (fonts[Font].privateSubrs>=0) // Builds the New Local Subrs index NewSubrsIndexNonCID = BuildNewIndex(fonts[Font].SubrsOffsets,hSubrsUsedNonCID,RETURN_OP); //Builds the New Global Subrs index NewGSubrsIndex = BuildNewIndex(gsubrOffsets,hGSubrsUsed,RETURN_OP); }
java
protected void BuildNewLGSubrs(int Font)throws IOException { // If the font is CID then the lsubrs are divided into FontDicts. // for each FD array the lsubrs will be subsetted. if(fonts[Font].isCID) { // Init the hashmap-array and the arraylist-array to hold the subrs used // in each private dict. hSubrsUsed = new HashMap[fonts[Font].fdprivateOffsets.length]; lSubrsUsed = new ArrayList[fonts[Font].fdprivateOffsets.length]; // A [][] which will store the byte array for each new FD Array lsubs index NewLSubrsIndex = new byte[fonts[Font].fdprivateOffsets.length][]; // An array to hold the offset for each Lsubr index fonts[Font].PrivateSubrsOffset = new int[fonts[Font].fdprivateOffsets.length]; // A [][] which will store the offset array for each lsubr index fonts[Font].PrivateSubrsOffsetsArray = new int[fonts[Font].fdprivateOffsets.length][]; // Put the FDarrayUsed into a list ArrayList FDInList = new ArrayList(FDArrayUsed.keySet()); // For each FD array which is used subset the lsubr for (int j=0;j<FDInList.size();j++) { // The FDArray index, Hash Map, Array List to work on int FD = ((Integer)FDInList.get(j)).intValue(); hSubrsUsed[FD] = new HashMap(); lSubrsUsed[FD] = new ArrayList(); //Reads the private dicts looking for the subr operator and // store both the offset for the index and its offset array BuildFDSubrsOffsets(Font,FD); // Verify that FDPrivate has a LSubrs index if(fonts[Font].PrivateSubrsOffset[FD]>=0) { //Scans the Charstring data storing the used Local and Global subroutines // by the glyphs. Scans the Subrs recursively. BuildSubrUsed(Font,FD,fonts[Font].PrivateSubrsOffset[FD],fonts[Font].PrivateSubrsOffsetsArray[FD],hSubrsUsed[FD],lSubrsUsed[FD]); // Builds the New Local Subrs index NewLSubrsIndex[FD] = BuildNewIndex(fonts[Font].PrivateSubrsOffsetsArray[FD],hSubrsUsed[FD],RETURN_OP); } } } // If the font is not CID && the Private Subr exists then subset: else if (fonts[Font].privateSubrs>=0) { // Build the subrs offsets; fonts[Font].SubrsOffsets = getIndex(fonts[Font].privateSubrs); //Scans the Charstring data storing the used Local and Global subroutines // by the glyphs. Scans the Subrs recursively. BuildSubrUsed(Font,-1,fonts[Font].privateSubrs,fonts[Font].SubrsOffsets,hSubrsUsedNonCID,lSubrsUsedNonCID); } // For all fonts subset the Global Subroutines // Scan the Global Subr Hashmap recursively on the Gsubrs BuildGSubrsUsed(Font); if (fonts[Font].privateSubrs>=0) // Builds the New Local Subrs index NewSubrsIndexNonCID = BuildNewIndex(fonts[Font].SubrsOffsets,hSubrsUsedNonCID,RETURN_OP); //Builds the New Global Subrs index NewGSubrsIndex = BuildNewIndex(gsubrOffsets,hGSubrsUsed,RETURN_OP); }
[ "protected", "void", "BuildNewLGSubrs", "(", "int", "Font", ")", "throws", "IOException", "{", "// If the font is CID then the lsubrs are divided into FontDicts.", "// for each FD array the lsubrs will be subsetted.", "if", "(", "fonts", "[", "Font", "]", ".", "isCID", ")", ...
Function builds the new local & global subsrs indices. IF CID then All of the FD Array lsubrs will be subsetted. @param Font the font @throws IOException
[ "Function", "builds", "the", "new", "local", "&", "global", "subsrs", "indices", ".", "IF", "CID", "then", "All", "of", "the", "FD", "Array", "lsubrs", "will", "be", "subsetted", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/CFFFontSubset.java#L435-L492
logic-ng/LogicNG
src/main/java/org/logicng/solvers/maxsat/encodings/Encoding.java
Encoding.addTernaryClause
void addTernaryClause(final MiniSatStyleSolver s, int a, int b, int c) { this.addTernaryClause(s, a, b, c, LIT_UNDEF); }
java
void addTernaryClause(final MiniSatStyleSolver s, int a, int b, int c) { this.addTernaryClause(s, a, b, c, LIT_UNDEF); }
[ "void", "addTernaryClause", "(", "final", "MiniSatStyleSolver", "s", ",", "int", "a", ",", "int", "b", ",", "int", "c", ")", "{", "this", ".", "addTernaryClause", "(", "s", ",", "a", ",", "b", ",", "c", ",", "LIT_UNDEF", ")", ";", "}" ]
Adds a ternary clause to the given SAT solver. @param s the sat solver @param a the first literal @param b the second literal @param c the third literal
[ "Adds", "a", "ternary", "clause", "to", "the", "given", "SAT", "solver", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/encodings/Encoding.java#L137-L139
kiswanij/jk-util
src/main/java/com/jk/util/JKDateTimeUtil.java
JKDateTimeUtil.addMonths
public static Date addMonths(Date date, int numOfMonths) { Calendar instance = Calendar.getInstance(); instance.setTime(date); instance.add(Calendar.MONTH, numOfMonths); return instance.getTime(); }
java
public static Date addMonths(Date date, int numOfMonths) { Calendar instance = Calendar.getInstance(); instance.setTime(date); instance.add(Calendar.MONTH, numOfMonths); return instance.getTime(); }
[ "public", "static", "Date", "addMonths", "(", "Date", "date", ",", "int", "numOfMonths", ")", "{", "Calendar", "instance", "=", "Calendar", ".", "getInstance", "(", ")", ";", "instance", ".", "setTime", "(", "date", ")", ";", "instance", ".", "add", "(",...
Adds the months. @param date the date @param numOfMonths the num of months @return the date
[ "Adds", "the", "months", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKDateTimeUtil.java#L262-L267
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Hub.java
Hub.listLive
public ListRet listLive(String prefix, int limit, String marker) throws PiliException { return list(true, prefix, limit, marker); }
java
public ListRet listLive(String prefix, int limit, String marker) throws PiliException { return list(true, prefix, limit, marker); }
[ "public", "ListRet", "listLive", "(", "String", "prefix", ",", "int", "limit", ",", "String", "marker", ")", "throws", "PiliException", "{", "return", "list", "(", "true", ",", "prefix", ",", "limit", ",", "marker", ")", ";", "}" ]
list streams which is live @param prefix @param limit @param marker @return @throws PiliException
[ "list", "streams", "which", "is", "live" ]
train
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Hub.java#L117-L119
vkostyukov/la4j
src/main/java/org/la4j/Vector.java
Vector.updateAt
public void updateAt(int i, VectorFunction function) { set(i, function.evaluate(i, get(i))); }
java
public void updateAt(int i, VectorFunction function) { set(i, function.evaluate(i, get(i))); }
[ "public", "void", "updateAt", "(", "int", "i", ",", "VectorFunction", "function", ")", "{", "set", "(", "i", ",", "function", ".", "evaluate", "(", "i", ",", "get", "(", "i", ")", ")", ")", ";", "}" ]
Updates the specified element of this vector by applying given {@code function}. @param i element's index @param function the vector function
[ "Updates", "the", "specified", "element", "of", "this", "vector", "by", "applying", "given", "{", "@code", "function", "}", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Vector.java#L752-L754
tomgibara/bits
src/main/java/com/tomgibara/bits/BitVector.java
BitVector.fromByteArray
public static BitVector fromByteArray(byte[] bytes, int size) { //TODO provide a more efficient implementation, perhaps based on Bits.asStore() if (bytes == null) throw new IllegalArgumentException("null bytes"); if (size < 0) throw new IllegalArgumentException("negative size"); BigInteger bigInt = new BigInteger(1, bytes); return fromBigIntegerImpl(bigInt, size); }
java
public static BitVector fromByteArray(byte[] bytes, int size) { //TODO provide a more efficient implementation, perhaps based on Bits.asStore() if (bytes == null) throw new IllegalArgumentException("null bytes"); if (size < 0) throw new IllegalArgumentException("negative size"); BigInteger bigInt = new BigInteger(1, bytes); return fromBigIntegerImpl(bigInt, size); }
[ "public", "static", "BitVector", "fromByteArray", "(", "byte", "[", "]", "bytes", ",", "int", "size", ")", "{", "//TODO provide a more efficient implementation, perhaps based on Bits.asStore()", "if", "(", "bytes", "==", "null", ")", "throw", "new", "IllegalArgumentExce...
Creates a {@link BitVector} from the bits of a byte array. The byte array is in big-endian order. If the specified size is less than the number of bits in the byte array, the most-significant bits are discarded. If the size exceeds the number of bits in the byte array, the most-significant bits of the {@link BitVector} are padded with zeros. @param bytes the bits in big-endian order @param size the size of the returned bit vector @return a bit vector containing the specified bits @see Bits#asStore(byte[])
[ "Creates", "a", "{", "@link", "BitVector", "}", "from", "the", "bits", "of", "a", "byte", "array", ".", "The", "byte", "array", "is", "in", "big", "-", "endian", "order", ".", "If", "the", "specified", "size", "is", "less", "than", "the", "number", "...
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/BitVector.java#L158-L164
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/lib/Chain.java
Chain.getChainElementConf
private static JobConf getChainElementConf(JobConf jobConf, String confKey) { JobConf conf; try { Stringifier<JobConf> stringifier = new DefaultStringifier<JobConf>(jobConf, JobConf.class); conf = stringifier.fromString(jobConf.get(confKey, null)); } catch (IOException ioex) { throw new RuntimeException(ioex); } // we have to do this because the Writable desearialization clears all // values set in the conf making not possible do do a new JobConf(jobConf) // in the creation of the conf above jobConf = new JobConf(jobConf); for(Map.Entry<String, String> entry : conf) { jobConf.set(entry.getKey(), entry.getValue()); } return jobConf; }
java
private static JobConf getChainElementConf(JobConf jobConf, String confKey) { JobConf conf; try { Stringifier<JobConf> stringifier = new DefaultStringifier<JobConf>(jobConf, JobConf.class); conf = stringifier.fromString(jobConf.get(confKey, null)); } catch (IOException ioex) { throw new RuntimeException(ioex); } // we have to do this because the Writable desearialization clears all // values set in the conf making not possible do do a new JobConf(jobConf) // in the creation of the conf above jobConf = new JobConf(jobConf); for(Map.Entry<String, String> entry : conf) { jobConf.set(entry.getKey(), entry.getValue()); } return jobConf; }
[ "private", "static", "JobConf", "getChainElementConf", "(", "JobConf", "jobConf", ",", "String", "confKey", ")", "{", "JobConf", "conf", ";", "try", "{", "Stringifier", "<", "JobConf", ">", "stringifier", "=", "new", "DefaultStringifier", "<", "JobConf", ">", ...
Creates a {@link JobConf} for one of the Maps or Reduce in the chain. <p/> It creates a new JobConf using the chain job's JobConf as base and adds to it the configuration properties for the chain element. The keys of the chain element jobConf have precedence over the given JobConf. @param jobConf the chain job's JobConf. @param confKey the key for chain element configuration serialized in the chain job's JobConf. @return a new JobConf aggregating the chain job's JobConf with the chain element configuration properties.
[ "Creates", "a", "{", "@link", "JobConf", "}", "for", "one", "of", "the", "Maps", "or", "Reduce", "in", "the", "chain", ".", "<p", "/", ">", "It", "creates", "a", "new", "JobConf", "using", "the", "chain", "job", "s", "JobConf", "as", "base", "and", ...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/lib/Chain.java#L122-L140
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
LeaderRole.commitCommand
private void commitCommand(CommandRequest request, CompletableFuture<CommandResponse> future) { final long term = raft.getTerm(); final long timestamp = System.currentTimeMillis(); CommandEntry command = new CommandEntry(term, timestamp, request.session(), request.sequenceNumber(), request.operation()); appendAndCompact(command) .whenCompleteAsync((entry, error) -> { if (error != null) { Throwable cause = Throwables.getRootCause(error); if (Throwables.getRootCause(error) instanceof StorageException.TooLarge) { log.warn("Failed to append command {}", command, cause); future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.PROTOCOL_ERROR) .build()); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } return; } // Replicate the command to followers. appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning()) { // If the command was successfully committed, apply it to the state machine. if (commitError == null) { raft.getServiceManager().<OperationResult>apply(entry.index()).whenComplete((r, e) -> { completeOperation(r, CommandResponse.builder(), e, future); }); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } }); }, raft.getThreadContext()); }
java
private void commitCommand(CommandRequest request, CompletableFuture<CommandResponse> future) { final long term = raft.getTerm(); final long timestamp = System.currentTimeMillis(); CommandEntry command = new CommandEntry(term, timestamp, request.session(), request.sequenceNumber(), request.operation()); appendAndCompact(command) .whenCompleteAsync((entry, error) -> { if (error != null) { Throwable cause = Throwables.getRootCause(error); if (Throwables.getRootCause(error) instanceof StorageException.TooLarge) { log.warn("Failed to append command {}", command, cause); future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.PROTOCOL_ERROR) .build()); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } return; } // Replicate the command to followers. appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning()) { // If the command was successfully committed, apply it to the state machine. if (commitError == null) { raft.getServiceManager().<OperationResult>apply(entry.index()).whenComplete((r, e) -> { completeOperation(r, CommandResponse.builder(), e, future); }); } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } } else { future.complete(CommandResponse.builder() .withStatus(RaftResponse.Status.ERROR) .withError(RaftError.Type.COMMAND_FAILURE) .build()); } }); }, raft.getThreadContext()); }
[ "private", "void", "commitCommand", "(", "CommandRequest", "request", ",", "CompletableFuture", "<", "CommandResponse", ">", "future", ")", "{", "final", "long", "term", "=", "raft", ".", "getTerm", "(", ")", ";", "final", "long", "timestamp", "=", "System", ...
Commits a command. @param request the command request @param future the command response future
[ "Commits", "a", "command", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java#L696-L743
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java
Resolve.isAccessible
public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) { return isAccessible(env, c, false); }
java
public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) { return isAccessible(env, c, false); }
[ "public", "boolean", "isAccessible", "(", "Env", "<", "AttrContext", ">", "env", ",", "TypeSymbol", "c", ")", "{", "return", "isAccessible", "(", "env", ",", "c", ",", "false", ")", ";", "}" ]
Is class accessible in given evironment? @param env The current environment. @param c The class whose accessibility is checked.
[ "Is", "class", "accessible", "in", "given", "evironment?" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L298-L300
amzn/ion-java
src/com/amazon/ion/util/IonTextUtils.java
IonTextUtils.printString
public static void printString(Appendable out, CharSequence text) throws IOException { if (text == null) { out.append("null.string"); } else { out.append('"'); printCodePoints(out, text, EscapeMode.ION_STRING); out.append('"'); } }
java
public static void printString(Appendable out, CharSequence text) throws IOException { if (text == null) { out.append("null.string"); } else { out.append('"'); printCodePoints(out, text, EscapeMode.ION_STRING); out.append('"'); } }
[ "public", "static", "void", "printString", "(", "Appendable", "out", ",", "CharSequence", "text", ")", "throws", "IOException", "{", "if", "(", "text", "==", "null", ")", "{", "out", ".", "append", "(", "\"null.string\"", ")", ";", "}", "else", "{", "out...
Prints characters as an ASCII-encoded Ion string, including surrounding double-quotes. If the {@code text} is null, this prints {@code null.string}. @param out the stream to receive the data. @param text the text to print; may be {@code null}. @throws IOException if the {@link Appendable} throws an exception. @throws IllegalArgumentException if the text contains invalid UTF-16 surrogates.
[ "Prints", "characters", "as", "an", "ASCII", "-", "encoded", "Ion", "string", "including", "surrounding", "double", "-", "quotes", ".", "If", "the", "{", "@code", "text", "}", "is", "null", "this", "prints", "{", "@code", "null", ".", "string", "}", "." ...
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonTextUtils.java#L405-L418
Netflix/governator
governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjector.java
LifecycleInjector.createStandardClasspathScanner
public static ClasspathScanner createStandardClasspathScanner(Collection<String> basePackages, List<Class<? extends Annotation>> additionalAnnotations) { List<Class<? extends Annotation>> annotations = Lists.newArrayList(); annotations.add(AutoBindSingleton.class); annotations.add(Inject.class); annotations.add(javax.inject.Inject.class); annotations.add(Resource.class); annotations.add(Resources.class); if ( additionalAnnotations != null ) { annotations.addAll(additionalAnnotations); } return new ClasspathScanner(basePackages, annotations); }
java
public static ClasspathScanner createStandardClasspathScanner(Collection<String> basePackages, List<Class<? extends Annotation>> additionalAnnotations) { List<Class<? extends Annotation>> annotations = Lists.newArrayList(); annotations.add(AutoBindSingleton.class); annotations.add(Inject.class); annotations.add(javax.inject.Inject.class); annotations.add(Resource.class); annotations.add(Resources.class); if ( additionalAnnotations != null ) { annotations.addAll(additionalAnnotations); } return new ClasspathScanner(basePackages, annotations); }
[ "public", "static", "ClasspathScanner", "createStandardClasspathScanner", "(", "Collection", "<", "String", ">", "basePackages", ",", "List", "<", "Class", "<", "?", "extends", "Annotation", ">", ">", "additionalAnnotations", ")", "{", "List", "<", "Class", "<", ...
If you need early access to the CLASSPATH scanner. For performance reasons, you should pass the scanner to the builder via {@link LifecycleInjectorBuilder#usingClasspathScanner(ClasspathScanner)}. @param basePackages packages to recursively scan @param additionalAnnotations any additional annotations to scan for @return scanner
[ "If", "you", "need", "early", "access", "to", "the", "CLASSPATH", "scanner", ".", "For", "performance", "reasons", "you", "should", "pass", "the", "scanner", "to", "the", "builder", "via", "{", "@link", "LifecycleInjectorBuilder#usingClasspathScanner", "(", "Class...
train
https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjector.java#L278-L291
Mangopay/mangopay2-java-sdk
src/main/java/com/mangopay/core/RestTool.java
RestTool.requestList
public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType) throws Exception { return requestList(classOfT, classOfTItem, urlMethod, requestType, null, null, null); }
java
public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType) throws Exception { return requestList(classOfT, classOfTItem, urlMethod, requestType, null, null, null); }
[ "public", "<", "T", "extends", "Dto", ">", "List", "<", "T", ">", "requestList", "(", "Class", "<", "T", "[", "]", ">", "classOfT", ",", "Class", "<", "T", ">", "classOfTItem", ",", "String", "urlMethod", ",", "String", "requestType", ")", "throws", ...
Makes a call to the MangoPay API. <p> This generic method handles calls targeting collections of <code>Dto</code> instances. In order to process single objects, use <code>request</code> method instead. @param <T> Type on behalf of which the request is being called. @param classOfT Type on behalf of which the request is being called. @param classOfTItem The class of single item in array. @param urlMethod Relevant method key. @param requestType HTTP request term. For lists should be always GET. @return The collection of Dto instances returned from API. @throws Exception
[ "Makes", "a", "call", "to", "the", "MangoPay", "API", ".", "<p", ">", "This", "generic", "method", "handles", "calls", "targeting", "collections", "of", "<code", ">", "Dto<", "/", "code", ">", "instances", ".", "In", "order", "to", "process", "single", "...
train
https://github.com/Mangopay/mangopay2-java-sdk/blob/037cecb44ea62def63b507817fd9961649151157/src/main/java/com/mangopay/core/RestTool.java#L258-L260
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/FeatureCollection.java
FeatureCollection.fromFeatures
public static FeatureCollection fromFeatures(@NonNull List<Feature> features) { return new FeatureCollection(TYPE, null, features); }
java
public static FeatureCollection fromFeatures(@NonNull List<Feature> features) { return new FeatureCollection(TYPE, null, features); }
[ "public", "static", "FeatureCollection", "fromFeatures", "(", "@", "NonNull", "List", "<", "Feature", ">", "features", ")", "{", "return", "new", "FeatureCollection", "(", "TYPE", ",", "null", ",", "features", ")", ";", "}" ]
Create a new instance of this class by giving the feature collection a list of {@link Feature}s. The list of features itself isn't null but it can empty and have a size of 0. @param features a list of features @return a new instance of this class defined by the values passed inside this static factory method @since 1.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "by", "giving", "the", "feature", "collection", "a", "list", "of", "{", "@link", "Feature", "}", "s", ".", "The", "list", "of", "features", "itself", "isn", "t", "null", "but", "it", "can", "empt...
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/FeatureCollection.java#L94-L96
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/dacl/DACLAssertor.java
DACLAssertor.doObjectFlagsMatch
private boolean doObjectFlagsMatch(final AceObjectFlags aceObjFlags, final AceObjectFlags assertionObjFlags) { boolean res = true; if (assertionObjFlags != null) { if (aceObjFlags != null && (aceObjFlags.asUInt() & assertionObjFlags.asUInt()) == assertionObjFlags.asUInt()) { res = true; } else { res = false; } } LOG.debug("doObjectFlagsMatch, result: {}", res); return res; }
java
private boolean doObjectFlagsMatch(final AceObjectFlags aceObjFlags, final AceObjectFlags assertionObjFlags) { boolean res = true; if (assertionObjFlags != null) { if (aceObjFlags != null && (aceObjFlags.asUInt() & assertionObjFlags.asUInt()) == assertionObjFlags.asUInt()) { res = true; } else { res = false; } } LOG.debug("doObjectFlagsMatch, result: {}", res); return res; }
[ "private", "boolean", "doObjectFlagsMatch", "(", "final", "AceObjectFlags", "aceObjFlags", ",", "final", "AceObjectFlags", "assertionObjFlags", ")", "{", "boolean", "res", "=", "true", ";", "if", "(", "assertionObjFlags", "!=", "null", ")", "{", "if", "(", "aceO...
Compares the AceObjectFlags attribute of an ACE against that of an AceAssertion. If the {@code assertionObjFlags} are null, a true result is returned. @param aceObjFlags object flags from the ACE @param assertionObjFlags object flags from the AceAssertion @return true if match, false if not
[ "Compares", "the", "AceObjectFlags", "attribute", "of", "an", "ACE", "against", "that", "of", "an", "AceAssertion", ".", "If", "the", "{", "@code", "assertionObjFlags", "}", "are", "null", "a", "true", "result", "is", "returned", "." ]
train
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/dacl/DACLAssertor.java#L371-L383
josesamuel/remoter
remoter/src/main/java/remoter/compiler/builder/ParamBuilder.java
ParamBuilder.writeArrayOutParamsToProxy
protected void writeArrayOutParamsToProxy(VariableElement param, MethodSpec.Builder methodBuilder) { methodBuilder.beginControlFlow("if (" + param.getSimpleName() + " == null)"); methodBuilder.addStatement("data.writeInt(-1)"); methodBuilder.endControlFlow(); methodBuilder.beginControlFlow("else"); methodBuilder.addStatement("data.writeInt(" + param.getSimpleName() + ".length)"); methodBuilder.endControlFlow(); }
java
protected void writeArrayOutParamsToProxy(VariableElement param, MethodSpec.Builder methodBuilder) { methodBuilder.beginControlFlow("if (" + param.getSimpleName() + " == null)"); methodBuilder.addStatement("data.writeInt(-1)"); methodBuilder.endControlFlow(); methodBuilder.beginControlFlow("else"); methodBuilder.addStatement("data.writeInt(" + param.getSimpleName() + ".length)"); methodBuilder.endControlFlow(); }
[ "protected", "void", "writeArrayOutParamsToProxy", "(", "VariableElement", "param", ",", "MethodSpec", ".", "Builder", "methodBuilder", ")", "{", "methodBuilder", ".", "beginControlFlow", "(", "\"if (\"", "+", "param", ".", "getSimpleName", "(", ")", "+", "\" == nul...
Called to generate code that writes the out params for array type
[ "Called", "to", "generate", "code", "that", "writes", "the", "out", "params", "for", "array", "type" ]
train
https://github.com/josesamuel/remoter/blob/007401868c319740d40134ebc07c3406988f9a86/remoter/src/main/java/remoter/compiler/builder/ParamBuilder.java#L76-L83
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
SpringApplication.configurePropertySources
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { sources.addLast( new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource( "springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } }
java
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) { MutablePropertySources sources = environment.getPropertySources(); if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) { sources.addLast( new MapPropertySource("defaultProperties", this.defaultProperties)); } if (this.addCommandLineProperties && args.length > 0) { String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME; if (sources.contains(name)) { PropertySource<?> source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); composite.addPropertySource(new SimpleCommandLinePropertySource( "springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } else { sources.addFirst(new SimpleCommandLinePropertySource(args)); } } }
[ "protected", "void", "configurePropertySources", "(", "ConfigurableEnvironment", "environment", ",", "String", "[", "]", "args", ")", "{", "MutablePropertySources", "sources", "=", "environment", ".", "getPropertySources", "(", ")", ";", "if", "(", "this", ".", "d...
Add, remove or re-order any {@link PropertySource}s in this application's environment. @param environment this application's environment @param args arguments passed to the {@code run} method @see #configureEnvironment(ConfigurableEnvironment, String[])
[ "Add", "remove", "or", "re", "-", "order", "any", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java#L508-L529
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/url/URLHelper.java
URLHelper.getAsURL
@Nullable public static URL getAsURL (@Nullable final String sURL, final boolean bWhine) { if (StringHelper.hasText (sURL)) try { return new URL (sURL); } catch (final MalformedURLException ex) { // fall-through if (bWhine && GlobalDebug.isDebugMode ()) if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Debug warn: failed to convert '" + sURL + "' to a URL!"); } return null; }
java
@Nullable public static URL getAsURL (@Nullable final String sURL, final boolean bWhine) { if (StringHelper.hasText (sURL)) try { return new URL (sURL); } catch (final MalformedURLException ex) { // fall-through if (bWhine && GlobalDebug.isDebugMode ()) if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Debug warn: failed to convert '" + sURL + "' to a URL!"); } return null; }
[ "@", "Nullable", "public", "static", "URL", "getAsURL", "(", "@", "Nullable", "final", "String", "sURL", ",", "final", "boolean", "bWhine", ")", "{", "if", "(", "StringHelper", ".", "hasText", "(", "sURL", ")", ")", "try", "{", "return", "new", "URL", ...
Get the passed String as an URL. If the string is empty or not an URL <code>null</code> is returned. @param sURL Source URL. May be <code>null</code>. @param bWhine <code>true</code> to debug log if conversion failed @return <code>null</code> if the passed URL is empty or invalid.
[ "Get", "the", "passed", "String", "as", "an", "URL", ".", "If", "the", "string", "is", "empty", "or", "not", "an", "URL", "<code", ">", "null<", "/", "code", ">", "is", "returned", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/url/URLHelper.java#L751-L767
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2/SessionsClient.java
SessionsClient.detectIntent
public final DetectIntentResponse detectIntent(String session, QueryInput queryInput) { DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session).setQueryInput(queryInput).build(); return detectIntent(request); }
java
public final DetectIntentResponse detectIntent(String session, QueryInput queryInput) { DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session).setQueryInput(queryInput).build(); return detectIntent(request); }
[ "public", "final", "DetectIntentResponse", "detectIntent", "(", "String", "session", ",", "QueryInput", "queryInput", ")", "{", "DetectIntentRequest", "request", "=", "DetectIntentRequest", ".", "newBuilder", "(", ")", ".", "setSession", "(", "session", ")", ".", ...
Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries. <p>Sample code: <pre><code> try (SessionsClient sessionsClient = SessionsClient.create()) { SessionName session = SessionName.of("[PROJECT]", "[SESSION]"); QueryInput queryInput = QueryInput.newBuilder().build(); DetectIntentResponse response = sessionsClient.detectIntent(session.toString(), queryInput); } </code></pre> @param session Required. The name of the session this query is sent to. Format: `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API caller to choose an appropriate session ID. It can be a random number or some type of user identifier (preferably hashed). The length of the session ID must not exceed 36 bytes. @param queryInput Required. The input specification. It can be set to: <p>1. an audio config which instructs the speech recognizer how to process the speech audio, <p>2. a conversational query in the form of text, or <p>3. an event that specifies which intent to trigger. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Processes", "a", "natural", "language", "query", "and", "returns", "structured", "actionable", "data", "as", "a", "result", ".", "This", "method", "is", "not", "idempotent", "because", "it", "may", "cause", "contexts", "and", "session", "entity", "types", "to...
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2/SessionsClient.java#L214-L219
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java
ImageMiscOps.fillUniform
public static void fillUniform(InterleavedS32 img, Random rand , int min , int max) { int range = max-min; int[] data = img.data; for (int y = 0; y < img.height; y++) { int index = img.getStartIndex() + y * img.getStride(); int end = index + img.width*img.numBands; for (; index < end; index++) { data[index] = (rand.nextInt(range)+min); } } }
java
public static void fillUniform(InterleavedS32 img, Random rand , int min , int max) { int range = max-min; int[] data = img.data; for (int y = 0; y < img.height; y++) { int index = img.getStartIndex() + y * img.getStride(); int end = index + img.width*img.numBands; for (; index < end; index++) { data[index] = (rand.nextInt(range)+min); } } }
[ "public", "static", "void", "fillUniform", "(", "InterleavedS32", "img", ",", "Random", "rand", ",", "int", "min", ",", "int", "max", ")", "{", "int", "range", "=", "max", "-", "min", ";", "int", "[", "]", "data", "=", "img", ".", "data", ";", "for...
Sets each value in the image to a value drawn from an uniform distribution that has a range of min &le; X &lt; max. @param img Image which is to be filled. Modified, @param rand Random number generator @param min Minimum value of the distribution, inclusive @param max Maximum value of the distribution, exclusive
[ "Sets", "each", "value", "in", "the", "image", "to", "a", "value", "drawn", "from", "an", "uniform", "distribution", "that", "has", "a", "range", "of", "min", "&le", ";", "X", "&lt", ";", "max", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java#L1399-L1411
Esri/geometry-api-java
src/main/java/com/esri/core/geometry/MultiPathImpl.java
MultiPathImpl.addEnvelope
public void addEnvelope(Envelope2D envSrc, boolean bReverse) { boolean bWasEmpty = m_pointCount == 0; startPath(envSrc.xmin, envSrc.ymin); if (bReverse) { lineTo(envSrc.xmax, envSrc.ymin); lineTo(envSrc.xmax, envSrc.ymax); lineTo(envSrc.xmin, envSrc.ymax); } else { lineTo(envSrc.xmin, envSrc.ymax); lineTo(envSrc.xmax, envSrc.ymax); lineTo(envSrc.xmax, envSrc.ymin); } closePathWithLine(); m_bPathStarted = false; if (bWasEmpty && !bReverse) { _setDirtyFlag(DirtyFlags.DirtyIsEnvelope, false);// now we no(sic?) // the polypath // is envelope } }
java
public void addEnvelope(Envelope2D envSrc, boolean bReverse) { boolean bWasEmpty = m_pointCount == 0; startPath(envSrc.xmin, envSrc.ymin); if (bReverse) { lineTo(envSrc.xmax, envSrc.ymin); lineTo(envSrc.xmax, envSrc.ymax); lineTo(envSrc.xmin, envSrc.ymax); } else { lineTo(envSrc.xmin, envSrc.ymax); lineTo(envSrc.xmax, envSrc.ymax); lineTo(envSrc.xmax, envSrc.ymin); } closePathWithLine(); m_bPathStarted = false; if (bWasEmpty && !bReverse) { _setDirtyFlag(DirtyFlags.DirtyIsEnvelope, false);// now we no(sic?) // the polypath // is envelope } }
[ "public", "void", "addEnvelope", "(", "Envelope2D", "envSrc", ",", "boolean", "bReverse", ")", "{", "boolean", "bWasEmpty", "=", "m_pointCount", "==", "0", ";", "startPath", "(", "envSrc", ".", "xmin", ",", "envSrc", ".", "ymin", ")", ";", "if", "(", "bR...
adds a rectangular closed Path to the MultiPathImpl. @param envSrc is the source rectangle. @param bReverse Creates reversed path.
[ "adds", "a", "rectangular", "closed", "Path", "to", "the", "MultiPathImpl", "." ]
train
https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/MultiPathImpl.java#L624-L646
stripe/stripe-java
src/main/java/com/stripe/Stripe.java
Stripe.setAppInfo
public static void setAppInfo(String name, String version, String url, String partnerId) { if (appInfo == null) { appInfo = new HashMap<String, String>(); } appInfo.put("name", name); appInfo.put("version", version); appInfo.put("url", url); appInfo.put("partner_id", partnerId); }
java
public static void setAppInfo(String name, String version, String url, String partnerId) { if (appInfo == null) { appInfo = new HashMap<String, String>(); } appInfo.put("name", name); appInfo.put("version", version); appInfo.put("url", url); appInfo.put("partner_id", partnerId); }
[ "public", "static", "void", "setAppInfo", "(", "String", "name", ",", "String", "version", ",", "String", "url", ",", "String", "partnerId", ")", "{", "if", "(", "appInfo", "==", "null", ")", "{", "appInfo", "=", "new", "HashMap", "<", "String", ",", "...
Sets information about your application. The information is passed along to Stripe. @param name Name of your application (e.g. "MyAwesomeApp") @param version Version of your application (e.g. "1.2.34") @param url Website for your application (e.g. "https://myawesomeapp.info") @param partnerId Your Stripe Partner ID (e.g. "pp_partner_1234")
[ "Sets", "information", "about", "your", "application", ".", "The", "information", "is", "passed", "along", "to", "Stripe", "." ]
train
https://github.com/stripe/stripe-java/blob/acfa8becef3e73bfe3e9d8880bea3f3f30dadeac/src/main/java/com/stripe/Stripe.java#L170-L179
facebookarchive/hadoop-20
src/contrib/index/src/java/org/apache/hadoop/contrib/index/lucene/RAMDirectoryUtil.java
RAMDirectoryUtil.readRAMFiles
public static void readRAMFiles(DataInput in, RAMDirectory dir) throws IOException { int numFiles = in.readInt(); for (int i = 0; i < numFiles; i++) { String name = Text.readString(in); long length = in.readLong(); if (length > 0) { // can we avoid the extra copy? IndexOutput output = null; try { output = dir.createOutput(name); int position = 0; byte[] buffer = new byte[BUFFER_SIZE]; while (position < length) { int len = position + BUFFER_SIZE <= length ? BUFFER_SIZE : (int) (length - position); in.readFully(buffer, 0, len); output.writeBytes(buffer, 0, len); position += len; } } finally { if (output != null) { output.close(); } } } } }
java
public static void readRAMFiles(DataInput in, RAMDirectory dir) throws IOException { int numFiles = in.readInt(); for (int i = 0; i < numFiles; i++) { String name = Text.readString(in); long length = in.readLong(); if (length > 0) { // can we avoid the extra copy? IndexOutput output = null; try { output = dir.createOutput(name); int position = 0; byte[] buffer = new byte[BUFFER_SIZE]; while (position < length) { int len = position + BUFFER_SIZE <= length ? BUFFER_SIZE : (int) (length - position); in.readFully(buffer, 0, len); output.writeBytes(buffer, 0, len); position += len; } } finally { if (output != null) { output.close(); } } } } }
[ "public", "static", "void", "readRAMFiles", "(", "DataInput", "in", ",", "RAMDirectory", "dir", ")", "throws", "IOException", "{", "int", "numFiles", "=", "in", ".", "readInt", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numFiles",...
Read a number of files from a data input to a ram directory. @param in the data input @param dir the ram directory @throws IOException
[ "Read", "a", "number", "of", "files", "from", "a", "data", "input", "to", "a", "ram", "directory", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/index/src/java/org/apache/hadoop/contrib/index/lucene/RAMDirectoryUtil.java#L85-L117
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/Config.java
Config.setExecutorConfigs
public Config setExecutorConfigs(Map<String, ExecutorConfig> executorConfigs) { this.executorConfigs.clear(); this.executorConfigs.putAll(executorConfigs); for (Entry<String, ExecutorConfig> entry : executorConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public Config setExecutorConfigs(Map<String, ExecutorConfig> executorConfigs) { this.executorConfigs.clear(); this.executorConfigs.putAll(executorConfigs); for (Entry<String, ExecutorConfig> entry : executorConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "Config", "setExecutorConfigs", "(", "Map", "<", "String", ",", "ExecutorConfig", ">", "executorConfigs", ")", "{", "this", ".", "executorConfigs", ".", "clear", "(", ")", ";", "this", ".", "executorConfigs", ".", "putAll", "(", "executorConfigs", ")...
Sets the map of executor configurations, mapped by config name. The config name may be a pattern with which the configuration will be obtained in the future. @param executorConfigs the executor configuration map to set @return this config instance
[ "Sets", "the", "map", "of", "executor", "configurations", "mapped", "by", "config", "name", ".", "The", "config", "name", "may", "be", "a", "pattern", "with", "which", "the", "configuration", "will", "be", "obtained", "in", "the", "future", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L2153-L2160
alkacon/opencms-core
src/org/opencms/jsp/CmsJspActionElement.java
CmsJspActionElement.getMessages
public CmsMessages getMessages( String bundleName, String language, String country, String variant, String defaultLanguage) { try { if ((defaultLanguage != null) && CmsStringUtil.isEmpty(language)) { language = defaultLanguage; } if (language == null) { language = ""; } if (country == null) { country = ""; } if (variant == null) { variant = ""; } return getMessages(bundleName, new Locale(language, country, variant)); } catch (Throwable t) { handleException(t); } return null; }
java
public CmsMessages getMessages( String bundleName, String language, String country, String variant, String defaultLanguage) { try { if ((defaultLanguage != null) && CmsStringUtil.isEmpty(language)) { language = defaultLanguage; } if (language == null) { language = ""; } if (country == null) { country = ""; } if (variant == null) { variant = ""; } return getMessages(bundleName, new Locale(language, country, variant)); } catch (Throwable t) { handleException(t); } return null; }
[ "public", "CmsMessages", "getMessages", "(", "String", "bundleName", ",", "String", "language", ",", "String", "country", ",", "String", "variant", ",", "String", "defaultLanguage", ")", "{", "try", "{", "if", "(", "(", "defaultLanguage", "!=", "null", ")", ...
Generates an initialized instance of {@link CmsMessages} for convenient access to localized resource bundles.<p> @param bundleName the name of the ResourceBundle to use @param language language identifier for the locale of the bundle @param country 2 letter country code for the locale of the bundle @param variant a vendor or browser-specific variant code @param defaultLanguage default for the language, will be used if language is null or empty String "", and defaultLanguage is not null @return CmsMessages a message bundle initialized with the provided values @see java.util.ResourceBundle @see org.opencms.i18n.CmsMessages
[ "Generates", "an", "initialized", "instance", "of", "{", "@link", "CmsMessages", "}", "for", "convenient", "access", "to", "localized", "resource", "bundles", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspActionElement.java#L321-L346
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/InventoryResultItem.java
InventoryResultItem.withContent
public InventoryResultItem withContent(java.util.Map<String, String>... content) { if (this.content == null) { setContent(new com.amazonaws.internal.SdkInternalList<java.util.Map<String, String>>(content.length)); } for (java.util.Map<String, String> ele : content) { this.content.add(ele); } return this; }
java
public InventoryResultItem withContent(java.util.Map<String, String>... content) { if (this.content == null) { setContent(new com.amazonaws.internal.SdkInternalList<java.util.Map<String, String>>(content.length)); } for (java.util.Map<String, String> ele : content) { this.content.add(ele); } return this; }
[ "public", "InventoryResultItem", "withContent", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "...", "content", ")", "{", "if", "(", "this", ".", "content", "==", "null", ")", "{", "setContent", "(", "new", "com", ".", "amazo...
<p> Contains all the inventory data of the item type. Results include attribute names and values. </p> <p> <b>NOTE:</b> This method appends the values to the existing list (if any). Use {@link #setContent(java.util.Collection)} or {@link #withContent(java.util.Collection)} if you want to override the existing values. </p> @param content Contains all the inventory data of the item type. Results include attribute names and values. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Contains", "all", "the", "inventory", "data", "of", "the", "item", "type", ".", "Results", "include", "attribute", "names", "and", "values", ".", "<", "/", "p", ">", "<p", ">", "<b", ">", "NOTE", ":", "<", "/", "b", ">", "This", "method...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/InventoryResultItem.java#L284-L292
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmElements.java
XsdAsmElements.generateMethodsForElement
static void generateMethodsForElement(ClassWriter classWriter, XsdElement child, String classType, String apiName) { generateMethodsForElement(classWriter, child.getName(), classType, apiName, new String[]{}); }
java
static void generateMethodsForElement(ClassWriter classWriter, XsdElement child, String classType, String apiName) { generateMethodsForElement(classWriter, child.getName(), classType, apiName, new String[]{}); }
[ "static", "void", "generateMethodsForElement", "(", "ClassWriter", "classWriter", ",", "XsdElement", "child", ",", "String", "classType", ",", "String", "apiName", ")", "{", "generateMethodsForElement", "(", "classWriter", ",", "child", ".", "getName", "(", ")", "...
Generates the methods in a given class for a given child that the class is allowed to have. @param classWriter The {@link ClassWriter} where the method will be written. @param child The child of the element which generated the class. Their name represents a method. @param classType The type of the class which contains the children elements. @param apiName The name of the generated fluent interface.
[ "Generates", "the", "methods", "in", "a", "given", "class", "for", "a", "given", "child", "that", "the", "class", "is", "allowed", "to", "have", "." ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmElements.java#L263-L265
borball/weixin-sdk
weixin-qydev/src/main/java/com/riversoft/weixin/qy/media/Medias.java
Medias.upload
public String upload(MediaType type, InputStream inputStream, String fileName) { if (type == MediaType.mpnews) { throw new com.riversoft.weixin.common.exception.WxRuntimeException(999, "unsupported media type: " + type.name()); } String url = WxEndpoint.get("url.media.upload"); String response = wxClient.post(String.format(url, type.name()), inputStream, fileName); //为什么这个成功返回的response没有error code,和其他的格格不入,临时工弄的? Map<String, Object> result = JsonMapper.defaultMapper().json2Map(response); if (result.containsKey("media_id")) { return result.get("media_id").toString(); } else { logger.warn("media upload failed: {}", response); throw new WxRuntimeException(998, response); } }
java
public String upload(MediaType type, InputStream inputStream, String fileName) { if (type == MediaType.mpnews) { throw new com.riversoft.weixin.common.exception.WxRuntimeException(999, "unsupported media type: " + type.name()); } String url = WxEndpoint.get("url.media.upload"); String response = wxClient.post(String.format(url, type.name()), inputStream, fileName); //为什么这个成功返回的response没有error code,和其他的格格不入,临时工弄的? Map<String, Object> result = JsonMapper.defaultMapper().json2Map(response); if (result.containsKey("media_id")) { return result.get("media_id").toString(); } else { logger.warn("media upload failed: {}", response); throw new WxRuntimeException(998, response); } }
[ "public", "String", "upload", "(", "MediaType", "type", ",", "InputStream", "inputStream", ",", "String", "fileName", ")", "{", "if", "(", "type", "==", "MediaType", ".", "mpnews", ")", "{", "throw", "new", "com", ".", "riversoft", ".", "weixin", ".", "c...
上传临时图片,语音,视频和普通文件 @param type 临时素材类型:只能是 图片,语音,视频和普通文件 @param inputStream 临时素材流 @param fileName 临时素材文件名 @return 返回临时素材metaId
[ "上传临时图片,语音,视频和普通文件" ]
train
https://github.com/borball/weixin-sdk/blob/32bf5e45cdd8d0d28074e83954e1ec62dcf25cb7/weixin-qydev/src/main/java/com/riversoft/weixin/qy/media/Medias.java#L49-L65
authorjapps/zerocode
core/src/main/java/org/jsmart/zerocode/core/engine/executor/JavaExecutorImpl.java
JavaExecutorImpl.execute
public Object execute(String qualifiedClassName, String methodName, Object... args) { try { return findMethod(qualifiedClassName, methodName) .invoke(injector.getInstance(getClass(qualifiedClassName)), args); } catch (Exception e) { LOGGER.error("Exception encountered while executing java method" + e); throw new RuntimeException(e); } }
java
public Object execute(String qualifiedClassName, String methodName, Object... args) { try { return findMethod(qualifiedClassName, methodName) .invoke(injector.getInstance(getClass(qualifiedClassName)), args); } catch (Exception e) { LOGGER.error("Exception encountered while executing java method" + e); throw new RuntimeException(e); } }
[ "public", "Object", "execute", "(", "String", "qualifiedClassName", ",", "String", "methodName", ",", "Object", "...", "args", ")", "{", "try", "{", "return", "findMethod", "(", "qualifiedClassName", ",", "methodName", ")", ".", "invoke", "(", "injector", ".",...
/* @param qualifiedClassName : including package name: e.g. "AddService" @param methodName @param args @return
[ "/", "*" ]
train
https://github.com/authorjapps/zerocode/blob/d66a3e8778d2eb5e4f0006bfcccfc0922ceb7cef/core/src/main/java/org/jsmart/zerocode/core/engine/executor/JavaExecutorImpl.java#L31-L41
liferay/com-liferay-commerce
commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationAttachmentPersistenceImpl.java
CommerceNotificationAttachmentPersistenceImpl.findByUUID_G
@Override public CommerceNotificationAttachment findByUUID_G(String uuid, long groupId) throws NoSuchNotificationAttachmentException { CommerceNotificationAttachment commerceNotificationAttachment = fetchByUUID_G(uuid, groupId); if (commerceNotificationAttachment == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchNotificationAttachmentException(msg.toString()); } return commerceNotificationAttachment; }
java
@Override public CommerceNotificationAttachment findByUUID_G(String uuid, long groupId) throws NoSuchNotificationAttachmentException { CommerceNotificationAttachment commerceNotificationAttachment = fetchByUUID_G(uuid, groupId); if (commerceNotificationAttachment == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchNotificationAttachmentException(msg.toString()); } return commerceNotificationAttachment; }
[ "@", "Override", "public", "CommerceNotificationAttachment", "findByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchNotificationAttachmentException", "{", "CommerceNotificationAttachment", "commerceNotificationAttachment", "=", "fetchByUUID_G", "("...
Returns the commerce notification attachment where uuid = &#63; and groupId = &#63; or throws a {@link NoSuchNotificationAttachmentException} if it could not be found. @param uuid the uuid @param groupId the group ID @return the matching commerce notification attachment @throws NoSuchNotificationAttachmentException if a matching commerce notification attachment could not be found
[ "Returns", "the", "commerce", "notification", "attachment", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchNotificationAttachmentException", "}", "if", "it", "could", "not", "be", "found", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationAttachmentPersistenceImpl.java#L680-L707
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbCredits.java
TmdbCredits.getCreditInfo
public CreditInfo getCreditInfo(String creditId, String language) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, creditId); parameters.add(Param.LANGUAGE, language); URL url = new ApiUrl(apiKey, MethodBase.CREDIT).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, CreditInfo.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get credit info", url, ex); } }
java
public CreditInfo getCreditInfo(String creditId, String language) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, creditId); parameters.add(Param.LANGUAGE, language); URL url = new ApiUrl(apiKey, MethodBase.CREDIT).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, CreditInfo.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get credit info", url, ex); } }
[ "public", "CreditInfo", "getCreditInfo", "(", "String", "creditId", ",", "String", "language", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID",...
Get the detailed information about a particular credit record. <p> This is currently only supported with the new credit model found in TV. <br/> These IDs can be found from any TV credit response as well as the TV_credits and combined_credits methods for people. <br/> The episodes object returns a list of episodes and are generally going to be guest stars. <br/> The season array will return a list of season numbers. <br/> Season credits are credits that were marked with the "add to every season" option in the editing interface and are assumed to be "season regulars". @param creditId @param language @return @throws MovieDbException
[ "Get", "the", "detailed", "information", "about", "a", "particular", "credit", "record", ".", "<p", ">", "This", "is", "currently", "only", "supported", "with", "the", "new", "credit", "model", "found", "in", "TV", ".", "<br", "/", ">", "These", "IDs", "...
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbCredits.java#L69-L82
librato/metrics-librato
src/main/java/com/librato/metrics/reporter/SourceInformation.java
SourceInformation.from
public static SourceInformation from(Pattern sourceRegex, String name) { if (sourceRegex == null) { return new SourceInformation(null, name); } Matcher matcher = sourceRegex.matcher(name); if (matcher.groupCount() != 1) { log.error("Source regex matcher must define a group"); return new SourceInformation(null, name); } if (!matcher.find()) { return new SourceInformation(null, name); } String source = matcher.group(1); int endPos = matcher.toMatchResult().end(); if (endPos >= name.length()) { // the source matched the whole metric name, probably in error. log.error("Source '{}' matched the whole metric name. Metric name cannot be empty"); return new SourceInformation(null, name); } String newName = name.substring(endPos); return new SourceInformation(source, newName); }
java
public static SourceInformation from(Pattern sourceRegex, String name) { if (sourceRegex == null) { return new SourceInformation(null, name); } Matcher matcher = sourceRegex.matcher(name); if (matcher.groupCount() != 1) { log.error("Source regex matcher must define a group"); return new SourceInformation(null, name); } if (!matcher.find()) { return new SourceInformation(null, name); } String source = matcher.group(1); int endPos = matcher.toMatchResult().end(); if (endPos >= name.length()) { // the source matched the whole metric name, probably in error. log.error("Source '{}' matched the whole metric name. Metric name cannot be empty"); return new SourceInformation(null, name); } String newName = name.substring(endPos); return new SourceInformation(source, newName); }
[ "public", "static", "SourceInformation", "from", "(", "Pattern", "sourceRegex", ",", "String", "name", ")", "{", "if", "(", "sourceRegex", "==", "null", ")", "{", "return", "new", "SourceInformation", "(", "null", ",", "name", ")", ";", "}", "Matcher", "ma...
If the pattern is not null, it will attempt to match against the supplied name to pull out the source.
[ "If", "the", "pattern", "is", "not", "null", "it", "will", "attempt", "to", "match", "against", "the", "supplied", "name", "to", "pull", "out", "the", "source", "." ]
train
https://github.com/librato/metrics-librato/blob/10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6/src/main/java/com/librato/metrics/reporter/SourceInformation.java#L18-L39
evernote/android-state
library/src/main/java/com/evernote/android/state/StateSaverImpl.java
StateSaverImpl.saveInstanceState
@NonNull /*package*/ <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) { Injector.View<T> injector = safeGet(target, Injector.View.DEFAULT); return injector.save(target, state); }
java
@NonNull /*package*/ <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) { Injector.View<T> injector = safeGet(target, Injector.View.DEFAULT); return injector.save(target, state); }
[ "@", "NonNull", "/*package*/", "<", "T", "extends", "View", ">", "Parcelable", "saveInstanceState", "(", "@", "NonNull", "T", "target", ",", "@", "Nullable", "Parcelable", "state", ")", "{", "Injector", ".", "View", "<", "T", ">", "injector", "=", "safeGet...
Save the state of the given view and the other state inside of the returned {@link Parcelable}. @param target The view containing fields annotated with {@link State}. @param state The super state of the parent class of the view. Usually it isn't {@code null}. @return A parcelable containing the view's state and its super state.
[ "Save", "the", "state", "of", "the", "given", "view", "and", "the", "other", "state", "inside", "of", "the", "returned", "{", "@link", "Parcelable", "}", "." ]
train
https://github.com/evernote/android-state/blob/6d56c0c5709f330324ec23d39c3f70c9d59bf6d3/library/src/main/java/com/evernote/android/state/StateSaverImpl.java#L96-L100
nabedge/mixer2
src/main/java/org/mixer2/xhtml/AbstractJaxb.java
AbstractJaxb.getById
@SuppressWarnings("unchecked") public <T extends AbstractJaxb> T getById(String id, Class<T> tagType) throws TagTypeUnmatchException { Object obj = GetByIdUtil.getById(id, this); if (obj != null && !obj.getClass().isAssignableFrom(tagType)) { throw new TagTypeUnmatchException(tagType.getClass(), obj.getClass()); } return (T) obj; }
java
@SuppressWarnings("unchecked") public <T extends AbstractJaxb> T getById(String id, Class<T> tagType) throws TagTypeUnmatchException { Object obj = GetByIdUtil.getById(id, this); if (obj != null && !obj.getClass().isAssignableFrom(tagType)) { throw new TagTypeUnmatchException(tagType.getClass(), obj.getClass()); } return (T) obj; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "AbstractJaxb", ">", "T", "getById", "(", "String", "id", ",", "Class", "<", "T", ">", "tagType", ")", "throws", "TagTypeUnmatchException", "{", "Object", "obj", "=", "GetById...
<p> get tag that has specified id attribute. You don't need to cast() because you can specify the tag type. </p> <pre> // sample: get a Div tag having id=&quot;foo&quot; attribute. html.getById(&quot;foo&quot;, Div.class); </pre> @param id @param tagType @return @throws TagTypeUnmatchException
[ "<p", ">", "get", "tag", "that", "has", "specified", "id", "attribute", ".", "You", "don", "t", "need", "to", "cast", "()", "because", "you", "can", "specify", "the", "tag", "type", ".", "<", "/", "p", ">" ]
train
https://github.com/nabedge/mixer2/blob/8c2db27cfcd65bf0b1e0242ef9362ebd8033777c/src/main/java/org/mixer2/xhtml/AbstractJaxb.java#L77-L86
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/Jimfs.java
Jimfs.newFileSystem
public static FileSystem newFileSystem(String name, Configuration configuration) { try { URI uri = new URI(URI_SCHEME, name, null, null); return newFileSystem(uri, configuration); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
java
public static FileSystem newFileSystem(String name, Configuration configuration) { try { URI uri = new URI(URI_SCHEME, name, null, null); return newFileSystem(uri, configuration); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
[ "public", "static", "FileSystem", "newFileSystem", "(", "String", "name", ",", "Configuration", "configuration", ")", "{", "try", "{", "URI", "uri", "=", "new", "URI", "(", "URI_SCHEME", ",", "name", ",", "null", ",", "null", ")", ";", "return", "newFileSy...
Creates a new in-memory file system with the given configuration. <p>The returned file system uses the given name as the host part of its URI and the URIs of paths in the file system. For example, given the name {@code my-file-system}, the file system's URI will be {@code jimfs://my-file-system} and the URI of the path {@code /foo/bar} will be {@code jimfs://my-file-system/foo/bar}.
[ "Creates", "a", "new", "in", "-", "memory", "file", "system", "with", "the", "given", "configuration", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/Jimfs.java#L130-L137
Azure/azure-sdk-for-java
recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupUsageSummariesInner.java
BackupUsageSummariesInner.listAsync
public Observable<List<BackupManagementUsageInner>> listAsync(String vaultName, String resourceGroupName) { return listWithServiceResponseAsync(vaultName, resourceGroupName).map(new Func1<ServiceResponse<List<BackupManagementUsageInner>>, List<BackupManagementUsageInner>>() { @Override public List<BackupManagementUsageInner> call(ServiceResponse<List<BackupManagementUsageInner>> response) { return response.body(); } }); }
java
public Observable<List<BackupManagementUsageInner>> listAsync(String vaultName, String resourceGroupName) { return listWithServiceResponseAsync(vaultName, resourceGroupName).map(new Func1<ServiceResponse<List<BackupManagementUsageInner>>, List<BackupManagementUsageInner>>() { @Override public List<BackupManagementUsageInner> call(ServiceResponse<List<BackupManagementUsageInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "BackupManagementUsageInner", ">", ">", "listAsync", "(", "String", "vaultName", ",", "String", "resourceGroupName", ")", "{", "return", "listWithServiceResponseAsync", "(", "vaultName", ",", "resourceGroupName", ")", ".", "...
Fetches the backup management usage summaries of the vault. @param vaultName The name of the recovery services vault. @param resourceGroupName The name of the resource group where the recovery services vault is present. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;BackupManagementUsageInner&gt; object
[ "Fetches", "the", "backup", "management", "usage", "summaries", "of", "the", "vault", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupUsageSummariesInner.java#L96-L103
apache/groovy
src/main/java/org/codehaus/groovy/transform/trait/TraitComposer.java
TraitComposer.createSuperForwarder
private static void createSuperForwarder(ClassNode targetNode, MethodNode forwarder, final Map<String,ClassNode> genericsSpec) { List<ClassNode> interfaces = new ArrayList<ClassNode>(Traits.collectAllInterfacesReverseOrder(targetNode, new LinkedHashSet<ClassNode>())); String name = forwarder.getName(); Parameter[] forwarderParameters = forwarder.getParameters(); LinkedHashSet<ClassNode> traits = new LinkedHashSet<ClassNode>(); List<MethodNode> superForwarders = new LinkedList<MethodNode>(); for (ClassNode node : interfaces) { if (Traits.isTrait(node)) { MethodNode method = node.getDeclaredMethod(name, forwarderParameters); if (method!=null) { // a similar method exists, we need a super bridge // trait$super$foo(Class currentTrait, ...) traits.add(node); superForwarders.add(method); } } } for (MethodNode superForwarder : superForwarders) { doCreateSuperForwarder(targetNode, superForwarder, traits.toArray(ClassNode.EMPTY_ARRAY), genericsSpec); } }
java
private static void createSuperForwarder(ClassNode targetNode, MethodNode forwarder, final Map<String,ClassNode> genericsSpec) { List<ClassNode> interfaces = new ArrayList<ClassNode>(Traits.collectAllInterfacesReverseOrder(targetNode, new LinkedHashSet<ClassNode>())); String name = forwarder.getName(); Parameter[] forwarderParameters = forwarder.getParameters(); LinkedHashSet<ClassNode> traits = new LinkedHashSet<ClassNode>(); List<MethodNode> superForwarders = new LinkedList<MethodNode>(); for (ClassNode node : interfaces) { if (Traits.isTrait(node)) { MethodNode method = node.getDeclaredMethod(name, forwarderParameters); if (method!=null) { // a similar method exists, we need a super bridge // trait$super$foo(Class currentTrait, ...) traits.add(node); superForwarders.add(method); } } } for (MethodNode superForwarder : superForwarders) { doCreateSuperForwarder(targetNode, superForwarder, traits.toArray(ClassNode.EMPTY_ARRAY), genericsSpec); } }
[ "private", "static", "void", "createSuperForwarder", "(", "ClassNode", "targetNode", ",", "MethodNode", "forwarder", ",", "final", "Map", "<", "String", ",", "ClassNode", ">", "genericsSpec", ")", "{", "List", "<", "ClassNode", ">", "interfaces", "=", "new", "...
Creates, if necessary, a super forwarder method, for stackable traits. @param forwarder a forwarder method @param genericsSpec
[ "Creates", "if", "necessary", "a", "super", "forwarder", "method", "for", "stackable", "traits", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/trait/TraitComposer.java#L458-L478
baratine/baratine
kraken/src/main/java/com/caucho/v5/kelp/TableWriterServiceImpl.java
TableWriterServiceImpl.openWriterGc
public OutSegment openWriterGc(long sequence) { int segmentSize = _segmentSizeGc; SegmentKelp segment = _segmentService.createSegment(segmentSize, getTableKey(), sequence); addTableSegmentLength(segmentSize); return new OutSegment(_table, _table.getTableService(), this, segment); }
java
public OutSegment openWriterGc(long sequence) { int segmentSize = _segmentSizeGc; SegmentKelp segment = _segmentService.createSegment(segmentSize, getTableKey(), sequence); addTableSegmentLength(segmentSize); return new OutSegment(_table, _table.getTableService(), this, segment); }
[ "public", "OutSegment", "openWriterGc", "(", "long", "sequence", ")", "{", "int", "segmentSize", "=", "_segmentSizeGc", ";", "SegmentKelp", "segment", "=", "_segmentService", ".", "createSegment", "(", "segmentSize", ",", "getTableKey", "(", ")", ",", "sequence", ...
Opens a new segment writer with a specified sequence. Called by the GC which has multiple segments with the same sequence number. @param sequence the sequence id for the new segment.
[ "Opens", "a", "new", "segment", "writer", "with", "a", "specified", "sequence", ".", "Called", "by", "the", "GC", "which", "has", "multiple", "segments", "with", "the", "same", "sequence", "number", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kelp/TableWriterServiceImpl.java#L547-L556
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.getConversations
public void getConversations(final boolean isPublic, @Nullable Callback<ComapiResult<List<Conversation>>> callback) { adapter.adapt(getConversations(isPublic), callback); }
java
public void getConversations(final boolean isPublic, @Nullable Callback<ComapiResult<List<Conversation>>> callback) { adapter.adapt(getConversations(isPublic), callback); }
[ "public", "void", "getConversations", "(", "final", "boolean", "isPublic", ",", "@", "Nullable", "Callback", "<", "ComapiResult", "<", "List", "<", "Conversation", ">", ">", ">", "callback", ")", "{", "adapter", ".", "adapt", "(", "getConversations", "(", "i...
Returns observable to get all visible conversations. @param isPublic Has the conversation public or private access. @param callback Callback to deliver new session instance.
[ "Returns", "observable", "to", "get", "all", "visible", "conversations", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L550-L552
OpenLiberty/open-liberty
dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPAKeyInfoManager.java
LTPAKeyInfoManager.getLTPAKeyFileResource
final WsResource getLTPAKeyFileResource(WsLocationAdmin locService, String ltpaKeyFile) { WsResource ltpaFile = locService.resolveResource(ltpaKeyFile); if (ltpaFile != null && ltpaFile.exists()) { return ltpaFile; } else { // The file does not exist so return null return null; } }
java
final WsResource getLTPAKeyFileResource(WsLocationAdmin locService, String ltpaKeyFile) { WsResource ltpaFile = locService.resolveResource(ltpaKeyFile); if (ltpaFile != null && ltpaFile.exists()) { return ltpaFile; } else { // The file does not exist so return null return null; } }
[ "final", "WsResource", "getLTPAKeyFileResource", "(", "WsLocationAdmin", "locService", ",", "String", "ltpaKeyFile", ")", "{", "WsResource", "ltpaFile", "=", "locService", ".", "resolveResource", "(", "ltpaKeyFile", ")", ";", "if", "(", "ltpaFile", "!=", "null", "...
Given the path to the LTPA key file return the WsResource for the file if the file exists. @param ltpaKeyFile @return WsResource if the file exist, null if it does not.
[ "Given", "the", "path", "to", "the", "LTPA", "key", "file", "return", "the", "WsResource", "for", "the", "file", "if", "the", "file", "exists", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.token.ltpa/src/com/ibm/ws/security/token/ltpa/internal/LTPAKeyInfoManager.java#L187-L195
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.contentEqualsIgnoreEOL
public static boolean contentEqualsIgnoreEOL(File file1, File file2, Charset charset) throws IORuntimeException { boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // 两个文件都不存在,返回true return true; } if (file1.isDirectory() || file2.isDirectory()) { // 不比较目录 throw new IORuntimeException("Can't compare directories, only files"); } if (equals(file1, file2)) { // 同一个文件 return true; } Reader input1 = null; Reader input2 = null; try { input1 = getReader(file1, charset); input2 = getReader(file2, charset); return IoUtil.contentEqualsIgnoreEOL(input1, input2); } finally { IoUtil.close(input1); IoUtil.close(input2); } }
java
public static boolean contentEqualsIgnoreEOL(File file1, File file2, Charset charset) throws IORuntimeException { boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (!file1Exists) { // 两个文件都不存在,返回true return true; } if (file1.isDirectory() || file2.isDirectory()) { // 不比较目录 throw new IORuntimeException("Can't compare directories, only files"); } if (equals(file1, file2)) { // 同一个文件 return true; } Reader input1 = null; Reader input2 = null; try { input1 = getReader(file1, charset); input2 = getReader(file2, charset); return IoUtil.contentEqualsIgnoreEOL(input1, input2); } finally { IoUtil.close(input1); IoUtil.close(input2); } }
[ "public", "static", "boolean", "contentEqualsIgnoreEOL", "(", "File", "file1", ",", "File", "file2", ",", "Charset", "charset", ")", "throws", "IORuntimeException", "{", "boolean", "file1Exists", "=", "file1", ".", "exists", "(", ")", ";", "if", "(", "file1Exi...
比较两个文件内容是否相同<br> 首先比较长度,长度一致再比较内容,比较内容采用按行读取,每行比较<br> 此方法来自Apache Commons io @param file1 文件1 @param file2 文件2 @param charset 编码,null表示使用平台默认编码 两个文件内容一致返回true,否则false @throws IORuntimeException IO异常 @since 4.0.6
[ "比较两个文件内容是否相同<br", ">", "首先比较长度,长度一致再比较内容,比较内容采用按行读取,每行比较<br", ">", "此方法来自Apache", "Commons", "io" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L1390-L1421
opengeospatial/teamengine
teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java
SoapParser.parseSoapFault
private Document parseSoapFault(Document soapMessage, PrintWriter logger) throws Exception { String namespace = soapMessage.getDocumentElement().getNamespaceURI(); if (namespace.equals(SOAP_12_NAMESPACE)) { parseSoap12Fault(soapMessage, logger); } else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{ parseSoap11Fault(soapMessage, logger); } return soapMessage; }
java
private Document parseSoapFault(Document soapMessage, PrintWriter logger) throws Exception { String namespace = soapMessage.getDocumentElement().getNamespaceURI(); if (namespace.equals(SOAP_12_NAMESPACE)) { parseSoap12Fault(soapMessage, logger); } else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{ parseSoap11Fault(soapMessage, logger); } return soapMessage; }
[ "private", "Document", "parseSoapFault", "(", "Document", "soapMessage", ",", "PrintWriter", "logger", ")", "throws", "Exception", "{", "String", "namespace", "=", "soapMessage", ".", "getDocumentElement", "(", ")", ".", "getNamespaceURI", "(", ")", ";", "if", "...
A method to parse a SOAP fault. It checks the namespace and invoke the correct SOAP 1.1 or 1.2 Fault parser. @param soapMessage the SOAP fault message to parse @param logger the PrintWriter to log all results to @return the parsed document otherwise @author Simone Gianfranceschi
[ "A", "method", "to", "parse", "a", "SOAP", "fault", ".", "It", "checks", "the", "namespace", "and", "invoke", "the", "correct", "SOAP", "1", ".", "1", "or", "1", ".", "2", "Fault", "parser", "." ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java#L257-L267
jparsec/jparsec
jparsec/src/main/java/org/jparsec/Parser.java
Parser.skipTimes
public final Parser<Void> skipTimes(int min, int max) { Checks.checkMinMax(min, max); return new SkipTimesParser(this, min, max); }
java
public final Parser<Void> skipTimes(int min, int max) { Checks.checkMinMax(min, max); return new SkipTimesParser(this, min, max); }
[ "public", "final", "Parser", "<", "Void", ">", "skipTimes", "(", "int", "min", ",", "int", "max", ")", "{", "Checks", ".", "checkMinMax", "(", "min", ",", "max", ")", ";", "return", "new", "SkipTimesParser", "(", "this", ",", "min", ",", "max", ")", ...
A {@link Parser} that runs {@code this} parser for at least {@code min} times and up to {@code max} times, with all the return values ignored.
[ "A", "{" ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/Parser.java#L282-L285
googleapis/google-cloud-java
google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/Watch.java
Watch.pushSnapshot
private void pushSnapshot(final Timestamp readTime, ByteString nextResumeToken) { final List<DocumentChange> changes = computeSnapshot(readTime); if (!hasPushed || !changes.isEmpty()) { final QuerySnapshot querySnapshot = QuerySnapshot.withChanges(query, readTime, documentSet, changes); userCallbackExecutor.execute( new Runnable() { @Override public void run() { listener.onEvent(querySnapshot, null); } }); hasPushed = true; } changeMap.clear(); resumeToken = nextResumeToken; }
java
private void pushSnapshot(final Timestamp readTime, ByteString nextResumeToken) { final List<DocumentChange> changes = computeSnapshot(readTime); if (!hasPushed || !changes.isEmpty()) { final QuerySnapshot querySnapshot = QuerySnapshot.withChanges(query, readTime, documentSet, changes); userCallbackExecutor.execute( new Runnable() { @Override public void run() { listener.onEvent(querySnapshot, null); } }); hasPushed = true; } changeMap.clear(); resumeToken = nextResumeToken; }
[ "private", "void", "pushSnapshot", "(", "final", "Timestamp", "readTime", ",", "ByteString", "nextResumeToken", ")", "{", "final", "List", "<", "DocumentChange", ">", "changes", "=", "computeSnapshot", "(", "readTime", ")", ";", "if", "(", "!", "hasPushed", "|...
Assembles a new snapshot from the current set of changes and invokes the user's callback. Clears the current changes on completion.
[ "Assembles", "a", "new", "snapshot", "from", "the", "current", "set", "of", "changes", "and", "invokes", "the", "user", "s", "callback", ".", "Clears", "the", "current", "changes", "on", "completion", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/Watch.java#L465-L482
unbescape/unbescape
src/main/java/org/unbescape/java/JavaEscape.java
JavaEscape.escapeJava
public static void escapeJava(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeJava(text, offset, len, writer, JavaEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_BASIC_ESCAPE_SET); }
java
public static void escapeJava(final char[] text, final int offset, final int len, final Writer writer) throws IOException { escapeJava(text, offset, len, writer, JavaEscapeLevel.LEVEL_2_ALL_NON_ASCII_PLUS_BASIC_ESCAPE_SET); }
[ "public", "static", "void", "escapeJava", "(", "final", "char", "[", "]", "text", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeJava", "(", "text", ",", "offset", ",...
<p> Perform a Java level 2 (basic set and all non-ASCII chars) <strong>escape</strong> operation on a <tt>char[]</tt> input. </p> <p> <em>Level 2</em> means this method will escape: </p> <ul> <li>The Java basic escape set: <ul> <li>The <em>Single Escape Characters</em>: <tt>&#92;b</tt> (<tt>U+0008</tt>), <tt>&#92;t</tt> (<tt>U+0009</tt>), <tt>&#92;n</tt> (<tt>U+000A</tt>), <tt>&#92;f</tt> (<tt>U+000C</tt>), <tt>&#92;r</tt> (<tt>U+000D</tt>), <tt>&#92;&quot;</tt> (<tt>U+0022</tt>), <tt>&#92;&#39;</tt> (<tt>U+0027</tt>) and <tt>&#92;&#92;</tt> (<tt>U+005C</tt>). Note <tt>&#92;&#39;</tt> is not really needed in String literals (only in Character literals), so it won't be used until escape level 3. </li> <li> Two ranges of non-displayable, control characters (some of which are already part of the <em>single escape characters</em> list): <tt>U+0000</tt> to <tt>U+001F</tt> and <tt>U+007F</tt> to <tt>U+009F</tt>. </li> </ul> </li> <li>All non ASCII characters.</li> </ul> <p> This escape will be performed by using the Single Escape Chars whenever possible. For escaped characters that do not have an associated SEC, default to <tt>&#92;uFFFF</tt> Hexadecimal Escapes. </p> <p> This method calls {@link #escapeJava(char[], int, int, java.io.Writer, JavaEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>level</tt>: {@link JavaEscapeLevel#LEVEL_2_ALL_NON_ASCII_PLUS_BASIC_ESCAPE_SET}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs
[ "<p", ">", "Perform", "a", "Java", "level", "2", "(", "basic", "set", "and", "all", "non", "-", "ASCII", "chars", ")", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "char", "[]", "<", "/", "tt", ">", "input", ...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/java/JavaEscape.java#L763-L766
braintree/browser-switch-android
browser-switch/src/main/java/com/braintreepayments/browserswitch/BrowserSwitchFragment.java
BrowserSwitchFragment.browserSwitch
public void browserSwitch(int requestCode, String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ChromeCustomTabs.addChromeCustomTabsExtras(mContext, intent); browserSwitch(requestCode, intent); }
java
public void browserSwitch(int requestCode, String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ChromeCustomTabs.addChromeCustomTabsExtras(mContext, intent); browserSwitch(requestCode, intent); }
[ "public", "void", "browserSwitch", "(", "int", "requestCode", ",", "String", "url", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "Intent", ".", "ACTION_VIEW", ",", "Uri", ".", "parse", "(", "url", ")", ")", ".", "addFlags", "(", "Intent", "...
Open a browser or <a href="https://developer.chrome.com/multidevice/android/customtabs">Chrome Custom Tab</a> with the given url. @param requestCode the request code used to differentiate requests from one another. @param url the url to open.
[ "Open", "a", "browser", "or", "<a", "href", "=", "https", ":", "//", "developer", ".", "chrome", ".", "com", "/", "multidevice", "/", "android", "/", "customtabs", ">", "Chrome", "Custom", "Tab<", "/", "a", ">", "with", "the", "given", "url", "." ]
train
https://github.com/braintree/browser-switch-android/blob/d830de21bc732b51e658e7296aad7b9037842a19/browser-switch/src/main/java/com/braintreepayments/browserswitch/BrowserSwitchFragment.java#L102-L109
lordcodes/SnackbarBuilder
snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/callback/SnackbarCallbackWrapper.java
SnackbarCallbackWrapper.onDismissed
@Override public void onDismissed(Snackbar snackbar, @DismissEvent int event) { if (callback != null) { callback.onDismissed(snackbar, event); } }
java
@Override public void onDismissed(Snackbar snackbar, @DismissEvent int event) { if (callback != null) { callback.onDismissed(snackbar, event); } }
[ "@", "Override", "public", "void", "onDismissed", "(", "Snackbar", "snackbar", ",", "@", "DismissEvent", "int", "event", ")", "{", "if", "(", "callback", "!=", "null", ")", "{", "callback", ".", "onDismissed", "(", "snackbar", ",", "event", ")", ";", "}"...
Notifies that the Snackbar has been dismissed through some means. @param snackbar The Snackbar which has been dismissed. @param event The event which caused the dismissal.
[ "Notifies", "that", "the", "Snackbar", "has", "been", "dismissed", "through", "some", "means", "." ]
train
https://github.com/lordcodes/SnackbarBuilder/blob/a104a753c78ed66940c19d295e141a521cf81d73/snackbarbuilder/src/main/java/com/github/andrewlord1990/snackbarbuilder/callback/SnackbarCallbackWrapper.java#L45-L50
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/common/CoGProperties.java
CoGProperties.useDevRandom
public boolean useDevRandom() { String value = System.getProperty("org.globus.dev.random"); if (value != null && value.equalsIgnoreCase("no")) { return false; } return getAsBoolean("org.globus.dev.random", true); }
java
public boolean useDevRandom() { String value = System.getProperty("org.globus.dev.random"); if (value != null && value.equalsIgnoreCase("no")) { return false; } return getAsBoolean("org.globus.dev.random", true); }
[ "public", "boolean", "useDevRandom", "(", ")", "{", "String", "value", "=", "System", ".", "getProperty", "(", "\"org.globus.dev.random\"", ")", ";", "if", "(", "value", "!=", "null", "&&", "value", ".", "equalsIgnoreCase", "(", "\"no\"", ")", ")", "{", "r...
Returns whether to use the /dev/urandom device for seed generation. @return true if the device should be used (if available of course) Returns true by default unless specified otherwise by the user.
[ "Returns", "whether", "to", "use", "the", "/", "dev", "/", "urandom", "device", "for", "seed", "generation", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/common/CoGProperties.java#L479-L485
eiichiro/acidhouse
acidhouse-appengine/src/main/java/org/eiichiro/acidhouse/appengine/Translation.java
Translation.toObject
public static <E> E toObject(Class<E> clazz, List<Entity> entities, Map<com.google.appengine.api.datastore.Key, Object> references, AppEngineDatastoreService datastore) { return toObject(clazz, entities, references, datastore, 0); }
java
public static <E> E toObject(Class<E> clazz, List<Entity> entities, Map<com.google.appengine.api.datastore.Key, Object> references, AppEngineDatastoreService datastore) { return toObject(clazz, entities, references, datastore, 0); }
[ "public", "static", "<", "E", ">", "E", "toObject", "(", "Class", "<", "E", ">", "clazz", ",", "List", "<", "Entity", ">", "entities", ",", "Map", "<", "com", ".", "google", ".", "appengine", ".", "api", ".", "datastore", ".", "Key", ",", "Object",...
Translates Google App Engine Datastore entities to Acid House entity with {@code AppEngineDatastoreService}. @param <E> The type of Acid House entity. @param clazz The {@code Class} of Acid House entity. @param entities Google App Engine Datastore entities. @param datastore {@code AppEngineDatastoreService}. @return Acid House entity translated from Google App Engine Datastore entities.
[ "Translates", "Google", "App", "Engine", "Datastore", "entities", "to", "Acid", "House", "entity", "with", "{", "@code", "AppEngineDatastoreService", "}", "." ]
train
https://github.com/eiichiro/acidhouse/blob/c50eaa0bb0f24abb46def4afa611f170637cdd62/acidhouse-appengine/src/main/java/org/eiichiro/acidhouse/appengine/Translation.java#L105-L109
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/AbstractResources.java
AbstractResources.postAndReceiveRowObject
protected CopyOrMoveRowResult postAndReceiveRowObject(String path, CopyOrMoveRowDirective objectToPost) throws SmartsheetException { Util.throwIfNull(path, objectToPost); Util.throwIfEmpty(path); HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.POST); ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream(); this.smartsheet.getJsonSerializer().serialize(objectToPost, objectBytesStream); HttpEntity entity = new HttpEntity(); entity.setContentType("application/json"); entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray())); entity.setContentLength(objectBytesStream.size()); request.setEntity(entity); CopyOrMoveRowResult obj = null; try { HttpResponse response = this.smartsheet.getHttpClient().request(request); switch (response.getStatusCode()) { case 200: obj = this.smartsheet.getJsonSerializer().deserializeCopyOrMoveRow( response.getEntity().getContent()); break; default: handleError(response); } } finally { smartsheet.getHttpClient().releaseConnection(); } return obj; }
java
protected CopyOrMoveRowResult postAndReceiveRowObject(String path, CopyOrMoveRowDirective objectToPost) throws SmartsheetException { Util.throwIfNull(path, objectToPost); Util.throwIfEmpty(path); HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.POST); ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream(); this.smartsheet.getJsonSerializer().serialize(objectToPost, objectBytesStream); HttpEntity entity = new HttpEntity(); entity.setContentType("application/json"); entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray())); entity.setContentLength(objectBytesStream.size()); request.setEntity(entity); CopyOrMoveRowResult obj = null; try { HttpResponse response = this.smartsheet.getHttpClient().request(request); switch (response.getStatusCode()) { case 200: obj = this.smartsheet.getJsonSerializer().deserializeCopyOrMoveRow( response.getEntity().getContent()); break; default: handleError(response); } } finally { smartsheet.getHttpClient().releaseConnection(); } return obj; }
[ "protected", "CopyOrMoveRowResult", "postAndReceiveRowObject", "(", "String", "path", ",", "CopyOrMoveRowDirective", "objectToPost", ")", "throws", "SmartsheetException", "{", "Util", ".", "throwIfNull", "(", "path", ",", "objectToPost", ")", ";", "Util", ".", "throwI...
Post an object to Smartsheet REST API and receive a CopyOrMoveRowResult object from response. Parameters: - path : the relative path of the resource collections - objectToPost : the object to post - Returns: the object Exceptions: IllegalArgumentException : if any argument is null, or path is empty string InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param path the path @param objectToPost the object to post @return the result object @throws SmartsheetException the smartsheet exception
[ "Post", "an", "object", "to", "Smartsheet", "REST", "API", "and", "receive", "a", "CopyOrMoveRowResult", "object", "from", "response", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/AbstractResources.java#L669-L700
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUService.java
ICUService.registerObject
public Factory registerObject(Object obj, String id) { return registerObject(obj, id, true); }
java
public Factory registerObject(Object obj, String id) { return registerObject(obj, id, true); }
[ "public", "Factory", "registerObject", "(", "Object", "obj", ",", "String", "id", ")", "{", "return", "registerObject", "(", "obj", ",", "id", ",", "true", ")", ";", "}" ]
A convenience override of registerObject(Object, String, boolean) that defaults visible to true.
[ "A", "convenience", "override", "of", "registerObject", "(", "Object", "String", "boolean", ")", "that", "defaults", "visible", "to", "true", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUService.java#L775-L777
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/DumpProcessingOutputAction.java
DumpProcessingOutputAction.getAsynchronousOutputStream
protected OutputStream getAsynchronousOutputStream( final OutputStream outputStream) throws IOException { final int SIZE = 1024 * 1024 * 10; final PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, SIZE); final FinishableRunnable run = new FinishableRunnable() { volatile boolean finish = false; volatile boolean hasFinished = false; @Override public void finish() { this.finish = true; while (!this.hasFinished) { // loop until thread is really finished } } @Override public void run() { try { byte[] bytes = new byte[SIZE]; // Note that we finish really gently here, writing all data // that is still in the input first (in theory, new data // could arrive asynchronously, so that the thread never // finishes, but this is not the intended mode of // operation). for (int len; (!this.finish || pis.available() > 0) && (len = pis.read(bytes)) > 0;) { outputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { close(pis); close(outputStream); this.hasFinished = true; } } }; new Thread(run, "async-output-stream").start(); this.outputStreams.add(new Closeable() { @Override public void close() throws IOException { run.finish(); } }); return pos; }
java
protected OutputStream getAsynchronousOutputStream( final OutputStream outputStream) throws IOException { final int SIZE = 1024 * 1024 * 10; final PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, SIZE); final FinishableRunnable run = new FinishableRunnable() { volatile boolean finish = false; volatile boolean hasFinished = false; @Override public void finish() { this.finish = true; while (!this.hasFinished) { // loop until thread is really finished } } @Override public void run() { try { byte[] bytes = new byte[SIZE]; // Note that we finish really gently here, writing all data // that is still in the input first (in theory, new data // could arrive asynchronously, so that the thread never // finishes, but this is not the intended mode of // operation). for (int len; (!this.finish || pis.available() > 0) && (len = pis.read(bytes)) > 0;) { outputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { close(pis); close(outputStream); this.hasFinished = true; } } }; new Thread(run, "async-output-stream").start(); this.outputStreams.add(new Closeable() { @Override public void close() throws IOException { run.finish(); } }); return pos; }
[ "protected", "OutputStream", "getAsynchronousOutputStream", "(", "final", "OutputStream", "outputStream", ")", "throws", "IOException", "{", "final", "int", "SIZE", "=", "1024", "*", "1024", "*", "10", ";", "final", "PipedOutputStream", "pos", "=", "new", "PipedOu...
Creates a separate thread for writing into the given output stream and returns a pipe output stream that can be used to pass data to this thread. <p> This code is inspired by http://stackoverflow.com/questions/12532073/gzipoutputstream -that-does-its-compression-in-a-separate-thread @param outputStream the stream to write to in the thread @return a new stream that data should be written to @throws IOException if the pipes could not be created for some reason
[ "Creates", "a", "separate", "thread", "for", "writing", "into", "the", "given", "output", "stream", "and", "returns", "a", "pipe", "output", "stream", "that", "can", "be", "used", "to", "pass", "data", "to", "this", "thread", ".", "<p", ">", "This", "cod...
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/DumpProcessingOutputAction.java#L287-L339
qiujiayu/AutoLoadCache
src/main/java/com/jarvis/cache/CacheUtil.java
CacheUtil.getDefaultCacheKey
public static String getDefaultCacheKey(String className, String method, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append(getDefaultCacheKeyPrefix(className, method, arguments)); if (null != arguments && arguments.length > 0) { sb.append(getUniqueHashStr(arguments)); } return sb.toString(); }
java
public static String getDefaultCacheKey(String className, String method, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append(getDefaultCacheKeyPrefix(className, method, arguments)); if (null != arguments && arguments.length > 0) { sb.append(getUniqueHashStr(arguments)); } return sb.toString(); }
[ "public", "static", "String", "getDefaultCacheKey", "(", "String", "className", ",", "String", "method", ",", "Object", "[", "]", "arguments", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "getDefaultC...
生成缓存Key @param className 类名称 @param method 方法名称 @param arguments 参数 @return CacheKey 缓存Key
[ "生成缓存Key" ]
train
https://github.com/qiujiayu/AutoLoadCache/blob/8121c146f1a420fa6d6832e849acadb547c13622/src/main/java/com/jarvis/cache/CacheUtil.java#L100-L107
redkale/redkale
src/org/redkale/source/ColumnValue.java
ColumnValue.mul
public static ColumnValue mul(String column, Serializable value) { return new ColumnValue(column, MUL, value); }
java
public static ColumnValue mul(String column, Serializable value) { return new ColumnValue(column, MUL, value); }
[ "public", "static", "ColumnValue", "mul", "(", "String", "column", ",", "Serializable", "value", ")", "{", "return", "new", "ColumnValue", "(", "column", ",", "MUL", ",", "value", ")", ";", "}" ]
返回 {column} = {column} * {value} 操作 @param column 字段名 @param value 字段值 @return ColumnValue
[ "返回", "{", "column", "}", "=", "{", "column", "}", "*", "{", "value", "}", "操作" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/ColumnValue.java#L85-L87
buschmais/jqa-maven-plugin
src/main/java/com/buschmais/jqassistant/scm/maven/ProjectResolver.java
ProjectResolver.getRootModule
static MavenProject getRootModule(MavenProject module, List<MavenProject> reactor, String rulesDirectory, boolean useExecutionRootAsProjectRoot) throws MojoExecutionException { String rootModuleContextKey = ProjectResolver.class.getName() + "#rootModule"; MavenProject rootModule = (MavenProject) module.getContextValue(rootModuleContextKey); if (rootModule == null) { if (useExecutionRootAsProjectRoot) { rootModule = getRootModule(reactor); } else { rootModule = getRootModule(module, rulesDirectory); } module.setContextValue(rootModuleContextKey, rootModule); } return rootModule; }
java
static MavenProject getRootModule(MavenProject module, List<MavenProject> reactor, String rulesDirectory, boolean useExecutionRootAsProjectRoot) throws MojoExecutionException { String rootModuleContextKey = ProjectResolver.class.getName() + "#rootModule"; MavenProject rootModule = (MavenProject) module.getContextValue(rootModuleContextKey); if (rootModule == null) { if (useExecutionRootAsProjectRoot) { rootModule = getRootModule(reactor); } else { rootModule = getRootModule(module, rulesDirectory); } module.setContextValue(rootModuleContextKey, rootModule); } return rootModule; }
[ "static", "MavenProject", "getRootModule", "(", "MavenProject", "module", ",", "List", "<", "MavenProject", ">", "reactor", ",", "String", "rulesDirectory", ",", "boolean", "useExecutionRootAsProjectRoot", ")", "throws", "MojoExecutionException", "{", "String", "rootMod...
Return the {@link MavenProject} which is the base module for scanning and analysis. The base module is by searching with the module tree starting from the current module over its parents until a module is found containing a directory "jqassistant" or no parent can be determined. @param module The current module. @param rulesDirectory The name of the directory used for identifying the root module. @param useExecutionRootAsProjectRoot `true` if the execution root shall be used as project root. @return The {@link MavenProject} containing a rules directory. @throws MojoExecutionException If the directory cannot be resolved.
[ "Return", "the", "{", "@link", "MavenProject", "}", "which", "is", "the", "base", "module", "for", "scanning", "and", "analysis", "." ]
train
https://github.com/buschmais/jqa-maven-plugin/blob/5c21a8058fc1b013333081907fbf00d3525e11c3/src/main/java/com/buschmais/jqassistant/scm/maven/ProjectResolver.java#L47-L60
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacFiler.java
JavacFiler.closeFileObject
private void closeFileObject(ModuleSymbol mod, String typeName, FileObject fileObject) { /* * If typeName is non-null, the file object was opened as a * source or class file by the user. If a file was opened as * a resource, typeName will be null and the file is *not* * subject to annotation processing. */ if ((typeName != null)) { if (!(fileObject instanceof JavaFileObject)) throw new AssertionError("JavaFileOject not found for " + fileObject); JavaFileObject javaFileObject = (JavaFileObject)fileObject; switch(javaFileObject.getKind()) { case SOURCE: generatedSourceNames.add(typeName); generatedSourceFileObjects.add(javaFileObject); openTypeNames.remove(typeName); break; case CLASS: generatedClasses.computeIfAbsent(mod, m -> Collections.synchronizedMap(new LinkedHashMap<>())).put(typeName, javaFileObject); openTypeNames.remove(typeName); break; default: break; } } }
java
private void closeFileObject(ModuleSymbol mod, String typeName, FileObject fileObject) { /* * If typeName is non-null, the file object was opened as a * source or class file by the user. If a file was opened as * a resource, typeName will be null and the file is *not* * subject to annotation processing. */ if ((typeName != null)) { if (!(fileObject instanceof JavaFileObject)) throw new AssertionError("JavaFileOject not found for " + fileObject); JavaFileObject javaFileObject = (JavaFileObject)fileObject; switch(javaFileObject.getKind()) { case SOURCE: generatedSourceNames.add(typeName); generatedSourceFileObjects.add(javaFileObject); openTypeNames.remove(typeName); break; case CLASS: generatedClasses.computeIfAbsent(mod, m -> Collections.synchronizedMap(new LinkedHashMap<>())).put(typeName, javaFileObject); openTypeNames.remove(typeName); break; default: break; } } }
[ "private", "void", "closeFileObject", "(", "ModuleSymbol", "mod", ",", "String", "typeName", ",", "FileObject", "fileObject", ")", "{", "/*\n * If typeName is non-null, the file object was opened as a\n * source or class file by the user. If a file was opened as\n ...
Upon close, register files opened by create{Source, Class}File for annotation processing.
[ "Upon", "close", "register", "files", "opened", "by", "create", "{", "Source", "Class", "}", "File", "for", "annotation", "processing", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/JavacFiler.java#L858-L885
spring-projects/spring-android
spring-android-core/src/main/java/org/springframework/util/comparator/CompoundComparator.java
CompoundComparator.addComparator
public void addComparator(Comparator<T> comparator, boolean ascending) { this.comparators.add(new InvertibleComparator<T>(comparator, ascending)); }
java
public void addComparator(Comparator<T> comparator, boolean ascending) { this.comparators.add(new InvertibleComparator<T>(comparator, ascending)); }
[ "public", "void", "addComparator", "(", "Comparator", "<", "T", ">", "comparator", ",", "boolean", "ascending", ")", "{", "this", ".", "comparators", ".", "add", "(", "new", "InvertibleComparator", "<", "T", ">", "(", "comparator", ",", "ascending", ")", "...
Add a Comparator to the end of the chain using the provided sort order. @param comparator the Comparator to add to the end of the chain @param ascending the sort order: ascending (true) or descending (false)
[ "Add", "a", "Comparator", "to", "the", "end", "of", "the", "chain", "using", "the", "provided", "sort", "order", "." ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/util/comparator/CompoundComparator.java#L93-L95
undertow-io/undertow
core/src/main/java/io/undertow/protocols/ssl/ALPNHackClientHelloExplorer.java
ALPNHackClientHelloExplorer.exploreExtensions
private static void exploreExtensions(ByteBuffer input, List<String> alpnProtocols, ByteArrayOutputStream out) throws SSLException { ByteArrayOutputStream extensionOut = out == null ? null : new ByteArrayOutputStream(); int length = getInt16(input); // length of extensions writeInt16(extensionOut, 0); //placeholder while (length > 0) { int extType = getInt16(input); // extenson type writeInt16(extensionOut, extType); int extLen = getInt16(input); // length of extension data writeInt16(extensionOut, extLen); if (extType == 16) { // 0x00: ty if(out == null) { exploreALPNExt(input, alpnProtocols); } else { throw new ALPNPresentException(); } } else { // ignore other extensions processByteVector(input, extLen, extensionOut); } length -= extLen + 4; } if(out != null) { byte[] alpnBits = generateAlpnExtension(alpnProtocols); extensionOut.write(alpnBits,0 ,alpnBits.length); byte[] extensionsData = extensionOut.toByteArray(); int newLength = extensionsData.length - 2; extensionsData[0] = (byte) ((newLength >> 8) & 0xFF); extensionsData[1] = (byte) (newLength & 0xFF); out.write(extensionsData, 0, extensionsData.length); } }
java
private static void exploreExtensions(ByteBuffer input, List<String> alpnProtocols, ByteArrayOutputStream out) throws SSLException { ByteArrayOutputStream extensionOut = out == null ? null : new ByteArrayOutputStream(); int length = getInt16(input); // length of extensions writeInt16(extensionOut, 0); //placeholder while (length > 0) { int extType = getInt16(input); // extenson type writeInt16(extensionOut, extType); int extLen = getInt16(input); // length of extension data writeInt16(extensionOut, extLen); if (extType == 16) { // 0x00: ty if(out == null) { exploreALPNExt(input, alpnProtocols); } else { throw new ALPNPresentException(); } } else { // ignore other extensions processByteVector(input, extLen, extensionOut); } length -= extLen + 4; } if(out != null) { byte[] alpnBits = generateAlpnExtension(alpnProtocols); extensionOut.write(alpnBits,0 ,alpnBits.length); byte[] extensionsData = extensionOut.toByteArray(); int newLength = extensionsData.length - 2; extensionsData[0] = (byte) ((newLength >> 8) & 0xFF); extensionsData[1] = (byte) (newLength & 0xFF); out.write(extensionsData, 0, extensionsData.length); } }
[ "private", "static", "void", "exploreExtensions", "(", "ByteBuffer", "input", ",", "List", "<", "String", ">", "alpnProtocols", ",", "ByteArrayOutputStream", "out", ")", "throws", "SSLException", "{", "ByteArrayOutputStream", "extensionOut", "=", "out", "==", "null"...
/* struct { ExtensionType extension_type; opaque extension_data<0..2^16-1>; } Extension; enum { server_name(0), max_fragment_length(1), client_certificate_url(2), trusted_ca_keys(3), truncated_hmac(4), status_request(5), (65535) } ExtensionType;
[ "/", "*", "struct", "{", "ExtensionType", "extension_type", ";", "opaque", "extension_data<0", "..", "2^16", "-", "1", ">", ";", "}", "Extension", ";" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/ssl/ALPNHackClientHelloExplorer.java#L350-L382
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.mapPort
public static int mapPort(Map<Integer, Integer> mapping, int port) { Integer mappedPort = mapping.get(port); if( mappedPort == null ) throw new RuntimeException("Could not map port "+port); return mappedPort; }
java
public static int mapPort(Map<Integer, Integer> mapping, int port) { Integer mappedPort = mapping.get(port); if( mappedPort == null ) throw new RuntimeException("Could not map port "+port); return mappedPort; }
[ "public", "static", "int", "mapPort", "(", "Map", "<", "Integer", ",", "Integer", ">", "mapping", ",", "int", "port", ")", "{", "Integer", "mappedPort", "=", "mapping", ".", "get", "(", "port", ")", ";", "if", "(", "mappedPort", "==", "null", ")", "t...
Looks up a corresponding port number from a port mapping. @param mapping the port mapping @param port the key in the port map. @return the corresponding port number from the port mapping. @throws RuntimeException if a value could not be found.
[ "Looks", "up", "a", "corresponding", "port", "number", "from", "a", "port", "mapping", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L81-L85
JodaOrg/joda-time
src/main/java/org/joda/time/format/DateTimeFormatter.java
DateTimeFormatter.printTo
public void printTo(Appendable appendable, ReadableInstant instant) throws IOException { long millis = DateTimeUtils.getInstantMillis(instant); Chronology chrono = DateTimeUtils.getInstantChronology(instant); printTo(appendable, millis, chrono); }
java
public void printTo(Appendable appendable, ReadableInstant instant) throws IOException { long millis = DateTimeUtils.getInstantMillis(instant); Chronology chrono = DateTimeUtils.getInstantChronology(instant); printTo(appendable, millis, chrono); }
[ "public", "void", "printTo", "(", "Appendable", "appendable", ",", "ReadableInstant", "instant", ")", "throws", "IOException", "{", "long", "millis", "=", "DateTimeUtils", ".", "getInstantMillis", "(", "instant", ")", ";", "Chronology", "chrono", "=", "DateTimeUti...
Prints a ReadableInstant, using the chronology supplied by the instant. @param appendable the destination to format to, not null @param instant instant to format, null means now @since 2.0
[ "Prints", "a", "ReadableInstant", "using", "the", "chronology", "supplied", "by", "the", "instant", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatter.java#L532-L536
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrRequestHandler.java
JawrRequestHandler.writeContent
protected void writeContent(String requestedPath, HttpServletRequest request, HttpServletResponse response) throws IOException, ResourceNotFoundException { // Send gzipped resource if user agent supports it. int idx = requestedPath.indexOf(BundleRenderer.GZIP_PATH_PREFIX); if (idx != -1) { requestedPath = JawrConstant.URL_SEPARATOR + requestedPath.substring(idx + BundleRenderer.GZIP_PATH_PREFIX.length(), requestedPath.length()); if (isValidRequestedPath(requestedPath)) { response.setHeader(CONTENT_ENCODING, GZIP); bundlesHandler.streamBundleTo(requestedPath, response.getOutputStream()); } else { throw new ResourceNotFoundException(requestedPath); } } else { // In debug mode, we take in account the image generated from a // StreamGenerator like classpath Image generator // The following code will rewrite the URL path for the generated // images, // because in debug mode, we are retrieving the CSS resources // directly from the webapp // and if the CSS contains generated images, we should rewrite the // URL. BinaryResourcesHandler imgRsHandler = (BinaryResourcesHandler) servletContext .getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE); if (imgRsHandler != null && this.jawrConfig.isDebugModeOn() && resourceType.equals(JawrConstant.CSS_TYPE)) { handleGeneratedCssInDebugMode(requestedPath, request, response, imgRsHandler); } else { if (isValidRequestedPath(requestedPath)) { Writer out = response.getWriter(); bundlesHandler.writeBundleTo(requestedPath, out); } else { throw new ResourceNotFoundException(requestedPath); } } } }
java
protected void writeContent(String requestedPath, HttpServletRequest request, HttpServletResponse response) throws IOException, ResourceNotFoundException { // Send gzipped resource if user agent supports it. int idx = requestedPath.indexOf(BundleRenderer.GZIP_PATH_PREFIX); if (idx != -1) { requestedPath = JawrConstant.URL_SEPARATOR + requestedPath.substring(idx + BundleRenderer.GZIP_PATH_PREFIX.length(), requestedPath.length()); if (isValidRequestedPath(requestedPath)) { response.setHeader(CONTENT_ENCODING, GZIP); bundlesHandler.streamBundleTo(requestedPath, response.getOutputStream()); } else { throw new ResourceNotFoundException(requestedPath); } } else { // In debug mode, we take in account the image generated from a // StreamGenerator like classpath Image generator // The following code will rewrite the URL path for the generated // images, // because in debug mode, we are retrieving the CSS resources // directly from the webapp // and if the CSS contains generated images, we should rewrite the // URL. BinaryResourcesHandler imgRsHandler = (BinaryResourcesHandler) servletContext .getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE); if (imgRsHandler != null && this.jawrConfig.isDebugModeOn() && resourceType.equals(JawrConstant.CSS_TYPE)) { handleGeneratedCssInDebugMode(requestedPath, request, response, imgRsHandler); } else { if (isValidRequestedPath(requestedPath)) { Writer out = response.getWriter(); bundlesHandler.writeBundleTo(requestedPath, out); } else { throw new ResourceNotFoundException(requestedPath); } } } }
[ "protected", "void", "writeContent", "(", "String", "requestedPath", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", ",", "ResourceNotFoundException", "{", "// Send gzipped resource if user agent supports it.", "int", ...
Writes the content to the output stream @param requestedPath the requested path @param request the request @param response the response @throws IOException if an IOException occurs @throws ResourceNotFoundException if the resource is not found
[ "Writes", "the", "content", "to", "the", "output", "stream" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrRequestHandler.java#L983-L1024
mgm-tp/jfunk
jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
WebDriverTool.getViewport
public Rectangle getViewport() { @SuppressWarnings("unchecked") Map<String, Number> result = (Map<String, Number>) executeScript(JS_GET_VIEWPORT); int width = result.get("width").intValue(); int height = result.get("height").intValue(); Rectangle viewport = new Rectangle(0, 0, height, width, width, height); LOGGER.info("Viewport rectangle: {}", viewport); return viewport; }
java
public Rectangle getViewport() { @SuppressWarnings("unchecked") Map<String, Number> result = (Map<String, Number>) executeScript(JS_GET_VIEWPORT); int width = result.get("width").intValue(); int height = result.get("height").intValue(); Rectangle viewport = new Rectangle(0, 0, height, width, width, height); LOGGER.info("Viewport rectangle: {}", viewport); return viewport; }
[ "public", "Rectangle", "getViewport", "(", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Map", "<", "String", ",", "Number", ">", "result", "=", "(", "Map", "<", "String", ",", "Number", ">", ")", "executeScript", "(", "JS_GET_VIEWPORT", "...
Returns the size of the viewport excluding, if rendered, the vertical and horizontal scrollbars. Uses JavaScript calling document.documentElement.client[Width|Height](). @return the rectangle
[ "Returns", "the", "size", "of", "the", "viewport", "excluding", "if", "rendered", "the", "vertical", "and", "horizontal", "scrollbars", ".", "Uses", "JavaScript", "calling", "document", ".", "documentElement", ".", "client", "[", "Width|Height", "]", "()", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java#L699-L707
isisaddons-legacy/isis-module-excel
dom/src/main/java/org/isisaddons/module/excel/dom/ExcelService.java
ExcelService.fromExcel
@Programmatic public <T> List<T> fromExcel( final Blob excelBlob, final Class<T> cls, final String sheetName) throws ExcelService.Exception { return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName)); }
java
@Programmatic public <T> List<T> fromExcel( final Blob excelBlob, final Class<T> cls, final String sheetName) throws ExcelService.Exception { return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName)); }
[ "@", "Programmatic", "public", "<", "T", ">", "List", "<", "T", ">", "fromExcel", "(", "final", "Blob", "excelBlob", ",", "final", "Class", "<", "T", ">", "cls", ",", "final", "String", "sheetName", ")", "throws", "ExcelService", ".", "Exception", "{", ...
Returns a list of objects for each line in the spreadsheet, of the specified type. <p> If the class is a view model then the objects will be properly instantiated (that is, using {@link DomainObjectContainer#newViewModelInstance(Class, String)}, with the correct view model memento); otherwise the objects will be simple transient objects (that is, using {@link DomainObjectContainer#newTransientInstance(Class)}). </p>
[ "Returns", "a", "list", "of", "objects", "for", "each", "line", "in", "the", "spreadsheet", "of", "the", "specified", "type", "." ]
train
https://github.com/isisaddons-legacy/isis-module-excel/blob/a3b92b1797ab2ed609667933d4164e9fb54b9f25/dom/src/main/java/org/isisaddons/module/excel/dom/ExcelService.java#L155-L161
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java
Descriptor.withMessageSerializer
public <T> Descriptor withMessageSerializer(Class<T> messageType, MessageSerializer<T, ?> messageSerializer) { return withMessageSerializer((Type) messageType, messageSerializer); }
java
public <T> Descriptor withMessageSerializer(Class<T> messageType, MessageSerializer<T, ?> messageSerializer) { return withMessageSerializer((Type) messageType, messageSerializer); }
[ "public", "<", "T", ">", "Descriptor", "withMessageSerializer", "(", "Class", "<", "T", ">", "messageType", ",", "MessageSerializer", "<", "T", ",", "?", ">", "messageSerializer", ")", "{", "return", "withMessageSerializer", "(", "(", "Type", ")", "messageType...
Provide a custom MessageSerializer for the given message type. @param messageType The type of the message. @param messageSerializer The message serializer for that type. @return A copy of this descriptor.
[ "Provide", "a", "custom", "MessageSerializer", "for", "the", "given", "message", "type", "." ]
train
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java#L689-L691
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Group.java
Group.foundGroupFormat
boolean foundGroupFormat(Map<String,?> map, String elementFormat) { if (map.containsKey(elementFormat)) { initMessages(); messages.error("doclet.Same_element_name_used", elementFormat); return true; } return false; }
java
boolean foundGroupFormat(Map<String,?> map, String elementFormat) { if (map.containsKey(elementFormat)) { initMessages(); messages.error("doclet.Same_element_name_used", elementFormat); return true; } return false; }
[ "boolean", "foundGroupFormat", "(", "Map", "<", "String", ",", "?", ">", "map", ",", "String", "elementFormat", ")", "{", "if", "(", "map", ".", "containsKey", "(", "elementFormat", ")", ")", "{", "initMessages", "(", ")", ";", "messages", ".", "error", ...
Search if the given map has the given element format. @param map Map to be searched. @param elementFormat The format to search. @return true if element name format found in the map, else false.
[ "Search", "if", "the", "given", "map", "has", "the", "given", "element", "format", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Group.java#L217-L224
m-m-m/util
datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java
GenericColor.calculateRgb
private static void calculateRgb(GenericColor genericColor, Hue hue, double min, double chroma) { genericColor.chroma = new Chroma(chroma); double hueX = hue.getValue().doubleValue() / 60; double x = chroma * (1 - Math.abs((hueX % 2) - 1)); double red, green, blue; if (hueX < 1) { red = chroma + min; green = x + min; blue = min; } else if (hueX < 2) { red = x + min; green = chroma + min; blue = min; } else if (hueX < 3) { red = min; green = chroma + min; blue = x + min; } else if (hueX < 4) { red = min; green = x + min; blue = chroma + min; } else if (hueX < 5) { red = x + min; green = min; blue = chroma + min; } else { red = chroma + min; green = min; blue = x + min; } genericColor.red = new Red(red); genericColor.green = new Green(green); genericColor.blue = new Blue(blue); }
java
private static void calculateRgb(GenericColor genericColor, Hue hue, double min, double chroma) { genericColor.chroma = new Chroma(chroma); double hueX = hue.getValue().doubleValue() / 60; double x = chroma * (1 - Math.abs((hueX % 2) - 1)); double red, green, blue; if (hueX < 1) { red = chroma + min; green = x + min; blue = min; } else if (hueX < 2) { red = x + min; green = chroma + min; blue = min; } else if (hueX < 3) { red = min; green = chroma + min; blue = x + min; } else if (hueX < 4) { red = min; green = x + min; blue = chroma + min; } else if (hueX < 5) { red = x + min; green = min; blue = chroma + min; } else { red = chroma + min; green = min; blue = x + min; } genericColor.red = new Red(red); genericColor.green = new Green(green); genericColor.blue = new Blue(blue); }
[ "private", "static", "void", "calculateRgb", "(", "GenericColor", "genericColor", ",", "Hue", "hue", ",", "double", "min", ",", "double", "chroma", ")", "{", "genericColor", ".", "chroma", "=", "new", "Chroma", "(", "chroma", ")", ";", "double", "hueX", "=...
Calculates and the RGB values and sets them in the given {@link GenericColor}. @param genericColor is the {@link GenericColor} to complete. @param hue is the {@link Hue} value. @param min is the minimum {@link Factor} of R/G/B. @param chroma is the {@link Chroma} value.
[ "Calculates", "and", "the", "RGB", "values", "and", "sets", "them", "in", "the", "given", "{", "@link", "GenericColor", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/datatype/src/main/java/net/sf/mmm/util/datatype/api/color/GenericColor.java#L336-L370
facebook/fresco
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
GenericDraweeHierarchy.setRetryImage
public void setRetryImage(int resourceId, ScalingUtils.ScaleType scaleType) { setRetryImage(mResources.getDrawable(resourceId), scaleType); }
java
public void setRetryImage(int resourceId, ScalingUtils.ScaleType scaleType) { setRetryImage(mResources.getDrawable(resourceId), scaleType); }
[ "public", "void", "setRetryImage", "(", "int", "resourceId", ",", "ScalingUtils", ".", "ScaleType", "scaleType", ")", "{", "setRetryImage", "(", "mResources", ".", "getDrawable", "(", "resourceId", ")", ",", "scaleType", ")", ";", "}" ]
Sets a new retry drawable with scale type. @param resourceId an identifier of an Android drawable or color resource. @param ScalingUtils.ScaleType a new scale type.
[ "Sets", "a", "new", "retry", "drawable", "with", "scale", "type", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L513-L515
dbracewell/mango
src/main/java/com/davidbracewell/config/Config.java
Config.hasProperty
public static boolean hasProperty(Class<?> clazz, Language language, String... propertyComponents) { return hasProperty(clazz.getName(), language, propertyComponents); }
java
public static boolean hasProperty(Class<?> clazz, Language language, String... propertyComponents) { return hasProperty(clazz.getName(), language, propertyComponents); }
[ "public", "static", "boolean", "hasProperty", "(", "Class", "<", "?", ">", "clazz", ",", "Language", "language", ",", "String", "...", "propertyComponents", ")", "{", "return", "hasProperty", "(", "clazz", ".", "getName", "(", ")", ",", "language", ",", "p...
<p>Checks if a property is in the config or or set on the system. The property name is constructed as <code>clazz.getName() + . + propertyComponent[0] + . + propertyComponent[1] + ... + (language.toString()|language.getCode().toLowerCase())</code> This will return true if the language specific config option is set or a default (i.e. no-language specified) version is set. </p> @param clazz The class with which the property is associated. @param language The language we would like the config for @param propertyComponents The components. @return True if the property is known, false if not.
[ "<p", ">", "Checks", "if", "a", "property", "is", "in", "the", "config", "or", "or", "set", "on", "the", "system", ".", "The", "property", "name", "is", "constructed", "as", "<code", ">", "clazz", ".", "getName", "()", "+", ".", "+", "propertyComponent...
train
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/config/Config.java#L298-L300
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java
FacesImpl.identifyAsync
public Observable<List<IdentifyResult>> identifyAsync(String personGroupId, List<UUID> faceIds, IdentifyOptionalParameter identifyOptionalParameter) { return identifyWithServiceResponseAsync(personGroupId, faceIds, identifyOptionalParameter).map(new Func1<ServiceResponse<List<IdentifyResult>>, List<IdentifyResult>>() { @Override public List<IdentifyResult> call(ServiceResponse<List<IdentifyResult>> response) { return response.body(); } }); }
java
public Observable<List<IdentifyResult>> identifyAsync(String personGroupId, List<UUID> faceIds, IdentifyOptionalParameter identifyOptionalParameter) { return identifyWithServiceResponseAsync(personGroupId, faceIds, identifyOptionalParameter).map(new Func1<ServiceResponse<List<IdentifyResult>>, List<IdentifyResult>>() { @Override public List<IdentifyResult> call(ServiceResponse<List<IdentifyResult>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "IdentifyResult", ">", ">", "identifyAsync", "(", "String", "personGroupId", ",", "List", "<", "UUID", ">", "faceIds", ",", "IdentifyOptionalParameter", "identifyOptionalParameter", ")", "{", "return", "identifyWithServiceResp...
Identify unknown faces from a person group. @param personGroupId PersonGroupId of the target person group, created by PersonGroups.Create @param faceIds Array of query faces faceIds, created by the Face - Detect. Each of the faces are identified independently. The valid number of faceIds is between [1, 10]. @param identifyOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;IdentifyResult&gt; object
[ "Identify", "unknown", "faces", "from", "a", "person", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java#L413-L420
StripesFramework/stripes-stuff
src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java
WaitPageInterceptor.removeExpired
protected void removeExpired(Map<Integer, Context> contexts) { Iterator<Context> contextsIter = contexts.values().iterator(); while (contextsIter.hasNext()) { Context context = contextsIter.next(); if (context.completeMoment != null && System.currentTimeMillis() - context.completeMoment > contextTimeout) { contextsIter.remove(); } } }
java
protected void removeExpired(Map<Integer, Context> contexts) { Iterator<Context> contextsIter = contexts.values().iterator(); while (contextsIter.hasNext()) { Context context = contextsIter.next(); if (context.completeMoment != null && System.currentTimeMillis() - context.completeMoment > contextTimeout) { contextsIter.remove(); } } }
[ "protected", "void", "removeExpired", "(", "Map", "<", "Integer", ",", "Context", ">", "contexts", ")", "{", "Iterator", "<", "Context", ">", "contextsIter", "=", "contexts", ".", "values", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "context...
Remove all contexts that are expired. @param contexts all contexts currently in memory
[ "Remove", "all", "contexts", "that", "are", "expired", "." ]
train
https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L367-L376
jtablesaw/tablesaw
core/src/main/java/tech/tablesaw/aggregate/CrossTab.java
CrossTab.tablePercents
public static Table tablePercents(Table table, String column1, String column2) { return tablePercents(table, table.categoricalColumn(column1), table.categoricalColumn(column2)); }
java
public static Table tablePercents(Table table, String column1, String column2) { return tablePercents(table, table.categoricalColumn(column1), table.categoricalColumn(column2)); }
[ "public", "static", "Table", "tablePercents", "(", "Table", "table", ",", "String", "column1", ",", "String", "column2", ")", "{", "return", "tablePercents", "(", "table", ",", "table", ".", "categoricalColumn", "(", "column1", ")", ",", "table", ".", "categ...
Returns a table containing the table percents made from a source table, after first calculating the counts cross-tabulated from the given columns
[ "Returns", "a", "table", "containing", "the", "table", "percents", "made", "from", "a", "source", "table", "after", "first", "calculating", "the", "counts", "cross", "-", "tabulated", "from", "the", "given", "columns" ]
train
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/aggregate/CrossTab.java#L287-L289
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java
ColumnLayoutExample.addExample
private void addExample(final int[] colWidths) { add(new WHeading(HeadingLevel.H2, getTitle(colWidths))); WPanel panel = new WPanel(); panel.setLayout(new ColumnLayout(colWidths)); add(panel); for (int i = 0; i < colWidths.length; i++) { panel.add(new BoxComponent(colWidths[i] + "%")); } }
java
private void addExample(final int[] colWidths) { add(new WHeading(HeadingLevel.H2, getTitle(colWidths))); WPanel panel = new WPanel(); panel.setLayout(new ColumnLayout(colWidths)); add(panel); for (int i = 0; i < colWidths.length; i++) { panel.add(new BoxComponent(colWidths[i] + "%")); } }
[ "private", "void", "addExample", "(", "final", "int", "[", "]", "colWidths", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H2", ",", "getTitle", "(", "colWidths", ")", ")", ")", ";", "WPanel", "panel", "=", "new", "WPanel", "(", ...
Adds an example to the set of examples. @param colWidths the percentage widths for each column.
[ "Adds", "an", "example", "to", "the", "set", "of", "examples", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/ColumnLayoutExample.java#L56-L67
Azure/azure-sdk-for-java
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java
ManagedInstanceKeysInner.createOrUpdate
public ManagedInstanceKeyInner createOrUpdate(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).toBlocking().last().body(); }
java
public ManagedInstanceKeyInner createOrUpdate(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).toBlocking().last().body(); }
[ "public", "ManagedInstanceKeyInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "String", "keyName", ",", "ManagedInstanceKeyInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourc...
Creates or updates a managed instance key. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param keyName The name of the managed instance key to be operated on (updated or created). @param parameters The requested managed instance key resource state. @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 ManagedInstanceKeyInner object if successful.
[ "Creates", "or", "updates", "a", "managed", "instance", "key", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java#L444-L446
neuland/jade4j
src/main/java/org/apache/commons/jexl2/JadeIntrospect.java
JadeIntrospect.getPropertyGet
@SuppressWarnings("deprecation") @Override public JexlPropertyGet getPropertyGet(Object obj, Object identifier, JexlInfo info) { JexlPropertyGet get = getJadeGetExecutor(obj, identifier); if (get == null && obj != null && identifier != null) { get = getIndexedGet(obj, identifier.toString()); if (get == null) { Field field = getField(obj, identifier.toString(), info); if (field != null) { return new FieldPropertyGet(field); } } } return get; }
java
@SuppressWarnings("deprecation") @Override public JexlPropertyGet getPropertyGet(Object obj, Object identifier, JexlInfo info) { JexlPropertyGet get = getJadeGetExecutor(obj, identifier); if (get == null && obj != null && identifier != null) { get = getIndexedGet(obj, identifier.toString()); if (get == null) { Field field = getField(obj, identifier.toString(), info); if (field != null) { return new FieldPropertyGet(field); } } } return get; }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "@", "Override", "public", "JexlPropertyGet", "getPropertyGet", "(", "Object", "obj", ",", "Object", "identifier", ",", "JexlInfo", "info", ")", "{", "JexlPropertyGet", "get", "=", "getJadeGetExecutor", "(", "o...
Overwriting method to replace "getGetExecutor" call with "getJadeGetExecutor"
[ "Overwriting", "method", "to", "replace", "getGetExecutor", "call", "with", "getJadeGetExecutor" ]
train
https://github.com/neuland/jade4j/blob/621907732fb88c1b0145733624751f0fcaca2ff7/src/main/java/org/apache/commons/jexl2/JadeIntrospect.java#L25-L39
hankcs/HanLP
src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java
PerceptronClassifier.addFeature
protected static void addFeature(String feature, FeatureMap featureMap, List<Integer> featureList) { int featureId = featureMap.idOf(feature); if (featureId != -1) featureList.add(featureId); }
java
protected static void addFeature(String feature, FeatureMap featureMap, List<Integer> featureList) { int featureId = featureMap.idOf(feature); if (featureId != -1) featureList.add(featureId); }
[ "protected", "static", "void", "addFeature", "(", "String", "feature", ",", "FeatureMap", "featureMap", ",", "List", "<", "Integer", ">", "featureList", ")", "{", "int", "featureId", "=", "featureMap", ".", "idOf", "(", "feature", ")", ";", "if", "(", "fea...
向特征向量插入特征 @param feature 特征 @param featureMap 特征映射 @param featureList 特征向量
[ "向特征向量插入特征" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java#L228-L233
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/quantiles/Util.java
Util.computeRetainedItems
static int computeRetainedItems(final int k, final long n) { final int bbCnt = computeBaseBufferItems(k, n); final long bitPattern = computeBitPattern(k, n); final int validLevels = computeValidLevels(bitPattern); return bbCnt + (validLevels * k); }
java
static int computeRetainedItems(final int k, final long n) { final int bbCnt = computeBaseBufferItems(k, n); final long bitPattern = computeBitPattern(k, n); final int validLevels = computeValidLevels(bitPattern); return bbCnt + (validLevels * k); }
[ "static", "int", "computeRetainedItems", "(", "final", "int", "k", ",", "final", "long", "n", ")", "{", "final", "int", "bbCnt", "=", "computeBaseBufferItems", "(", "k", ",", "n", ")", ";", "final", "long", "bitPattern", "=", "computeBitPattern", "(", "k",...
Returns the number of retained valid items in the sketch given k and n. @param k the given configured k of the sketch @param n the current number of items seen by the sketch @return the number of retained items in the sketch given k and n.
[ "Returns", "the", "number", "of", "retained", "valid", "items", "in", "the", "sketch", "given", "k", "and", "n", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L321-L326
JoeKerouac/utils
src/main/java/com/joe/utils/secure/KeyTools.java
KeyTools.buildKey
public static SecretKey buildKey(AbstractCipher.Algorithms algorithm, byte[] keySpec) { SecretKeySpec key = new SecretKeySpec(keySpec, algorithm.name()); return key; }
java
public static SecretKey buildKey(AbstractCipher.Algorithms algorithm, byte[] keySpec) { SecretKeySpec key = new SecretKeySpec(keySpec, algorithm.name()); return key; }
[ "public", "static", "SecretKey", "buildKey", "(", "AbstractCipher", ".", "Algorithms", "algorithm", ",", "byte", "[", "]", "keySpec", ")", "{", "SecretKeySpec", "key", "=", "new", "SecretKeySpec", "(", "keySpec", ",", "algorithm", ".", "name", "(", ")", ")",...
使用指定keySpec构建对称加密的key @param algorithm 算法名称,当前仅支持AES和DES @param keySpec keySpec,多次调用该方法生成的key等效 @return 对称加密的key
[ "使用指定keySpec构建对称加密的key" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/secure/KeyTools.java#L125-L128
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/SVMLightClassifierFactory.java
SVMLightClassifierFactory.heldOutSetC
public void heldOutSetC(final GeneralDataset<L, F> trainSet, final GeneralDataset<L, F> devSet, final Scorer<L> scorer, LineSearcher minimizer) { useAlphaFile = true; boolean oldUseSigmoid = useSigmoid; useSigmoid = false; Function<Double,Double> negativeScorer = new Function<Double,Double> () { public Double apply(Double cToTry) { C = cToTry; SVMLightClassifier<L, F> classifier = trainClassifierBasic(trainSet); double score = scorer.score(classifier,devSet); return -score; } }; C = minimizer.minimize(negativeScorer); useAlphaFile = false; useSigmoid = oldUseSigmoid; }
java
public void heldOutSetC(final GeneralDataset<L, F> trainSet, final GeneralDataset<L, F> devSet, final Scorer<L> scorer, LineSearcher minimizer) { useAlphaFile = true; boolean oldUseSigmoid = useSigmoid; useSigmoid = false; Function<Double,Double> negativeScorer = new Function<Double,Double> () { public Double apply(Double cToTry) { C = cToTry; SVMLightClassifier<L, F> classifier = trainClassifierBasic(trainSet); double score = scorer.score(classifier,devSet); return -score; } }; C = minimizer.minimize(negativeScorer); useAlphaFile = false; useSigmoid = oldUseSigmoid; }
[ "public", "void", "heldOutSetC", "(", "final", "GeneralDataset", "<", "L", ",", "F", ">", "trainSet", ",", "final", "GeneralDataset", "<", "L", ",", "F", ">", "devSet", ",", "final", "Scorer", "<", "L", ">", "scorer", ",", "LineSearcher", "minimizer", ")...
This method will cross validate on the given data and number of folds to find the optimal C. The scorer is how you determine what to optimize for (F-score, accuracy, etc). The C is then saved, so that if you train a classifier after calling this method, that C will be used.
[ "This", "method", "will", "cross", "validate", "on", "the", "given", "data", "and", "number", "of", "folds", "to", "find", "the", "optimal", "C", ".", "The", "scorer", "is", "how", "you", "determine", "what", "to", "optimize", "for", "(", "F", "-", "sc...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/SVMLightClassifierFactory.java#L294-L315
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/RegionMap.java
RegionMap.toSubRegion
public RegionMap toSubRegion( Envelope envelope ) { double w = envelope.getMinX(); double s = envelope.getMinY(); double e = envelope.getMaxX(); double n = envelope.getMaxY(); return toSubRegion(n, s, w, e); }
java
public RegionMap toSubRegion( Envelope envelope ) { double w = envelope.getMinX(); double s = envelope.getMinY(); double e = envelope.getMaxX(); double n = envelope.getMaxY(); return toSubRegion(n, s, w, e); }
[ "public", "RegionMap", "toSubRegion", "(", "Envelope", "envelope", ")", "{", "double", "w", "=", "envelope", ".", "getMinX", "(", ")", ";", "double", "s", "=", "envelope", ".", "getMinY", "(", ")", ";", "double", "e", "=", "envelope", ".", "getMaxX", "...
Creates a new {@link RegionMap} cropped on the new bounds and snapped on the original grid. <p><b>The supplied bounds are contained in the resulting region.</b></p> @param envelope the envelope to snap. @return the new {@link RegionMap}.
[ "Creates", "a", "new", "{", "@link", "RegionMap", "}", "cropped", "on", "the", "new", "bounds", "and", "snapped", "on", "the", "original", "grid", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/RegionMap.java#L258-L264
spring-projects/spring-security-oauth
spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/OAuthProviderProcessingFilter.java
OAuthProviderProcessingFilter.parametersAreAdequate
protected boolean parametersAreAdequate(Map<String, String> oauthParams) { return oauthParams.containsKey(OAuthConsumerParameter.oauth_consumer_key.toString()); }
java
protected boolean parametersAreAdequate(Map<String, String> oauthParams) { return oauthParams.containsKey(OAuthConsumerParameter.oauth_consumer_key.toString()); }
[ "protected", "boolean", "parametersAreAdequate", "(", "Map", "<", "String", ",", "String", ">", "oauthParams", ")", "{", "return", "oauthParams", ".", "containsKey", "(", "OAuthConsumerParameter", ".", "oauth_consumer_key", ".", "toString", "(", ")", ")", ";", "...
By default, OAuth parameters are adequate if a consumer key is present. @param oauthParams The oauth params. @return Whether the parsed parameters are adequate.
[ "By", "default", "OAuth", "parameters", "are", "adequate", "if", "a", "consumer", "key", "is", "present", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/OAuthProviderProcessingFilter.java#L220-L222
google/closure-compiler
src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java
FeatureSet.with
@VisibleForTesting public FeatureSet with(Set<Feature> newFeatures) { return new FeatureSet(union(features, newFeatures)); }
java
@VisibleForTesting public FeatureSet with(Set<Feature> newFeatures) { return new FeatureSet(union(features, newFeatures)); }
[ "@", "VisibleForTesting", "public", "FeatureSet", "with", "(", "Set", "<", "Feature", ">", "newFeatures", ")", "{", "return", "new", "FeatureSet", "(", "union", "(", "features", ",", "newFeatures", ")", ")", ";", "}" ]
Returns a feature set combining all the features from {@code this} and {@code newFeatures}.
[ "Returns", "a", "feature", "set", "combining", "all", "the", "features", "from", "{" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java#L373-L376
eobermuhlner/big-math
ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java
BigDecimalMath.log10
public static BigDecimal log10(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 2, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTen(mc), mc); return round(result, mathContext); }
java
public static BigDecimal log10(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 2, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTen(mc), mc); return round(result, mathContext); }
[ "public", "static", "BigDecimal", "log10", "(", "BigDecimal", "x", ",", "MathContext", "mathContext", ")", "{", "checkMathContext", "(", "mathContext", ")", ";", "MathContext", "mc", "=", "new", "MathContext", "(", "mathContext", ".", "getPrecision", "(", ")", ...
Calculates the logarithm of {@link BigDecimal} x to the base 10. @param x the {@link BigDecimal} to calculate the logarithm base 10 for @param mathContext the {@link MathContext} used for the result @return the calculated natural logarithm {@link BigDecimal} to the base 10 with the precision specified in the <code>mathContext</code> @throws ArithmeticException if x &lt;= 0 @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
[ "Calculates", "the", "logarithm", "of", "{", "@link", "BigDecimal", "}", "x", "to", "the", "base", "10", "." ]
train
https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java#L936-L942
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.getCertificateContactsAsync
public ServiceFuture<Contacts> getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback<Contacts> serviceCallback) { return ServiceFuture.fromResponse(getCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); }
java
public ServiceFuture<Contacts> getCertificateContactsAsync(String vaultBaseUrl, final ServiceCallback<Contacts> serviceCallback) { return ServiceFuture.fromResponse(getCertificateContactsWithServiceResponseAsync(vaultBaseUrl), serviceCallback); }
[ "public", "ServiceFuture", "<", "Contacts", ">", "getCertificateContactsAsync", "(", "String", "vaultBaseUrl", ",", "final", "ServiceCallback", "<", "Contacts", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", ".", "fromResponse", "(", "getCertificateContact...
Lists the certificate contacts for a specified key vault. The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. This operation requires the certificates/managecontacts permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Lists", "the", "certificate", "contacts", "for", "a", "specified", "key", "vault", ".", "The", "GetCertificateContacts", "operation", "returns", "the", "set", "of", "certificate", "contact", "resources", "in", "the", "specified", "key", "vault", ".", "This", "o...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5514-L5516
OpenBEL/openbel-framework
org.openbel.framework.api/src/main/java/org/openbel/framework/api/OrthologizedKam.java
OrthologizedKam.wrapNode
private KamNode wrapNode(KamNode kamNode) { if (kamNode == null) { return null; } TermParameter param = ntp.get(kamNode.getId()); if (param != null) { return new OrthologousNode(kamNode, param); } return kamNode; }
java
private KamNode wrapNode(KamNode kamNode) { if (kamNode == null) { return null; } TermParameter param = ntp.get(kamNode.getId()); if (param != null) { return new OrthologousNode(kamNode, param); } return kamNode; }
[ "private", "KamNode", "wrapNode", "(", "KamNode", "kamNode", ")", "{", "if", "(", "kamNode", "==", "null", ")", "{", "return", "null", ";", "}", "TermParameter", "param", "=", "ntp", ".", "get", "(", "kamNode", ".", "getId", "(", ")", ")", ";", "if",...
Wrap a {@link KamNode} as an {@link OrthologousNode} to allow conversion of the node label by the {@link SpeciesDialect}. @param kamNode {@link KamNode} @return the wrapped kam node, <ol> <li>{@code null} if {@code kamNode} input is {@code null}</li> <li>{@link OrthologousNode} if {@code kamNode} has orthologized</li> <li>the original {@code kamNode} input if it has not orthologized</li> </ol>
[ "Wrap", "a", "{", "@link", "KamNode", "}", "as", "an", "{", "@link", "OrthologousNode", "}", "to", "allow", "conversion", "of", "the", "node", "label", "by", "the", "{", "@link", "SpeciesDialect", "}", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.api/src/main/java/org/openbel/framework/api/OrthologizedKam.java#L526-L537
threerings/nenya
core/src/main/java/com/threerings/miso/client/MisoScenePanel.java
MisoScenePanel.paintBits
@Override protected void paintBits (Graphics2D gfx, int layer, Rectangle dirty) { _animmgr.paint(gfx, layer, dirty); }
java
@Override protected void paintBits (Graphics2D gfx, int layer, Rectangle dirty) { _animmgr.paint(gfx, layer, dirty); }
[ "@", "Override", "protected", "void", "paintBits", "(", "Graphics2D", "gfx", ",", "int", "layer", ",", "Rectangle", "dirty", ")", "{", "_animmgr", ".", "paint", "(", "gfx", ",", "layer", ",", "dirty", ")", ";", "}" ]
We don't want sprites rendered using the standard mechanism because we intersperse them with objects in our scene and need to manage their z-order.
[ "We", "don", "t", "want", "sprites", "rendered", "using", "the", "standard", "mechanism", "because", "we", "intersperse", "them", "with", "objects", "in", "our", "scene", "and", "need", "to", "manage", "their", "z", "-", "order", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L1253-L1257
Stratio/deep-spark
deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/DeepCqlRecordWriter.java
DeepCqlRecordWriter.write
public void write(Cells keys, Cells values) { if (!hasCurrentTask) { String localCql = queryBuilder.prepareQuery(keys, values); currentTask = new WriteTask(localCql); hasCurrentTask = true; } // add primary key columns to the bind variables List<Object> allValues = new ArrayList<>(values.getCellValues()); allValues.addAll(keys.getCellValues()); currentTask.add(allValues); if (isBatchSizeReached()) { executeTaskAsync(); } }
java
public void write(Cells keys, Cells values) { if (!hasCurrentTask) { String localCql = queryBuilder.prepareQuery(keys, values); currentTask = new WriteTask(localCql); hasCurrentTask = true; } // add primary key columns to the bind variables List<Object> allValues = new ArrayList<>(values.getCellValues()); allValues.addAll(keys.getCellValues()); currentTask.add(allValues); if (isBatchSizeReached()) { executeTaskAsync(); } }
[ "public", "void", "write", "(", "Cells", "keys", ",", "Cells", "values", ")", "{", "if", "(", "!", "hasCurrentTask", ")", "{", "String", "localCql", "=", "queryBuilder", ".", "prepareQuery", "(", "keys", ",", "values", ")", ";", "currentTask", "=", "new"...
Adds the provided row to a batch. If the batch size reaches the threshold configured in IDeepJobConfig.getBatchSize the batch will be sent to the data store. @param keys the Cells object containing the row keys. @param values the Cells object containing all the other row columns.
[ "Adds", "the", "provided", "row", "to", "a", "batch", ".", "If", "the", "batch", "size", "reaches", "the", "threshold", "configured", "in", "IDeepJobConfig", ".", "getBatchSize", "the", "batch", "will", "be", "sent", "to", "the", "data", "store", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-cassandra/src/main/java/com/stratio/deep/cassandra/cql/DeepCqlRecordWriter.java#L107-L123
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java
SourceLineAnnotation.fromVisitedInstruction
public static SourceLineAnnotation fromVisitedInstruction(JavaClass jclass, Method method, int pc) { LineNumberTable lineNumberTable = method.getCode().getLineNumberTable(); String className = jclass.getClassName(); String sourceFile = jclass.getSourceFileName(); if (lineNumberTable == null) { return createUnknown(className, sourceFile, pc, pc); } int startLine = lineNumberTable.getSourceLine(pc); return new SourceLineAnnotation(className, sourceFile, startLine, startLine, pc, pc); }
java
public static SourceLineAnnotation fromVisitedInstruction(JavaClass jclass, Method method, int pc) { LineNumberTable lineNumberTable = method.getCode().getLineNumberTable(); String className = jclass.getClassName(); String sourceFile = jclass.getSourceFileName(); if (lineNumberTable == null) { return createUnknown(className, sourceFile, pc, pc); } int startLine = lineNumberTable.getSourceLine(pc); return new SourceLineAnnotation(className, sourceFile, startLine, startLine, pc, pc); }
[ "public", "static", "SourceLineAnnotation", "fromVisitedInstruction", "(", "JavaClass", "jclass", ",", "Method", "method", ",", "int", "pc", ")", "{", "LineNumberTable", "lineNumberTable", "=", "method", ".", "getCode", "(", ")", ".", "getLineNumberTable", "(", ")...
Create from Method and bytecode offset in a visited class. @param jclass JavaClass of visited class @param method Method in visited class @param pc bytecode offset in visited method @return SourceLineAnnotation describing visited instruction
[ "Create", "from", "Method", "and", "bytecode", "offset", "in", "a", "visited", "class", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/SourceLineAnnotation.java#L468-L478
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java
XsdAsmInterfaces.createSequenceClasses
private void createSequenceClasses(XsdAbstractElement sequenceElement, ClassWriter classWriter, String className, String typeName, String nextTypeName, String apiName, boolean isFirst){ List<XsdElement> elements = null; if (sequenceElement instanceof XsdElement) { elements = Collections.singletonList((XsdElement) sequenceElement); } if (sequenceElement instanceof XsdGroup || sequenceElement instanceof XsdChoice || sequenceElement instanceof XsdAll) { elements = getAllElementsRecursively(sequenceElement); } if (elements != null){ if (isFirst){ createFirstSequenceInterface(classWriter, className, nextTypeName, apiName, elements); } else { createElementsForSequence(className, typeName, nextTypeName, apiName, elements); } } }
java
private void createSequenceClasses(XsdAbstractElement sequenceElement, ClassWriter classWriter, String className, String typeName, String nextTypeName, String apiName, boolean isFirst){ List<XsdElement> elements = null; if (sequenceElement instanceof XsdElement) { elements = Collections.singletonList((XsdElement) sequenceElement); } if (sequenceElement instanceof XsdGroup || sequenceElement instanceof XsdChoice || sequenceElement instanceof XsdAll) { elements = getAllElementsRecursively(sequenceElement); } if (elements != null){ if (isFirst){ createFirstSequenceInterface(classWriter, className, nextTypeName, apiName, elements); } else { createElementsForSequence(className, typeName, nextTypeName, apiName, elements); } } }
[ "private", "void", "createSequenceClasses", "(", "XsdAbstractElement", "sequenceElement", ",", "ClassWriter", "classWriter", ",", "String", "className", ",", "String", "typeName", ",", "String", "nextTypeName", ",", "String", "apiName", ",", "boolean", "isFirst", ")",...
Creates classes and methods required to implement the sequence. @param sequenceElement The current sequence element. @param classWriter The {@link ClassWriter} of the first class, which contains the sequence. @param className The name of the class which contains the sequence. @param typeName The current sequence element type name. @param nextTypeName The next sequence element type name. @param apiName The name of the generated fluent interface. @param isFirst Indication if this is the first element of the sequence.
[ "Creates", "classes", "and", "methods", "required", "to", "implement", "the", "sequence", "." ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L425-L443
demidenko05/beigesoft-webstore
src/main/java/org/beigesoft/webstore/processor/PrcRefreshItemsInList.java
PrcRefreshItemsInList.findItemInListFor
protected final ItemInList findItemInListFor(final List<ItemInList> pItemsList, final Long pItemId, final EShopItemType pItemType) { int j = 0; while (j < pItemsList.size()) { if (pItemsList.get(j).getItsType().equals(pItemType) && pItemsList.get(j).getItemId().equals(pItemId)) { return pItemsList.get(j); } j++; } return null; }
java
protected final ItemInList findItemInListFor(final List<ItemInList> pItemsList, final Long pItemId, final EShopItemType pItemType) { int j = 0; while (j < pItemsList.size()) { if (pItemsList.get(j).getItsType().equals(pItemType) && pItemsList.get(j).getItemId().equals(pItemId)) { return pItemsList.get(j); } j++; } return null; }
[ "protected", "final", "ItemInList", "findItemInListFor", "(", "final", "List", "<", "ItemInList", ">", "pItemsList", ",", "final", "Long", "pItemId", ",", "final", "EShopItemType", "pItemType", ")", "{", "int", "j", "=", "0", ";", "while", "(", "j", "<", "...
<p>Find ItemInList with given item ID and type.</p> @param pItemsList items list @param pItemId Item ID @param pItemType Item type @return ItemInList with given item and type if exist or null
[ "<p", ">", "Find", "ItemInList", "with", "given", "item", "ID", "and", "type", ".", "<", "/", "p", ">" ]
train
https://github.com/demidenko05/beigesoft-webstore/blob/41ed2e2f1c640d37951d5fb235f26856008b87e1/src/main/java/org/beigesoft/webstore/processor/PrcRefreshItemsInList.java#L1150-L1160
JOML-CI/JOML
src/org/joml/Quaternionf.java
Quaternionf.rotationTo
public Quaternionf rotationTo(Vector3fc fromDir, Vector3fc toDir) { return rotationTo(fromDir.x(), fromDir.y(), fromDir.z(), toDir.x(), toDir.y(), toDir.z()); }
java
public Quaternionf rotationTo(Vector3fc fromDir, Vector3fc toDir) { return rotationTo(fromDir.x(), fromDir.y(), fromDir.z(), toDir.x(), toDir.y(), toDir.z()); }
[ "public", "Quaternionf", "rotationTo", "(", "Vector3fc", "fromDir", ",", "Vector3fc", "toDir", ")", "{", "return", "rotationTo", "(", "fromDir", ".", "x", "(", ")", ",", "fromDir", ".", "y", "(", ")", ",", "fromDir", ".", "z", "(", ")", ",", "toDir", ...
Set <code>this</code> quaternion to a rotation that rotates the <code>fromDir</code> vector to point along <code>toDir</code>. <p> Because there can be multiple possible rotations, this method chooses the one with the shortest arc. @see #rotationTo(float, float, float, float, float, float) @param fromDir the starting direction @param toDir the destination direction @return this
[ "Set", "<code", ">", "this<", "/", "code", ">", "quaternion", "to", "a", "rotation", "that", "rotates", "the", "<code", ">", "fromDir<", "/", "code", ">", "vector", "to", "point", "along", "<code", ">", "toDir<", "/", "code", ">", ".", "<p", ">", "Be...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L2261-L2263
arquillian/arquillian-algeron
common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java
GitOperations.pullFromRepository
public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) { try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
java
public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) { try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
[ "public", "PullResult", "pullFromRepository", "(", "Git", "git", ",", "String", "remote", ",", "String", "remoteBranch", ",", "String", "username", ",", "String", "password", ")", "{", "try", "{", "return", "git", ".", "pull", "(", ")", ".", "setRemote", "...
Pull repository from current branch and remote branch with same name as current @param git instance. @param remote to be used. @param remoteBranch to use. @param username to connect @param password to connect
[ "Pull", "repository", "from", "current", "branch", "and", "remote", "branch", "with", "same", "name", "as", "current" ]
train
https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L401-L411
prestodb/presto
presto-benchmark/src/main/java/com/facebook/presto/benchmark/HashJoinBenchmark.java
HashJoinBenchmark.createDrivers
@Override protected List<Driver> createDrivers(TaskContext taskContext) { if (probeDriverFactory == null) { List<Type> ordersTypes = getColumnTypes("orders", "orderkey", "totalprice"); OperatorFactory ordersTableScan = createTableScanOperator(0, new PlanNodeId("test"), "orders", "orderkey", "totalprice"); JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory( ordersTypes, ImmutableList.of(0, 1).stream() .map(ordersTypes::get) .collect(toImmutableList()), Ints.asList(0).stream() .map(ordersTypes::get) .collect(toImmutableList()), 1, requireNonNull(ImmutableMap.of(), "layout is null"), false)); HashBuilderOperatorFactory hashBuilder = new HashBuilderOperatorFactory( 1, new PlanNodeId("test"), lookupSourceFactoryManager, ImmutableList.of(0, 1), Ints.asList(0), OptionalInt.empty(), Optional.empty(), Optional.empty(), ImmutableList.of(), 1_500_000, new PagesIndex.TestingFactory(false), false, SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory()); DriverContext driverContext = taskContext.addPipelineContext(0, false, false, false).addDriverContext(); DriverFactory buildDriverFactory = new DriverFactory(0, false, false, ImmutableList.of(ordersTableScan, hashBuilder), OptionalInt.empty(), UNGROUPED_EXECUTION); List<Type> lineItemTypes = getColumnTypes("lineitem", "orderkey", "quantity"); OperatorFactory lineItemTableScan = createTableScanOperator(0, new PlanNodeId("test"), "lineitem", "orderkey", "quantity"); OperatorFactory joinOperator = LOOKUP_JOIN_OPERATORS.innerJoin(1, new PlanNodeId("test"), lookupSourceFactoryManager, lineItemTypes, Ints.asList(0), OptionalInt.empty(), Optional.empty(), OptionalInt.empty(), unsupportedPartitioningSpillerFactory()); NullOutputOperatorFactory output = new NullOutputOperatorFactory(2, new PlanNodeId("test")); this.probeDriverFactory = new DriverFactory(1, true, true, ImmutableList.of(lineItemTableScan, joinOperator, output), OptionalInt.empty(), UNGROUPED_EXECUTION); Driver driver = buildDriverFactory.createDriver(driverContext); Future<LookupSourceProvider> lookupSourceProvider = lookupSourceFactoryManager.getJoinBridge(Lifespan.taskWide()).createLookupSourceProvider(); while (!lookupSourceProvider.isDone()) { driver.process(); } getFutureValue(lookupSourceProvider).close(); } DriverContext driverContext = taskContext.addPipelineContext(1, true, true, false).addDriverContext(); Driver driver = probeDriverFactory.createDriver(driverContext); return ImmutableList.of(driver); }
java
@Override protected List<Driver> createDrivers(TaskContext taskContext) { if (probeDriverFactory == null) { List<Type> ordersTypes = getColumnTypes("orders", "orderkey", "totalprice"); OperatorFactory ordersTableScan = createTableScanOperator(0, new PlanNodeId("test"), "orders", "orderkey", "totalprice"); JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory( ordersTypes, ImmutableList.of(0, 1).stream() .map(ordersTypes::get) .collect(toImmutableList()), Ints.asList(0).stream() .map(ordersTypes::get) .collect(toImmutableList()), 1, requireNonNull(ImmutableMap.of(), "layout is null"), false)); HashBuilderOperatorFactory hashBuilder = new HashBuilderOperatorFactory( 1, new PlanNodeId("test"), lookupSourceFactoryManager, ImmutableList.of(0, 1), Ints.asList(0), OptionalInt.empty(), Optional.empty(), Optional.empty(), ImmutableList.of(), 1_500_000, new PagesIndex.TestingFactory(false), false, SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory()); DriverContext driverContext = taskContext.addPipelineContext(0, false, false, false).addDriverContext(); DriverFactory buildDriverFactory = new DriverFactory(0, false, false, ImmutableList.of(ordersTableScan, hashBuilder), OptionalInt.empty(), UNGROUPED_EXECUTION); List<Type> lineItemTypes = getColumnTypes("lineitem", "orderkey", "quantity"); OperatorFactory lineItemTableScan = createTableScanOperator(0, new PlanNodeId("test"), "lineitem", "orderkey", "quantity"); OperatorFactory joinOperator = LOOKUP_JOIN_OPERATORS.innerJoin(1, new PlanNodeId("test"), lookupSourceFactoryManager, lineItemTypes, Ints.asList(0), OptionalInt.empty(), Optional.empty(), OptionalInt.empty(), unsupportedPartitioningSpillerFactory()); NullOutputOperatorFactory output = new NullOutputOperatorFactory(2, new PlanNodeId("test")); this.probeDriverFactory = new DriverFactory(1, true, true, ImmutableList.of(lineItemTableScan, joinOperator, output), OptionalInt.empty(), UNGROUPED_EXECUTION); Driver driver = buildDriverFactory.createDriver(driverContext); Future<LookupSourceProvider> lookupSourceProvider = lookupSourceFactoryManager.getJoinBridge(Lifespan.taskWide()).createLookupSourceProvider(); while (!lookupSourceProvider.isDone()) { driver.process(); } getFutureValue(lookupSourceProvider).close(); } DriverContext driverContext = taskContext.addPipelineContext(1, true, true, false).addDriverContext(); Driver driver = probeDriverFactory.createDriver(driverContext); return ImmutableList.of(driver); }
[ "@", "Override", "protected", "List", "<", "Driver", ">", "createDrivers", "(", "TaskContext", "taskContext", ")", "{", "if", "(", "probeDriverFactory", "==", "null", ")", "{", "List", "<", "Type", ">", "ordersTypes", "=", "getColumnTypes", "(", "\"orders\"", ...
/* select orderkey, quantity, totalprice from lineitem join orders using (orderkey)
[ "/", "*", "select", "orderkey", "quantity", "totalprice", "from", "lineitem", "join", "orders", "using", "(", "orderkey", ")" ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-benchmark/src/main/java/com/facebook/presto/benchmark/HashJoinBenchmark.java#L65-L117
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201902/inventoryservice/GetAdUnitHierarchy.java
GetAdUnitHierarchy.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the InventoryService. InventoryServiceInterface inventoryService = adManagerServices.get(session, InventoryServiceInterface.class); // Get the NetworkService. NetworkServiceInterface networkService = adManagerServices.get(session, NetworkServiceInterface.class); // Get the effective root ad unit. String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId(); // Create a statement to select only the root ad unit by ID. StatementBuilder statementBuilder = new StatementBuilder() .where("id = :id") .orderBy("id ASC") .limit(1) .withBindVariableValue("id", rootAdUnitId); AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement()); AdUnit effectiveRootAdUnit = Iterables.getOnlyElement(Arrays.asList(page.getResults())); // Get all ad units. List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session); buildAndDisplayAdUnitTree(effectiveRootAdUnit, adUnits); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the InventoryService. InventoryServiceInterface inventoryService = adManagerServices.get(session, InventoryServiceInterface.class); // Get the NetworkService. NetworkServiceInterface networkService = adManagerServices.get(session, NetworkServiceInterface.class); // Get the effective root ad unit. String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId(); // Create a statement to select only the root ad unit by ID. StatementBuilder statementBuilder = new StatementBuilder() .where("id = :id") .orderBy("id ASC") .limit(1) .withBindVariableValue("id", rootAdUnitId); AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement()); AdUnit effectiveRootAdUnit = Iterables.getOnlyElement(Arrays.asList(page.getResults())); // Get all ad units. List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session); buildAndDisplayAdUnitTree(effectiveRootAdUnit, adUnits); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the InventoryService.", "InventoryServiceInterface", "inventoryService", "=", "adManagerServices", ".", ...
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201902/inventoryservice/GetAdUnitHierarchy.java#L60-L89
jenkinsci/jenkins
core/src/main/java/hudson/util/ChunkedOutputStream.java
ChunkedOutputStream.flushCacheWithAppend
protected void flushCacheWithAppend(byte[] bufferToAppend, int off, int len) throws IOException { byte[] chunkHeader = (Integer.toHexString(cachePosition + len) + "\r\n").getBytes(StandardCharsets.US_ASCII); stream.write(chunkHeader, 0, chunkHeader.length); stream.write(cache, 0, cachePosition); stream.write(bufferToAppend, off, len); stream.write(ENDCHUNK, 0, ENDCHUNK.length); cachePosition = 0; }
java
protected void flushCacheWithAppend(byte[] bufferToAppend, int off, int len) throws IOException { byte[] chunkHeader = (Integer.toHexString(cachePosition + len) + "\r\n").getBytes(StandardCharsets.US_ASCII); stream.write(chunkHeader, 0, chunkHeader.length); stream.write(cache, 0, cachePosition); stream.write(bufferToAppend, off, len); stream.write(ENDCHUNK, 0, ENDCHUNK.length); cachePosition = 0; }
[ "protected", "void", "flushCacheWithAppend", "(", "byte", "[", "]", "bufferToAppend", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "byte", "[", "]", "chunkHeader", "=", "(", "Integer", ".", "toHexString", "(", "cachePosition", "+"...
Writes the cache and bufferToAppend to the underlying stream as one large chunk @param bufferToAppend @param off @param len @throws IOException @since 3.0
[ "Writes", "the", "cache", "and", "bufferToAppend", "to", "the", "underlying", "stream", "as", "one", "large", "chunk", "@param", "bufferToAppend", "@param", "off", "@param", "len", "@throws", "IOException" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/ChunkedOutputStream.java#L118-L125
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/PeerGroup.java
PeerGroup.connectTo
@Nullable @GuardedBy("lock") protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, int connectTimeoutMillis) { checkState(lock.isHeldByCurrentThread()); VersionMessage ver = getVersionMessage().duplicate(); ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight(); ver.time = Utils.currentTimeSeconds(); ver.receivingAddr = address; ver.receivingAddr.setParent(ver); Peer peer = createPeer(address, ver); peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener); peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener); peer.setMinProtocolVersion(vMinRequiredProtocolVersion); pendingPeers.add(peer); try { log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address, peers.size(), pendingPeers.size(), maxConnections); ListenableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer); if (future.isDone()) Uninterruptibles.getUninterruptibly(future); } catch (ExecutionException e) { Throwable cause = Throwables.getRootCause(e); log.warn("Failed to connect to " + address + ": " + cause.getMessage()); handlePeerDeath(peer, cause); return null; } peer.setSocketTimeout(connectTimeoutMillis); // When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on // a worker thread. if (incrementMaxConnections) { // We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new // outbound connection. maxConnections++; } return peer; }
java
@Nullable @GuardedBy("lock") protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, int connectTimeoutMillis) { checkState(lock.isHeldByCurrentThread()); VersionMessage ver = getVersionMessage().duplicate(); ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight(); ver.time = Utils.currentTimeSeconds(); ver.receivingAddr = address; ver.receivingAddr.setParent(ver); Peer peer = createPeer(address, ver); peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener); peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener); peer.setMinProtocolVersion(vMinRequiredProtocolVersion); pendingPeers.add(peer); try { log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address, peers.size(), pendingPeers.size(), maxConnections); ListenableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer); if (future.isDone()) Uninterruptibles.getUninterruptibly(future); } catch (ExecutionException e) { Throwable cause = Throwables.getRootCause(e); log.warn("Failed to connect to " + address + ": " + cause.getMessage()); handlePeerDeath(peer, cause); return null; } peer.setSocketTimeout(connectTimeoutMillis); // When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on // a worker thread. if (incrementMaxConnections) { // We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new // outbound connection. maxConnections++; } return peer; }
[ "@", "Nullable", "@", "GuardedBy", "(", "\"lock\"", ")", "protected", "Peer", "connectTo", "(", "PeerAddress", "address", ",", "boolean", "incrementMaxConnections", ",", "int", "connectTimeoutMillis", ")", "{", "checkState", "(", "lock", ".", "isHeldByCurrentThread"...
Creates a version message to send, constructs a Peer object and attempts to connect it. Returns the peer on success or null on failure. @param address Remote network address @param incrementMaxConnections Whether to consider this connection an attempt to fill our quota, or something explicitly requested. @return Peer or null.
[ "Creates", "a", "version", "message", "to", "send", "constructs", "a", "Peer", "object", "and", "attempts", "to", "connect", "it", ".", "Returns", "the", "peer", "on", "success", "or", "null", "on", "failure", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1342-L1378