repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java
CommerceWarehousePersistenceImpl.countByG_A_P
@Override public int countByG_A_P(long groupId, boolean active, boolean primary) { """ Returns the number of commerce warehouses where groupId = ? and active = ? and primary = ?. @param groupId the group ID @param active the active @param primary the primary @return the number of matching commerce warehouses """ FinderPath finderPath = FINDER_PATH_COUNT_BY_G_A_P; Object[] finderArgs = new Object[] { groupId, active, primary }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_COMMERCEWAREHOUSE_WHERE); query.append(_FINDER_COLUMN_G_A_P_GROUPID_2); query.append(_FINDER_COLUMN_G_A_P_ACTIVE_2); query.append(_FINDER_COLUMN_G_A_P_PRIMARY_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(active); qPos.add(primary); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
java
@Override public int countByG_A_P(long groupId, boolean active, boolean primary) { FinderPath finderPath = FINDER_PATH_COUNT_BY_G_A_P; Object[] finderArgs = new Object[] { groupId, active, primary }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_COMMERCEWAREHOUSE_WHERE); query.append(_FINDER_COLUMN_G_A_P_GROUPID_2); query.append(_FINDER_COLUMN_G_A_P_ACTIVE_2); query.append(_FINDER_COLUMN_G_A_P_PRIMARY_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(active); qPos.add(primary); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
[ "@", "Override", "public", "int", "countByG_A_P", "(", "long", "groupId", ",", "boolean", "active", ",", "boolean", "primary", ")", "{", "FinderPath", "finderPath", "=", "FINDER_PATH_COUNT_BY_G_A_P", ";", "Object", "[", "]", "finderArgs", "=", "new", "Object", "[", "]", "{", "groupId", ",", "active", ",", "primary", "}", ";", "Long", "count", "=", "(", "Long", ")", "finderCache", ".", "getResult", "(", "finderPath", ",", "finderArgs", ",", "this", ")", ";", "if", "(", "count", "==", "null", ")", "{", "StringBundler", "query", "=", "new", "StringBundler", "(", "4", ")", ";", "query", ".", "append", "(", "_SQL_COUNT_COMMERCEWAREHOUSE_WHERE", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_A_P_GROUPID_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_A_P_ACTIVE_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_A_P_PRIMARY_2", ")", ";", "String", "sql", "=", "query", ".", "toString", "(", ")", ";", "Session", "session", "=", "null", ";", "try", "{", "session", "=", "openSession", "(", ")", ";", "Query", "q", "=", "session", ".", "createQuery", "(", "sql", ")", ";", "QueryPos", "qPos", "=", "QueryPos", ".", "getInstance", "(", "q", ")", ";", "qPos", ".", "add", "(", "groupId", ")", ";", "qPos", ".", "add", "(", "active", ")", ";", "qPos", ".", "add", "(", "primary", ")", ";", "count", "=", "(", "Long", ")", "q", ".", "uniqueResult", "(", ")", ";", "finderCache", ".", "putResult", "(", "finderPath", ",", "finderArgs", ",", "count", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "finderCache", ".", "removeResult", "(", "finderPath", ",", "finderArgs", ")", ";", "throw", "processException", "(", "e", ")", ";", "}", "finally", "{", "closeSession", "(", "session", ")", ";", "}", "}", "return", "count", ".", "intValue", "(", ")", ";", "}" ]
Returns the number of commerce warehouses where groupId = ? and active = ? and primary = ?. @param groupId the group ID @param active the active @param primary the primary @return the number of matching commerce warehouses
[ "Returns", "the", "number", "of", "commerce", "warehouses", "where", "groupId", "=", "&#63", ";", "and", "active", "=", "&#63", ";", "and", "primary", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java#L3374-L3425
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/interestrate/TermStructureModelMonteCarloSimulation.java
TermStructureModelMonteCarloSimulation.getCloneWithModifiedData
public TermStructureModelMonteCarloSimulationInterface getCloneWithModifiedData(String entityKey, Object dataModified) throws CalculationException { """ Create a clone of this simulation modifying one of its properties (if any). @param entityKey The entity to modify. @param dataModified The data which should be changed in the new model @return Returns a clone of this model, where the specified part of the data is modified data (then it is no longer a clone :-) @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. """ Map<String, Object> dataModifiedMap = new HashMap<String, Object>(); dataModifiedMap.put(entityKey, dataModified); return getCloneWithModifiedData(dataModifiedMap); }
java
public TermStructureModelMonteCarloSimulationInterface getCloneWithModifiedData(String entityKey, Object dataModified) throws CalculationException { Map<String, Object> dataModifiedMap = new HashMap<String, Object>(); dataModifiedMap.put(entityKey, dataModified); return getCloneWithModifiedData(dataModifiedMap); }
[ "public", "TermStructureModelMonteCarloSimulationInterface", "getCloneWithModifiedData", "(", "String", "entityKey", ",", "Object", "dataModified", ")", "throws", "CalculationException", "{", "Map", "<", "String", ",", "Object", ">", "dataModifiedMap", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "dataModifiedMap", ".", "put", "(", "entityKey", ",", "dataModified", ")", ";", "return", "getCloneWithModifiedData", "(", "dataModifiedMap", ")", ";", "}" ]
Create a clone of this simulation modifying one of its properties (if any). @param entityKey The entity to modify. @param dataModified The data which should be changed in the new model @return Returns a clone of this model, where the specified part of the data is modified data (then it is no longer a clone :-) @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "Create", "a", "clone", "of", "this", "simulation", "modifying", "one", "of", "its", "properties", "(", "if", "any", ")", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/TermStructureModelMonteCarloSimulation.java#L186-L191
overturetool/overture
core/typechecker/src/main/java/org/overture/typechecker/TypeComparator.java
TypeComparator.searchSubType
private Result searchSubType(PType sub, PType sup, boolean invignore) { """ Search the {@link #done} vector for an existing subtype comparison of two types before either returning the previous result, or making a new comparison and adding that result to the vector. @param sub @param sup @param invignore @return Yes or No, if sub is a subtype of sup. """ TypePair pair = new TypePair(sub, sup); int i = done.indexOf(pair); if (i >= 0) { return done.get(i).result; // May be "Maybe". } else { done.add(pair); } // The pair.result is "Maybe" until this call returns. pair.result = subtest(sub, sup, invignore); return pair.result; }
java
private Result searchSubType(PType sub, PType sup, boolean invignore) { TypePair pair = new TypePair(sub, sup); int i = done.indexOf(pair); if (i >= 0) { return done.get(i).result; // May be "Maybe". } else { done.add(pair); } // The pair.result is "Maybe" until this call returns. pair.result = subtest(sub, sup, invignore); return pair.result; }
[ "private", "Result", "searchSubType", "(", "PType", "sub", ",", "PType", "sup", ",", "boolean", "invignore", ")", "{", "TypePair", "pair", "=", "new", "TypePair", "(", "sub", ",", "sup", ")", ";", "int", "i", "=", "done", ".", "indexOf", "(", "pair", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "return", "done", ".", "get", "(", "i", ")", ".", "result", ";", "// May be \"Maybe\".", "}", "else", "{", "done", ".", "add", "(", "pair", ")", ";", "}", "// The pair.result is \"Maybe\" until this call returns.", "pair", ".", "result", "=", "subtest", "(", "sub", ",", "sup", ",", "invignore", ")", ";", "return", "pair", ".", "result", ";", "}" ]
Search the {@link #done} vector for an existing subtype comparison of two types before either returning the previous result, or making a new comparison and adding that result to the vector. @param sub @param sup @param invignore @return Yes or No, if sub is a subtype of sup.
[ "Search", "the", "{", "@link", "#done", "}", "vector", "for", "an", "existing", "subtype", "comparison", "of", "two", "types", "before", "either", "returning", "the", "previous", "result", "or", "making", "a", "new", "comparison", "and", "adding", "that", "result", "to", "the", "vector", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/typechecker/src/main/java/org/overture/typechecker/TypeComparator.java#L586-L603
lotaris/rox-client-java
rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java
Configuration.getUid
public String getUid(String category, String projectName, String projectVersion, boolean force) { """ Generate a UID or retrieve the latest if it is valid depending the context given by the category, project name and project version @param category The category @param projectName The project name @param projectVersion The project version @param force Force the generation of a new UID @return The valid UID """ String uid = null; if (!force) { uid = readUid(new File(uidDirectory, "latest")); } // Check if the UID was already used for the ROX client and projec/version if (uid != null && uidAlreadyUsed(category, projectName, uid)) { uid = null; } // Generate UID and store it if (uid == null) { uid = generateUid(); writeUid(new File(uidDirectory, "latest"), uid); } writeUid(getUidFile(category, projectName, projectVersion), uid); return uid; }
java
public String getUid(String category, String projectName, String projectVersion, boolean force) { String uid = null; if (!force) { uid = readUid(new File(uidDirectory, "latest")); } // Check if the UID was already used for the ROX client and projec/version if (uid != null && uidAlreadyUsed(category, projectName, uid)) { uid = null; } // Generate UID and store it if (uid == null) { uid = generateUid(); writeUid(new File(uidDirectory, "latest"), uid); } writeUid(getUidFile(category, projectName, projectVersion), uid); return uid; }
[ "public", "String", "getUid", "(", "String", "category", ",", "String", "projectName", ",", "String", "projectVersion", ",", "boolean", "force", ")", "{", "String", "uid", "=", "null", ";", "if", "(", "!", "force", ")", "{", "uid", "=", "readUid", "(", "new", "File", "(", "uidDirectory", ",", "\"latest\"", ")", ")", ";", "}", "// Check if the UID was already used for the ROX client and projec/version", "if", "(", "uid", "!=", "null", "&&", "uidAlreadyUsed", "(", "category", ",", "projectName", ",", "uid", ")", ")", "{", "uid", "=", "null", ";", "}", "// Generate UID and store it", "if", "(", "uid", "==", "null", ")", "{", "uid", "=", "generateUid", "(", ")", ";", "writeUid", "(", "new", "File", "(", "uidDirectory", ",", "\"latest\"", ")", ",", "uid", ")", ";", "}", "writeUid", "(", "getUidFile", "(", "category", ",", "projectName", ",", "projectVersion", ")", ",", "uid", ")", ";", "return", "uid", ";", "}" ]
Generate a UID or retrieve the latest if it is valid depending the context given by the category, project name and project version @param category The category @param projectName The project name @param projectVersion The project version @param force Force the generation of a new UID @return The valid UID
[ "Generate", "a", "UID", "or", "retrieve", "the", "latest", "if", "it", "is", "valid", "depending", "the", "context", "given", "by", "the", "category", "project", "name", "and", "project", "version" ]
train
https://github.com/lotaris/rox-client-java/blob/1b33f7560347c382c59a40c4037d175ab8127fde/rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java#L422-L443
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
JdbcProjectImpl.addProjectToProjectVersions
private void addProjectToProjectVersions( final DatabaseTransOperator transOperator, final int projectId, final int version, final File localFile, final String uploader, final byte[] md5, final String resourceId) throws ProjectManagerException { """ Insert a new version record to TABLE project_versions before uploading files. The reason for this operation: When error chunking happens in remote mysql server, incomplete file data remains in DB, and an SQL exception is thrown. If we don't have this operation before uploading file, the SQL exception prevents AZ from creating the new version record in Table project_versions. However, the Table project_files still reserve the incomplete files, which causes troubles when uploading a new file: Since the version in TABLE project_versions is still old, mysql will stop inserting new files to db. Why this operation is safe: When AZ uploads a new zip file, it always fetches the latest version proj_v from TABLE project_version, proj_v+1 will be used as the new version for the uploading files. Assume error chunking happens on day 1. proj_v is created for this bad file (old file version + 1). When we upload a new project zip in day2, new file in day 2 will use the new version (proj_v + 1). When file uploading completes, AZ will clean all old chunks in DB afterward. """ final long updateTime = System.currentTimeMillis(); final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions " + "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id) values " + "(?,?,?,?,?,?,?,?,?)"; try { /* * As we don't know the num_chunks before uploading the file, we initialize it to 0, * and will update it after uploading completes. */ transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader, Files.getFileExtension(localFile.getName()), localFile.getName(), md5, 0, resourceId); } catch (final SQLException e) { final String msg = String .format("Error initializing project id: %d version: %d ", projectId, version); logger.error(msg, e); throw new ProjectManagerException(msg, e); } }
java
private void addProjectToProjectVersions( final DatabaseTransOperator transOperator, final int projectId, final int version, final File localFile, final String uploader, final byte[] md5, final String resourceId) throws ProjectManagerException { final long updateTime = System.currentTimeMillis(); final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions " + "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id) values " + "(?,?,?,?,?,?,?,?,?)"; try { /* * As we don't know the num_chunks before uploading the file, we initialize it to 0, * and will update it after uploading completes. */ transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader, Files.getFileExtension(localFile.getName()), localFile.getName(), md5, 0, resourceId); } catch (final SQLException e) { final String msg = String .format("Error initializing project id: %d version: %d ", projectId, version); logger.error(msg, e); throw new ProjectManagerException(msg, e); } }
[ "private", "void", "addProjectToProjectVersions", "(", "final", "DatabaseTransOperator", "transOperator", ",", "final", "int", "projectId", ",", "final", "int", "version", ",", "final", "File", "localFile", ",", "final", "String", "uploader", ",", "final", "byte", "[", "]", "md5", ",", "final", "String", "resourceId", ")", "throws", "ProjectManagerException", "{", "final", "long", "updateTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "final", "String", "INSERT_PROJECT_VERSION", "=", "\"INSERT INTO project_versions \"", "+", "\"(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id) values \"", "+", "\"(?,?,?,?,?,?,?,?,?)\"", ";", "try", "{", "/*\n * As we don't know the num_chunks before uploading the file, we initialize it to 0,\n * and will update it after uploading completes.\n */", "transOperator", ".", "update", "(", "INSERT_PROJECT_VERSION", ",", "projectId", ",", "version", ",", "updateTime", ",", "uploader", ",", "Files", ".", "getFileExtension", "(", "localFile", ".", "getName", "(", ")", ")", ",", "localFile", ".", "getName", "(", ")", ",", "md5", ",", "0", ",", "resourceId", ")", ";", "}", "catch", "(", "final", "SQLException", "e", ")", "{", "final", "String", "msg", "=", "String", ".", "format", "(", "\"Error initializing project id: %d version: %d \"", ",", "projectId", ",", "version", ")", ";", "logger", ".", "error", "(", "msg", ",", "e", ")", ";", "throw", "new", "ProjectManagerException", "(", "msg", ",", "e", ")", ";", "}", "}" ]
Insert a new version record to TABLE project_versions before uploading files. The reason for this operation: When error chunking happens in remote mysql server, incomplete file data remains in DB, and an SQL exception is thrown. If we don't have this operation before uploading file, the SQL exception prevents AZ from creating the new version record in Table project_versions. However, the Table project_files still reserve the incomplete files, which causes troubles when uploading a new file: Since the version in TABLE project_versions is still old, mysql will stop inserting new files to db. Why this operation is safe: When AZ uploads a new zip file, it always fetches the latest version proj_v from TABLE project_version, proj_v+1 will be used as the new version for the uploading files. Assume error chunking happens on day 1. proj_v is created for this bad file (old file version + 1). When we upload a new project zip in day2, new file in day 2 will use the new version (proj_v + 1). When file uploading completes, AZ will clean all old chunks in DB afterward.
[ "Insert", "a", "new", "version", "record", "to", "TABLE", "project_versions", "before", "uploading", "files", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java#L344-L370
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractTreeWriter.java
AbstractTreeWriter.addTree
protected void addTree(SortedSet<TypeElement> sset, String heading, HtmlTree div) { """ Add the heading for the tree depending upon tree type if it's a Class Tree or Interface tree. @param sset classes which are at the most base level, all the other classes in this run will derive from these classes @param heading heading for the tree @param div the content tree to which the tree will be added """ addTree(sset, heading, div, false); }
java
protected void addTree(SortedSet<TypeElement> sset, String heading, HtmlTree div) { addTree(sset, heading, div, false); }
[ "protected", "void", "addTree", "(", "SortedSet", "<", "TypeElement", ">", "sset", ",", "String", "heading", ",", "HtmlTree", "div", ")", "{", "addTree", "(", "sset", ",", "heading", ",", "div", ",", "false", ")", ";", "}" ]
Add the heading for the tree depending upon tree type if it's a Class Tree or Interface tree. @param sset classes which are at the most base level, all the other classes in this run will derive from these classes @param heading heading for the tree @param div the content tree to which the tree will be added
[ "Add", "the", "heading", "for", "the", "tree", "depending", "upon", "tree", "type", "if", "it", "s", "a", "Class", "Tree", "or", "Interface", "tree", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractTreeWriter.java#L111-L113
spacecowboy/NoNonsense-FilePicker
library/src/main/java/com/nononsenseapps/filepicker/FilePickerFragment.java
FilePickerFragment.compareFiles
protected int compareFiles(@NonNull File lhs, @NonNull File rhs) { """ Compare two files to determine their relative sort order. This follows the usual comparison interface. Override to determine your own custom sort order. <p/> Default behaviour is to place directories before files, but sort them alphabetically otherwise. @param lhs File on the "left-hand side" @param rhs File on the "right-hand side" @return -1 if if lhs should be placed before rhs, 0 if they are equal, and 1 if rhs should be placed before lhs """ if (lhs.isDirectory() && !rhs.isDirectory()) { return -1; } else if (rhs.isDirectory() && !lhs.isDirectory()) { return 1; } else { return lhs.getName().compareToIgnoreCase(rhs.getName()); } }
java
protected int compareFiles(@NonNull File lhs, @NonNull File rhs) { if (lhs.isDirectory() && !rhs.isDirectory()) { return -1; } else if (rhs.isDirectory() && !lhs.isDirectory()) { return 1; } else { return lhs.getName().compareToIgnoreCase(rhs.getName()); } }
[ "protected", "int", "compareFiles", "(", "@", "NonNull", "File", "lhs", ",", "@", "NonNull", "File", "rhs", ")", "{", "if", "(", "lhs", ".", "isDirectory", "(", ")", "&&", "!", "rhs", ".", "isDirectory", "(", ")", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "rhs", ".", "isDirectory", "(", ")", "&&", "!", "lhs", ".", "isDirectory", "(", ")", ")", "{", "return", "1", ";", "}", "else", "{", "return", "lhs", ".", "getName", "(", ")", ".", "compareToIgnoreCase", "(", "rhs", ".", "getName", "(", ")", ")", ";", "}", "}" ]
Compare two files to determine their relative sort order. This follows the usual comparison interface. Override to determine your own custom sort order. <p/> Default behaviour is to place directories before files, but sort them alphabetically otherwise. @param lhs File on the "left-hand side" @param rhs File on the "right-hand side" @return -1 if if lhs should be placed before rhs, 0 if they are equal, and 1 if rhs should be placed before lhs
[ "Compare", "two", "files", "to", "determine", "their", "relative", "sort", "order", ".", "This", "follows", "the", "usual", "comparison", "interface", ".", "Override", "to", "determine", "your", "own", "custom", "sort", "order", ".", "<p", "/", ">", "Default", "behaviour", "is", "to", "place", "directories", "before", "files", "but", "sort", "them", "alphabetically", "otherwise", "." ]
train
https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/FilePickerFragment.java#L346-L354
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/action/menu/ToggleEditModeAction.java
ToggleEditModeAction.execute
public boolean execute(Canvas target, Menu menu, MenuItem item) { """ This menu item will be checked if the controller is in {@link #EditController.INSERT_MODE}. """ if (editController.getEditMode() == EditMode.DRAG_MODE) { return false; } return true; }
java
public boolean execute(Canvas target, Menu menu, MenuItem item) { if (editController.getEditMode() == EditMode.DRAG_MODE) { return false; } return true; }
[ "public", "boolean", "execute", "(", "Canvas", "target", ",", "Menu", "menu", ",", "MenuItem", "item", ")", "{", "if", "(", "editController", ".", "getEditMode", "(", ")", "==", "EditMode", ".", "DRAG_MODE", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
This menu item will be checked if the controller is in {@link #EditController.INSERT_MODE}.
[ "This", "menu", "item", "will", "be", "checked", "if", "the", "controller", "is", "in", "{" ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/action/menu/ToggleEditModeAction.java#L61-L66
m-m-m/util
gwt/src/main/java/net/sf/mmm/util/nls/base/AbstractNlsResourceBundleJavaScriptServlet.java
AbstractNlsResourceBundleJavaScriptServlet.writeBundle
protected void writeBundle(PrintWriter writer, String name, ResourceBundle bundle) { """ This method writes the given {@link ResourceBundle} to the {@code writer}. @param writer is the {@link PrintWriter} to use. @param name is the {@link ResourceBundle#getBundle(String) bundle name}. @param bundle is the {@link ResourceBundle} for the users locale to write to the given {@code writer}. """ writer.print("var "); writer.print(escapeBundleName(name)); writer.println(" = {"); Enumeration<String> keyEnum = bundle.getKeys(); while (keyEnum.hasMoreElements()) { String key = keyEnum.nextElement(); Object object = bundle.getObject(key); if (object instanceof String) { writer.print(escapeBundleKey(key)); writer.print(":\""); writer.print(object.toString()); writer.print("\","); } } writer.println("};"); }
java
protected void writeBundle(PrintWriter writer, String name, ResourceBundle bundle) { writer.print("var "); writer.print(escapeBundleName(name)); writer.println(" = {"); Enumeration<String> keyEnum = bundle.getKeys(); while (keyEnum.hasMoreElements()) { String key = keyEnum.nextElement(); Object object = bundle.getObject(key); if (object instanceof String) { writer.print(escapeBundleKey(key)); writer.print(":\""); writer.print(object.toString()); writer.print("\","); } } writer.println("};"); }
[ "protected", "void", "writeBundle", "(", "PrintWriter", "writer", ",", "String", "name", ",", "ResourceBundle", "bundle", ")", "{", "writer", ".", "print", "(", "\"var \"", ")", ";", "writer", ".", "print", "(", "escapeBundleName", "(", "name", ")", ")", ";", "writer", ".", "println", "(", "\" = {\"", ")", ";", "Enumeration", "<", "String", ">", "keyEnum", "=", "bundle", ".", "getKeys", "(", ")", ";", "while", "(", "keyEnum", ".", "hasMoreElements", "(", ")", ")", "{", "String", "key", "=", "keyEnum", ".", "nextElement", "(", ")", ";", "Object", "object", "=", "bundle", ".", "getObject", "(", "key", ")", ";", "if", "(", "object", "instanceof", "String", ")", "{", "writer", ".", "print", "(", "escapeBundleKey", "(", "key", ")", ")", ";", "writer", ".", "print", "(", "\":\\\"\"", ")", ";", "writer", ".", "print", "(", "object", ".", "toString", "(", ")", ")", ";", "writer", ".", "print", "(", "\"\\\",\"", ")", ";", "}", "}", "writer", ".", "println", "(", "\"};\"", ")", ";", "}" ]
This method writes the given {@link ResourceBundle} to the {@code writer}. @param writer is the {@link PrintWriter} to use. @param name is the {@link ResourceBundle#getBundle(String) bundle name}. @param bundle is the {@link ResourceBundle} for the users locale to write to the given {@code writer}.
[ "This", "method", "writes", "the", "given", "{", "@link", "ResourceBundle", "}", "to", "the", "{", "@code", "writer", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/gwt/src/main/java/net/sf/mmm/util/nls/base/AbstractNlsResourceBundleJavaScriptServlet.java#L81-L98
lindar-open/well-rested-client
src/main/java/com/lindar/wellrested/WellRestedRequestBuilder.java
WellRestedRequestBuilder.addGlobalHeader
public WellRestedRequestBuilder addGlobalHeader(String name, String value) { """ Use this method to add one more global header. These headers are going to be added on every request you make. <br/> A good use for this method is setting a global authentication header or a content type header. """ if (this.globalHeaders == null) { this.globalHeaders = new ArrayList<>(); } this.globalHeaders.add(new BasicHeader(name, value)); return this; }
java
public WellRestedRequestBuilder addGlobalHeader(String name, String value) { if (this.globalHeaders == null) { this.globalHeaders = new ArrayList<>(); } this.globalHeaders.add(new BasicHeader(name, value)); return this; }
[ "public", "WellRestedRequestBuilder", "addGlobalHeader", "(", "String", "name", ",", "String", "value", ")", "{", "if", "(", "this", ".", "globalHeaders", "==", "null", ")", "{", "this", ".", "globalHeaders", "=", "new", "ArrayList", "<>", "(", ")", ";", "}", "this", ".", "globalHeaders", ".", "add", "(", "new", "BasicHeader", "(", "name", ",", "value", ")", ")", ";", "return", "this", ";", "}" ]
Use this method to add one more global header. These headers are going to be added on every request you make. <br/> A good use for this method is setting a global authentication header or a content type header.
[ "Use", "this", "method", "to", "add", "one", "more", "global", "header", ".", "These", "headers", "are", "going", "to", "be", "added", "on", "every", "request", "you", "make", ".", "<br", "/", ">", "A", "good", "use", "for", "this", "method", "is", "setting", "a", "global", "authentication", "header", "or", "a", "content", "type", "header", "." ]
train
https://github.com/lindar-open/well-rested-client/blob/d87542f747cd624e3ce0cdc8230f51836326596b/src/main/java/com/lindar/wellrested/WellRestedRequestBuilder.java#L165-L171
FasterXML/woodstox
src/main/java/com/ctc/wstx/dtd/DTDAttribute.java
DTDAttribute.checkEntity
protected void checkEntity(InputProblemReporter rep, String id, EntityDecl ent) throws XMLStreamException { """ /* Too bad this method can not be combined with previous segment -- the reason is that DTDValidator does not implement InputProblemReporter... """ if (ent == null) { rep.reportValidationProblem("Referenced entity '"+id+"' not defined"); } else if (ent.isParsed()) { rep.reportValidationProblem("Referenced entity '"+id+"' is not an unparsed entity"); } }
java
protected void checkEntity(InputProblemReporter rep, String id, EntityDecl ent) throws XMLStreamException { if (ent == null) { rep.reportValidationProblem("Referenced entity '"+id+"' not defined"); } else if (ent.isParsed()) { rep.reportValidationProblem("Referenced entity '"+id+"' is not an unparsed entity"); } }
[ "protected", "void", "checkEntity", "(", "InputProblemReporter", "rep", ",", "String", "id", ",", "EntityDecl", "ent", ")", "throws", "XMLStreamException", "{", "if", "(", "ent", "==", "null", ")", "{", "rep", ".", "reportValidationProblem", "(", "\"Referenced entity '\"", "+", "id", "+", "\"' not defined\"", ")", ";", "}", "else", "if", "(", "ent", ".", "isParsed", "(", ")", ")", "{", "rep", ".", "reportValidationProblem", "(", "\"Referenced entity '\"", "+", "id", "+", "\"' is not an unparsed entity\"", ")", ";", "}", "}" ]
/* Too bad this method can not be combined with previous segment -- the reason is that DTDValidator does not implement InputProblemReporter...
[ "/", "*", "Too", "bad", "this", "method", "can", "not", "be", "combined", "with", "previous", "segment", "--", "the", "reason", "is", "that", "DTDValidator", "does", "not", "implement", "InputProblemReporter", "..." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/dtd/DTDAttribute.java#L469-L477
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RouterClient.java
RouterClient.previewRouter
@BetaApi public final RoutersPreviewResponse previewRouter(String router, Router routerResource) { """ Preview fields auto-generated during router create and update operations. Calling this method does NOT create or update the router. <p>Sample code: <pre><code> try (RouterClient routerClient = RouterClient.create()) { ProjectRegionRouterName router = ProjectRegionRouterName.of("[PROJECT]", "[REGION]", "[ROUTER]"); Router routerResource = Router.newBuilder().build(); RoutersPreviewResponse response = routerClient.previewRouter(router.toString(), routerResource); } </code></pre> @param router Name of the Router resource to query. @param routerResource Router resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ PreviewRouterHttpRequest request = PreviewRouterHttpRequest.newBuilder() .setRouter(router) .setRouterResource(routerResource) .build(); return previewRouter(request); }
java
@BetaApi public final RoutersPreviewResponse previewRouter(String router, Router routerResource) { PreviewRouterHttpRequest request = PreviewRouterHttpRequest.newBuilder() .setRouter(router) .setRouterResource(routerResource) .build(); return previewRouter(request); }
[ "@", "BetaApi", "public", "final", "RoutersPreviewResponse", "previewRouter", "(", "String", "router", ",", "Router", "routerResource", ")", "{", "PreviewRouterHttpRequest", "request", "=", "PreviewRouterHttpRequest", ".", "newBuilder", "(", ")", ".", "setRouter", "(", "router", ")", ".", "setRouterResource", "(", "routerResource", ")", ".", "build", "(", ")", ";", "return", "previewRouter", "(", "request", ")", ";", "}" ]
Preview fields auto-generated during router create and update operations. Calling this method does NOT create or update the router. <p>Sample code: <pre><code> try (RouterClient routerClient = RouterClient.create()) { ProjectRegionRouterName router = ProjectRegionRouterName.of("[PROJECT]", "[REGION]", "[ROUTER]"); Router routerResource = Router.newBuilder().build(); RoutersPreviewResponse response = routerClient.previewRouter(router.toString(), routerResource); } </code></pre> @param router Name of the Router resource to query. @param routerResource Router resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Preview", "fields", "auto", "-", "generated", "during", "router", "create", "and", "update", "operations", ".", "Calling", "this", "method", "does", "NOT", "create", "or", "update", "the", "router", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RouterClient.java#L1156-L1165
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/format/FastDateFormat.java
FastDateFormat.getInstance
public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) { """ 获得 {@link FastDateFormat} 实例<br> 支持缓存 @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式 @param timeZone 时区{@link TimeZone} @param locale {@link Locale} 日期地理位置 @return {@link FastDateFormat} @throws IllegalArgumentException 日期格式问题 """ return cache.getInstance(pattern, timeZone, locale); }
java
public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) { return cache.getInstance(pattern, timeZone, locale); }
[ "public", "static", "FastDateFormat", "getInstance", "(", "final", "String", "pattern", ",", "final", "TimeZone", "timeZone", ",", "final", "Locale", "locale", ")", "{", "return", "cache", ".", "getInstance", "(", "pattern", ",", "timeZone", ",", "locale", ")", ";", "}" ]
获得 {@link FastDateFormat} 实例<br> 支持缓存 @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式 @param timeZone 时区{@link TimeZone} @param locale {@link Locale} 日期地理位置 @return {@link FastDateFormat} @throws IllegalArgumentException 日期格式问题
[ "获得", "{", "@link", "FastDateFormat", "}", "实例<br", ">", "支持缓存" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/format/FastDateFormat.java#L109-L111
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/script/el/tokens/ExpressionToken.java
ExpressionToken.listUpdate
protected final void listUpdate(List list, int index, Object value) { """ Update a {@link List} with the Object <code>value</code> at <code>index</code>. @param list the List @param index the index @param value the new value """ Object converted = value; if(list.size() > index) { Object o = list.get(index); // can only convert types when there is an item in the currently requested place if(o != null) { Class itemType = o.getClass(); converted = ParseUtils.convertType(value, itemType); } list.set(index, value); } else { // @note: not sure that this is the right thing. Question is whether or not to insert nulls here to fill list up to "index" // @update: List doesn't guarantee that implementations will accept nulls. So, we can't rely on that as a solution. // @update: this is an unfortunate but necessary solution...unless the List has enough elements to // accomodate the new item at a particular index, this must be an error case. The reasons are this: // 1) can't fill the list with nulls, List implementations are allowed to disallow them // 2) can't just do an "add" to the list -- in processing [0] and [1] on an empty list, [1] may get processed first. // this will go into list slot [0]. then, [0] gets processed and simply overwrites the previous because it's // already in the list // 3) can't go to a mixed approach because there's no metadata about what has been done and no time to build // something that is apt to be complicated and exposed to the user // so... // the ultimate 8.1sp2 functionality is to simply disallow updating a value in a list that doesn't exist. that // being said, it is still possible to simply add to the list. if {actionForm.list[42]} inserts into the 42'nd // item, {actionForm.list} will just do an append on POST since there is no index specified. this fix does // not break backwards compatability because it will work on full lists and is completely broken now on empty // lists, so changing this just gives a better exception message that "ArrayIndexOutOfBounds". :) // // September 2, 2003 // [email protected] // String msg = "An error occurred setting a value at index \"" + index + "\" because the list is " + (list != null ? (" of size " + list.size()) : "null") + ". " + "Be sure to allocate enough items in the List to accomodate any updates which may occur against the list."; LOGGER.error(msg); throw new RuntimeException(msg); } }
java
protected final void listUpdate(List list, int index, Object value) { Object converted = value; if(list.size() > index) { Object o = list.get(index); // can only convert types when there is an item in the currently requested place if(o != null) { Class itemType = o.getClass(); converted = ParseUtils.convertType(value, itemType); } list.set(index, value); } else { // @note: not sure that this is the right thing. Question is whether or not to insert nulls here to fill list up to "index" // @update: List doesn't guarantee that implementations will accept nulls. So, we can't rely on that as a solution. // @update: this is an unfortunate but necessary solution...unless the List has enough elements to // accomodate the new item at a particular index, this must be an error case. The reasons are this: // 1) can't fill the list with nulls, List implementations are allowed to disallow them // 2) can't just do an "add" to the list -- in processing [0] and [1] on an empty list, [1] may get processed first. // this will go into list slot [0]. then, [0] gets processed and simply overwrites the previous because it's // already in the list // 3) can't go to a mixed approach because there's no metadata about what has been done and no time to build // something that is apt to be complicated and exposed to the user // so... // the ultimate 8.1sp2 functionality is to simply disallow updating a value in a list that doesn't exist. that // being said, it is still possible to simply add to the list. if {actionForm.list[42]} inserts into the 42'nd // item, {actionForm.list} will just do an append on POST since there is no index specified. this fix does // not break backwards compatability because it will work on full lists and is completely broken now on empty // lists, so changing this just gives a better exception message that "ArrayIndexOutOfBounds". :) // // September 2, 2003 // [email protected] // String msg = "An error occurred setting a value at index \"" + index + "\" because the list is " + (list != null ? (" of size " + list.size()) : "null") + ". " + "Be sure to allocate enough items in the List to accomodate any updates which may occur against the list."; LOGGER.error(msg); throw new RuntimeException(msg); } }
[ "protected", "final", "void", "listUpdate", "(", "List", "list", ",", "int", "index", ",", "Object", "value", ")", "{", "Object", "converted", "=", "value", ";", "if", "(", "list", ".", "size", "(", ")", ">", "index", ")", "{", "Object", "o", "=", "list", ".", "get", "(", "index", ")", ";", "// can only convert types when there is an item in the currently requested place", "if", "(", "o", "!=", "null", ")", "{", "Class", "itemType", "=", "o", ".", "getClass", "(", ")", ";", "converted", "=", "ParseUtils", ".", "convertType", "(", "value", ",", "itemType", ")", ";", "}", "list", ".", "set", "(", "index", ",", "value", ")", ";", "}", "else", "{", "// @note: not sure that this is the right thing. Question is whether or not to insert nulls here to fill list up to \"index\"", "// @update: List doesn't guarantee that implementations will accept nulls. So, we can't rely on that as a solution.", "// @update: this is an unfortunate but necessary solution...unless the List has enough elements to ", "// accomodate the new item at a particular index, this must be an error case. The reasons are this:", "// 1) can't fill the list with nulls, List implementations are allowed to disallow them", "// 2) can't just do an \"add\" to the list -- in processing [0] and [1] on an empty list, [1] may get processed first. ", "// this will go into list slot [0]. then, [0] gets processed and simply overwrites the previous because it's ", "// already in the list", "// 3) can't go to a mixed approach because there's no metadata about what has been done and no time to build", "// something that is apt to be complicated and exposed to the user", "// so...", "// the ultimate 8.1sp2 functionality is to simply disallow updating a value in a list that doesn't exist. that ", "// being said, it is still possible to simply add to the list. if {actionForm.list[42]} inserts into the 42'nd ", "// item, {actionForm.list} will just do an append on POST since there is no index specified. this fix does ", "// not break backwards compatability because it will work on full lists and is completely broken now on empty ", "// lists, so changing this just gives a better exception message that \"ArrayIndexOutOfBounds\". :)", "// ", "// September 2, 2003", "// [email protected]", "// ", "String", "msg", "=", "\"An error occurred setting a value at index \\\"\"", "+", "index", "+", "\"\\\" because the list is \"", "+", "(", "list", "!=", "null", "?", "(", "\" of size \"", "+", "list", ".", "size", "(", ")", ")", ":", "\"null\"", ")", "+", "\". \"", "+", "\"Be sure to allocate enough items in the List to accomodate any updates which may occur against the list.\"", ";", "LOGGER", ".", "error", "(", "msg", ")", ";", "throw", "new", "RuntimeException", "(", "msg", ")", ";", "}", "}" ]
Update a {@link List} with the Object <code>value</code> at <code>index</code>. @param list the List @param index the index @param value the new value
[ "Update", "a", "{" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/script/el/tokens/ExpressionToken.java#L134-L176
aws/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/DeleteReservationResult.java
DeleteReservationResult.withTags
public DeleteReservationResult withTags(java.util.Map<String, String> tags) { """ A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public DeleteReservationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "DeleteReservationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together.
[ "A", "collection", "of", "key", "-", "value", "pairs" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/DeleteReservationResult.java#L688-L691
codahale/xsalsa20poly1305
src/main/java/com/codahale/xsalsa20poly1305/SecretBox.java
SecretBox.open
public Optional<byte[]> open(byte[] nonce, byte[] ciphertext) { """ Decrypt a ciphertext using the given key and nonce. @param nonce a 24-byte nonce @param ciphertext the encrypted message @return an {@link Optional} of the original plaintext, or if either the key, nonce, or ciphertext was modified, an empty {@link Optional} @see #nonce(byte[]) @see #nonce() """ final XSalsa20Engine xsalsa20 = new XSalsa20Engine(); final Poly1305 poly1305 = new Poly1305(); // initialize XSalsa20 xsalsa20.init(false, new ParametersWithIV(new KeyParameter(key), nonce)); // generate mac subkey final byte[] sk = new byte[Keys.KEY_LEN]; xsalsa20.processBytes(sk, 0, sk.length, sk, 0); // hash ciphertext poly1305.init(new KeyParameter(sk)); final int len = Math.max(ciphertext.length - poly1305.getMacSize(), 0); poly1305.update(ciphertext, poly1305.getMacSize(), len); final byte[] calculatedMAC = new byte[poly1305.getMacSize()]; poly1305.doFinal(calculatedMAC, 0); // extract mac final byte[] presentedMAC = new byte[poly1305.getMacSize()]; System.arraycopy( ciphertext, 0, presentedMAC, 0, Math.min(ciphertext.length, poly1305.getMacSize())); // compare macs if (!MessageDigest.isEqual(calculatedMAC, presentedMAC)) { return Optional.empty(); } // decrypt ciphertext final byte[] plaintext = new byte[len]; xsalsa20.processBytes(ciphertext, poly1305.getMacSize(), plaintext.length, plaintext, 0); return Optional.of(plaintext); }
java
public Optional<byte[]> open(byte[] nonce, byte[] ciphertext) { final XSalsa20Engine xsalsa20 = new XSalsa20Engine(); final Poly1305 poly1305 = new Poly1305(); // initialize XSalsa20 xsalsa20.init(false, new ParametersWithIV(new KeyParameter(key), nonce)); // generate mac subkey final byte[] sk = new byte[Keys.KEY_LEN]; xsalsa20.processBytes(sk, 0, sk.length, sk, 0); // hash ciphertext poly1305.init(new KeyParameter(sk)); final int len = Math.max(ciphertext.length - poly1305.getMacSize(), 0); poly1305.update(ciphertext, poly1305.getMacSize(), len); final byte[] calculatedMAC = new byte[poly1305.getMacSize()]; poly1305.doFinal(calculatedMAC, 0); // extract mac final byte[] presentedMAC = new byte[poly1305.getMacSize()]; System.arraycopy( ciphertext, 0, presentedMAC, 0, Math.min(ciphertext.length, poly1305.getMacSize())); // compare macs if (!MessageDigest.isEqual(calculatedMAC, presentedMAC)) { return Optional.empty(); } // decrypt ciphertext final byte[] plaintext = new byte[len]; xsalsa20.processBytes(ciphertext, poly1305.getMacSize(), plaintext.length, plaintext, 0); return Optional.of(plaintext); }
[ "public", "Optional", "<", "byte", "[", "]", ">", "open", "(", "byte", "[", "]", "nonce", ",", "byte", "[", "]", "ciphertext", ")", "{", "final", "XSalsa20Engine", "xsalsa20", "=", "new", "XSalsa20Engine", "(", ")", ";", "final", "Poly1305", "poly1305", "=", "new", "Poly1305", "(", ")", ";", "// initialize XSalsa20", "xsalsa20", ".", "init", "(", "false", ",", "new", "ParametersWithIV", "(", "new", "KeyParameter", "(", "key", ")", ",", "nonce", ")", ")", ";", "// generate mac subkey", "final", "byte", "[", "]", "sk", "=", "new", "byte", "[", "Keys", ".", "KEY_LEN", "]", ";", "xsalsa20", ".", "processBytes", "(", "sk", ",", "0", ",", "sk", ".", "length", ",", "sk", ",", "0", ")", ";", "// hash ciphertext", "poly1305", ".", "init", "(", "new", "KeyParameter", "(", "sk", ")", ")", ";", "final", "int", "len", "=", "Math", ".", "max", "(", "ciphertext", ".", "length", "-", "poly1305", ".", "getMacSize", "(", ")", ",", "0", ")", ";", "poly1305", ".", "update", "(", "ciphertext", ",", "poly1305", ".", "getMacSize", "(", ")", ",", "len", ")", ";", "final", "byte", "[", "]", "calculatedMAC", "=", "new", "byte", "[", "poly1305", ".", "getMacSize", "(", ")", "]", ";", "poly1305", ".", "doFinal", "(", "calculatedMAC", ",", "0", ")", ";", "// extract mac", "final", "byte", "[", "]", "presentedMAC", "=", "new", "byte", "[", "poly1305", ".", "getMacSize", "(", ")", "]", ";", "System", ".", "arraycopy", "(", "ciphertext", ",", "0", ",", "presentedMAC", ",", "0", ",", "Math", ".", "min", "(", "ciphertext", ".", "length", ",", "poly1305", ".", "getMacSize", "(", ")", ")", ")", ";", "// compare macs", "if", "(", "!", "MessageDigest", ".", "isEqual", "(", "calculatedMAC", ",", "presentedMAC", ")", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "// decrypt ciphertext", "final", "byte", "[", "]", "plaintext", "=", "new", "byte", "[", "len", "]", ";", "xsalsa20", ".", "processBytes", "(", "ciphertext", ",", "poly1305", ".", "getMacSize", "(", ")", ",", "plaintext", ".", "length", ",", "plaintext", ",", "0", ")", ";", "return", "Optional", ".", "of", "(", "plaintext", ")", ";", "}" ]
Decrypt a ciphertext using the given key and nonce. @param nonce a 24-byte nonce @param ciphertext the encrypted message @return an {@link Optional} of the original plaintext, or if either the key, nonce, or ciphertext was modified, an empty {@link Optional} @see #nonce(byte[]) @see #nonce()
[ "Decrypt", "a", "ciphertext", "using", "the", "given", "key", "and", "nonce", "." ]
train
https://github.com/codahale/xsalsa20poly1305/blob/f3c1ab2f05b17df137ed8fbb66da2b417066729a/src/main/java/com/codahale/xsalsa20poly1305/SecretBox.java#L104-L136
litsec/eidas-opensaml
opensaml3/src/main/java/se/litsec/eidas/opensaml/ext/attributes/AttributeUtils.java
AttributeUtils.createAttribute
public static Attribute createAttribute(String name, String friendlyName) { """ Creates an {@code Attribute} with the given name (and friendly name) and with a name format of {@value Attribute#URI_REFERENCE}. @param name the attribute name @param friendlyName the attribute friendly name (may be {@code null}) @return an {@code Attribute} object @see #createAttribute(String, String, String) """ return createAttribute(name, friendlyName, Attribute.URI_REFERENCE); }
java
public static Attribute createAttribute(String name, String friendlyName) { return createAttribute(name, friendlyName, Attribute.URI_REFERENCE); }
[ "public", "static", "Attribute", "createAttribute", "(", "String", "name", ",", "String", "friendlyName", ")", "{", "return", "createAttribute", "(", "name", ",", "friendlyName", ",", "Attribute", ".", "URI_REFERENCE", ")", ";", "}" ]
Creates an {@code Attribute} with the given name (and friendly name) and with a name format of {@value Attribute#URI_REFERENCE}. @param name the attribute name @param friendlyName the attribute friendly name (may be {@code null}) @return an {@code Attribute} object @see #createAttribute(String, String, String)
[ "Creates", "an", "{", "@code", "Attribute", "}", "with", "the", "given", "name", "(", "and", "friendly", "name", ")", "and", "with", "a", "name", "format", "of", "{", "@value", "Attribute#URI_REFERENCE", "}", "." ]
train
https://github.com/litsec/eidas-opensaml/blob/522ba6dba433a9524cb8a02464cc3b087b47a2b7/opensaml3/src/main/java/se/litsec/eidas/opensaml/ext/attributes/AttributeUtils.java#L71-L73
opentok/Opentok-Java-SDK
src/main/java/com/opentok/OpenTok.java
OpenTok.generateToken
public String generateToken(String sessionId) throws OpenTokException { """ Creates a token for connecting to an OpenTok session, using the default settings. The default settings are the following: <ul> <li>The token is assigned the role of publisher.</li> <li>The token expires 24 hours after it is created.</li> <li>The token includes no connection data.</li> </ul> <p> The following example shows how to generate a token that has the default settings: <p> <pre> import com.opentok.OpenTok; class Test { public static void main(String argv[]) throws OpenTokException { int API_KEY = 0; // Replace with your OpenTok API key (see https://tokbox.com/account). String API_SECRET = ""; // Replace with your OpenTok API secret. OpenTok sdk = new OpenTok(API_KEY, API_SECRET); //Generate a basic session. Or you could use an existing session ID. String sessionId = System.out.println(sdk.createSession().getSessionId()); String token = sdk.generateToken(sessionId); System.out.println(token); } } </pre> @param sessionId The session ID corresponding to the session to which the user will connect. @return The token string. @see #generateToken(String, TokenOptions) """ return generateToken(sessionId, new TokenOptions.Builder().build()); }
java
public String generateToken(String sessionId) throws OpenTokException { return generateToken(sessionId, new TokenOptions.Builder().build()); }
[ "public", "String", "generateToken", "(", "String", "sessionId", ")", "throws", "OpenTokException", "{", "return", "generateToken", "(", "sessionId", ",", "new", "TokenOptions", ".", "Builder", "(", ")", ".", "build", "(", ")", ")", ";", "}" ]
Creates a token for connecting to an OpenTok session, using the default settings. The default settings are the following: <ul> <li>The token is assigned the role of publisher.</li> <li>The token expires 24 hours after it is created.</li> <li>The token includes no connection data.</li> </ul> <p> The following example shows how to generate a token that has the default settings: <p> <pre> import com.opentok.OpenTok; class Test { public static void main(String argv[]) throws OpenTokException { int API_KEY = 0; // Replace with your OpenTok API key (see https://tokbox.com/account). String API_SECRET = ""; // Replace with your OpenTok API secret. OpenTok sdk = new OpenTok(API_KEY, API_SECRET); //Generate a basic session. Or you could use an existing session ID. String sessionId = System.out.println(sdk.createSession().getSessionId()); String token = sdk.generateToken(sessionId); System.out.println(token); } } </pre> @param sessionId The session ID corresponding to the session to which the user will connect. @return The token string. @see #generateToken(String, TokenOptions)
[ "Creates", "a", "token", "for", "connecting", "to", "an", "OpenTok", "session", "using", "the", "default", "settings", ".", "The", "default", "settings", "are", "the", "following", ":" ]
train
https://github.com/opentok/Opentok-Java-SDK/blob/d71b7999facc3131c415aebea874ea55776d477f/src/main/java/com/opentok/OpenTok.java#L182-L184
actorapp/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/ActorSDK.java
ActorSDK.startGroupInfoActivity
public void startGroupInfoActivity(Context context, int gid) { """ Method is used internally for starting default activity or activity added in delegate @param context current context @param gid group id """ Bundle b = new Bundle(); b.putInt(Intents.EXTRA_GROUP_ID, gid); startActivity(context, b, GroupInfoActivity.class); }
java
public void startGroupInfoActivity(Context context, int gid) { Bundle b = new Bundle(); b.putInt(Intents.EXTRA_GROUP_ID, gid); startActivity(context, b, GroupInfoActivity.class); }
[ "public", "void", "startGroupInfoActivity", "(", "Context", "context", ",", "int", "gid", ")", "{", "Bundle", "b", "=", "new", "Bundle", "(", ")", ";", "b", ".", "putInt", "(", "Intents", ".", "EXTRA_GROUP_ID", ",", "gid", ")", ";", "startActivity", "(", "context", ",", "b", ",", "GroupInfoActivity", ".", "class", ")", ";", "}" ]
Method is used internally for starting default activity or activity added in delegate @param context current context @param gid group id
[ "Method", "is", "used", "internally", "for", "starting", "default", "activity", "or", "activity", "added", "in", "delegate" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/ActorSDK.java#L967-L971
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java
DataNode.startDataNode
void startDataNode(Configuration conf, AbstractList<File> dataDirs ) throws IOException { """ This method starts the data node with the specified conf. @param conf - the configuration if conf's CONFIG_PROPERTY_SIMULATED property is set then a simulated storage based data node is created. @param dataDirs - only for a non-simulated storage data node @throws IOException """ initGlobalSetting(conf, dataDirs); /* Initialize namespace manager */ List<InetSocketAddress> nameNodeAddrs = DFSUtil.getNNServiceRpcAddresses(conf); //TODO this will be no longer valid, since we will have multiple namenodes // We might want to keep it and assign the first NN to it. DataNode.nameNodeAddr = nameNodeAddrs.get(0); namespaceManager = new NamespaceManager(conf, nameNodeAddrs); initDataSetAndScanner(conf, dataDirs, nameNodeAddrs.size()); }
java
void startDataNode(Configuration conf, AbstractList<File> dataDirs ) throws IOException { initGlobalSetting(conf, dataDirs); /* Initialize namespace manager */ List<InetSocketAddress> nameNodeAddrs = DFSUtil.getNNServiceRpcAddresses(conf); //TODO this will be no longer valid, since we will have multiple namenodes // We might want to keep it and assign the first NN to it. DataNode.nameNodeAddr = nameNodeAddrs.get(0); namespaceManager = new NamespaceManager(conf, nameNodeAddrs); initDataSetAndScanner(conf, dataDirs, nameNodeAddrs.size()); }
[ "void", "startDataNode", "(", "Configuration", "conf", ",", "AbstractList", "<", "File", ">", "dataDirs", ")", "throws", "IOException", "{", "initGlobalSetting", "(", "conf", ",", "dataDirs", ")", ";", "/* Initialize namespace manager */", "List", "<", "InetSocketAddress", ">", "nameNodeAddrs", "=", "DFSUtil", ".", "getNNServiceRpcAddresses", "(", "conf", ")", ";", "//TODO this will be no longer valid, since we will have multiple namenodes", "// We might want to keep it and assign the first NN to it.", "DataNode", ".", "nameNodeAddr", "=", "nameNodeAddrs", ".", "get", "(", "0", ")", ";", "namespaceManager", "=", "new", "NamespaceManager", "(", "conf", ",", "nameNodeAddrs", ")", ";", "initDataSetAndScanner", "(", "conf", ",", "dataDirs", ",", "nameNodeAddrs", ".", "size", "(", ")", ")", ";", "}" ]
This method starts the data node with the specified conf. @param conf - the configuration if conf's CONFIG_PROPERTY_SIMULATED property is set then a simulated storage based data node is created. @param dataDirs - only for a non-simulated storage data node @throws IOException
[ "This", "method", "starts", "the", "data", "node", "with", "the", "specified", "conf", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataNode.java#L426-L440
soabase/exhibitor
exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/DefaultProperties.java
DefaultProperties.getFromInstanceConfig
public static Properties getFromInstanceConfig(InstanceConfig defaultInstanceConfig) { """ Return the default properties given an instance config @param defaultInstanceConfig the default properties as an object @return default properties """ PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(new ConfigCollectionImpl(defaultInstanceConfig, null)); return config.getProperties(); }
java
public static Properties getFromInstanceConfig(InstanceConfig defaultInstanceConfig) { PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(new ConfigCollectionImpl(defaultInstanceConfig, null)); return config.getProperties(); }
[ "public", "static", "Properties", "getFromInstanceConfig", "(", "InstanceConfig", "defaultInstanceConfig", ")", "{", "PropertyBasedInstanceConfig", "config", "=", "new", "PropertyBasedInstanceConfig", "(", "new", "ConfigCollectionImpl", "(", "defaultInstanceConfig", ",", "null", ")", ")", ";", "return", "config", ".", "getProperties", "(", ")", ";", "}" ]
Return the default properties given an instance config @param defaultInstanceConfig the default properties as an object @return default properties
[ "Return", "the", "default", "properties", "given", "an", "instance", "config" ]
train
https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/DefaultProperties.java#L58-L62
cdk/cdk
base/core/src/main/java/org/openscience/cdk/graph/RegularPathGraph.java
RegularPathGraph.combine
private List<PathEdge> combine(final List<PathEdge> edges, final int x) { """ Pairwise combination of all disjoint <i>edges</i> incident to a vertex <i>x</i>. @param edges edges which are currently incident to <i>x</i> @param x a vertex in the graph @return reduced edges """ final int n = edges.size(); final List<PathEdge> reduced = new ArrayList<PathEdge>(n); for (int i = 0; i < n; i++) { PathEdge e = edges.get(i); for (int j = i + 1; j < n; j++) { PathEdge f = edges.get(j); if (e.disjoint(f)) reduced.add(new ReducedEdge(e, f, x)); } } return reduced; }
java
private List<PathEdge> combine(final List<PathEdge> edges, final int x) { final int n = edges.size(); final List<PathEdge> reduced = new ArrayList<PathEdge>(n); for (int i = 0; i < n; i++) { PathEdge e = edges.get(i); for (int j = i + 1; j < n; j++) { PathEdge f = edges.get(j); if (e.disjoint(f)) reduced.add(new ReducedEdge(e, f, x)); } } return reduced; }
[ "private", "List", "<", "PathEdge", ">", "combine", "(", "final", "List", "<", "PathEdge", ">", "edges", ",", "final", "int", "x", ")", "{", "final", "int", "n", "=", "edges", ".", "size", "(", ")", ";", "final", "List", "<", "PathEdge", ">", "reduced", "=", "new", "ArrayList", "<", "PathEdge", ">", "(", "n", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "PathEdge", "e", "=", "edges", ".", "get", "(", "i", ")", ";", "for", "(", "int", "j", "=", "i", "+", "1", ";", "j", "<", "n", ";", "j", "++", ")", "{", "PathEdge", "f", "=", "edges", ".", "get", "(", "j", ")", ";", "if", "(", "e", ".", "disjoint", "(", "f", ")", ")", "reduced", ".", "add", "(", "new", "ReducedEdge", "(", "e", ",", "f", ",", "x", ")", ")", ";", "}", "}", "return", "reduced", ";", "}" ]
Pairwise combination of all disjoint <i>edges</i> incident to a vertex <i>x</i>. @param edges edges which are currently incident to <i>x</i> @param x a vertex in the graph @return reduced edges
[ "Pairwise", "combination", "of", "all", "disjoint", "<i", ">", "edges<", "/", "i", ">", "incident", "to", "a", "vertex", "<i", ">", "x<", "/", "i", ">", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/RegularPathGraph.java#L146-L160
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/base64/Base64.java
Base64.safeDecode
@Nullable @ReturnsMutableCopy public static byte [] safeDecode (@Nullable final String sEncoded, final int nOptions) { """ Decode the string with the default encoding (US-ASCII is the preferred one). @param sEncoded The encoded string. @param nOptions Decoding options. @return <code>null</code> if decoding failed. """ if (sEncoded != null) try { return decode (sEncoded, nOptions); } catch (final Exception ex) { // fall through } return null; }
java
@Nullable @ReturnsMutableCopy public static byte [] safeDecode (@Nullable final String sEncoded, final int nOptions) { if (sEncoded != null) try { return decode (sEncoded, nOptions); } catch (final Exception ex) { // fall through } return null; }
[ "@", "Nullable", "@", "ReturnsMutableCopy", "public", "static", "byte", "[", "]", "safeDecode", "(", "@", "Nullable", "final", "String", "sEncoded", ",", "final", "int", "nOptions", ")", "{", "if", "(", "sEncoded", "!=", "null", ")", "try", "{", "return", "decode", "(", "sEncoded", ",", "nOptions", ")", ";", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "// fall through", "}", "return", "null", ";", "}" ]
Decode the string with the default encoding (US-ASCII is the preferred one). @param sEncoded The encoded string. @param nOptions Decoding options. @return <code>null</code> if decoding failed.
[ "Decode", "the", "string", "with", "the", "default", "encoding", "(", "US", "-", "ASCII", "is", "the", "preferred", "one", ")", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2555-L2569
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceList.java
StructureInterfaceList.addNcsEquivalent
public void addNcsEquivalent(StructureInterface interfaceNew, StructureInterface interfaceRef) { """ Add an interface to the list, possibly defining it as NCS-equivalent to an interface already in the list. Used to build up the NCS clustering. @param interfaceNew an interface to be added to the list. @param interfaceRef interfaceNew will be added to the cluster which contains interfaceRef. If interfaceRef is null, new cluster will be created for interfaceNew. @since 5.0.0 """ this.add(interfaceNew); if (clustersNcs == null) { clustersNcs = new ArrayList<>(); } if (interfaceRef == null) { StructureInterfaceCluster newCluster = new StructureInterfaceCluster(); newCluster.addMember(interfaceNew); clustersNcs.add(newCluster); return; } Optional<StructureInterfaceCluster> clusterRef = clustersNcs.stream(). filter(r->r.getMembers().stream(). anyMatch(c -> c.equals(interfaceRef))). findFirst(); if (clusterRef.isPresent()) { clusterRef.get().addMember(interfaceNew); return; } logger.warn("The specified reference interface, if not null, should have been added to this set previously. " + "Creating new cluster and adding both interfaces. This is likely a bug."); this.add(interfaceRef); StructureInterfaceCluster newCluster = new StructureInterfaceCluster(); newCluster.addMember(interfaceRef); newCluster.addMember(interfaceNew); clustersNcs.add(newCluster); }
java
public void addNcsEquivalent(StructureInterface interfaceNew, StructureInterface interfaceRef) { this.add(interfaceNew); if (clustersNcs == null) { clustersNcs = new ArrayList<>(); } if (interfaceRef == null) { StructureInterfaceCluster newCluster = new StructureInterfaceCluster(); newCluster.addMember(interfaceNew); clustersNcs.add(newCluster); return; } Optional<StructureInterfaceCluster> clusterRef = clustersNcs.stream(). filter(r->r.getMembers().stream(). anyMatch(c -> c.equals(interfaceRef))). findFirst(); if (clusterRef.isPresent()) { clusterRef.get().addMember(interfaceNew); return; } logger.warn("The specified reference interface, if not null, should have been added to this set previously. " + "Creating new cluster and adding both interfaces. This is likely a bug."); this.add(interfaceRef); StructureInterfaceCluster newCluster = new StructureInterfaceCluster(); newCluster.addMember(interfaceRef); newCluster.addMember(interfaceNew); clustersNcs.add(newCluster); }
[ "public", "void", "addNcsEquivalent", "(", "StructureInterface", "interfaceNew", ",", "StructureInterface", "interfaceRef", ")", "{", "this", ".", "add", "(", "interfaceNew", ")", ";", "if", "(", "clustersNcs", "==", "null", ")", "{", "clustersNcs", "=", "new", "ArrayList", "<>", "(", ")", ";", "}", "if", "(", "interfaceRef", "==", "null", ")", "{", "StructureInterfaceCluster", "newCluster", "=", "new", "StructureInterfaceCluster", "(", ")", ";", "newCluster", ".", "addMember", "(", "interfaceNew", ")", ";", "clustersNcs", ".", "add", "(", "newCluster", ")", ";", "return", ";", "}", "Optional", "<", "StructureInterfaceCluster", ">", "clusterRef", "=", "clustersNcs", ".", "stream", "(", ")", ".", "filter", "(", "r", "->", "r", ".", "getMembers", "(", ")", ".", "stream", "(", ")", ".", "anyMatch", "(", "c", "->", "c", ".", "equals", "(", "interfaceRef", ")", ")", ")", ".", "findFirst", "(", ")", ";", "if", "(", "clusterRef", ".", "isPresent", "(", ")", ")", "{", "clusterRef", ".", "get", "(", ")", ".", "addMember", "(", "interfaceNew", ")", ";", "return", ";", "}", "logger", ".", "warn", "(", "\"The specified reference interface, if not null, should have been added to this set previously. \"", "+", "\"Creating new cluster and adding both interfaces. This is likely a bug.\"", ")", ";", "this", ".", "add", "(", "interfaceRef", ")", ";", "StructureInterfaceCluster", "newCluster", "=", "new", "StructureInterfaceCluster", "(", ")", ";", "newCluster", ".", "addMember", "(", "interfaceRef", ")", ";", "newCluster", ".", "addMember", "(", "interfaceNew", ")", ";", "clustersNcs", ".", "add", "(", "newCluster", ")", ";", "}" ]
Add an interface to the list, possibly defining it as NCS-equivalent to an interface already in the list. Used to build up the NCS clustering. @param interfaceNew an interface to be added to the list. @param interfaceRef interfaceNew will be added to the cluster which contains interfaceRef. If interfaceRef is null, new cluster will be created for interfaceNew. @since 5.0.0
[ "Add", "an", "interface", "to", "the", "list", "possibly", "defining", "it", "as", "NCS", "-", "equivalent", "to", "an", "interface", "already", "in", "the", "list", ".", "Used", "to", "build", "up", "the", "NCS", "clustering", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceList.java#L279-L311
google/closure-compiler
src/com/google/javascript/jscomp/Promises.java
Promises.getResolvedType
static final JSType getResolvedType(JSTypeRegistry registry, JSType type) { """ Returns the type of `await [expr]`. <p>This is equivalent to the type of `result` in `Promise.resolve([expr]).then(result => ` <p>For example: <p>{@code !Promise<number>} becomes {@code number} <p>{@code !IThenable<number>} becomes {@code number} <p>{@code string} becomes {@code string} <p>{@code (!Promise<number>|string)} becomes {@code (number|string)} <p>{@code ?Promise<number>} becomes {@code (null|number)} """ if (type.isUnknownType()) { return type; } if (type.isUnionType()) { UnionTypeBuilder unionTypeBuilder = UnionTypeBuilder.create(registry); for (JSType alternate : type.toMaybeUnionType().getAlternates()) { unionTypeBuilder.addAlternate(getResolvedType(registry, alternate)); } return unionTypeBuilder.build(); } // If we can find the "IThenable" template key (which is true for Promise and IThenable), return // the resolved value. e.g. for "!Promise<string>" return "string". TemplateTypeMap templates = type.getTemplateTypeMap(); if (templates.hasTemplateKey(registry.getIThenableTemplate())) { // Call getResolvedPromiseType again in case someone does something unusual like // !Promise<!Promise<number>> // TODO(lharker): we don't need to handle this case and should report an error for this in a // type annotation (not here, maybe in TypeCheck). A Promise cannot resolve to another Promise return getResolvedType( registry, templates.getResolvedTemplateType(registry.getIThenableTemplate())); } // Awaiting anything with a ".then" property (other than IThenable, handled above) should return // unknown, rather than the type itself. if (type.isSubtypeOf(registry.getNativeType(JSTypeNative.THENABLE_TYPE))) { return registry.getNativeType(JSTypeNative.UNKNOWN_TYPE); } return type; }
java
static final JSType getResolvedType(JSTypeRegistry registry, JSType type) { if (type.isUnknownType()) { return type; } if (type.isUnionType()) { UnionTypeBuilder unionTypeBuilder = UnionTypeBuilder.create(registry); for (JSType alternate : type.toMaybeUnionType().getAlternates()) { unionTypeBuilder.addAlternate(getResolvedType(registry, alternate)); } return unionTypeBuilder.build(); } // If we can find the "IThenable" template key (which is true for Promise and IThenable), return // the resolved value. e.g. for "!Promise<string>" return "string". TemplateTypeMap templates = type.getTemplateTypeMap(); if (templates.hasTemplateKey(registry.getIThenableTemplate())) { // Call getResolvedPromiseType again in case someone does something unusual like // !Promise<!Promise<number>> // TODO(lharker): we don't need to handle this case and should report an error for this in a // type annotation (not here, maybe in TypeCheck). A Promise cannot resolve to another Promise return getResolvedType( registry, templates.getResolvedTemplateType(registry.getIThenableTemplate())); } // Awaiting anything with a ".then" property (other than IThenable, handled above) should return // unknown, rather than the type itself. if (type.isSubtypeOf(registry.getNativeType(JSTypeNative.THENABLE_TYPE))) { return registry.getNativeType(JSTypeNative.UNKNOWN_TYPE); } return type; }
[ "static", "final", "JSType", "getResolvedType", "(", "JSTypeRegistry", "registry", ",", "JSType", "type", ")", "{", "if", "(", "type", ".", "isUnknownType", "(", ")", ")", "{", "return", "type", ";", "}", "if", "(", "type", ".", "isUnionType", "(", ")", ")", "{", "UnionTypeBuilder", "unionTypeBuilder", "=", "UnionTypeBuilder", ".", "create", "(", "registry", ")", ";", "for", "(", "JSType", "alternate", ":", "type", ".", "toMaybeUnionType", "(", ")", ".", "getAlternates", "(", ")", ")", "{", "unionTypeBuilder", ".", "addAlternate", "(", "getResolvedType", "(", "registry", ",", "alternate", ")", ")", ";", "}", "return", "unionTypeBuilder", ".", "build", "(", ")", ";", "}", "// If we can find the \"IThenable\" template key (which is true for Promise and IThenable), return", "// the resolved value. e.g. for \"!Promise<string>\" return \"string\".", "TemplateTypeMap", "templates", "=", "type", ".", "getTemplateTypeMap", "(", ")", ";", "if", "(", "templates", ".", "hasTemplateKey", "(", "registry", ".", "getIThenableTemplate", "(", ")", ")", ")", "{", "// Call getResolvedPromiseType again in case someone does something unusual like", "// !Promise<!Promise<number>>", "// TODO(lharker): we don't need to handle this case and should report an error for this in a", "// type annotation (not here, maybe in TypeCheck). A Promise cannot resolve to another Promise", "return", "getResolvedType", "(", "registry", ",", "templates", ".", "getResolvedTemplateType", "(", "registry", ".", "getIThenableTemplate", "(", ")", ")", ")", ";", "}", "// Awaiting anything with a \".then\" property (other than IThenable, handled above) should return", "// unknown, rather than the type itself.", "if", "(", "type", ".", "isSubtypeOf", "(", "registry", ".", "getNativeType", "(", "JSTypeNative", ".", "THENABLE_TYPE", ")", ")", ")", "{", "return", "registry", ".", "getNativeType", "(", "JSTypeNative", ".", "UNKNOWN_TYPE", ")", ";", "}", "return", "type", ";", "}" ]
Returns the type of `await [expr]`. <p>This is equivalent to the type of `result` in `Promise.resolve([expr]).then(result => ` <p>For example: <p>{@code !Promise<number>} becomes {@code number} <p>{@code !IThenable<number>} becomes {@code number} <p>{@code string} becomes {@code string} <p>{@code (!Promise<number>|string)} becomes {@code (number|string)} <p>{@code ?Promise<number>} becomes {@code (null|number)}
[ "Returns", "the", "type", "of", "await", "[", "expr", "]", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Promises.java#L70-L102
beangle/beangle3
commons/model/src/main/java/org/beangle/commons/transfer/importer/MultiEntityImporter.java
MultiEntityImporter.addEntity
public void addEntity(String alias, Class<?> entityClass) { """ <p> addEntity. </p> @param alias a {@link java.lang.String} object. @param entityClass a {@link java.lang.Class} object. """ EntityType entityType = Model.getType(entityClass); if (null == entityType) { throw new RuntimeException("cannot find entity type for " + entityClass); } entityTypes.put(alias, entityType); }
java
public void addEntity(String alias, Class<?> entityClass) { EntityType entityType = Model.getType(entityClass); if (null == entityType) { throw new RuntimeException("cannot find entity type for " + entityClass); } entityTypes.put(alias, entityType); }
[ "public", "void", "addEntity", "(", "String", "alias", ",", "Class", "<", "?", ">", "entityClass", ")", "{", "EntityType", "entityType", "=", "Model", ".", "getType", "(", "entityClass", ")", ";", "if", "(", "null", "==", "entityType", ")", "{", "throw", "new", "RuntimeException", "(", "\"cannot find entity type for \"", "+", "entityClass", ")", ";", "}", "entityTypes", ".", "put", "(", "alias", ",", "entityType", ")", ";", "}" ]
<p> addEntity. </p> @param alias a {@link java.lang.String} object. @param entityClass a {@link java.lang.Class} object.
[ "<p", ">", "addEntity", ".", "<", "/", "p", ">" ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/model/src/main/java/org/beangle/commons/transfer/importer/MultiEntityImporter.java#L169-L173
datacleaner/DataCleaner
desktop/api/src/main/java/org/datacleaner/widgets/properties/PropertyWidgetCollection.java
PropertyWidgetCollection.registerWidget
public void registerWidget(final ConfiguredPropertyDescriptor propertyDescriptor, final PropertyWidget<?> widget) { """ Registers a widget in this factory in rare cases when the factory is not used to actually instantiate the widget, but it is still needed to register the widget for compliancy with eg. the onConfigurationChanged() behaviour. @param propertyDescriptor @param widget """ if (widget == null) { _widgets.remove(propertyDescriptor); } else { _widgets.put(propertyDescriptor, widget); @SuppressWarnings("unchecked") final PropertyWidget<Object> objectWidget = (PropertyWidget<Object>) widget; final Object value = _componentBuilder.getConfiguredProperty(objectWidget.getPropertyDescriptor()); objectWidget.initialize(value); } }
java
public void registerWidget(final ConfiguredPropertyDescriptor propertyDescriptor, final PropertyWidget<?> widget) { if (widget == null) { _widgets.remove(propertyDescriptor); } else { _widgets.put(propertyDescriptor, widget); @SuppressWarnings("unchecked") final PropertyWidget<Object> objectWidget = (PropertyWidget<Object>) widget; final Object value = _componentBuilder.getConfiguredProperty(objectWidget.getPropertyDescriptor()); objectWidget.initialize(value); } }
[ "public", "void", "registerWidget", "(", "final", "ConfiguredPropertyDescriptor", "propertyDescriptor", ",", "final", "PropertyWidget", "<", "?", ">", "widget", ")", "{", "if", "(", "widget", "==", "null", ")", "{", "_widgets", ".", "remove", "(", "propertyDescriptor", ")", ";", "}", "else", "{", "_widgets", ".", "put", "(", "propertyDescriptor", ",", "widget", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "final", "PropertyWidget", "<", "Object", ">", "objectWidget", "=", "(", "PropertyWidget", "<", "Object", ">", ")", "widget", ";", "final", "Object", "value", "=", "_componentBuilder", ".", "getConfiguredProperty", "(", "objectWidget", ".", "getPropertyDescriptor", "(", ")", ")", ";", "objectWidget", ".", "initialize", "(", "value", ")", ";", "}", "}" ]
Registers a widget in this factory in rare cases when the factory is not used to actually instantiate the widget, but it is still needed to register the widget for compliancy with eg. the onConfigurationChanged() behaviour. @param propertyDescriptor @param widget
[ "Registers", "a", "widget", "in", "this", "factory", "in", "rare", "cases", "when", "the", "factory", "is", "not", "used", "to", "actually", "instantiate", "the", "widget", "but", "it", "is", "still", "needed", "to", "register", "the", "widget", "for", "compliancy", "with", "eg", ".", "the", "onConfigurationChanged", "()", "behaviour", "." ]
train
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/api/src/main/java/org/datacleaner/widgets/properties/PropertyWidgetCollection.java#L84-L93
sdl/odata
odata_common/src/main/java/com/sdl/odata/controller/AbstractODataController.java
AbstractODataController.fillServletResponse
private void fillServletResponse(ODataResponse oDataResponse, HttpServletResponse servletResponse) throws IOException, ODataException { """ Transfers data from an {@code ODataResponse} into an {@code HttpServletResponse}. @param oDataResponse The {@code ODataResponse}. @param servletResponse The {@code HttpServletResponse} @throws java.io.IOException If an I/O error occurs. """ servletResponse.setStatus(oDataResponse.getStatus().getCode()); for (Map.Entry<String, String> entry : oDataResponse.getHeaders().entrySet()) { servletResponse.setHeader(entry.getKey(), entry.getValue()); } byte[] body = oDataResponse.getBody(); if (body != null && body.length != 0) { OutputStream out = servletResponse.getOutputStream(); out.write(oDataResponse.getBody()); out.flush(); } else if (oDataResponse.getStreamingContent() != null) { oDataResponse.getStreamingContent().write(servletResponse); } }
java
private void fillServletResponse(ODataResponse oDataResponse, HttpServletResponse servletResponse) throws IOException, ODataException { servletResponse.setStatus(oDataResponse.getStatus().getCode()); for (Map.Entry<String, String> entry : oDataResponse.getHeaders().entrySet()) { servletResponse.setHeader(entry.getKey(), entry.getValue()); } byte[] body = oDataResponse.getBody(); if (body != null && body.length != 0) { OutputStream out = servletResponse.getOutputStream(); out.write(oDataResponse.getBody()); out.flush(); } else if (oDataResponse.getStreamingContent() != null) { oDataResponse.getStreamingContent().write(servletResponse); } }
[ "private", "void", "fillServletResponse", "(", "ODataResponse", "oDataResponse", ",", "HttpServletResponse", "servletResponse", ")", "throws", "IOException", ",", "ODataException", "{", "servletResponse", ".", "setStatus", "(", "oDataResponse", ".", "getStatus", "(", ")", ".", "getCode", "(", ")", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "oDataResponse", ".", "getHeaders", "(", ")", ".", "entrySet", "(", ")", ")", "{", "servletResponse", ".", "setHeader", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "byte", "[", "]", "body", "=", "oDataResponse", ".", "getBody", "(", ")", ";", "if", "(", "body", "!=", "null", "&&", "body", ".", "length", "!=", "0", ")", "{", "OutputStream", "out", "=", "servletResponse", ".", "getOutputStream", "(", ")", ";", "out", ".", "write", "(", "oDataResponse", ".", "getBody", "(", ")", ")", ";", "out", ".", "flush", "(", ")", ";", "}", "else", "if", "(", "oDataResponse", ".", "getStreamingContent", "(", ")", "!=", "null", ")", "{", "oDataResponse", ".", "getStreamingContent", "(", ")", ".", "write", "(", "servletResponse", ")", ";", "}", "}" ]
Transfers data from an {@code ODataResponse} into an {@code HttpServletResponse}. @param oDataResponse The {@code ODataResponse}. @param servletResponse The {@code HttpServletResponse} @throws java.io.IOException If an I/O error occurs.
[ "Transfers", "data", "from", "an", "{", "@code", "ODataResponse", "}", "into", "an", "{", "@code", "HttpServletResponse", "}", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_common/src/main/java/com/sdl/odata/controller/AbstractODataController.java#L160-L176
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/AbstractAggregatorImpl.java
AbstractAggregatorImpl.getAggregatorName
protected String getAggregatorName(Map<String, String> configMap) { """ Returns the name for this aggregator <p> This method is called during aggregator intialization. Subclasses may override this method to initialize the aggregator using a different name. Use the public {@link IAggregator#getName()} method to get the name of an initialized aggregator. @param configMap A Map having key-value pairs denoting configuration settings for the aggregator servlet @return The aggregator name """ // trim leading and trailing '/' String alias = (String)configMap.get("alias"); //$NON-NLS-1$ while (alias.charAt(0) == '/') alias = alias.substring(1); while (alias.charAt(alias.length()-1) == '/') alias = alias.substring(0, alias.length()-1); return alias; }
java
protected String getAggregatorName(Map<String, String> configMap) { // trim leading and trailing '/' String alias = (String)configMap.get("alias"); //$NON-NLS-1$ while (alias.charAt(0) == '/') alias = alias.substring(1); while (alias.charAt(alias.length()-1) == '/') alias = alias.substring(0, alias.length()-1); return alias; }
[ "protected", "String", "getAggregatorName", "(", "Map", "<", "String", ",", "String", ">", "configMap", ")", "{", "// trim leading and trailing '/'\r", "String", "alias", "=", "(", "String", ")", "configMap", ".", "get", "(", "\"alias\"", ")", ";", "//$NON-NLS-1$\r", "while", "(", "alias", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "alias", "=", "alias", ".", "substring", "(", "1", ")", ";", "while", "(", "alias", ".", "charAt", "(", "alias", ".", "length", "(", ")", "-", "1", ")", "==", "'", "'", ")", "alias", "=", "alias", ".", "substring", "(", "0", ",", "alias", ".", "length", "(", ")", "-", "1", ")", ";", "return", "alias", ";", "}" ]
Returns the name for this aggregator <p> This method is called during aggregator intialization. Subclasses may override this method to initialize the aggregator using a different name. Use the public {@link IAggregator#getName()} method to get the name of an initialized aggregator. @param configMap A Map having key-value pairs denoting configuration settings for the aggregator servlet @return The aggregator name
[ "Returns", "the", "name", "for", "this", "aggregator", "<p", ">", "This", "method", "is", "called", "during", "aggregator", "intialization", ".", "Subclasses", "may", "override", "this", "method", "to", "initialize", "the", "aggregator", "using", "a", "different", "name", ".", "Use", "the", "public", "{", "@link", "IAggregator#getName", "()", "}", "method", "to", "get", "the", "name", "of", "an", "initialized", "aggregator", "." ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/AbstractAggregatorImpl.java#L1466-L1474
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/RandomMatrices_DDRM.java
RandomMatrices_DDRM.triangularUpper
public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand ) { """ Creates an upper triangular matrix whose values are selected from a uniform distribution. If hessenberg is greater than zero then a hessenberg matrix of the specified degree is created instead. @param dimen Number of rows and columns in the matrix.. @param hessenberg 0 for triangular matrix and &gt; 0 for hessenberg matrix. @param min minimum value an element can be. @param max maximum value an element can be. @param rand random number generator used. @return The randomly generated matrix. """ if( hessenberg < 0 ) throw new RuntimeException("hessenberg must be more than or equal to 0"); double range = max-min; DMatrixRMaj A = new DMatrixRMaj(dimen,dimen); for( int i = 0; i < dimen; i++ ) { int start = i <= hessenberg ? 0 : i-hessenberg; for( int j = start; j < dimen; j++ ) { A.set(i,j, rand.nextDouble()*range+min); } } return A; }
java
public static DMatrixRMaj triangularUpper(int dimen , int hessenberg , double min , double max , Random rand ) { if( hessenberg < 0 ) throw new RuntimeException("hessenberg must be more than or equal to 0"); double range = max-min; DMatrixRMaj A = new DMatrixRMaj(dimen,dimen); for( int i = 0; i < dimen; i++ ) { int start = i <= hessenberg ? 0 : i-hessenberg; for( int j = start; j < dimen; j++ ) { A.set(i,j, rand.nextDouble()*range+min); } } return A; }
[ "public", "static", "DMatrixRMaj", "triangularUpper", "(", "int", "dimen", ",", "int", "hessenberg", ",", "double", "min", ",", "double", "max", ",", "Random", "rand", ")", "{", "if", "(", "hessenberg", "<", "0", ")", "throw", "new", "RuntimeException", "(", "\"hessenberg must be more than or equal to 0\"", ")", ";", "double", "range", "=", "max", "-", "min", ";", "DMatrixRMaj", "A", "=", "new", "DMatrixRMaj", "(", "dimen", ",", "dimen", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dimen", ";", "i", "++", ")", "{", "int", "start", "=", "i", "<=", "hessenberg", "?", "0", ":", "i", "-", "hessenberg", ";", "for", "(", "int", "j", "=", "start", ";", "j", "<", "dimen", ";", "j", "++", ")", "{", "A", ".", "set", "(", "i", ",", "j", ",", "rand", ".", "nextDouble", "(", ")", "*", "range", "+", "min", ")", ";", "}", "}", "return", "A", ";", "}" ]
Creates an upper triangular matrix whose values are selected from a uniform distribution. If hessenberg is greater than zero then a hessenberg matrix of the specified degree is created instead. @param dimen Number of rows and columns in the matrix.. @param hessenberg 0 for triangular matrix and &gt; 0 for hessenberg matrix. @param min minimum value an element can be. @param max maximum value an element can be. @param rand random number generator used. @return The randomly generated matrix.
[ "Creates", "an", "upper", "triangular", "matrix", "whose", "values", "are", "selected", "from", "a", "uniform", "distribution", ".", "If", "hessenberg", "is", "greater", "than", "zero", "then", "a", "hessenberg", "matrix", "of", "the", "specified", "degree", "is", "created", "instead", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/RandomMatrices_DDRM.java#L512-L531
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/chrono/AbstractChronology.java
AbstractChronology.registerChrono
static Chronology registerChrono(Chronology chrono, String id) { """ Register a Chronology by ID and type for lookup by {@link #of(String)}. Chronos must not be registered until they are completely constructed. Specifically, not in the constructor of Chronology. @param chrono the chronology to register; not null @param id the ID to register the chronology; not null @return the already registered Chronology if any, may be null """ Chronology prev = CHRONOS_BY_ID.putIfAbsent(id, chrono); if (prev == null) { String type = chrono.getCalendarType(); if (type != null) { CHRONOS_BY_TYPE.putIfAbsent(type, chrono); } } return prev; }
java
static Chronology registerChrono(Chronology chrono, String id) { Chronology prev = CHRONOS_BY_ID.putIfAbsent(id, chrono); if (prev == null) { String type = chrono.getCalendarType(); if (type != null) { CHRONOS_BY_TYPE.putIfAbsent(type, chrono); } } return prev; }
[ "static", "Chronology", "registerChrono", "(", "Chronology", "chrono", ",", "String", "id", ")", "{", "Chronology", "prev", "=", "CHRONOS_BY_ID", ".", "putIfAbsent", "(", "id", ",", "chrono", ")", ";", "if", "(", "prev", "==", "null", ")", "{", "String", "type", "=", "chrono", ".", "getCalendarType", "(", ")", ";", "if", "(", "type", "!=", "null", ")", "{", "CHRONOS_BY_TYPE", ".", "putIfAbsent", "(", "type", ",", "chrono", ")", ";", "}", "}", "return", "prev", ";", "}" ]
Register a Chronology by ID and type for lookup by {@link #of(String)}. Chronos must not be registered until they are completely constructed. Specifically, not in the constructor of Chronology. @param chrono the chronology to register; not null @param id the ID to register the chronology; not null @return the already registered Chronology if any, may be null
[ "Register", "a", "Chronology", "by", "ID", "and", "type", "for", "lookup", "by", "{", "@link", "#of", "(", "String", ")", "}", ".", "Chronos", "must", "not", "be", "registered", "until", "they", "are", "completely", "constructed", ".", "Specifically", "not", "in", "the", "constructor", "of", "Chronology", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/chrono/AbstractChronology.java#L189-L198
vanilladb/vanillacore
src/main/java/org/vanilladb/core/storage/metadata/statistics/SampledHistogramBuilder.java
SampledHistogramBuilder.newMaxDiffAreaHistogram
public Histogram newMaxDiffAreaHistogram(int numBkts) { """ Constructs a histogram with the "MaxDiff(V, A)" buckets for all fields. All fields must be numeric. @param numBkts the number of buckets to construct for each field @return a "MaxDiff(V, A)" histogram """ Map<String, BucketBuilder> initBbs = new HashMap<String, BucketBuilder>(); for (String fld : schema.fields()) { initBbs.put(fld, new MaxDiffAreaBucketBuilder(frequencies(fld), null)); } return newMaxDiffHistogram(numBkts, initBbs); }
java
public Histogram newMaxDiffAreaHistogram(int numBkts) { Map<String, BucketBuilder> initBbs = new HashMap<String, BucketBuilder>(); for (String fld : schema.fields()) { initBbs.put(fld, new MaxDiffAreaBucketBuilder(frequencies(fld), null)); } return newMaxDiffHistogram(numBkts, initBbs); }
[ "public", "Histogram", "newMaxDiffAreaHistogram", "(", "int", "numBkts", ")", "{", "Map", "<", "String", ",", "BucketBuilder", ">", "initBbs", "=", "new", "HashMap", "<", "String", ",", "BucketBuilder", ">", "(", ")", ";", "for", "(", "String", "fld", ":", "schema", ".", "fields", "(", ")", ")", "{", "initBbs", ".", "put", "(", "fld", ",", "new", "MaxDiffAreaBucketBuilder", "(", "frequencies", "(", "fld", ")", ",", "null", ")", ")", ";", "}", "return", "newMaxDiffHistogram", "(", "numBkts", ",", "initBbs", ")", ";", "}" ]
Constructs a histogram with the "MaxDiff(V, A)" buckets for all fields. All fields must be numeric. @param numBkts the number of buckets to construct for each field @return a "MaxDiff(V, A)" histogram
[ "Constructs", "a", "histogram", "with", "the", "MaxDiff", "(", "V", "A", ")", "buckets", "for", "all", "fields", ".", "All", "fields", "must", "be", "numeric", "." ]
train
https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/metadata/statistics/SampledHistogramBuilder.java#L416-L423
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/AlignedBox3f.java
AlignedBox3f.setY
@Override public void setY(double min, double max) { """ Set the y bounds of the box. @param min the min value for the y axis. @param max the max value for the y axis. """ if (min <= max) { this.miny = min; this.maxy = max; } else { this.miny = max; this.maxy = min; } }
java
@Override public void setY(double min, double max) { if (min <= max) { this.miny = min; this.maxy = max; } else { this.miny = max; this.maxy = min; } }
[ "@", "Override", "public", "void", "setY", "(", "double", "min", ",", "double", "max", ")", "{", "if", "(", "min", "<=", "max", ")", "{", "this", ".", "miny", "=", "min", ";", "this", ".", "maxy", "=", "max", ";", "}", "else", "{", "this", ".", "miny", "=", "max", ";", "this", ".", "maxy", "=", "min", ";", "}", "}" ]
Set the y bounds of the box. @param min the min value for the y axis. @param max the max value for the y axis.
[ "Set", "the", "y", "bounds", "of", "the", "box", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/AlignedBox3f.java#L620-L629
basho/riak-java-client
src/main/java/com/basho/riak/client/core/query/UserMetadata/RiakUserMetadata.java
RiakUserMetadata.put
public void put(String key, String value, Charset charset) { """ Set a user metadata entry. <p> This method and its {@link RiakUserMetadata#get(java.lang.String, java.nio.charset.Charset) } counterpart use the supplied {@code Charset} to convert the {@code String}s. </p> @param key the key for the user metadata entry as a {@code String} encoded using the supplied {@code Charset} @param value the value for the entry as a {@code String} encoded using the supplied {@code Charset} """ BinaryValue wrappedKey = BinaryValue.unsafeCreate(key.getBytes(charset)); BinaryValue wrappedValue = BinaryValue.unsafeCreate(value.getBytes(charset)); meta.put(wrappedKey, wrappedValue); }
java
public void put(String key, String value, Charset charset) { BinaryValue wrappedKey = BinaryValue.unsafeCreate(key.getBytes(charset)); BinaryValue wrappedValue = BinaryValue.unsafeCreate(value.getBytes(charset)); meta.put(wrappedKey, wrappedValue); }
[ "public", "void", "put", "(", "String", "key", ",", "String", "value", ",", "Charset", "charset", ")", "{", "BinaryValue", "wrappedKey", "=", "BinaryValue", ".", "unsafeCreate", "(", "key", ".", "getBytes", "(", "charset", ")", ")", ";", "BinaryValue", "wrappedValue", "=", "BinaryValue", ".", "unsafeCreate", "(", "value", ".", "getBytes", "(", "charset", ")", ")", ";", "meta", ".", "put", "(", "wrappedKey", ",", "wrappedValue", ")", ";", "}" ]
Set a user metadata entry. <p> This method and its {@link RiakUserMetadata#get(java.lang.String, java.nio.charset.Charset) } counterpart use the supplied {@code Charset} to convert the {@code String}s. </p> @param key the key for the user metadata entry as a {@code String} encoded using the supplied {@code Charset} @param value the value for the entry as a {@code String} encoded using the supplied {@code Charset}
[ "Set", "a", "user", "metadata", "entry", ".", "<p", ">", "This", "method", "and", "its", "{", "@link", "RiakUserMetadata#get", "(", "java", ".", "lang", ".", "String", "java", ".", "nio", ".", "charset", ".", "Charset", ")", "}", "counterpart", "use", "the", "supplied", "{", "@code", "Charset", "}", "to", "convert", "the", "{", "@code", "String", "}", "s", ".", "<", "/", "p", ">" ]
train
https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/core/query/UserMetadata/RiakUserMetadata.java#L180-L185
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssUtils.java
LssUtils.hmacSha256
public static String hmacSha256(String input, String secretKey) { """ Encodes the input String using the UTF8 charset and calls hmacSha256; @param input data to calculate mac @param secretKey secret key @return String, sha256 mac """ if (input == null) { throw new NullPointerException("input"); } else if (secretKey == null) { throw new NullPointerException("secretKey"); } return hmacSha256(input.getBytes(CHARSET_UTF8), secretKey.getBytes(CHARSET_UTF8)); }
java
public static String hmacSha256(String input, String secretKey) { if (input == null) { throw new NullPointerException("input"); } else if (secretKey == null) { throw new NullPointerException("secretKey"); } return hmacSha256(input.getBytes(CHARSET_UTF8), secretKey.getBytes(CHARSET_UTF8)); }
[ "public", "static", "String", "hmacSha256", "(", "String", "input", ",", "String", "secretKey", ")", "{", "if", "(", "input", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"input\"", ")", ";", "}", "else", "if", "(", "secretKey", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"secretKey\"", ")", ";", "}", "return", "hmacSha256", "(", "input", ".", "getBytes", "(", "CHARSET_UTF8", ")", ",", "secretKey", ".", "getBytes", "(", "CHARSET_UTF8", ")", ")", ";", "}" ]
Encodes the input String using the UTF8 charset and calls hmacSha256; @param input data to calculate mac @param secretKey secret key @return String, sha256 mac
[ "Encodes", "the", "input", "String", "using", "the", "UTF8", "charset", "and", "calls", "hmacSha256", ";" ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssUtils.java#L27-L34
kaazing/java.client
net.api/src/main/java/org/kaazing/net/URLFactory.java
URLFactory.createURL
public static URL createURL(String protocol, String host, int port, String file) throws MalformedURLException { """ Creates a URL from the specified protocol name, host name, port number, and file name. <p/> No validation of the inputs is performed by this method. @param protocol the name of the protocol to use @param host the name of the host @param port the port number @param file the file on the host @return URL created using specified protocol, host, and file @throws MalformedURLException if an unknown protocol is specified """ URLStreamHandlerFactory factory = _factories.get(protocol); // If there is no URLStreamHandlerFactory registered for the // scheme/protocol, then we just use the regular URL constructor. if (factory == null) { return new URL(protocol, host, port, file); } // If there is a URLStreamHandlerFactory associated for the // scheme/protocol, then we create a URLStreamHandler. And, then use // then use the URLStreamHandler to create a URL. URLStreamHandler handler = factory.createURLStreamHandler(protocol); return new URL(protocol, host, port, file, handler); }
java
public static URL createURL(String protocol, String host, int port, String file) throws MalformedURLException { URLStreamHandlerFactory factory = _factories.get(protocol); // If there is no URLStreamHandlerFactory registered for the // scheme/protocol, then we just use the regular URL constructor. if (factory == null) { return new URL(protocol, host, port, file); } // If there is a URLStreamHandlerFactory associated for the // scheme/protocol, then we create a URLStreamHandler. And, then use // then use the URLStreamHandler to create a URL. URLStreamHandler handler = factory.createURLStreamHandler(protocol); return new URL(protocol, host, port, file, handler); }
[ "public", "static", "URL", "createURL", "(", "String", "protocol", ",", "String", "host", ",", "int", "port", ",", "String", "file", ")", "throws", "MalformedURLException", "{", "URLStreamHandlerFactory", "factory", "=", "_factories", ".", "get", "(", "protocol", ")", ";", "// If there is no URLStreamHandlerFactory registered for the", "// scheme/protocol, then we just use the regular URL constructor.", "if", "(", "factory", "==", "null", ")", "{", "return", "new", "URL", "(", "protocol", ",", "host", ",", "port", ",", "file", ")", ";", "}", "// If there is a URLStreamHandlerFactory associated for the", "// scheme/protocol, then we create a URLStreamHandler. And, then use", "// then use the URLStreamHandler to create a URL.", "URLStreamHandler", "handler", "=", "factory", ".", "createURLStreamHandler", "(", "protocol", ")", ";", "return", "new", "URL", "(", "protocol", ",", "host", ",", "port", ",", "file", ",", "handler", ")", ";", "}" ]
Creates a URL from the specified protocol name, host name, port number, and file name. <p/> No validation of the inputs is performed by this method. @param protocol the name of the protocol to use @param host the name of the host @param port the port number @param file the file on the host @return URL created using specified protocol, host, and file @throws MalformedURLException if an unknown protocol is specified
[ "Creates", "a", "URL", "from", "the", "specified", "protocol", "name", "host", "name", "port", "number", "and", "file", "name", ".", "<p", "/", ">", "No", "validation", "of", "the", "inputs", "is", "performed", "by", "this", "method", "." ]
train
https://github.com/kaazing/java.client/blob/25ad2ae5bb24aa9d6b79400fce649b518dcfbe26/net.api/src/main/java/org/kaazing/net/URLFactory.java#L182-L199
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/util/Utils.java
Utils.matches
public static boolean matches(final String text1, final String text2, final Configuration config) { """ システム設定に従いラベルを比較する。 <p>正規表現や正規化を行い指定する。 @since 1.1 @param text1 セルのラベル @param text2 アノテーションに指定されているラベル。 {@literal /<ラベル>/}と指定する場合、正規表現による比較を行う。 @param config システム設定 @return true:ラベルが一致する。 """ if(config.isRegexLabelText() && text2.startsWith("/") && text2.endsWith("/")){ return normalize(text1, config).matches(text2.substring(1, text2.length() - 1)); } else { return normalize(text1, config).equals(normalize(text2, config)); // return normalize(text1, config).equals(text2); } }
java
public static boolean matches(final String text1, final String text2, final Configuration config){ if(config.isRegexLabelText() && text2.startsWith("/") && text2.endsWith("/")){ return normalize(text1, config).matches(text2.substring(1, text2.length() - 1)); } else { return normalize(text1, config).equals(normalize(text2, config)); // return normalize(text1, config).equals(text2); } }
[ "public", "static", "boolean", "matches", "(", "final", "String", "text1", ",", "final", "String", "text2", ",", "final", "Configuration", "config", ")", "{", "if", "(", "config", ".", "isRegexLabelText", "(", ")", "&&", "text2", ".", "startsWith", "(", "\"/\"", ")", "&&", "text2", ".", "endsWith", "(", "\"/\"", ")", ")", "{", "return", "normalize", "(", "text1", ",", "config", ")", ".", "matches", "(", "text2", ".", "substring", "(", "1", ",", "text2", ".", "length", "(", ")", "-", "1", ")", ")", ";", "}", "else", "{", "return", "normalize", "(", "text1", ",", "config", ")", ".", "equals", "(", "normalize", "(", "text2", ",", "config", ")", ")", ";", "// return normalize(text1, config).equals(text2);\r", "}", "}" ]
システム設定に従いラベルを比較する。 <p>正規表現や正規化を行い指定する。 @since 1.1 @param text1 セルのラベル @param text2 アノテーションに指定されているラベル。 {@literal /<ラベル>/}と指定する場合、正規表現による比較を行う。 @param config システム設定 @return true:ラベルが一致する。
[ "システム設定に従いラベルを比較する。", "<p", ">", "正規表現や正規化を行い指定する。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/Utils.java#L240-L247
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/ri/GetDeclaredMethodLookup.java
GetDeclaredMethodLookup.isMoreSpecificReturnTypeThan
private boolean isMoreSpecificReturnTypeThan(Invoker m1, Invoker m2) { """ /* @return true if m2 has a more specific return type than m1 """ //This uses 'Class.isAssigableFrom'. This is ok, assuming that inheritance hierarchy is not something that we are allowed // to change on reloads. Class<?> cls1 = m1.getReturnType(); Class<?> cls2 = m2.getReturnType(); return cls2.isAssignableFrom(cls1); }
java
private boolean isMoreSpecificReturnTypeThan(Invoker m1, Invoker m2) { //This uses 'Class.isAssigableFrom'. This is ok, assuming that inheritance hierarchy is not something that we are allowed // to change on reloads. Class<?> cls1 = m1.getReturnType(); Class<?> cls2 = m2.getReturnType(); return cls2.isAssignableFrom(cls1); }
[ "private", "boolean", "isMoreSpecificReturnTypeThan", "(", "Invoker", "m1", ",", "Invoker", "m2", ")", "{", "//This uses 'Class.isAssigableFrom'. This is ok, assuming that inheritance hierarchy is not something that we are allowed", "// to change on reloads.", "Class", "<", "?", ">", "cls1", "=", "m1", ".", "getReturnType", "(", ")", ";", "Class", "<", "?", ">", "cls2", "=", "m2", ".", "getReturnType", "(", ")", ";", "return", "cls2", ".", "isAssignableFrom", "(", "cls1", ")", ";", "}" ]
/* @return true if m2 has a more specific return type than m1
[ "/", "*" ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/ri/GetDeclaredMethodLookup.java#L57-L63
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-maven/src/main/java/org/xwiki/extension/maven/internal/MavenUtils.java
MavenUtils.toExtensionId
public static ExtensionId toExtensionId(String groupId, String artifactId, String classifier, String version) { """ Create a extension identifier from Maven artifact identifier elements. @param groupId the group id @param artifactId the artifact id @param classifier the classifier @param version the version @return the extension identifier @since 10.9 @since 10.8.1 """ return toExtensionId(groupId, artifactId, classifier, version != null ? new DefaultVersion(version) : null); }
java
public static ExtensionId toExtensionId(String groupId, String artifactId, String classifier, String version) { return toExtensionId(groupId, artifactId, classifier, version != null ? new DefaultVersion(version) : null); }
[ "public", "static", "ExtensionId", "toExtensionId", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "classifier", ",", "String", "version", ")", "{", "return", "toExtensionId", "(", "groupId", ",", "artifactId", ",", "classifier", ",", "version", "!=", "null", "?", "new", "DefaultVersion", "(", "version", ")", ":", "null", ")", ";", "}" ]
Create a extension identifier from Maven artifact identifier elements. @param groupId the group id @param artifactId the artifact id @param classifier the classifier @param version the version @return the extension identifier @since 10.9 @since 10.8.1
[ "Create", "a", "extension", "identifier", "from", "Maven", "artifact", "identifier", "elements", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-maven/src/main/java/org/xwiki/extension/maven/internal/MavenUtils.java#L122-L125
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/DataChecksum.java
DataChecksum.calculateChunkedSums
public void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums) { """ Calculate checksums for the given data. The 'mark' of the ByteBuffer parameters may be modified by this function, but the position is maintained. @param data the DirectByteBuffer pointing to the data to checksum. @param checksums the DirectByteBuffer into which checksums will be stored. Enough space must be available in this buffer to put the checksums. """ if (size == 0) return; if (data.hasArray() && checksums.hasArray()) { calculateChunkedSums(data.array(), data.arrayOffset() + data.position(), data.remaining(), checksums.array(), checksums.arrayOffset() + checksums.position()); return; } data.mark(); checksums.mark(); try { byte[] buf = new byte[bytesPerChecksum]; while (data.remaining() > 0) { int n = Math.min(data.remaining(), bytesPerChecksum); data.get(buf, 0, n); summer.reset(); summer.update(buf, 0, n); checksums.putInt((int)summer.getValue()); } } finally { data.reset(); checksums.reset(); } }
java
public void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums) { if (size == 0) return; if (data.hasArray() && checksums.hasArray()) { calculateChunkedSums(data.array(), data.arrayOffset() + data.position(), data.remaining(), checksums.array(), checksums.arrayOffset() + checksums.position()); return; } data.mark(); checksums.mark(); try { byte[] buf = new byte[bytesPerChecksum]; while (data.remaining() > 0) { int n = Math.min(data.remaining(), bytesPerChecksum); data.get(buf, 0, n); summer.reset(); summer.update(buf, 0, n); checksums.putInt((int)summer.getValue()); } } finally { data.reset(); checksums.reset(); } }
[ "public", "void", "calculateChunkedSums", "(", "ByteBuffer", "data", ",", "ByteBuffer", "checksums", ")", "{", "if", "(", "size", "==", "0", ")", "return", ";", "if", "(", "data", ".", "hasArray", "(", ")", "&&", "checksums", ".", "hasArray", "(", ")", ")", "{", "calculateChunkedSums", "(", "data", ".", "array", "(", ")", ",", "data", ".", "arrayOffset", "(", ")", "+", "data", ".", "position", "(", ")", ",", "data", ".", "remaining", "(", ")", ",", "checksums", ".", "array", "(", ")", ",", "checksums", ".", "arrayOffset", "(", ")", "+", "checksums", ".", "position", "(", ")", ")", ";", "return", ";", "}", "data", ".", "mark", "(", ")", ";", "checksums", ".", "mark", "(", ")", ";", "try", "{", "byte", "[", "]", "buf", "=", "new", "byte", "[", "bytesPerChecksum", "]", ";", "while", "(", "data", ".", "remaining", "(", ")", ">", "0", ")", "{", "int", "n", "=", "Math", ".", "min", "(", "data", ".", "remaining", "(", ")", ",", "bytesPerChecksum", ")", ";", "data", ".", "get", "(", "buf", ",", "0", ",", "n", ")", ";", "summer", ".", "reset", "(", ")", ";", "summer", ".", "update", "(", "buf", ",", "0", ",", "n", ")", ";", "checksums", ".", "putInt", "(", "(", "int", ")", "summer", ".", "getValue", "(", ")", ")", ";", "}", "}", "finally", "{", "data", ".", "reset", "(", ")", ";", "checksums", ".", "reset", "(", ")", ";", "}", "}" ]
Calculate checksums for the given data. The 'mark' of the ByteBuffer parameters may be modified by this function, but the position is maintained. @param data the DirectByteBuffer pointing to the data to checksum. @param checksums the DirectByteBuffer into which checksums will be stored. Enough space must be available in this buffer to put the checksums.
[ "Calculate", "checksums", "for", "the", "given", "data", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/DataChecksum.java#L401-L425
JDBDT/jdbdt
src/main/java/org/jdbdt/JDBDT.java
JDBDT.assertTableExists
@SafeVarargs public static void assertTableExists(DB db, String... tableNames) throws DBAssertionError { """ Assert that tables exist in the database. @param db Database. @param tableNames Table names. @throws DBAssertionError If the assertion fails. @see #assertTableDoesNotExist(DB, String...) @see #drop(Table...) @since 1.2 """ multipleTableExistenceAssertions(CallInfo.create(), db, tableNames, true); }
java
@SafeVarargs public static void assertTableExists(DB db, String... tableNames) throws DBAssertionError { multipleTableExistenceAssertions(CallInfo.create(), db, tableNames, true); }
[ "@", "SafeVarargs", "public", "static", "void", "assertTableExists", "(", "DB", "db", ",", "String", "...", "tableNames", ")", "throws", "DBAssertionError", "{", "multipleTableExistenceAssertions", "(", "CallInfo", ".", "create", "(", ")", ",", "db", ",", "tableNames", ",", "true", ")", ";", "}" ]
Assert that tables exist in the database. @param db Database. @param tableNames Table names. @throws DBAssertionError If the assertion fails. @see #assertTableDoesNotExist(DB, String...) @see #drop(Table...) @since 1.2
[ "Assert", "that", "tables", "exist", "in", "the", "database", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L794-L797
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/BitFieldArgs.java
BitFieldArgs.incrBy
public BitFieldArgs incrBy(BitFieldType bitFieldType, Offset offset, long value) { """ Adds a new {@code INCRBY} subcommand. @param bitFieldType the bit field type, must not be {@literal null}. @param offset bitfield offset, must not be {@literal null}. @param value the value @return a new {@code INCRBY} subcommand for the given {@code bitFieldType}, {@code offset} and {@code value}. @since 4.3 """ LettuceAssert.notNull(offset, "BitFieldOffset must not be null"); return addSubCommand(new IncrBy(bitFieldType, offset.isMultiplyByTypeWidth(), offset.getOffset(), value)); }
java
public BitFieldArgs incrBy(BitFieldType bitFieldType, Offset offset, long value) { LettuceAssert.notNull(offset, "BitFieldOffset must not be null"); return addSubCommand(new IncrBy(bitFieldType, offset.isMultiplyByTypeWidth(), offset.getOffset(), value)); }
[ "public", "BitFieldArgs", "incrBy", "(", "BitFieldType", "bitFieldType", ",", "Offset", "offset", ",", "long", "value", ")", "{", "LettuceAssert", ".", "notNull", "(", "offset", ",", "\"BitFieldOffset must not be null\"", ")", ";", "return", "addSubCommand", "(", "new", "IncrBy", "(", "bitFieldType", ",", "offset", ".", "isMultiplyByTypeWidth", "(", ")", ",", "offset", ".", "getOffset", "(", ")", ",", "value", ")", ")", ";", "}" ]
Adds a new {@code INCRBY} subcommand. @param bitFieldType the bit field type, must not be {@literal null}. @param offset bitfield offset, must not be {@literal null}. @param value the value @return a new {@code INCRBY} subcommand for the given {@code bitFieldType}, {@code offset} and {@code value}. @since 4.3
[ "Adds", "a", "new", "{", "@code", "INCRBY", "}", "subcommand", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/BitFieldArgs.java#L380-L385
atomix/copycat
server/src/main/java/io/atomix/copycat/server/state/ServerSessionContext.java
ServerSessionContext.registerResult
ServerSessionContext registerResult(long sequence, ServerStateMachine.Result result) { """ Registers a session result. <p> Results are stored in memory on all servers in order to provide linearizable semantics. When a command is applied to the state machine, the command's return value is stored with the sequence number. Once the client acknowledges receipt of the command output the result will be cleared from memory. @param sequence The result sequence number. @param result The result. @return The server session. """ results.put(sequence, result); return this; }
java
ServerSessionContext registerResult(long sequence, ServerStateMachine.Result result) { results.put(sequence, result); return this; }
[ "ServerSessionContext", "registerResult", "(", "long", "sequence", ",", "ServerStateMachine", ".", "Result", "result", ")", "{", "results", ".", "put", "(", "sequence", ",", "result", ")", ";", "return", "this", ";", "}" ]
Registers a session result. <p> Results are stored in memory on all servers in order to provide linearizable semantics. When a command is applied to the state machine, the command's return value is stored with the sequence number. Once the client acknowledges receipt of the command output the result will be cleared from memory. @param sequence The result sequence number. @param result The result. @return The server session.
[ "Registers", "a", "session", "result", ".", "<p", ">", "Results", "are", "stored", "in", "memory", "on", "all", "servers", "in", "order", "to", "provide", "linearizable", "semantics", ".", "When", "a", "command", "is", "applied", "to", "the", "state", "machine", "the", "command", "s", "return", "value", "is", "stored", "with", "the", "sequence", "number", ".", "Once", "the", "client", "acknowledges", "receipt", "of", "the", "command", "output", "the", "result", "will", "be", "cleared", "from", "memory", "." ]
train
https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/state/ServerSessionContext.java#L354-L357
Azure/azure-sdk-for-java
hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ConfigurationsInner.java
ConfigurationsInner.updateAsync
public Observable<Void> updateAsync(String resourceGroupName, String clusterName, String configurationName, Map<String, String> parameters) { """ Configures the HTTP settings on the specified cluster. This API is deprecated, please use UpdateGatewaySettings in cluster endpoint instead. @param resourceGroupName The name of the resource group. @param clusterName The name of the cluster. @param configurationName The name of the cluster configuration. @param parameters The cluster configurations. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return updateWithServiceResponseAsync(resourceGroupName, clusterName, configurationName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> updateAsync(String resourceGroupName, String clusterName, String configurationName, Map<String, String> parameters) { return updateWithServiceResponseAsync(resourceGroupName, clusterName, configurationName, parameters).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "String", "configurationName", ",", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "(", "resourceGroupName", ",", "clusterName", ",", "configurationName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Configures the HTTP settings on the specified cluster. This API is deprecated, please use UpdateGatewaySettings in cluster endpoint instead. @param resourceGroupName The name of the resource group. @param clusterName The name of the cluster. @param configurationName The name of the cluster configuration. @param parameters The cluster configurations. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Configures", "the", "HTTP", "settings", "on", "the", "specified", "cluster", ".", "This", "API", "is", "deprecated", "please", "use", "UpdateGatewaySettings", "in", "cluster", "endpoint", "instead", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ConfigurationsInner.java#L202-L209
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/linear/kernelized/BOGD.java
BOGD.guessRegularization
public static Distribution guessRegularization(DataSet d) { """ Guesses the distribution to use for the Regularization parameter @param d the dataset to get the guess for @return the guess for the Regularization parameter @see #setRegularization(double) """ double T2 = d.size(); T2*=T2; return new LogUniform(Math.pow(2, -3)/T2, Math.pow(2, 3)/T2); }
java
public static Distribution guessRegularization(DataSet d) { double T2 = d.size(); T2*=T2; return new LogUniform(Math.pow(2, -3)/T2, Math.pow(2, 3)/T2); }
[ "public", "static", "Distribution", "guessRegularization", "(", "DataSet", "d", ")", "{", "double", "T2", "=", "d", ".", "size", "(", ")", ";", "T2", "*=", "T2", ";", "return", "new", "LogUniform", "(", "Math", ".", "pow", "(", "2", ",", "-", "3", ")", "/", "T2", ",", "Math", ".", "pow", "(", "2", ",", "3", ")", "/", "T2", ")", ";", "}" ]
Guesses the distribution to use for the Regularization parameter @param d the dataset to get the guess for @return the guess for the Regularization parameter @see #setRegularization(double)
[ "Guesses", "the", "distribution", "to", "use", "for", "the", "Regularization", "parameter" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/kernelized/BOGD.java#L388-L394
lucee/Lucee
core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java
ResourceUtil.toResourceExistingParent
public static Resource toResourceExistingParent(PageContext pc, String destination) throws ExpressionException { """ cast a String (argument destination) to a File Object, if destination is not a absolute, file object will be relative to current position (get from PageContext) at least parent must exist @param pc Page Context to the current position in filesystem @param destination relative or absolute path for file object @return file object from destination @throws ExpressionException """ return toResourceExistingParent(pc, destination, pc.getConfig().allowRealPath()); }
java
public static Resource toResourceExistingParent(PageContext pc, String destination) throws ExpressionException { return toResourceExistingParent(pc, destination, pc.getConfig().allowRealPath()); }
[ "public", "static", "Resource", "toResourceExistingParent", "(", "PageContext", "pc", ",", "String", "destination", ")", "throws", "ExpressionException", "{", "return", "toResourceExistingParent", "(", "pc", ",", "destination", ",", "pc", ".", "getConfig", "(", ")", ".", "allowRealPath", "(", ")", ")", ";", "}" ]
cast a String (argument destination) to a File Object, if destination is not a absolute, file object will be relative to current position (get from PageContext) at least parent must exist @param pc Page Context to the current position in filesystem @param destination relative or absolute path for file object @return file object from destination @throws ExpressionException
[ "cast", "a", "String", "(", "argument", "destination", ")", "to", "a", "File", "Object", "if", "destination", "is", "not", "a", "absolute", "file", "object", "will", "be", "relative", "to", "current", "position", "(", "get", "from", "PageContext", ")", "at", "least", "parent", "must", "exist" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceUtil.java#L261-L263
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_serviceMonitoring_monitoringId_GET
public OvhServiceMonitoring serviceName_serviceMonitoring_monitoringId_GET(String serviceName, Long monitoringId) throws IOException { """ Get this object properties REST: GET /dedicated/server/{serviceName}/serviceMonitoring/{monitoringId} @param serviceName [required] The internal name of your dedicated server @param monitoringId [required] This monitoring id """ String qPath = "/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}"; StringBuilder sb = path(qPath, serviceName, monitoringId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhServiceMonitoring.class); }
java
public OvhServiceMonitoring serviceName_serviceMonitoring_monitoringId_GET(String serviceName, Long monitoringId) throws IOException { String qPath = "/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}"; StringBuilder sb = path(qPath, serviceName, monitoringId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhServiceMonitoring.class); }
[ "public", "OvhServiceMonitoring", "serviceName_serviceMonitoring_monitoringId_GET", "(", "String", "serviceName", ",", "Long", "monitoringId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/server/{serviceName}/serviceMonitoring/{monitoringId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "monitoringId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhServiceMonitoring", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /dedicated/server/{serviceName}/serviceMonitoring/{monitoringId} @param serviceName [required] The internal name of your dedicated server @param monitoringId [required] This monitoring id
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L2268-L2273
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/release/gradle/BaseGradleReleaseAction.java
BaseGradleReleaseAction.getModuleRoot
public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException { """ Get the root path where the build is located, the project may be checked out to a sub-directory from the root workspace location. @param globalEnv EnvVars to take the workspace from, if workspace is not found then it is take from project.getSomeWorkspace() @return The location of the root of the Gradle build. @throws IOException @throws InterruptedException """ FilePath someWorkspace = project.getSomeWorkspace(); if (someWorkspace == null) { throw new IllegalStateException("Couldn't find workspace"); } Map<String, String> workspaceEnv = Maps.newHashMap(); workspaceEnv.put("WORKSPACE", someWorkspace.getRemote()); for (Builder builder : getBuilders()) { if (builder instanceof Gradle) { Gradle gradleBuilder = (Gradle) builder; String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir(); if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) { String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv); rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv); return new FilePath(someWorkspace, rootBuildScriptNormalized); } else { return someWorkspace; } } } throw new IllegalArgumentException("Couldn't find Gradle builder in the current builders list"); }
java
public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException { FilePath someWorkspace = project.getSomeWorkspace(); if (someWorkspace == null) { throw new IllegalStateException("Couldn't find workspace"); } Map<String, String> workspaceEnv = Maps.newHashMap(); workspaceEnv.put("WORKSPACE", someWorkspace.getRemote()); for (Builder builder : getBuilders()) { if (builder instanceof Gradle) { Gradle gradleBuilder = (Gradle) builder; String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir(); if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) { String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv); rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv); return new FilePath(someWorkspace, rootBuildScriptNormalized); } else { return someWorkspace; } } } throw new IllegalArgumentException("Couldn't find Gradle builder in the current builders list"); }
[ "public", "FilePath", "getModuleRoot", "(", "Map", "<", "String", ",", "String", ">", "globalEnv", ")", "throws", "IOException", ",", "InterruptedException", "{", "FilePath", "someWorkspace", "=", "project", ".", "getSomeWorkspace", "(", ")", ";", "if", "(", "someWorkspace", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Couldn't find workspace\"", ")", ";", "}", "Map", "<", "String", ",", "String", ">", "workspaceEnv", "=", "Maps", ".", "newHashMap", "(", ")", ";", "workspaceEnv", ".", "put", "(", "\"WORKSPACE\"", ",", "someWorkspace", ".", "getRemote", "(", ")", ")", ";", "for", "(", "Builder", "builder", ":", "getBuilders", "(", ")", ")", "{", "if", "(", "builder", "instanceof", "Gradle", ")", "{", "Gradle", "gradleBuilder", "=", "(", "Gradle", ")", "builder", ";", "String", "rootBuildScriptDir", "=", "gradleBuilder", ".", "getRootBuildScriptDir", "(", ")", ";", "if", "(", "rootBuildScriptDir", "!=", "null", "&&", "rootBuildScriptDir", ".", "trim", "(", ")", ".", "length", "(", ")", "!=", "0", ")", "{", "String", "rootBuildScriptNormalized", "=", "Util", ".", "replaceMacro", "(", "rootBuildScriptDir", ".", "trim", "(", ")", ",", "workspaceEnv", ")", ";", "rootBuildScriptNormalized", "=", "Util", ".", "replaceMacro", "(", "rootBuildScriptNormalized", ",", "globalEnv", ")", ";", "return", "new", "FilePath", "(", "someWorkspace", ",", "rootBuildScriptNormalized", ")", ";", "}", "else", "{", "return", "someWorkspace", ";", "}", "}", "}", "throw", "new", "IllegalArgumentException", "(", "\"Couldn't find Gradle builder in the current builders list\"", ")", ";", "}" ]
Get the root path where the build is located, the project may be checked out to a sub-directory from the root workspace location. @param globalEnv EnvVars to take the workspace from, if workspace is not found then it is take from project.getSomeWorkspace() @return The location of the root of the Gradle build. @throws IOException @throws InterruptedException
[ "Get", "the", "root", "path", "where", "the", "build", "is", "located", "the", "project", "may", "be", "checked", "out", "to", "a", "sub", "-", "directory", "from", "the", "root", "workspace", "location", "." ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/release/gradle/BaseGradleReleaseAction.java#L100-L124
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/PoissonDistribution.java
PoissonDistribution.rawLogProbability
public static double rawLogProbability(double x, double lambda) { """ Poisson distribution probability, but also for non-integer arguments. <p> lb^x exp(-lb) / x! @param x X @param lambda lambda @return Poisson distribution probability """ // Extreme lambda if(lambda == 0) { return ((x == 0) ? 1. : Double.NEGATIVE_INFINITY); } // Extreme values if(Double.isInfinite(lambda) || x < 0) { return Double.NEGATIVE_INFINITY; } if(x <= lambda * Double.MIN_NORMAL) { return -lambda; } if(lambda < x * Double.MIN_NORMAL) { return -lambda + x * FastMath.log(lambda) - GammaDistribution.logGamma(x + 1); } final double f = MathUtil.TWOPI * x; final double y = -stirlingError(x) - devianceTerm(x, lambda); return -0.5 * FastMath.log(f) + y; }
java
public static double rawLogProbability(double x, double lambda) { // Extreme lambda if(lambda == 0) { return ((x == 0) ? 1. : Double.NEGATIVE_INFINITY); } // Extreme values if(Double.isInfinite(lambda) || x < 0) { return Double.NEGATIVE_INFINITY; } if(x <= lambda * Double.MIN_NORMAL) { return -lambda; } if(lambda < x * Double.MIN_NORMAL) { return -lambda + x * FastMath.log(lambda) - GammaDistribution.logGamma(x + 1); } final double f = MathUtil.TWOPI * x; final double y = -stirlingError(x) - devianceTerm(x, lambda); return -0.5 * FastMath.log(f) + y; }
[ "public", "static", "double", "rawLogProbability", "(", "double", "x", ",", "double", "lambda", ")", "{", "// Extreme lambda", "if", "(", "lambda", "==", "0", ")", "{", "return", "(", "(", "x", "==", "0", ")", "?", "1.", ":", "Double", ".", "NEGATIVE_INFINITY", ")", ";", "}", "// Extreme values", "if", "(", "Double", ".", "isInfinite", "(", "lambda", ")", "||", "x", "<", "0", ")", "{", "return", "Double", ".", "NEGATIVE_INFINITY", ";", "}", "if", "(", "x", "<=", "lambda", "*", "Double", ".", "MIN_NORMAL", ")", "{", "return", "-", "lambda", ";", "}", "if", "(", "lambda", "<", "x", "*", "Double", ".", "MIN_NORMAL", ")", "{", "return", "-", "lambda", "+", "x", "*", "FastMath", ".", "log", "(", "lambda", ")", "-", "GammaDistribution", ".", "logGamma", "(", "x", "+", "1", ")", ";", "}", "final", "double", "f", "=", "MathUtil", ".", "TWOPI", "*", "x", ";", "final", "double", "y", "=", "-", "stirlingError", "(", "x", ")", "-", "devianceTerm", "(", "x", ",", "lambda", ")", ";", "return", "-", "0.5", "*", "FastMath", ".", "log", "(", "f", ")", "+", "y", ";", "}" ]
Poisson distribution probability, but also for non-integer arguments. <p> lb^x exp(-lb) / x! @param x X @param lambda lambda @return Poisson distribution probability
[ "Poisson", "distribution", "probability", "but", "also", "for", "non", "-", "integer", "arguments", ".", "<p", ">", "lb^x", "exp", "(", "-", "lb", ")", "/", "x!" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/PoissonDistribution.java#L464-L482
hibernate/hibernate-ogm
core/src/main/java/org/hibernate/ogm/datastore/document/association/spi/AssociationRow.java
AssociationRow.buildRowKey
private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) { """ Creates the row key of the given association row; columns present in the given association key will be obtained from there, all other columns from the given native association row. """ String[] columnNames = associationKey.getMetadata().getRowKeyColumnNames(); Object[] columnValues = new Object[columnNames.length]; for ( int i = 0; i < columnNames.length; i++ ) { String columnName = columnNames[i]; columnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName ); } return new RowKey( columnNames, columnValues ); }
java
private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) { String[] columnNames = associationKey.getMetadata().getRowKeyColumnNames(); Object[] columnValues = new Object[columnNames.length]; for ( int i = 0; i < columnNames.length; i++ ) { String columnName = columnNames[i]; columnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName ); } return new RowKey( columnNames, columnValues ); }
[ "private", "static", "<", "R", ">", "RowKey", "buildRowKey", "(", "AssociationKey", "associationKey", ",", "R", "row", ",", "AssociationRowAccessor", "<", "R", ">", "accessor", ")", "{", "String", "[", "]", "columnNames", "=", "associationKey", ".", "getMetadata", "(", ")", ".", "getRowKeyColumnNames", "(", ")", ";", "Object", "[", "]", "columnValues", "=", "new", "Object", "[", "columnNames", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnNames", ".", "length", ";", "i", "++", ")", "{", "String", "columnName", "=", "columnNames", "[", "i", "]", ";", "columnValues", "[", "i", "]", "=", "associationKey", ".", "getMetadata", "(", ")", ".", "isKeyColumn", "(", "columnName", ")", "?", "associationKey", ".", "getColumnValue", "(", "columnName", ")", ":", "accessor", ".", "get", "(", "row", ",", "columnName", ")", ";", "}", "return", "new", "RowKey", "(", "columnNames", ",", "columnValues", ")", ";", "}" ]
Creates the row key of the given association row; columns present in the given association key will be obtained from there, all other columns from the given native association row.
[ "Creates", "the", "row", "key", "of", "the", "given", "association", "row", ";", "columns", "present", "in", "the", "given", "association", "key", "will", "be", "obtained", "from", "there", "all", "other", "columns", "from", "the", "given", "native", "association", "row", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/datastore/document/association/spi/AssociationRow.java#L74-L84
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceRegionPersistenceImpl.java
CommerceRegionPersistenceImpl.findByC_A
@Override public List<CommerceRegion> findByC_A(long commerceCountryId, boolean active, int start, int end) { """ Returns a range of all the commerce regions where commerceCountryId = &#63; and active = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceRegionModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commerceCountryId the commerce country ID @param active the active @param start the lower bound of the range of commerce regions @param end the upper bound of the range of commerce regions (not inclusive) @return the range of matching commerce regions """ return findByC_A(commerceCountryId, active, start, end, null); }
java
@Override public List<CommerceRegion> findByC_A(long commerceCountryId, boolean active, int start, int end) { return findByC_A(commerceCountryId, active, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceRegion", ">", "findByC_A", "(", "long", "commerceCountryId", ",", "boolean", "active", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByC_A", "(", "commerceCountryId", ",", "active", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce regions where commerceCountryId = &#63; and active = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceRegionModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commerceCountryId the commerce country ID @param active the active @param start the lower bound of the range of commerce regions @param end the upper bound of the range of commerce regions (not inclusive) @return the range of matching commerce regions
[ "Returns", "a", "range", "of", "all", "the", "commerce", "regions", "where", "commerceCountryId", "=", "&#63", ";", "and", "active", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceRegionPersistenceImpl.java#L2300-L2304
dadoonet/elasticsearch-beyonder
src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java
TemplateElasticsearchUpdater.createTemplateWithJsonInElasticsearch
@Deprecated private static void createTemplateWithJsonInElasticsearch(Client client, String template, String json) throws Exception { """ Create a new index in Elasticsearch @param client Elasticsearch client @param template Template name @param json JSon content for the template @throws Exception if something goes wrong @deprecated Will be removed when we don't support TransportClient anymore """ logger.trace("createTemplate([{}])", template); assert client != null; assert template != null; AcknowledgedResponse response = client.admin().indices() .preparePutTemplate(template) .setSource(json.getBytes(), XContentType.JSON) .get(); if (!response.isAcknowledged()) { logger.warn("Could not create template [{}]", template); throw new Exception("Could not create template ["+template+"]."); } logger.trace("/createTemplate([{}])", template); }
java
@Deprecated private static void createTemplateWithJsonInElasticsearch(Client client, String template, String json) throws Exception { logger.trace("createTemplate([{}])", template); assert client != null; assert template != null; AcknowledgedResponse response = client.admin().indices() .preparePutTemplate(template) .setSource(json.getBytes(), XContentType.JSON) .get(); if (!response.isAcknowledged()) { logger.warn("Could not create template [{}]", template); throw new Exception("Could not create template ["+template+"]."); } logger.trace("/createTemplate([{}])", template); }
[ "@", "Deprecated", "private", "static", "void", "createTemplateWithJsonInElasticsearch", "(", "Client", "client", ",", "String", "template", ",", "String", "json", ")", "throws", "Exception", "{", "logger", ".", "trace", "(", "\"createTemplate([{}])\"", ",", "template", ")", ";", "assert", "client", "!=", "null", ";", "assert", "template", "!=", "null", ";", "AcknowledgedResponse", "response", "=", "client", ".", "admin", "(", ")", ".", "indices", "(", ")", ".", "preparePutTemplate", "(", "template", ")", ".", "setSource", "(", "json", ".", "getBytes", "(", ")", ",", "XContentType", ".", "JSON", ")", ".", "get", "(", ")", ";", "if", "(", "!", "response", ".", "isAcknowledged", "(", ")", ")", "{", "logger", ".", "warn", "(", "\"Could not create template [{}]\"", ",", "template", ")", ";", "throw", "new", "Exception", "(", "\"Could not create template [\"", "+", "template", "+", "\"].\"", ")", ";", "}", "logger", ".", "trace", "(", "\"/createTemplate([{}])\"", ",", "template", ")", ";", "}" ]
Create a new index in Elasticsearch @param client Elasticsearch client @param template Template name @param json JSon content for the template @throws Exception if something goes wrong @deprecated Will be removed when we don't support TransportClient anymore
[ "Create", "a", "new", "index", "in", "Elasticsearch" ]
train
https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java#L104-L122
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/ws/pmi/server/NLS.java
NLS.getFormattedMessage
public String getFormattedMessage(String key, Object[] args, String defaultString) { """ An easy way to pass variables into the messages. Provides a consistent way of formatting the {0} type parameters. Returns the formatted resource, or if it is not found, the formatted default string that was passed in. @param key Resource lookup key @param args Variables to insert into the string. @param defaultString Default string to use if the resource is not found. """ try { String result = getString(key); return MessageFormat.format(result, args); } catch (MissingResourceException e) { return MessageFormat.format(defaultString, args); } }
java
public String getFormattedMessage(String key, Object[] args, String defaultString) { try { String result = getString(key); return MessageFormat.format(result, args); } catch (MissingResourceException e) { return MessageFormat.format(defaultString, args); } }
[ "public", "String", "getFormattedMessage", "(", "String", "key", ",", "Object", "[", "]", "args", ",", "String", "defaultString", ")", "{", "try", "{", "String", "result", "=", "getString", "(", "key", ")", ";", "return", "MessageFormat", ".", "format", "(", "result", ",", "args", ")", ";", "}", "catch", "(", "MissingResourceException", "e", ")", "{", "return", "MessageFormat", ".", "format", "(", "defaultString", ",", "args", ")", ";", "}", "}" ]
An easy way to pass variables into the messages. Provides a consistent way of formatting the {0} type parameters. Returns the formatted resource, or if it is not found, the formatted default string that was passed in. @param key Resource lookup key @param args Variables to insert into the string. @param defaultString Default string to use if the resource is not found.
[ "An", "easy", "way", "to", "pass", "variables", "into", "the", "messages", ".", "Provides", "a", "consistent", "way", "of", "formatting", "the", "{", "0", "}", "type", "parameters", ".", "Returns", "the", "formatted", "resource", "or", "if", "it", "is", "not", "found", "the", "formatted", "default", "string", "that", "was", "passed", "in", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/pmi/server/NLS.java#L380-L387
aws/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/PutIntegrationResponseResult.java
PutIntegrationResponseResult.withResponseParameters
public PutIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) { """ <p> A key-value map specifying response parameters that are passed to the method response from the back end. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of <code>method.response.header.{name}</code>, where <code>name</code> is a valid and unique header name. The mapped non-static value must match the pattern of <code>integration.response.header.{name}</code> or <code>integration.response.body.{JSON-expression}</code>, where <code>name</code> is a valid and unique response header name and <code>JSON-expression</code> is a valid JSON expression without the <code>$</code> prefix. </p> @param responseParameters A key-value map specifying response parameters that are passed to the method response from the back end. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of <code>method.response.header.{name}</code>, where <code>name</code> is a valid and unique header name. The mapped non-static value must match the pattern of <code>integration.response.header.{name}</code> or <code>integration.response.body.{JSON-expression}</code>, where <code>name</code> is a valid and unique response header name and <code>JSON-expression</code> is a valid JSON expression without the <code>$</code> prefix. @return Returns a reference to this object so that method calls can be chained together. """ setResponseParameters(responseParameters); return this; }
java
public PutIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) { setResponseParameters(responseParameters); return this; }
[ "public", "PutIntegrationResponseResult", "withResponseParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "responseParameters", ")", "{", "setResponseParameters", "(", "responseParameters", ")", ";", "return", "this", ";", "}" ]
<p> A key-value map specifying response parameters that are passed to the method response from the back end. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of <code>method.response.header.{name}</code>, where <code>name</code> is a valid and unique header name. The mapped non-static value must match the pattern of <code>integration.response.header.{name}</code> or <code>integration.response.body.{JSON-expression}</code>, where <code>name</code> is a valid and unique response header name and <code>JSON-expression</code> is a valid JSON expression without the <code>$</code> prefix. </p> @param responseParameters A key-value map specifying response parameters that are passed to the method response from the back end. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of <code>method.response.header.{name}</code>, where <code>name</code> is a valid and unique header name. The mapped non-static value must match the pattern of <code>integration.response.header.{name}</code> or <code>integration.response.body.{JSON-expression}</code>, where <code>name</code> is a valid and unique response header name and <code>JSON-expression</code> is a valid JSON expression without the <code>$</code> prefix. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "key", "-", "value", "map", "specifying", "response", "parameters", "that", "are", "passed", "to", "the", "method", "response", "from", "the", "back", "end", ".", "The", "key", "is", "a", "method", "response", "header", "parameter", "name", "and", "the", "mapped", "value", "is", "an", "integration", "response", "header", "value", "a", "static", "value", "enclosed", "within", "a", "pair", "of", "single", "quotes", "or", "a", "JSON", "expression", "from", "the", "integration", "response", "body", ".", "The", "mapping", "key", "must", "match", "the", "pattern", "of", "<code", ">", "method", ".", "response", ".", "header", ".", "{", "name", "}", "<", "/", "code", ">", "where", "<code", ">", "name<", "/", "code", ">", "is", "a", "valid", "and", "unique", "header", "name", ".", "The", "mapped", "non", "-", "static", "value", "must", "match", "the", "pattern", "of", "<code", ">", "integration", ".", "response", ".", "header", ".", "{", "name", "}", "<", "/", "code", ">", "or", "<code", ">", "integration", ".", "response", ".", "body", ".", "{", "JSON", "-", "expression", "}", "<", "/", "code", ">", "where", "<code", ">", "name<", "/", "code", ">", "is", "a", "valid", "and", "unique", "response", "header", "name", "and", "<code", ">", "JSON", "-", "expression<", "/", "code", ">", "is", "a", "valid", "JSON", "expression", "without", "the", "<code", ">", "$<", "/", "code", ">", "prefix", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/PutIntegrationResponseResult.java#L284-L287
alkacon/opencms-core
src/org/opencms/jsp/CmsJspResourceWrapper.java
CmsJspResourceWrapper.readResource
private CmsJspResourceWrapper readResource(String sitePath) { """ Reads a resource, suppressing possible exceptions.<p> @param sitePath the site path of the resource to read. @return the resource of <code>null</code> on case an exception occurred while reading """ CmsJspResourceWrapper result = null; try { result = new CmsJspResourceWrapper(m_cms, m_cms.readResource(sitePath)); } catch (CmsException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } } return result; }
java
private CmsJspResourceWrapper readResource(String sitePath) { CmsJspResourceWrapper result = null; try { result = new CmsJspResourceWrapper(m_cms, m_cms.readResource(sitePath)); } catch (CmsException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } } return result; }
[ "private", "CmsJspResourceWrapper", "readResource", "(", "String", "sitePath", ")", "{", "CmsJspResourceWrapper", "result", "=", "null", ";", "try", "{", "result", "=", "new", "CmsJspResourceWrapper", "(", "m_cms", ",", "m_cms", ".", "readResource", "(", "sitePath", ")", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "return", "result", ";", "}" ]
Reads a resource, suppressing possible exceptions.<p> @param sitePath the site path of the resource to read. @return the resource of <code>null</code> on case an exception occurred while reading
[ "Reads", "a", "resource", "suppressing", "possible", "exceptions", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspResourceWrapper.java#L866-L877
phax/ph-web
ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponseDefaultSettings.java
UnifiedResponseDefaultSettings.setXFrameOptions
public static void setXFrameOptions (@Nullable final EXFrameOptionType eType, @Nullable final ISimpleURL aDomain) { """ The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a &lt;frame&gt;, &lt;iframe&gt; or &lt;object&gt; . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites. Example: <pre> X-Frame-Options: DENY X-Frame-Options: SAMEORIGIN X-Frame-Options: ALLOW-FROM https://example.com/ </pre> @param eType The X-Frame-Options type to be set. May not be <code>null</code>. @param aDomain The domain URL to be used in "ALLOW-FROM". May be <code>null</code> for the other cases. """ if (eType != null && eType.isURLRequired ()) ValueEnforcer.notNull (aDomain, "Domain"); if (eType == null) { removeResponseHeaders (CHttpHeader.X_FRAME_OPTIONS); } else { final String sHeaderValue = eType.isURLRequired () ? eType.getID () + " " + aDomain.getAsStringWithEncodedParameters () : eType.getID (); setResponseHeader (CHttpHeader.X_FRAME_OPTIONS, sHeaderValue); } }
java
public static void setXFrameOptions (@Nullable final EXFrameOptionType eType, @Nullable final ISimpleURL aDomain) { if (eType != null && eType.isURLRequired ()) ValueEnforcer.notNull (aDomain, "Domain"); if (eType == null) { removeResponseHeaders (CHttpHeader.X_FRAME_OPTIONS); } else { final String sHeaderValue = eType.isURLRequired () ? eType.getID () + " " + aDomain.getAsStringWithEncodedParameters () : eType.getID (); setResponseHeader (CHttpHeader.X_FRAME_OPTIONS, sHeaderValue); } }
[ "public", "static", "void", "setXFrameOptions", "(", "@", "Nullable", "final", "EXFrameOptionType", "eType", ",", "@", "Nullable", "final", "ISimpleURL", "aDomain", ")", "{", "if", "(", "eType", "!=", "null", "&&", "eType", ".", "isURLRequired", "(", ")", ")", "ValueEnforcer", ".", "notNull", "(", "aDomain", ",", "\"Domain\"", ")", ";", "if", "(", "eType", "==", "null", ")", "{", "removeResponseHeaders", "(", "CHttpHeader", ".", "X_FRAME_OPTIONS", ")", ";", "}", "else", "{", "final", "String", "sHeaderValue", "=", "eType", ".", "isURLRequired", "(", ")", "?", "eType", ".", "getID", "(", ")", "+", "\" \"", "+", "aDomain", ".", "getAsStringWithEncodedParameters", "(", ")", ":", "eType", ".", "getID", "(", ")", ";", "setResponseHeader", "(", "CHttpHeader", ".", "X_FRAME_OPTIONS", ",", "sHeaderValue", ")", ";", "}", "}" ]
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a &lt;frame&gt;, &lt;iframe&gt; or &lt;object&gt; . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites. Example: <pre> X-Frame-Options: DENY X-Frame-Options: SAMEORIGIN X-Frame-Options: ALLOW-FROM https://example.com/ </pre> @param eType The X-Frame-Options type to be set. May not be <code>null</code>. @param aDomain The domain URL to be used in "ALLOW-FROM". May be <code>null</code> for the other cases.
[ "The", "X", "-", "Frame", "-", "Options", "HTTP", "response", "header", "can", "be", "used", "to", "indicate", "whether", "or", "not", "a", "browser", "should", "be", "allowed", "to", "render", "a", "page", "in", "a", "&lt", ";", "frame&gt", ";", "&lt", ";", "iframe&gt", ";", "or", "&lt", ";", "object&gt", ";", ".", "Sites", "can", "use", "this", "to", "avoid", "clickjacking", "attacks", "by", "ensuring", "that", "their", "content", "is", "not", "embedded", "into", "other", "sites", ".", "Example", ":" ]
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponseDefaultSettings.java#L174-L191
iipc/openwayback
wayback-core/src/main/java/org/archive/wayback/resourcestore/locationdb/RemoteResourceFileLocationDB.java
RemoteResourceFileLocationDB.addNameUrl
public void addNameUrl(final String name, final String url) throws IOException { """ add an Url location for an arcName, unless it already exists @param name @param url @throws IOException """ doPostMethod(ResourceFileLocationDBServlet.ADD_OPERATION, name, url); }
java
public void addNameUrl(final String name, final String url) throws IOException { doPostMethod(ResourceFileLocationDBServlet.ADD_OPERATION, name, url); }
[ "public", "void", "addNameUrl", "(", "final", "String", "name", ",", "final", "String", "url", ")", "throws", "IOException", "{", "doPostMethod", "(", "ResourceFileLocationDBServlet", ".", "ADD_OPERATION", ",", "name", ",", "url", ")", ";", "}" ]
add an Url location for an arcName, unless it already exists @param name @param url @throws IOException
[ "add", "an", "Url", "location", "for", "an", "arcName", "unless", "it", "already", "exists" ]
train
https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/resourcestore/locationdb/RemoteResourceFileLocationDB.java#L137-L140
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br/br_remotelicense.java
br_remotelicense.configureremotelicense
public static br_remotelicense configureremotelicense(nitro_service client, br_remotelicense resource) throws Exception { """ <pre> Use this operation to configure Remote license server on Repeater Instances. </pre> """ return ((br_remotelicense[]) resource.perform_operation(client, "configureremotelicense"))[0]; }
java
public static br_remotelicense configureremotelicense(nitro_service client, br_remotelicense resource) throws Exception { return ((br_remotelicense[]) resource.perform_operation(client, "configureremotelicense"))[0]; }
[ "public", "static", "br_remotelicense", "configureremotelicense", "(", "nitro_service", "client", ",", "br_remotelicense", "resource", ")", "throws", "Exception", "{", "return", "(", "(", "br_remotelicense", "[", "]", ")", "resource", ".", "perform_operation", "(", "client", ",", "\"configureremotelicense\"", ")", ")", "[", "0", "]", ";", "}" ]
<pre> Use this operation to configure Remote license server on Repeater Instances. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "configure", "Remote", "license", "server", "on", "Repeater", "Instances", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_remotelicense.java#L147-L150
looly/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/RSA.java
RSA.generatePublicKey
public static PublicKey generatePublicKey(BigInteger modulus, BigInteger publicExponent) { """ 生成RSA公钥 @param modulus N特征值 @param publicExponent e特征值 @return {@link PublicKey} """ return SecureUtil.generatePublicKey(ALGORITHM_RSA.getValue(), new RSAPublicKeySpec(modulus, publicExponent)); }
java
public static PublicKey generatePublicKey(BigInteger modulus, BigInteger publicExponent) { return SecureUtil.generatePublicKey(ALGORITHM_RSA.getValue(), new RSAPublicKeySpec(modulus, publicExponent)); }
[ "public", "static", "PublicKey", "generatePublicKey", "(", "BigInteger", "modulus", ",", "BigInteger", "publicExponent", ")", "{", "return", "SecureUtil", ".", "generatePublicKey", "(", "ALGORITHM_RSA", ".", "getValue", "(", ")", ",", "new", "RSAPublicKeySpec", "(", "modulus", ",", "publicExponent", ")", ")", ";", "}" ]
生成RSA公钥 @param modulus N特征值 @param publicExponent e特征值 @return {@link PublicKey}
[ "生成RSA公钥" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/RSA.java#L53-L55
elki-project/elki
elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/covertree/AbstractCoverTree.java
AbstractCoverTree.excludeNotCovered
protected void excludeNotCovered(ModifiableDoubleDBIDList candidates, double fmax, ModifiableDoubleDBIDList collect) { """ Retain all elements within the current cover. @param candidates Candidates @param fmax Maximum distance @param collect Far neighbors """ for(DoubleDBIDListIter it = candidates.iter(); it.valid();) { if(it.doubleValue() > fmax) { collect.add(it.doubleValue(), it); candidates.removeSwap(it.getOffset()); } else { it.advance(); // Keep in candidates } } }
java
protected void excludeNotCovered(ModifiableDoubleDBIDList candidates, double fmax, ModifiableDoubleDBIDList collect) { for(DoubleDBIDListIter it = candidates.iter(); it.valid();) { if(it.doubleValue() > fmax) { collect.add(it.doubleValue(), it); candidates.removeSwap(it.getOffset()); } else { it.advance(); // Keep in candidates } } }
[ "protected", "void", "excludeNotCovered", "(", "ModifiableDoubleDBIDList", "candidates", ",", "double", "fmax", ",", "ModifiableDoubleDBIDList", "collect", ")", "{", "for", "(", "DoubleDBIDListIter", "it", "=", "candidates", ".", "iter", "(", ")", ";", "it", ".", "valid", "(", ")", ";", ")", "{", "if", "(", "it", ".", "doubleValue", "(", ")", ">", "fmax", ")", "{", "collect", ".", "add", "(", "it", ".", "doubleValue", "(", ")", ",", "it", ")", ";", "candidates", ".", "removeSwap", "(", "it", ".", "getOffset", "(", ")", ")", ";", "}", "else", "{", "it", ".", "advance", "(", ")", ";", "// Keep in candidates", "}", "}", "}" ]
Retain all elements within the current cover. @param candidates Candidates @param fmax Maximum distance @param collect Far neighbors
[ "Retain", "all", "elements", "within", "the", "current", "cover", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/covertree/AbstractCoverTree.java#L173-L183
redkale/redkale
src/org/redkale/util/ResourceFactory.java
ResourceFactory.register
public <A> A register(final String name, final A rs) { """ 将对象以指定资源名注入到资源池中,并同步已被注入的资源 @param <A> 泛型 @param name 资源名 @param rs 资源对象 @return 旧资源对象 """ return register(true, name, rs); }
java
public <A> A register(final String name, final A rs) { return register(true, name, rs); }
[ "public", "<", "A", ">", "A", "register", "(", "final", "String", "name", ",", "final", "A", "rs", ")", "{", "return", "register", "(", "true", ",", "name", ",", "rs", ")", ";", "}" ]
将对象以指定资源名注入到资源池中,并同步已被注入的资源 @param <A> 泛型 @param name 资源名 @param rs 资源对象 @return 旧资源对象
[ "将对象以指定资源名注入到资源池中,并同步已被注入的资源" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/util/ResourceFactory.java#L334-L336
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/MachinetagsApi.java
MachinetagsApi.getPairs
public Pairs getPairs(String namespace, String predicate, int perPage, int page, boolean sign) throws JinxException { """ Return a list of unique namespace and predicate pairs, optionally limited by predicate or namespace, in alphabetical order. <br> This method does not require authentication. @param namespace (Optional) Limit the list of pairs returned to those that have this namespace. @param predicate (Optional) Limit the list of pairs returned to those that have this predicate. @param perPage Number of photos to return per page. If this argument is less than 1, it defaults to 100. The maximum allowed value is 500. @param page The page of results to return. If this argument is less than 1, it defaults to 1. @param sign if true, the request will be signed. @return object containing a list of unique namespace and predicate parts. @throws JinxException if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.machinetags.getPairs.html">flickr.machinetags.getPairs</a> """ Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.machinetags.getPairs"); if (!JinxUtils.isNullOrEmpty(namespace)) { params.put("namespace", namespace); } if (!JinxUtils.isNullOrEmpty(predicate)) { params.put("predicate", predicate); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } if (page > 0) { params.put("page", Integer.toString(page)); } return jinx.flickrGet(params, Pairs.class, sign); }
java
public Pairs getPairs(String namespace, String predicate, int perPage, int page, boolean sign) throws JinxException { Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.machinetags.getPairs"); if (!JinxUtils.isNullOrEmpty(namespace)) { params.put("namespace", namespace); } if (!JinxUtils.isNullOrEmpty(predicate)) { params.put("predicate", predicate); } if (perPage > 0) { params.put("per_page", Integer.toString(perPage)); } if (page > 0) { params.put("page", Integer.toString(page)); } return jinx.flickrGet(params, Pairs.class, sign); }
[ "public", "Pairs", "getPairs", "(", "String", "namespace", ",", "String", "predicate", ",", "int", "perPage", ",", "int", "page", ",", "boolean", "sign", ")", "throws", "JinxException", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "TreeMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"method\"", ",", "\"flickr.machinetags.getPairs\"", ")", ";", "if", "(", "!", "JinxUtils", ".", "isNullOrEmpty", "(", "namespace", ")", ")", "{", "params", ".", "put", "(", "\"namespace\"", ",", "namespace", ")", ";", "}", "if", "(", "!", "JinxUtils", ".", "isNullOrEmpty", "(", "predicate", ")", ")", "{", "params", ".", "put", "(", "\"predicate\"", ",", "predicate", ")", ";", "}", "if", "(", "perPage", ">", "0", ")", "{", "params", ".", "put", "(", "\"per_page\"", ",", "Integer", ".", "toString", "(", "perPage", ")", ")", ";", "}", "if", "(", "page", ">", "0", ")", "{", "params", ".", "put", "(", "\"page\"", ",", "Integer", ".", "toString", "(", "page", ")", ")", ";", "}", "return", "jinx", ".", "flickrGet", "(", "params", ",", "Pairs", ".", "class", ",", "sign", ")", ";", "}" ]
Return a list of unique namespace and predicate pairs, optionally limited by predicate or namespace, in alphabetical order. <br> This method does not require authentication. @param namespace (Optional) Limit the list of pairs returned to those that have this namespace. @param predicate (Optional) Limit the list of pairs returned to those that have this predicate. @param perPage Number of photos to return per page. If this argument is less than 1, it defaults to 100. The maximum allowed value is 500. @param page The page of results to return. If this argument is less than 1, it defaults to 1. @param sign if true, the request will be signed. @return object containing a list of unique namespace and predicate parts. @throws JinxException if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.machinetags.getPairs.html">flickr.machinetags.getPairs</a>
[ "Return", "a", "list", "of", "unique", "namespace", "and", "predicate", "pairs", "optionally", "limited", "by", "predicate", "or", "namespace", "in", "alphabetical", "order", ".", "<br", ">", "This", "method", "does", "not", "require", "authentication", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/MachinetagsApi.java#L86-L102
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/UUID.java
UUID.fromString
public static UUID fromString(String name) { """ 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。 @param name 指定 {@code UUID} 字符串 @return 具有指定值的 {@code UUID} @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常 """ String[] components = name.split("-"); if (components.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + name); } for (int i = 0; i < 5; i++) { components[i] = "0x" + components[i]; } long mostSigBits = Long.decode(components[0]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]).longValue(); long leastSigBits = Long.decode(components[3]).longValue(); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]).longValue(); return new UUID(mostSigBits, leastSigBits); }
java
public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + name); } for (int i = 0; i < 5; i++) { components[i] = "0x" + components[i]; } long mostSigBits = Long.decode(components[0]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]).longValue(); long leastSigBits = Long.decode(components[3]).longValue(); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]).longValue(); return new UUID(mostSigBits, leastSigBits); }
[ "public", "static", "UUID", "fromString", "(", "String", "name", ")", "{", "String", "[", "]", "components", "=", "name", ".", "split", "(", "\"-\"", ")", ";", "if", "(", "components", ".", "length", "!=", "5", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid UUID string: \"", "+", "name", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "5", ";", "i", "++", ")", "{", "components", "[", "i", "]", "=", "\"0x\"", "+", "components", "[", "i", "]", ";", "}", "long", "mostSigBits", "=", "Long", ".", "decode", "(", "components", "[", "0", "]", ")", ".", "longValue", "(", ")", ";", "mostSigBits", "<<=", "16", ";", "mostSigBits", "|=", "Long", ".", "decode", "(", "components", "[", "1", "]", ")", ".", "longValue", "(", ")", ";", "mostSigBits", "<<=", "16", ";", "mostSigBits", "|=", "Long", ".", "decode", "(", "components", "[", "2", "]", ")", ".", "longValue", "(", ")", ";", "long", "leastSigBits", "=", "Long", ".", "decode", "(", "components", "[", "3", "]", ")", ".", "longValue", "(", ")", ";", "leastSigBits", "<<=", "48", ";", "leastSigBits", "|=", "Long", ".", "decode", "(", "components", "[", "4", "]", ")", ".", "longValue", "(", ")", ";", "return", "new", "UUID", "(", "mostSigBits", ",", "leastSigBits", ")", ";", "}" ]
根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。 @param name 指定 {@code UUID} 字符串 @return 具有指定值的 {@code UUID} @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常
[ "根据", "{", "@link", "#toString", "()", "}", "方法中描述的字符串标准表示形式创建", "{", "@code", "UUID", "}", "。" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/UUID.java#L159-L179
hivemq/hivemq-spi
src/main/java/com/hivemq/spi/util/DefaultSslEngineUtil.java
DefaultSslEngineUtil.getSupportedCipherSuites
@ReadOnly public List<String> getSupportedCipherSuites() throws SslException { """ Returns a list of all supported Cipher Suites of the JVM. @return a list of all supported cipher suites of the JVM @throws SslException """ try { final SSLEngine engine = getDefaultSslEngine(); return ImmutableList.copyOf(engine.getSupportedCipherSuites()); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new SslException("Not able to get list of supported cipher suites from JVM", e); } }
java
@ReadOnly public List<String> getSupportedCipherSuites() throws SslException { try { final SSLEngine engine = getDefaultSslEngine(); return ImmutableList.copyOf(engine.getSupportedCipherSuites()); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new SslException("Not able to get list of supported cipher suites from JVM", e); } }
[ "@", "ReadOnly", "public", "List", "<", "String", ">", "getSupportedCipherSuites", "(", ")", "throws", "SslException", "{", "try", "{", "final", "SSLEngine", "engine", "=", "getDefaultSslEngine", "(", ")", ";", "return", "ImmutableList", ".", "copyOf", "(", "engine", ".", "getSupportedCipherSuites", "(", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "|", "KeyManagementException", "e", ")", "{", "throw", "new", "SslException", "(", "\"Not able to get list of supported cipher suites from JVM\"", ",", "e", ")", ";", "}", "}" ]
Returns a list of all supported Cipher Suites of the JVM. @return a list of all supported cipher suites of the JVM @throws SslException
[ "Returns", "a", "list", "of", "all", "supported", "Cipher", "Suites", "of", "the", "JVM", "." ]
train
https://github.com/hivemq/hivemq-spi/blob/55fa89ccb081ad5b6d46eaca02179272148e64ed/src/main/java/com/hivemq/spi/util/DefaultSslEngineUtil.java#L43-L54
stratosphere/stratosphere
stratosphere-addons/spargel/src/main/java/eu/stratosphere/spargel/java/VertexCentricIteration.java
VertexCentricIteration.createResult
@Override public DataSet<Tuple2<VertexKey, VertexValue>> createResult() { """ Creates the operator that represents this vertex-centric graph computation. @return The operator that represents this vertex-centric graph computation. """ if (this.initialVertices == null) { throw new IllegalStateException("The input data set has not been set."); } // prepare some type information TypeInformation<Tuple2<VertexKey, VertexValue>> vertexTypes = initialVertices.getType(); TypeInformation<VertexKey> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0); TypeInformation<Tuple2<VertexKey, Message>> messageTypeInfo = new TupleTypeInfo<Tuple2<VertexKey,Message>>(keyType, messageType); // set up the iteration operator final String name = (this.name != null) ? this.name : "Vertex-centric iteration (" + updateFunction + " | " + messagingFunction + ")"; final int[] zeroKeyPos = new int[] {0}; final DeltaIteration<Tuple2<VertexKey, VertexValue>, Tuple2<VertexKey, VertexValue>> iteration = this.initialVertices.iterateDelta(this.initialVertices, this.maximumNumberOfIterations, zeroKeyPos); iteration.name(name); iteration.parallelism(parallelism); // register all aggregators for (Map.Entry<String, Class<? extends Aggregator<?>>> entry : this.aggregators.entrySet()) { iteration.registerAggregator(entry.getKey(), entry.getValue()); } // build the messaging function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, Message>> messages; if (edgesWithoutValue != null) { MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message> messenger = new MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message>(messagingFunction, messageTypeInfo); messages = this.edgesWithoutValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } else { MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue> messenger = new MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue>(messagingFunction, messageTypeInfo); messages = this.edgesWithValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } // configure coGroup message function with name and broadcast variables messages = messages.name("Messaging"); for (Tuple2<String, DataSet<?>> e : this.bcVarsMessaging) { messages = messages.withBroadcastSet(e.f1, e.f0); } VertexUpdateUdf<VertexKey, VertexValue, Message> updateUdf = new VertexUpdateUdf<VertexKey, VertexValue, Message>(updateFunction, vertexTypes); // build the update function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, VertexValue>> updates = messages.coGroup(iteration.getSolutionSet()).where(0).equalTo(0).with(updateUdf); // configure coGroup update function with name and broadcast variables updates = updates.name("Vertex State Updates"); for (Tuple2<String, DataSet<?>> e : this.bcVarsUpdate) { updates = updates.withBroadcastSet(e.f1, e.f0); } // let the operator know that we preserve the key field updates.withConstantSetFirst("0").withConstantSetSecond("0"); return iteration.closeWith(updates, updates); }
java
@Override public DataSet<Tuple2<VertexKey, VertexValue>> createResult() { if (this.initialVertices == null) { throw new IllegalStateException("The input data set has not been set."); } // prepare some type information TypeInformation<Tuple2<VertexKey, VertexValue>> vertexTypes = initialVertices.getType(); TypeInformation<VertexKey> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0); TypeInformation<Tuple2<VertexKey, Message>> messageTypeInfo = new TupleTypeInfo<Tuple2<VertexKey,Message>>(keyType, messageType); // set up the iteration operator final String name = (this.name != null) ? this.name : "Vertex-centric iteration (" + updateFunction + " | " + messagingFunction + ")"; final int[] zeroKeyPos = new int[] {0}; final DeltaIteration<Tuple2<VertexKey, VertexValue>, Tuple2<VertexKey, VertexValue>> iteration = this.initialVertices.iterateDelta(this.initialVertices, this.maximumNumberOfIterations, zeroKeyPos); iteration.name(name); iteration.parallelism(parallelism); // register all aggregators for (Map.Entry<String, Class<? extends Aggregator<?>>> entry : this.aggregators.entrySet()) { iteration.registerAggregator(entry.getKey(), entry.getValue()); } // build the messaging function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, Message>> messages; if (edgesWithoutValue != null) { MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message> messenger = new MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message>(messagingFunction, messageTypeInfo); messages = this.edgesWithoutValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } else { MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue> messenger = new MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue>(messagingFunction, messageTypeInfo); messages = this.edgesWithValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } // configure coGroup message function with name and broadcast variables messages = messages.name("Messaging"); for (Tuple2<String, DataSet<?>> e : this.bcVarsMessaging) { messages = messages.withBroadcastSet(e.f1, e.f0); } VertexUpdateUdf<VertexKey, VertexValue, Message> updateUdf = new VertexUpdateUdf<VertexKey, VertexValue, Message>(updateFunction, vertexTypes); // build the update function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, VertexValue>> updates = messages.coGroup(iteration.getSolutionSet()).where(0).equalTo(0).with(updateUdf); // configure coGroup update function with name and broadcast variables updates = updates.name("Vertex State Updates"); for (Tuple2<String, DataSet<?>> e : this.bcVarsUpdate) { updates = updates.withBroadcastSet(e.f1, e.f0); } // let the operator know that we preserve the key field updates.withConstantSetFirst("0").withConstantSetSecond("0"); return iteration.closeWith(updates, updates); }
[ "@", "Override", "public", "DataSet", "<", "Tuple2", "<", "VertexKey", ",", "VertexValue", ">", ">", "createResult", "(", ")", "{", "if", "(", "this", ".", "initialVertices", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The input data set has not been set.\"", ")", ";", "}", "// prepare some type information", "TypeInformation", "<", "Tuple2", "<", "VertexKey", ",", "VertexValue", ">", ">", "vertexTypes", "=", "initialVertices", ".", "getType", "(", ")", ";", "TypeInformation", "<", "VertexKey", ">", "keyType", "=", "(", "(", "TupleTypeInfo", "<", "?", ">", ")", "initialVertices", ".", "getType", "(", ")", ")", ".", "getTypeAt", "(", "0", ")", ";", "TypeInformation", "<", "Tuple2", "<", "VertexKey", ",", "Message", ">", ">", "messageTypeInfo", "=", "new", "TupleTypeInfo", "<", "Tuple2", "<", "VertexKey", ",", "Message", ">", ">", "(", "keyType", ",", "messageType", ")", ";", "// set up the iteration operator", "final", "String", "name", "=", "(", "this", ".", "name", "!=", "null", ")", "?", "this", ".", "name", ":", "\"Vertex-centric iteration (\"", "+", "updateFunction", "+", "\" | \"", "+", "messagingFunction", "+", "\")\"", ";", "final", "int", "[", "]", "zeroKeyPos", "=", "new", "int", "[", "]", "{", "0", "}", ";", "final", "DeltaIteration", "<", "Tuple2", "<", "VertexKey", ",", "VertexValue", ">", ",", "Tuple2", "<", "VertexKey", ",", "VertexValue", ">", ">", "iteration", "=", "this", ".", "initialVertices", ".", "iterateDelta", "(", "this", ".", "initialVertices", ",", "this", ".", "maximumNumberOfIterations", ",", "zeroKeyPos", ")", ";", "iteration", ".", "name", "(", "name", ")", ";", "iteration", ".", "parallelism", "(", "parallelism", ")", ";", "// register all aggregators", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Class", "<", "?", "extends", "Aggregator", "<", "?", ">", ">", ">", "entry", ":", "this", ".", "aggregators", ".", "entrySet", "(", ")", ")", "{", "iteration", ".", "registerAggregator", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "// build the messaging function (co group)", "CoGroupOperator", "<", "?", ",", "?", ",", "Tuple2", "<", "VertexKey", ",", "Message", ">", ">", "messages", ";", "if", "(", "edgesWithoutValue", "!=", "null", ")", "{", "MessagingUdfNoEdgeValues", "<", "VertexKey", ",", "VertexValue", ",", "Message", ">", "messenger", "=", "new", "MessagingUdfNoEdgeValues", "<", "VertexKey", ",", "VertexValue", ",", "Message", ">", "(", "messagingFunction", ",", "messageTypeInfo", ")", ";", "messages", "=", "this", ".", "edgesWithoutValue", ".", "coGroup", "(", "iteration", ".", "getWorkset", "(", ")", ")", ".", "where", "(", "0", ")", ".", "equalTo", "(", "0", ")", ".", "with", "(", "messenger", ")", ";", "}", "else", "{", "MessagingUdfWithEdgeValues", "<", "VertexKey", ",", "VertexValue", ",", "Message", ",", "EdgeValue", ">", "messenger", "=", "new", "MessagingUdfWithEdgeValues", "<", "VertexKey", ",", "VertexValue", ",", "Message", ",", "EdgeValue", ">", "(", "messagingFunction", ",", "messageTypeInfo", ")", ";", "messages", "=", "this", ".", "edgesWithValue", ".", "coGroup", "(", "iteration", ".", "getWorkset", "(", ")", ")", ".", "where", "(", "0", ")", ".", "equalTo", "(", "0", ")", ".", "with", "(", "messenger", ")", ";", "}", "// configure coGroup message function with name and broadcast variables", "messages", "=", "messages", ".", "name", "(", "\"Messaging\"", ")", ";", "for", "(", "Tuple2", "<", "String", ",", "DataSet", "<", "?", ">", ">", "e", ":", "this", ".", "bcVarsMessaging", ")", "{", "messages", "=", "messages", ".", "withBroadcastSet", "(", "e", ".", "f1", ",", "e", ".", "f0", ")", ";", "}", "VertexUpdateUdf", "<", "VertexKey", ",", "VertexValue", ",", "Message", ">", "updateUdf", "=", "new", "VertexUpdateUdf", "<", "VertexKey", ",", "VertexValue", ",", "Message", ">", "(", "updateFunction", ",", "vertexTypes", ")", ";", "// build the update function (co group)", "CoGroupOperator", "<", "?", ",", "?", ",", "Tuple2", "<", "VertexKey", ",", "VertexValue", ">", ">", "updates", "=", "messages", ".", "coGroup", "(", "iteration", ".", "getSolutionSet", "(", ")", ")", ".", "where", "(", "0", ")", ".", "equalTo", "(", "0", ")", ".", "with", "(", "updateUdf", ")", ";", "// configure coGroup update function with name and broadcast variables", "updates", "=", "updates", ".", "name", "(", "\"Vertex State Updates\"", ")", ";", "for", "(", "Tuple2", "<", "String", ",", "DataSet", "<", "?", ">", ">", "e", ":", "this", ".", "bcVarsUpdate", ")", "{", "updates", "=", "updates", ".", "withBroadcastSet", "(", "e", ".", "f1", ",", "e", ".", "f0", ")", ";", "}", "// let the operator know that we preserve the key field", "updates", ".", "withConstantSetFirst", "(", "\"0\"", ")", ".", "withConstantSetSecond", "(", "\"0\"", ")", ";", "return", "iteration", ".", "closeWith", "(", "updates", ",", "updates", ")", ";", "}" ]
Creates the operator that represents this vertex-centric graph computation. @return The operator that represents this vertex-centric graph computation.
[ "Creates", "the", "operator", "that", "represents", "this", "vertex", "-", "centric", "graph", "computation", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-addons/spargel/src/main/java/eu/stratosphere/spargel/java/VertexCentricIteration.java#L267-L327
jtablesaw/tablesaw
core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
DataFrameJoiner.inner
public Table inner(Table table2, String col2Name) { """ Joins the joiner to the table2, using the given column for the second table and returns the resulting table @param table2 The table to join with @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after rounding to integers. @return The resulting table """ return inner(table2, false, col2Name); }
java
public Table inner(Table table2, String col2Name) { return inner(table2, false, col2Name); }
[ "public", "Table", "inner", "(", "Table", "table2", ",", "String", "col2Name", ")", "{", "return", "inner", "(", "table2", ",", "false", ",", "col2Name", ")", ";", "}" ]
Joins the joiner to the table2, using the given column for the second table and returns the resulting table @param table2 The table to join with @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after rounding to integers. @return The resulting table
[ "Joins", "the", "joiner", "to", "the", "table2", "using", "the", "given", "column", "for", "the", "second", "table", "and", "returns", "the", "resulting", "table" ]
train
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java#L103-L105
srikalyc/Sql4D
Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/OverlordAccessor.java
OverlordAccessor.fireTask
public String fireTask(CrudStatementMeta meta, Map<String, String> reqHeaders, boolean wait) { """ Task means an indexer task(goes straight to overlord). @param meta @param reqHeaders @param wait @return """ CloseableHttpResponse resp = null; String url = format(overlordUrl, overlordHost, overlordPort); try { resp = postJson(url, meta.toString(), reqHeaders); if (resp.getStatusLine().getStatusCode() == 500) { return "Task failed with server error, " + IOUtils.toString(resp.getEntity().getContent()); } //TODO: Check for nulls in the following. String strResp = IOUtils.toString(resp.getEntity().getContent()); JSONObject respJson = new JSONObject(strResp); if (wait) { if (waitForTask(respJson.getString("task"), reqHeaders, TWO_HOURS_IN_MILLIS)) { return "Task completed successfully , task Id " + respJson; } return "Task failed/still running, task Id " + respJson; } else { String taskId = respJson.optString("task"); if (StringUtils.isBlank(taskId)) { log.error("Response has no taskId, Response body : {}", respJson); return null; } return respJson.getString("task"); } } catch (IOException | IllegalStateException | JSONException ex) { log.error("Error when firing task to overlord {}", ExceptionUtils.getStackTrace(ex)); return format("Http %s \n", ex); } finally { returnClient(resp); } }
java
public String fireTask(CrudStatementMeta meta, Map<String, String> reqHeaders, boolean wait) { CloseableHttpResponse resp = null; String url = format(overlordUrl, overlordHost, overlordPort); try { resp = postJson(url, meta.toString(), reqHeaders); if (resp.getStatusLine().getStatusCode() == 500) { return "Task failed with server error, " + IOUtils.toString(resp.getEntity().getContent()); } //TODO: Check for nulls in the following. String strResp = IOUtils.toString(resp.getEntity().getContent()); JSONObject respJson = new JSONObject(strResp); if (wait) { if (waitForTask(respJson.getString("task"), reqHeaders, TWO_HOURS_IN_MILLIS)) { return "Task completed successfully , task Id " + respJson; } return "Task failed/still running, task Id " + respJson; } else { String taskId = respJson.optString("task"); if (StringUtils.isBlank(taskId)) { log.error("Response has no taskId, Response body : {}", respJson); return null; } return respJson.getString("task"); } } catch (IOException | IllegalStateException | JSONException ex) { log.error("Error when firing task to overlord {}", ExceptionUtils.getStackTrace(ex)); return format("Http %s \n", ex); } finally { returnClient(resp); } }
[ "public", "String", "fireTask", "(", "CrudStatementMeta", "meta", ",", "Map", "<", "String", ",", "String", ">", "reqHeaders", ",", "boolean", "wait", ")", "{", "CloseableHttpResponse", "resp", "=", "null", ";", "String", "url", "=", "format", "(", "overlordUrl", ",", "overlordHost", ",", "overlordPort", ")", ";", "try", "{", "resp", "=", "postJson", "(", "url", ",", "meta", ".", "toString", "(", ")", ",", "reqHeaders", ")", ";", "if", "(", "resp", ".", "getStatusLine", "(", ")", ".", "getStatusCode", "(", ")", "==", "500", ")", "{", "return", "\"Task failed with server error, \"", "+", "IOUtils", ".", "toString", "(", "resp", ".", "getEntity", "(", ")", ".", "getContent", "(", ")", ")", ";", "}", "//TODO: Check for nulls in the following.", "String", "strResp", "=", "IOUtils", ".", "toString", "(", "resp", ".", "getEntity", "(", ")", ".", "getContent", "(", ")", ")", ";", "JSONObject", "respJson", "=", "new", "JSONObject", "(", "strResp", ")", ";", "if", "(", "wait", ")", "{", "if", "(", "waitForTask", "(", "respJson", ".", "getString", "(", "\"task\"", ")", ",", "reqHeaders", ",", "TWO_HOURS_IN_MILLIS", ")", ")", "{", "return", "\"Task completed successfully , task Id \"", "+", "respJson", ";", "}", "return", "\"Task failed/still running, task Id \"", "+", "respJson", ";", "}", "else", "{", "String", "taskId", "=", "respJson", ".", "optString", "(", "\"task\"", ")", ";", "if", "(", "StringUtils", ".", "isBlank", "(", "taskId", ")", ")", "{", "log", ".", "error", "(", "\"Response has no taskId, Response body : {}\"", ",", "respJson", ")", ";", "return", "null", ";", "}", "return", "respJson", ".", "getString", "(", "\"task\"", ")", ";", "}", "}", "catch", "(", "IOException", "|", "IllegalStateException", "|", "JSONException", "ex", ")", "{", "log", ".", "error", "(", "\"Error when firing task to overlord {}\"", ",", "ExceptionUtils", ".", "getStackTrace", "(", "ex", ")", ")", ";", "return", "format", "(", "\"Http %s \\n\"", ",", "ex", ")", ";", "}", "finally", "{", "returnClient", "(", "resp", ")", ";", "}", "}" ]
Task means an indexer task(goes straight to overlord). @param meta @param reqHeaders @param wait @return
[ "Task", "means", "an", "indexer", "task", "(", "goes", "straight", "to", "overlord", ")", "." ]
train
https://github.com/srikalyc/Sql4D/blob/2c052fe60ead5a16277c798a3440de7d4f6f24f6/Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/OverlordAccessor.java#L51-L81
icode/ameba
src/main/java/ameba/db/ebean/support/ModelResourceStructure.java
ModelResourceStructure.buildLocationUri
protected URI buildLocationUri(MODEL_ID id, boolean useTemplate) { """ <p>buildLocationUri.</p> @param id a MODEL_ID object. @param useTemplate use current template @return a {@link java.net.URI} object. """ if (id == null) { throw new NotFoundException(); } UriBuilder ub = uriInfo.getAbsolutePathBuilder(); if (useTemplate) { return ub.build(id); } else { return ub.path(idToString(id)).build(); } }
java
protected URI buildLocationUri(MODEL_ID id, boolean useTemplate) { if (id == null) { throw new NotFoundException(); } UriBuilder ub = uriInfo.getAbsolutePathBuilder(); if (useTemplate) { return ub.build(id); } else { return ub.path(idToString(id)).build(); } }
[ "protected", "URI", "buildLocationUri", "(", "MODEL_ID", "id", ",", "boolean", "useTemplate", ")", "{", "if", "(", "id", "==", "null", ")", "{", "throw", "new", "NotFoundException", "(", ")", ";", "}", "UriBuilder", "ub", "=", "uriInfo", ".", "getAbsolutePathBuilder", "(", ")", ";", "if", "(", "useTemplate", ")", "{", "return", "ub", ".", "build", "(", "id", ")", ";", "}", "else", "{", "return", "ub", ".", "path", "(", "idToString", "(", "id", ")", ")", ".", "build", "(", ")", ";", "}", "}" ]
<p>buildLocationUri.</p> @param id a MODEL_ID object. @param useTemplate use current template @return a {@link java.net.URI} object.
[ "<p", ">", "buildLocationUri", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/db/ebean/support/ModelResourceStructure.java#L1192-L1202
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddressString.java
IPAddressString.adjustPrefixBySegment
public IPAddressString adjustPrefixBySegment(boolean nextSegment) { """ Increases or decreases prefix length to the next segment boundary of the given address version's standard segment boundaries. <p> This acts on address strings with an associated prefix length, whether or not there is also an associated address value, see {@link IPAddressString#isPrefixOnly()}. If there is no associated address value then the segment boundaries are considered to be at each byte, much like IPv4. <p> If the address string has prefix length 0 and represents all addresses of the same version, and the prefix length is being decreased, then the address representing all addresses of any version is returned. <p> Follows the same rules as {@link #adjustPrefixLength(int)} when there is an associated address value:<br> When prefix length is increased, the bits moved within the prefix become zero. When a prefix length is decreased, the bits moved outside the prefix become zero. Also see {@link IPAddress#adjustPrefixBySegment(boolean)} @param nextSegment whether to move prefix to previous or following segment boundary @return """ if(isPrefixOnly()) { // Use IPv4 segment boundaries int bitsPerSegment = IPv4Address.BITS_PER_SEGMENT; int existingPrefixLength = getNetworkPrefixLength(); int newBits; if(nextSegment) { int adjustment = existingPrefixLength % bitsPerSegment; newBits = Math.min(IPv6Address.BIT_COUNT, existingPrefixLength + bitsPerSegment - adjustment); } else { int adjustment = ((existingPrefixLength - 1) % bitsPerSegment) + 1; newBits = Math.max(0, existingPrefixLength - adjustment); } return new IPAddressString(IPAddressNetwork.getPrefixString(newBits), validationOptions); } IPAddress address = getAddress(); if(address == null) { return null; } Integer prefix = address.getNetworkPrefixLength(); if(!nextSegment && prefix != null && prefix == 0 && address.isMultiple() && address.isPrefixBlock()) { return new IPAddressString(IPAddress.SEGMENT_WILDCARD_STR, validationOptions); } return address.adjustPrefixBySegment(nextSegment).toAddressString(); }
java
public IPAddressString adjustPrefixBySegment(boolean nextSegment) { if(isPrefixOnly()) { // Use IPv4 segment boundaries int bitsPerSegment = IPv4Address.BITS_PER_SEGMENT; int existingPrefixLength = getNetworkPrefixLength(); int newBits; if(nextSegment) { int adjustment = existingPrefixLength % bitsPerSegment; newBits = Math.min(IPv6Address.BIT_COUNT, existingPrefixLength + bitsPerSegment - adjustment); } else { int adjustment = ((existingPrefixLength - 1) % bitsPerSegment) + 1; newBits = Math.max(0, existingPrefixLength - adjustment); } return new IPAddressString(IPAddressNetwork.getPrefixString(newBits), validationOptions); } IPAddress address = getAddress(); if(address == null) { return null; } Integer prefix = address.getNetworkPrefixLength(); if(!nextSegment && prefix != null && prefix == 0 && address.isMultiple() && address.isPrefixBlock()) { return new IPAddressString(IPAddress.SEGMENT_WILDCARD_STR, validationOptions); } return address.adjustPrefixBySegment(nextSegment).toAddressString(); }
[ "public", "IPAddressString", "adjustPrefixBySegment", "(", "boolean", "nextSegment", ")", "{", "if", "(", "isPrefixOnly", "(", ")", ")", "{", "// Use IPv4 segment boundaries", "int", "bitsPerSegment", "=", "IPv4Address", ".", "BITS_PER_SEGMENT", ";", "int", "existingPrefixLength", "=", "getNetworkPrefixLength", "(", ")", ";", "int", "newBits", ";", "if", "(", "nextSegment", ")", "{", "int", "adjustment", "=", "existingPrefixLength", "%", "bitsPerSegment", ";", "newBits", "=", "Math", ".", "min", "(", "IPv6Address", ".", "BIT_COUNT", ",", "existingPrefixLength", "+", "bitsPerSegment", "-", "adjustment", ")", ";", "}", "else", "{", "int", "adjustment", "=", "(", "(", "existingPrefixLength", "-", "1", ")", "%", "bitsPerSegment", ")", "+", "1", ";", "newBits", "=", "Math", ".", "max", "(", "0", ",", "existingPrefixLength", "-", "adjustment", ")", ";", "}", "return", "new", "IPAddressString", "(", "IPAddressNetwork", ".", "getPrefixString", "(", "newBits", ")", ",", "validationOptions", ")", ";", "}", "IPAddress", "address", "=", "getAddress", "(", ")", ";", "if", "(", "address", "==", "null", ")", "{", "return", "null", ";", "}", "Integer", "prefix", "=", "address", ".", "getNetworkPrefixLength", "(", ")", ";", "if", "(", "!", "nextSegment", "&&", "prefix", "!=", "null", "&&", "prefix", "==", "0", "&&", "address", ".", "isMultiple", "(", ")", "&&", "address", ".", "isPrefixBlock", "(", ")", ")", "{", "return", "new", "IPAddressString", "(", "IPAddress", ".", "SEGMENT_WILDCARD_STR", ",", "validationOptions", ")", ";", "}", "return", "address", ".", "adjustPrefixBySegment", "(", "nextSegment", ")", ".", "toAddressString", "(", ")", ";", "}" ]
Increases or decreases prefix length to the next segment boundary of the given address version's standard segment boundaries. <p> This acts on address strings with an associated prefix length, whether or not there is also an associated address value, see {@link IPAddressString#isPrefixOnly()}. If there is no associated address value then the segment boundaries are considered to be at each byte, much like IPv4. <p> If the address string has prefix length 0 and represents all addresses of the same version, and the prefix length is being decreased, then the address representing all addresses of any version is returned. <p> Follows the same rules as {@link #adjustPrefixLength(int)} when there is an associated address value:<br> When prefix length is increased, the bits moved within the prefix become zero. When a prefix length is decreased, the bits moved outside the prefix become zero. Also see {@link IPAddress#adjustPrefixBySegment(boolean)} @param nextSegment whether to move prefix to previous or following segment boundary @return
[ "Increases", "or", "decreases", "prefix", "length", "to", "the", "next", "segment", "boundary", "of", "the", "given", "address", "version", "s", "standard", "segment", "boundaries", ".", "<p", ">", "This", "acts", "on", "address", "strings", "with", "an", "associated", "prefix", "length", "whether", "or", "not", "there", "is", "also", "an", "associated", "address", "value", "see", "{", "@link", "IPAddressString#isPrefixOnly", "()", "}", ".", "If", "there", "is", "no", "associated", "address", "value", "then", "the", "segment", "boundaries", "are", "considered", "to", "be", "at", "each", "byte", "much", "like", "IPv4", ".", "<p", ">", "If", "the", "address", "string", "has", "prefix", "length", "0", "and", "represents", "all", "addresses", "of", "the", "same", "version", "and", "the", "prefix", "length", "is", "being", "decreased", "then", "the", "address", "representing", "all", "addresses", "of", "any", "version", "is", "returned", ".", "<p", ">", "Follows", "the", "same", "rules", "as", "{", "@link", "#adjustPrefixLength", "(", "int", ")", "}", "when", "there", "is", "an", "associated", "address", "value", ":", "<br", ">", "When", "prefix", "length", "is", "increased", "the", "bits", "moved", "within", "the", "prefix", "become", "zero", ".", "When", "a", "prefix", "length", "is", "decreased", "the", "bits", "moved", "outside", "the", "prefix", "become", "zero", "." ]
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddressString.java#L799-L823
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java
BaseDfuImpl.writeOpCode
void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value, final boolean reset) throws DeviceDisconnectedException, DfuException, UploadAbortedException { """ Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or the device gets disconnected. If connection state will change, or an error will occur, an exception will be thrown. @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT @param value the value to write to the characteristic @param reset whether the command trigger restarting the device @throws DeviceDisconnectedException Thrown when the device will disconnect in the middle of the transmission. @throws DfuException Thrown if DFU error occur. @throws UploadAbortedException Thrown if DFU operation was aborted by user. """ if (mAborted) throw new UploadAbortedException(); mReceivedData = null; mError = 0; mRequestCompleted = false; /* * Sending a command that will make the DFU target to reboot may cause an error 133 * (0x85 - Gatt Error). If so, with this flag set, the error will not be shown to the user * as the peripheral is disconnected anyway. * See: mGattCallback#onCharacteristicWrite(...) method */ mResetRequestSent = reset; characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); characteristic.setValue(value); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Writing to characteristic " + characteristic.getUuid()); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); mGatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((!mRequestCompleted && mConnected && mError == 0) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (!mResetRequestSent && !mConnected) throw new DeviceDisconnectedException("Unable to write Op Code " + value[0] + ": device disconnected"); if (!mResetRequestSent && mError != 0) throw new DfuException("Unable to write Op Code " + value[0], mError); }
java
void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value, final boolean reset) throws DeviceDisconnectedException, DfuException, UploadAbortedException { if (mAborted) throw new UploadAbortedException(); mReceivedData = null; mError = 0; mRequestCompleted = false; /* * Sending a command that will make the DFU target to reboot may cause an error 133 * (0x85 - Gatt Error). If so, with this flag set, the error will not be shown to the user * as the peripheral is disconnected anyway. * See: mGattCallback#onCharacteristicWrite(...) method */ mResetRequestSent = reset; characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); characteristic.setValue(value); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_VERBOSE, "Writing to characteristic " + characteristic.getUuid()); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); mGatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((!mRequestCompleted && mConnected && mError == 0) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (!mResetRequestSent && !mConnected) throw new DeviceDisconnectedException("Unable to write Op Code " + value[0] + ": device disconnected"); if (!mResetRequestSent && mError != 0) throw new DfuException("Unable to write Op Code " + value[0], mError); }
[ "void", "writeOpCode", "(", "@", "NonNull", "final", "BluetoothGattCharacteristic", "characteristic", ",", "@", "NonNull", "final", "byte", "[", "]", "value", ",", "final", "boolean", "reset", ")", "throws", "DeviceDisconnectedException", ",", "DfuException", ",", "UploadAbortedException", "{", "if", "(", "mAborted", ")", "throw", "new", "UploadAbortedException", "(", ")", ";", "mReceivedData", "=", "null", ";", "mError", "=", "0", ";", "mRequestCompleted", "=", "false", ";", "/*\n\t\t * Sending a command that will make the DFU target to reboot may cause an error 133\n\t\t * (0x85 - Gatt Error). If so, with this flag set, the error will not be shown to the user\n\t\t * as the peripheral is disconnected anyway.\n\t\t * See: mGattCallback#onCharacteristicWrite(...) method\n\t\t */", "mResetRequestSent", "=", "reset", ";", "characteristic", ".", "setWriteType", "(", "BluetoothGattCharacteristic", ".", "WRITE_TYPE_DEFAULT", ")", ";", "characteristic", ".", "setValue", "(", "value", ")", ";", "mService", ".", "sendLogBroadcast", "(", "DfuBaseService", ".", "LOG_LEVEL_VERBOSE", ",", "\"Writing to characteristic \"", "+", "characteristic", ".", "getUuid", "(", ")", ")", ";", "mService", ".", "sendLogBroadcast", "(", "DfuBaseService", ".", "LOG_LEVEL_DEBUG", ",", "\"gatt.writeCharacteristic(\"", "+", "characteristic", ".", "getUuid", "(", ")", "+", "\")\"", ")", ";", "mGatt", ".", "writeCharacteristic", "(", "characteristic", ")", ";", "// We have to wait for confirmation", "try", "{", "synchronized", "(", "mLock", ")", "{", "while", "(", "(", "!", "mRequestCompleted", "&&", "mConnected", "&&", "mError", "==", "0", ")", "||", "mPaused", ")", "mLock", ".", "wait", "(", ")", ";", "}", "}", "catch", "(", "final", "InterruptedException", "e", ")", "{", "loge", "(", "\"Sleeping interrupted\"", ",", "e", ")", ";", "}", "if", "(", "!", "mResetRequestSent", "&&", "!", "mConnected", ")", "throw", "new", "DeviceDisconnectedException", "(", "\"Unable to write Op Code \"", "+", "value", "[", "0", "]", "+", "\": device disconnected\"", ")", ";", "if", "(", "!", "mResetRequestSent", "&&", "mError", "!=", "0", ")", "throw", "new", "DfuException", "(", "\"Unable to write Op Code \"", "+", "value", "[", "0", "]", ",", "mError", ")", ";", "}" ]
Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or the device gets disconnected. If connection state will change, or an error will occur, an exception will be thrown. @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT @param value the value to write to the characteristic @param reset whether the command trigger restarting the device @throws DeviceDisconnectedException Thrown when the device will disconnect in the middle of the transmission. @throws DfuException Thrown if DFU error occur. @throws UploadAbortedException Thrown if DFU operation was aborted by user.
[ "Writes", "the", "operation", "code", "to", "the", "characteristic", ".", "This", "method", "is", "SYNCHRONOUS", "and", "wait", "until", "the", "{", "@link", "android", ".", "bluetooth", ".", "BluetoothGattCallback#onCharacteristicWrite", "(", "android", ".", "bluetooth", ".", "BluetoothGatt", "android", ".", "bluetooth", ".", "BluetoothGattCharacteristic", "int", ")", "}", "will", "be", "called", "or", "the", "device", "gets", "disconnected", ".", "If", "connection", "state", "will", "change", "or", "an", "error", "will", "occur", "an", "exception", "will", "be", "thrown", "." ]
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseDfuImpl.java#L535-L569
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxJavaUtils.java
TileBoundingBoxJavaUtils.getFloatRectangle
public static ImageRectangleF getFloatRectangle(long width, long height, BoundingBox boundingBox, BoundingBox boundingBoxSection) { """ Get a rectangle with floating point boundaries using the tile width, height, bounding box, and the bounding box section within the outer box to build the rectangle from @param width width @param height height @param boundingBox full bounding box @param boundingBoxSection rectangle bounding box section @return floating point rectangle @since 1.2.0 """ float left = TileBoundingBoxUtils.getXPixel(width, boundingBox, boundingBoxSection.getMinLongitude()); float right = TileBoundingBoxUtils.getXPixel(width, boundingBox, boundingBoxSection.getMaxLongitude()); float top = TileBoundingBoxUtils.getYPixel(height, boundingBox, boundingBoxSection.getMaxLatitude()); float bottom = TileBoundingBoxUtils.getYPixel(height, boundingBox, boundingBoxSection.getMinLatitude()); ImageRectangleF rect = new ImageRectangleF(left, top, right, bottom); return rect; }
java
public static ImageRectangleF getFloatRectangle(long width, long height, BoundingBox boundingBox, BoundingBox boundingBoxSection) { float left = TileBoundingBoxUtils.getXPixel(width, boundingBox, boundingBoxSection.getMinLongitude()); float right = TileBoundingBoxUtils.getXPixel(width, boundingBox, boundingBoxSection.getMaxLongitude()); float top = TileBoundingBoxUtils.getYPixel(height, boundingBox, boundingBoxSection.getMaxLatitude()); float bottom = TileBoundingBoxUtils.getYPixel(height, boundingBox, boundingBoxSection.getMinLatitude()); ImageRectangleF rect = new ImageRectangleF(left, top, right, bottom); return rect; }
[ "public", "static", "ImageRectangleF", "getFloatRectangle", "(", "long", "width", ",", "long", "height", ",", "BoundingBox", "boundingBox", ",", "BoundingBox", "boundingBoxSection", ")", "{", "float", "left", "=", "TileBoundingBoxUtils", ".", "getXPixel", "(", "width", ",", "boundingBox", ",", "boundingBoxSection", ".", "getMinLongitude", "(", ")", ")", ";", "float", "right", "=", "TileBoundingBoxUtils", ".", "getXPixel", "(", "width", ",", "boundingBox", ",", "boundingBoxSection", ".", "getMaxLongitude", "(", ")", ")", ";", "float", "top", "=", "TileBoundingBoxUtils", ".", "getYPixel", "(", "height", ",", "boundingBox", ",", "boundingBoxSection", ".", "getMaxLatitude", "(", ")", ")", ";", "float", "bottom", "=", "TileBoundingBoxUtils", ".", "getYPixel", "(", "height", ",", "boundingBox", ",", "boundingBoxSection", ".", "getMinLatitude", "(", ")", ")", ";", "ImageRectangleF", "rect", "=", "new", "ImageRectangleF", "(", "left", ",", "top", ",", "right", ",", "bottom", ")", ";", "return", "rect", ";", "}" ]
Get a rectangle with floating point boundaries using the tile width, height, bounding box, and the bounding box section within the outer box to build the rectangle from @param width width @param height height @param boundingBox full bounding box @param boundingBoxSection rectangle bounding box section @return floating point rectangle @since 1.2.0
[ "Get", "a", "rectangle", "with", "floating", "point", "boundaries", "using", "the", "tile", "width", "height", "bounding", "box", "and", "the", "bounding", "box", "section", "within", "the", "outer", "box", "to", "build", "the", "rectangle", "from" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxJavaUtils.java#L81-L96
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/LabelsApi.java
LabelsApi.updateLabelColor
public Label updateLabelColor(Object projectIdOrPath, String name, String color, String description, Integer priority) throws GitLabApiException { """ Update the specified label @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param name the name for the label @param color the color for the label @param description the description for the label @param priority the priority for the label @return the modified Label instance @throws GitLabApiException if any exception occurs """ return (updateLabel(projectIdOrPath, name, null, color, description, priority)); }
java
public Label updateLabelColor(Object projectIdOrPath, String name, String color, String description, Integer priority) throws GitLabApiException { return (updateLabel(projectIdOrPath, name, null, color, description, priority)); }
[ "public", "Label", "updateLabelColor", "(", "Object", "projectIdOrPath", ",", "String", "name", ",", "String", "color", ",", "String", "description", ",", "Integer", "priority", ")", "throws", "GitLabApiException", "{", "return", "(", "updateLabel", "(", "projectIdOrPath", ",", "name", ",", "null", ",", "color", ",", "description", ",", "priority", ")", ")", ";", "}" ]
Update the specified label @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param name the name for the label @param color the color for the label @param description the description for the label @param priority the priority for the label @return the modified Label instance @throws GitLabApiException if any exception occurs
[ "Update", "the", "specified", "label" ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/LabelsApi.java#L158-L160
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.retainBottom
public static <E> void retainBottom(Counter<E> c, int num) { """ Removes all entries from c except for the bottom <code>num</code> """ int numToPurge = c.size() - num; if (numToPurge <= 0) { return; } List<E> l = Counters.toSortedList(c); for (int i = 0; i < numToPurge; i++) { c.remove(l.get(i)); } }
java
public static <E> void retainBottom(Counter<E> c, int num) { int numToPurge = c.size() - num; if (numToPurge <= 0) { return; } List<E> l = Counters.toSortedList(c); for (int i = 0; i < numToPurge; i++) { c.remove(l.get(i)); } }
[ "public", "static", "<", "E", ">", "void", "retainBottom", "(", "Counter", "<", "E", ">", "c", ",", "int", "num", ")", "{", "int", "numToPurge", "=", "c", ".", "size", "(", ")", "-", "num", ";", "if", "(", "numToPurge", "<=", "0", ")", "{", "return", ";", "}", "List", "<", "E", ">", "l", "=", "Counters", ".", "toSortedList", "(", "c", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numToPurge", ";", "i", "++", ")", "{", "c", ".", "remove", "(", "l", ".", "get", "(", "i", ")", ")", ";", "}", "}" ]
Removes all entries from c except for the bottom <code>num</code>
[ "Removes", "all", "entries", "from", "c", "except", "for", "the", "bottom", "<code", ">", "num<", "/", "code", ">" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L544-L554
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/generic/GenericSignatureParser.java
GenericSignatureParser.compareSignatures
public static boolean compareSignatures(String plainSignature, String genericSignature) { """ Compare a plain method signature to the a generic method Signature and return true if they match """ GenericSignatureParser plainParser = new GenericSignatureParser(plainSignature); GenericSignatureParser genericParser = new GenericSignatureParser(genericSignature); return plainParser.getNumParameters() == genericParser.getNumParameters(); }
java
public static boolean compareSignatures(String plainSignature, String genericSignature) { GenericSignatureParser plainParser = new GenericSignatureParser(plainSignature); GenericSignatureParser genericParser = new GenericSignatureParser(genericSignature); return plainParser.getNumParameters() == genericParser.getNumParameters(); }
[ "public", "static", "boolean", "compareSignatures", "(", "String", "plainSignature", ",", "String", "genericSignature", ")", "{", "GenericSignatureParser", "plainParser", "=", "new", "GenericSignatureParser", "(", "plainSignature", ")", ";", "GenericSignatureParser", "genericParser", "=", "new", "GenericSignatureParser", "(", "genericSignature", ")", ";", "return", "plainParser", ".", "getNumParameters", "(", ")", "==", "genericParser", ".", "getNumParameters", "(", ")", ";", "}" ]
Compare a plain method signature to the a generic method Signature and return true if they match
[ "Compare", "a", "plain", "method", "signature", "to", "the", "a", "generic", "method", "Signature", "and", "return", "true", "if", "they", "match" ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/generic/GenericSignatureParser.java#L245-L250
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/util/annotation/AnnotationUtils.java
AnnotationUtils.findAnnotation
public static <A extends Annotation> A findAnnotation(final Annotation source, final Class<A> targetAnnotationClass) { """ Deep search of specified source considering "annotation as meta annotation" case (source annotated with specified source). @param source {@link Annotation} - source @param targetAnnotationClass represents class of the required annotaiton @param <A> type param @return {@link A} in case if found, {@code null} otherwise """ Objects.requireNonNull(source, "incoming 'source' is not valid"); Objects.requireNonNull(targetAnnotationClass, "incoming 'targetAnnotationClass' is not valid"); return findAnnotation(source, targetAnnotationClass, new HashSet<Class<? extends Annotation>>()); }
java
public static <A extends Annotation> A findAnnotation(final Annotation source, final Class<A> targetAnnotationClass) { Objects.requireNonNull(source, "incoming 'source' is not valid"); Objects.requireNonNull(targetAnnotationClass, "incoming 'targetAnnotationClass' is not valid"); return findAnnotation(source, targetAnnotationClass, new HashSet<Class<? extends Annotation>>()); }
[ "public", "static", "<", "A", "extends", "Annotation", ">", "A", "findAnnotation", "(", "final", "Annotation", "source", ",", "final", "Class", "<", "A", ">", "targetAnnotationClass", ")", "{", "Objects", ".", "requireNonNull", "(", "source", ",", "\"incoming 'source' is not valid\"", ")", ";", "Objects", ".", "requireNonNull", "(", "targetAnnotationClass", ",", "\"incoming 'targetAnnotationClass' is not valid\"", ")", ";", "return", "findAnnotation", "(", "source", ",", "targetAnnotationClass", ",", "new", "HashSet", "<", "Class", "<", "?", "extends", "Annotation", ">", ">", "(", ")", ")", ";", "}" ]
Deep search of specified source considering "annotation as meta annotation" case (source annotated with specified source). @param source {@link Annotation} - source @param targetAnnotationClass represents class of the required annotaiton @param <A> type param @return {@link A} in case if found, {@code null} otherwise
[ "Deep", "search", "of", "specified", "source", "considering", "annotation", "as", "meta", "annotation", "case", "(", "source", "annotated", "with", "specified", "source", ")", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/util/annotation/AnnotationUtils.java#L76-L80
99soft/lifegycle
src/main/java/org/nnsoft/guice/lifegycle/AbstractMethodTypeListener.java
AbstractMethodTypeListener.hear
private <I> void hear( Class<? super I> type, TypeEncounter<I> encounter ) { """ Allows traverse the input type hierarchy. @param type encountered by Guice. @param encounter the injection context. """ if ( type == null || type.getPackage().getName().startsWith( JAVA_PACKAGE ) ) { return; } for ( Method method : type.getDeclaredMethods() ) { if ( method.isAnnotationPresent( annotationType ) ) { if ( method.getParameterTypes().length != 0 ) { encounter.addError( "Annotated methods with @%s must not accept any argument, found %s", annotationType.getName(), method ); } hear( method, encounter ); } } hear( type.getSuperclass(), encounter ); }
java
private <I> void hear( Class<? super I> type, TypeEncounter<I> encounter ) { if ( type == null || type.getPackage().getName().startsWith( JAVA_PACKAGE ) ) { return; } for ( Method method : type.getDeclaredMethods() ) { if ( method.isAnnotationPresent( annotationType ) ) { if ( method.getParameterTypes().length != 0 ) { encounter.addError( "Annotated methods with @%s must not accept any argument, found %s", annotationType.getName(), method ); } hear( method, encounter ); } } hear( type.getSuperclass(), encounter ); }
[ "private", "<", "I", ">", "void", "hear", "(", "Class", "<", "?", "super", "I", ">", "type", ",", "TypeEncounter", "<", "I", ">", "encounter", ")", "{", "if", "(", "type", "==", "null", "||", "type", ".", "getPackage", "(", ")", ".", "getName", "(", ")", ".", "startsWith", "(", "JAVA_PACKAGE", ")", ")", "{", "return", ";", "}", "for", "(", "Method", "method", ":", "type", ".", "getDeclaredMethods", "(", ")", ")", "{", "if", "(", "method", ".", "isAnnotationPresent", "(", "annotationType", ")", ")", "{", "if", "(", "method", ".", "getParameterTypes", "(", ")", ".", "length", "!=", "0", ")", "{", "encounter", ".", "addError", "(", "\"Annotated methods with @%s must not accept any argument, found %s\"", ",", "annotationType", ".", "getName", "(", ")", ",", "method", ")", ";", "}", "hear", "(", "method", ",", "encounter", ")", ";", "}", "}", "hear", "(", "type", ".", "getSuperclass", "(", ")", ",", "encounter", ")", ";", "}" ]
Allows traverse the input type hierarchy. @param type encountered by Guice. @param encounter the injection context.
[ "Allows", "traverse", "the", "input", "type", "hierarchy", "." ]
train
https://github.com/99soft/lifegycle/blob/0adde20bcf32e90fe995bb493630b77fa6ce6361/src/main/java/org/nnsoft/guice/lifegycle/AbstractMethodTypeListener.java#L67-L89
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_download_policy.java
ns_conf_download_policy.update
public static ns_conf_download_policy update(nitro_service client, ns_conf_download_policy resource) throws Exception { """ <pre> Use this operation to set the polling frequency of the Netscaler configuration file. </pre> """ resource.validate("modify"); return ((ns_conf_download_policy[]) resource.update_resource(client))[0]; }
java
public static ns_conf_download_policy update(nitro_service client, ns_conf_download_policy resource) throws Exception { resource.validate("modify"); return ((ns_conf_download_policy[]) resource.update_resource(client))[0]; }
[ "public", "static", "ns_conf_download_policy", "update", "(", "nitro_service", "client", ",", "ns_conf_download_policy", "resource", ")", "throws", "Exception", "{", "resource", ".", "validate", "(", "\"modify\"", ")", ";", "return", "(", "(", "ns_conf_download_policy", "[", "]", ")", "resource", ".", "update_resource", "(", "client", ")", ")", "[", "0", "]", ";", "}" ]
<pre> Use this operation to set the polling frequency of the Netscaler configuration file. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "set", "the", "polling", "frequency", "of", "the", "Netscaler", "configuration", "file", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_conf_download_policy.java#L126-L130
qiniu/java-sdk
src/main/java/com/qiniu/streaming/StreamingManager.java
StreamingManager.history
public ActivityRecords history(String streamKey, long start, long end) throws QiniuException { """ 获取流推流的片段列表,一个流开始和断流算一个片段 @param streamKey 流名称 @param start 开始时间戳,单位秒 @param end 结束时间戳,单位秒 """ if (start <= 0 || end < 0 || (start >= end && end != 0)) { throw new QiniuException(new IllegalArgumentException("bad argument" + start + "," + end)); } String path = encodeKey(streamKey) + "/historyactivity?start=" + start; if (end != 0) { path += "&end=" + end; } return get(path, ActivityRecords.class); }
java
public ActivityRecords history(String streamKey, long start, long end) throws QiniuException { if (start <= 0 || end < 0 || (start >= end && end != 0)) { throw new QiniuException(new IllegalArgumentException("bad argument" + start + "," + end)); } String path = encodeKey(streamKey) + "/historyactivity?start=" + start; if (end != 0) { path += "&end=" + end; } return get(path, ActivityRecords.class); }
[ "public", "ActivityRecords", "history", "(", "String", "streamKey", ",", "long", "start", ",", "long", "end", ")", "throws", "QiniuException", "{", "if", "(", "start", "<=", "0", "||", "end", "<", "0", "||", "(", "start", ">=", "end", "&&", "end", "!=", "0", ")", ")", "{", "throw", "new", "QiniuException", "(", "new", "IllegalArgumentException", "(", "\"bad argument\"", "+", "start", "+", "\",\"", "+", "end", ")", ")", ";", "}", "String", "path", "=", "encodeKey", "(", "streamKey", ")", "+", "\"/historyactivity?start=\"", "+", "start", ";", "if", "(", "end", "!=", "0", ")", "{", "path", "+=", "\"&end=\"", "+", "end", ";", "}", "return", "get", "(", "path", ",", "ActivityRecords", ".", "class", ")", ";", "}" ]
获取流推流的片段列表,一个流开始和断流算一个片段 @param streamKey 流名称 @param start 开始时间戳,单位秒 @param end 结束时间戳,单位秒
[ "获取流推流的片段列表,一个流开始和断流算一个片段" ]
train
https://github.com/qiniu/java-sdk/blob/6c05f3fb718403a496c725b048e9241f80171499/src/main/java/com/qiniu/streaming/StreamingManager.java#L185-L194
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/Trees.java
Trees.instance
public static Trees instance(CompilationTask task) { """ Returns a Trees object for a given CompilationTask. @param task the compilation task for which to get the Trees object @throws IllegalArgumentException if the task does not support the Trees API. @return the Trees object """ String taskClassName = task.getClass().getName(); if (!taskClassName.equals("com.sun.tools.javac.api.JavacTaskImpl") && !taskClassName.equals("com.sun.tools.javac.api.BasicJavacTask")) throw new IllegalArgumentException(); return getJavacTrees(CompilationTask.class, task); }
java
public static Trees instance(CompilationTask task) { String taskClassName = task.getClass().getName(); if (!taskClassName.equals("com.sun.tools.javac.api.JavacTaskImpl") && !taskClassName.equals("com.sun.tools.javac.api.BasicJavacTask")) throw new IllegalArgumentException(); return getJavacTrees(CompilationTask.class, task); }
[ "public", "static", "Trees", "instance", "(", "CompilationTask", "task", ")", "{", "String", "taskClassName", "=", "task", ".", "getClass", "(", ")", ".", "getName", "(", ")", ";", "if", "(", "!", "taskClassName", ".", "equals", "(", "\"com.sun.tools.javac.api.JavacTaskImpl\"", ")", "&&", "!", "taskClassName", ".", "equals", "(", "\"com.sun.tools.javac.api.BasicJavacTask\"", ")", ")", "throw", "new", "IllegalArgumentException", "(", ")", ";", "return", "getJavacTrees", "(", "CompilationTask", ".", "class", ",", "task", ")", ";", "}" ]
Returns a Trees object for a given CompilationTask. @param task the compilation task for which to get the Trees object @throws IllegalArgumentException if the task does not support the Trees API. @return the Trees object
[ "Returns", "a", "Trees", "object", "for", "a", "given", "CompilationTask", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/Trees.java#L61-L67
KyoriPowered/lunar
src/main/java/net/kyori/lunar/Modules.java
Modules.createLayer
public static @NonNull ModuleLayer createLayer(final @NonNull ModuleLayer parent, final @NonNull Set<Path> paths) { """ Creates a new module layer from a parent layer and a set of paths. @param parent the parent layer @param paths the paths @return a new layer """ final ModuleFinder finder = ModuleFinder.of(paths.toArray(new Path[paths.size()])); final Set<String> modules = finder.findAll().stream().map(reference -> reference.descriptor().name()).collect(Collectors.toSet()); final Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), modules); final ClassLoader loader = ClassLoader.getSystemClassLoader(); return parent.defineModulesWithOneLoader(configuration, loader); }
java
public static @NonNull ModuleLayer createLayer(final @NonNull ModuleLayer parent, final @NonNull Set<Path> paths) { final ModuleFinder finder = ModuleFinder.of(paths.toArray(new Path[paths.size()])); final Set<String> modules = finder.findAll().stream().map(reference -> reference.descriptor().name()).collect(Collectors.toSet()); final Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), modules); final ClassLoader loader = ClassLoader.getSystemClassLoader(); return parent.defineModulesWithOneLoader(configuration, loader); }
[ "public", "static", "@", "NonNull", "ModuleLayer", "createLayer", "(", "final", "@", "NonNull", "ModuleLayer", "parent", ",", "final", "@", "NonNull", "Set", "<", "Path", ">", "paths", ")", "{", "final", "ModuleFinder", "finder", "=", "ModuleFinder", ".", "of", "(", "paths", ".", "toArray", "(", "new", "Path", "[", "paths", ".", "size", "(", ")", "]", ")", ")", ";", "final", "Set", "<", "String", ">", "modules", "=", "finder", ".", "findAll", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "reference", "->", "reference", ".", "descriptor", "(", ")", ".", "name", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "final", "Configuration", "configuration", "=", "parent", ".", "configuration", "(", ")", ".", "resolve", "(", "finder", ",", "ModuleFinder", ".", "of", "(", ")", ",", "modules", ")", ";", "final", "ClassLoader", "loader", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ";", "return", "parent", ".", "defineModulesWithOneLoader", "(", "configuration", ",", "loader", ")", ";", "}" ]
Creates a new module layer from a parent layer and a set of paths. @param parent the parent layer @param paths the paths @return a new layer
[ "Creates", "a", "new", "module", "layer", "from", "a", "parent", "layer", "and", "a", "set", "of", "paths", "." ]
train
https://github.com/KyoriPowered/lunar/blob/6856747d9034a2fe0c8d0a8a0150986797732b5c/src/main/java/net/kyori/lunar/Modules.java#L58-L64
HubSpot/Singularity
SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java
SingularityClient.getTaskLogs
public Collection<SingularityS3Log> getTaskLogs(String taskId) { """ Retrieve the list of logs stored in S3 for a specific task @param taskId The task ID to search for @return A collection of {@link SingularityS3Log} """ final Function<String, String> requestUri = (host) -> String.format(S3_LOG_GET_TASK_LOGS, getApiBase(host), taskId); final String type = String.format("S3 logs for task %s", taskId); return getCollection(requestUri, type, S3_LOG_COLLECTION); }
java
public Collection<SingularityS3Log> getTaskLogs(String taskId) { final Function<String, String> requestUri = (host) -> String.format(S3_LOG_GET_TASK_LOGS, getApiBase(host), taskId); final String type = String.format("S3 logs for task %s", taskId); return getCollection(requestUri, type, S3_LOG_COLLECTION); }
[ "public", "Collection", "<", "SingularityS3Log", ">", "getTaskLogs", "(", "String", "taskId", ")", "{", "final", "Function", "<", "String", ",", "String", ">", "requestUri", "=", "(", "host", ")", "-", ">", "String", ".", "format", "(", "S3_LOG_GET_TASK_LOGS", ",", "getApiBase", "(", "host", ")", ",", "taskId", ")", ";", "final", "String", "type", "=", "String", ".", "format", "(", "\"S3 logs for task %s\"", ",", "taskId", ")", ";", "return", "getCollection", "(", "requestUri", ",", "type", ",", "S3_LOG_COLLECTION", ")", ";", "}" ]
Retrieve the list of logs stored in S3 for a specific task @param taskId The task ID to search for @return A collection of {@link SingularityS3Log}
[ "Retrieve", "the", "list", "of", "logs", "stored", "in", "S3", "for", "a", "specific", "task" ]
train
https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java#L1338-L1344
lessthanoptimal/ejml
main/ejml-simple/src/org/ejml/equation/Operation.java
Operation.solve
public static Info solve( final Variable A , final Variable B , ManagerTempVariables manager) { """ If input is two vectors then it returns the dot product as a double. """ Info ret = new Info(); final VariableMatrix output = manager.createMatrix(); ret.output = output; if( A instanceof VariableMatrix && B instanceof VariableMatrix ) { ret.op = new Operation("solve-mm") { LinearSolverDense<DMatrixRMaj> solver; @Override public void process() { DMatrixRMaj a = ((VariableMatrix)A).matrix; DMatrixRMaj b = ((VariableMatrix)B).matrix; if( solver == null ) { solver = LinearSolverFactory_DDRM.leastSquares(a.numRows,a.numCols); } if( !solver.setA(a)) throw new RuntimeException("Solver failed!"); output.matrix.reshape(a.numCols,b.numCols); solver.solve(b, output.matrix); } }; } else { throw new RuntimeException("Expected two matrices got "+A+" "+B); } return ret; }
java
public static Info solve( final Variable A , final Variable B , ManagerTempVariables manager) { Info ret = new Info(); final VariableMatrix output = manager.createMatrix(); ret.output = output; if( A instanceof VariableMatrix && B instanceof VariableMatrix ) { ret.op = new Operation("solve-mm") { LinearSolverDense<DMatrixRMaj> solver; @Override public void process() { DMatrixRMaj a = ((VariableMatrix)A).matrix; DMatrixRMaj b = ((VariableMatrix)B).matrix; if( solver == null ) { solver = LinearSolverFactory_DDRM.leastSquares(a.numRows,a.numCols); } if( !solver.setA(a)) throw new RuntimeException("Solver failed!"); output.matrix.reshape(a.numCols,b.numCols); solver.solve(b, output.matrix); } }; } else { throw new RuntimeException("Expected two matrices got "+A+" "+B); } return ret; }
[ "public", "static", "Info", "solve", "(", "final", "Variable", "A", ",", "final", "Variable", "B", ",", "ManagerTempVariables", "manager", ")", "{", "Info", "ret", "=", "new", "Info", "(", ")", ";", "final", "VariableMatrix", "output", "=", "manager", ".", "createMatrix", "(", ")", ";", "ret", ".", "output", "=", "output", ";", "if", "(", "A", "instanceof", "VariableMatrix", "&&", "B", "instanceof", "VariableMatrix", ")", "{", "ret", ".", "op", "=", "new", "Operation", "(", "\"solve-mm\"", ")", "{", "LinearSolverDense", "<", "DMatrixRMaj", ">", "solver", ";", "@", "Override", "public", "void", "process", "(", ")", "{", "DMatrixRMaj", "a", "=", "(", "(", "VariableMatrix", ")", "A", ")", ".", "matrix", ";", "DMatrixRMaj", "b", "=", "(", "(", "VariableMatrix", ")", "B", ")", ".", "matrix", ";", "if", "(", "solver", "==", "null", ")", "{", "solver", "=", "LinearSolverFactory_DDRM", ".", "leastSquares", "(", "a", ".", "numRows", ",", "a", ".", "numCols", ")", ";", "}", "if", "(", "!", "solver", ".", "setA", "(", "a", ")", ")", "throw", "new", "RuntimeException", "(", "\"Solver failed!\"", ")", ";", "output", ".", "matrix", ".", "reshape", "(", "a", ".", "numCols", ",", "b", ".", "numCols", ")", ";", "solver", ".", "solve", "(", "b", ",", "output", ".", "matrix", ")", ";", "}", "}", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Expected two matrices got \"", "+", "A", "+", "\" \"", "+", "B", ")", ";", "}", "return", "ret", ";", "}" ]
If input is two vectors then it returns the dot product as a double.
[ "If", "input", "is", "two", "vectors", "then", "it", "returns", "the", "dot", "product", "as", "a", "double", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/equation/Operation.java#L1499-L1529
knowm/Datasets
datasets-hja-birdsong/src/main/java/com/musicg/wave/WaveformRender.java
WaveformRender.saveWaveform
public void saveWaveform(Wave wave, int width, String filename) throws IOException { """ Render a waveform of a wave file @param filename output file @throws IOException @see RGB graphic rendered """ BufferedImage bufferedImage = renderWaveform(wave, width); saveWaveform(bufferedImage, filename); }
java
public void saveWaveform(Wave wave, int width, String filename) throws IOException { BufferedImage bufferedImage = renderWaveform(wave, width); saveWaveform(bufferedImage, filename); }
[ "public", "void", "saveWaveform", "(", "Wave", "wave", ",", "int", "width", ",", "String", "filename", ")", "throws", "IOException", "{", "BufferedImage", "bufferedImage", "=", "renderWaveform", "(", "wave", ",", "width", ")", ";", "saveWaveform", "(", "bufferedImage", ",", "filename", ")", ";", "}" ]
Render a waveform of a wave file @param filename output file @throws IOException @see RGB graphic rendered
[ "Render", "a", "waveform", "of", "a", "wave", "file" ]
train
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-hja-birdsong/src/main/java/com/musicg/wave/WaveformRender.java#L111-L115
opsbears/owc-dic
src/main/java/com/opsbears/webcomponents/dic/InjectionConfiguration.java
InjectionConfiguration.define
public <T> void define(Class<T> classDefinition, Map<String, Object> namedParameterValues) { """ Allows the dependency injector to use the specified class and specifies values for some or all parameters. (Only works if the class in question is compiled with `-parameters`.) @param classDefinition The class to use. @param namedParameterValues Values for the specified parameters. """ injectorConfiguration = injectorConfiguration.withDefined(classDefinition); namedParameterValues.forEach((key, value) -> { injectorConfiguration = injectorConfiguration.withNamedParameterValue(classDefinition, key, value); }); }
java
public <T> void define(Class<T> classDefinition, Map<String, Object> namedParameterValues) { injectorConfiguration = injectorConfiguration.withDefined(classDefinition); namedParameterValues.forEach((key, value) -> { injectorConfiguration = injectorConfiguration.withNamedParameterValue(classDefinition, key, value); }); }
[ "public", "<", "T", ">", "void", "define", "(", "Class", "<", "T", ">", "classDefinition", ",", "Map", "<", "String", ",", "Object", ">", "namedParameterValues", ")", "{", "injectorConfiguration", "=", "injectorConfiguration", ".", "withDefined", "(", "classDefinition", ")", ";", "namedParameterValues", ".", "forEach", "(", "(", "key", ",", "value", ")", "->", "{", "injectorConfiguration", "=", "injectorConfiguration", ".", "withNamedParameterValue", "(", "classDefinition", ",", "key", ",", "value", ")", ";", "}", ")", ";", "}" ]
Allows the dependency injector to use the specified class and specifies values for some or all parameters. (Only works if the class in question is compiled with `-parameters`.) @param classDefinition The class to use. @param namedParameterValues Values for the specified parameters.
[ "Allows", "the", "dependency", "injector", "to", "use", "the", "specified", "class", "and", "specifies", "values", "for", "some", "or", "all", "parameters", ".", "(", "Only", "works", "if", "the", "class", "in", "question", "is", "compiled", "with", "-", "parameters", ".", ")" ]
train
https://github.com/opsbears/owc-dic/blob/eb254ca993b26c299292a01598b358a31f323566/src/main/java/com/opsbears/webcomponents/dic/InjectionConfiguration.java#L60-L66
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java
AbstractFileStateBackend.validatePath
private static Path validatePath(Path path) { """ Checks the validity of the path's scheme and path. @param path The path to check. @return The URI as a Path. @throws IllegalArgumentException Thrown, if the URI misses scheme or path. """ final URI uri = path.toUri(); final String scheme = uri.getScheme(); final String pathPart = uri.getPath(); // some validity checks if (scheme == null) { throw new IllegalArgumentException("The scheme (hdfs://, file://, etc) is null. " + "Please specify the file system scheme explicitly in the URI."); } if (pathPart == null) { throw new IllegalArgumentException("The path to store the checkpoint data in is null. " + "Please specify a directory path for the checkpoint data."); } if (pathPart.length() == 0 || pathPart.equals("/")) { throw new IllegalArgumentException("Cannot use the root directory for checkpoints."); } return path; }
java
private static Path validatePath(Path path) { final URI uri = path.toUri(); final String scheme = uri.getScheme(); final String pathPart = uri.getPath(); // some validity checks if (scheme == null) { throw new IllegalArgumentException("The scheme (hdfs://, file://, etc) is null. " + "Please specify the file system scheme explicitly in the URI."); } if (pathPart == null) { throw new IllegalArgumentException("The path to store the checkpoint data in is null. " + "Please specify a directory path for the checkpoint data."); } if (pathPart.length() == 0 || pathPart.equals("/")) { throw new IllegalArgumentException("Cannot use the root directory for checkpoints."); } return path; }
[ "private", "static", "Path", "validatePath", "(", "Path", "path", ")", "{", "final", "URI", "uri", "=", "path", ".", "toUri", "(", ")", ";", "final", "String", "scheme", "=", "uri", ".", "getScheme", "(", ")", ";", "final", "String", "pathPart", "=", "uri", ".", "getPath", "(", ")", ";", "// some validity checks", "if", "(", "scheme", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The scheme (hdfs://, file://, etc) is null. \"", "+", "\"Please specify the file system scheme explicitly in the URI.\"", ")", ";", "}", "if", "(", "pathPart", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The path to store the checkpoint data in is null. \"", "+", "\"Please specify a directory path for the checkpoint data.\"", ")", ";", "}", "if", "(", "pathPart", ".", "length", "(", ")", "==", "0", "||", "pathPart", ".", "equals", "(", "\"/\"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot use the root directory for checkpoints.\"", ")", ";", "}", "return", "path", ";", "}" ]
Checks the validity of the path's scheme and path. @param path The path to check. @return The URI as a Path. @throws IllegalArgumentException Thrown, if the URI misses scheme or path.
[ "Checks", "the", "validity", "of", "the", "path", "s", "scheme", "and", "path", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java#L180-L199
xiaosunzhu/resource-utils
src/main/java/net/sunyijun/resource/config/Configs.java
Configs.isHavePathSelfConfig
public static boolean isHavePathSelfConfig(IConfigKeyWithPath key) { """ Get self config boolean value @param key config key with configAbsoluteClassPath in config file @return true/false. If not add config file or not config in config file, return false. @see #addSelfConfigs(String, OneProperties) """ String configAbsoluteClassPath = key.getConfigPath(); return isSelfConfig(configAbsoluteClassPath, key); }
java
public static boolean isHavePathSelfConfig(IConfigKeyWithPath key) { String configAbsoluteClassPath = key.getConfigPath(); return isSelfConfig(configAbsoluteClassPath, key); }
[ "public", "static", "boolean", "isHavePathSelfConfig", "(", "IConfigKeyWithPath", "key", ")", "{", "String", "configAbsoluteClassPath", "=", "key", ".", "getConfigPath", "(", ")", ";", "return", "isSelfConfig", "(", "configAbsoluteClassPath", ",", "key", ")", ";", "}" ]
Get self config boolean value @param key config key with configAbsoluteClassPath in config file @return true/false. If not add config file or not config in config file, return false. @see #addSelfConfigs(String, OneProperties)
[ "Get", "self", "config", "boolean", "value" ]
train
https://github.com/xiaosunzhu/resource-utils/blob/4f2bf3f36df10195a978f122ed682ba1eb0462b5/src/main/java/net/sunyijun/resource/config/Configs.java#L365-L368
ZieIony/Carbon
carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java
LayerDrawable.setLayerInset
public void setLayerInset(int index, int l, int t, int r, int b) { """ Specifies the insets in pixels for the drawable at the specified index. @param index the index of the drawable to adjust @param l number of pixels to add to the left bound @param t number of pixels to add to the top bound @param r number of pixels to subtract from the right bound @param b number of pixels to subtract from the bottom bound @attr ref android.R.styleable#LayerDrawableItem_left @attr ref android.R.styleable#LayerDrawableItem_top @attr ref android.R.styleable#LayerDrawableItem_right @attr ref android.R.styleable#LayerDrawableItem_bottom """ setLayerInsetInternal(index, l, t, r, b, UNDEFINED_INSET, UNDEFINED_INSET); }
java
public void setLayerInset(int index, int l, int t, int r, int b) { setLayerInsetInternal(index, l, t, r, b, UNDEFINED_INSET, UNDEFINED_INSET); }
[ "public", "void", "setLayerInset", "(", "int", "index", ",", "int", "l", ",", "int", "t", ",", "int", "r", ",", "int", "b", ")", "{", "setLayerInsetInternal", "(", "index", ",", "l", ",", "t", ",", "r", ",", "b", ",", "UNDEFINED_INSET", ",", "UNDEFINED_INSET", ")", ";", "}" ]
Specifies the insets in pixels for the drawable at the specified index. @param index the index of the drawable to adjust @param l number of pixels to add to the left bound @param t number of pixels to add to the top bound @param r number of pixels to subtract from the right bound @param b number of pixels to subtract from the bottom bound @attr ref android.R.styleable#LayerDrawableItem_left @attr ref android.R.styleable#LayerDrawableItem_top @attr ref android.R.styleable#LayerDrawableItem_right @attr ref android.R.styleable#LayerDrawableItem_bottom
[ "Specifies", "the", "insets", "in", "pixels", "for", "the", "drawable", "at", "the", "specified", "index", "." ]
train
https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/LayerDrawable.java#L671-L673
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java
PageInBrowserStats.getWindowMinLoadTime
public long getWindowMinLoadTime(final String intervalName, final TimeUnit unit) { """ Returns web page minimum load time for given interval and {@link TimeUnit}. @param intervalName name of the interval @param unit {@link TimeUnit} @return web page minimum load time """ final long min = windowMinLoadTime.getValueAsLong(intervalName); return min == Constants.MIN_TIME_DEFAULT ? min : unit.transformMillis(min); }
java
public long getWindowMinLoadTime(final String intervalName, final TimeUnit unit) { final long min = windowMinLoadTime.getValueAsLong(intervalName); return min == Constants.MIN_TIME_DEFAULT ? min : unit.transformMillis(min); }
[ "public", "long", "getWindowMinLoadTime", "(", "final", "String", "intervalName", ",", "final", "TimeUnit", "unit", ")", "{", "final", "long", "min", "=", "windowMinLoadTime", ".", "getValueAsLong", "(", "intervalName", ")", ";", "return", "min", "==", "Constants", ".", "MIN_TIME_DEFAULT", "?", "min", ":", "unit", ".", "transformMillis", "(", "min", ")", ";", "}" ]
Returns web page minimum load time for given interval and {@link TimeUnit}. @param intervalName name of the interval @param unit {@link TimeUnit} @return web page minimum load time
[ "Returns", "web", "page", "minimum", "load", "time", "for", "given", "interval", "and", "{", "@link", "TimeUnit", "}", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/predefined/PageInBrowserStats.java#L175-L178
aws/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/GetIdentityVerificationAttributesResult.java
GetIdentityVerificationAttributesResult.withVerificationAttributes
public GetIdentityVerificationAttributesResult withVerificationAttributes(java.util.Map<String, IdentityVerificationAttributes> verificationAttributes) { """ <p> A map of Identities to IdentityVerificationAttributes objects. </p> @param verificationAttributes A map of Identities to IdentityVerificationAttributes objects. @return Returns a reference to this object so that method calls can be chained together. """ setVerificationAttributes(verificationAttributes); return this; }
java
public GetIdentityVerificationAttributesResult withVerificationAttributes(java.util.Map<String, IdentityVerificationAttributes> verificationAttributes) { setVerificationAttributes(verificationAttributes); return this; }
[ "public", "GetIdentityVerificationAttributesResult", "withVerificationAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "IdentityVerificationAttributes", ">", "verificationAttributes", ")", "{", "setVerificationAttributes", "(", "verificationAttributes", ")", ";", "return", "this", ";", "}" ]
<p> A map of Identities to IdentityVerificationAttributes objects. </p> @param verificationAttributes A map of Identities to IdentityVerificationAttributes objects. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "Identities", "to", "IdentityVerificationAttributes", "objects", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/GetIdentityVerificationAttributesResult.java#L77-L80
opensourceBIM/BIMserver
PluginBase/src/org/bimserver/utils/RichIfcModel.java
RichIfcModel.addDecomposes
public void addDecomposes(IfcObjectDefinition parent, IfcObjectDefinition... children) throws IfcModelInterfaceException { """ Create a decomposes relationship @param parent The object that represents the nest or aggregation @param child The objects being nested or aggregated @throws IfcModelInterfaceException """ IfcRelAggregates ifcRelAggregates = this.create(IfcRelAggregates.class); ifcRelAggregates.setRelatingObject(parent); for (IfcObjectDefinition child: children) { ifcRelAggregates.getRelatedObjects().add(child); } }
java
public void addDecomposes(IfcObjectDefinition parent, IfcObjectDefinition... children) throws IfcModelInterfaceException { IfcRelAggregates ifcRelAggregates = this.create(IfcRelAggregates.class); ifcRelAggregates.setRelatingObject(parent); for (IfcObjectDefinition child: children) { ifcRelAggregates.getRelatedObjects().add(child); } }
[ "public", "void", "addDecomposes", "(", "IfcObjectDefinition", "parent", ",", "IfcObjectDefinition", "...", "children", ")", "throws", "IfcModelInterfaceException", "{", "IfcRelAggregates", "ifcRelAggregates", "=", "this", ".", "create", "(", "IfcRelAggregates", ".", "class", ")", ";", "ifcRelAggregates", ".", "setRelatingObject", "(", "parent", ")", ";", "for", "(", "IfcObjectDefinition", "child", ":", "children", ")", "{", "ifcRelAggregates", ".", "getRelatedObjects", "(", ")", ".", "add", "(", "child", ")", ";", "}", "}" ]
Create a decomposes relationship @param parent The object that represents the nest or aggregation @param child The objects being nested or aggregated @throws IfcModelInterfaceException
[ "Create", "a", "decomposes", "relationship" ]
train
https://github.com/opensourceBIM/BIMserver/blob/116803c3047d1b32217366757cee1bb3880fda63/PluginBase/src/org/bimserver/utils/RichIfcModel.java#L78-L84
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java
CommerceWarehousePersistenceImpl.removeByG_P
@Override public void removeByG_P(long groupId, boolean primary) { """ Removes all the commerce warehouses where groupId = &#63; and primary = &#63; from the database. @param groupId the group ID @param primary the primary """ for (CommerceWarehouse commerceWarehouse : findByG_P(groupId, primary, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceWarehouse); } }
java
@Override public void removeByG_P(long groupId, boolean primary) { for (CommerceWarehouse commerceWarehouse : findByG_P(groupId, primary, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceWarehouse); } }
[ "@", "Override", "public", "void", "removeByG_P", "(", "long", "groupId", ",", "boolean", "primary", ")", "{", "for", "(", "CommerceWarehouse", "commerceWarehouse", ":", "findByG_P", "(", "groupId", ",", "primary", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "commerceWarehouse", ")", ";", "}", "}" ]
Removes all the commerce warehouses where groupId = &#63; and primary = &#63; from the database. @param groupId the group ID @param primary the primary
[ "Removes", "all", "the", "commerce", "warehouses", "where", "groupId", "=", "&#63", ";", "and", "primary", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceWarehousePersistenceImpl.java#L2182-L2188
alkacon/opencms-core
src/org/opencms/staticexport/A_CmsStaticExportHandler.java
A_CmsStaticExportHandler.purgeFile
protected void purgeFile(String rfsFilePath, String vfsName) { """ Deletes the given file from the RFS if it exists, also deletes all parameter variations of the file.<p> @param rfsFilePath the path of the RFS file to delete @param vfsName the VFS name of the file to delete (required for logging) """ File rfsFile = new File(rfsFilePath); // first delete the base file deleteFile(rfsFile, vfsName); // now delete the file parameter variations // get the parent folder File parent = rfsFile.getParentFile(); if (parent != null) { // list all files in the parent folder that are variations of the base file File[] paramVariants = parent.listFiles(new PrefixFileFilter(rfsFile)); if (paramVariants != null) { for (int v = 0; v < paramVariants.length; v++) { deleteFile(paramVariants[v], vfsName); } } } }
java
protected void purgeFile(String rfsFilePath, String vfsName) { File rfsFile = new File(rfsFilePath); // first delete the base file deleteFile(rfsFile, vfsName); // now delete the file parameter variations // get the parent folder File parent = rfsFile.getParentFile(); if (parent != null) { // list all files in the parent folder that are variations of the base file File[] paramVariants = parent.listFiles(new PrefixFileFilter(rfsFile)); if (paramVariants != null) { for (int v = 0; v < paramVariants.length; v++) { deleteFile(paramVariants[v], vfsName); } } } }
[ "protected", "void", "purgeFile", "(", "String", "rfsFilePath", ",", "String", "vfsName", ")", "{", "File", "rfsFile", "=", "new", "File", "(", "rfsFilePath", ")", ";", "// first delete the base file", "deleteFile", "(", "rfsFile", ",", "vfsName", ")", ";", "// now delete the file parameter variations", "// get the parent folder", "File", "parent", "=", "rfsFile", ".", "getParentFile", "(", ")", ";", "if", "(", "parent", "!=", "null", ")", "{", "// list all files in the parent folder that are variations of the base file", "File", "[", "]", "paramVariants", "=", "parent", ".", "listFiles", "(", "new", "PrefixFileFilter", "(", "rfsFile", ")", ")", ";", "if", "(", "paramVariants", "!=", "null", ")", "{", "for", "(", "int", "v", "=", "0", ";", "v", "<", "paramVariants", ".", "length", ";", "v", "++", ")", "{", "deleteFile", "(", "paramVariants", "[", "v", "]", ",", "vfsName", ")", ";", "}", "}", "}", "}" ]
Deletes the given file from the RFS if it exists, also deletes all parameter variations of the file.<p> @param rfsFilePath the path of the RFS file to delete @param vfsName the VFS name of the file to delete (required for logging)
[ "Deletes", "the", "given", "file", "from", "the", "RFS", "if", "it", "exists", "also", "deletes", "all", "parameter", "variations", "of", "the", "file", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/A_CmsStaticExportHandler.java#L320-L339
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_fax_serviceName_PUT
public void billingAccount_fax_serviceName_PUT(String billingAccount, String serviceName, OvhFax body) throws IOException { """ Alter this object properties REST: PUT /telephony/{billingAccount}/fax/{serviceName} @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param serviceName [required] """ String qPath = "/telephony/{billingAccount}/fax/{serviceName}"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
java
public void billingAccount_fax_serviceName_PUT(String billingAccount, String serviceName, OvhFax body) throws IOException { String qPath = "/telephony/{billingAccount}/fax/{serviceName}"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "billingAccount_fax_serviceName_PUT", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "OvhFax", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/fax/{serviceName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /telephony/{billingAccount}/fax/{serviceName} @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L4532-L4536
grpc/grpc-java
netty/src/main/java/io/grpc/netty/NettyServerBuilder.java
NettyServerBuilder.maxConnectionIdle
public NettyServerBuilder maxConnectionIdle(long maxConnectionIdle, TimeUnit timeUnit) { """ Sets a custom max connection idle time, connection being idle for longer than which will be gracefully terminated. Idleness duration is defined since the most recent time the number of outstanding RPCs became zero or the connection establishment. An unreasonably small value might be increased. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable max connection idle. @since 1.4.0 """ checkArgument(maxConnectionIdle > 0L, "max connection idle must be positive"); maxConnectionIdleInNanos = timeUnit.toNanos(maxConnectionIdle); if (maxConnectionIdleInNanos >= AS_LARGE_AS_INFINITE) { maxConnectionIdleInNanos = MAX_CONNECTION_IDLE_NANOS_DISABLED; } if (maxConnectionIdleInNanos < MIN_MAX_CONNECTION_IDLE_NANO) { maxConnectionIdleInNanos = MIN_MAX_CONNECTION_IDLE_NANO; } return this; }
java
public NettyServerBuilder maxConnectionIdle(long maxConnectionIdle, TimeUnit timeUnit) { checkArgument(maxConnectionIdle > 0L, "max connection idle must be positive"); maxConnectionIdleInNanos = timeUnit.toNanos(maxConnectionIdle); if (maxConnectionIdleInNanos >= AS_LARGE_AS_INFINITE) { maxConnectionIdleInNanos = MAX_CONNECTION_IDLE_NANOS_DISABLED; } if (maxConnectionIdleInNanos < MIN_MAX_CONNECTION_IDLE_NANO) { maxConnectionIdleInNanos = MIN_MAX_CONNECTION_IDLE_NANO; } return this; }
[ "public", "NettyServerBuilder", "maxConnectionIdle", "(", "long", "maxConnectionIdle", ",", "TimeUnit", "timeUnit", ")", "{", "checkArgument", "(", "maxConnectionIdle", ">", "0L", ",", "\"max connection idle must be positive\"", ")", ";", "maxConnectionIdleInNanos", "=", "timeUnit", ".", "toNanos", "(", "maxConnectionIdle", ")", ";", "if", "(", "maxConnectionIdleInNanos", ">=", "AS_LARGE_AS_INFINITE", ")", "{", "maxConnectionIdleInNanos", "=", "MAX_CONNECTION_IDLE_NANOS_DISABLED", ";", "}", "if", "(", "maxConnectionIdleInNanos", "<", "MIN_MAX_CONNECTION_IDLE_NANO", ")", "{", "maxConnectionIdleInNanos", "=", "MIN_MAX_CONNECTION_IDLE_NANO", ";", "}", "return", "this", ";", "}" ]
Sets a custom max connection idle time, connection being idle for longer than which will be gracefully terminated. Idleness duration is defined since the most recent time the number of outstanding RPCs became zero or the connection establishment. An unreasonably small value might be increased. {@code Long.MAX_VALUE} nano seconds or an unreasonably large value will disable max connection idle. @since 1.4.0
[ "Sets", "a", "custom", "max", "connection", "idle", "time", "connection", "being", "idle", "for", "longer", "than", "which", "will", "be", "gracefully", "terminated", ".", "Idleness", "duration", "is", "defined", "since", "the", "most", "recent", "time", "the", "number", "of", "outstanding", "RPCs", "became", "zero", "or", "the", "connection", "establishment", ".", "An", "unreasonably", "small", "value", "might", "be", "increased", ".", "{", "@code", "Long", ".", "MAX_VALUE", "}", "nano", "seconds", "or", "an", "unreasonably", "large", "value", "will", "disable", "max", "connection", "idle", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/NettyServerBuilder.java#L413-L423
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/application/impl/metadata/ProcessesXmlParse.java
ProcessesXmlParse.parseProcessArchive
protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) { """ parse a <code>&lt;process-archive .../&gt;</code> element and add it to the list of parsed elements """ ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl(); processArchive.setName(element.attribute(NAME)); processArchive.setTenantId(element.attribute(TENANT_ID)); List<String> processResourceNames = new ArrayList<String>(); Map<String, String> properties = new HashMap<String, String>(); for (Element childElement : element.elements()) { if(PROCESS_ENGINE.equals(childElement.getTagName())) { processArchive.setProcessEngineName(childElement.getText()); } else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) { processResourceNames.add(childElement.getText()); } else if(PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); } } // set properties processArchive.setProperties(properties); // add collected resource names. processArchive.setProcessResourceNames(processResourceNames); // add process archive to list of parsed archives. parsedProcessArchives.add(processArchive); }
java
protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) { ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl(); processArchive.setName(element.attribute(NAME)); processArchive.setTenantId(element.attribute(TENANT_ID)); List<String> processResourceNames = new ArrayList<String>(); Map<String, String> properties = new HashMap<String, String>(); for (Element childElement : element.elements()) { if(PROCESS_ENGINE.equals(childElement.getTagName())) { processArchive.setProcessEngineName(childElement.getText()); } else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) { processResourceNames.add(childElement.getText()); } else if(PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); } } // set properties processArchive.setProperties(properties); // add collected resource names. processArchive.setProcessResourceNames(processResourceNames); // add process archive to list of parsed archives. parsedProcessArchives.add(processArchive); }
[ "protected", "void", "parseProcessArchive", "(", "Element", "element", ",", "List", "<", "ProcessArchiveXml", ">", "parsedProcessArchives", ")", "{", "ProcessArchiveXmlImpl", "processArchive", "=", "new", "ProcessArchiveXmlImpl", "(", ")", ";", "processArchive", ".", "setName", "(", "element", ".", "attribute", "(", "NAME", ")", ")", ";", "processArchive", ".", "setTenantId", "(", "element", ".", "attribute", "(", "TENANT_ID", ")", ")", ";", "List", "<", "String", ">", "processResourceNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "properties", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "for", "(", "Element", "childElement", ":", "element", ".", "elements", "(", ")", ")", "{", "if", "(", "PROCESS_ENGINE", ".", "equals", "(", "childElement", ".", "getTagName", "(", ")", ")", ")", "{", "processArchive", ".", "setProcessEngineName", "(", "childElement", ".", "getText", "(", ")", ")", ";", "}", "else", "if", "(", "PROCESS", ".", "equals", "(", "childElement", ".", "getTagName", "(", ")", ")", "||", "RESOURCE", ".", "equals", "(", "childElement", ".", "getTagName", "(", ")", ")", ")", "{", "processResourceNames", ".", "add", "(", "childElement", ".", "getText", "(", ")", ")", ";", "}", "else", "if", "(", "PROPERTIES", ".", "equals", "(", "childElement", ".", "getTagName", "(", ")", ")", ")", "{", "parseProperties", "(", "childElement", ",", "properties", ")", ";", "}", "}", "// set properties", "processArchive", ".", "setProperties", "(", "properties", ")", ";", "// add collected resource names.", "processArchive", ".", "setProcessResourceNames", "(", "processResourceNames", ")", ";", "// add process archive to list of parsed archives.", "parsedProcessArchives", ".", "add", "(", "processArchive", ")", ";", "}" ]
parse a <code>&lt;process-archive .../&gt;</code> element and add it to the list of parsed elements
[ "parse", "a", "<code", ">", "&lt", ";", "process", "-", "archive", "...", "/", "&gt", ";", "<", "/", "code", ">", "element", "and", "add", "it", "to", "the", "list", "of", "parsed", "elements" ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/application/impl/metadata/ProcessesXmlParse.java#L92-L124
ModeShape/modeshape
connectors/modeshape-connector-cmis/src/main/java/org/modeshape/connector/cmis/CmisConnector.java
CmisConnector.jcrBinaryContent
private ContentStream jcrBinaryContent( Document document ) { """ Creates content stream using JCR node. @param document JCR node representation @return CMIS content stream object """ // pickup node properties Document props = document.getDocument("properties").getDocument(JcrLexicon.Namespace.URI); // extract binary value and content Binary value = props.getBinary("data"); if (value == null) { return null; } byte[] content = value.getBytes(); String fileName = props.getString("fileName"); String mimeType = props.getString("mimeType"); // wrap with input stream ByteArrayInputStream bin = new ByteArrayInputStream(content); bin.reset(); // create content stream return new ContentStreamImpl(fileName, BigInteger.valueOf(content.length), mimeType, bin); }
java
private ContentStream jcrBinaryContent( Document document ) { // pickup node properties Document props = document.getDocument("properties").getDocument(JcrLexicon.Namespace.URI); // extract binary value and content Binary value = props.getBinary("data"); if (value == null) { return null; } byte[] content = value.getBytes(); String fileName = props.getString("fileName"); String mimeType = props.getString("mimeType"); // wrap with input stream ByteArrayInputStream bin = new ByteArrayInputStream(content); bin.reset(); // create content stream return new ContentStreamImpl(fileName, BigInteger.valueOf(content.length), mimeType, bin); }
[ "private", "ContentStream", "jcrBinaryContent", "(", "Document", "document", ")", "{", "// pickup node properties", "Document", "props", "=", "document", ".", "getDocument", "(", "\"properties\"", ")", ".", "getDocument", "(", "JcrLexicon", ".", "Namespace", ".", "URI", ")", ";", "// extract binary value and content", "Binary", "value", "=", "props", ".", "getBinary", "(", "\"data\"", ")", ";", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "byte", "[", "]", "content", "=", "value", ".", "getBytes", "(", ")", ";", "String", "fileName", "=", "props", ".", "getString", "(", "\"fileName\"", ")", ";", "String", "mimeType", "=", "props", ".", "getString", "(", "\"mimeType\"", ")", ";", "// wrap with input stream", "ByteArrayInputStream", "bin", "=", "new", "ByteArrayInputStream", "(", "content", ")", ";", "bin", ".", "reset", "(", ")", ";", "// create content stream", "return", "new", "ContentStreamImpl", "(", "fileName", ",", "BigInteger", ".", "valueOf", "(", "content", ".", "length", ")", ",", "mimeType", ",", "bin", ")", ";", "}" ]
Creates content stream using JCR node. @param document JCR node representation @return CMIS content stream object
[ "Creates", "content", "stream", "using", "JCR", "node", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/connectors/modeshape-connector-cmis/src/main/java/org/modeshape/connector/cmis/CmisConnector.java#L952-L973
jbundle/jbundle
thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/SessionProxy.java
SessionProxy.getRemoteTable
public RemoteTable getRemoteTable(String strRecordName) throws RemoteException { """ Get this table for this session. @param strRecordName Table Name or Class Name of the record to find """ BaseTransport transport = this.createProxyTransport(GET_REMOTE_TABLE); transport.addParam(NAME, strRecordName); String strTableID = (String)transport.sendMessageAndGetReply(); // See if I have this one already TableProxy tableProxy = (TableProxy)this.getChildList().get(strTableID); if (tableProxy == null) tableProxy = new TableProxy(this, strTableID); // This will add it to my list return tableProxy; }
java
public RemoteTable getRemoteTable(String strRecordName) throws RemoteException { BaseTransport transport = this.createProxyTransport(GET_REMOTE_TABLE); transport.addParam(NAME, strRecordName); String strTableID = (String)transport.sendMessageAndGetReply(); // See if I have this one already TableProxy tableProxy = (TableProxy)this.getChildList().get(strTableID); if (tableProxy == null) tableProxy = new TableProxy(this, strTableID); // This will add it to my list return tableProxy; }
[ "public", "RemoteTable", "getRemoteTable", "(", "String", "strRecordName", ")", "throws", "RemoteException", "{", "BaseTransport", "transport", "=", "this", ".", "createProxyTransport", "(", "GET_REMOTE_TABLE", ")", ";", "transport", ".", "addParam", "(", "NAME", ",", "strRecordName", ")", ";", "String", "strTableID", "=", "(", "String", ")", "transport", ".", "sendMessageAndGetReply", "(", ")", ";", "// See if I have this one already", "TableProxy", "tableProxy", "=", "(", "TableProxy", ")", "this", ".", "getChildList", "(", ")", ".", "get", "(", "strTableID", ")", ";", "if", "(", "tableProxy", "==", "null", ")", "tableProxy", "=", "new", "TableProxy", "(", "this", ",", "strTableID", ")", ";", "// This will add it to my list", "return", "tableProxy", ";", "}" ]
Get this table for this session. @param strRecordName Table Name or Class Name of the record to find
[ "Get", "this", "table", "for", "this", "session", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/SessionProxy.java#L60-L70
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java
StringUtil.isNumeric
public static boolean isNumeric(String str, int beginIndex, int endIndex) { """ check if the specified string it Latin numeric @param str @param beginIndex @param endIndex @return boolean """ for ( int i = beginIndex; i < endIndex; i++ ) { char chr = str.charAt(i); if ( ! StringUtil.isEnNumeric(chr) ) { return false; } } return true; }
java
public static boolean isNumeric(String str, int beginIndex, int endIndex) { for ( int i = beginIndex; i < endIndex; i++ ) { char chr = str.charAt(i); if ( ! StringUtil.isEnNumeric(chr) ) { return false; } } return true; }
[ "public", "static", "boolean", "isNumeric", "(", "String", "str", ",", "int", "beginIndex", ",", "int", "endIndex", ")", "{", "for", "(", "int", "i", "=", "beginIndex", ";", "i", "<", "endIndex", ";", "i", "++", ")", "{", "char", "chr", "=", "str", ".", "charAt", "(", "i", ")", ";", "if", "(", "!", "StringUtil", ".", "isEnNumeric", "(", "chr", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
check if the specified string it Latin numeric @param str @param beginIndex @param endIndex @return boolean
[ "check", "if", "the", "specified", "string", "it", "Latin", "numeric" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java#L419-L429
landawn/AbacusUtil
src/com/landawn/abacus/util/Primitives.java
Primitives.unbox
public static int[] unbox(final Integer[] a, final int valueForNull) { """ <p> Converts an array of object Integer to primitives handling {@code null}. </p> <p> This method returns {@code null} for a {@code null} input array. </p> @param a a {@code Integer} array, may be {@code null} @param valueForNull the value to insert if {@code null} found @return an {@code int} array, {@code null} if null array input """ if (a == null) { return null; } return unbox(a, 0, a.length, valueForNull); }
java
public static int[] unbox(final Integer[] a, final int valueForNull) { if (a == null) { return null; } return unbox(a, 0, a.length, valueForNull); }
[ "public", "static", "int", "[", "]", "unbox", "(", "final", "Integer", "[", "]", "a", ",", "final", "int", "valueForNull", ")", "{", "if", "(", "a", "==", "null", ")", "{", "return", "null", ";", "}", "return", "unbox", "(", "a", ",", "0", ",", "a", ".", "length", ",", "valueForNull", ")", ";", "}" ]
<p> Converts an array of object Integer to primitives handling {@code null}. </p> <p> This method returns {@code null} for a {@code null} input array. </p> @param a a {@code Integer} array, may be {@code null} @param valueForNull the value to insert if {@code null} found @return an {@code int} array, {@code null} if null array input
[ "<p", ">", "Converts", "an", "array", "of", "object", "Integer", "to", "primitives", "handling", "{", "@code", "null", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Primitives.java#L1019-L1025
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDataSource.java
MariaDbDataSource.getPooledConnection
public PooledConnection getPooledConnection(String user, String password) throws SQLException { """ Attempts to establish a physical database connection that can be used as a pooled connection. @param user the database user on whose behalf the connection is being made @param password the user's password @return a <code>PooledConnection</code> object that is a physical connection to the database that this <code>ConnectionPoolDataSource</code> object represents @throws SQLException if a database access error occurs """ return new MariaDbPooledConnection((MariaDbConnection) getConnection(user, password)); }
java
public PooledConnection getPooledConnection(String user, String password) throws SQLException { return new MariaDbPooledConnection((MariaDbConnection) getConnection(user, password)); }
[ "public", "PooledConnection", "getPooledConnection", "(", "String", "user", ",", "String", "password", ")", "throws", "SQLException", "{", "return", "new", "MariaDbPooledConnection", "(", "(", "MariaDbConnection", ")", "getConnection", "(", "user", ",", "password", ")", ")", ";", "}" ]
Attempts to establish a physical database connection that can be used as a pooled connection. @param user the database user on whose behalf the connection is being made @param password the user's password @return a <code>PooledConnection</code> object that is a physical connection to the database that this <code>ConnectionPoolDataSource</code> object represents @throws SQLException if a database access error occurs
[ "Attempts", "to", "establish", "a", "physical", "database", "connection", "that", "can", "be", "used", "as", "a", "pooled", "connection", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDataSource.java#L464-L466