hexsha
stringlengths
40
40
repo
stringlengths
4
114
path
stringlengths
6
369
license
sequence
language
stringclasses
1 value
identifier
stringlengths
1
123
original_docstring
stringlengths
8
49.2k
docstring
stringlengths
5
8.63k
docstring_tokens
sequence
code
stringlengths
25
988k
code_tokens
sequence
short_docstring
stringlengths
0
6.18k
short_docstring_tokens
sequence
comment
sequence
parameters
list
docstring_params
dict
7b74dbc0ffa71422da238fe3927289ab8868bba2
janekdb/rocoto
src/test/java/com/googlecode/rocoto/configuration/MemcachedConfiguration.java
[ "Apache-2.0" ]
Java
MemcachedConfiguration
/** * * * @author Simone Tripodi * @version $Id$ */
@author Simone Tripodi @version $Id$
[ "@author", "Simone", "Tripodi", "@version", "$Id$" ]
public final class MemcachedConfiguration { @Inject @Named("com.ibaguice.memcached.keyprefix") private String keyPrefix; @Inject @Named("com.ibaguice.memcached.compression") private boolean compressionEnabled; public String getKeyPrefix() { return keyPrefix; } public void setKeyPrefix(String keyPrefix) { this.keyPrefix = keyPrefix; } public boolean isCompressionEnabled() { return compressionEnabled; } public void setCompressionEnabled(boolean compressionEnabled) { this.compressionEnabled = compressionEnabled; } }
[ "public", "final", "class", "MemcachedConfiguration", "{", "@", "Inject", "@", "Named", "(", "\"", "com.ibaguice.memcached.keyprefix", "\"", ")", "private", "String", "keyPrefix", ";", "@", "Inject", "@", "Named", "(", "\"", "com.ibaguice.memcached.compression", "\"", ")", "private", "boolean", "compressionEnabled", ";", "public", "String", "getKeyPrefix", "(", ")", "{", "return", "keyPrefix", ";", "}", "public", "void", "setKeyPrefix", "(", "String", "keyPrefix", ")", "{", "this", ".", "keyPrefix", "=", "keyPrefix", ";", "}", "public", "boolean", "isCompressionEnabled", "(", ")", "{", "return", "compressionEnabled", ";", "}", "public", "void", "setCompressionEnabled", "(", "boolean", "compressionEnabled", ")", "{", "this", ".", "compressionEnabled", "=", "compressionEnabled", ";", "}", "}" ]
@author Simone Tripodi @version $Id$
[ "@author", "Simone", "Tripodi", "@version", "$Id$" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b757fac4cd0a63d7f85c6d20b96ebd3be2eb08b
itaiag/jsystem-tutorial-project
file-system-so/src/main/java/org/jsystem/file_system_so/AbstractRemoteFileSystem.java
[ "Apache-2.0" ]
Java
AbstractRemoteFileSystem
/** * System object that represents remote file system. This class should be * inhrite by different classes that will implement the different services * according to each operating system * * @author Itai Agmon * */
System object that represents remote file system. This class should be inhrite by different classes that will implement the different services according to each operating system @author Itai Agmon
[ "System", "object", "that", "represents", "remote", "file", "system", ".", "This", "class", "should", "be", "inhrite", "by", "different", "classes", "that", "will", "implement", "the", "different", "services", "according", "to", "each", "operating", "system", "@author", "Itai", "Agmon" ]
public abstract class AbstractRemoteFileSystem extends SystemObjectImpl { public CliConnectionImpl cliConnection; @Override public void init() throws Exception { super.init(); report.report("Initializing file system from type " + this.getClass().getSimpleName()); Assert.assertNotNull(cliConnection); } public abstract void copyFile(String sourceFolder, String sourceFile, String destinationFolder, String destinationFile) throws Exception; public abstract void createNewFile(String folder, String file) throws Exception; public abstract void writeContentToFile(String folder, String file, String content, boolean append) throws Exception; public abstract void deleteFile(String folder, String file) throws Exception; @Override public void close() { report.report("Closing file system from type " + this.getClass().getSimpleName()); } }
[ "public", "abstract", "class", "AbstractRemoteFileSystem", "extends", "SystemObjectImpl", "{", "public", "CliConnectionImpl", "cliConnection", ";", "@", "Override", "public", "void", "init", "(", ")", "throws", "Exception", "{", "super", ".", "init", "(", ")", ";", "report", ".", "report", "(", "\"", "Initializing file system from type ", "\"", "+", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "Assert", ".", "assertNotNull", "(", "cliConnection", ")", ";", "}", "public", "abstract", "void", "copyFile", "(", "String", "sourceFolder", ",", "String", "sourceFile", ",", "String", "destinationFolder", ",", "String", "destinationFile", ")", "throws", "Exception", ";", "public", "abstract", "void", "createNewFile", "(", "String", "folder", ",", "String", "file", ")", "throws", "Exception", ";", "public", "abstract", "void", "writeContentToFile", "(", "String", "folder", ",", "String", "file", ",", "String", "content", ",", "boolean", "append", ")", "throws", "Exception", ";", "public", "abstract", "void", "deleteFile", "(", "String", "folder", ",", "String", "file", ")", "throws", "Exception", ";", "@", "Override", "public", "void", "close", "(", ")", "{", "report", ".", "report", "(", "\"", "Closing file system from type ", "\"", "+", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "}", "}" ]
System object that represents remote file system.
[ "System", "object", "that", "represents", "remote", "file", "system", "." ]
[]
[ { "param": "SystemObjectImpl", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SystemObjectImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b76e158a394fcac1942b75248d41e21bee0cf06
BijuAle/Computing-Project-Epidemic-Analyzer
Implementation/EpidemicAnalyzer/src/main/java/ea/biju/controller/MapProjectionController.java
[ "MIT" ]
Java
MapProjectionController
/** * * @author Biju Ale */
@author Biju Ale
[ "@author", "Biju", "Ale" ]
@Controller @RequestMapping("patient_case") public class MapProjectionController { @Autowired PatientRepository patientRepository; @RequestMapping(value = "project_to_map") public String getJSON() { createEpidemicMapProjectionData(); return "patient_case/epidemic_map_projection"; } private void createEpidemicMapProjectionData() { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Create 1 root element - parent node = 'markers' Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("markers"); doc.appendChild(rootElement); //Create many marker element - child node = 'marker' Iterable<Patient> resultSet = patientRepository.findAll(); for (Patient p : resultSet) { Element marker = doc.createElement("marker"); rootElement.appendChild(marker); marker.setAttribute("id", Integer.toString(p.getId())); marker.setAttribute("name", p.getFirstName() + " " + p.getMiddleName() + " " + p.getLastName()); marker.setAttribute("age", getAge(p.getDob())); marker.setAttribute("gender", p.getGender().getDisplayName()); marker.setAttribute("address", p.getAddress().getWardNo() + ", " + p.getAddress().getVdc() + ", " + p.getAddress().getDistrict()); marker.setAttribute("lat", p.getAddress().getLatitude()); marker.setAttribute("lng", p.getAddress().getLongitude()); marker.setAttribute("currentInfectionStatus", p.getCurrentInfectionStatus().getDisplayName()); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); String filePathString = "src\\main\\resources\\static\\xml\\EpidemicMapProjectionData.xml"; File xmlFile = new File(filePathString); if (xmlFile.exists() && !xmlFile.isDirectory()) { xmlFile.delete(); } StreamResult result = new StreamResult(xmlFile); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } private String getAge(Date dob) { Calendar cal = Calendar.getInstance(); cal.setTime(dob); LocalDate birthdate = new LocalDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); LocalDate now = new LocalDate(); String age = Integer.toString(Years.yearsBetween(birthdate, now).getYears()); return age; } }
[ "@", "Controller", "@", "RequestMapping", "(", "\"", "patient_case", "\"", ")", "public", "class", "MapProjectionController", "{", "@", "Autowired", "PatientRepository", "patientRepository", ";", "@", "RequestMapping", "(", "value", "=", "\"", "project_to_map", "\"", ")", "public", "String", "getJSON", "(", ")", "{", "createEpidemicMapProjectionData", "(", ")", ";", "return", "\"", "patient_case/epidemic_map_projection", "\"", ";", "}", "private", "void", "createEpidemicMapProjectionData", "(", ")", "{", "try", "{", "DocumentBuilderFactory", "docFactory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "DocumentBuilder", "docBuilder", "=", "docFactory", ".", "newDocumentBuilder", "(", ")", ";", "Document", "doc", "=", "docBuilder", ".", "newDocument", "(", ")", ";", "Element", "rootElement", "=", "doc", ".", "createElement", "(", "\"", "markers", "\"", ")", ";", "doc", ".", "appendChild", "(", "rootElement", ")", ";", "Iterable", "<", "Patient", ">", "resultSet", "=", "patientRepository", ".", "findAll", "(", ")", ";", "for", "(", "Patient", "p", ":", "resultSet", ")", "{", "Element", "marker", "=", "doc", ".", "createElement", "(", "\"", "marker", "\"", ")", ";", "rootElement", ".", "appendChild", "(", "marker", ")", ";", "marker", ".", "setAttribute", "(", "\"", "id", "\"", ",", "Integer", ".", "toString", "(", "p", ".", "getId", "(", ")", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "name", "\"", ",", "p", ".", "getFirstName", "(", ")", "+", "\"", " ", "\"", "+", "p", ".", "getMiddleName", "(", ")", "+", "\"", " ", "\"", "+", "p", ".", "getLastName", "(", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "age", "\"", ",", "getAge", "(", "p", ".", "getDob", "(", ")", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "gender", "\"", ",", "p", ".", "getGender", "(", ")", ".", "getDisplayName", "(", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "address", "\"", ",", "p", ".", "getAddress", "(", ")", ".", "getWardNo", "(", ")", "+", "\"", ", ", "\"", "+", "p", ".", "getAddress", "(", ")", ".", "getVdc", "(", ")", "+", "\"", ", ", "\"", "+", "p", ".", "getAddress", "(", ")", ".", "getDistrict", "(", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "lat", "\"", ",", "p", ".", "getAddress", "(", ")", ".", "getLatitude", "(", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "lng", "\"", ",", "p", ".", "getAddress", "(", ")", ".", "getLongitude", "(", ")", ")", ";", "marker", ".", "setAttribute", "(", "\"", "currentInfectionStatus", "\"", ",", "p", ".", "getCurrentInfectionStatus", "(", ")", ".", "getDisplayName", "(", ")", ")", ";", "}", "TransformerFactory", "transformerFactory", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "transformer", "=", "transformerFactory", ".", "newTransformer", "(", ")", ";", "DOMSource", "source", "=", "new", "DOMSource", "(", "doc", ")", ";", "String", "filePathString", "=", "\"", "src", "\\\\", "main", "\\\\", "resources", "\\\\", "static", "\\\\", "xml", "\\\\", "EpidemicMapProjectionData.xml", "\"", ";", "File", "xmlFile", "=", "new", "File", "(", "filePathString", ")", ";", "if", "(", "xmlFile", ".", "exists", "(", ")", "&&", "!", "xmlFile", ".", "isDirectory", "(", ")", ")", "{", "xmlFile", ".", "delete", "(", ")", ";", "}", "StreamResult", "result", "=", "new", "StreamResult", "(", "xmlFile", ")", ";", "transformer", ".", "transform", "(", "source", ",", "result", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "File saved!", "\"", ")", ";", "}", "catch", "(", "ParserConfigurationException", "pce", ")", "{", "pce", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "TransformerException", "tfe", ")", "{", "tfe", ".", "printStackTrace", "(", ")", ";", "}", "}", "private", "String", "getAge", "(", "Date", "dob", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "setTime", "(", "dob", ")", ";", "LocalDate", "birthdate", "=", "new", "LocalDate", "(", "cal", ".", "get", "(", "Calendar", ".", "YEAR", ")", ",", "cal", ".", "get", "(", "Calendar", ".", "MONTH", ")", ",", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ")", ";", "LocalDate", "now", "=", "new", "LocalDate", "(", ")", ";", "String", "age", "=", "Integer", ".", "toString", "(", "Years", ".", "yearsBetween", "(", "birthdate", ",", "now", ")", ".", "getYears", "(", ")", ")", ";", "return", "age", ";", "}", "}" ]
@author Biju Ale
[ "@author", "Biju", "Ale" ]
[ "// Create 1 root element - parent node = 'markers'", "//Create many marker element - child node = 'marker'", "// write the content into xml file", "// Output to console for testing", "// StreamResult result = new StreamResult(System.out);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b776475d3397d7150c1744c4085148a523c48c4
LmhForkAndroidStudy/PingForAndroid
app/src/main/java/com/sohu/ping/NativeMethodHelper.java
[ "Apache-2.0" ]
Java
NativeMethodHelper
/** * Created by wangyan on 2019/3/14 */
Created by wangyan on 2019/3/14
[ "Created", "by", "wangyan", "on", "2019", "/", "3", "/", "14" ]
public class NativeMethodHelper { static { System.loadLibrary("native"); } public static native String ping(String domain); }
[ "public", "class", "NativeMethodHelper", "{", "static", "{", "System", ".", "loadLibrary", "(", "\"", "native", "\"", ")", ";", "}", "public", "static", "native", "String", "ping", "(", "String", "domain", ")", ";", "}" ]
Created by wangyan on 2019/3/14
[ "Created", "by", "wangyan", "on", "2019", "/", "3", "/", "14" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b77d4fcdcb4cb1c2e81d21cddab1664448dc8fe
cstechfoodie/SOEN387-PokemonWebApp
Pokemon/src/application/command/ChallengePlayerPC.java
[ "MIT" ]
Java
ChallengePlayerPC
/** * Servlet implementation class ChallengePlayerPC */
Servlet implementation class ChallengePlayerPC
[ "Servlet", "implementation", "class", "ChallengePlayerPC" ]
@WebServlet("/ChallengePlayer") public class ChallengePlayerPC extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ChallengePlayerPC() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub processRequest(request, response); } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { int deckId = Integer.parseInt(req.getParameter("deck")); int playerId = URIUtil.findInteger(req.getRequestURI()); int id = req.getSession(true).getAttribute("userid") == null ? -1 : (int)req.getSession(true).getAttribute("userid"); if(id < 0) { req.setAttribute("message", "User Not Login"); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } if(playerId < 0) { req.setAttribute("message", "Challenge player with illegal id."); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } if(playerId == id) { req.setAttribute("message", "Can't challenge yourself."); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } if(Deck.isMyOwnDeck(playerId, deckId)) { req.setAttribute("message", "Can't chanllenge with someone else's deck."); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } ArrayList<DeckCardRDG> cards = Deck.viewDeck(deckId); if(cards.size() == 0) { req.setAttribute("message", "No deck uploaded"); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } UserRDG u = null; try { u = UserRDG.find(playerId); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (u == null) { req.setAttribute("message", "Invalid challengee id"); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } else { try { if(ChallengeRDG.challengeTwice(id, playerId)) { req.setAttribute("message", "Challenge the same player twice not okay"); req.setAttribute("status", "fail"); req.getRequestDispatcher("/WEB-INF/jsp/failure.jsp").forward(req, res); return; } } catch (SQLException e1) { System.out.println("Exception in challenging the same player twice"); } ChallengeRDG ch = new ChallengeRDG(id, playerId, 0, deckId); try { ch.insert(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } req.setAttribute("message", "Challenge with id = " + ch.getId() + " has been successfully created."); req.setAttribute("status", "success"); req.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(req, res); return; } } }
[ "@", "WebServlet", "(", "\"", "/ChallengePlayer", "\"", ")", "public", "class", "ChallengePlayerPC", "extends", "HttpServlet", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\n * @see HttpServlet#HttpServlet()\n */", "public", "ChallengePlayerPC", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n\t * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)\n\t */", "protected", "void", "doGet", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "response", ".", "getWriter", "(", ")", ".", "append", "(", "\"", "Served at: ", "\"", ")", ".", "append", "(", "request", ".", "getContextPath", "(", ")", ")", ";", "}", "/**\n\t * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)\n\t */", "protected", "void", "doPost", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "processRequest", "(", "request", ",", "response", ")", ";", "}", "public", "void", "processRequest", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "ServletException", ",", "IOException", "{", "int", "deckId", "=", "Integer", ".", "parseInt", "(", "req", ".", "getParameter", "(", "\"", "deck", "\"", ")", ")", ";", "int", "playerId", "=", "URIUtil", ".", "findInteger", "(", "req", ".", "getRequestURI", "(", ")", ")", ";", "int", "id", "=", "req", ".", "getSession", "(", "true", ")", ".", "getAttribute", "(", "\"", "userid", "\"", ")", "==", "null", "?", "-", "1", ":", "(", "int", ")", "req", ".", "getSession", "(", "true", ")", ".", "getAttribute", "(", "\"", "userid", "\"", ")", ";", "if", "(", "id", "<", "0", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "User Not Login", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "if", "(", "playerId", "<", "0", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "Challenge player with illegal id.", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "if", "(", "playerId", "==", "id", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "Can't challenge yourself.", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "if", "(", "Deck", ".", "isMyOwnDeck", "(", "playerId", ",", "deckId", ")", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "Can't chanllenge with someone else's deck.", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "ArrayList", "<", "DeckCardRDG", ">", "cards", "=", "Deck", ".", "viewDeck", "(", "deckId", ")", ";", "if", "(", "cards", ".", "size", "(", ")", "==", "0", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "No deck uploaded", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "UserRDG", "u", "=", "null", ";", "try", "{", "u", "=", "UserRDG", ".", "find", "(", "playerId", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "if", "(", "u", "==", "null", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "Invalid challengee id", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "else", "{", "try", "{", "if", "(", "ChallengeRDG", ".", "challengeTwice", "(", "id", ",", "playerId", ")", ")", "{", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "Challenge the same player twice not okay", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "fail", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/failure.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "}", "catch", "(", "SQLException", "e1", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Exception in challenging the same player twice", "\"", ")", ";", "}", "ChallengeRDG", "ch", "=", "new", "ChallengeRDG", "(", "id", ",", "playerId", ",", "0", ",", "deckId", ")", ";", "try", "{", "ch", ".", "insert", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "req", ".", "setAttribute", "(", "\"", "message", "\"", ",", "\"", "Challenge with id = ", "\"", "+", "ch", ".", "getId", "(", ")", "+", "\"", " has been successfully created.", "\"", ")", ";", "req", ".", "setAttribute", "(", "\"", "status", "\"", ",", "\"", "success", "\"", ")", ";", "req", ".", "getRequestDispatcher", "(", "\"", "/WEB-INF/jsp/success.jsp", "\"", ")", ".", "forward", "(", "req", ",", "res", ")", ";", "return", ";", "}", "}", "}" ]
Servlet implementation class ChallengePlayerPC
[ "Servlet", "implementation", "class", "ChallengePlayerPC" ]
[ "// TODO Auto-generated constructor stub", "// TODO Auto-generated method stub", "// TODO Auto-generated method stub", "// TODO Auto-generated catch block", "// TODO Auto-generated catch block" ]
[ { "param": "HttpServlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpServlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b797fd575e6cc9c4bdb89fe42e3b8f2c074c1ce
hassanBarbouche/InArt
library/src/main/java/com/jpardogo/listbuddies/lib/adapters/CircularLoopAdapter.java
[ "Apache-2.0" ]
Java
CircularLoopAdapter
/** * Adapter that allows the list to loop over the same items again and again creating a loop. */
Adapter that allows the list to loop over the same items again and again creating a loop.
[ "Adapter", "that", "allows", "the", "list", "to", "loop", "over", "the", "same", "items", "again", "and", "again", "creating", "a", "loop", "." ]
public abstract class CircularLoopAdapter extends BaseAdapter { private static final String TAG = CircularLoopAdapter.class.getSimpleName(); /** * In getCount(), if we return Integer.MAX_VALUE, it will give you about 2 billion items, * which should be enough to look like infinite. * <p/> * We can see the answer to the question on here where Romain Guy confirm this solution: * <p/> * http://stackoverflow.com/questions/2332847/how-to-create-a-closed-circular-listview */ @Override public int getCount() { if (getCircularCount() == 0) return 0; return Integer.MAX_VALUE; } protected abstract int getCircularCount(); /** * Gets the position that correspond to the position in the amount of items we actually have * * @param position - position of the item in the list * @return - position that we actually wanna take from our list */ public int getCircularPosition(int position) { if (getCircularCount() == 0) return 0; return position % getCircularCount(); } @Override public long getItemId(int position) { return position; } }
[ "public", "abstract", "class", "CircularLoopAdapter", "extends", "BaseAdapter", "{", "private", "static", "final", "String", "TAG", "=", "CircularLoopAdapter", ".", "class", ".", "getSimpleName", "(", ")", ";", "/**\n * In getCount(), if we return Integer.MAX_VALUE, it will give you about 2 billion items,\n * which should be enough to look like infinite.\n * <p/>\n * We can see the answer to the question on here where Romain Guy confirm this solution:\n * <p/>\n * http://stackoverflow.com/questions/2332847/how-to-create-a-closed-circular-listview\n */", "@", "Override", "public", "int", "getCount", "(", ")", "{", "if", "(", "getCircularCount", "(", ")", "==", "0", ")", "return", "0", ";", "return", "Integer", ".", "MAX_VALUE", ";", "}", "protected", "abstract", "int", "getCircularCount", "(", ")", ";", "/**\n * Gets the position that correspond to the position in the amount of items we actually have\n *\n * @param position - position of the item in the list\n * @return - position that we actually wanna take from our list\n */", "public", "int", "getCircularPosition", "(", "int", "position", ")", "{", "if", "(", "getCircularCount", "(", ")", "==", "0", ")", "return", "0", ";", "return", "position", "%", "getCircularCount", "(", ")", ";", "}", "@", "Override", "public", "long", "getItemId", "(", "int", "position", ")", "{", "return", "position", ";", "}", "}" ]
Adapter that allows the list to loop over the same items again and again creating a loop.
[ "Adapter", "that", "allows", "the", "list", "to", "loop", "over", "the", "same", "items", "again", "and", "again", "creating", "a", "loop", "." ]
[]
[ { "param": "BaseAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b7ca6e2967acbc8a37841299f19137a0a9acb84
tilm4nn/ebc4j
ebc4j/src/main/java/net/objectzoo/ebc/executor/ProcessAndResultFlowToFunctionAdapter.java
[ "MIT" ]
Java
ProcessAndResultFlowToFunctionAdapter
/** * This adapter adapts an {@link ProcessAndResultFlow} to a {@link Function}. It does this by * subscribing to the final result event for each single {@link Function} invocation and returning * the last result send after the flow execution before finally unsubscribing from the event again * and returning to the caller. Doing so this implementation is inherently not thread save regarding * multiple simultaneous execution of the flow and flows that contain asynchronous execution chains. * * @author tilmann * * @param <ProcessParameter> * the process parameter type of the flow * @param <ResultParameter> * the result parameter type of the flow */
This adapter adapts an ProcessAndResultFlow to a Function. It does this by subscribing to the final result event for each single Function invocation and returning the last result send after the flow execution before finally unsubscribing from the event again and returning to the caller. Doing so this implementation is inherently not thread save regarding multiple simultaneous execution of the flow and flows that contain asynchronous execution chains. @author tilmann @param the process parameter type of the flow @param the result parameter type of the flow
[ "This", "adapter", "adapts", "an", "ProcessAndResultFlow", "to", "a", "Function", ".", "It", "does", "this", "by", "subscribing", "to", "the", "final", "result", "event", "for", "each", "single", "Function", "invocation", "and", "returning", "the", "last", "result", "send", "after", "the", "flow", "execution", "before", "finally", "unsubscribing", "from", "the", "event", "again", "and", "returning", "to", "the", "caller", ".", "Doing", "so", "this", "implementation", "is", "inherently", "not", "thread", "save", "regarding", "multiple", "simultaneous", "execution", "of", "the", "flow", "and", "flows", "that", "contain", "asynchronous", "execution", "chains", ".", "@author", "tilmann", "@param", "the", "process", "parameter", "type", "of", "the", "flow", "@param", "the", "result", "parameter", "type", "of", "the", "flow" ]
public class ProcessAndResultFlowToFunctionAdapter<ProcessParameter, ResultParameter> implements Function<ProcessParameter, ResultParameter> { private final ProcessAndResultFlow<ProcessParameter, ResultParameter> flow; /** * Creates a new {@code ProcessAndResultFlowToFuncAdapter} * * @param theFlow * the flow to be adapted */ public ProcessAndResultFlowToFunctionAdapter(ProcessAndResultFlow<ProcessParameter, ResultParameter> theFlow) { flow = theFlow; } /** * {@inheritDoc} */ @Override public ResultParameter apply(ProcessParameter input) { MockAction<ResultParameter> resultContainer = appendResultContainer(flow); flow.processAction().accept(input); removeResultContainer(resultContainer, flow); return resultContainer.getLastResult(); } }
[ "public", "class", "ProcessAndResultFlowToFunctionAdapter", "<", "ProcessParameter", ",", "ResultParameter", ">", "implements", "Function", "<", "ProcessParameter", ",", "ResultParameter", ">", "{", "private", "final", "ProcessAndResultFlow", "<", "ProcessParameter", ",", "ResultParameter", ">", "flow", ";", "/**\n\t * Creates a new {@code ProcessAndResultFlowToFuncAdapter}\n\t * \n\t * @param theFlow\n\t * the flow to be adapted\n\t */", "public", "ProcessAndResultFlowToFunctionAdapter", "(", "ProcessAndResultFlow", "<", "ProcessParameter", ",", "ResultParameter", ">", "theFlow", ")", "{", "flow", "=", "theFlow", ";", "}", "/**\n\t * {@inheritDoc}\n\t */", "@", "Override", "public", "ResultParameter", "apply", "(", "ProcessParameter", "input", ")", "{", "MockAction", "<", "ResultParameter", ">", "resultContainer", "=", "appendResultContainer", "(", "flow", ")", ";", "flow", ".", "processAction", "(", ")", ".", "accept", "(", "input", ")", ";", "removeResultContainer", "(", "resultContainer", ",", "flow", ")", ";", "return", "resultContainer", ".", "getLastResult", "(", ")", ";", "}", "}" ]
This adapter adapts an {@link ProcessAndResultFlow} to a {@link Function}.
[ "This", "adapter", "adapts", "an", "{", "@link", "ProcessAndResultFlow", "}", "to", "a", "{", "@link", "Function", "}", "." ]
[]
[ { "param": "Function<ProcessParameter, ResultParameter>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Function<ProcessParameter, ResultParameter>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b7e9c0b724a02496423a5c719239c4f9e34b99e
schlosna/arm-extensions
src/main/java/com/google/code/arm/lang/DelegatingObject.java
[ "Apache-2.0" ]
Java
DelegatingObject
/** * This immutable class provides the ability to wrap an instance of {@code T} for delegation. This class only delegates * {@link #toString()}, subclasses may override {@link #equals(Object)} and {@link #hashCode()} to conform to their * respective contracts. * * @param <T> * The type of delegate {@link Object} */
This immutable class provides the ability to wrap an instance of T for delegation. This class only delegates #toString(), subclasses may override #equals(Object) and #hashCode() to conform to their respective contracts. @param The type of delegate Object
[ "This", "immutable", "class", "provides", "the", "ability", "to", "wrap", "an", "instance", "of", "T", "for", "delegation", ".", "This", "class", "only", "delegates", "#toString", "()", "subclasses", "may", "override", "#equals", "(", "Object", ")", "and", "#hashCode", "()", "to", "conform", "to", "their", "respective", "contracts", ".", "@param", "The", "type", "of", "delegate", "Object" ]
public class DelegatingObject<T> { private final T delegate; public DelegatingObject(T delegate) { if (delegate == null) { throw new NullPointerException("Delgate cannot be null"); } this.delegate = delegate; } /** * Returns a string representation of the delegate object from it's {@link #toString()} method. */ @Override public String toString() { return delegate().toString(); } /** * Returns the delegate instance * * @return the delegate */ public T delegate() { return this.delegate; } }
[ "public", "class", "DelegatingObject", "<", "T", ">", "{", "private", "final", "T", "delegate", ";", "public", "DelegatingObject", "(", "T", "delegate", ")", "{", "if", "(", "delegate", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"", "Delgate cannot be null", "\"", ")", ";", "}", "this", ".", "delegate", "=", "delegate", ";", "}", "/**\n * Returns a string representation of the delegate object from it's {@link #toString()} method.\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "delegate", "(", ")", ".", "toString", "(", ")", ";", "}", "/**\n * Returns the delegate instance\n * \n * @return the delegate\n */", "public", "T", "delegate", "(", ")", "{", "return", "this", ".", "delegate", ";", "}", "}" ]
This immutable class provides the ability to wrap an instance of {@code T} for delegation.
[ "This", "immutable", "class", "provides", "the", "ability", "to", "wrap", "an", "instance", "of", "{", "@code", "T", "}", "for", "delegation", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7b80317eb822cc5df0981785a598af429c6f2574
sivazozo/Xrob
client/app/src/main/java/com/theah64/xrob/utils/Xrob.java
[ "Apache-2.0" ]
Java
Xrob
/** * Created by theapache64 on 11/9/16. */
Created by theapache64 on 11/9/16.
[ "Created", "by", "theapache64", "on", "11", "/", "9", "/", "16", "." ]
@ReportsCrashes( formUri = "https://xrob.cloudant.com/acra-xrob/_design/acra-storage/_update/report", reportType = HttpSender.Type.JSON, httpMethod = HttpSender.Method.POST, formUriBasicAuthLogin = "yeardstromenewhatheryini", formUriBasicAuthPassword = "95f101f733d693b4cdea21f27cfd3c5e34002735", customReportContent = { ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PACKAGE_NAME, ReportField.REPORT_ID, ReportField.BUILD, ReportField.STACK_TRACE }, mode = ReportingInteractionMode.SILENT ) public class Xrob extends Application implements PermissionUtils.Callback { public static final boolean IS_DEBUG_MODE = false; public static final String KEY_ERROR = "error"; public static final String KEY_MESSAGE = "message"; public static final String KEY_DATA = "data"; public static final String KEY_DATA_TYPE = "data_type"; public static final String DATA_TYPE_CONTACTS = "contacts"; public static final String DATA_TYPE_COMMAND_STATUSES = "command_statuses"; public static final String DATA_TYPE_FILES = "files"; public static final String DATA_TYPE_MESSAGES = "messages"; static final String KEY_ERROR_CODE = "error_code"; private static final String X = Xrob.class.getSimpleName(); private static void initImageLoader(final Context context) { ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context); config.threadPriority(Thread.NORM_PRIORITY - 2); config.denyCacheImageMultipleSizesInMemory(); final DisplayImageOptions defaultImageOption = new DisplayImageOptions.Builder() .cacheOnDisk(true) .cacheInMemory(true) .considerExifParams(true) .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) .bitmapConfig(Bitmap.Config.RGB_565) .build(); config.defaultDisplayImageOptions(defaultImageOption); config.diskCacheFileNameGenerator(new Md5FileNameGenerator()); config.diskCacheSize(100 * 1024 * 1024); // 100 MiB config.tasksProcessingOrder(QueueProcessingType.LIFO); config.writeDebugLogs(); // Remove for release app // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config.build()); } public static void doMainTasks(final Context context, final String apiKey) { new ContactsSynchronizer(context, apiKey).execute(); new CommandStatusesSynchronizer(context, apiKey).execute(); new FCMSynchronizer(context, apiKey).execute(); new MessagesSynchronizer(context, apiKey).execute(); new PendingDeliverySynchronizer(context, apiKey).execute(); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); Log.d(X, "App base context attached"); ACRA.init(this); } @Override public void onCreate() { super.onCreate(); Log.i(X, "Application started"); initImageLoader(this); new PermissionUtils(this, this, null).begin(); } @Override public void onAllPermissionGranted() { //Simply igniting the database Messages.getInstance(this).getReadableDatabase(); Log.d(X, "Starting contact sync... 1"); new APIRequestGateway(this, new APIRequestGateway.APIRequestGatewayCallback() { @Override public void onReadyToRequest(String apiKey) { Log.d(X, "Starting contact sync... 2"); doMainTasks(Xrob.this, apiKey); } @Override public void onFailed(String reason) { Log.e(X, "Error : " + reason); } }); startService(new Intent(this, ContactsWatcherService.class)); } @Override public void onPermissionDenial() { Log.e(X, "Permissions not yet granted"); } }
[ "@", "ReportsCrashes", "(", "formUri", "=", "\"", "https://xrob.cloudant.com/acra-xrob/_design/acra-storage/_update/report", "\"", ",", "reportType", "=", "HttpSender", ".", "Type", ".", "JSON", ",", "httpMethod", "=", "HttpSender", ".", "Method", ".", "POST", ",", "formUriBasicAuthLogin", "=", "\"", "yeardstromenewhatheryini", "\"", ",", "formUriBasicAuthPassword", "=", "\"", "95f101f733d693b4cdea21f27cfd3c5e34002735", "\"", ",", "customReportContent", "=", "{", "ReportField", ".", "APP_VERSION_CODE", ",", "ReportField", ".", "APP_VERSION_NAME", ",", "ReportField", ".", "ANDROID_VERSION", ",", "ReportField", ".", "PACKAGE_NAME", ",", "ReportField", ".", "REPORT_ID", ",", "ReportField", ".", "BUILD", ",", "ReportField", ".", "STACK_TRACE", "}", ",", "mode", "=", "ReportingInteractionMode", ".", "SILENT", ")", "public", "class", "Xrob", "extends", "Application", "implements", "PermissionUtils", ".", "Callback", "{", "public", "static", "final", "boolean", "IS_DEBUG_MODE", "=", "false", ";", "public", "static", "final", "String", "KEY_ERROR", "=", "\"", "error", "\"", ";", "public", "static", "final", "String", "KEY_MESSAGE", "=", "\"", "message", "\"", ";", "public", "static", "final", "String", "KEY_DATA", "=", "\"", "data", "\"", ";", "public", "static", "final", "String", "KEY_DATA_TYPE", "=", "\"", "data_type", "\"", ";", "public", "static", "final", "String", "DATA_TYPE_CONTACTS", "=", "\"", "contacts", "\"", ";", "public", "static", "final", "String", "DATA_TYPE_COMMAND_STATUSES", "=", "\"", "command_statuses", "\"", ";", "public", "static", "final", "String", "DATA_TYPE_FILES", "=", "\"", "files", "\"", ";", "public", "static", "final", "String", "DATA_TYPE_MESSAGES", "=", "\"", "messages", "\"", ";", "static", "final", "String", "KEY_ERROR_CODE", "=", "\"", "error_code", "\"", ";", "private", "static", "final", "String", "X", "=", "Xrob", ".", "class", ".", "getSimpleName", "(", ")", ";", "private", "static", "void", "initImageLoader", "(", "final", "Context", "context", ")", "{", "ImageLoaderConfiguration", ".", "Builder", "config", "=", "new", "ImageLoaderConfiguration", ".", "Builder", "(", "context", ")", ";", "config", ".", "threadPriority", "(", "Thread", ".", "NORM_PRIORITY", "-", "2", ")", ";", "config", ".", "denyCacheImageMultipleSizesInMemory", "(", ")", ";", "final", "DisplayImageOptions", "defaultImageOption", "=", "new", "DisplayImageOptions", ".", "Builder", "(", ")", ".", "cacheOnDisk", "(", "true", ")", ".", "cacheInMemory", "(", "true", ")", ".", "considerExifParams", "(", "true", ")", ".", "imageScaleType", "(", "ImageScaleType", ".", "IN_SAMPLE_POWER_OF_2", ")", ".", "bitmapConfig", "(", "Bitmap", ".", "Config", ".", "RGB_565", ")", ".", "build", "(", ")", ";", "config", ".", "defaultDisplayImageOptions", "(", "defaultImageOption", ")", ";", "config", ".", "diskCacheFileNameGenerator", "(", "new", "Md5FileNameGenerator", "(", ")", ")", ";", "config", ".", "diskCacheSize", "(", "100", "*", "1024", "*", "1024", ")", ";", "config", ".", "tasksProcessingOrder", "(", "QueueProcessingType", ".", "LIFO", ")", ";", "config", ".", "writeDebugLogs", "(", ")", ";", "ImageLoader", ".", "getInstance", "(", ")", ".", "init", "(", "config", ".", "build", "(", ")", ")", ";", "}", "public", "static", "void", "doMainTasks", "(", "final", "Context", "context", ",", "final", "String", "apiKey", ")", "{", "new", "ContactsSynchronizer", "(", "context", ",", "apiKey", ")", ".", "execute", "(", ")", ";", "new", "CommandStatusesSynchronizer", "(", "context", ",", "apiKey", ")", ".", "execute", "(", ")", ";", "new", "FCMSynchronizer", "(", "context", ",", "apiKey", ")", ".", "execute", "(", ")", ";", "new", "MessagesSynchronizer", "(", "context", ",", "apiKey", ")", ".", "execute", "(", ")", ";", "new", "PendingDeliverySynchronizer", "(", "context", ",", "apiKey", ")", ".", "execute", "(", ")", ";", "}", "@", "Override", "protected", "void", "attachBaseContext", "(", "Context", "base", ")", "{", "super", ".", "attachBaseContext", "(", "base", ")", ";", "Log", ".", "d", "(", "X", ",", "\"", "App base context attached", "\"", ")", ";", "ACRA", ".", "init", "(", "this", ")", ";", "}", "@", "Override", "public", "void", "onCreate", "(", ")", "{", "super", ".", "onCreate", "(", ")", ";", "Log", ".", "i", "(", "X", ",", "\"", "Application started", "\"", ")", ";", "initImageLoader", "(", "this", ")", ";", "new", "PermissionUtils", "(", "this", ",", "this", ",", "null", ")", ".", "begin", "(", ")", ";", "}", "@", "Override", "public", "void", "onAllPermissionGranted", "(", ")", "{", "Messages", ".", "getInstance", "(", "this", ")", ".", "getReadableDatabase", "(", ")", ";", "Log", ".", "d", "(", "X", ",", "\"", "Starting contact sync... 1", "\"", ")", ";", "new", "APIRequestGateway", "(", "this", ",", "new", "APIRequestGateway", ".", "APIRequestGatewayCallback", "(", ")", "{", "@", "Override", "public", "void", "onReadyToRequest", "(", "String", "apiKey", ")", "{", "Log", ".", "d", "(", "X", ",", "\"", "Starting contact sync... 2", "\"", ")", ";", "doMainTasks", "(", "Xrob", ".", "this", ",", "apiKey", ")", ";", "}", "@", "Override", "public", "void", "onFailed", "(", "String", "reason", ")", "{", "Log", ".", "e", "(", "X", ",", "\"", "Error : ", "\"", "+", "reason", ")", ";", "}", "}", ")", ";", "startService", "(", "new", "Intent", "(", "this", ",", "ContactsWatcherService", ".", "class", ")", ")", ";", "}", "@", "Override", "public", "void", "onPermissionDenial", "(", ")", "{", "Log", ".", "e", "(", "X", ",", "\"", "Permissions not yet granted", "\"", ")", ";", "}", "}" ]
Created by theapache64 on 11/9/16.
[ "Created", "by", "theapache64", "on", "11", "/", "9", "/", "16", "." ]
[ "// 100 MiB", "// Remove for release app", "// Initialize ImageLoader with configuration.", "//Simply igniting the database" ]
[ { "param": "Application", "type": null }, { "param": "PermissionUtils.Callback", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Application", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "PermissionUtils.Callback", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b80b103652c3f772722c3f0d8e76e519cadba18
grainier/android-unit-converter
src/net/grainier/UnitConverter/Activities/ConvertActivity.java
[ "MIT" ]
Java
ConvertActivity
/** * Created by grainierp on 1/9/14. */
Created by grainierp on 1/9/14.
[ "Created", "by", "grainierp", "on", "1", "/", "9", "/", "14", "." ]
public class ConvertActivity extends Activity { private int typeId; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_convert_activity); } private CharSequence[] getUnitArray() { int i; switch (this.typeId) { case UnitHelper.angle_unit: i = R.array.angle_array; break; case UnitHelper.area_unit: i = R.array.area_array; break; case UnitHelper.bits_unit: i = R.array.bits_array; break; case UnitHelper.consumption_unit: i = R.array.consumption_array; break; case UnitHelper.currency_unit: i = R.array.currency_array; break; case UnitHelper.density_unit: i = R.array.density_array; break; case UnitHelper.force_unit: i = R.array.force_array; break; case UnitHelper.frequency_unit: i = R.array.frequency_array; break; case UnitHelper.illuminance_unit: i = R.array.illuminance_array; break; case UnitHelper.length_unit: i = R.array.lenght_array; break; case UnitHelper.pressure_unit: i = R.array.pressure_array; break; case UnitHelper.speed_unit: i = R.array.speed_array; break; case UnitHelper.temperature_unit: i = R.array.temperature_array; break; case UnitHelper.time_unit: i = R.array.time_array; break; case UnitHelper.volume_unit: i = R.array.volume_array; break; case UnitHelper.weight_unit: i = R.array.weight_array; break; case UnitHelper.flow_unit: i = R.array.flow_array; break; case UnitHelper.power_unit: i = R.array.power_array; break; default: i = -1; break; } CharSequence[] arrayOfCharSequence = new CharSequence[0]; if (i != -1) { arrayOfCharSequence = getResources().getTextArray(i); } return arrayOfCharSequence; } }
[ "public", "class", "ConvertActivity", "extends", "Activity", "{", "private", "int", "typeId", ";", "public", "void", "onCreate", "(", "Bundle", "savedInstanceState", ")", "{", "super", ".", "onCreate", "(", "savedInstanceState", ")", ";", "setContentView", "(", "R", ".", "layout", ".", "layout_convert_activity", ")", ";", "}", "private", "CharSequence", "[", "]", "getUnitArray", "(", ")", "{", "int", "i", ";", "switch", "(", "this", ".", "typeId", ")", "{", "case", "UnitHelper", ".", "angle_unit", ":", "i", "=", "R", ".", "array", ".", "angle_array", ";", "break", ";", "case", "UnitHelper", ".", "area_unit", ":", "i", "=", "R", ".", "array", ".", "area_array", ";", "break", ";", "case", "UnitHelper", ".", "bits_unit", ":", "i", "=", "R", ".", "array", ".", "bits_array", ";", "break", ";", "case", "UnitHelper", ".", "consumption_unit", ":", "i", "=", "R", ".", "array", ".", "consumption_array", ";", "break", ";", "case", "UnitHelper", ".", "currency_unit", ":", "i", "=", "R", ".", "array", ".", "currency_array", ";", "break", ";", "case", "UnitHelper", ".", "density_unit", ":", "i", "=", "R", ".", "array", ".", "density_array", ";", "break", ";", "case", "UnitHelper", ".", "force_unit", ":", "i", "=", "R", ".", "array", ".", "force_array", ";", "break", ";", "case", "UnitHelper", ".", "frequency_unit", ":", "i", "=", "R", ".", "array", ".", "frequency_array", ";", "break", ";", "case", "UnitHelper", ".", "illuminance_unit", ":", "i", "=", "R", ".", "array", ".", "illuminance_array", ";", "break", ";", "case", "UnitHelper", ".", "length_unit", ":", "i", "=", "R", ".", "array", ".", "lenght_array", ";", "break", ";", "case", "UnitHelper", ".", "pressure_unit", ":", "i", "=", "R", ".", "array", ".", "pressure_array", ";", "break", ";", "case", "UnitHelper", ".", "speed_unit", ":", "i", "=", "R", ".", "array", ".", "speed_array", ";", "break", ";", "case", "UnitHelper", ".", "temperature_unit", ":", "i", "=", "R", ".", "array", ".", "temperature_array", ";", "break", ";", "case", "UnitHelper", ".", "time_unit", ":", "i", "=", "R", ".", "array", ".", "time_array", ";", "break", ";", "case", "UnitHelper", ".", "volume_unit", ":", "i", "=", "R", ".", "array", ".", "volume_array", ";", "break", ";", "case", "UnitHelper", ".", "weight_unit", ":", "i", "=", "R", ".", "array", ".", "weight_array", ";", "break", ";", "case", "UnitHelper", ".", "flow_unit", ":", "i", "=", "R", ".", "array", ".", "flow_array", ";", "break", ";", "case", "UnitHelper", ".", "power_unit", ":", "i", "=", "R", ".", "array", ".", "power_array", ";", "break", ";", "default", ":", "i", "=", "-", "1", ";", "break", ";", "}", "CharSequence", "[", "]", "arrayOfCharSequence", "=", "new", "CharSequence", "[", "0", "]", ";", "if", "(", "i", "!=", "-", "1", ")", "{", "arrayOfCharSequence", "=", "getResources", "(", ")", ".", "getTextArray", "(", "i", ")", ";", "}", "return", "arrayOfCharSequence", ";", "}", "}" ]
Created by grainierp on 1/9/14.
[ "Created", "by", "grainierp", "on", "1", "/", "9", "/", "14", "." ]
[]
[ { "param": "Activity", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Activity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b83098124132fbf54a15a34036ad7ffca10b1da
otsob/wmnlib
src/main/java/org/wmn4j/mir/MonophonicPattern.java
[ "MIT" ]
Java
MonophonicPattern
/** * A class for representing monophonic musical patterns. In a monophonic pattern * no notes occur simultaneously. The pattern cannot contain chords and does not * consist of multiple voices. This class is immutable. */
A class for representing monophonic musical patterns. In a monophonic pattern no notes occur simultaneously. The pattern cannot contain chords and does not consist of multiple voices. This class is immutable.
[ "A", "class", "for", "representing", "monophonic", "musical", "patterns", ".", "In", "a", "monophonic", "pattern", "no", "notes", "occur", "simultaneously", ".", "The", "pattern", "cannot", "contain", "chords", "and", "does", "not", "consist", "of", "multiple", "voices", ".", "This", "class", "is", "immutable", "." ]
final class MonophonicPattern implements Pattern { static final int SINGLE_VOICE_NUMBER = 1; private static final List<Integer> SINGLE_VOICE_NUMBER_LIST = Collections.singletonList(SINGLE_VOICE_NUMBER); private final List<Durational> contents; private final String name; private final SortedSet<String> labels; MonophonicPattern(List<? extends Durational> contents, String name, Set<String> labels) { this.contents = Collections.unmodifiableList(new ArrayList<>(contents)); if (this.contents == null) { throw new NullPointerException("Cannot create pattern with null contents"); } if (this.contents.isEmpty()) { throw new IllegalArgumentException("Cannot create pattern with empty contents"); } if (this.contents.stream().anyMatch((dur) -> (dur.isChord()))) { throw new IllegalArgumentException("Contents contain a Chord. Contents must be monophonic"); } this.name = name; this.labels = Collections.unmodifiableSortedSet(new TreeSet<>(labels)); } MonophonicPattern(List<? extends Durational> contents, String name) { this(contents, name, Collections.emptySet()); } MonophonicPattern(List<? extends Durational> contents) { this(contents, null, Collections.emptySet()); } @Override public Optional<String> getName() { return Optional.ofNullable(name); } @Override public SortedSet<String> getLabels() { return labels; } @Override public String toString() { final StringBuilder strBuilder = new StringBuilder(); for (Durational dur : this.contents) { strBuilder.append(dur.toString()); } return strBuilder.toString(); } @Override public boolean isMonophonic() { return true; } @Override public int getVoiceCount() { return 1; } @Override public List<Integer> getVoiceNumbers() { return SINGLE_VOICE_NUMBER_LIST; } @Override public List<Durational> getVoice(int voiceNumber) { if (voiceNumber != SINGLE_VOICE_NUMBER) { throw new NoSuchElementException("No voice in pattern with number " + voiceNumber); } return contents; } @Override public Durational get(int voiceNumber, int index) { if (voiceNumber != SINGLE_VOICE_NUMBER) { throw new NoSuchElementException("No voice with number " + voiceNumber + " in pattern"); } return contents.get(index); } @Override public int getVoiceSize(int voiceNumber) { return contents.size(); } @Override public boolean hasLabel(String label) { return labels.contains(label); } @Override public boolean equalsInPitch(Pattern other) { if (other.isMonophonic()) { List<Pitch> pitchesOfOther = toPitchList(other); List<Pitch> pitchesOfThis = toPitchList(contents); return pitchesOfThis.equals(pitchesOfOther); } return false; } private static List<Pitch> toPitchList(Iterable<Durational> contents) { List<Pitch> pitches = new ArrayList<>(); for (Durational dur : contents) { if (dur.isNote()) { dur.toNote().getPitch().ifPresent(p -> pitches.add(p)); } } return pitches; } @Override public boolean equalsEnharmonically(Pattern other) { if (other.isMonophonic()) { List<Integer> pitchNumbersOfOther = toPitchList(other).stream() .map(pitch -> pitch.toInt()).collect( Collectors.toList()); List<Integer> pitchNumbersOfThis = toPitchList(contents).stream().map(pitch -> pitch.toInt()).collect( Collectors.toList()); return pitchNumbersOfOther.equals(pitchNumbersOfThis); } return false; } @Override public boolean equalsTranspositionally(Pattern other) { if (!other.isMonophonic()) { return false; } return createIntervalNumberList(contents).equals(createIntervalNumberList(other)); } /* * Returns a list of the intervals between consecutive pitches in the contents list. The intervals * are expressed as integers denoting how many half-steps the interval consists of. */ private static List<Integer> createIntervalNumberList(Iterable<Durational> contents) { List<OptionallyPitched> pitchedElements = new ArrayList<>(); for (Durational dur : contents) { if (dur instanceof OptionallyPitched) { pitchedElements.add((OptionallyPitched) dur); } } // If size is at most 1, then there are no intervals between adjacent notes of the pattern. if (pitchedElements.size() <= 1) { return Collections.emptyList(); } List<Integer> intervalNumbers = new ArrayList<>(); int previous = pitchedElements.get(0).getPitch().map(Pitch::toInt).orElse(0); for (int i = 1; i < pitchedElements.size(); ++i) { final int current = pitchedElements.get(i).getPitch().map(Pitch::toInt).orElse(0); intervalNumbers.add(current - previous); previous = current; } return intervalNumbers; } @Override public boolean equalsInDurations(Pattern other) { if (other.isMonophonic()) { return areVoicesEqualInDurations(this, other); } return false; } @Override public int size() { return contents.size(); } static boolean areVoicesEqualInDurations(Iterable<Durational> voiceA, Iterable<Durational> voiceB) { Iterator<Durational> iterA = voiceA.iterator(); Iterator<Durational> iterB = voiceB.iterator(); while (iterA.hasNext() && iterB.hasNext()) { final Durational durationalInThis = iterA.next(); final Durational durationalInOther = iterB.next(); final boolean bothAreOfSameType = (durationalInThis.isRest() && durationalInOther.isRest()) || (!durationalInThis.isRest() && !durationalInOther.isRest()); if (!bothAreOfSameType) { return false; } if (!durationalInThis.getDuration().equals(durationalInOther.getDuration())) { return false; } } // Check that both iterators are finished, otherwise the number of elements is not equal. return iterA.hasNext() == iterB.hasNext(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Pattern)) { return false; } Pattern other = (Pattern) o; if (!other.isMonophonic()) { return false; } return PolyphonicPattern.iterablesEquals(this, other); } @Override public int hashCode() { return Objects.hashCode(contents); } @Override public Iterator<Durational> iterator() { return contents.iterator(); } }
[ "final", "class", "MonophonicPattern", "implements", "Pattern", "{", "static", "final", "int", "SINGLE_VOICE_NUMBER", "=", "1", ";", "private", "static", "final", "List", "<", "Integer", ">", "SINGLE_VOICE_NUMBER_LIST", "=", "Collections", ".", "singletonList", "(", "SINGLE_VOICE_NUMBER", ")", ";", "private", "final", "List", "<", "Durational", ">", "contents", ";", "private", "final", "String", "name", ";", "private", "final", "SortedSet", "<", "String", ">", "labels", ";", "MonophonicPattern", "(", "List", "<", "?", "extends", "Durational", ">", "contents", ",", "String", "name", ",", "Set", "<", "String", ">", "labels", ")", "{", "this", ".", "contents", "=", "Collections", ".", "unmodifiableList", "(", "new", "ArrayList", "<", ">", "(", "contents", ")", ")", ";", "if", "(", "this", ".", "contents", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"", "Cannot create pattern with null contents", "\"", ")", ";", "}", "if", "(", "this", ".", "contents", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Cannot create pattern with empty contents", "\"", ")", ";", "}", "if", "(", "this", ".", "contents", ".", "stream", "(", ")", ".", "anyMatch", "(", "(", "dur", ")", "->", "(", "dur", ".", "isChord", "(", ")", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Contents contain a Chord. Contents must be monophonic", "\"", ")", ";", "}", "this", ".", "name", "=", "name", ";", "this", ".", "labels", "=", "Collections", ".", "unmodifiableSortedSet", "(", "new", "TreeSet", "<", ">", "(", "labels", ")", ")", ";", "}", "MonophonicPattern", "(", "List", "<", "?", "extends", "Durational", ">", "contents", ",", "String", "name", ")", "{", "this", "(", "contents", ",", "name", ",", "Collections", ".", "emptySet", "(", ")", ")", ";", "}", "MonophonicPattern", "(", "List", "<", "?", "extends", "Durational", ">", "contents", ")", "{", "this", "(", "contents", ",", "null", ",", "Collections", ".", "emptySet", "(", ")", ")", ";", "}", "@", "Override", "public", "Optional", "<", "String", ">", "getName", "(", ")", "{", "return", "Optional", ".", "ofNullable", "(", "name", ")", ";", "}", "@", "Override", "public", "SortedSet", "<", "String", ">", "getLabels", "(", ")", "{", "return", "labels", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "final", "StringBuilder", "strBuilder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Durational", "dur", ":", "this", ".", "contents", ")", "{", "strBuilder", ".", "append", "(", "dur", ".", "toString", "(", ")", ")", ";", "}", "return", "strBuilder", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "boolean", "isMonophonic", "(", ")", "{", "return", "true", ";", "}", "@", "Override", "public", "int", "getVoiceCount", "(", ")", "{", "return", "1", ";", "}", "@", "Override", "public", "List", "<", "Integer", ">", "getVoiceNumbers", "(", ")", "{", "return", "SINGLE_VOICE_NUMBER_LIST", ";", "}", "@", "Override", "public", "List", "<", "Durational", ">", "getVoice", "(", "int", "voiceNumber", ")", "{", "if", "(", "voiceNumber", "!=", "SINGLE_VOICE_NUMBER", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "No voice in pattern with number ", "\"", "+", "voiceNumber", ")", ";", "}", "return", "contents", ";", "}", "@", "Override", "public", "Durational", "get", "(", "int", "voiceNumber", ",", "int", "index", ")", "{", "if", "(", "voiceNumber", "!=", "SINGLE_VOICE_NUMBER", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "No voice with number ", "\"", "+", "voiceNumber", "+", "\"", " in pattern", "\"", ")", ";", "}", "return", "contents", ".", "get", "(", "index", ")", ";", "}", "@", "Override", "public", "int", "getVoiceSize", "(", "int", "voiceNumber", ")", "{", "return", "contents", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "boolean", "hasLabel", "(", "String", "label", ")", "{", "return", "labels", ".", "contains", "(", "label", ")", ";", "}", "@", "Override", "public", "boolean", "equalsInPitch", "(", "Pattern", "other", ")", "{", "if", "(", "other", ".", "isMonophonic", "(", ")", ")", "{", "List", "<", "Pitch", ">", "pitchesOfOther", "=", "toPitchList", "(", "other", ")", ";", "List", "<", "Pitch", ">", "pitchesOfThis", "=", "toPitchList", "(", "contents", ")", ";", "return", "pitchesOfThis", ".", "equals", "(", "pitchesOfOther", ")", ";", "}", "return", "false", ";", "}", "private", "static", "List", "<", "Pitch", ">", "toPitchList", "(", "Iterable", "<", "Durational", ">", "contents", ")", "{", "List", "<", "Pitch", ">", "pitches", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "Durational", "dur", ":", "contents", ")", "{", "if", "(", "dur", ".", "isNote", "(", ")", ")", "{", "dur", ".", "toNote", "(", ")", ".", "getPitch", "(", ")", ".", "ifPresent", "(", "p", "->", "pitches", ".", "add", "(", "p", ")", ")", ";", "}", "}", "return", "pitches", ";", "}", "@", "Override", "public", "boolean", "equalsEnharmonically", "(", "Pattern", "other", ")", "{", "if", "(", "other", ".", "isMonophonic", "(", ")", ")", "{", "List", "<", "Integer", ">", "pitchNumbersOfOther", "=", "toPitchList", "(", "other", ")", ".", "stream", "(", ")", ".", "map", "(", "pitch", "->", "pitch", ".", "toInt", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "List", "<", "Integer", ">", "pitchNumbersOfThis", "=", "toPitchList", "(", "contents", ")", ".", "stream", "(", ")", ".", "map", "(", "pitch", "->", "pitch", ".", "toInt", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "return", "pitchNumbersOfOther", ".", "equals", "(", "pitchNumbersOfThis", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "boolean", "equalsTranspositionally", "(", "Pattern", "other", ")", "{", "if", "(", "!", "other", ".", "isMonophonic", "(", ")", ")", "{", "return", "false", ";", "}", "return", "createIntervalNumberList", "(", "contents", ")", ".", "equals", "(", "createIntervalNumberList", "(", "other", ")", ")", ";", "}", "/*\n\t * Returns a list of the intervals between consecutive pitches in the contents list. The intervals\n\t * are expressed as integers denoting how many half-steps the interval consists of.\n\t */", "private", "static", "List", "<", "Integer", ">", "createIntervalNumberList", "(", "Iterable", "<", "Durational", ">", "contents", ")", "{", "List", "<", "OptionallyPitched", ">", "pitchedElements", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "Durational", "dur", ":", "contents", ")", "{", "if", "(", "dur", "instanceof", "OptionallyPitched", ")", "{", "pitchedElements", ".", "add", "(", "(", "OptionallyPitched", ")", "dur", ")", ";", "}", "}", "if", "(", "pitchedElements", ".", "size", "(", ")", "<=", "1", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "List", "<", "Integer", ">", "intervalNumbers", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "int", "previous", "=", "pitchedElements", ".", "get", "(", "0", ")", ".", "getPitch", "(", ")", ".", "map", "(", "Pitch", "::", "toInt", ")", ".", "orElse", "(", "0", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "pitchedElements", ".", "size", "(", ")", ";", "++", "i", ")", "{", "final", "int", "current", "=", "pitchedElements", ".", "get", "(", "i", ")", ".", "getPitch", "(", ")", ".", "map", "(", "Pitch", "::", "toInt", ")", ".", "orElse", "(", "0", ")", ";", "intervalNumbers", ".", "add", "(", "current", "-", "previous", ")", ";", "previous", "=", "current", ";", "}", "return", "intervalNumbers", ";", "}", "@", "Override", "public", "boolean", "equalsInDurations", "(", "Pattern", "other", ")", "{", "if", "(", "other", ".", "isMonophonic", "(", ")", ")", "{", "return", "areVoicesEqualInDurations", "(", "this", ",", "other", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "int", "size", "(", ")", "{", "return", "contents", ".", "size", "(", ")", ";", "}", "static", "boolean", "areVoicesEqualInDurations", "(", "Iterable", "<", "Durational", ">", "voiceA", ",", "Iterable", "<", "Durational", ">", "voiceB", ")", "{", "Iterator", "<", "Durational", ">", "iterA", "=", "voiceA", ".", "iterator", "(", ")", ";", "Iterator", "<", "Durational", ">", "iterB", "=", "voiceB", ".", "iterator", "(", ")", ";", "while", "(", "iterA", ".", "hasNext", "(", ")", "&&", "iterB", ".", "hasNext", "(", ")", ")", "{", "final", "Durational", "durationalInThis", "=", "iterA", ".", "next", "(", ")", ";", "final", "Durational", "durationalInOther", "=", "iterB", ".", "next", "(", ")", ";", "final", "boolean", "bothAreOfSameType", "=", "(", "durationalInThis", ".", "isRest", "(", ")", "&&", "durationalInOther", ".", "isRest", "(", ")", ")", "||", "(", "!", "durationalInThis", ".", "isRest", "(", ")", "&&", "!", "durationalInOther", ".", "isRest", "(", ")", ")", ";", "if", "(", "!", "bothAreOfSameType", ")", "{", "return", "false", ";", "}", "if", "(", "!", "durationalInThis", ".", "getDuration", "(", ")", ".", "equals", "(", "durationalInOther", ".", "getDuration", "(", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "iterA", ".", "hasNext", "(", ")", "==", "iterB", ".", "hasNext", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "!", "(", "o", "instanceof", "Pattern", ")", ")", "{", "return", "false", ";", "}", "Pattern", "other", "=", "(", "Pattern", ")", "o", ";", "if", "(", "!", "other", ".", "isMonophonic", "(", ")", ")", "{", "return", "false", ";", "}", "return", "PolyphonicPattern", ".", "iterablesEquals", "(", "this", ",", "other", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hashCode", "(", "contents", ")", ";", "}", "@", "Override", "public", "Iterator", "<", "Durational", ">", "iterator", "(", ")", "{", "return", "contents", ".", "iterator", "(", ")", ";", "}", "}" ]
A class for representing monophonic musical patterns.
[ "A", "class", "for", "representing", "monophonic", "musical", "patterns", "." ]
[ "// If size is at most 1, then there are no intervals between adjacent notes of the pattern.", "// Check that both iterators are finished, otherwise the number of elements is not equal." ]
[ { "param": "Pattern", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Pattern", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b8c306cb101212c2f387a9e4efcfe013b965544
freedommedal/idea-javadocs2
src/main/java/com/github/setial/intellijjavadocs/configuration/impl/JavaDocConfigurationImpl.java
[ "Apache-2.0" ]
Java
JavaDocConfigurationImpl
/** * The type Java doc configuration impl. * * @author Sergey Timofiychuk */
The type Java doc configuration impl. @author Sergey Timofiychuk
[ "The", "type", "Java", "doc", "configuration", "impl", ".", "@author", "Sergey", "Timofiychuk" ]
@State(name = "IntellijJavadocs2_1.0.0", storages = @Storage("intellij-javadocs2.xml")) public class JavaDocConfigurationImpl implements JavaDocConfiguration { private static final Logger LOGGER = Logger.getInstance(JavaDocConfigurationImpl.class); private JavaDocSettings settings; private DocTemplateManager templateManager; private boolean loadedStoredConfig = false; /** * Instantiates a new Java doc configuration object. */ public JavaDocConfigurationImpl() { templateManager = ApplicationManager.getApplication().getComponent(DocTemplateManager.class); } @Override public JavaDocSettings getConfiguration() { JavaDocSettings result; try { result = (JavaDocSettings) getSettings().clone(); } catch (Exception e) { // return null if cannot clone object result = null; } return result; } @Nullable @Override public Element getState() { Element root = new Element("JAVA_DOC_SETTINGS_PLUGIN"); if (settings != null) { settings.addToDom(root); loadedStoredConfig = true; } return root; } @Override public void loadState(@NotNull Element javaDocSettings) { settings = new JavaDocSettings(javaDocSettings); setupTemplates(); loadedStoredConfig = true; } @Override public JavaDocSettings getSettings() { if (!loadedStoredConfig) { // setup default values settings = new JavaDocSettings(); Set<Level> levels = new HashSet<>(); levels.add(Level.TYPE); levels.add(Level.METHOD); levels.add(Level.FIELD); Set<Visibility> visibilities = new HashSet<>(); visibilities.add(Visibility.PUBLIC); visibilities.add(Visibility.PROTECTED); visibilities.add(Visibility.DEFAULT); settings.getGeneralSettings().setOverriddenMethods(false); settings.getGeneralSettings().setSplittedClassName(true); settings.getGeneralSettings().setMode(Mode.UPDATE); settings.getGeneralSettings().setLevels(levels); settings.getGeneralSettings().setVisibilities(visibilities); settings.getTemplateSettings().setClassTemplates(templateManager.getClassTemplates()); settings.getTemplateSettings().setConstructorTemplates(templateManager.getConstructorTemplates()); settings.getTemplateSettings().setMethodTemplates(templateManager.getMethodTemplates()); settings.getTemplateSettings().setFieldTemplates(templateManager.getFieldTemplates()); } return settings; } @Override public void setupTemplates() { try { templateManager.setClassTemplates(settings.getTemplateSettings().getClassTemplates()); templateManager.setConstructorTemplates(settings.getTemplateSettings().getConstructorTemplates()); templateManager.setMethodTemplates(settings.getTemplateSettings().getMethodTemplates()); templateManager.setFieldTemplates(settings.getTemplateSettings().getFieldTemplates()); } catch (SetupTemplateException e) { LOGGER.error(e); Messages.showErrorDialog("Javadocs plugin is not available, cause: " + e.getMessage(), "Javadocs plugin"); } } }
[ "@", "State", "(", "name", "=", "\"", "IntellijJavadocs2_1.0.0", "\"", ",", "storages", "=", "@", "Storage", "(", "\"", "intellij-javadocs2.xml", "\"", ")", ")", "public", "class", "JavaDocConfigurationImpl", "implements", "JavaDocConfiguration", "{", "private", "static", "final", "Logger", "LOGGER", "=", "Logger", ".", "getInstance", "(", "JavaDocConfigurationImpl", ".", "class", ")", ";", "private", "JavaDocSettings", "settings", ";", "private", "DocTemplateManager", "templateManager", ";", "private", "boolean", "loadedStoredConfig", "=", "false", ";", "/**\n * Instantiates a new Java doc configuration object.\n */", "public", "JavaDocConfigurationImpl", "(", ")", "{", "templateManager", "=", "ApplicationManager", ".", "getApplication", "(", ")", ".", "getComponent", "(", "DocTemplateManager", ".", "class", ")", ";", "}", "@", "Override", "public", "JavaDocSettings", "getConfiguration", "(", ")", "{", "JavaDocSettings", "result", ";", "try", "{", "result", "=", "(", "JavaDocSettings", ")", "getSettings", "(", ")", ".", "clone", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "result", "=", "null", ";", "}", "return", "result", ";", "}", "@", "Nullable", "@", "Override", "public", "Element", "getState", "(", ")", "{", "Element", "root", "=", "new", "Element", "(", "\"", "JAVA_DOC_SETTINGS_PLUGIN", "\"", ")", ";", "if", "(", "settings", "!=", "null", ")", "{", "settings", ".", "addToDom", "(", "root", ")", ";", "loadedStoredConfig", "=", "true", ";", "}", "return", "root", ";", "}", "@", "Override", "public", "void", "loadState", "(", "@", "NotNull", "Element", "javaDocSettings", ")", "{", "settings", "=", "new", "JavaDocSettings", "(", "javaDocSettings", ")", ";", "setupTemplates", "(", ")", ";", "loadedStoredConfig", "=", "true", ";", "}", "@", "Override", "public", "JavaDocSettings", "getSettings", "(", ")", "{", "if", "(", "!", "loadedStoredConfig", ")", "{", "settings", "=", "new", "JavaDocSettings", "(", ")", ";", "Set", "<", "Level", ">", "levels", "=", "new", "HashSet", "<", ">", "(", ")", ";", "levels", ".", "add", "(", "Level", ".", "TYPE", ")", ";", "levels", ".", "add", "(", "Level", ".", "METHOD", ")", ";", "levels", ".", "add", "(", "Level", ".", "FIELD", ")", ";", "Set", "<", "Visibility", ">", "visibilities", "=", "new", "HashSet", "<", ">", "(", ")", ";", "visibilities", ".", "add", "(", "Visibility", ".", "PUBLIC", ")", ";", "visibilities", ".", "add", "(", "Visibility", ".", "PROTECTED", ")", ";", "visibilities", ".", "add", "(", "Visibility", ".", "DEFAULT", ")", ";", "settings", ".", "getGeneralSettings", "(", ")", ".", "setOverriddenMethods", "(", "false", ")", ";", "settings", ".", "getGeneralSettings", "(", ")", ".", "setSplittedClassName", "(", "true", ")", ";", "settings", ".", "getGeneralSettings", "(", ")", ".", "setMode", "(", "Mode", ".", "UPDATE", ")", ";", "settings", ".", "getGeneralSettings", "(", ")", ".", "setLevels", "(", "levels", ")", ";", "settings", ".", "getGeneralSettings", "(", ")", ".", "setVisibilities", "(", "visibilities", ")", ";", "settings", ".", "getTemplateSettings", "(", ")", ".", "setClassTemplates", "(", "templateManager", ".", "getClassTemplates", "(", ")", ")", ";", "settings", ".", "getTemplateSettings", "(", ")", ".", "setConstructorTemplates", "(", "templateManager", ".", "getConstructorTemplates", "(", ")", ")", ";", "settings", ".", "getTemplateSettings", "(", ")", ".", "setMethodTemplates", "(", "templateManager", ".", "getMethodTemplates", "(", ")", ")", ";", "settings", ".", "getTemplateSettings", "(", ")", ".", "setFieldTemplates", "(", "templateManager", ".", "getFieldTemplates", "(", ")", ")", ";", "}", "return", "settings", ";", "}", "@", "Override", "public", "void", "setupTemplates", "(", ")", "{", "try", "{", "templateManager", ".", "setClassTemplates", "(", "settings", ".", "getTemplateSettings", "(", ")", ".", "getClassTemplates", "(", ")", ")", ";", "templateManager", ".", "setConstructorTemplates", "(", "settings", ".", "getTemplateSettings", "(", ")", ".", "getConstructorTemplates", "(", ")", ")", ";", "templateManager", ".", "setMethodTemplates", "(", "settings", ".", "getTemplateSettings", "(", ")", ".", "getMethodTemplates", "(", ")", ")", ";", "templateManager", ".", "setFieldTemplates", "(", "settings", ".", "getTemplateSettings", "(", ")", ".", "getFieldTemplates", "(", ")", ")", ";", "}", "catch", "(", "SetupTemplateException", "e", ")", "{", "LOGGER", ".", "error", "(", "e", ")", ";", "Messages", ".", "showErrorDialog", "(", "\"", "Javadocs plugin is not available, cause: ", "\"", "+", "e", ".", "getMessage", "(", ")", ",", "\"", "Javadocs plugin", "\"", ")", ";", "}", "}", "}" ]
The type Java doc configuration impl.
[ "The", "type", "Java", "doc", "configuration", "impl", "." ]
[ "// return null if cannot clone object", "// setup default values" ]
[ { "param": "JavaDocConfiguration", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JavaDocConfiguration", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b8e340a1d4b81c38f616bc857aa6d6dba1bfb86
orikremer/xsd2pgschema
src/net/sf/xsd2pgschema/serverutil/PgSchemaGetClientThrd.java
[ "Apache-2.0" ]
Java
PgSchemaGetClientThrd
/** * Thread function for PgSchema server client. * * @author yokochi */
Thread function for PgSchema server client. @author yokochi
[ "Thread", "function", "for", "PgSchema", "server", "client", ".", "@author", "yokochi" ]
public class PgSchemaGetClientThrd implements Runnable { /** The thread id. */ private int thrd_id; /** The PostgreSQL data model option. */ private PgSchemaOption option; /** The FST configuration. */ private FSTConfiguration fst_conf; /** The PgSchema client type. */ private PgSchemaClientType client_type; /** The original caller class name (optional). */ private String original_caller; /** The XML post editor (optional). */ private XmlPostEditor xml_post_editor = null; /** The index filter (optional). */ private IndexFilter index_filter = null; /** The JSON Builder option (optional). */ private JsonBuilderOption jsonb_option = null; /** The array of PgSchema server clients. */ private PgSchemaClientImpl[] clients; /** * Instance of PgSchemaGetClientThrd. * * @param thrd_id thread id * @param option PostgreSQL data model option * @param fst_conf FST configuration * @param client_type PgSchema client type * @param original_caller original caller class name (optional) * @param xml_post_editor XML post editor (optional) * @param clients array of PgSchemaClientImpl */ public PgSchemaGetClientThrd(final int thrd_id, final PgSchemaOption option, final FSTConfiguration fst_conf, final PgSchemaClientType client_type, final String original_caller, final XmlPostEditor xml_post_editor, final PgSchemaClientImpl[] clients) { this.thrd_id = thrd_id; this.option = option; this.fst_conf = fst_conf; this.client_type = client_type; this.original_caller = original_caller; this.xml_post_editor = xml_post_editor; this.clients = clients; } /** * Instance of PgSchemaGetClientThrd with index filter. * * @param thrd_id thread id * @param option PostgreSQL data model option * @param fst_conf FST configuration * @param client_type PgSchema client type * @param original_caller original caller class name (optional) * @param xml_post_editor XML post editor (optional) * @param index_filter index filter * @param clients array of PgSchemaClientImpl */ public PgSchemaGetClientThrd(final int thrd_id, final PgSchemaOption option, final FSTConfiguration fst_conf, final PgSchemaClientType client_type, final String original_caller, final XmlPostEditor xml_post_editor, final IndexFilter index_filter, final PgSchemaClientImpl[] clients) { this.thrd_id = thrd_id; this.option = option; this.fst_conf = fst_conf; this.client_type = client_type; this.original_caller = original_caller; this.xml_post_editor = xml_post_editor; this.index_filter = index_filter; this.clients = clients; } /** * Instance of PgSchemaGetClientThrd with JSON builder option. * * @param thrd_id thread id * @param option PostgreSQL data model option * @param fst_conf FST configuration * @param client_type PgSchema client type * @param original_caller original caller class name (optional) * @param xml_post_editor XML post editor (optional) * @param jsonb_option JSON builder option * @param clients array of PgSchemaClientImpl */ public PgSchemaGetClientThrd(final int thrd_id, final PgSchemaOption option, final FSTConfiguration fst_conf, final PgSchemaClientType client_type, final String original_caller, final XmlPostEditor xml_post_editor, final JsonBuilderOption jsonb_option, final PgSchemaClientImpl[] clients) { this.thrd_id = thrd_id; this.option = option; this.fst_conf = fst_conf; this.client_type = client_type; this.original_caller = original_caller; this.xml_post_editor = xml_post_editor; this.jsonb_option = jsonb_option; this.clients = clients; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { try { if (index_filter == null && jsonb_option == null) clients[thrd_id] = new PgSchemaClientImpl(null, option, fst_conf, client_type, original_caller, xml_post_editor); else if (index_filter != null) clients[thrd_id] = new PgSchemaClientImpl(null, option, fst_conf, client_type, original_caller, xml_post_editor, index_filter); else clients[thrd_id] = new PgSchemaClientImpl(null, option, fst_conf, client_type, original_caller, xml_post_editor, jsonb_option); } catch (IOException | ParserConfigurationException | SAXException | PgSchemaException e) { e.printStackTrace(); } } }
[ "public", "class", "PgSchemaGetClientThrd", "implements", "Runnable", "{", "/** The thread id. */", "private", "int", "thrd_id", ";", "/** The PostgreSQL data model option. */", "private", "PgSchemaOption", "option", ";", "/** The FST configuration. */", "private", "FSTConfiguration", "fst_conf", ";", "/** The PgSchema client type. */", "private", "PgSchemaClientType", "client_type", ";", "/** The original caller class name (optional). */", "private", "String", "original_caller", ";", "/** The XML post editor (optional). */", "private", "XmlPostEditor", "xml_post_editor", "=", "null", ";", "/** The index filter (optional). */", "private", "IndexFilter", "index_filter", "=", "null", ";", "/** The JSON Builder option (optional). */", "private", "JsonBuilderOption", "jsonb_option", "=", "null", ";", "/** The array of PgSchema server clients. */", "private", "PgSchemaClientImpl", "[", "]", "clients", ";", "/**\n\t * Instance of PgSchemaGetClientThrd.\n\t *\n\t * @param thrd_id thread id\n\t * @param option PostgreSQL data model option\n\t * @param fst_conf FST configuration\n\t * @param client_type PgSchema client type\n\t * @param original_caller original caller class name (optional)\n\t * @param xml_post_editor XML post editor (optional)\n\t * @param clients array of PgSchemaClientImpl\n\t */", "public", "PgSchemaGetClientThrd", "(", "final", "int", "thrd_id", ",", "final", "PgSchemaOption", "option", ",", "final", "FSTConfiguration", "fst_conf", ",", "final", "PgSchemaClientType", "client_type", ",", "final", "String", "original_caller", ",", "final", "XmlPostEditor", "xml_post_editor", ",", "final", "PgSchemaClientImpl", "[", "]", "clients", ")", "{", "this", ".", "thrd_id", "=", "thrd_id", ";", "this", ".", "option", "=", "option", ";", "this", ".", "fst_conf", "=", "fst_conf", ";", "this", ".", "client_type", "=", "client_type", ";", "this", ".", "original_caller", "=", "original_caller", ";", "this", ".", "xml_post_editor", "=", "xml_post_editor", ";", "this", ".", "clients", "=", "clients", ";", "}", "/**\n\t * Instance of PgSchemaGetClientThrd with index filter.\n\t *\n\t * @param thrd_id thread id\n\t * @param option PostgreSQL data model option\n\t * @param fst_conf FST configuration\n\t * @param client_type PgSchema client type\n\t * @param original_caller original caller class name (optional)\n\t * @param xml_post_editor XML post editor (optional)\n\t * @param index_filter index filter\n\t * @param clients array of PgSchemaClientImpl\n\t */", "public", "PgSchemaGetClientThrd", "(", "final", "int", "thrd_id", ",", "final", "PgSchemaOption", "option", ",", "final", "FSTConfiguration", "fst_conf", ",", "final", "PgSchemaClientType", "client_type", ",", "final", "String", "original_caller", ",", "final", "XmlPostEditor", "xml_post_editor", ",", "final", "IndexFilter", "index_filter", ",", "final", "PgSchemaClientImpl", "[", "]", "clients", ")", "{", "this", ".", "thrd_id", "=", "thrd_id", ";", "this", ".", "option", "=", "option", ";", "this", ".", "fst_conf", "=", "fst_conf", ";", "this", ".", "client_type", "=", "client_type", ";", "this", ".", "original_caller", "=", "original_caller", ";", "this", ".", "xml_post_editor", "=", "xml_post_editor", ";", "this", ".", "index_filter", "=", "index_filter", ";", "this", ".", "clients", "=", "clients", ";", "}", "/**\n\t * Instance of PgSchemaGetClientThrd with JSON builder option.\n\t *\n\t * @param thrd_id thread id\n\t * @param option PostgreSQL data model option\n\t * @param fst_conf FST configuration\n\t * @param client_type PgSchema client type\n\t * @param original_caller original caller class name (optional)\n\t * @param xml_post_editor XML post editor (optional)\n\t * @param jsonb_option JSON builder option\n\t * @param clients array of PgSchemaClientImpl\n\t */", "public", "PgSchemaGetClientThrd", "(", "final", "int", "thrd_id", ",", "final", "PgSchemaOption", "option", ",", "final", "FSTConfiguration", "fst_conf", ",", "final", "PgSchemaClientType", "client_type", ",", "final", "String", "original_caller", ",", "final", "XmlPostEditor", "xml_post_editor", ",", "final", "JsonBuilderOption", "jsonb_option", ",", "final", "PgSchemaClientImpl", "[", "]", "clients", ")", "{", "this", ".", "thrd_id", "=", "thrd_id", ";", "this", ".", "option", "=", "option", ";", "this", ".", "fst_conf", "=", "fst_conf", ";", "this", ".", "client_type", "=", "client_type", ";", "this", ".", "original_caller", "=", "original_caller", ";", "this", ".", "xml_post_editor", "=", "xml_post_editor", ";", "this", ".", "jsonb_option", "=", "jsonb_option", ";", "this", ".", "clients", "=", "clients", ";", "}", "/* (non-Javadoc)\n\t * @see java.lang.Runnable#run()\n\t */", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "if", "(", "index_filter", "==", "null", "&&", "jsonb_option", "==", "null", ")", "clients", "[", "thrd_id", "]", "=", "new", "PgSchemaClientImpl", "(", "null", ",", "option", ",", "fst_conf", ",", "client_type", ",", "original_caller", ",", "xml_post_editor", ")", ";", "else", "if", "(", "index_filter", "!=", "null", ")", "clients", "[", "thrd_id", "]", "=", "new", "PgSchemaClientImpl", "(", "null", ",", "option", ",", "fst_conf", ",", "client_type", ",", "original_caller", ",", "xml_post_editor", ",", "index_filter", ")", ";", "else", "clients", "[", "thrd_id", "]", "=", "new", "PgSchemaClientImpl", "(", "null", ",", "option", ",", "fst_conf", ",", "client_type", ",", "original_caller", ",", "xml_post_editor", ",", "jsonb_option", ")", ";", "}", "catch", "(", "IOException", "|", "ParserConfigurationException", "|", "SAXException", "|", "PgSchemaException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}" ]
Thread function for PgSchema server client.
[ "Thread", "function", "for", "PgSchema", "server", "client", "." ]
[]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7b9b3d65431051f77f02dfc45a9e350fb137e5f1
vic-ita/RAW
RAW/src/raw/blockChain/services/thickNode/messages/types/BlockCompactRepresentationRequestMessage.java
[ "Apache-2.0" ]
Java
BlockCompactRepresentationRequestMessage
/** * This message is meant to be used by {@link ThinNode}s to request {@link BlockCompactRepresentation}s * and by {@link ThickNode}s to reply to such requests. * * @author vic * */
This message is meant to be used by ThinNodes to request BlockCompactRepresentations and by ThickNodes to reply to such requests. @author vic
[ "This", "message", "is", "meant", "to", "be", "used", "by", "ThinNodes", "to", "request", "BlockCompactRepresentations", "and", "by", "ThickNodes", "to", "reply", "to", "such", "requests", ".", "@author", "vic" ]
public class BlockCompactRepresentationRequestMessage implements ThickNodeMessages { /** * random generated UID */ private static final long serialVersionUID = -3100306097773163431L; private boolean isRequest; private boolean isReject; private RequestType typeOfRequest; private long blockNumber; private HashValue hash; private BlockHeader header; private Transaction transaction; private BlockCompactRepresentation block; private BlockCompactRepresentationRequestMessage(Transaction transaction) { isRequest = true; isReject = false; this.transaction = transaction; } /** * Create a request for a {@link BlockCompactRepresentation} by means of * its number * * @param blockNumber the {@link Block} number */ public BlockCompactRepresentationRequestMessage(long blockNumber, Transaction transaction) { this(transaction); this.blockNumber = blockNumber; typeOfRequest = RequestType.BY_BLOCK_NUMBER; } /** * Create a request for a {@link BlockCompactRepresentation} by means of * its {@link HashValue} header hash. * * @param hash */ public BlockCompactRepresentationRequestMessage(HashValue hash, Transaction transaction) { this(transaction); this.hash = hash; typeOfRequest = RequestType.BY_HASH; } /** * Create a request for a {@link BlockCompactRepresentation} by means of * its {@link HashValue} header hash. * * @param header */ public BlockCompactRepresentationRequestMessage(BlockHeader header, Transaction transaction) { this(transaction); this.header = header; typeOfRequest = RequestType.BY_HEADER; } /** * Create a reply to a {@link BlockCompactRepresentation} request. * * @param block the {@link BlockCompactRepresentation} requested */ public BlockCompactRepresentationRequestMessage(BlockCompactRepresentation block) { isRequest = false; isReject = false; this.block = block; } /** * Change a message from a request one to * a rejection. */ public void rejectMessage(){ isRequest = false; isReject = true; } public boolean isRequestMessage(){ return isRequest; } public boolean isPositiveReply(){ return (!isRequest)&&(!isReject); } public boolean isNegativeReply(){ return (!isRequest)&&isReject; } /** * @return the typeOfRequest */ public RequestType getTypeOfRequest() { return typeOfRequest; } /** * @return the blockNumber */ public long getBlockNumber() { return blockNumber; } /** * @return the hash */ public HashValue getHash() { return hash; } /** * @return the block */ public BlockCompactRepresentation getBlockCompactRepresentation() { return block; } /** * @return the header */ public BlockHeader getHeader() { return header; } /** * @return the transaction */ public Transaction getTransaction() { return transaction; } public enum RequestType{ BY_BLOCK_NUMBER, BY_HASH, BY_HEADER; } }
[ "public", "class", "BlockCompactRepresentationRequestMessage", "implements", "ThickNodeMessages", "{", "/**\n\t * random generated UID\n\t */", "private", "static", "final", "long", "serialVersionUID", "=", "-", "3100306097773163431L", ";", "private", "boolean", "isRequest", ";", "private", "boolean", "isReject", ";", "private", "RequestType", "typeOfRequest", ";", "private", "long", "blockNumber", ";", "private", "HashValue", "hash", ";", "private", "BlockHeader", "header", ";", "private", "Transaction", "transaction", ";", "private", "BlockCompactRepresentation", "block", ";", "private", "BlockCompactRepresentationRequestMessage", "(", "Transaction", "transaction", ")", "{", "isRequest", "=", "true", ";", "isReject", "=", "false", ";", "this", ".", "transaction", "=", "transaction", ";", "}", "/**\n\t * Create a request for a {@link BlockCompactRepresentation} by means of\n\t * its number \n\t * \n\t * @param blockNumber the {@link Block} number\n\t */", "public", "BlockCompactRepresentationRequestMessage", "(", "long", "blockNumber", ",", "Transaction", "transaction", ")", "{", "this", "(", "transaction", ")", ";", "this", ".", "blockNumber", "=", "blockNumber", ";", "typeOfRequest", "=", "RequestType", ".", "BY_BLOCK_NUMBER", ";", "}", "/**\n\t * Create a request for a {@link BlockCompactRepresentation} by means of\n\t * its {@link HashValue} header hash.\n\t * \n\t * @param hash\n\t */", "public", "BlockCompactRepresentationRequestMessage", "(", "HashValue", "hash", ",", "Transaction", "transaction", ")", "{", "this", "(", "transaction", ")", ";", "this", ".", "hash", "=", "hash", ";", "typeOfRequest", "=", "RequestType", ".", "BY_HASH", ";", "}", "/**\n\t * Create a request for a {@link BlockCompactRepresentation} by means of\n\t * its {@link HashValue} header hash.\n\t * \n\t * @param header\n\t */", "public", "BlockCompactRepresentationRequestMessage", "(", "BlockHeader", "header", ",", "Transaction", "transaction", ")", "{", "this", "(", "transaction", ")", ";", "this", ".", "header", "=", "header", ";", "typeOfRequest", "=", "RequestType", ".", "BY_HEADER", ";", "}", "/**\n\t * Create a reply to a {@link BlockCompactRepresentation} request.\n\t * \n\t * @param block the {@link BlockCompactRepresentation} requested\n\t */", "public", "BlockCompactRepresentationRequestMessage", "(", "BlockCompactRepresentation", "block", ")", "{", "isRequest", "=", "false", ";", "isReject", "=", "false", ";", "this", ".", "block", "=", "block", ";", "}", "/**\n\t * Change a message from a request one to\n\t * a rejection.\n\t */", "public", "void", "rejectMessage", "(", ")", "{", "isRequest", "=", "false", ";", "isReject", "=", "true", ";", "}", "public", "boolean", "isRequestMessage", "(", ")", "{", "return", "isRequest", ";", "}", "public", "boolean", "isPositiveReply", "(", ")", "{", "return", "(", "!", "isRequest", ")", "&&", "(", "!", "isReject", ")", ";", "}", "public", "boolean", "isNegativeReply", "(", ")", "{", "return", "(", "!", "isRequest", ")", "&&", "isReject", ";", "}", "/**\n\t * @return the typeOfRequest\n\t */", "public", "RequestType", "getTypeOfRequest", "(", ")", "{", "return", "typeOfRequest", ";", "}", "/**\n\t * @return the blockNumber\n\t */", "public", "long", "getBlockNumber", "(", ")", "{", "return", "blockNumber", ";", "}", "/**\n\t * @return the hash\n\t */", "public", "HashValue", "getHash", "(", ")", "{", "return", "hash", ";", "}", "/**\n\t * @return the block\n\t */", "public", "BlockCompactRepresentation", "getBlockCompactRepresentation", "(", ")", "{", "return", "block", ";", "}", "/**\n\t * @return the header\n\t */", "public", "BlockHeader", "getHeader", "(", ")", "{", "return", "header", ";", "}", "/**\n\t * @return the transaction\n\t */", "public", "Transaction", "getTransaction", "(", ")", "{", "return", "transaction", ";", "}", "public", "enum", "RequestType", "{", "BY_BLOCK_NUMBER", ",", "BY_HASH", ",", "BY_HEADER", ";", "}", "}" ]
This message is meant to be used by {@link ThinNode}s to request {@link BlockCompactRepresentation}s and by {@link ThickNode}s to reply to such requests.
[ "This", "message", "is", "meant", "to", "be", "used", "by", "{", "@link", "ThinNode", "}", "s", "to", "request", "{", "@link", "BlockCompactRepresentation", "}", "s", "and", "by", "{", "@link", "ThickNode", "}", "s", "to", "reply", "to", "such", "requests", "." ]
[]
[ { "param": "ThickNodeMessages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ThickNodeMessages", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7ba5e7c1db7d0c354218f116c965487ace7fc1d2
dmiterkh/ComSolvdCarina
src/test/java/com/qaprosoft/carina/demo/onliner/OnlinerVideoTest.java
[ "Apache-2.0" ]
Java
OnlinerVideoTest
/** * @author Dmitry Kharevich */
@author Dmitry Kharevich
[ "@author", "Dmitry", "Kharevich" ]
public class OnlinerVideoTest extends ParentBaseTestNotLoginTests implements IAbstractTest { private static final Logger LOGGER = LoggerFactory.getLogger(OnlinerVideoTest.class); private HomePageOnliner homePageOnliner; @BeforeSuite public void beforeSuiteVideoTestChild() { LOGGER.info("@VideoTest-BeforeSuite-Child"); } @BeforeTest public void beforeTestVideoTestChild() { LOGGER.info("@VideoTest-BeforeTest-Child"); } @BeforeClass public void beforeClassVideoTestChild() { LOGGER.info("@VideoTest-BeforeClass-Child"); } @BeforeMethod public void beforeMethodVideoTestChild() { LOGGER.info("@VideoTest-BeforeMethod-Child"); // Open Home page homePageOnliner = new HomePageOnliner(getDriver()); homePageOnliner.open(); Assert.assertTrue(homePageOnliner.isPageOpened(), "Home page is not opened"); } @Test() @MethodOwner(owner = "dkharevich") @TestPriority(Priority.P3) @TestLabel(name = "feature", value = {"web", "regression"}) //testcase017 Verify that the user Gets correct work of youtube video in any article with youtube video public void testUserGetsCorrectWorkOfYoutubeVideo() { // Open Video page if (homePageOnliner.isVideoPageLinkPresent()) { VideoPageOnliner videoPageOnliner = homePageOnliner.openVideoPageOnlinerUsualFor(); videoPageOnliner.showVideoPageOperations(); videoPageOnliner.returnToHomePage(); pause(3); } else { LOGGER.info("Required Elements are not found on the Home Page"); } } @Test() @MethodOwner(owner = "dkharevich") @TestPriority(Priority.P3) @TestLabel(name = "feature", value = {"web", "regression"}) //testcase017 Verify that the user Gets correct work of youtube video in any article with youtube video public void testUserGetsCorrectWorkOfYoutubeVideoWithForEach() { // Open Video page if (homePageOnliner.isVideoPageLinkPresent()) { VideoPageOnliner videoPageOnliner = homePageOnliner.openVideoPageOnlinerForEach(); videoPageOnliner.showVideoPageOperations(); videoPageOnliner.returnToHomePage(); } else { LOGGER.info("Required Elements are not found on the Home Page"); } } @AfterMethod public void afterMethodVideoTestChild() { LOGGER.info("@VideoTest-AfterMethod-Child"); } @AfterClass public void afterClassVideoTestChild() { LOGGER.info("@VideoTest-AfterClass-Child"); } @AfterTest public void afterTestVideoTestChild() { LOGGER.info("@VideoTest-AfterTest-Child"); } @AfterSuite public void afterSuiteVideoTestChild() { LOGGER.info("@VideoTest-AfterSuite-Child"); } }
[ "public", "class", "OnlinerVideoTest", "extends", "ParentBaseTestNotLoginTests", "implements", "IAbstractTest", "{", "private", "static", "final", "Logger", "LOGGER", "=", "LoggerFactory", ".", "getLogger", "(", "OnlinerVideoTest", ".", "class", ")", ";", "private", "HomePageOnliner", "homePageOnliner", ";", "@", "BeforeSuite", "public", "void", "beforeSuiteVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-BeforeSuite-Child", "\"", ")", ";", "}", "@", "BeforeTest", "public", "void", "beforeTestVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-BeforeTest-Child", "\"", ")", ";", "}", "@", "BeforeClass", "public", "void", "beforeClassVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-BeforeClass-Child", "\"", ")", ";", "}", "@", "BeforeMethod", "public", "void", "beforeMethodVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-BeforeMethod-Child", "\"", ")", ";", "homePageOnliner", "=", "new", "HomePageOnliner", "(", "getDriver", "(", ")", ")", ";", "homePageOnliner", ".", "open", "(", ")", ";", "Assert", ".", "assertTrue", "(", "homePageOnliner", ".", "isPageOpened", "(", ")", ",", "\"", "Home page is not opened", "\"", ")", ";", "}", "@", "Test", "(", ")", "@", "MethodOwner", "(", "owner", "=", "\"", "dkharevich", "\"", ")", "@", "TestPriority", "(", "Priority", ".", "P3", ")", "@", "TestLabel", "(", "name", "=", "\"", "feature", "\"", ",", "value", "=", "{", "\"", "web", "\"", ",", "\"", "regression", "\"", "}", ")", "public", "void", "testUserGetsCorrectWorkOfYoutubeVideo", "(", ")", "{", "if", "(", "homePageOnliner", ".", "isVideoPageLinkPresent", "(", ")", ")", "{", "VideoPageOnliner", "videoPageOnliner", "=", "homePageOnliner", ".", "openVideoPageOnlinerUsualFor", "(", ")", ";", "videoPageOnliner", ".", "showVideoPageOperations", "(", ")", ";", "videoPageOnliner", ".", "returnToHomePage", "(", ")", ";", "pause", "(", "3", ")", ";", "}", "else", "{", "LOGGER", ".", "info", "(", "\"", "Required Elements are not found on the Home Page", "\"", ")", ";", "}", "}", "@", "Test", "(", ")", "@", "MethodOwner", "(", "owner", "=", "\"", "dkharevich", "\"", ")", "@", "TestPriority", "(", "Priority", ".", "P3", ")", "@", "TestLabel", "(", "name", "=", "\"", "feature", "\"", ",", "value", "=", "{", "\"", "web", "\"", ",", "\"", "regression", "\"", "}", ")", "public", "void", "testUserGetsCorrectWorkOfYoutubeVideoWithForEach", "(", ")", "{", "if", "(", "homePageOnliner", ".", "isVideoPageLinkPresent", "(", ")", ")", "{", "VideoPageOnliner", "videoPageOnliner", "=", "homePageOnliner", ".", "openVideoPageOnlinerForEach", "(", ")", ";", "videoPageOnliner", ".", "showVideoPageOperations", "(", ")", ";", "videoPageOnliner", ".", "returnToHomePage", "(", ")", ";", "}", "else", "{", "LOGGER", ".", "info", "(", "\"", "Required Elements are not found on the Home Page", "\"", ")", ";", "}", "}", "@", "AfterMethod", "public", "void", "afterMethodVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-AfterMethod-Child", "\"", ")", ";", "}", "@", "AfterClass", "public", "void", "afterClassVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-AfterClass-Child", "\"", ")", ";", "}", "@", "AfterTest", "public", "void", "afterTestVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-AfterTest-Child", "\"", ")", ";", "}", "@", "AfterSuite", "public", "void", "afterSuiteVideoTestChild", "(", ")", "{", "LOGGER", ".", "info", "(", "\"", "@VideoTest-AfterSuite-Child", "\"", ")", ";", "}", "}" ]
@author Dmitry Kharevich
[ "@author", "Dmitry", "Kharevich" ]
[ "// Open Home page", "//testcase017 Verify that the user Gets correct work of youtube video in any article with youtube video", "// Open Video page ", "//testcase017 Verify that the user Gets correct work of youtube video in any article with youtube video", "// Open Video page " ]
[ { "param": "ParentBaseTestNotLoginTests", "type": null }, { "param": "IAbstractTest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ParentBaseTestNotLoginTests", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "IAbstractTest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7ba7c630bcb8da5794e0bb2a405ce46de82fa451
ajha6/Service-Oriented-Architecture
src/main/java/cs601/project4/Project4Init.java
[ "MIT" ]
Java
Project4Init
/** * @author anuragjha * WebInit class holds the config information * */
@author anuragjha WebInit class holds the config information
[ "@author", "anuragjha", "WebInit", "class", "holds", "the", "config", "information" ]
public class Project4Init { private int portWS; private int portUS; private int portES; private String loggerFile; //ThreadPool private int minThreads; private int maxThreads; private int timeout; //URI basepath private String basepathWebService; private String basepathUserService; private String basepathEventService; //database private String username; private String password; private String db; private String dbHostname; /** * constructor */ public Project4Init() { } /** * @return the port */ public int getPortWS() { return portWS; } /** * @return the port */ public int getPortES() { return portES; } /** * @return the port */ public int getPortUS() { return portUS; } /** * @return the loggerFile */ public String getLoggerFile() { return loggerFile; } /** * @return the basepathWebService */ public String getBasepathWebService() { return basepathWebService; } /** * @return the basepathUserService */ public String getBasepathUserService() { return basepathUserService; } /** * @return the basepathEventService */ public String getBasepathEventService() { return basepathEventService; } /** * @return the minThreads */ public int getMinThreads() { return minThreads; } /** * @return the maxThreads */ public int getMaxThreads() { return maxThreads; } /** * @return the timeout */ public int getTimeout() { return timeout; } /** * @return the username */ public String getUsername() { return username; } /** * @return the password */ public String getPassword() { return password; } /** * @return the db */ public String getDb() { return db; } /** * @return the dbHostname */ public String getDbHostname() { return dbHostname; } @Override public String toString() { StringBuilder sb = new StringBuilder(); //sb.append("port: " + this.port + "\n"); //sb.append("loggerFile: " + this.loggerFile + "\n"); return sb.toString(); } /** * @param args */ public void main(String[] args) { // TODO Auto-generated method stub } }
[ "public", "class", "Project4Init", "{", "private", "int", "portWS", ";", "private", "int", "portUS", ";", "private", "int", "portES", ";", "private", "String", "loggerFile", ";", "private", "int", "minThreads", ";", "private", "int", "maxThreads", ";", "private", "int", "timeout", ";", "private", "String", "basepathWebService", ";", "private", "String", "basepathUserService", ";", "private", "String", "basepathEventService", ";", "private", "String", "username", ";", "private", "String", "password", ";", "private", "String", "db", ";", "private", "String", "dbHostname", ";", "/**\n\t * constructor\n\t */", "public", "Project4Init", "(", ")", "{", "}", "/**\n\t * @return the port\n\t */", "public", "int", "getPortWS", "(", ")", "{", "return", "portWS", ";", "}", "/**\n\t * @return the port\n\t */", "public", "int", "getPortES", "(", ")", "{", "return", "portES", ";", "}", "/**\n\t * @return the port\n\t */", "public", "int", "getPortUS", "(", ")", "{", "return", "portUS", ";", "}", "/**\n\t * @return the loggerFile\n\t */", "public", "String", "getLoggerFile", "(", ")", "{", "return", "loggerFile", ";", "}", "/**\n\t * @return the basepathWebService\n\t */", "public", "String", "getBasepathWebService", "(", ")", "{", "return", "basepathWebService", ";", "}", "/**\n\t * @return the basepathUserService\n\t */", "public", "String", "getBasepathUserService", "(", ")", "{", "return", "basepathUserService", ";", "}", "/**\n\t * @return the basepathEventService\n\t */", "public", "String", "getBasepathEventService", "(", ")", "{", "return", "basepathEventService", ";", "}", "/**\n\t * @return the minThreads\n\t */", "public", "int", "getMinThreads", "(", ")", "{", "return", "minThreads", ";", "}", "/**\n\t * @return the maxThreads\n\t */", "public", "int", "getMaxThreads", "(", ")", "{", "return", "maxThreads", ";", "}", "/**\n\t * @return the timeout\n\t */", "public", "int", "getTimeout", "(", ")", "{", "return", "timeout", ";", "}", "/**\n\t * @return the username\n\t */", "public", "String", "getUsername", "(", ")", "{", "return", "username", ";", "}", "/**\n\t * @return the password\n\t */", "public", "String", "getPassword", "(", ")", "{", "return", "password", ";", "}", "/**\n\t * @return the db\n\t */", "public", "String", "getDb", "(", ")", "{", "return", "db", ";", "}", "/**\n\t * @return the dbHostname\n\t */", "public", "String", "getDbHostname", "(", ")", "{", "return", "dbHostname", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n\t * @param args\n\t */", "public", "void", "main", "(", "String", "[", "]", "args", ")", "{", "}", "}" ]
@author anuragjha WebInit class holds the config information
[ "@author", "anuragjha", "WebInit", "class", "holds", "the", "config", "information" ]
[ "//ThreadPool ", "//URI basepath", "//database", "//sb.append(\"port: \" + this.port + \"\\n\");", "//sb.append(\"loggerFile: \" + this.loggerFile + \"\\n\");", "// TODO Auto-generated method stub" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7baa8ae60531f9ba4b1b94075c48e15cd4e4aa0c
qiangxu1996/vmtrace
base/build-system/gradle-core/src/main/java/com/android/build/gradle/tasks/CmakeExternalNativeJsonGenerator.java
[ "Apache-2.0" ]
Java
CmakeExternalNativeJsonGenerator
/** * CMake JSON generation logic. This is separated from the corresponding CMake task so that JSON can * be generated during configuration. */
CMake JSON generation logic. This is separated from the corresponding CMake task so that JSON can be generated during configuration.
[ "CMake", "JSON", "generation", "logic", ".", "This", "is", "separated", "from", "the", "corresponding", "CMake", "task", "so", "that", "JSON", "can", "be", "generated", "during", "configuration", "." ]
abstract class CmakeExternalNativeJsonGenerator extends ExternalNativeJsonGenerator { @NonNull protected final CxxCmakeModuleModel cmake; CmakeExternalNativeJsonGenerator( @NonNull CxxBuildModel build, @NonNull CxxVariantModel variant, @NonNull List<CxxAbiModel> abis, @NonNull GradleBuildVariant.Builder stats) { super(build, variant, abis, stats); this.stats.setNativeBuildSystemType(GradleNativeAndroidModule.NativeBuildSystemType.CMAKE); this.cmake = Objects.requireNonNull(variant.getModule().getCmake()); // Check some basic requirements. This code executes at sync time but any call to // recordConfigurationError will later cause the generation of json to fail. File cmakelists = getMakefile(); if (cmakelists.isDirectory()) { errorln( "Gradle project cmake.path %s is a folder. It must be CMakeLists.txt", cmakelists); } else if (cmakelists.isFile()) { String filename = cmakelists.getName(); if (!filename.equals("CMakeLists.txt")) { errorln( "Gradle project cmake.path specifies %s but it must be CMakeLists.txt", filename); } } else { errorln("Gradle project cmake.path is %s but that file doesn't exist", cmakelists); } } /** * Executes the JSON generation process. Return the combination of STDIO and STDERR from running * the process. * * @return Returns the combination of STDIO and STDERR from running the process. */ @NonNull public abstract String executeProcessAndGetOutput(@NonNull CxxAbiModel abi) throws ProcessException, IOException; @NonNull @Override public String executeProcess(@NonNull CxxAbiModel abi) throws ProcessException, IOException { String output = executeProcessAndGetOutput(abi); return makeCmakeMessagePathsAbsolute(output, getMakefile().getParentFile()); } @Override void processBuildOutput(@NonNull String buildOutput, @NonNull CxxAbiModel abi) { } @NonNull @Override ProcessInfoBuilder getProcessBuilder(@NonNull CxxAbiModel abi) { ProcessInfoBuilder builder = new ProcessInfoBuilder(); builder.setExecutable(cmake.getCmakeExe()); List<CommandLineArgument> arguments = Lists.newArrayList(); arguments.addAll(getFinalCmakeCommandLineArguments(abi)); builder.addArgs(convertCmakeCommandLineArgumentsToStringList(arguments)); return builder; } @NonNull @Override public NativeBuildSystem getNativeBuildSystem() { return NativeBuildSystem.CMAKE; } @NonNull @Override Map<Abi, File> getStlSharedObjectFiles() { // Search for ANDROID_STL build argument. Process in order / later flags take precedent. Stl stl = null; for (String argument : getBuildArguments()) { argument = argument.replace(" ", ""); if (argument.startsWith("-DANDROID_STL=")) { String stlName = argument.split("=", 2)[1]; stl = Stl.fromArgumentName(stlName); if (stl == null) { errorln("Unrecognized STL in arguments: %s", stlName); } } } // TODO: Query the default from the NDK. // We currently assume the default to not require packaging for the default STL. This is // currently safe because the default for ndk-build has always been system (which doesn't // require packaging because it's a system library) and gnustl_static or c++_static for // CMake (which also doesn't require packaging). // // https://github.com/android-ndk/ndk/issues/744 wants to change the default for both to // c++_shared, but that can't happen until we stop assuming the default does not need to be // packaged. if (stl == null) { return Maps.newHashMap(); } return variant.getModule().getStlSharedObjectMap().get(stl).entrySet().stream() .filter(e -> getAbis().contains(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @InputFile @PathSensitive(PathSensitivity.RELATIVE) @Nullable @Optional public File getCmakeSettingsJson() { File cmakeSettings = CxxModuleModelKt.getCmakeSettingsFile(variant.getModule()); if (cmakeSettings.isFile()) { return cmakeSettings; } return null; } }
[ "abstract", "class", "CmakeExternalNativeJsonGenerator", "extends", "ExternalNativeJsonGenerator", "{", "@", "NonNull", "protected", "final", "CxxCmakeModuleModel", "cmake", ";", "CmakeExternalNativeJsonGenerator", "(", "@", "NonNull", "CxxBuildModel", "build", ",", "@", "NonNull", "CxxVariantModel", "variant", ",", "@", "NonNull", "List", "<", "CxxAbiModel", ">", "abis", ",", "@", "NonNull", "GradleBuildVariant", ".", "Builder", "stats", ")", "{", "super", "(", "build", ",", "variant", ",", "abis", ",", "stats", ")", ";", "this", ".", "stats", ".", "setNativeBuildSystemType", "(", "GradleNativeAndroidModule", ".", "NativeBuildSystemType", ".", "CMAKE", ")", ";", "this", ".", "cmake", "=", "Objects", ".", "requireNonNull", "(", "variant", ".", "getModule", "(", ")", ".", "getCmake", "(", ")", ")", ";", "File", "cmakelists", "=", "getMakefile", "(", ")", ";", "if", "(", "cmakelists", ".", "isDirectory", "(", ")", ")", "{", "errorln", "(", "\"", "Gradle project cmake.path %s is a folder. It must be CMakeLists.txt", "\"", ",", "cmakelists", ")", ";", "}", "else", "if", "(", "cmakelists", ".", "isFile", "(", ")", ")", "{", "String", "filename", "=", "cmakelists", ".", "getName", "(", ")", ";", "if", "(", "!", "filename", ".", "equals", "(", "\"", "CMakeLists.txt", "\"", ")", ")", "{", "errorln", "(", "\"", "Gradle project cmake.path specifies %s but it must be CMakeLists.txt", "\"", ",", "filename", ")", ";", "}", "}", "else", "{", "errorln", "(", "\"", "Gradle project cmake.path is %s but that file doesn't exist", "\"", ",", "cmakelists", ")", ";", "}", "}", "/**\n * Executes the JSON generation process. Return the combination of STDIO and STDERR from running\n * the process.\n *\n * @return Returns the combination of STDIO and STDERR from running the process.\n */", "@", "NonNull", "public", "abstract", "String", "executeProcessAndGetOutput", "(", "@", "NonNull", "CxxAbiModel", "abi", ")", "throws", "ProcessException", ",", "IOException", ";", "@", "NonNull", "@", "Override", "public", "String", "executeProcess", "(", "@", "NonNull", "CxxAbiModel", "abi", ")", "throws", "ProcessException", ",", "IOException", "{", "String", "output", "=", "executeProcessAndGetOutput", "(", "abi", ")", ";", "return", "makeCmakeMessagePathsAbsolute", "(", "output", ",", "getMakefile", "(", ")", ".", "getParentFile", "(", ")", ")", ";", "}", "@", "Override", "void", "processBuildOutput", "(", "@", "NonNull", "String", "buildOutput", ",", "@", "NonNull", "CxxAbiModel", "abi", ")", "{", "}", "@", "NonNull", "@", "Override", "ProcessInfoBuilder", "getProcessBuilder", "(", "@", "NonNull", "CxxAbiModel", "abi", ")", "{", "ProcessInfoBuilder", "builder", "=", "new", "ProcessInfoBuilder", "(", ")", ";", "builder", ".", "setExecutable", "(", "cmake", ".", "getCmakeExe", "(", ")", ")", ";", "List", "<", "CommandLineArgument", ">", "arguments", "=", "Lists", ".", "newArrayList", "(", ")", ";", "arguments", ".", "addAll", "(", "getFinalCmakeCommandLineArguments", "(", "abi", ")", ")", ";", "builder", ".", "addArgs", "(", "convertCmakeCommandLineArgumentsToStringList", "(", "arguments", ")", ")", ";", "return", "builder", ";", "}", "@", "NonNull", "@", "Override", "public", "NativeBuildSystem", "getNativeBuildSystem", "(", ")", "{", "return", "NativeBuildSystem", ".", "CMAKE", ";", "}", "@", "NonNull", "@", "Override", "Map", "<", "Abi", ",", "File", ">", "getStlSharedObjectFiles", "(", ")", "{", "Stl", "stl", "=", "null", ";", "for", "(", "String", "argument", ":", "getBuildArguments", "(", ")", ")", "{", "argument", "=", "argument", ".", "replace", "(", "\"", " ", "\"", ",", "\"", "\"", ")", ";", "if", "(", "argument", ".", "startsWith", "(", "\"", "-DANDROID_STL=", "\"", ")", ")", "{", "String", "stlName", "=", "argument", ".", "split", "(", "\"", "=", "\"", ",", "2", ")", "[", "1", "]", ";", "stl", "=", "Stl", ".", "fromArgumentName", "(", "stlName", ")", ";", "if", "(", "stl", "==", "null", ")", "{", "errorln", "(", "\"", "Unrecognized STL in arguments: %s", "\"", ",", "stlName", ")", ";", "}", "}", "}", "if", "(", "stl", "==", "null", ")", "{", "return", "Maps", ".", "newHashMap", "(", ")", ";", "}", "return", "variant", ".", "getModule", "(", ")", ".", "getStlSharedObjectMap", "(", ")", ".", "get", "(", "stl", ")", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "e", "->", "getAbis", "(", ")", ".", "contains", "(", "e", ".", "getKey", "(", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toMap", "(", "Map", ".", "Entry", "::", "getKey", ",", "Map", ".", "Entry", "::", "getValue", ")", ")", ";", "}", "@", "InputFile", "@", "PathSensitive", "(", "PathSensitivity", ".", "RELATIVE", ")", "@", "Nullable", "@", "Optional", "public", "File", "getCmakeSettingsJson", "(", ")", "{", "File", "cmakeSettings", "=", "CxxModuleModelKt", ".", "getCmakeSettingsFile", "(", "variant", ".", "getModule", "(", ")", ")", ";", "if", "(", "cmakeSettings", ".", "isFile", "(", ")", ")", "{", "return", "cmakeSettings", ";", "}", "return", "null", ";", "}", "}" ]
CMake JSON generation logic.
[ "CMake", "JSON", "generation", "logic", "." ]
[ "// Check some basic requirements. This code executes at sync time but any call to", "// recordConfigurationError will later cause the generation of json to fail.", "// Search for ANDROID_STL build argument. Process in order / later flags take precedent.", "// TODO: Query the default from the NDK.", "// We currently assume the default to not require packaging for the default STL. This is", "// currently safe because the default for ndk-build has always been system (which doesn't", "// require packaging because it's a system library) and gnustl_static or c++_static for", "// CMake (which also doesn't require packaging).", "//", "// https://github.com/android-ndk/ndk/issues/744 wants to change the default for both to", "// c++_shared, but that can't happen until we stop assuming the default does not need to be", "// packaged." ]
[ { "param": "ExternalNativeJsonGenerator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ExternalNativeJsonGenerator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bae59531e3718666b5c882f88fbad084033a89a
anHALytics/anHALytics-core
anhalytics-harvest/src/main/java/fr/inria/anhalytics/harvest/grobid/GrobidFulltextWorker.java
[ "Apache-2.0" ]
Java
GrobidFulltextWorker
/** * Worker to extract tei/assets from a publication binary. * * @author Achraf */
Worker to extract tei/assets from a publication binary. @author Achraf
[ "Worker", "to", "extract", "tei", "/", "assets", "from", "a", "publication", "binary", ".", "@author", "Achraf" ]
public class GrobidFulltextWorker extends GrobidWorker { private static final Logger logger = LoggerFactory.getLogger(GrobidFulltextWorker.class); public GrobidFulltextWorker(BiblioObject biblioObject, String date, int start, int end) throws ParserConfigurationException { super(biblioObject, start, end); } // @Override // protected void saveExtractions(String resultDirectoryPath) { // String tei = null; // try { // File directoryPath = new File(resultDirectoryPath); // if (directoryPath.exists()) { // File[] files = directoryPath.listFiles(); // if (files != null) { // for (final File currFile : files) { // if (currFile.getName().toLowerCase().endsWith(".png")) { // InputStream targetStream = FileUtils.openInputStream(currFile); // mm.insertGrobidAssetDocument(targetStream, repositoryDocId, anhalyticsId,currFile.getName(), date); // targetStream.close(); // } else if (currFile.getName().toLowerCase().endsWith(".xml")) { // tei = Utilities.readFile(currFile.getAbsolutePath()); // tei = Utilities.trimEncodedCharaters(tei); // tei = generateIdsTeiDoc(tei); // System.out.println(repositoryDocId); // mm.insertGrobidTei(tei, repositoryDocId, anhalyticsId, date); // } // } // } // } // } catch (Exception ex) { // logger.error(ex.getMessage(), ex.getCause()); // } // } }
[ "public", "class", "GrobidFulltextWorker", "extends", "GrobidWorker", "{", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "GrobidFulltextWorker", ".", "class", ")", ";", "public", "GrobidFulltextWorker", "(", "BiblioObject", "biblioObject", ",", "String", "date", ",", "int", "start", ",", "int", "end", ")", "throws", "ParserConfigurationException", "{", "super", "(", "biblioObject", ",", "start", ",", "end", ")", ";", "}", "}" ]
Worker to extract tei/assets from a publication binary.
[ "Worker", "to", "extract", "tei", "/", "assets", "from", "a", "publication", "binary", "." ]
[ "// @Override", "// protected void saveExtractions(String resultDirectoryPath) {", "// String tei = null;", "// try {", "// File directoryPath = new File(resultDirectoryPath);", "// if (directoryPath.exists()) {", "// File[] files = directoryPath.listFiles();", "// if (files != null) {", "// for (final File currFile : files) {", "// if (currFile.getName().toLowerCase().endsWith(\".png\")) {", "// InputStream targetStream = FileUtils.openInputStream(currFile);", "// mm.insertGrobidAssetDocument(targetStream, repositoryDocId, anhalyticsId,currFile.getName(), date);", "// targetStream.close();", "// } else if (currFile.getName().toLowerCase().endsWith(\".xml\")) {", "// tei = Utilities.readFile(currFile.getAbsolutePath());", "// tei = Utilities.trimEncodedCharaters(tei);", "// tei = generateIdsTeiDoc(tei);", "// System.out.println(repositoryDocId);", "// mm.insertGrobidTei(tei, repositoryDocId, anhalyticsId, date);", "// }", "// }", "// }", "// }", "// } catch (Exception ex) {", "// logger.error(ex.getMessage(), ex.getCause());", "// }", "// }" ]
[ { "param": "GrobidWorker", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GrobidWorker", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bbc1d5ccebece7d16c2fa4876c81256fa7d66cc
thaingo/parsec-libraries
parsec-clients/src/main/java/com/yahoo/parsec/clients/ParsecHttpRequestRetryCallable.java
[ "Apache-2.0" ]
Java
ParsecHttpRequestRetryCallable
/** * {@link Callable} implementation that handles HTTP request retry based on response status code. */
Callable implementation that handles HTTP request retry based on response status code.
[ "Callable", "implementation", "that", "handles", "HTTP", "request", "retry", "based", "on", "response", "status", "code", "." ]
class ParsecHttpRequestRetryCallable<T> implements Callable<T> { /** * By default, do not delay the retries. */ private static final long DEFAULT_RETRY_INTERVAL = 0; /** * Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(ParsecHttpRequestRetryCallable.class); /** * Async handler. */ private final AsyncHandler<T> asyncHandler; /** * Ning client. */ private final AsyncHttpClient client; /** * Request. */ private final ParsecAsyncHttpRequest request; /** * For delayed retries */ private RetryDelayer retryDelayer; /** * Response list. */ private List<T> responses; /** * Constructor. * * @param client client * @param request request */ public ParsecHttpRequestRetryCallable(final AsyncHttpClient client, final ParsecAsyncHttpRequest request) { this(client, request, null); } /** * Constructor. * * @param client client * @param request request * @param asyncHandler async handler */ public ParsecHttpRequestRetryCallable( final AsyncHttpClient client, final ParsecAsyncHttpRequest request, final AsyncHandler<T> asyncHandler) { this(client, request, asyncHandler, DEFAULT_RETRY_INTERVAL); } /** * Constructor. * * @param client client * @param request request * @param asyncHandler async handler * @param retryIntervalMillis retry interval in milliseconds */ public ParsecHttpRequestRetryCallable( final AsyncHttpClient client, final ParsecAsyncHttpRequest request, final AsyncHandler<T> asyncHandler, long retryIntervalMillis ) { this.client = client; this.request = request; this.asyncHandler = asyncHandler; this.retryDelayer = new RetryDelayer(retryIntervalMillis); responses = new ArrayList<>(); } /** * Package-private Constructor. Only for unit-test usage. * * @param client client * @param request request * @param asyncHandler async handler * @param retryDelayer custom retry Delayer */ ParsecHttpRequestRetryCallable( final AsyncHttpClient client, final ParsecAsyncHttpRequest request, final AsyncHandler<T> asyncHandler, RetryDelayer retryDelayer ) { this.client = client; this.request = request; this.asyncHandler = asyncHandler; this.retryDelayer = retryDelayer; responses = new ArrayList<>(); } /** * Check status code and handles retry if T is type {@link Response} or Ning {@link com.ning.http.client.Response}. * * @return T * @throws Exception exception */ @Override public T call() throws Exception { responses.clear(); final Request ningRequest = request.getNingRequest(); final List<Integer> retryStatusCodes = request.getRetryStatusCodes(); final List<Class<? extends Throwable>> retryExceptions = request.getRetryExceptions(); final int maxRetries = request.getMaxRetries(); T response; Exception exception; int retries = 0; for (; ; ) { response = null; exception = null; try { // when this is not the first try (i.e. is re-trying), delay an interval if (retries > 0) { retryDelayer.delay(); } response = executeRequest(ningRequest); responses.add(response); int statusCode = getStatusCode(response); if (statusCode == -1 || !retryStatusCodes.contains(statusCode)) { break; } } catch (Exception e) { Throwable root = ExceptionUtils.getRootCause(e); if (!retryExceptions.contains(root.getClass())) { throw e; } exception = e; } if (retries == maxRetries) { LOGGER.debug("Max retries reached: " + retries + " (max: " + maxRetries + ")"); break; } retries++; LOGGER.debug("Retry number: " + retries + " (max: " + maxRetries + ")"); } if (exception != null) { throw exception; } return response; } /** * Execute Request. * * @param ningRequest Ning request * @return T * @throws InterruptedException Interrupted exception * @throws ExecutionException Execution exception */ @SuppressWarnings("unchecked") private T executeRequest(Request ningRequest) throws InterruptedException, ExecutionException { if (asyncHandler != null) { return client.executeRequest(ningRequest, asyncHandler).get(); } else { return (T) client.executeRequest(ningRequest).get(); } } /** * Get Responses. * * @return {@literal List<T>} */ public List<T> getResponses() { return responses; } /** * Gets Status Code from {@link Response} or Ning {@link com.ning.http.client.Response}. * * @param response T * @return status code or -1 if T is not type of {@link Response} or Ning {@link com.ning.http.client.Response} */ private int getStatusCode(T response) { if (response instanceof Response) { return ((Response) response).getStatus(); } else if (response instanceof com.ning.http.client.Response) { return ((com.ning.http.client.Response) response).getStatusCode(); } else { return -1; } } /** * Package-private, this is only for unit-testing. * @return retryDelayer */ RetryDelayer getRetryDelayer() { return retryDelayer; } /** * Extract delay mechanism as a class to let it be testable */ public class RetryDelayer { private final long retryIntervalMillis; RetryDelayer(long retryIntervalMillis) { this.retryIntervalMillis = retryIntervalMillis; } public void delay() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(retryIntervalMillis); } /** * Package-private, this is only for unit-testing. * @return retryIntervalMillis */ long getRetryIntervalMillis() { return retryIntervalMillis; } } }
[ "class", "ParsecHttpRequestRetryCallable", "<", "T", ">", "implements", "Callable", "<", "T", ">", "{", "/**\n * By default, do not delay the retries.\n */", "private", "static", "final", "long", "DEFAULT_RETRY_INTERVAL", "=", "0", ";", "/**\n * Logger.\n */", "private", "static", "final", "Logger", "LOGGER", "=", "LoggerFactory", ".", "getLogger", "(", "ParsecHttpRequestRetryCallable", ".", "class", ")", ";", "/**\n * Async handler.\n */", "private", "final", "AsyncHandler", "<", "T", ">", "asyncHandler", ";", "/**\n * Ning client.\n */", "private", "final", "AsyncHttpClient", "client", ";", "/**\n * Request.\n */", "private", "final", "ParsecAsyncHttpRequest", "request", ";", "/**\n * For delayed retries\n */", "private", "RetryDelayer", "retryDelayer", ";", "/**\n * Response list.\n */", "private", "List", "<", "T", ">", "responses", ";", "/**\n * Constructor.\n *\n * @param client client\n * @param request request\n */", "public", "ParsecHttpRequestRetryCallable", "(", "final", "AsyncHttpClient", "client", ",", "final", "ParsecAsyncHttpRequest", "request", ")", "{", "this", "(", "client", ",", "request", ",", "null", ")", ";", "}", "/**\n * Constructor.\n *\n * @param client client\n * @param request request\n * @param asyncHandler async handler\n */", "public", "ParsecHttpRequestRetryCallable", "(", "final", "AsyncHttpClient", "client", ",", "final", "ParsecAsyncHttpRequest", "request", ",", "final", "AsyncHandler", "<", "T", ">", "asyncHandler", ")", "{", "this", "(", "client", ",", "request", ",", "asyncHandler", ",", "DEFAULT_RETRY_INTERVAL", ")", ";", "}", "/**\n * Constructor.\n *\n * @param client client\n * @param request request\n * @param asyncHandler async handler\n * @param retryIntervalMillis retry interval in milliseconds\n */", "public", "ParsecHttpRequestRetryCallable", "(", "final", "AsyncHttpClient", "client", ",", "final", "ParsecAsyncHttpRequest", "request", ",", "final", "AsyncHandler", "<", "T", ">", "asyncHandler", ",", "long", "retryIntervalMillis", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "request", "=", "request", ";", "this", ".", "asyncHandler", "=", "asyncHandler", ";", "this", ".", "retryDelayer", "=", "new", "RetryDelayer", "(", "retryIntervalMillis", ")", ";", "responses", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "/**\n * Package-private Constructor. Only for unit-test usage.\n *\n * @param client client\n * @param request request\n * @param asyncHandler async handler\n * @param retryDelayer custom retry Delayer\n */", "ParsecHttpRequestRetryCallable", "(", "final", "AsyncHttpClient", "client", ",", "final", "ParsecAsyncHttpRequest", "request", ",", "final", "AsyncHandler", "<", "T", ">", "asyncHandler", ",", "RetryDelayer", "retryDelayer", ")", "{", "this", ".", "client", "=", "client", ";", "this", ".", "request", "=", "request", ";", "this", ".", "asyncHandler", "=", "asyncHandler", ";", "this", ".", "retryDelayer", "=", "retryDelayer", ";", "responses", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "/**\n * Check status code and handles retry if T is type {@link Response} or Ning {@link com.ning.http.client.Response}.\n *\n * @return T\n * @throws Exception exception\n */", "@", "Override", "public", "T", "call", "(", ")", "throws", "Exception", "{", "responses", ".", "clear", "(", ")", ";", "final", "Request", "ningRequest", "=", "request", ".", "getNingRequest", "(", ")", ";", "final", "List", "<", "Integer", ">", "retryStatusCodes", "=", "request", ".", "getRetryStatusCodes", "(", ")", ";", "final", "List", "<", "Class", "<", "?", "extends", "Throwable", ">", ">", "retryExceptions", "=", "request", ".", "getRetryExceptions", "(", ")", ";", "final", "int", "maxRetries", "=", "request", ".", "getMaxRetries", "(", ")", ";", "T", "response", ";", "Exception", "exception", ";", "int", "retries", "=", "0", ";", "for", "(", ";", ";", ")", "{", "response", "=", "null", ";", "exception", "=", "null", ";", "try", "{", "if", "(", "retries", ">", "0", ")", "{", "retryDelayer", ".", "delay", "(", ")", ";", "}", "response", "=", "executeRequest", "(", "ningRequest", ")", ";", "responses", ".", "add", "(", "response", ")", ";", "int", "statusCode", "=", "getStatusCode", "(", "response", ")", ";", "if", "(", "statusCode", "==", "-", "1", "||", "!", "retryStatusCodes", ".", "contains", "(", "statusCode", ")", ")", "{", "break", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "Throwable", "root", "=", "ExceptionUtils", ".", "getRootCause", "(", "e", ")", ";", "if", "(", "!", "retryExceptions", ".", "contains", "(", "root", ".", "getClass", "(", ")", ")", ")", "{", "throw", "e", ";", "}", "exception", "=", "e", ";", "}", "if", "(", "retries", "==", "maxRetries", ")", "{", "LOGGER", ".", "debug", "(", "\"", "Max retries reached: ", "\"", "+", "retries", "+", "\"", " (max: ", "\"", "+", "maxRetries", "+", "\"", ")", "\"", ")", ";", "break", ";", "}", "retries", "++", ";", "LOGGER", ".", "debug", "(", "\"", "Retry number: ", "\"", "+", "retries", "+", "\"", " (max: ", "\"", "+", "maxRetries", "+", "\"", ")", "\"", ")", ";", "}", "if", "(", "exception", "!=", "null", ")", "{", "throw", "exception", ";", "}", "return", "response", ";", "}", "/**\n * Execute Request.\n *\n * @param ningRequest Ning request\n * @return T\n * @throws InterruptedException Interrupted exception\n * @throws ExecutionException Execution exception\n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "private", "T", "executeRequest", "(", "Request", "ningRequest", ")", "throws", "InterruptedException", ",", "ExecutionException", "{", "if", "(", "asyncHandler", "!=", "null", ")", "{", "return", "client", ".", "executeRequest", "(", "ningRequest", ",", "asyncHandler", ")", ".", "get", "(", ")", ";", "}", "else", "{", "return", "(", "T", ")", "client", ".", "executeRequest", "(", "ningRequest", ")", ".", "get", "(", ")", ";", "}", "}", "/**\n * Get Responses.\n *\n * @return {@literal List<T>}\n */", "public", "List", "<", "T", ">", "getResponses", "(", ")", "{", "return", "responses", ";", "}", "/**\n * Gets Status Code from {@link Response} or Ning {@link com.ning.http.client.Response}.\n *\n * @param response T\n * @return status code or -1 if T is not type of {@link Response} or Ning {@link com.ning.http.client.Response}\n */", "private", "int", "getStatusCode", "(", "T", "response", ")", "{", "if", "(", "response", "instanceof", "Response", ")", "{", "return", "(", "(", "Response", ")", "response", ")", ".", "getStatus", "(", ")", ";", "}", "else", "if", "(", "response", "instanceof", "com", ".", "ning", ".", "http", ".", "client", ".", "Response", ")", "{", "return", "(", "(", "com", ".", "ning", ".", "http", ".", "client", ".", "Response", ")", "response", ")", ".", "getStatusCode", "(", ")", ";", "}", "else", "{", "return", "-", "1", ";", "}", "}", "/**\n * Package-private, this is only for unit-testing.\n * @return retryDelayer\n */", "RetryDelayer", "getRetryDelayer", "(", ")", "{", "return", "retryDelayer", ";", "}", "/**\n * Extract delay mechanism as a class to let it be testable\n */", "public", "class", "RetryDelayer", "{", "private", "final", "long", "retryIntervalMillis", ";", "RetryDelayer", "(", "long", "retryIntervalMillis", ")", "{", "this", ".", "retryIntervalMillis", "=", "retryIntervalMillis", ";", "}", "public", "void", "delay", "(", ")", "throws", "InterruptedException", "{", "TimeUnit", ".", "MILLISECONDS", ".", "sleep", "(", "retryIntervalMillis", ")", ";", "}", "/**\n * Package-private, this is only for unit-testing.\n * @return retryIntervalMillis\n */", "long", "getRetryIntervalMillis", "(", ")", "{", "return", "retryIntervalMillis", ";", "}", "}", "}" ]
{@link Callable} implementation that handles HTTP request retry based on response status code.
[ "{", "@link", "Callable", "}", "implementation", "that", "handles", "HTTP", "request", "retry", "based", "on", "response", "status", "code", "." ]
[ "// when this is not the first try (i.e. is re-trying), delay an interval" ]
[ { "param": "Callable<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Callable<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bbc1d5ccebece7d16c2fa4876c81256fa7d66cc
thaingo/parsec-libraries
parsec-clients/src/main/java/com/yahoo/parsec/clients/ParsecHttpRequestRetryCallable.java
[ "Apache-2.0" ]
Java
RetryDelayer
/** * Extract delay mechanism as a class to let it be testable */
Extract delay mechanism as a class to let it be testable
[ "Extract", "delay", "mechanism", "as", "a", "class", "to", "let", "it", "be", "testable" ]
public class RetryDelayer { private final long retryIntervalMillis; RetryDelayer(long retryIntervalMillis) { this.retryIntervalMillis = retryIntervalMillis; } public void delay() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(retryIntervalMillis); } /** * Package-private, this is only for unit-testing. * @return retryIntervalMillis */ long getRetryIntervalMillis() { return retryIntervalMillis; } }
[ "public", "class", "RetryDelayer", "{", "private", "final", "long", "retryIntervalMillis", ";", "RetryDelayer", "(", "long", "retryIntervalMillis", ")", "{", "this", ".", "retryIntervalMillis", "=", "retryIntervalMillis", ";", "}", "public", "void", "delay", "(", ")", "throws", "InterruptedException", "{", "TimeUnit", ".", "MILLISECONDS", ".", "sleep", "(", "retryIntervalMillis", ")", ";", "}", "/**\n * Package-private, this is only for unit-testing.\n * @return retryIntervalMillis\n */", "long", "getRetryIntervalMillis", "(", ")", "{", "return", "retryIntervalMillis", ";", "}", "}" ]
Extract delay mechanism as a class to let it be testable
[ "Extract", "delay", "mechanism", "as", "a", "class", "to", "let", "it", "be", "testable" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bbfc84c41ae52a1fdb361129aebf2a2cd5d218d
marcosdanix/dice-thrower
src/main/java/danix/gui/DiceThrowerView.java
[ "MIT" ]
Java
DiceThrowerView
/** * @author Marcos Pires * */
@author Marcos Pires
[ "@author", "Marcos", "Pires" ]
public class DiceThrowerView { protected static final int SPRITE_SIZE = 50; private boolean done; private BufferedImage[] diceSprites; private DiceThrowerModel model; private JFrame frame; private DiceDisplayView dicePanel; private JButton btnDice; private JFormattedTextField textField; /** * Create the application. */ public DiceThrowerView(DiceThrowerModel model) { this.model = model; done = false; EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); loadResources(); initialize(); } catch (Exception e) { e.printStackTrace(); } } }); } /** * loads the dice sprites */ private synchronized void loadResources() throws IOException { diceSprites = new BufferedImage[6]; File sprite = new File("sprites/spr_dice.png"); System.out.println("Loading sprite: " + sprite.getAbsolutePath()); BufferedImage diceSpriteFile = ImageIO.read(sprite); for (int i=0; i<6; ++i) { diceSprites[i] = diceSpriteFile.getSubimage(i*SPRITE_SIZE, 0, SPRITE_SIZE, SPRITE_SIZE); } System.out.println("Done"); } /** * Initialize the contents of the frame. */ private synchronized void initialize() { frame = new JFrame("Dice Thrower Prototype"); frame.getContentPane().addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent arg0) { dicePanel.readjustLayout(); } }); //frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 12)); JPanel panel = new JPanel(); textField = new JFormattedTextField(new NumberFormatter()); btnDice = new JButton("Throw Dice"); JScrollPane scrollPane = new JScrollPane(); GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE) .addComponent(panel, GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)) .addContainerGap()) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE) .addContainerGap()) ); dicePanel = new DiceDisplayView(model, diceSprites); dicePanel.setBackground(Color.LIGHT_GRAY); scrollPane.setViewportView(dicePanel); dicePanel.setLayout(new GridLayout(0, 1, 5, 20)); JLabel lblNumberOfDice = new JLabel("Number of dice:"); DiceResultView diceResult = new DiceResultView(model); //diceResult.setText("Result:"); GroupLayout gl_panel = new GroupLayout(panel); gl_panel.setHorizontalGroup( gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup() .addComponent(lblNumberOfDice) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(textField, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(diceResult, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, 168, Short.MAX_VALUE) .addComponent(btnDice)) ); gl_panel.setVerticalGroup( gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup() .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE) .addComponent(lblNumberOfDice) .addComponent(btnDice) .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(diceResult, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panel.setLayout(gl_panel); panel.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{textField, btnDice})); frame.getContentPane().setLayout(groupLayout); frame.setBounds(100, 100, 454, 303); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{frame.getContentPane(), panel, lblNumberOfDice, textField, btnDice})); done = true; this.notifyAll(); } //race conditions! public synchronized void setVisible() { waitIfNotDone(); frame.setVisible(true); } //race conditions! public synchronized void addDiceThrowListener(ActionListener diceThrowListener) { waitIfNotDone(); btnDice.addActionListener(diceThrowListener); } public int getDiceThrowInput() { return ((Long) textField.getValue()).intValue(); } private void waitIfNotDone() { while (!done) { try { this.wait(); } catch (InterruptedException e) {} } } @SuppressWarnings("serial") class DiceDisplayView extends JPanel implements Observer { BufferedImage sprites[]; int dicenum; public DiceDisplayView(DiceThrowerModel model, BufferedImage sprites[]) { super(); this.sprites = sprites; this.dicenum = 0; model.addObserver(this); } public void readjustLayout() { int hsize = this.getWidth(); GridLayout manager = (GridLayout) this.getLayout(); int spritesize = (int) (1.5 * DiceThrowerView.SPRITE_SIZE); int colnum = Math.min(hsize / spritesize, dicenum); manager.setColumns(Math.max(colnum, 1)); //It has to be at least one column this.revalidate(); this.repaint(); } @Override public void update(Observable arg0, Object arg1) { DiceThrowerModel model = (DiceThrowerModel) arg0; this.dicenum = model.getNumberOfDice(); //draw the panel 'ere this.removeAll(); for (int die : model) { this.add(newDiceComponent(die)); this.revalidate(); } this.readjustLayout(); } private Component newDiceComponent(int die) { return new JLabel(new ImageIcon(sprites[die-1])); } } @SuppressWarnings("serial") class DiceResultView extends JLabel implements Observer { public DiceResultView(DiceThrowerModel model) { super("Result:"); model.addObserver(this); } @Override public void update(Observable arg0, Object arg1) { DiceThrowerModel model = (DiceThrowerModel) arg0; this.setText("Result: " + model.getResult()); } } }
[ "public", "class", "DiceThrowerView", "{", "protected", "static", "final", "int", "SPRITE_SIZE", "=", "50", ";", "private", "boolean", "done", ";", "private", "BufferedImage", "[", "]", "diceSprites", ";", "private", "DiceThrowerModel", "model", ";", "private", "JFrame", "frame", ";", "private", "DiceDisplayView", "dicePanel", ";", "private", "JButton", "btnDice", ";", "private", "JFormattedTextField", "textField", ";", "/**\n\t * Create the application.\n\t */", "public", "DiceThrowerView", "(", "DiceThrowerModel", "model", ")", "{", "this", ".", "model", "=", "model", ";", "done", "=", "false", ";", "EventQueue", ".", "invokeLater", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "try", "{", "UIManager", ".", "setLookAndFeel", "(", "UIManager", ".", "getSystemLookAndFeelClassName", "(", ")", ")", ";", "loadResources", "(", ")", ";", "initialize", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", ")", ";", "}", "/**\n\t * loads the dice sprites\n\t */", "private", "synchronized", "void", "loadResources", "(", ")", "throws", "IOException", "{", "diceSprites", "=", "new", "BufferedImage", "[", "6", "]", ";", "File", "sprite", "=", "new", "File", "(", "\"", "sprites/spr_dice.png", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Loading sprite: ", "\"", "+", "sprite", ".", "getAbsolutePath", "(", ")", ")", ";", "BufferedImage", "diceSpriteFile", "=", "ImageIO", ".", "read", "(", "sprite", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "6", ";", "++", "i", ")", "{", "diceSprites", "[", "i", "]", "=", "diceSpriteFile", ".", "getSubimage", "(", "i", "*", "SPRITE_SIZE", ",", "0", ",", "SPRITE_SIZE", ",", "SPRITE_SIZE", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"", "Done", "\"", ")", ";", "}", "/**\n\t * Initialize the contents of the frame.\n\t */", "private", "synchronized", "void", "initialize", "(", ")", "{", "frame", "=", "new", "JFrame", "(", "\"", "Dice Thrower Prototype", "\"", ")", ";", "frame", ".", "getContentPane", "(", ")", ".", "addComponentListener", "(", "new", "ComponentAdapter", "(", ")", "{", "@", "Override", "public", "void", "componentResized", "(", "ComponentEvent", "arg0", ")", "{", "dicePanel", ".", "readjustLayout", "(", ")", ";", "}", "}", ")", ";", "JPanel", "panel", "=", "new", "JPanel", "(", ")", ";", "textField", "=", "new", "JFormattedTextField", "(", "new", "NumberFormatter", "(", ")", ")", ";", "btnDice", "=", "new", "JButton", "(", "\"", "Throw Dice", "\"", ")", ";", "JScrollPane", "scrollPane", "=", "new", "JScrollPane", "(", ")", ";", "GroupLayout", "groupLayout", "=", "new", "GroupLayout", "(", "frame", ".", "getContentPane", "(", ")", ")", ";", "groupLayout", ".", "setHorizontalGroup", "(", "groupLayout", ".", "createParallelGroup", "(", "Alignment", ".", "TRAILING", ")", ".", "addGroup", "(", "groupLayout", ".", "createSequentialGroup", "(", ")", ".", "addContainerGap", "(", ")", ".", "addGroup", "(", "groupLayout", ".", "createParallelGroup", "(", "Alignment", ".", "TRAILING", ")", ".", "addComponent", "(", "scrollPane", ",", "Alignment", ".", "LEADING", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "418", ",", "Short", ".", "MAX_VALUE", ")", ".", "addComponent", "(", "panel", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "418", ",", "Short", ".", "MAX_VALUE", ")", ")", ".", "addContainerGap", "(", ")", ")", ")", ";", "groupLayout", ".", "setVerticalGroup", "(", "groupLayout", ".", "createParallelGroup", "(", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "groupLayout", ".", "createSequentialGroup", "(", ")", ".", "addContainerGap", "(", ")", ".", "addComponent", "(", "panel", ",", "GroupLayout", ".", "PREFERRED_SIZE", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addGap", "(", "18", ")", ".", "addComponent", "(", "scrollPane", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "190", ",", "Short", ".", "MAX_VALUE", ")", ".", "addContainerGap", "(", ")", ")", ")", ";", "dicePanel", "=", "new", "DiceDisplayView", "(", "model", ",", "diceSprites", ")", ";", "dicePanel", ".", "setBackground", "(", "Color", ".", "LIGHT_GRAY", ")", ";", "scrollPane", ".", "setViewportView", "(", "dicePanel", ")", ";", "dicePanel", ".", "setLayout", "(", "new", "GridLayout", "(", "0", ",", "1", ",", "5", ",", "20", ")", ")", ";", "JLabel", "lblNumberOfDice", "=", "new", "JLabel", "(", "\"", "Number of dice:", "\"", ")", ";", "DiceResultView", "diceResult", "=", "new", "DiceResultView", "(", "model", ")", ";", "GroupLayout", "gl_panel", "=", "new", "GroupLayout", "(", "panel", ")", ";", "gl_panel", ".", "setHorizontalGroup", "(", "gl_panel", ".", "createParallelGroup", "(", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "gl_panel", ".", "createSequentialGroup", "(", ")", ".", "addComponent", "(", "lblNumberOfDice", ")", ".", "addPreferredGap", "(", "ComponentPlacement", ".", "UNRELATED", ")", ".", "addComponent", "(", "textField", ",", "GroupLayout", ".", "PREFERRED_SIZE", ",", "35", ",", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addPreferredGap", "(", "ComponentPlacement", ".", "UNRELATED", ")", ".", "addComponent", "(", "diceResult", ",", "GroupLayout", ".", "PREFERRED_SIZE", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addPreferredGap", "(", "ComponentPlacement", ".", "RELATED", ",", "168", ",", "Short", ".", "MAX_VALUE", ")", ".", "addComponent", "(", "btnDice", ")", ")", ")", ";", "gl_panel", ".", "setVerticalGroup", "(", "gl_panel", ".", "createParallelGroup", "(", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "gl_panel", ".", "createSequentialGroup", "(", ")", ".", "addGroup", "(", "gl_panel", ".", "createParallelGroup", "(", "Alignment", ".", "BASELINE", ")", ".", "addComponent", "(", "lblNumberOfDice", ")", ".", "addComponent", "(", "btnDice", ")", ".", "addComponent", "(", "textField", ",", "GroupLayout", ".", "PREFERRED_SIZE", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addComponent", "(", "diceResult", ",", "GroupLayout", ".", "PREFERRED_SIZE", ",", "GroupLayout", ".", "DEFAULT_SIZE", ",", "GroupLayout", ".", "PREFERRED_SIZE", ")", ")", ".", "addContainerGap", "(", "GroupLayout", ".", "DEFAULT_SIZE", ",", "Short", ".", "MAX_VALUE", ")", ")", ")", ";", "panel", ".", "setLayout", "(", "gl_panel", ")", ";", "panel", ".", "setFocusTraversalPolicy", "(", "new", "FocusTraversalOnArray", "(", "new", "Component", "[", "]", "{", "textField", ",", "btnDice", "}", ")", ")", ";", "frame", ".", "getContentPane", "(", ")", ".", "setLayout", "(", "groupLayout", ")", ";", "frame", ".", "setBounds", "(", "100", ",", "100", ",", "454", ",", "303", ")", ";", "frame", ".", "setDefaultCloseOperation", "(", "JFrame", ".", "EXIT_ON_CLOSE", ")", ";", "frame", ".", "setFocusTraversalPolicy", "(", "new", "FocusTraversalOnArray", "(", "new", "Component", "[", "]", "{", "frame", ".", "getContentPane", "(", ")", ",", "panel", ",", "lblNumberOfDice", ",", "textField", ",", "btnDice", "}", ")", ")", ";", "done", "=", "true", ";", "this", ".", "notifyAll", "(", ")", ";", "}", "public", "synchronized", "void", "setVisible", "(", ")", "{", "waitIfNotDone", "(", ")", ";", "frame", ".", "setVisible", "(", "true", ")", ";", "}", "public", "synchronized", "void", "addDiceThrowListener", "(", "ActionListener", "diceThrowListener", ")", "{", "waitIfNotDone", "(", ")", ";", "btnDice", ".", "addActionListener", "(", "diceThrowListener", ")", ";", "}", "public", "int", "getDiceThrowInput", "(", ")", "{", "return", "(", "(", "Long", ")", "textField", ".", "getValue", "(", ")", ")", ".", "intValue", "(", ")", ";", "}", "private", "void", "waitIfNotDone", "(", ")", "{", "while", "(", "!", "done", ")", "{", "try", "{", "this", ".", "wait", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "}", "}", "}", "@", "SuppressWarnings", "(", "\"", "serial", "\"", ")", "class", "DiceDisplayView", "extends", "JPanel", "implements", "Observer", "{", "BufferedImage", "sprites", "[", "]", ";", "int", "dicenum", ";", "public", "DiceDisplayView", "(", "DiceThrowerModel", "model", ",", "BufferedImage", "sprites", "[", "]", ")", "{", "super", "(", ")", ";", "this", ".", "sprites", "=", "sprites", ";", "this", ".", "dicenum", "=", "0", ";", "model", ".", "addObserver", "(", "this", ")", ";", "}", "public", "void", "readjustLayout", "(", ")", "{", "int", "hsize", "=", "this", ".", "getWidth", "(", ")", ";", "GridLayout", "manager", "=", "(", "GridLayout", ")", "this", ".", "getLayout", "(", ")", ";", "int", "spritesize", "=", "(", "int", ")", "(", "1.5", "*", "DiceThrowerView", ".", "SPRITE_SIZE", ")", ";", "int", "colnum", "=", "Math", ".", "min", "(", "hsize", "/", "spritesize", ",", "dicenum", ")", ";", "manager", ".", "setColumns", "(", "Math", ".", "max", "(", "colnum", ",", "1", ")", ")", ";", "this", ".", "revalidate", "(", ")", ";", "this", ".", "repaint", "(", ")", ";", "}", "@", "Override", "public", "void", "update", "(", "Observable", "arg0", ",", "Object", "arg1", ")", "{", "DiceThrowerModel", "model", "=", "(", "DiceThrowerModel", ")", "arg0", ";", "this", ".", "dicenum", "=", "model", ".", "getNumberOfDice", "(", ")", ";", "this", ".", "removeAll", "(", ")", ";", "for", "(", "int", "die", ":", "model", ")", "{", "this", ".", "add", "(", "newDiceComponent", "(", "die", ")", ")", ";", "this", ".", "revalidate", "(", ")", ";", "}", "this", ".", "readjustLayout", "(", ")", ";", "}", "private", "Component", "newDiceComponent", "(", "int", "die", ")", "{", "return", "new", "JLabel", "(", "new", "ImageIcon", "(", "sprites", "[", "die", "-", "1", "]", ")", ")", ";", "}", "}", "@", "SuppressWarnings", "(", "\"", "serial", "\"", ")", "class", "DiceResultView", "extends", "JLabel", "implements", "Observer", "{", "public", "DiceResultView", "(", "DiceThrowerModel", "model", ")", "{", "super", "(", "\"", "Result:", "\"", ")", ";", "model", ".", "addObserver", "(", "this", ")", ";", "}", "@", "Override", "public", "void", "update", "(", "Observable", "arg0", ",", "Object", "arg1", ")", "{", "DiceThrowerModel", "model", "=", "(", "DiceThrowerModel", ")", "arg0", ";", "this", ".", "setText", "(", "\"", "Result: ", "\"", "+", "model", ".", "getResult", "(", ")", ")", ";", "}", "}", "}" ]
@author Marcos Pires
[ "@author", "Marcos", "Pires" ]
[ "//frame.getContentPane().setFont(new Font(\"Tahoma\", Font.PLAIN, 12));", "//diceResult.setText(\"Result:\");", "//race conditions!", "//race conditions!", "//It has to be at least one column", "//draw the panel 'ere" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bc419e540d4cc1935477043c16f1fbef269baa4
ysmarks/treinamento-java8
src/introducaoLambda/test/LambdaInterfaceFunctionTest.java
[ "Apache-2.0" ]
Java
LambdaInterfaceFunctionTest
/** * * @author ysantos * Exemplo de uso da interface Functional * */
@author ysantos Exemplo de uso da interface Functional
[ "@author", "ysantos", "Exemplo", "de", "uso", "da", "interface", "Functional" ]
public class LambdaInterfaceFunctionTest { public static void main(String[] args) { List<Integer> integers = testeInterfaceFunction(Arrays.asList("Romario", "Bebeto", "Rai", "Dunga"), (String nome) -> nome.length()); System.out.println(integers); } public static <T, R> List<R> testeInterfaceFunction(List<T> list, Function<T, R> function) { List<R> result = new ArrayList<>(); for (T t : list) { result.add(function.apply(t)); } return result; } }
[ "public", "class", "LambdaInterfaceFunctionTest", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "List", "<", "Integer", ">", "integers", "=", "testeInterfaceFunction", "(", "Arrays", ".", "asList", "(", "\"", "Romario", "\"", ",", "\"", "Bebeto", "\"", ",", "\"", "Rai", "\"", ",", "\"", "Dunga", "\"", ")", ",", "(", "String", "nome", ")", "->", "nome", ".", "length", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "integers", ")", ";", "}", "public", "static", "<", "T", ",", "R", ">", "List", "<", "R", ">", "testeInterfaceFunction", "(", "List", "<", "T", ">", "list", ",", "Function", "<", "T", ",", "R", ">", "function", ")", "{", "List", "<", "R", ">", "result", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "T", "t", ":", "list", ")", "{", "result", ".", "add", "(", "function", ".", "apply", "(", "t", ")", ")", ";", "}", "return", "result", ";", "}", "}" ]
@author ysantos Exemplo de uso da interface Functional
[ "@author", "ysantos", "Exemplo", "de", "uso", "da", "interface", "Functional" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bc45b3b8c59cf0b73cc74e00791bbe77dcf136f
timchung92/PhillyCityData
src/logging/Logger.java
[ "MIT" ]
Java
Logger
/** * Singleton Logger class for logging output to a file * * @author Chris Henry + Tim Chung */
Singleton Logger class for logging output to a file @author Chris Henry + Tim Chung
[ "Singleton", "Logger", "class", "for", "logging", "output", "to", "a", "file", "@author", "Chris", "Henry", "+", "Tim", "Chung" ]
public class Logger { private static final String LOG_FILE_ERR_MSG = "log file must be writeable"; private PrintWriter out; private static Logger instance; /** * Creates or uses a file by the specified filename to be used for logging * * @param file the appendable FileWriter to use for logging */ private Logger(FileWriter file) { try { out = new PrintWriter(file); } catch (Exception e) { } } /** * Initializes the logger singleton using filename provided * * @param logFilename the filename to use for logging */ public static void init(String logFilename) { try { FileWriter logFile = new FileWriter(logFilename, true); instance = new Logger(logFile); } catch (IOException e) { System.out.println(LOG_FILE_ERR_MSG); System.exit(3); } } /** * Gets an instance of the Logger class * * @return a singleton instance of the logger class */ public static Logger getInstance() { return instance; } /** * Prints and flushes messages to the initialized log file * * @param msg the message to be printed to the log file */ public void log(String msg) { out.println(msg); out.flush(); } }
[ "public", "class", "Logger", "{", "private", "static", "final", "String", "LOG_FILE_ERR_MSG", "=", "\"", "log file must be writeable", "\"", ";", "private", "PrintWriter", "out", ";", "private", "static", "Logger", "instance", ";", "/**\r\n * Creates or uses a file by the specified filename to be used for logging\r\n *\r\n * @param file the appendable FileWriter to use for logging\r\n */", "private", "Logger", "(", "FileWriter", "file", ")", "{", "try", "{", "out", "=", "new", "PrintWriter", "(", "file", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "/**\r\n * Initializes the logger singleton using filename provided\r\n *\r\n * @param logFilename the filename to use for logging\r\n */", "public", "static", "void", "init", "(", "String", "logFilename", ")", "{", "try", "{", "FileWriter", "logFile", "=", "new", "FileWriter", "(", "logFilename", ",", "true", ")", ";", "instance", "=", "new", "Logger", "(", "logFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "LOG_FILE_ERR_MSG", ")", ";", "System", ".", "exit", "(", "3", ")", ";", "}", "}", "/**\r\n * Gets an instance of the Logger class\r\n *\r\n * @return a singleton instance of the logger class\r\n */", "public", "static", "Logger", "getInstance", "(", ")", "{", "return", "instance", ";", "}", "/**\r\n * Prints and flushes messages to the initialized log file\r\n *\r\n * @param msg the message to be printed to the log file\r\n */", "public", "void", "log", "(", "String", "msg", ")", "{", "out", ".", "println", "(", "msg", ")", ";", "out", ".", "flush", "(", ")", ";", "}", "}" ]
Singleton Logger class for logging output to a file
[ "Singleton", "Logger", "class", "for", "logging", "output", "to", "a", "file" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bcacd2688bc274f31384807bb53ea9a636bbc59
orangeclk/huiyin
src/main/java/com/orangeclk/controller/HomeController.java
[ "Apache-2.0" ]
Java
HomeController
/** * Created by orangeclk on 12/9/16. */
Created by orangeclk on 12/9/16.
[ "Created", "by", "orangeclk", "on", "12", "/", "9", "/", "16", "." ]
@Controller public class HomeController { @RequestMapping("/") public String home(Model model) { model.addAttribute(new Search()); return "home"; } @RequestMapping("/search") public String searchSubmit(final Search search) { boolean valid = search .getQuery() .chars() .mapToObj(Character::isDigit) .reduce(true, (x, y) -> x && y); if (valid) { return "redirect:/book/" + search.getQuery(); } else { return "error"; } } }
[ "@", "Controller", "public", "class", "HomeController", "{", "@", "RequestMapping", "(", "\"", "/", "\"", ")", "public", "String", "home", "(", "Model", "model", ")", "{", "model", ".", "addAttribute", "(", "new", "Search", "(", ")", ")", ";", "return", "\"", "home", "\"", ";", "}", "@", "RequestMapping", "(", "\"", "/search", "\"", ")", "public", "String", "searchSubmit", "(", "final", "Search", "search", ")", "{", "boolean", "valid", "=", "search", ".", "getQuery", "(", ")", ".", "chars", "(", ")", ".", "mapToObj", "(", "Character", "::", "isDigit", ")", ".", "reduce", "(", "true", ",", "(", "x", ",", "y", ")", "->", "x", "&&", "y", ")", ";", "if", "(", "valid", ")", "{", "return", "\"", "redirect:/book/", "\"", "+", "search", ".", "getQuery", "(", ")", ";", "}", "else", "{", "return", "\"", "error", "\"", ";", "}", "}", "}" ]
Created by orangeclk on 12/9/16.
[ "Created", "by", "orangeclk", "on", "12", "/", "9", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bce33b8758063bd41534ce88b81c5522727c823
wwjiang007/isis
viewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/scalars/reference/ReferencePanel.java
[ "Apache-2.0" ]
Java
ReferencePanel
/** * Panel for rendering scalars which of are of reference type (as opposed to * value types). */
Panel for rendering scalars which of are of reference type (as opposed to value types).
[ "Panel", "for", "rendering", "scalars", "which", "of", "are", "of", "reference", "type", "(", "as", "opposed", "to", "value", "types", ")", "." ]
public class ReferencePanel extends ScalarPanelSelectAbstract { private static final long serialVersionUID = 1L; private static final String ID_AUTO_COMPLETE = "autoComplete"; private static final String ID_ENTITY_TITLE_IF_NULL = "entityTitleIfNull"; private EntityLinkSelect2Panel entityLink; private EntityLinkSimplePanel entityLinkOutputFormat; private final boolean isCompactFormat; public ReferencePanel(final String id, final ScalarModel scalarModel) { super(id, scalarModel); this.isCompactFormat = !scalarModel.getRenderingHint().isRegular(); } @Override protected String obtainOutputFormat() { return select2.obtainInlinePromptModel().getObject(); } @Override protected Component createComponentForOutput(final String id) { val scalarModel = scalarModel(); final String name = scalarModel.getFriendlyName(); this.entityLinkOutputFormat = (EntityLinkSimplePanel) getComponentFactoryRegistry() .createComponent(ComponentType.ENTITY_LINK, scalarModel); entityLinkOutputFormat.setOutputMarkupId(true); entityLinkOutputFormat.setLabel(Model.of(name)); return CompactFragment.ENTITY_LINK .createFragment(id, this, scalarValueId->entityLinkOutputFormat); } @Override protected Optional<InputFragment> getInputFragmentType() { return Optional.of(InputFragment.SELECT2); } @Override protected FormComponent<ManagedObject> createFormComponent(final String id, final ScalarModel scalarModel) { this.entityLink = new EntityLinkSelect2Panel(ComponentType.ENTITY_LINK.getId(), this); entityLink.setRequired(scalarModel().isRequired()); this.select2 = createSelect2(ID_AUTO_COMPLETE); addSelect2Semantics(select2); entityLink.addOrReplace(select2.asComponent()); entityLink.setOutputMarkupId(true); return this.entityLink; } private void addSelect2Semantics(final Select2 select2) { val scalarModel = scalarModel(); final Settings settings = select2.getSettings(); // one of these three case should be true // (as per the isEditableWithEitherAutoCompleteOrChoices() guard above) if(scalarModel.hasChoices()) { settings.setPlaceholder(scalarModel.getFriendlyName()); } else if(scalarModel.hasAutoComplete()) { final int minLength = scalarModel.getAutoCompleteMinLength(); settings.setMinimumInputLength(minLength); settings.setPlaceholder(scalarModel.getFriendlyName()); } else if(hasObjectAutoComplete()) { Facets.autoCompleteMinLength(scalarModel.getScalarTypeSpec()) .ifPresent(settings::setMinimumInputLength); } } // -- ON BEFORE RENDER @Override protected void onInitializeEditable() { super.onInitializeEditable(); syncWithInput(); } @Override protected void onInitializeNotEditable() { super.onInitializeNotEditable(); syncWithInput(); } @Override protected void onInitializeReadonly(final String disableReason) { super.onInitializeReadonly(disableReason); syncWithInput(); } @Override protected void onNotEditable(final String disableReason, final Optional<AjaxRequestTarget> target) { super.onNotEditable(disableReason, target); if(isCompactFormat) return; entityLink.setEnabled(false); Wkt.attributeReplace(entityLink, "title", disableReason); } @Override protected void onEditable(final Optional<AjaxRequestTarget> target) { super.onEditable(target); if(isCompactFormat) return; entityLink.setEnabled(true); Wkt.attributeReplace(entityLink, "title", ""); } private Optional<MarkupContainer> lookupScalarValueContainer() { return Optional.ofNullable(getFieldFrame()) .flatMap(FieldFrame.SCALAR_VALUE_CONTAINER::lookupIn) .map(MarkupContainer.class::cast); } private void syncWithInput() { if(isCompactFormat) return; val scalarModel = scalarModel(); lookupScalarValueContainer() .ifPresent(container->{ val componentFactory = getComponentFactoryRegistry() .findComponentFactory(ComponentType.ENTITY_ICON_AND_TITLE, scalarModel); val iconAndTitle = componentFactory .createComponent(ComponentType.ENTITY_ICON_AND_TITLE.getId(), scalarModel); container.addOrReplace(iconAndTitle); val isInlinePrompt = scalarModel.isInlinePrompt(); if(isInlinePrompt) { iconAndTitle.setVisible(false); // bit of a hack... allows us to suppress the title using CSS //Wkt.cssAppend(iconAndTitle, "inlinePrompt"); } val adapter = scalarModel.getObject(); if(adapter != null || isInlinePrompt) { WktComponents.permanentlyHide(container, ID_ENTITY_TITLE_IF_NULL); } else { Wkt.labelAdd(container, ID_ENTITY_TITLE_IF_NULL, "(none)"); //XXX missing i18n support } }); // syncLinkWithInputIfAutoCompleteOrChoices if(isEditableWithEitherAutoCompleteOrChoices()) { if(select2 == null) { throw new IllegalStateException("select2 should be created already"); } else { // // the select2Choice already exists, so the widget has been rendered before. If it is // being re-rendered now, it may be because some other property/parameter was invalid. // when the form was submitted, the selected object (its oid as a string) would have // been saved as rawInput. If the property/parameter had been valid, then this rawInput // would be correctly converted and processed by the select2Choice's choiceProvider. However, // an invalid property/parameter means that the webpage is re-rendered in another request, // and the rawInput can no longer be interpreted. The net result is that the field appears // with no input. // // The fix is therefore (I think) simply to clear any rawInput, so that the select2Choice // renders its state from its model. // // see: FormComponent#getInputAsArray() // see: Select2Choice#renderInitializationScript() // select2.clearInput(); } if(fieldFrame != null) { WktComponents.permanentlyHide(fieldFrame, ID_ENTITY_TITLE_IF_NULL); } // syncUsability if(select2 != null) { final boolean mutability = entityLink.isEnableAllowed() && !getModel().isViewMode(); select2.setEnabled(mutability); } WktComponents.permanentlyHide(entityLink, ID_ENTITY_TITLE_IF_NULL); } else { // this is horrid; adds a label to the id // should instead be a 'temporary hide' WktComponents.permanentlyHide(entityLink, ID_AUTO_COMPLETE); // setSelect2(null); // this forces recreation next time around } } @Override protected ChoiceProvider<ObjectMemento> buildChoiceProvider() { val scalarModel = scalarModel(); if (scalarModel.hasChoices()) { return new ObjectAdapterMementoProviderForReferenceChoices(scalarModel); } if(scalarModel.hasAutoComplete()) { return new ObjectAdapterMementoProviderForReferenceParamOrPropertyAutoComplete(scalarModel); } return new ObjectAdapterMementoProviderForReferenceObjectAutoComplete(scalarModel); } // -- GET INPUT AS TITLE String getTitleForFormComponentInput() { val pendingElseCurrentAdapter = scalarModel().getObject(); return pendingElseCurrentAdapter != null ? pendingElseCurrentAdapter.titleString() : "(no object)"; } // -- CONVERT INPUT /** * Converts and validates the conversion of the raw input string into the object specified by * {@link FormComponent#getType()} and records any thrown {@link ConversionException}s. * Converted value is available through {@link FormComponent#getConvertedInput()}. * <p> * Usually the user should do custom conversions by specifying an {@link IConverter} by * registering it with the application by overriding {@link Application#getConverterLocator()}, * or at the component level by overriding {@link #getConverter(Class)} . */ void convertInput() { val scalarModel = scalarModel(); val pendingValue = scalarModel.proposedValue().getValue(); if(isEditableWithEitherAutoCompleteOrChoices()) { // flush changes to pending model val adapter = select2.getConvertedInputValue(); pendingValue.setValue(adapter); } entityLink.setConvertedInput(pendingValue.getValue()); } // -- @Override public void onUpdate(final AjaxRequestTarget target, final ScalarPanelAbstract scalarPanel) { super.onUpdate(target, scalarPanel); Wkt.javaScriptAdd(target, EventTopic.CLOSE_SELECT2, getMarkupId()); } // -- HELPERS private boolean isEditableWithEitherAutoCompleteOrChoices() { if(getModel().getRenderingHint().isInTable()) { return false; } // doesn't apply if not editable, either if(getModel().isViewMode()) { return false; } return getModel().hasChoices() || getModel().hasAutoComplete() || hasObjectAutoComplete(); } private boolean hasObjectAutoComplete() { return Facets.autoCompleteIsPresent(scalarModel().getScalarTypeSpec()); } }
[ "public", "class", "ReferencePanel", "extends", "ScalarPanelSelectAbstract", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "static", "final", "String", "ID_AUTO_COMPLETE", "=", "\"", "autoComplete", "\"", ";", "private", "static", "final", "String", "ID_ENTITY_TITLE_IF_NULL", "=", "\"", "entityTitleIfNull", "\"", ";", "private", "EntityLinkSelect2Panel", "entityLink", ";", "private", "EntityLinkSimplePanel", "entityLinkOutputFormat", ";", "private", "final", "boolean", "isCompactFormat", ";", "public", "ReferencePanel", "(", "final", "String", "id", ",", "final", "ScalarModel", "scalarModel", ")", "{", "super", "(", "id", ",", "scalarModel", ")", ";", "this", ".", "isCompactFormat", "=", "!", "scalarModel", ".", "getRenderingHint", "(", ")", ".", "isRegular", "(", ")", ";", "}", "@", "Override", "protected", "String", "obtainOutputFormat", "(", ")", "{", "return", "select2", ".", "obtainInlinePromptModel", "(", ")", ".", "getObject", "(", ")", ";", "}", "@", "Override", "protected", "Component", "createComponentForOutput", "(", "final", "String", "id", ")", "{", "val", "scalarModel", "=", "scalarModel", "(", ")", ";", "final", "String", "name", "=", "scalarModel", ".", "getFriendlyName", "(", ")", ";", "this", ".", "entityLinkOutputFormat", "=", "(", "EntityLinkSimplePanel", ")", "getComponentFactoryRegistry", "(", ")", ".", "createComponent", "(", "ComponentType", ".", "ENTITY_LINK", ",", "scalarModel", ")", ";", "entityLinkOutputFormat", ".", "setOutputMarkupId", "(", "true", ")", ";", "entityLinkOutputFormat", ".", "setLabel", "(", "Model", ".", "of", "(", "name", ")", ")", ";", "return", "CompactFragment", ".", "ENTITY_LINK", ".", "createFragment", "(", "id", ",", "this", ",", "scalarValueId", "->", "entityLinkOutputFormat", ")", ";", "}", "@", "Override", "protected", "Optional", "<", "InputFragment", ">", "getInputFragmentType", "(", ")", "{", "return", "Optional", ".", "of", "(", "InputFragment", ".", "SELECT2", ")", ";", "}", "@", "Override", "protected", "FormComponent", "<", "ManagedObject", ">", "createFormComponent", "(", "final", "String", "id", ",", "final", "ScalarModel", "scalarModel", ")", "{", "this", ".", "entityLink", "=", "new", "EntityLinkSelect2Panel", "(", "ComponentType", ".", "ENTITY_LINK", ".", "getId", "(", ")", ",", "this", ")", ";", "entityLink", ".", "setRequired", "(", "scalarModel", "(", ")", ".", "isRequired", "(", ")", ")", ";", "this", ".", "select2", "=", "createSelect2", "(", "ID_AUTO_COMPLETE", ")", ";", "addSelect2Semantics", "(", "select2", ")", ";", "entityLink", ".", "addOrReplace", "(", "select2", ".", "asComponent", "(", ")", ")", ";", "entityLink", ".", "setOutputMarkupId", "(", "true", ")", ";", "return", "this", ".", "entityLink", ";", "}", "private", "void", "addSelect2Semantics", "(", "final", "Select2", "select2", ")", "{", "val", "scalarModel", "=", "scalarModel", "(", ")", ";", "final", "Settings", "settings", "=", "select2", ".", "getSettings", "(", ")", ";", "if", "(", "scalarModel", ".", "hasChoices", "(", ")", ")", "{", "settings", ".", "setPlaceholder", "(", "scalarModel", ".", "getFriendlyName", "(", ")", ")", ";", "}", "else", "if", "(", "scalarModel", ".", "hasAutoComplete", "(", ")", ")", "{", "final", "int", "minLength", "=", "scalarModel", ".", "getAutoCompleteMinLength", "(", ")", ";", "settings", ".", "setMinimumInputLength", "(", "minLength", ")", ";", "settings", ".", "setPlaceholder", "(", "scalarModel", ".", "getFriendlyName", "(", ")", ")", ";", "}", "else", "if", "(", "hasObjectAutoComplete", "(", ")", ")", "{", "Facets", ".", "autoCompleteMinLength", "(", "scalarModel", ".", "getScalarTypeSpec", "(", ")", ")", ".", "ifPresent", "(", "settings", "::", "setMinimumInputLength", ")", ";", "}", "}", "@", "Override", "protected", "void", "onInitializeEditable", "(", ")", "{", "super", ".", "onInitializeEditable", "(", ")", ";", "syncWithInput", "(", ")", ";", "}", "@", "Override", "protected", "void", "onInitializeNotEditable", "(", ")", "{", "super", ".", "onInitializeNotEditable", "(", ")", ";", "syncWithInput", "(", ")", ";", "}", "@", "Override", "protected", "void", "onInitializeReadonly", "(", "final", "String", "disableReason", ")", "{", "super", ".", "onInitializeReadonly", "(", "disableReason", ")", ";", "syncWithInput", "(", ")", ";", "}", "@", "Override", "protected", "void", "onNotEditable", "(", "final", "String", "disableReason", ",", "final", "Optional", "<", "AjaxRequestTarget", ">", "target", ")", "{", "super", ".", "onNotEditable", "(", "disableReason", ",", "target", ")", ";", "if", "(", "isCompactFormat", ")", "return", ";", "entityLink", ".", "setEnabled", "(", "false", ")", ";", "Wkt", ".", "attributeReplace", "(", "entityLink", ",", "\"", "title", "\"", ",", "disableReason", ")", ";", "}", "@", "Override", "protected", "void", "onEditable", "(", "final", "Optional", "<", "AjaxRequestTarget", ">", "target", ")", "{", "super", ".", "onEditable", "(", "target", ")", ";", "if", "(", "isCompactFormat", ")", "return", ";", "entityLink", ".", "setEnabled", "(", "true", ")", ";", "Wkt", ".", "attributeReplace", "(", "entityLink", ",", "\"", "title", "\"", ",", "\"", "\"", ")", ";", "}", "private", "Optional", "<", "MarkupContainer", ">", "lookupScalarValueContainer", "(", ")", "{", "return", "Optional", ".", "ofNullable", "(", "getFieldFrame", "(", ")", ")", ".", "flatMap", "(", "FieldFrame", ".", "SCALAR_VALUE_CONTAINER", "::", "lookupIn", ")", ".", "map", "(", "MarkupContainer", ".", "class", "::", "cast", ")", ";", "}", "private", "void", "syncWithInput", "(", ")", "{", "if", "(", "isCompactFormat", ")", "return", ";", "val", "scalarModel", "=", "scalarModel", "(", ")", ";", "lookupScalarValueContainer", "(", ")", ".", "ifPresent", "(", "container", "->", "{", "val", "componentFactory", "=", "getComponentFactoryRegistry", "(", ")", ".", "findComponentFactory", "(", "ComponentType", ".", "ENTITY_ICON_AND_TITLE", ",", "scalarModel", ")", ";", "val", "iconAndTitle", "=", "componentFactory", ".", "createComponent", "(", "ComponentType", ".", "ENTITY_ICON_AND_TITLE", ".", "getId", "(", ")", ",", "scalarModel", ")", ";", "container", ".", "addOrReplace", "(", "iconAndTitle", ")", ";", "val", "isInlinePrompt", "=", "scalarModel", ".", "isInlinePrompt", "(", ")", ";", "if", "(", "isInlinePrompt", ")", "{", "iconAndTitle", ".", "setVisible", "(", "false", ")", ";", "}", "val", "adapter", "=", "scalarModel", ".", "getObject", "(", ")", ";", "if", "(", "adapter", "!=", "null", "||", "isInlinePrompt", ")", "{", "WktComponents", ".", "permanentlyHide", "(", "container", ",", "ID_ENTITY_TITLE_IF_NULL", ")", ";", "}", "else", "{", "Wkt", ".", "labelAdd", "(", "container", ",", "ID_ENTITY_TITLE_IF_NULL", ",", "\"", "(none)", "\"", ")", ";", "}", "}", ")", ";", "if", "(", "isEditableWithEitherAutoCompleteOrChoices", "(", ")", ")", "{", "if", "(", "select2", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "select2 should be created already", "\"", ")", ";", "}", "else", "{", "select2", ".", "clearInput", "(", ")", ";", "}", "if", "(", "fieldFrame", "!=", "null", ")", "{", "WktComponents", ".", "permanentlyHide", "(", "fieldFrame", ",", "ID_ENTITY_TITLE_IF_NULL", ")", ";", "}", "if", "(", "select2", "!=", "null", ")", "{", "final", "boolean", "mutability", "=", "entityLink", ".", "isEnableAllowed", "(", ")", "&&", "!", "getModel", "(", ")", ".", "isViewMode", "(", ")", ";", "select2", ".", "setEnabled", "(", "mutability", ")", ";", "}", "WktComponents", ".", "permanentlyHide", "(", "entityLink", ",", "ID_ENTITY_TITLE_IF_NULL", ")", ";", "}", "else", "{", "WktComponents", ".", "permanentlyHide", "(", "entityLink", ",", "ID_AUTO_COMPLETE", ")", ";", "}", "}", "@", "Override", "protected", "ChoiceProvider", "<", "ObjectMemento", ">", "buildChoiceProvider", "(", ")", "{", "val", "scalarModel", "=", "scalarModel", "(", ")", ";", "if", "(", "scalarModel", ".", "hasChoices", "(", ")", ")", "{", "return", "new", "ObjectAdapterMementoProviderForReferenceChoices", "(", "scalarModel", ")", ";", "}", "if", "(", "scalarModel", ".", "hasAutoComplete", "(", ")", ")", "{", "return", "new", "ObjectAdapterMementoProviderForReferenceParamOrPropertyAutoComplete", "(", "scalarModel", ")", ";", "}", "return", "new", "ObjectAdapterMementoProviderForReferenceObjectAutoComplete", "(", "scalarModel", ")", ";", "}", "String", "getTitleForFormComponentInput", "(", ")", "{", "val", "pendingElseCurrentAdapter", "=", "scalarModel", "(", ")", ".", "getObject", "(", ")", ";", "return", "pendingElseCurrentAdapter", "!=", "null", "?", "pendingElseCurrentAdapter", ".", "titleString", "(", ")", ":", "\"", "(no object)", "\"", ";", "}", "/**\n * Converts and validates the conversion of the raw input string into the object specified by\n * {@link FormComponent#getType()} and records any thrown {@link ConversionException}s.\n * Converted value is available through {@link FormComponent#getConvertedInput()}.\n * <p>\n * Usually the user should do custom conversions by specifying an {@link IConverter} by\n * registering it with the application by overriding {@link Application#getConverterLocator()},\n * or at the component level by overriding {@link #getConverter(Class)} .\n */", "void", "convertInput", "(", ")", "{", "val", "scalarModel", "=", "scalarModel", "(", ")", ";", "val", "pendingValue", "=", "scalarModel", ".", "proposedValue", "(", ")", ".", "getValue", "(", ")", ";", "if", "(", "isEditableWithEitherAutoCompleteOrChoices", "(", ")", ")", "{", "val", "adapter", "=", "select2", ".", "getConvertedInputValue", "(", ")", ";", "pendingValue", ".", "setValue", "(", "adapter", ")", ";", "}", "entityLink", ".", "setConvertedInput", "(", "pendingValue", ".", "getValue", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onUpdate", "(", "final", "AjaxRequestTarget", "target", ",", "final", "ScalarPanelAbstract", "scalarPanel", ")", "{", "super", ".", "onUpdate", "(", "target", ",", "scalarPanel", ")", ";", "Wkt", ".", "javaScriptAdd", "(", "target", ",", "EventTopic", ".", "CLOSE_SELECT2", ",", "getMarkupId", "(", ")", ")", ";", "}", "private", "boolean", "isEditableWithEitherAutoCompleteOrChoices", "(", ")", "{", "if", "(", "getModel", "(", ")", ".", "getRenderingHint", "(", ")", ".", "isInTable", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "getModel", "(", ")", ".", "isViewMode", "(", ")", ")", "{", "return", "false", ";", "}", "return", "getModel", "(", ")", ".", "hasChoices", "(", ")", "||", "getModel", "(", ")", ".", "hasAutoComplete", "(", ")", "||", "hasObjectAutoComplete", "(", ")", ";", "}", "private", "boolean", "hasObjectAutoComplete", "(", ")", "{", "return", "Facets", ".", "autoCompleteIsPresent", "(", "scalarModel", "(", ")", ".", "getScalarTypeSpec", "(", ")", ")", ";", "}", "}" ]
Panel for rendering scalars which of are of reference type (as opposed to value types).
[ "Panel", "for", "rendering", "scalars", "which", "of", "are", "of", "reference", "type", "(", "as", "opposed", "to", "value", "types", ")", "." ]
[ "// one of these three case should be true", "// (as per the isEditableWithEitherAutoCompleteOrChoices() guard above)", "// -- ON BEFORE RENDER", "// bit of a hack... allows us to suppress the title using CSS", "//Wkt.cssAppend(iconAndTitle, \"inlinePrompt\");", "//XXX missing i18n support", "// syncLinkWithInputIfAutoCompleteOrChoices", "//", "// the select2Choice already exists, so the widget has been rendered before. If it is", "// being re-rendered now, it may be because some other property/parameter was invalid.", "// when the form was submitted, the selected object (its oid as a string) would have", "// been saved as rawInput. If the property/parameter had been valid, then this rawInput", "// would be correctly converted and processed by the select2Choice's choiceProvider. However,", "// an invalid property/parameter means that the webpage is re-rendered in another request,", "// and the rawInput can no longer be interpreted. The net result is that the field appears", "// with no input.", "//", "// The fix is therefore (I think) simply to clear any rawInput, so that the select2Choice", "// renders its state from its model.", "//", "// see: FormComponent#getInputAsArray()", "// see: Select2Choice#renderInitializationScript()", "//", "// syncUsability", "// this is horrid; adds a label to the id", "// should instead be a 'temporary hide'", "// setSelect2(null); // this forces recreation next time around", "// -- GET INPUT AS TITLE", "// -- CONVERT INPUT", "// flush changes to pending model", "// --", "// -- HELPERS", "// doesn't apply if not editable, either" ]
[ { "param": "ScalarPanelSelectAbstract", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ScalarPanelSelectAbstract", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bce7428c036da8d61ce1838a5d1db9933b1b12e
the-programmers-hangout/mimic
src/main/java/uk/co/markg/mimic/db/Keys.java
[ "MIT" ]
Java
Keys
/** * A class modelling foreign key relationships and constraints of tables of * the <code></code> schema. */
A class modelling foreign key relationships and constraints of tables of the schema.
[ "A", "class", "modelling", "foreign", "key", "relationships", "and", "constraints", "of", "tables", "of", "the", "schema", "." ]
@SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Keys { // ------------------------------------------------------------------------- // IDENTITY definitions // ------------------------------------------------------------------------- public static final Identity<UsageRecord, Integer> IDENTITY_USAGE = Identities0.IDENTITY_USAGE; // ------------------------------------------------------------------------- // UNIQUE and PRIMARY KEY definitions // ------------------------------------------------------------------------- public static final UniqueKey<ChannelsRecord> CHANNELS_PKEY = UniqueKeys0.CHANNELS_PKEY; public static final UniqueKey<MessagesRecord> MESSAGES_PKEY = UniqueKeys0.MESSAGES_PKEY; public static final UniqueKey<ServerConfigRecord> SERVER_CONFIG_PKEY = UniqueKeys0.SERVER_CONFIG_PKEY; public static final UniqueKey<UsageRecord> USAGE_PKEY = UniqueKeys0.USAGE_PKEY; // ------------------------------------------------------------------------- // FOREIGN KEY definitions // ------------------------------------------------------------------------- public static final ForeignKey<MessagesRecord, ChannelsRecord> MESSAGES__CHANNEL_FKEY = ForeignKeys0.MESSAGES__CHANNEL_FKEY; // ------------------------------------------------------------------------- // [#1459] distribute members to avoid static initialisers > 64kb // ------------------------------------------------------------------------- private static class Identities0 { public static Identity<UsageRecord, Integer> IDENTITY_USAGE = Internal.createIdentity(Usage.USAGE, Usage.USAGE.ID); } private static class UniqueKeys0 { public static final UniqueKey<ChannelsRecord> CHANNELS_PKEY = Internal.createUniqueKey(Channels.CHANNELS, "channels_pkey", new TableField[] { Channels.CHANNELS.CHANNELID }, true); public static final UniqueKey<MessagesRecord> MESSAGES_PKEY = Internal.createUniqueKey(Messages.MESSAGES, "messages_pkey", new TableField[] { Messages.MESSAGES.MESSAGEID }, true); public static final UniqueKey<ServerConfigRecord> SERVER_CONFIG_PKEY = Internal.createUniqueKey(ServerConfig.SERVER_CONFIG, "server_config_pkey", new TableField[] { ServerConfig.SERVER_CONFIG.SERVERID }, true); public static final UniqueKey<UsageRecord> USAGE_PKEY = Internal.createUniqueKey(Usage.USAGE, "usage_pkey", new TableField[] { Usage.USAGE.ID }, true); } private static class ForeignKeys0 { public static final ForeignKey<MessagesRecord, ChannelsRecord> MESSAGES__CHANNEL_FKEY = Internal.createForeignKey(Keys.CHANNELS_PKEY, Messages.MESSAGES, "channel_fkey", new TableField[] { Messages.MESSAGES.CHANNELID }, true); } }
[ "@", "SuppressWarnings", "(", "{", "\"", "all", "\"", ",", "\"", "unchecked", "\"", ",", "\"", "rawtypes", "\"", "}", ")", "public", "class", "Keys", "{", "public", "static", "final", "Identity", "<", "UsageRecord", ",", "Integer", ">", "IDENTITY_USAGE", "=", "Identities0", ".", "IDENTITY_USAGE", ";", "public", "static", "final", "UniqueKey", "<", "ChannelsRecord", ">", "CHANNELS_PKEY", "=", "UniqueKeys0", ".", "CHANNELS_PKEY", ";", "public", "static", "final", "UniqueKey", "<", "MessagesRecord", ">", "MESSAGES_PKEY", "=", "UniqueKeys0", ".", "MESSAGES_PKEY", ";", "public", "static", "final", "UniqueKey", "<", "ServerConfigRecord", ">", "SERVER_CONFIG_PKEY", "=", "UniqueKeys0", ".", "SERVER_CONFIG_PKEY", ";", "public", "static", "final", "UniqueKey", "<", "UsageRecord", ">", "USAGE_PKEY", "=", "UniqueKeys0", ".", "USAGE_PKEY", ";", "public", "static", "final", "ForeignKey", "<", "MessagesRecord", ",", "ChannelsRecord", ">", "MESSAGES__CHANNEL_FKEY", "=", "ForeignKeys0", ".", "MESSAGES__CHANNEL_FKEY", ";", "private", "static", "class", "Identities0", "{", "public", "static", "Identity", "<", "UsageRecord", ",", "Integer", ">", "IDENTITY_USAGE", "=", "Internal", ".", "createIdentity", "(", "Usage", ".", "USAGE", ",", "Usage", ".", "USAGE", ".", "ID", ")", ";", "}", "private", "static", "class", "UniqueKeys0", "{", "public", "static", "final", "UniqueKey", "<", "ChannelsRecord", ">", "CHANNELS_PKEY", "=", "Internal", ".", "createUniqueKey", "(", "Channels", ".", "CHANNELS", ",", "\"", "channels_pkey", "\"", ",", "new", "TableField", "[", "]", "{", "Channels", ".", "CHANNELS", ".", "CHANNELID", "}", ",", "true", ")", ";", "public", "static", "final", "UniqueKey", "<", "MessagesRecord", ">", "MESSAGES_PKEY", "=", "Internal", ".", "createUniqueKey", "(", "Messages", ".", "MESSAGES", ",", "\"", "messages_pkey", "\"", ",", "new", "TableField", "[", "]", "{", "Messages", ".", "MESSAGES", ".", "MESSAGEID", "}", ",", "true", ")", ";", "public", "static", "final", "UniqueKey", "<", "ServerConfigRecord", ">", "SERVER_CONFIG_PKEY", "=", "Internal", ".", "createUniqueKey", "(", "ServerConfig", ".", "SERVER_CONFIG", ",", "\"", "server_config_pkey", "\"", ",", "new", "TableField", "[", "]", "{", "ServerConfig", ".", "SERVER_CONFIG", ".", "SERVERID", "}", ",", "true", ")", ";", "public", "static", "final", "UniqueKey", "<", "UsageRecord", ">", "USAGE_PKEY", "=", "Internal", ".", "createUniqueKey", "(", "Usage", ".", "USAGE", ",", "\"", "usage_pkey", "\"", ",", "new", "TableField", "[", "]", "{", "Usage", ".", "USAGE", ".", "ID", "}", ",", "true", ")", ";", "}", "private", "static", "class", "ForeignKeys0", "{", "public", "static", "final", "ForeignKey", "<", "MessagesRecord", ",", "ChannelsRecord", ">", "MESSAGES__CHANNEL_FKEY", "=", "Internal", ".", "createForeignKey", "(", "Keys", ".", "CHANNELS_PKEY", ",", "Messages", ".", "MESSAGES", ",", "\"", "channel_fkey", "\"", ",", "new", "TableField", "[", "]", "{", "Messages", ".", "MESSAGES", ".", "CHANNELID", "}", ",", "true", ")", ";", "}", "}" ]
A class modelling foreign key relationships and constraints of tables of the <code></code> schema.
[ "A", "class", "modelling", "foreign", "key", "relationships", "and", "constraints", "of", "tables", "of", "the", "<code", ">", "<", "/", "code", ">", "schema", "." ]
[ "// -------------------------------------------------------------------------", "// IDENTITY definitions", "// -------------------------------------------------------------------------", "// -------------------------------------------------------------------------", "// UNIQUE and PRIMARY KEY definitions", "// -------------------------------------------------------------------------", "// -------------------------------------------------------------------------", "// FOREIGN KEY definitions", "// -------------------------------------------------------------------------", "// -------------------------------------------------------------------------", "// [#1459] distribute members to avoid static initialisers > 64kb", "// -------------------------------------------------------------------------" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bce86adbad94ff1f57d24af3f199c25ccafe04b
Localista-Tech/graphhopper
core/src/main/java/com/graphhopper/routing/weighting/TimeDependentAccessWeighting.java
[ "Apache-2.0" ]
Java
TimeDependentAccessWeighting
/** * Calculates the fastest route with the specified vehicle (VehicleEncoder). Calculates the time-dependent weight * in seconds. * <p> * * @author Andrzej Oles */
Calculates the fastest route with the specified vehicle (VehicleEncoder). Calculates the time-dependent weight in seconds. @author Andrzej Oles
[ "Calculates", "the", "fastest", "route", "with", "the", "specified", "vehicle", "(", "VehicleEncoder", ")", ".", "Calculates", "the", "time", "-", "dependent", "weight", "in", "seconds", ".", "@author", "Andrzej", "Oles" ]
public class TimeDependentAccessWeighting extends AbstractAdjustedWeighting { private TimeDependentAccessEdgeFilter edgeFilter; public TimeDependentAccessWeighting(Weighting weighting, GraphHopperStorage graph, FlagEncoder encoder) { super(weighting); this.edgeFilter = new TimeDependentAccessEdgeFilter(graph, encoder); } @Override public double calcWeight(EdgeIteratorState edge, boolean reverse, int prevOrNextEdgeId, long linkEnterTime) { if (edgeFilter.accept(edge, linkEnterTime)) { return superWeighting.calcWeight(edge, reverse, prevOrNextEdgeId, linkEnterTime); } else { return Double.POSITIVE_INFINITY; } } @Override public String getName() { return superWeighting.getName(); } @Override public String toString() { return "td_access" + "|" + superWeighting.toString(); } @Override public boolean isTimeDependent() { return true; } }
[ "public", "class", "TimeDependentAccessWeighting", "extends", "AbstractAdjustedWeighting", "{", "private", "TimeDependentAccessEdgeFilter", "edgeFilter", ";", "public", "TimeDependentAccessWeighting", "(", "Weighting", "weighting", ",", "GraphHopperStorage", "graph", ",", "FlagEncoder", "encoder", ")", "{", "super", "(", "weighting", ")", ";", "this", ".", "edgeFilter", "=", "new", "TimeDependentAccessEdgeFilter", "(", "graph", ",", "encoder", ")", ";", "}", "@", "Override", "public", "double", "calcWeight", "(", "EdgeIteratorState", "edge", ",", "boolean", "reverse", ",", "int", "prevOrNextEdgeId", ",", "long", "linkEnterTime", ")", "{", "if", "(", "edgeFilter", ".", "accept", "(", "edge", ",", "linkEnterTime", ")", ")", "{", "return", "superWeighting", ".", "calcWeight", "(", "edge", ",", "reverse", ",", "prevOrNextEdgeId", ",", "linkEnterTime", ")", ";", "}", "else", "{", "return", "Double", ".", "POSITIVE_INFINITY", ";", "}", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "superWeighting", ".", "getName", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "td_access", "\"", "+", "\"", "|", "\"", "+", "superWeighting", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "boolean", "isTimeDependent", "(", ")", "{", "return", "true", ";", "}", "}" ]
Calculates the fastest route with the specified vehicle (VehicleEncoder).
[ "Calculates", "the", "fastest", "route", "with", "the", "specified", "vehicle", "(", "VehicleEncoder", ")", "." ]
[]
[ { "param": "AbstractAdjustedWeighting", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractAdjustedWeighting", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bd099ac9db155a445ea4b11308845d291745921
maritimeconnectivity/ServiceRegistry
src/main/java/net/maritimeconnectivity/serviceregistry/services/DocService.java
[ "Apache-2.0" ]
Java
DocService
/** * Service Implementation for managing Doc. * * @author Nikolaos Vastardis (email: Nikolaos.Vastardis@gla-rad.org) */
Service Implementation for managing Doc.
[ "Service", "Implementation", "for", "managing", "Doc", "." ]
@Service @Slf4j @Transactional public class DocService { @Autowired private DocRepo docRepo; @Autowired private DesignRepo designRepo; @Autowired private SpecificationRepo specificationRepo; @Autowired private InstanceRepo instanceRepo; /** * Save a doc. * * @param doc the entity to save * @return the persisted entity */ public Doc save(Doc doc){ log.debug("Request to save Doc : {}", doc); this.docRepo.save(doc); // Save the linked designed, if any Optional.of(this.designRepo) .map(DesignRepo::findAllWithEagerRelationships) .orElse(Collections.emptyList()) .stream() .filter(d -> d.getDesignAsDoc() != null && d.getDesignAsDoc().getId() == doc.getId()) .forEach(d -> { log.debug("Updating Linked Specification: {}", d); this.designRepo.save(d); }); // Save the linked specifications, if any Optional.of(this.specificationRepo) .map(SpecificationRepo::findAllWithEagerRelationships) .orElse(Collections.emptyList()) .stream() .filter(s -> s.getSpecAsDoc() != null && s.getSpecAsDoc().getId() == doc.getId()) .forEach(s -> { log.debug("Updating Linked Specification: {}", s); this.specificationRepo.save(s); }); // Save the linked instances, if any Optional.of(this.instanceRepo) .map(InstanceRepo::findAllWithEagerRelationships) .orElse(Collections.emptyList()) .stream() .filter(i -> i.getInstanceAsDoc() != null && i.getInstanceAsDoc().getId() == doc.getId()) .forEach(i -> { log.debug("Updating Linked Instance: {}", i); this.instanceRepo.save(i); }); return doc; } /** * Get all the docs. * * @param pageable the pagination information * @return the list of entities */ @Transactional(readOnly = true) public Page<Doc> findAll(Pageable pageable) { this.log.debug("Request to get all Docs"); Page<Doc> result = this.docRepo.findAll(pageable); return result; } /** * Get one doc by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public Doc findOne(Long id) { this.log.debug("Request to get Doc : {}", id); Doc doc = this.docRepo.findById(id).orElse(null); return doc; } /** * Delete the doc by id. * * @param id the id of the entity */ public void delete(Long id) { log.debug("Request to delete Doc : {}", id); this.docRepo.deleteById(id); } }
[ "@", "Service", "@", "Slf4j", "@", "Transactional", "public", "class", "DocService", "{", "@", "Autowired", "private", "DocRepo", "docRepo", ";", "@", "Autowired", "private", "DesignRepo", "designRepo", ";", "@", "Autowired", "private", "SpecificationRepo", "specificationRepo", ";", "@", "Autowired", "private", "InstanceRepo", "instanceRepo", ";", "/**\n * Save a doc.\n *\n * @param doc the entity to save\n * @return the persisted entity\n */", "public", "Doc", "save", "(", "Doc", "doc", ")", "{", "log", ".", "debug", "(", "\"", "Request to save Doc : {}", "\"", ",", "doc", ")", ";", "this", ".", "docRepo", ".", "save", "(", "doc", ")", ";", "Optional", ".", "of", "(", "this", ".", "designRepo", ")", ".", "map", "(", "DesignRepo", "::", "findAllWithEagerRelationships", ")", ".", "orElse", "(", "Collections", ".", "emptyList", "(", ")", ")", ".", "stream", "(", ")", ".", "filter", "(", "d", "->", "d", ".", "getDesignAsDoc", "(", ")", "!=", "null", "&&", "d", ".", "getDesignAsDoc", "(", ")", ".", "getId", "(", ")", "==", "doc", ".", "getId", "(", ")", ")", ".", "forEach", "(", "d", "->", "{", "log", ".", "debug", "(", "\"", "Updating Linked Specification: {}", "\"", ",", "d", ")", ";", "this", ".", "designRepo", ".", "save", "(", "d", ")", ";", "}", ")", ";", "Optional", ".", "of", "(", "this", ".", "specificationRepo", ")", ".", "map", "(", "SpecificationRepo", "::", "findAllWithEagerRelationships", ")", ".", "orElse", "(", "Collections", ".", "emptyList", "(", ")", ")", ".", "stream", "(", ")", ".", "filter", "(", "s", "->", "s", ".", "getSpecAsDoc", "(", ")", "!=", "null", "&&", "s", ".", "getSpecAsDoc", "(", ")", ".", "getId", "(", ")", "==", "doc", ".", "getId", "(", ")", ")", ".", "forEach", "(", "s", "->", "{", "log", ".", "debug", "(", "\"", "Updating Linked Specification: {}", "\"", ",", "s", ")", ";", "this", ".", "specificationRepo", ".", "save", "(", "s", ")", ";", "}", ")", ";", "Optional", ".", "of", "(", "this", ".", "instanceRepo", ")", ".", "map", "(", "InstanceRepo", "::", "findAllWithEagerRelationships", ")", ".", "orElse", "(", "Collections", ".", "emptyList", "(", ")", ")", ".", "stream", "(", ")", ".", "filter", "(", "i", "->", "i", ".", "getInstanceAsDoc", "(", ")", "!=", "null", "&&", "i", ".", "getInstanceAsDoc", "(", ")", ".", "getId", "(", ")", "==", "doc", ".", "getId", "(", ")", ")", ".", "forEach", "(", "i", "->", "{", "log", ".", "debug", "(", "\"", "Updating Linked Instance: {}", "\"", ",", "i", ")", ";", "this", ".", "instanceRepo", ".", "save", "(", "i", ")", ";", "}", ")", ";", "return", "doc", ";", "}", "/**\n * Get all the docs.\n *\n * @param pageable the pagination information\n * @return the list of entities\n */", "@", "Transactional", "(", "readOnly", "=", "true", ")", "public", "Page", "<", "Doc", ">", "findAll", "(", "Pageable", "pageable", ")", "{", "this", ".", "log", ".", "debug", "(", "\"", "Request to get all Docs", "\"", ")", ";", "Page", "<", "Doc", ">", "result", "=", "this", ".", "docRepo", ".", "findAll", "(", "pageable", ")", ";", "return", "result", ";", "}", "/**\n * Get one doc by id.\n *\n * @param id the id of the entity\n * @return the entity\n */", "@", "Transactional", "(", "readOnly", "=", "true", ")", "public", "Doc", "findOne", "(", "Long", "id", ")", "{", "this", ".", "log", ".", "debug", "(", "\"", "Request to get Doc : {}", "\"", ",", "id", ")", ";", "Doc", "doc", "=", "this", ".", "docRepo", ".", "findById", "(", "id", ")", ".", "orElse", "(", "null", ")", ";", "return", "doc", ";", "}", "/**\n * Delete the doc by id.\n *\n * @param id the id of the entity\n */", "public", "void", "delete", "(", "Long", "id", ")", "{", "log", ".", "debug", "(", "\"", "Request to delete Doc : {}", "\"", ",", "id", ")", ";", "this", ".", "docRepo", ".", "deleteById", "(", "id", ")", ";", "}", "}" ]
Service Implementation for managing Doc.
[ "Service", "Implementation", "for", "managing", "Doc", "." ]
[ "// Save the linked designed, if any", "// Save the linked specifications, if any", "// Save the linked instances, if any" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bd1c9b92ef8b83a022702ec9262122bc5331451
niallthomson/Spring-Mini-Profiler
src/main/java/org/devcodes/miniprofiler/entries/AbstractProfilerEntry.java
[ "MIT" ]
Java
AbstractProfilerEntry
/** * Base class for profiler entries, each of which represents a distinct section of code being profiled. * Examples of profiler entries include: * * <ul> * <li>HTTP requests</li> * <li>Method calls</li> * <li>Arbitrary sections of code</li> * <li>JDBC queries</li> * <li>View rendering</li> * <ul> * * @author Niall Thomson */
Base class for profiler entries, each of which represents a distinct section of code being profiled. Examples of profiler entries include. HTTP requests Method calls Arbitrary sections of code JDBC queries View rendering @author Niall Thomson
[ "Base", "class", "for", "profiler", "entries", "each", "of", "which", "represents", "a", "distinct", "section", "of", "code", "being", "profiled", ".", "Examples", "of", "profiler", "entries", "include", ".", "HTTP", "requests", "Method", "calls", "Arbitrary", "sections", "of", "code", "JDBC", "queries", "View", "rendering", "@author", "Niall", "Thomson" ]
public abstract class AbstractProfilerEntry implements IProfilerEntry { private long id; private String tag; private long startTime; private long duration; private long fromStart; private int depth; private List<QueryProfilerEntry> queries; private List<IProfilerEntry> children; private long queryTime; public AbstractProfilerEntry(String tag) { this.tag = tag; this.children = new ArrayList<IProfilerEntry>(); this.setQueries(new ArrayList<QueryProfilerEntry>()); } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public List<IProfilerEntry> getChildren() { return children; } public void setChildren(List<IProfilerEntry> children) { this.children = children; } public void addChild(IProfilerEntry entry) { this.children.add(entry); } public void setId(long id) { this.id = id; } public long getId() { return id; } public void completed(long endTime) { this.duration = endTime - this.startTime; } public void setFromStart(long fromStart) { this.fromStart = fromStart; } public long getFromStart() { return fromStart; } public abstract String getDisplayString(); public void setDepth(int depth) { this.depth = depth; } public int getDepth() { return depth; } public void addQuery(QueryProfilerEntry query) { this.queries.add(query); this.queryTime += query.getDuration(); } public void setQueries(List<QueryProfilerEntry> queries) { this.queries = queries; } public List<QueryProfilerEntry> getQueries() { return queries; } public void setQueryTime(long queryTime) { this.queryTime = queryTime; } public long getQueryTime() { return queryTime; } public void open(long rootStartTime) { long startTime = System.currentTimeMillis(); this.setStartTime(startTime); long fromStart = startTime - rootStartTime; this.setFromStart(fromStart); } public void close() { long endTime = System.currentTimeMillis(); this.setDuration(endTime - getStartTime()); } }
[ "public", "abstract", "class", "AbstractProfilerEntry", "implements", "IProfilerEntry", "{", "private", "long", "id", ";", "private", "String", "tag", ";", "private", "long", "startTime", ";", "private", "long", "duration", ";", "private", "long", "fromStart", ";", "private", "int", "depth", ";", "private", "List", "<", "QueryProfilerEntry", ">", "queries", ";", "private", "List", "<", "IProfilerEntry", ">", "children", ";", "private", "long", "queryTime", ";", "public", "AbstractProfilerEntry", "(", "String", "tag", ")", "{", "this", ".", "tag", "=", "tag", ";", "this", ".", "children", "=", "new", "ArrayList", "<", "IProfilerEntry", ">", "(", ")", ";", "this", ".", "setQueries", "(", "new", "ArrayList", "<", "QueryProfilerEntry", ">", "(", ")", ")", ";", "}", "public", "String", "getTag", "(", ")", "{", "return", "tag", ";", "}", "public", "void", "setTag", "(", "String", "tag", ")", "{", "this", ".", "tag", "=", "tag", ";", "}", "public", "long", "getStartTime", "(", ")", "{", "return", "startTime", ";", "}", "public", "void", "setStartTime", "(", "long", "startTime", ")", "{", "this", ".", "startTime", "=", "startTime", ";", "}", "public", "long", "getDuration", "(", ")", "{", "return", "duration", ";", "}", "public", "void", "setDuration", "(", "long", "duration", ")", "{", "this", ".", "duration", "=", "duration", ";", "}", "public", "List", "<", "IProfilerEntry", ">", "getChildren", "(", ")", "{", "return", "children", ";", "}", "public", "void", "setChildren", "(", "List", "<", "IProfilerEntry", ">", "children", ")", "{", "this", ".", "children", "=", "children", ";", "}", "public", "void", "addChild", "(", "IProfilerEntry", "entry", ")", "{", "this", ".", "children", ".", "add", "(", "entry", ")", ";", "}", "public", "void", "setId", "(", "long", "id", ")", "{", "this", ".", "id", "=", "id", ";", "}", "public", "long", "getId", "(", ")", "{", "return", "id", ";", "}", "public", "void", "completed", "(", "long", "endTime", ")", "{", "this", ".", "duration", "=", "endTime", "-", "this", ".", "startTime", ";", "}", "public", "void", "setFromStart", "(", "long", "fromStart", ")", "{", "this", ".", "fromStart", "=", "fromStart", ";", "}", "public", "long", "getFromStart", "(", ")", "{", "return", "fromStart", ";", "}", "public", "abstract", "String", "getDisplayString", "(", ")", ";", "public", "void", "setDepth", "(", "int", "depth", ")", "{", "this", ".", "depth", "=", "depth", ";", "}", "public", "int", "getDepth", "(", ")", "{", "return", "depth", ";", "}", "public", "void", "addQuery", "(", "QueryProfilerEntry", "query", ")", "{", "this", ".", "queries", ".", "add", "(", "query", ")", ";", "this", ".", "queryTime", "+=", "query", ".", "getDuration", "(", ")", ";", "}", "public", "void", "setQueries", "(", "List", "<", "QueryProfilerEntry", ">", "queries", ")", "{", "this", ".", "queries", "=", "queries", ";", "}", "public", "List", "<", "QueryProfilerEntry", ">", "getQueries", "(", ")", "{", "return", "queries", ";", "}", "public", "void", "setQueryTime", "(", "long", "queryTime", ")", "{", "this", ".", "queryTime", "=", "queryTime", ";", "}", "public", "long", "getQueryTime", "(", ")", "{", "return", "queryTime", ";", "}", "public", "void", "open", "(", "long", "rootStartTime", ")", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "this", ".", "setStartTime", "(", "startTime", ")", ";", "long", "fromStart", "=", "startTime", "-", "rootStartTime", ";", "this", ".", "setFromStart", "(", "fromStart", ")", ";", "}", "public", "void", "close", "(", ")", "{", "long", "endTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "this", ".", "setDuration", "(", "endTime", "-", "getStartTime", "(", ")", ")", ";", "}", "}" ]
Base class for profiler entries, each of which represents a distinct section of code being profiled.
[ "Base", "class", "for", "profiler", "entries", "each", "of", "which", "represents", "a", "distinct", "section", "of", "code", "being", "profiled", "." ]
[]
[ { "param": "IProfilerEntry", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IProfilerEntry", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bd38427d07791dcecff29855183fecf77eabc43
rafaelcoutinho/comendobemdelivery
src/br/copacabana/RetrieveClientCommand.java
[ "Apache-2.0" ]
Java
RetrieveClientCommand
/** * Executes the logic of load an entity from the persistent layer. * * @author Rafael Coutinho */
Executes the logic of load an entity from the persistent layer. @author Rafael Coutinho
[ "Executes", "the", "logic", "of", "load", "an", "entity", "from", "the", "persistent", "layer", ".", "@author", "Rafael", "Coutinho" ]
public class RetrieveClientCommand extends RetrieveCommand<Client> { @Override public void execute(Manager manager) throws Exception { execute(); } @Override public void execute() throws Exception { ClientManager jpaman = new ClientManager(); entity = (Client) jpaman.get(KeyFactory.stringToKey((String) this.getId())); this.setEntity(entity); } }
[ "public", "class", "RetrieveClientCommand", "extends", "RetrieveCommand", "<", "Client", ">", "{", "@", "Override", "public", "void", "execute", "(", "Manager", "manager", ")", "throws", "Exception", "{", "execute", "(", ")", ";", "}", "@", "Override", "public", "void", "execute", "(", ")", "throws", "Exception", "{", "ClientManager", "jpaman", "=", "new", "ClientManager", "(", ")", ";", "entity", "=", "(", "Client", ")", "jpaman", ".", "get", "(", "KeyFactory", ".", "stringToKey", "(", "(", "String", ")", "this", ".", "getId", "(", ")", ")", ")", ";", "this", ".", "setEntity", "(", "entity", ")", ";", "}", "}" ]
Executes the logic of load an entity from the persistent layer.
[ "Executes", "the", "logic", "of", "load", "an", "entity", "from", "the", "persistent", "layer", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bd4d446a29a6a246488216a5245357ca6ae4ff8
hakanmhmd/algorithms-and-data-structures
src/main/java/DynamicProgramming/CountWays.java
[ "MIT" ]
Java
CountWays
/** * A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. * Implement a method to count how many possible ways the child can run up the stairs. */
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.
[ "A", "child", "is", "running", "up", "a", "staircase", "with", "n", "steps", "and", "can", "hop", "either", "1", "step", "2", "steps", "or", "3", "steps", "at", "a", "time", ".", "Implement", "a", "method", "to", "count", "how", "many", "possible", "ways", "the", "child", "can", "run", "up", "the", "stairs", "." ]
public class CountWays { public static void main(String[] args) { int n = 7000; int[] memo = new int[n+1]; Arrays.fill(memo, -1); System.out.println(countWays(n, memo)); } private static int countWays(int n, int[] memo) { if(n == 0) return 1; if(n < 0) return 0; if(memo[n] == -1){ memo[n] = countWays(n-1, memo) + countWays(n-2, memo) + countWays(n-3, memo); } return memo[n]; } }
[ "public", "class", "CountWays", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "int", "n", "=", "7000", ";", "int", "[", "]", "memo", "=", "new", "int", "[", "n", "+", "1", "]", ";", "Arrays", ".", "fill", "(", "memo", ",", "-", "1", ")", ";", "System", ".", "out", ".", "println", "(", "countWays", "(", "n", ",", "memo", ")", ")", ";", "}", "private", "static", "int", "countWays", "(", "int", "n", ",", "int", "[", "]", "memo", ")", "{", "if", "(", "n", "==", "0", ")", "return", "1", ";", "if", "(", "n", "<", "0", ")", "return", "0", ";", "if", "(", "memo", "[", "n", "]", "==", "-", "1", ")", "{", "memo", "[", "n", "]", "=", "countWays", "(", "n", "-", "1", ",", "memo", ")", "+", "countWays", "(", "n", "-", "2", ",", "memo", ")", "+", "countWays", "(", "n", "-", "3", ",", "memo", ")", ";", "}", "return", "memo", "[", "n", "]", ";", "}", "}" ]
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time.
[ "A", "child", "is", "running", "up", "a", "staircase", "with", "n", "steps", "and", "can", "hop", "either", "1", "step", "2", "steps", "or", "3", "steps", "at", "a", "time", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bdaf50a741b77f5d98dfe2aa4beae17648d9d82
aarpon/obit_annotation_tool
AnnotationTool/ch/ethz/scu/obit/at/gui/AnnotationToolWindow.java
[ "Apache-2.0" ]
Java
AnnotationToolWindow
/** * Main window of the AnnotationTool application. * @author Aaron Ponti */
Main window of the AnnotationTool application. @author Aaron Ponti
[ "Main", "window", "of", "the", "AnnotationTool", "application", ".", "@author", "Aaron", "Ponti" ]
public final class AnnotationToolWindow extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private GlobalSettingsManager globalSettingsManager; private OpenBISProcessor openBISProcessor; private OpenBISViewer openBISViewer; private AbstractViewer metadataViewer; private ImageIcon appIcon; /** * Constructor */ public AnnotationToolWindow() { // Call the frame's constructor super("openBIS Importer Toolset (oBIT) :: Annotation Tool v" + VersionInfo.version + " " + VersionInfo.status); // Use the system default look-and-feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Couldn't set look and feel."); } // Load the settings globalSettingsManager = new GlobalSettingsManager(); // We instantiate the OutputPane so we can start logging to it OutputPane outputPane = new OutputPane(); // Instantiate an OpenBISProcessor openBISProcessor = new OpenBISProcessor(globalSettingsManager); // We create a main panel where to add the various viewers/editors JPanel mainPanel = new JPanel(); // Set a grid bag layout mainPanel.setLayout(new GridBagLayout()); // Common constraints GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.NORTHWEST; constraints.fill = GridBagConstraints.BOTH; // First, we ask the user to login. // Here we will insist on getting valid openBIS credentials, since a // valid login is essential for the functioning of the application. // The OpenBISProcessor takes care of closing the application if the // user just closes the dialog. outputPane.log("Logging in to openBIS..."); boolean status = false; while (!status) { try { status = openBISProcessor.login(); if (! status) { outputPane.err("Failed logged in to openBIS!"); } } catch (InterruptedException e) { JOptionPane.showMessageDialog(null, "Interrupted execution of login threads!", "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } } outputPane.log("Successfully logged in to openBIS."); // Icon appIcon = new ImageIcon( this.getClass().getResource("icons/icon.png")); // Set it to the window setIconImage(appIcon.getImage()); // Create a GridBagLayout GridBagLayout gridBagLayout = new GridBagLayout(); setLayout(gridBagLayout); // Add the metadata viewer try { metadataViewer = ViewerFactory.createViewer(globalSettingsManager); } catch (Exception e1) { System.err.println("There was a problem instantiating " + "the tools for current acquisition station."); System.exit(1); } // Set constraints and add widget constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets = new Insets(5, 5, 0, 5); mainPanel.add(metadataViewer.getPanel(), constraints); // Set the output pane to the viewer metadataViewer.setOutputPane(outputPane); // Add the openBIS viewer openBISViewer = new OpenBISViewer(openBISProcessor, outputPane, globalSettingsManager); // Set constraints and add widget constraints.gridx = 2; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets = new Insets(5, 0, 0, 5); mainPanel.add(openBISViewer.getPanel(), constraints); // Add the editor: it is important to create this object as // the last one, since it requires non-null references to the // metadata, the openBIS viewers, and the output pane! EditorContainer editorContainer = new EditorContainer( metadataViewer, openBISViewer, outputPane, globalSettingsManager); // Set constraints and add widget constraints.gridx = 1; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets = new Insets(5, 0, 0, 5); mainPanel.add(editorContainer, constraints); // Add observers to the viewers and the editor container. metadataViewer.addObserver(editorContainer.getEditor()); metadataViewer.addObserver(editorContainer); openBISViewer.addObserver(editorContainer.getEditor()); openBISViewer.addObserver(editorContainer); editorContainer.getEditor().addObserver(editorContainer); // We do not want the window to close without some clean up setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { QuitApplication(); } }); // Wrap the output pane to allow for constraints JPanel outputPaneWrapper = new JPanel(); outputPaneWrapper.setLayout(new GridBagLayout()); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 3; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(5, 5, 5, 5); outputPaneWrapper.add(outputPane, constraints); // Create a splitpane JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, outputPaneWrapper); splitPane.setResizeWeight(0.75); splitPane.setBorder(null); add(splitPane); // Add the split panel to the layout constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.gridwidth = 1; constraints.insets = new Insets(0, 0, 0, 0); add(splitPane, constraints); // Set up the frame and center on screen setMinimumSize(new Dimension(1200, 700)); setPreferredSize(new Dimension(1200, 900)); pack(); setLocationRelativeTo(null); // Make window visible setVisible(true); } /** * Scans the data folder and the openBIS structure and updates the UI. */ public void scan() { // Scan the openBIS instance openBISViewer.scan(); // Scan the user data folder for datasets metadataViewer.setUserName(openBISViewer.getUserName()); metadataViewer.scan(); } /** * Implements the actionPerformed callback. * @param e The ActionEvent */ public void actionPerformed(ActionEvent e) { // React to the context menu if (e.getActionCommand().equals("Quit")) { QuitApplication(); } else { // Nothing } } /** * Quits the application properly */ private void QuitApplication() { // Ask the user for confirmation if (JOptionPane.showConfirmDialog(this, "Do you really want to quit?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, appIcon) == JOptionPane.YES_OPTION) { try { openBISProcessor.logout(); System.exit(0); } catch (RemoteAccessException e) { // Inform user that logging out was unsuccessful // Give the user the option to wait or close // the application Object[] options = {"Wait", "Force close"}; int n = JOptionPane.showOptionDialog(this, "Could not log out from openBIS: " + "the server is no longer reachable.\n" + "Do you want to wait and retry later or to " + "force close the application?", "Connection error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (n!=0) { // Force close System.exit(1); } } } } }
[ "public", "final", "class", "AnnotationToolWindow", "extends", "JFrame", "implements", "ActionListener", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "GlobalSettingsManager", "globalSettingsManager", ";", "private", "OpenBISProcessor", "openBISProcessor", ";", "private", "OpenBISViewer", "openBISViewer", ";", "private", "AbstractViewer", "metadataViewer", ";", "private", "ImageIcon", "appIcon", ";", "/**\n\t * Constructor\n\t */", "public", "AnnotationToolWindow", "(", ")", "{", "super", "(", "\"", "openBIS Importer Toolset (oBIT) :: Annotation Tool v", "\"", "+", "VersionInfo", ".", "version", "+", "\"", " ", "\"", "+", "VersionInfo", ".", "status", ")", ";", "try", "{", "UIManager", ".", "setLookAndFeel", "(", "UIManager", ".", "getSystemLookAndFeelClassName", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Couldn't set look and feel.", "\"", ")", ";", "}", "globalSettingsManager", "=", "new", "GlobalSettingsManager", "(", ")", ";", "OutputPane", "outputPane", "=", "new", "OutputPane", "(", ")", ";", "openBISProcessor", "=", "new", "OpenBISProcessor", "(", "globalSettingsManager", ")", ";", "JPanel", "mainPanel", "=", "new", "JPanel", "(", ")", ";", "mainPanel", ".", "setLayout", "(", "new", "GridBagLayout", "(", ")", ")", ";", "GridBagConstraints", "constraints", "=", "new", "GridBagConstraints", "(", ")", ";", "constraints", ".", "anchor", "=", "GridBagConstraints", ".", "NORTHWEST", ";", "constraints", ".", "fill", "=", "GridBagConstraints", ".", "BOTH", ";", "outputPane", ".", "log", "(", "\"", "Logging in to openBIS...", "\"", ")", ";", "boolean", "status", "=", "false", ";", "while", "(", "!", "status", ")", "{", "try", "{", "status", "=", "openBISProcessor", ".", "login", "(", ")", ";", "if", "(", "!", "status", ")", "{", "outputPane", ".", "err", "(", "\"", "Failed logged in to openBIS!", "\"", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "JOptionPane", ".", "showMessageDialog", "(", "null", ",", "\"", "Interrupted execution of login threads!", "\"", ",", "\"", "Error", "\"", ",", "JOptionPane", ".", "ERROR_MESSAGE", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "outputPane", ".", "log", "(", "\"", "Successfully logged in to openBIS.", "\"", ")", ";", "appIcon", "=", "new", "ImageIcon", "(", "this", ".", "getClass", "(", ")", ".", "getResource", "(", "\"", "icons/icon.png", "\"", ")", ")", ";", "setIconImage", "(", "appIcon", ".", "getImage", "(", ")", ")", ";", "GridBagLayout", "gridBagLayout", "=", "new", "GridBagLayout", "(", ")", ";", "setLayout", "(", "gridBagLayout", ")", ";", "try", "{", "metadataViewer", "=", "ViewerFactory", ".", "createViewer", "(", "globalSettingsManager", ")", ";", "}", "catch", "(", "Exception", "e1", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "There was a problem instantiating ", "\"", "+", "\"", "the tools for current acquisition station.", "\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "constraints", ".", "gridx", "=", "0", ";", "constraints", ".", "gridy", "=", "0", ";", "constraints", ".", "gridwidth", "=", "1", ";", "constraints", ".", "gridheight", "=", "1", ";", "constraints", ".", "weightx", "=", "1.0", ";", "constraints", ".", "weighty", "=", "1.0", ";", "constraints", ".", "insets", "=", "new", "Insets", "(", "5", ",", "5", ",", "0", ",", "5", ")", ";", "mainPanel", ".", "add", "(", "metadataViewer", ".", "getPanel", "(", ")", ",", "constraints", ")", ";", "metadataViewer", ".", "setOutputPane", "(", "outputPane", ")", ";", "openBISViewer", "=", "new", "OpenBISViewer", "(", "openBISProcessor", ",", "outputPane", ",", "globalSettingsManager", ")", ";", "constraints", ".", "gridx", "=", "2", ";", "constraints", ".", "gridy", "=", "0", ";", "constraints", ".", "gridwidth", "=", "1", ";", "constraints", ".", "gridheight", "=", "1", ";", "constraints", ".", "weightx", "=", "1.0", ";", "constraints", ".", "weighty", "=", "1.0", ";", "constraints", ".", "insets", "=", "new", "Insets", "(", "5", ",", "0", ",", "0", ",", "5", ")", ";", "mainPanel", ".", "add", "(", "openBISViewer", ".", "getPanel", "(", ")", ",", "constraints", ")", ";", "EditorContainer", "editorContainer", "=", "new", "EditorContainer", "(", "metadataViewer", ",", "openBISViewer", ",", "outputPane", ",", "globalSettingsManager", ")", ";", "constraints", ".", "gridx", "=", "1", ";", "constraints", ".", "gridy", "=", "0", ";", "constraints", ".", "gridwidth", "=", "1", ";", "constraints", ".", "gridheight", "=", "1", ";", "constraints", ".", "weightx", "=", "1.0", ";", "constraints", ".", "weighty", "=", "1.0", ";", "constraints", ".", "insets", "=", "new", "Insets", "(", "5", ",", "0", ",", "0", ",", "5", ")", ";", "mainPanel", ".", "add", "(", "editorContainer", ",", "constraints", ")", ";", "metadataViewer", ".", "addObserver", "(", "editorContainer", ".", "getEditor", "(", ")", ")", ";", "metadataViewer", ".", "addObserver", "(", "editorContainer", ")", ";", "openBISViewer", ".", "addObserver", "(", "editorContainer", ".", "getEditor", "(", ")", ")", ";", "openBISViewer", ".", "addObserver", "(", "editorContainer", ")", ";", "editorContainer", ".", "getEditor", "(", ")", ".", "addObserver", "(", "editorContainer", ")", ";", "setDefaultCloseOperation", "(", "WindowConstants", ".", "DO_NOTHING_ON_CLOSE", ")", ";", "addWindowListener", "(", "new", "WindowAdapter", "(", ")", "{", "@", "Override", "public", "void", "windowClosing", "(", "WindowEvent", "e", ")", "{", "QuitApplication", "(", ")", ";", "}", "}", ")", ";", "JPanel", "outputPaneWrapper", "=", "new", "JPanel", "(", ")", ";", "outputPaneWrapper", ".", "setLayout", "(", "new", "GridBagLayout", "(", ")", ")", ";", "constraints", ".", "gridx", "=", "0", ";", "constraints", ".", "gridy", "=", "0", ";", "constraints", ".", "gridwidth", "=", "3", ";", "constraints", ".", "gridheight", "=", "1", ";", "constraints", ".", "weightx", "=", "1.0", ";", "constraints", ".", "weighty", "=", "1.0", ";", "constraints", ".", "fill", "=", "GridBagConstraints", ".", "BOTH", ";", "constraints", ".", "insets", "=", "new", "Insets", "(", "5", ",", "5", ",", "5", ",", "5", ")", ";", "outputPaneWrapper", ".", "add", "(", "outputPane", ",", "constraints", ")", ";", "JSplitPane", "splitPane", "=", "new", "JSplitPane", "(", "JSplitPane", ".", "VERTICAL_SPLIT", ",", "mainPanel", ",", "outputPaneWrapper", ")", ";", "splitPane", ".", "setResizeWeight", "(", "0.75", ")", ";", "splitPane", ".", "setBorder", "(", "null", ")", ";", "add", "(", "splitPane", ")", ";", "constraints", ".", "gridx", "=", "0", ";", "constraints", ".", "gridy", "=", "1", ";", "constraints", ".", "weightx", "=", "1.0", ";", "constraints", ".", "weighty", "=", "1.0", ";", "constraints", ".", "gridwidth", "=", "1", ";", "constraints", ".", "insets", "=", "new", "Insets", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "add", "(", "splitPane", ",", "constraints", ")", ";", "setMinimumSize", "(", "new", "Dimension", "(", "1200", ",", "700", ")", ")", ";", "setPreferredSize", "(", "new", "Dimension", "(", "1200", ",", "900", ")", ")", ";", "pack", "(", ")", ";", "setLocationRelativeTo", "(", "null", ")", ";", "setVisible", "(", "true", ")", ";", "}", "/**\n\t * Scans the data folder and the openBIS structure and updates the UI.\n\t */", "public", "void", "scan", "(", ")", "{", "openBISViewer", ".", "scan", "(", ")", ";", "metadataViewer", ".", "setUserName", "(", "openBISViewer", ".", "getUserName", "(", ")", ")", ";", "metadataViewer", ".", "scan", "(", ")", ";", "}", "/**\n\t * Implements the actionPerformed callback.\n\t * @param e The ActionEvent \n\t */", "public", "void", "actionPerformed", "(", "ActionEvent", "e", ")", "{", "if", "(", "e", ".", "getActionCommand", "(", ")", ".", "equals", "(", "\"", "Quit", "\"", ")", ")", "{", "QuitApplication", "(", ")", ";", "}", "else", "{", "}", "}", "/**\n\t * Quits the application properly\n\t */", "private", "void", "QuitApplication", "(", ")", "{", "if", "(", "JOptionPane", ".", "showConfirmDialog", "(", "this", ",", "\"", "Do you really want to quit?", "\"", ",", "\"", "Question", "\"", ",", "JOptionPane", ".", "YES_NO_OPTION", ",", "JOptionPane", ".", "QUESTION_MESSAGE", ",", "appIcon", ")", "==", "JOptionPane", ".", "YES_OPTION", ")", "{", "try", "{", "openBISProcessor", ".", "logout", "(", ")", ";", "System", ".", "exit", "(", "0", ")", ";", "}", "catch", "(", "RemoteAccessException", "e", ")", "{", "Object", "[", "]", "options", "=", "{", "\"", "Wait", "\"", ",", "\"", "Force close", "\"", "}", ";", "int", "n", "=", "JOptionPane", ".", "showOptionDialog", "(", "this", ",", "\"", "Could not log out from openBIS: ", "\"", "+", "\"", "the server is no longer reachable.", "\\n", "\"", "+", "\"", "Do you want to wait and retry later or to ", "\"", "+", "\"", "force close the application?", "\"", ",", "\"", "Connection error", "\"", ",", "JOptionPane", ".", "YES_NO_OPTION", ",", "JOptionPane", ".", "ERROR_MESSAGE", ",", "null", ",", "options", ",", "options", "[", "0", "]", ")", ";", "if", "(", "n", "!=", "0", ")", "{", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "}", "}", "}" ]
Main window of the AnnotationTool application.
[ "Main", "window", "of", "the", "AnnotationTool", "application", "." ]
[ "// Call the frame's constructor", "// Use the system default look-and-feel", "// Load the settings", "// We instantiate the OutputPane so we can start logging to it", "// Instantiate an OpenBISProcessor", "// We create a main panel where to add the various viewers/editors", "// Set a grid bag layout", "// Common constraints", "// First, we ask the user to login.", "// Here we will insist on getting valid openBIS credentials, since a", "// valid login is essential for the functioning of the application.", "// The OpenBISProcessor takes care of closing the application if the", "// user just closes the dialog.", "// Icon", "// Set it to the window", "// Create a GridBagLayout", "// Add the metadata viewer", "// Set constraints and add widget", "// Set the output pane to the viewer", "// Add the openBIS viewer", "// Set constraints and add widget", "// Add the editor: it is important to create this object as", "// the last one, since it requires non-null references to the ", "// metadata, the openBIS viewers, and the output pane!", "// Set constraints and add widget", "// Add observers to the viewers and the editor container.", "// We do not want the window to close without some clean up", "// Wrap the output pane to allow for constraints", "// Create a splitpane", "// Add the split panel to the layout", "// Set up the frame and center on screen", "// Make window visible", "// Scan the openBIS instance", "// Scan the user data folder for datasets", "// React to the context menu", "// Nothing", "// Ask the user for confirmation", "// Inform user that logging out was unsuccessful", "// Give the user the option to wait or close", "// the application", "// Force close" ]
[ { "param": "JFrame", "type": null }, { "param": "ActionListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JFrame", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ActionListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bdb7cfdec042d519e45b02d1cc917411f90c6ba
besom/bbossgroups-3.5
bboss-rpc/src-jgroups/bboss/org/jgroups/protocols/VERIFY_SUSPECT.java
[ "Apache-2.0" ]
Java
VERIFY_SUSPECT
/** * Catches SUSPECT events traveling up the stack. Verifies that the suspected member is really dead. If yes, * passes SUSPECT event up the stack, otherwise discards it. Has to be placed somewhere above the FD layer and * below the GMS layer (receiver of the SUSPECT event). Note that SUSPECT events may be reordered by this protocol. * @author Bela Ban * @version $Id: VERIFY_SUSPECT.java,v 1.46 2010/06/15 06:44:35 belaban Exp $ */
Catches SUSPECT events traveling up the stack. Verifies that the suspected member is really dead. If yes, passes SUSPECT event up the stack, otherwise discards it. Has to be placed somewhere above the FD layer and below the GMS layer (receiver of the SUSPECT event). Note that SUSPECT events may be reordered by this protocol.
[ "Catches", "SUSPECT", "events", "traveling", "up", "the", "stack", ".", "Verifies", "that", "the", "suspected", "member", "is", "really", "dead", ".", "If", "yes", "passes", "SUSPECT", "event", "up", "the", "stack", "otherwise", "discards", "it", ".", "Has", "to", "be", "placed", "somewhere", "above", "the", "FD", "layer", "and", "below", "the", "GMS", "layer", "(", "receiver", "of", "the", "SUSPECT", "event", ")", ".", "Note", "that", "SUSPECT", "events", "may", "be", "reordered", "by", "this", "protocol", "." ]
public class VERIFY_SUSPECT extends Protocol implements Runnable { /* ------------------------------------------ Properties ------------------------------------------ */ @Property(description="Number of millisecs to wait for a response from a suspected member") private long timeout=2000; @Property(description="Number of verify heartbeats sent to a suspected member") private int num_msgs=1; @Property(description="Use InetAddress.isReachable() to verify suspected member instead of regular messages") private boolean use_icmp=false; @Property(description="Interface for ICMP pings. Used if use_icmp is true " + "The following special values are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL and NON_LOOPBACK", systemProperty={Global.BIND_ADDR, Global.BIND_ADDR_OLD}, defaultValueIPv4=Global.NON_LOOPBACK_ADDRESS, defaultValueIPv6=Global.NON_LOOPBACK_ADDRESS) private InetAddress bind_addr; // interface for ICMP pings @Property(name="bind_interface", converter=PropertyConverters.BindInterface.class, description="The interface (NIC) which should be used by this transport", dependsUpon="bind_addr") protected String bind_interface_str=null; /* --------------------------------------------- Fields ------------------------------------------------ */ /** network interface to be used to send the ICMP packets */ private NetworkInterface intf=null; private Address local_addr=null; /**keys=Addresses, vals=time in mcses since added **/ private final Hashtable<Address,Long> suspects=new Hashtable<Address,Long>(); private Thread timer=null; public VERIFY_SUSPECT() { } public Object down(Event evt) { if(evt.getType() == Event.SET_LOCAL_ADDRESS) { local_addr=(Address)evt.getArg(); } return down_prot.down(evt); } public Object up(Event evt) { switch(evt.getType()) { case Event.SUSPECT: // it all starts here ... Address suspected_mbr=(Address)evt.getArg(); if(suspected_mbr == null) { if(log.isErrorEnabled()) log.error("suspected member is null"); return null; } if(local_addr != null && local_addr.equals(suspected_mbr)) { if(log.isTraceEnabled()) log.trace("I was suspected; ignoring SUSPECT message"); return null; } if(!use_icmp) verifySuspect(suspected_mbr); else verifySuspectWithICMP(suspected_mbr); return null; // don't pass up; we will decide later (after verification) whether to pass it up case Event.MSG: Message msg=(Message)evt.getArg(); VerifyHeader hdr=(VerifyHeader)msg.getHeader(this.id); if(hdr == null) break; switch(hdr.type) { case VerifyHeader.ARE_YOU_DEAD: if(hdr.from == null) { if(log.isErrorEnabled()) log.error("ARE_YOU_DEAD: hdr.from is null"); } else { Message rsp; for(int i=0; i < num_msgs; i++) { rsp=new Message(hdr.from, null, null); rsp.setFlag(Message.OOB); rsp.putHeader(this.id, new VerifyHeader(VerifyHeader.I_AM_NOT_DEAD, local_addr)); down_prot.down(new Event(Event.MSG, rsp)); } } return null; case VerifyHeader.I_AM_NOT_DEAD: if(hdr.from == null) { if(log.isErrorEnabled()) log.error("I_AM_NOT_DEAD: hdr.from is null"); return null; } unsuspect(hdr.from); return null; } return null; case Event.CONFIG: if(bind_addr == null) { Map<String,Object> config=(Map<String,Object>)evt.getArg(); bind_addr=(InetAddress)config.get("bind_addr"); } } return up_prot.up(evt); } /** * Will be started when a suspect is added to the suspects hashtable. Continually iterates over the * entries and removes entries whose time have elapsed. For each removed entry, a SUSPECT event is passed * up the stack (because elapsed time means verification of member's liveness failed). Computes the shortest * time to wait (min of all timeouts) and waits(time) msecs. Will be woken up when entry is removed (in case * of successful verification of that member's liveness). Terminates when no entry remains in the hashtable. */ public void run() { long val, diff; while(!suspects.isEmpty()) { diff=0; List<Address> confirmed_suspects=new LinkedList<Address>(); synchronized(suspects) { for(Enumeration<Address> e=suspects.keys(); e.hasMoreElements();) { Address mbr=e.nextElement(); val=suspects.get(mbr).longValue(); diff=System.currentTimeMillis() - val; if(diff >= timeout) { // haven't been unsuspected, pass up SUSPECT if(log.isTraceEnabled()) log.trace("diff=" + diff + ", mbr " + mbr + " is dead (passing up SUSPECT event)"); confirmed_suspects.add(mbr); suspects.remove(mbr); continue; } diff=Math.max(diff, timeout - diff); } } for(Address suspect:confirmed_suspects) up_prot.up(new Event(Event.SUSPECT,suspect)); if(diff > 0) Util.sleep(diff); } } /* --------------------------------- Private Methods ----------------------------------- */ /** * Sends ARE_YOU_DEAD message to suspected_mbr, wait for return or timeout */ void verifySuspect(Address mbr) { Message msg; if(mbr == null) return; synchronized(suspects) { if(suspects.containsKey(mbr)) return; suspects.put(mbr, new Long(System.currentTimeMillis())); } //start timer before we send out are you dead messages startTimer(); // moved out of synchronized statement (bela): http://jira.jboss.com/jira/browse/JGRP-302 if(log.isTraceEnabled()) log.trace("verifying that " + mbr + " is dead"); for(int i=0; i < num_msgs; i++) { msg=new Message(mbr, null, null); msg.setFlag(Message.OOB); msg.putHeader(this.id, new VerifyHeader(VerifyHeader.ARE_YOU_DEAD, local_addr)); down_prot.down(new Event(Event.MSG, msg)); } } void verifySuspectWithICMP(Address suspected_mbr) { InetAddress host=suspected_mbr instanceof IpAddress? ((IpAddress)suspected_mbr).getIpAddress() : null; if(host == null) throw new IllegalArgumentException("suspected_mbr is not of type IpAddress - FD_ICMP only works with these"); try { if(log.isTraceEnabled()) log.trace("pinging host " + suspected_mbr + " using interface " + intf); long start=System.currentTimeMillis(), stop; boolean rc=host.isReachable(intf, 0, (int)timeout); stop=System.currentTimeMillis(); if(rc) { // success if(log.isTraceEnabled()) log.trace("successfully received response from " + host + " (after " + (stop-start) + "ms)"); } else { // failure if(log.isTraceEnabled()) log.debug("could not ping " + suspected_mbr + " after " + (stop-start) + "ms; " + "passing up SUSPECT event"); suspects.remove(suspected_mbr); up_prot.up(new Event(Event.SUSPECT, suspected_mbr)); } } catch(Exception ex) { if(log.isErrorEnabled()) log.error("failed pinging " + suspected_mbr, ex); } } void unsuspect(Address mbr) { if(mbr == null) return; boolean removed=false; synchronized(suspects) { if(suspects.containsKey(mbr)) { if(log.isTraceEnabled()) log.trace("member " + mbr + " is not dead !"); suspects.remove(mbr); removed=true; } } if(removed) { down_prot.down(new Event(Event.UNSUSPECT, mbr)); up_prot.up(new Event(Event.UNSUSPECT, mbr)); } } private synchronized void startTimer() { if(timer == null || !timer.isAlive()) { timer=getThreadFactory().newThread(this,"VERIFY_SUSPECT.TimerThread"); timer.setDaemon(true); timer.start(); } } public void init() throws Exception { super.init(); if(bind_addr != null) intf=NetworkInterface.getByInetAddress(bind_addr); } public synchronized void stop() { Thread tmp; if(timer != null && timer.isAlive()) { tmp=timer; timer=null; tmp.interrupt(); tmp=null; } timer=null; } /* ----------------------------- End of Private Methods -------------------------------- */ public static class VerifyHeader extends Header { static final short ARE_YOU_DEAD=1; // 'from' is sender of verify msg static final short I_AM_NOT_DEAD=2; // 'from' is suspected member short type=ARE_YOU_DEAD; Address from=null; // member who wants to verify that suspected_mbr is dead public VerifyHeader() { } // used for externalization VerifyHeader(short type) { this.type=type; } VerifyHeader(short type, Address from) { this(type); this.from=from; } public String toString() { switch(type) { case ARE_YOU_DEAD: return "[VERIFY_SUSPECT: ARE_YOU_DEAD]"; case I_AM_NOT_DEAD: return "[VERIFY_SUSPECT: I_AM_NOT_DEAD]"; default: return "[VERIFY_SUSPECT: unknown type (" + type + ")]"; } } public void writeTo(DataOutputStream out) throws IOException { out.writeShort(type); Util.writeAddress(from, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readShort(); from=Util.readAddress(in); } public int size() { return Global.SHORT_SIZE + Util.size(from); } } }
[ "public", "class", "VERIFY_SUSPECT", "extends", "Protocol", "implements", "Runnable", "{", "/* ------------------------------------------ Properties ------------------------------------------ */", "@", "Property", "(", "description", "=", "\"", "Number of millisecs to wait for a response from a suspected member", "\"", ")", "private", "long", "timeout", "=", "2000", ";", "@", "Property", "(", "description", "=", "\"", "Number of verify heartbeats sent to a suspected member", "\"", ")", "private", "int", "num_msgs", "=", "1", ";", "@", "Property", "(", "description", "=", "\"", "Use InetAddress.isReachable() to verify suspected member instead of regular messages", "\"", ")", "private", "boolean", "use_icmp", "=", "false", ";", "@", "Property", "(", "description", "=", "\"", "Interface for ICMP pings. Used if use_icmp is true ", "\"", "+", "\"", "The following special values are also recognized: GLOBAL, SITE_LOCAL, LINK_LOCAL and NON_LOOPBACK", "\"", ",", "systemProperty", "=", "{", "Global", ".", "BIND_ADDR", ",", "Global", ".", "BIND_ADDR_OLD", "}", ",", "defaultValueIPv4", "=", "Global", ".", "NON_LOOPBACK_ADDRESS", ",", "defaultValueIPv6", "=", "Global", ".", "NON_LOOPBACK_ADDRESS", ")", "private", "InetAddress", "bind_addr", ";", "@", "Property", "(", "name", "=", "\"", "bind_interface", "\"", ",", "converter", "=", "PropertyConverters", ".", "BindInterface", ".", "class", ",", "description", "=", "\"", "The interface (NIC) which should be used by this transport", "\"", ",", "dependsUpon", "=", "\"", "bind_addr", "\"", ")", "protected", "String", "bind_interface_str", "=", "null", ";", "/* --------------------------------------------- Fields ------------------------------------------------ */", "/** network interface to be used to send the ICMP packets */", "private", "NetworkInterface", "intf", "=", "null", ";", "private", "Address", "local_addr", "=", "null", ";", "/**keys=Addresses, vals=time in mcses since added **/", "private", "final", "Hashtable", "<", "Address", ",", "Long", ">", "suspects", "=", "new", "Hashtable", "<", "Address", ",", "Long", ">", "(", ")", ";", "private", "Thread", "timer", "=", "null", ";", "public", "VERIFY_SUSPECT", "(", ")", "{", "}", "public", "Object", "down", "(", "Event", "evt", ")", "{", "if", "(", "evt", ".", "getType", "(", ")", "==", "Event", ".", "SET_LOCAL_ADDRESS", ")", "{", "local_addr", "=", "(", "Address", ")", "evt", ".", "getArg", "(", ")", ";", "}", "return", "down_prot", ".", "down", "(", "evt", ")", ";", "}", "public", "Object", "up", "(", "Event", "evt", ")", "{", "switch", "(", "evt", ".", "getType", "(", ")", ")", "{", "case", "Event", ".", "SUSPECT", ":", "Address", "suspected_mbr", "=", "(", "Address", ")", "evt", ".", "getArg", "(", ")", ";", "if", "(", "suspected_mbr", "==", "null", ")", "{", "if", "(", "log", ".", "isErrorEnabled", "(", ")", ")", "log", ".", "error", "(", "\"", "suspected member is null", "\"", ")", ";", "return", "null", ";", "}", "if", "(", "local_addr", "!=", "null", "&&", "local_addr", ".", "equals", "(", "suspected_mbr", ")", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"", "I was suspected; ignoring SUSPECT message", "\"", ")", ";", "return", "null", ";", "}", "if", "(", "!", "use_icmp", ")", "verifySuspect", "(", "suspected_mbr", ")", ";", "else", "verifySuspectWithICMP", "(", "suspected_mbr", ")", ";", "return", "null", ";", "case", "Event", ".", "MSG", ":", "Message", "msg", "=", "(", "Message", ")", "evt", ".", "getArg", "(", ")", ";", "VerifyHeader", "hdr", "=", "(", "VerifyHeader", ")", "msg", ".", "getHeader", "(", "this", ".", "id", ")", ";", "if", "(", "hdr", "==", "null", ")", "break", ";", "switch", "(", "hdr", ".", "type", ")", "{", "case", "VerifyHeader", ".", "ARE_YOU_DEAD", ":", "if", "(", "hdr", ".", "from", "==", "null", ")", "{", "if", "(", "log", ".", "isErrorEnabled", "(", ")", ")", "log", ".", "error", "(", "\"", "ARE_YOU_DEAD: hdr.from is null", "\"", ")", ";", "}", "else", "{", "Message", "rsp", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "num_msgs", ";", "i", "++", ")", "{", "rsp", "=", "new", "Message", "(", "hdr", ".", "from", ",", "null", ",", "null", ")", ";", "rsp", ".", "setFlag", "(", "Message", ".", "OOB", ")", ";", "rsp", ".", "putHeader", "(", "this", ".", "id", ",", "new", "VerifyHeader", "(", "VerifyHeader", ".", "I_AM_NOT_DEAD", ",", "local_addr", ")", ")", ";", "down_prot", ".", "down", "(", "new", "Event", "(", "Event", ".", "MSG", ",", "rsp", ")", ")", ";", "}", "}", "return", "null", ";", "case", "VerifyHeader", ".", "I_AM_NOT_DEAD", ":", "if", "(", "hdr", ".", "from", "==", "null", ")", "{", "if", "(", "log", ".", "isErrorEnabled", "(", ")", ")", "log", ".", "error", "(", "\"", "I_AM_NOT_DEAD: hdr.from is null", "\"", ")", ";", "return", "null", ";", "}", "unsuspect", "(", "hdr", ".", "from", ")", ";", "return", "null", ";", "}", "return", "null", ";", "case", "Event", ".", "CONFIG", ":", "if", "(", "bind_addr", "==", "null", ")", "{", "Map", "<", "String", ",", "Object", ">", "config", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "evt", ".", "getArg", "(", ")", ";", "bind_addr", "=", "(", "InetAddress", ")", "config", ".", "get", "(", "\"", "bind_addr", "\"", ")", ";", "}", "}", "return", "up_prot", ".", "up", "(", "evt", ")", ";", "}", "/**\r\n * Will be started when a suspect is added to the suspects hashtable. Continually iterates over the\r\n * entries and removes entries whose time have elapsed. For each removed entry, a SUSPECT event is passed\r\n * up the stack (because elapsed time means verification of member's liveness failed). Computes the shortest\r\n * time to wait (min of all timeouts) and waits(time) msecs. Will be woken up when entry is removed (in case\r\n * of successful verification of that member's liveness). Terminates when no entry remains in the hashtable.\r\n */", "public", "void", "run", "(", ")", "{", "long", "val", ",", "diff", ";", "while", "(", "!", "suspects", ".", "isEmpty", "(", ")", ")", "{", "diff", "=", "0", ";", "List", "<", "Address", ">", "confirmed_suspects", "=", "new", "LinkedList", "<", "Address", ">", "(", ")", ";", "synchronized", "(", "suspects", ")", "{", "for", "(", "Enumeration", "<", "Address", ">", "e", "=", "suspects", ".", "keys", "(", ")", ";", "e", ".", "hasMoreElements", "(", ")", ";", ")", "{", "Address", "mbr", "=", "e", ".", "nextElement", "(", ")", ";", "val", "=", "suspects", ".", "get", "(", "mbr", ")", ".", "longValue", "(", ")", ";", "diff", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "val", ";", "if", "(", "diff", ">=", "timeout", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"", "diff=", "\"", "+", "diff", "+", "\"", ", mbr ", "\"", "+", "mbr", "+", "\"", " is dead (passing up SUSPECT event)", "\"", ")", ";", "confirmed_suspects", ".", "add", "(", "mbr", ")", ";", "suspects", ".", "remove", "(", "mbr", ")", ";", "continue", ";", "}", "diff", "=", "Math", ".", "max", "(", "diff", ",", "timeout", "-", "diff", ")", ";", "}", "}", "for", "(", "Address", "suspect", ":", "confirmed_suspects", ")", "up_prot", ".", "up", "(", "new", "Event", "(", "Event", ".", "SUSPECT", ",", "suspect", ")", ")", ";", "if", "(", "diff", ">", "0", ")", "Util", ".", "sleep", "(", "diff", ")", ";", "}", "}", "/* --------------------------------- Private Methods ----------------------------------- */", "/**\r\n * Sends ARE_YOU_DEAD message to suspected_mbr, wait for return or timeout\r\n */", "void", "verifySuspect", "(", "Address", "mbr", ")", "{", "Message", "msg", ";", "if", "(", "mbr", "==", "null", ")", "return", ";", "synchronized", "(", "suspects", ")", "{", "if", "(", "suspects", ".", "containsKey", "(", "mbr", ")", ")", "return", ";", "suspects", ".", "put", "(", "mbr", ",", "new", "Long", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ";", "}", "startTimer", "(", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"", "verifying that ", "\"", "+", "mbr", "+", "\"", " is dead", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "num_msgs", ";", "i", "++", ")", "{", "msg", "=", "new", "Message", "(", "mbr", ",", "null", ",", "null", ")", ";", "msg", ".", "setFlag", "(", "Message", ".", "OOB", ")", ";", "msg", ".", "putHeader", "(", "this", ".", "id", ",", "new", "VerifyHeader", "(", "VerifyHeader", ".", "ARE_YOU_DEAD", ",", "local_addr", ")", ")", ";", "down_prot", ".", "down", "(", "new", "Event", "(", "Event", ".", "MSG", ",", "msg", ")", ")", ";", "}", "}", "void", "verifySuspectWithICMP", "(", "Address", "suspected_mbr", ")", "{", "InetAddress", "host", "=", "suspected_mbr", "instanceof", "IpAddress", "?", "(", "(", "IpAddress", ")", "suspected_mbr", ")", ".", "getIpAddress", "(", ")", ":", "null", ";", "if", "(", "host", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "suspected_mbr is not of type IpAddress - FD_ICMP only works with these", "\"", ")", ";", "try", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"", "pinging host ", "\"", "+", "suspected_mbr", "+", "\"", " using interface ", "\"", "+", "intf", ")", ";", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ",", "stop", ";", "boolean", "rc", "=", "host", ".", "isReachable", "(", "intf", ",", "0", ",", "(", "int", ")", "timeout", ")", ";", "stop", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "rc", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"", "successfully received response from ", "\"", "+", "host", "+", "\"", " (after ", "\"", "+", "(", "stop", "-", "start", ")", "+", "\"", "ms)", "\"", ")", ";", "}", "else", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"", "could not ping ", "\"", "+", "suspected_mbr", "+", "\"", " after ", "\"", "+", "(", "stop", "-", "start", ")", "+", "\"", "ms; ", "\"", "+", "\"", "passing up SUSPECT event", "\"", ")", ";", "suspects", ".", "remove", "(", "suspected_mbr", ")", ";", "up_prot", ".", "up", "(", "new", "Event", "(", "Event", ".", "SUSPECT", ",", "suspected_mbr", ")", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "if", "(", "log", ".", "isErrorEnabled", "(", ")", ")", "log", ".", "error", "(", "\"", "failed pinging ", "\"", "+", "suspected_mbr", ",", "ex", ")", ";", "}", "}", "void", "unsuspect", "(", "Address", "mbr", ")", "{", "if", "(", "mbr", "==", "null", ")", "return", ";", "boolean", "removed", "=", "false", ";", "synchronized", "(", "suspects", ")", "{", "if", "(", "suspects", ".", "containsKey", "(", "mbr", ")", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"", "member ", "\"", "+", "mbr", "+", "\"", " is not dead !", "\"", ")", ";", "suspects", ".", "remove", "(", "mbr", ")", ";", "removed", "=", "true", ";", "}", "}", "if", "(", "removed", ")", "{", "down_prot", ".", "down", "(", "new", "Event", "(", "Event", ".", "UNSUSPECT", ",", "mbr", ")", ")", ";", "up_prot", ".", "up", "(", "new", "Event", "(", "Event", ".", "UNSUSPECT", ",", "mbr", ")", ")", ";", "}", "}", "private", "synchronized", "void", "startTimer", "(", ")", "{", "if", "(", "timer", "==", "null", "||", "!", "timer", ".", "isAlive", "(", ")", ")", "{", "timer", "=", "getThreadFactory", "(", ")", ".", "newThread", "(", "this", ",", "\"", "VERIFY_SUSPECT.TimerThread", "\"", ")", ";", "timer", ".", "setDaemon", "(", "true", ")", ";", "timer", ".", "start", "(", ")", ";", "}", "}", "public", "void", "init", "(", ")", "throws", "Exception", "{", "super", ".", "init", "(", ")", ";", "if", "(", "bind_addr", "!=", "null", ")", "intf", "=", "NetworkInterface", ".", "getByInetAddress", "(", "bind_addr", ")", ";", "}", "public", "synchronized", "void", "stop", "(", ")", "{", "Thread", "tmp", ";", "if", "(", "timer", "!=", "null", "&&", "timer", ".", "isAlive", "(", ")", ")", "{", "tmp", "=", "timer", ";", "timer", "=", "null", ";", "tmp", ".", "interrupt", "(", ")", ";", "tmp", "=", "null", ";", "}", "timer", "=", "null", ";", "}", "/* ----------------------------- End of Private Methods -------------------------------- */", "public", "static", "class", "VerifyHeader", "extends", "Header", "{", "static", "final", "short", "ARE_YOU_DEAD", "=", "1", ";", "static", "final", "short", "I_AM_NOT_DEAD", "=", "2", ";", "short", "type", "=", "ARE_YOU_DEAD", ";", "Address", "from", "=", "null", ";", "public", "VerifyHeader", "(", ")", "{", "}", "VerifyHeader", "(", "short", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "VerifyHeader", "(", "short", "type", ",", "Address", "from", ")", "{", "this", "(", "type", ")", ";", "this", ".", "from", "=", "from", ";", "}", "public", "String", "toString", "(", ")", "{", "switch", "(", "type", ")", "{", "case", "ARE_YOU_DEAD", ":", "return", "\"", "[VERIFY_SUSPECT: ARE_YOU_DEAD]", "\"", ";", "case", "I_AM_NOT_DEAD", ":", "return", "\"", "[VERIFY_SUSPECT: I_AM_NOT_DEAD]", "\"", ";", "default", ":", "return", "\"", "[VERIFY_SUSPECT: unknown type (", "\"", "+", "type", "+", "\"", ")]", "\"", ";", "}", "}", "public", "void", "writeTo", "(", "DataOutputStream", "out", ")", "throws", "IOException", "{", "out", ".", "writeShort", "(", "type", ")", ";", "Util", ".", "writeAddress", "(", "from", ",", "out", ")", ";", "}", "public", "void", "readFrom", "(", "DataInputStream", "in", ")", "throws", "IOException", ",", "IllegalAccessException", ",", "InstantiationException", "{", "type", "=", "in", ".", "readShort", "(", ")", ";", "from", "=", "Util", ".", "readAddress", "(", "in", ")", ";", "}", "public", "int", "size", "(", ")", "{", "return", "Global", ".", "SHORT_SIZE", "+", "Util", ".", "size", "(", "from", ")", ";", "}", "}", "}" ]
Catches SUSPECT events traveling up the stack.
[ "Catches", "SUSPECT", "events", "traveling", "up", "the", "stack", "." ]
[ "// interface for ICMP pings\r", "// it all starts here ...\r", "// don't pass up; we will decide later (after verification) whether to pass it up\r", "// haven't been unsuspected, pass up SUSPECT\r", "//start timer before we send out are you dead messages\r", "// moved out of synchronized statement (bela): http://jira.jboss.com/jira/browse/JGRP-302\r", "// success\r", "// failure\r", "// 'from' is sender of verify msg\r", "// 'from' is suspected member\r", "// member who wants to verify that suspected_mbr is dead\r", "// used for externalization\r" ]
[ { "param": "Protocol", "type": null }, { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Protocol", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bdb7cfdec042d519e45b02d1cc917411f90c6ba
besom/bbossgroups-3.5
bboss-rpc/src-jgroups/bboss/org/jgroups/protocols/VERIFY_SUSPECT.java
[ "Apache-2.0" ]
Java
VerifyHeader
/* ----------------------------- End of Private Methods -------------------------------- */
End of Private Methods
[ "End", "of", "Private", "Methods" ]
public static class VerifyHeader extends Header { static final short ARE_YOU_DEAD=1; // 'from' is sender of verify msg static final short I_AM_NOT_DEAD=2; // 'from' is suspected member short type=ARE_YOU_DEAD; Address from=null; // member who wants to verify that suspected_mbr is dead public VerifyHeader() { } // used for externalization VerifyHeader(short type) { this.type=type; } VerifyHeader(short type, Address from) { this(type); this.from=from; } public String toString() { switch(type) { case ARE_YOU_DEAD: return "[VERIFY_SUSPECT: ARE_YOU_DEAD]"; case I_AM_NOT_DEAD: return "[VERIFY_SUSPECT: I_AM_NOT_DEAD]"; default: return "[VERIFY_SUSPECT: unknown type (" + type + ")]"; } } public void writeTo(DataOutputStream out) throws IOException { out.writeShort(type); Util.writeAddress(from, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readShort(); from=Util.readAddress(in); } public int size() { return Global.SHORT_SIZE + Util.size(from); } }
[ "public", "static", "class", "VerifyHeader", "extends", "Header", "{", "static", "final", "short", "ARE_YOU_DEAD", "=", "1", ";", "static", "final", "short", "I_AM_NOT_DEAD", "=", "2", ";", "short", "type", "=", "ARE_YOU_DEAD", ";", "Address", "from", "=", "null", ";", "public", "VerifyHeader", "(", ")", "{", "}", "VerifyHeader", "(", "short", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "VerifyHeader", "(", "short", "type", ",", "Address", "from", ")", "{", "this", "(", "type", ")", ";", "this", ".", "from", "=", "from", ";", "}", "public", "String", "toString", "(", ")", "{", "switch", "(", "type", ")", "{", "case", "ARE_YOU_DEAD", ":", "return", "\"", "[VERIFY_SUSPECT: ARE_YOU_DEAD]", "\"", ";", "case", "I_AM_NOT_DEAD", ":", "return", "\"", "[VERIFY_SUSPECT: I_AM_NOT_DEAD]", "\"", ";", "default", ":", "return", "\"", "[VERIFY_SUSPECT: unknown type (", "\"", "+", "type", "+", "\"", ")]", "\"", ";", "}", "}", "public", "void", "writeTo", "(", "DataOutputStream", "out", ")", "throws", "IOException", "{", "out", ".", "writeShort", "(", "type", ")", ";", "Util", ".", "writeAddress", "(", "from", ",", "out", ")", ";", "}", "public", "void", "readFrom", "(", "DataInputStream", "in", ")", "throws", "IOException", ",", "IllegalAccessException", ",", "InstantiationException", "{", "type", "=", "in", ".", "readShort", "(", ")", ";", "from", "=", "Util", ".", "readAddress", "(", "in", ")", ";", "}", "public", "int", "size", "(", ")", "{", "return", "Global", ".", "SHORT_SIZE", "+", "Util", ".", "size", "(", "from", ")", ";", "}", "}" ]
End of Private Methods
[ "End", "of", "Private", "Methods" ]
[ "// 'from' is sender of verify msg\r", "// 'from' is suspected member\r", "// member who wants to verify that suspected_mbr is dead\r", "// used for externalization\r" ]
[ { "param": "Header", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Header", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7be0882e5f8bdd1936cbb60a958254d304d33f98
AY1920S1-CS2103-T11-2/main
src/main/java/seedu/address/model/util/SampleDataUtil.java
[ "MIT" ]
Java
SampleDataUtil
/** * Contains utility methods for populating {@code WordBank} with sample data. */
Contains utility methods for populating WordBank with sample data.
[ "Contains", "utility", "methods", "for", "populating", "WordBank", "with", "sample", "data", "." ]
public class SampleDataUtil { private static final String pokemonName = "pokemon"; private static final String arithmeticName = "arithmetic"; private static final String triviaName = "trivia"; private static final String cs2103tName = "cs2103t"; private static final String graphName = "graph"; private static Card[] getPokemonCards() { Card card1 = new Card("abrajfbeoudnjcp", new Word("Pikachu"), new Meaning("Ash's first pokemon."), getTagSet("electric")); Card card2 = new Card("sdfa33234", new Word("Squirtle"), new Meaning("Gary's starter pokemon."), getTagSet("water")); Card card3 = new Card("charizardaiudan", new Word("Charizard"), new Meaning("Charmander's final evolution."), getTagSet("fire", "flying")); Card card4 = new Card("dittonfjsdodc", new Word("Gary"), new Meaning("Ash's rival"), getTagSet("asshole")); Card card5 = new Card("eeveeouhvdsn", new Word("Flareon"), new Meaning("Eevee + fire stone = ?"), getTagSet("fire")); Card card6 = new Card("eeveeouhvdsn", new Word("Mewtwo"), new Meaning("Mew's clone"), getTagSet("psychic")); return new Card[]{card1, card2, card3, card4, card5, card6}; } private static Card[] getArithmeticCards() { Card card1 = new Card("threeajdshakjsd", new Word("3"), new Meaning("2 + 2 - 1 = ?"), getTagSet("Ez")); Card card2 = new Card("11asdfjkhalse", new Word("121"), new Meaning("11 * 11 = ?"), getTagSet("Ez")); Card card3 = new Card("sadjkfhaljk2", new Word("0"), new Meaning("1236123 modulo 9 = ?"), getTagSet("Medium")); Card card4 = new Card("1kbasdasdasdf", new Word("1024"), new Meaning("2 ^ 10 = ?"), getTagSet("Medium")); Card card5 = new Card("adjksfhk", new Word("29126"), new Meaning("square root of 848323876 = ?"), getTagSet("Hard", "Secret")); Card card6 = new Card("uadiosf12", new Word("2103"), new Meaning("21 * 100 + 3 = ?"), getTagSet("Ez")); return new Card[]{card1, card2, card3, card4, card5, card6}; } private static Card[] getTriviaCards() { Card card1 = new Card("adswfasf3", new Word("39"), new Meaning("How old is nus?"), getTagSet("Medium")); Card card2 = new Card("123124123g4", new Word("FASS"), new Meaning("Which faculty has the most student?"), getTagSet("Medium")); Card card3 = new Card("1234g1234g123sadrf", new Word("Dukemon"), new Meaning("What is the best app in the world?"), getTagSet("Easy")); Card card4 = new Card("adsrga3", new Word("SErebros"), new Meaning("What is our group name?"), getTagSet("Hard")); Card card5 = new Card("sdfa33", new Word("cs2103t"), new Meaning("What is the full module code of this mod? _ _ _ _ _ _ _"), getTagSet("Easy")); Card card6 = new Card("sadf2134", new Word("Yes"), new Meaning("Is Dukemon awesome?"), getTagSet("Easy")); return new Card[]{card1, card2, card3, card4, card5, card6}; } private static Card[] getCS2103tCards() { Card card1 = new Card("sasdfaeqr", new Word("Class Diagram"), new Meaning("Describes the structure (but not the behavior) on an OOP solution."), getTagSet("UML")); Card card2 = new Card("asdfasfe", new Word("Object Diagram"), new Meaning("Diagram to model different object structures that can result from a design."), getTagSet("UML")); Card card3 = new Card("23r12345", new Word("Sequence Diagram"), new Meaning("Diagram that captures interactions between multiple objects for a given scenario."), getTagSet("UML")); Card card4 = new Card("dfyjd6", new Word("Coupling"), new Meaning("A measure of the degree of dependence."), getTagSet("DesignPrinciples")); Card card5 = new Card("5324524g", new Word("Cohesion"), new Meaning("Measure of how strongly-related and focused the various responsibilities of" + " a component are."), getTagSet("DesignPrinciples")); Card card6 = new Card("dsgasd2arrads", new Word("Test Coverage"), new Meaning("Metric used to measure the extent to which testing exercises the code."), getTagSet("Coverage")); return new Card[]{card1, card2, card3, card4, card5, card6}; } private static Card[] getGraphCards() { Card card1 = new Card("dfghdfghdfr", new Word("Tree"), new Meaning("A simple graph that is connected and contains no cycle."), getTagSet("Easy")); Card card2 = new Card("bcvncvo", new Word("Leaf"), new Meaning("Vertex of degree 1."), getTagSet("Easy")); Card card3 = new Card("fdjgmjfghjm", new Word("n - 1"), new Meaning("How many edges does a tree with n vertices have?"), getTagSet("Easy")); Card card4 = new Card("fgj6f6df", new Word("Spanning tree"), new Meaning("A type of tree, that is a subgraph of G and contains ALL the vertices of G."), getTagSet("Easy")); Card card5 = new Card("hjklhji9hjil", new Word("Minimal spanning tree"), new Meaning("What is the spanning tree which has the minimum weight among all the spanning trees of" + " a particular graph?"), getTagSet("Easy")); Card card6 = new Card("fhnfhtfhyn", new Word("n - m + l = 2"), new Meaning("Equation for Euler's Formula."), getTagSet("Important")); return new Card[]{card1, card2, card3, card4, card5, card6}; } public static WordBank getPokemonWordBank() { WordBank pokemonWb = new WordBank(pokemonName); for (Card sampleCard : getPokemonCards()) { pokemonWb.addCard(sampleCard); } return pokemonWb; } public static WordBank getArithmeticWordBank() { WordBank arithmeticWb = new WordBank(arithmeticName); for (Card arithmeticCard : getArithmeticCards()) { arithmeticWb.addCard(arithmeticCard); } return arithmeticWb; } public static WordBank getTriviaWordBank() { WordBank triviaWb = new WordBank(triviaName); for (Card triviaCard : getTriviaCards()) { triviaWb.addCard(triviaCard); } return triviaWb; } public static WordBank getCS2103tWordBank() { WordBank cs2103tWb = new WordBank(cs2103tName); for (Card cs2103tCard : getCS2103tCards()) { cs2103tWb.addCard(cs2103tCard); } return cs2103tWb; } public static WordBank getGraphWordBank() { WordBank graphBank = new WordBank(graphName); for (Card graphCard : getGraphCards()) { graphBank.addCard(graphCard); } return graphBank; } /** * Returns a tag set containing the list of strings given. */ public static Set<Tag> getTagSet(String... strings) { return Arrays.stream(strings) .map(Tag::new) .collect(Collectors.toSet()); } }
[ "public", "class", "SampleDataUtil", "{", "private", "static", "final", "String", "pokemonName", "=", "\"", "pokemon", "\"", ";", "private", "static", "final", "String", "arithmeticName", "=", "\"", "arithmetic", "\"", ";", "private", "static", "final", "String", "triviaName", "=", "\"", "trivia", "\"", ";", "private", "static", "final", "String", "cs2103tName", "=", "\"", "cs2103t", "\"", ";", "private", "static", "final", "String", "graphName", "=", "\"", "graph", "\"", ";", "private", "static", "Card", "[", "]", "getPokemonCards", "(", ")", "{", "Card", "card1", "=", "new", "Card", "(", "\"", "abrajfbeoudnjcp", "\"", ",", "new", "Word", "(", "\"", "Pikachu", "\"", ")", ",", "new", "Meaning", "(", "\"", "Ash's first pokemon.", "\"", ")", ",", "getTagSet", "(", "\"", "electric", "\"", ")", ")", ";", "Card", "card2", "=", "new", "Card", "(", "\"", "sdfa33234", "\"", ",", "new", "Word", "(", "\"", "Squirtle", "\"", ")", ",", "new", "Meaning", "(", "\"", "Gary's starter pokemon.", "\"", ")", ",", "getTagSet", "(", "\"", "water", "\"", ")", ")", ";", "Card", "card3", "=", "new", "Card", "(", "\"", "charizardaiudan", "\"", ",", "new", "Word", "(", "\"", "Charizard", "\"", ")", ",", "new", "Meaning", "(", "\"", "Charmander's final evolution.", "\"", ")", ",", "getTagSet", "(", "\"", "fire", "\"", ",", "\"", "flying", "\"", ")", ")", ";", "Card", "card4", "=", "new", "Card", "(", "\"", "dittonfjsdodc", "\"", ",", "new", "Word", "(", "\"", "Gary", "\"", ")", ",", "new", "Meaning", "(", "\"", "Ash's rival", "\"", ")", ",", "getTagSet", "(", "\"", "asshole", "\"", ")", ")", ";", "Card", "card5", "=", "new", "Card", "(", "\"", "eeveeouhvdsn", "\"", ",", "new", "Word", "(", "\"", "Flareon", "\"", ")", ",", "new", "Meaning", "(", "\"", "Eevee + fire stone = ?", "\"", ")", ",", "getTagSet", "(", "\"", "fire", "\"", ")", ")", ";", "Card", "card6", "=", "new", "Card", "(", "\"", "eeveeouhvdsn", "\"", ",", "new", "Word", "(", "\"", "Mewtwo", "\"", ")", ",", "new", "Meaning", "(", "\"", "Mew's clone", "\"", ")", ",", "getTagSet", "(", "\"", "psychic", "\"", ")", ")", ";", "return", "new", "Card", "[", "]", "{", "card1", ",", "card2", ",", "card3", ",", "card4", ",", "card5", ",", "card6", "}", ";", "}", "private", "static", "Card", "[", "]", "getArithmeticCards", "(", ")", "{", "Card", "card1", "=", "new", "Card", "(", "\"", "threeajdshakjsd", "\"", ",", "new", "Word", "(", "\"", "3", "\"", ")", ",", "new", "Meaning", "(", "\"", "2 + 2 - 1 = ?", "\"", ")", ",", "getTagSet", "(", "\"", "Ez", "\"", ")", ")", ";", "Card", "card2", "=", "new", "Card", "(", "\"", "11asdfjkhalse", "\"", ",", "new", "Word", "(", "\"", "121", "\"", ")", ",", "new", "Meaning", "(", "\"", "11 * 11 = ?", "\"", ")", ",", "getTagSet", "(", "\"", "Ez", "\"", ")", ")", ";", "Card", "card3", "=", "new", "Card", "(", "\"", "sadjkfhaljk2", "\"", ",", "new", "Word", "(", "\"", "0", "\"", ")", ",", "new", "Meaning", "(", "\"", "1236123 modulo 9 = ?", "\"", ")", ",", "getTagSet", "(", "\"", "Medium", "\"", ")", ")", ";", "Card", "card4", "=", "new", "Card", "(", "\"", "1kbasdasdasdf", "\"", ",", "new", "Word", "(", "\"", "1024", "\"", ")", ",", "new", "Meaning", "(", "\"", "2 ^ 10 = ?", "\"", ")", ",", "getTagSet", "(", "\"", "Medium", "\"", ")", ")", ";", "Card", "card5", "=", "new", "Card", "(", "\"", "adjksfhk", "\"", ",", "new", "Word", "(", "\"", "29126", "\"", ")", ",", "new", "Meaning", "(", "\"", "square root of 848323876 = ?", "\"", ")", ",", "getTagSet", "(", "\"", "Hard", "\"", ",", "\"", "Secret", "\"", ")", ")", ";", "Card", "card6", "=", "new", "Card", "(", "\"", "uadiosf12", "\"", ",", "new", "Word", "(", "\"", "2103", "\"", ")", ",", "new", "Meaning", "(", "\"", "21 * 100 + 3 = ?", "\"", ")", ",", "getTagSet", "(", "\"", "Ez", "\"", ")", ")", ";", "return", "new", "Card", "[", "]", "{", "card1", ",", "card2", ",", "card3", ",", "card4", ",", "card5", ",", "card6", "}", ";", "}", "private", "static", "Card", "[", "]", "getTriviaCards", "(", ")", "{", "Card", "card1", "=", "new", "Card", "(", "\"", "adswfasf3", "\"", ",", "new", "Word", "(", "\"", "39", "\"", ")", ",", "new", "Meaning", "(", "\"", "How old is nus?", "\"", ")", ",", "getTagSet", "(", "\"", "Medium", "\"", ")", ")", ";", "Card", "card2", "=", "new", "Card", "(", "\"", "123124123g4", "\"", ",", "new", "Word", "(", "\"", "FASS", "\"", ")", ",", "new", "Meaning", "(", "\"", "Which faculty has the most student?", "\"", ")", ",", "getTagSet", "(", "\"", "Medium", "\"", ")", ")", ";", "Card", "card3", "=", "new", "Card", "(", "\"", "1234g1234g123sadrf", "\"", ",", "new", "Word", "(", "\"", "Dukemon", "\"", ")", ",", "new", "Meaning", "(", "\"", "What is the best app in the world?", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card4", "=", "new", "Card", "(", "\"", "adsrga3", "\"", ",", "new", "Word", "(", "\"", "SErebros", "\"", ")", ",", "new", "Meaning", "(", "\"", "What is our group name?", "\"", ")", ",", "getTagSet", "(", "\"", "Hard", "\"", ")", ")", ";", "Card", "card5", "=", "new", "Card", "(", "\"", "sdfa33", "\"", ",", "new", "Word", "(", "\"", "cs2103t", "\"", ")", ",", "new", "Meaning", "(", "\"", "What is the full module code of this mod? _ _ _ _ _ _ _", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card6", "=", "new", "Card", "(", "\"", "sadf2134", "\"", ",", "new", "Word", "(", "\"", "Yes", "\"", ")", ",", "new", "Meaning", "(", "\"", "Is Dukemon awesome?", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "return", "new", "Card", "[", "]", "{", "card1", ",", "card2", ",", "card3", ",", "card4", ",", "card5", ",", "card6", "}", ";", "}", "private", "static", "Card", "[", "]", "getCS2103tCards", "(", ")", "{", "Card", "card1", "=", "new", "Card", "(", "\"", "sasdfaeqr", "\"", ",", "new", "Word", "(", "\"", "Class Diagram", "\"", ")", ",", "new", "Meaning", "(", "\"", "Describes the structure (but not the behavior) on an OOP solution.", "\"", ")", ",", "getTagSet", "(", "\"", "UML", "\"", ")", ")", ";", "Card", "card2", "=", "new", "Card", "(", "\"", "asdfasfe", "\"", ",", "new", "Word", "(", "\"", "Object Diagram", "\"", ")", ",", "new", "Meaning", "(", "\"", "Diagram to model different object structures that can result from a design.", "\"", ")", ",", "getTagSet", "(", "\"", "UML", "\"", ")", ")", ";", "Card", "card3", "=", "new", "Card", "(", "\"", "23r12345", "\"", ",", "new", "Word", "(", "\"", "Sequence Diagram", "\"", ")", ",", "new", "Meaning", "(", "\"", "Diagram that captures interactions between multiple objects for a given scenario.", "\"", ")", ",", "getTagSet", "(", "\"", "UML", "\"", ")", ")", ";", "Card", "card4", "=", "new", "Card", "(", "\"", "dfyjd6", "\"", ",", "new", "Word", "(", "\"", "Coupling", "\"", ")", ",", "new", "Meaning", "(", "\"", "A measure of the degree of dependence.", "\"", ")", ",", "getTagSet", "(", "\"", "DesignPrinciples", "\"", ")", ")", ";", "Card", "card5", "=", "new", "Card", "(", "\"", "5324524g", "\"", ",", "new", "Word", "(", "\"", "Cohesion", "\"", ")", ",", "new", "Meaning", "(", "\"", "Measure of how strongly-related and focused the various responsibilities of", "\"", "+", "\"", " a component are.", "\"", ")", ",", "getTagSet", "(", "\"", "DesignPrinciples", "\"", ")", ")", ";", "Card", "card6", "=", "new", "Card", "(", "\"", "dsgasd2arrads", "\"", ",", "new", "Word", "(", "\"", "Test Coverage", "\"", ")", ",", "new", "Meaning", "(", "\"", "Metric used to measure the extent to which testing exercises the code.", "\"", ")", ",", "getTagSet", "(", "\"", "Coverage", "\"", ")", ")", ";", "return", "new", "Card", "[", "]", "{", "card1", ",", "card2", ",", "card3", ",", "card4", ",", "card5", ",", "card6", "}", ";", "}", "private", "static", "Card", "[", "]", "getGraphCards", "(", ")", "{", "Card", "card1", "=", "new", "Card", "(", "\"", "dfghdfghdfr", "\"", ",", "new", "Word", "(", "\"", "Tree", "\"", ")", ",", "new", "Meaning", "(", "\"", "A simple graph that is connected and contains no cycle.", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card2", "=", "new", "Card", "(", "\"", "bcvncvo", "\"", ",", "new", "Word", "(", "\"", "Leaf", "\"", ")", ",", "new", "Meaning", "(", "\"", "Vertex of degree 1.", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card3", "=", "new", "Card", "(", "\"", "fdjgmjfghjm", "\"", ",", "new", "Word", "(", "\"", "n - 1", "\"", ")", ",", "new", "Meaning", "(", "\"", "How many edges does a tree with n vertices have?", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card4", "=", "new", "Card", "(", "\"", "fgj6f6df", "\"", ",", "new", "Word", "(", "\"", "Spanning tree", "\"", ")", ",", "new", "Meaning", "(", "\"", "A type of tree, that is a subgraph of G and contains ALL the vertices of G.", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card5", "=", "new", "Card", "(", "\"", "hjklhji9hjil", "\"", ",", "new", "Word", "(", "\"", "Minimal spanning tree", "\"", ")", ",", "new", "Meaning", "(", "\"", "What is the spanning tree which has the minimum weight among all the spanning trees of", "\"", "+", "\"", " a particular graph?", "\"", ")", ",", "getTagSet", "(", "\"", "Easy", "\"", ")", ")", ";", "Card", "card6", "=", "new", "Card", "(", "\"", "fhnfhtfhyn", "\"", ",", "new", "Word", "(", "\"", "n - m + l = 2", "\"", ")", ",", "new", "Meaning", "(", "\"", "Equation for Euler's Formula.", "\"", ")", ",", "getTagSet", "(", "\"", "Important", "\"", ")", ")", ";", "return", "new", "Card", "[", "]", "{", "card1", ",", "card2", ",", "card3", ",", "card4", ",", "card5", ",", "card6", "}", ";", "}", "public", "static", "WordBank", "getPokemonWordBank", "(", ")", "{", "WordBank", "pokemonWb", "=", "new", "WordBank", "(", "pokemonName", ")", ";", "for", "(", "Card", "sampleCard", ":", "getPokemonCards", "(", ")", ")", "{", "pokemonWb", ".", "addCard", "(", "sampleCard", ")", ";", "}", "return", "pokemonWb", ";", "}", "public", "static", "WordBank", "getArithmeticWordBank", "(", ")", "{", "WordBank", "arithmeticWb", "=", "new", "WordBank", "(", "arithmeticName", ")", ";", "for", "(", "Card", "arithmeticCard", ":", "getArithmeticCards", "(", ")", ")", "{", "arithmeticWb", ".", "addCard", "(", "arithmeticCard", ")", ";", "}", "return", "arithmeticWb", ";", "}", "public", "static", "WordBank", "getTriviaWordBank", "(", ")", "{", "WordBank", "triviaWb", "=", "new", "WordBank", "(", "triviaName", ")", ";", "for", "(", "Card", "triviaCard", ":", "getTriviaCards", "(", ")", ")", "{", "triviaWb", ".", "addCard", "(", "triviaCard", ")", ";", "}", "return", "triviaWb", ";", "}", "public", "static", "WordBank", "getCS2103tWordBank", "(", ")", "{", "WordBank", "cs2103tWb", "=", "new", "WordBank", "(", "cs2103tName", ")", ";", "for", "(", "Card", "cs2103tCard", ":", "getCS2103tCards", "(", ")", ")", "{", "cs2103tWb", ".", "addCard", "(", "cs2103tCard", ")", ";", "}", "return", "cs2103tWb", ";", "}", "public", "static", "WordBank", "getGraphWordBank", "(", ")", "{", "WordBank", "graphBank", "=", "new", "WordBank", "(", "graphName", ")", ";", "for", "(", "Card", "graphCard", ":", "getGraphCards", "(", ")", ")", "{", "graphBank", ".", "addCard", "(", "graphCard", ")", ";", "}", "return", "graphBank", ";", "}", "/**\n * Returns a tag set containing the list of strings given.\n */", "public", "static", "Set", "<", "Tag", ">", "getTagSet", "(", "String", "...", "strings", ")", "{", "return", "Arrays", ".", "stream", "(", "strings", ")", ".", "map", "(", "Tag", "::", "new", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}", "}" ]
Contains utility methods for populating {@code WordBank} with sample data.
[ "Contains", "utility", "methods", "for", "populating", "{", "@code", "WordBank", "}", "with", "sample", "data", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7be397ce3410038b17b6de5d6bbe158ad0f905b3
yashashrirane/interlok
interlok-core/src/main/java/com/adaptris/core/MultiPayloadAdaptrisMessageImp.java
[ "Apache-2.0" ]
Java
MultiPayloadAdaptrisMessageImp
/** * The standard implementation of multi-payload messages; * {@link MultiPayloadAdaptrisMessage} implementation created by * {@link MultiPayloadMessageFactory}. * * @author aanderson * @see MultiPayloadAdaptrisMessage * @see MultiPayloadMessageFactory * @see AdaptrisMessageImp * @since 3.9.3 */
The standard implementation of multi-payload messages; MultiPayloadAdaptrisMessage implementation created by MultiPayloadMessageFactory.
[ "The", "standard", "implementation", "of", "multi", "-", "payload", "messages", ";", "MultiPayloadAdaptrisMessage", "implementation", "created", "by", "MultiPayloadMessageFactory", "." ]
@ComponentProfile(summary = "A multi-payload message implementation", tag = "multi-payload,message", since="3.9.3") public class MultiPayloadAdaptrisMessageImp extends AdaptrisMessageImp implements MultiPayloadAdaptrisMessage { private static final String RESOLVE_REGEXP = "^.*%payload_id\\{([\\w!\\$\"#&%'\\*\\+,\\-\\.:=]+)\\}.*$"; private static final String RESOLVE_2_REGEX = "^.*%payload\\{id:([\\w!\\$\"#&%'\\*\\+,\\-\\.:=]+)\\}.*$"; private static final transient Pattern normalPayloadResolver = Pattern.compile(RESOLVE_REGEXP); private static final transient Pattern dotAllPayloadResolver = Pattern.compile(RESOLVE_REGEXP, Pattern.DOTALL); private static final transient Pattern normalPayloadResolver2 = Pattern.compile(RESOLVE_2_REGEX); private static final transient Pattern dotAllPayloadResolver2 = Pattern.compile(RESOLVE_2_REGEX, Pattern.DOTALL); private Map<String, Payload> payloads = new HashMap<>(); @NotNull private String currentPayloadId = DEFAULT_PAYLOAD_ID; public MultiPayloadAdaptrisMessageImp(@NotNull String payloadId, IdGenerator guid, AdaptrisMessageFactory messageFactory) { this(payloadId, guid, messageFactory, new byte[0]); } public MultiPayloadAdaptrisMessageImp(@NotNull String payloadId, IdGenerator guid, AdaptrisMessageFactory messageFactory, byte[] payload) { super(guid, messageFactory); addPayload(payloadId, payload); } public MultiPayloadAdaptrisMessageImp(@NotNull String payloadId, IdGenerator guid, AdaptrisMessageFactory messageFactory, String content, Charset encoding) { super(guid, messageFactory); addContent(payloadId, content, encoding != null ? encoding.toString() : null); } /** * {@inheritDoc}. */ @Override public void switchPayload(@NotNull String payloadId) { currentPayloadId = payloadId; } /** * {@inheritDoc}. */ @Override public boolean hasPayloadId(@NotNull String payloadId) { return payloads.containsKey(payloadId); } /** * {@inheritDoc}. */ @Override public void setCurrentPayloadId(@NotNull String payloadId) { Payload payload = payloads.remove(currentPayloadId); currentPayloadId = payloadId; payloads.put(currentPayloadId, payload); } /** * {@inheritDoc}. */ @Override public String getCurrentPayloadId() { return currentPayloadId; } /** * {@inheritDoc}. */ @Override public Set<String> getPayloadIDs() { return payloads.keySet(); } /** * @see AdaptrisMessage#equivalentForTracking * (com.adaptris.core.AdaptrisMessage). */ @Override public boolean equivalentForTracking(AdaptrisMessage o) { if (!(o instanceof MultiPayloadAdaptrisMessage)) { return false; } MultiPayloadAdaptrisMessage other = (MultiPayloadAdaptrisMessage) o; if (!StringUtils.equals(getUniqueId(), other.getUniqueId())) { return false; } if (!getMetadata().equals(other.getMetadata())) { return false; } if (getPayloadCount() != other.getPayloadCount()) { return false; } for (String id : payloads.keySet()) { if (!other.hasPayloadId(id)) { return false; } else if (!Arrays.equals(getPayload(id), other.getPayload(id))) { return false; } else if (!StringUtils.equals(getContentEncoding(id), other.getContentEncoding(id))) { return false; } } return true; } /** * Set the current payload data. * * @param bytes * The payload data. * @see AdaptrisMessage#setPayload(byte[]) */ @Override public void setPayload(byte[] bytes) { addPayload(currentPayloadId, bytes); } /** * {@inheritDoc}. */ @Override public void addPayload(@NotNull String payloadId, byte[] bytes) { byte[] pb; if (bytes == null) { pb = new byte[0]; } else { pb = bytes; } Payload payload; if (payloads.containsKey(payloadId)) { payload = payloads.get(payloadId); payload.data = pb; } else { payload = new Payload(pb); } payloads.put(payloadId, payload); currentPayloadId = payloadId; } /** * {@inheritDoc}. */ @Override public void deletePayload(@NotNull String payloadId) { payloads.remove(payloadId); } /** * Get the current payload data. * * @return The payload data. * @see AdaptrisMessage#getPayload() */ @Override public byte[] getPayload() { return getPayload(currentPayloadId); } /** * {@inheritDoc}. */ @Override public byte[] getPayload(@NotNull String payloadId) { return payloads.get(payloadId).payload(); } /** * Get the current payload size. * * @return The payload size. * @see AdaptrisMessage#getSize() */ @Override public long getSize() { return getSize(currentPayloadId); } /** * {@inheritDoc}. */ public int getPayloadCount() { return payloads.size(); } /** * {@inheritDoc}. */ @Override public long getSize(@NotNull String payloadId) { return getPayload(payloadId).length; } /** * @see InterlokMessage#setContent(String, String). */ @Override public void setContent(String payloadString, String charEnc) { addContent(currentPayloadId, payloadString, charEnc); } /** * {@inheritDoc}. */ @Override public void setContent(String payloadId, String payloadString, String charEnc) { addContent(payloadId, payloadString, charEnc); } /** * {@inheritDoc}. */ @Override public void addContent(@NotNull String payloadId, String payloadString) { String encoding = null; if (payloads.containsKey(payloadId)) { encoding = getContentEncoding(payloadId); } addContent(payloadId, payloadString, encoding); } /** * {@inheritDoc}. */ @Override public void addContent(@NotNull String payloadId, String payloadString, String charEnc) { byte[] payload; if (payloadString != null) { Charset charset = Charset.forName(StringUtils.defaultIfBlank(charEnc, Charset.defaultCharset().name())); payload = payloadString.getBytes(charset); } else { payload = new byte[0]; } setContentEncoding(payloadId, charEnc); addPayload(payloadId, payload); } /** * Get the current payload content. * * @return The payload content. * @see AdaptrisMessage#getContent() */ @Override public String getContent() { return getContent(currentPayloadId); } /** * {@inheritDoc}. */ @Override public String getContent(@NotNull String payloadId) { byte[] payload = getPayload(payloadId); if (isEmpty(getContentEncoding())) { return new String(payload); } else { return new String(payload, Charset.forName(getContentEncoding())); } } @Override public String getPayloadForLogging() { StringBuffer sb = new StringBuffer("{"); boolean c = false; for (String id : payloads.keySet()) { if (c) { sb.append(","); } else { c = true; } sb.append(id); if (id.equals(currentPayloadId)) { sb.append(":"); sb.append(getContent(id)); } } return sb.append("}").toString(); } /** * {@inheritDoc}. */ @Override public void setContentEncoding(String enc) { setContentEncoding(currentPayloadId, enc); } /** * {@inheritDoc}. */ @Override public void setContentEncoding(@NotNull String payloadId, String enc) { String contentEncoding = enc != null ? Charset.forName(enc).name() : getFactory().getDefaultCharEncoding(); Payload payload; if (payloads.containsKey(payloadId)) { payload = payloads.get(payloadId); payload.encoding = contentEncoding; } else { payload = new Payload(contentEncoding, new byte[0]); } payloads.put(payloadId, payload); } /** * {@inheritDoc}. */ @Override public String getContentEncoding() { return getContentEncoding(currentPayloadId); } /** * {@inheritDoc}. */ @Override public String getContentEncoding(@NotNull String payloadId) { return payloads.containsKey(payloadId) ? payloads.get(payloadId).encoding : getFactory().getDefaultCharEncoding(); } /** * @see Object#clone() */ @Override public Object clone() throws CloneNotSupportedException { MultiPayloadAdaptrisMessageImp result = (MultiPayloadAdaptrisMessageImp) super.clone(); // clone the payloads. result.payloads = new HashMap<>(); for (String payloadId : payloads.keySet()) { Payload payload = payloads.get(payloadId); result.addPayload(payloadId, payload.payload()); result.setContentEncoding(payloadId, payload.encoding); } result.switchPayload(currentPayloadId); return result; } /** * @see AdaptrisMessage#getInputStream() */ @Override public InputStream getInputStream() { return getInputStream(currentPayloadId); } /** * {@inheritDoc}. */ @Override public InputStream getInputStream(@NotNull String payloadId) { byte[] payload = getPayload(payloadId); return payload != null ? new ByteArrayInputStream(payload) : new ByteArrayInputStream(new byte[0]); } /** * @see AdaptrisMessage#getOutputStream() */ @Override public OutputStream getOutputStream() { return getOutputStream(currentPayloadId); } /** * {@inheritDoc}. */ @Override public OutputStream getOutputStream(@NotNull String payloadId) { return new ByteFilterStream(payloadId, new ByteArrayOutputStream()); } /** * @see InterlokMessage#getWriter() */ @Override public Writer getWriter() throws IOException { return getWriter(currentPayloadId); } /** * {@inheritDoc}. */ @Override public Writer getWriter(@NotNull String payloadId) throws IOException { return getWriter(payloadId, getContentEncoding(payloadId)); } /** * {@inheritDoc}. */ @Override public Writer getWriter(@NotNull String payloadId, String encoding) throws IOException { OutputStream outputStream = getOutputStream(payloadId); return encoding != null ? new OutputStreamWriter(outputStream, encoding) : new OutputStreamWriter(outputStream); } /** * Resolve against this message's payloads or metadata. * * This is a helper method that allows you to pass in {@code %payload_id{pl1}} * and get the payload associated with {@code pl1}, or {@code %message{key1}} * and get the metadata associated with {@code key1}. Strings that do not match * that format will be returned as is. Support for punctuation characters is * down to the implementation; the standard implementations only support a * limited subset of punctuation characters in addition to standard word * characters ({@code [a-zA-Z_0-9]}); they are {@code _!"#&'+,-.:=}. The magic * values {@code %message{%uniqueId}} and {@code %message{%size}} should return * the message unique-id and message size respectively. * * @param target * The string to resolve. * @param dotAll * Whether to resolve in {@link java.util.regex.Pattern#DOTALL} mode, * allowing you to match against multiple lines. * @return The original string, the matched payload, an item of metadata, or * null (if none exists). */ @Override public String resolve(String target, boolean dotAll) { if (target == null) { return null; } target = super.resolve(target, dotAll); // resolve any %payload{id:...}'s or %payload_id{...}'s before attempting any %message{...}'s Pattern pattern = dotAll ? normalPayloadResolver2 : dotAllPayloadResolver2; target = resolve(target, pattern, false); pattern = dotAll ? normalPayloadResolver : dotAllPayloadResolver; return resolve(target, pattern, true); } private String resolve(String target, Pattern pattern, boolean defaultPattern) { Matcher m = pattern.matcher(target); while (m.matches()) { String key = m.group(1); if (!hasPayloadId(key)) { throw new UnresolvableException("Could not resolve payload ID [" + key + "]"); } target = target.replace(String.format(defaultPattern ? "%%payload_id{%s}" : "%%payload{id:%s}", key), getContent(key)); m = pattern.matcher(target); } return target; } private class ByteFilterStream extends FilterOutputStream { private final String payloadId; ByteFilterStream(@NotNull String payloadId, ByteArrayOutputStream out) { super(out); this.payloadId = payloadId; payloads.put(payloadId, new Payload(out)); } @Override public void close() throws IOException { super.close(); addPayload(payloadId, ((ByteArrayOutputStream) super.out).toByteArray()); } } private class Payload { String encoding = getFactory().getDefaultCharEncoding(); private byte[] data; private ByteArrayOutputStream stream; Payload(String encoding, @NotNull byte[] data) { this.encoding = encoding; this.data = data; } Payload(@NotNull byte[] data) { this.data = data; } Payload(@NotNull ByteArrayOutputStream stream) { this.stream = stream; } byte[] payload() { if (stream != null) { return stream.toByteArray(); } return data; } } }
[ "@", "ComponentProfile", "(", "summary", "=", "\"", "A multi-payload message implementation", "\"", ",", "tag", "=", "\"", "multi-payload,message", "\"", ",", "since", "=", "\"", "3.9.3", "\"", ")", "public", "class", "MultiPayloadAdaptrisMessageImp", "extends", "AdaptrisMessageImp", "implements", "MultiPayloadAdaptrisMessage", "{", "private", "static", "final", "String", "RESOLVE_REGEXP", "=", "\"", "^.*%payload_id", "\\\\", "{([", "\\\\", "w!", "\\\\", "$", "\\\"", "#&%'", "\\\\", "*", "\\\\", "+,", "\\\\", "-", "\\\\", ".:=]+)", "\\\\", "}.*$", "\"", ";", "private", "static", "final", "String", "RESOLVE_2_REGEX", "=", "\"", "^.*%payload", "\\\\", "{id:([", "\\\\", "w!", "\\\\", "$", "\\\"", "#&%'", "\\\\", "*", "\\\\", "+,", "\\\\", "-", "\\\\", ".:=]+)", "\\\\", "}.*$", "\"", ";", "private", "static", "final", "transient", "Pattern", "normalPayloadResolver", "=", "Pattern", ".", "compile", "(", "RESOLVE_REGEXP", ")", ";", "private", "static", "final", "transient", "Pattern", "dotAllPayloadResolver", "=", "Pattern", ".", "compile", "(", "RESOLVE_REGEXP", ",", "Pattern", ".", "DOTALL", ")", ";", "private", "static", "final", "transient", "Pattern", "normalPayloadResolver2", "=", "Pattern", ".", "compile", "(", "RESOLVE_2_REGEX", ")", ";", "private", "static", "final", "transient", "Pattern", "dotAllPayloadResolver2", "=", "Pattern", ".", "compile", "(", "RESOLVE_2_REGEX", ",", "Pattern", ".", "DOTALL", ")", ";", "private", "Map", "<", "String", ",", "Payload", ">", "payloads", "=", "new", "HashMap", "<", ">", "(", ")", ";", "@", "NotNull", "private", "String", "currentPayloadId", "=", "DEFAULT_PAYLOAD_ID", ";", "public", "MultiPayloadAdaptrisMessageImp", "(", "@", "NotNull", "String", "payloadId", ",", "IdGenerator", "guid", ",", "AdaptrisMessageFactory", "messageFactory", ")", "{", "this", "(", "payloadId", ",", "guid", ",", "messageFactory", ",", "new", "byte", "[", "0", "]", ")", ";", "}", "public", "MultiPayloadAdaptrisMessageImp", "(", "@", "NotNull", "String", "payloadId", ",", "IdGenerator", "guid", ",", "AdaptrisMessageFactory", "messageFactory", ",", "byte", "[", "]", "payload", ")", "{", "super", "(", "guid", ",", "messageFactory", ")", ";", "addPayload", "(", "payloadId", ",", "payload", ")", ";", "}", "public", "MultiPayloadAdaptrisMessageImp", "(", "@", "NotNull", "String", "payloadId", ",", "IdGenerator", "guid", ",", "AdaptrisMessageFactory", "messageFactory", ",", "String", "content", ",", "Charset", "encoding", ")", "{", "super", "(", "guid", ",", "messageFactory", ")", ";", "addContent", "(", "payloadId", ",", "content", ",", "encoding", "!=", "null", "?", "encoding", ".", "toString", "(", ")", ":", "null", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "switchPayload", "(", "@", "NotNull", "String", "payloadId", ")", "{", "currentPayloadId", "=", "payloadId", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "boolean", "hasPayloadId", "(", "@", "NotNull", "String", "payloadId", ")", "{", "return", "payloads", ".", "containsKey", "(", "payloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "setCurrentPayloadId", "(", "@", "NotNull", "String", "payloadId", ")", "{", "Payload", "payload", "=", "payloads", ".", "remove", "(", "currentPayloadId", ")", ";", "currentPayloadId", "=", "payloadId", ";", "payloads", ".", "put", "(", "currentPayloadId", ",", "payload", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "String", "getCurrentPayloadId", "(", ")", "{", "return", "currentPayloadId", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "Set", "<", "String", ">", "getPayloadIDs", "(", ")", "{", "return", "payloads", ".", "keySet", "(", ")", ";", "}", "/**\n * @see AdaptrisMessage#equivalentForTracking\n * (com.adaptris.core.AdaptrisMessage).\n */", "@", "Override", "public", "boolean", "equivalentForTracking", "(", "AdaptrisMessage", "o", ")", "{", "if", "(", "!", "(", "o", "instanceof", "MultiPayloadAdaptrisMessage", ")", ")", "{", "return", "false", ";", "}", "MultiPayloadAdaptrisMessage", "other", "=", "(", "MultiPayloadAdaptrisMessage", ")", "o", ";", "if", "(", "!", "StringUtils", ".", "equals", "(", "getUniqueId", "(", ")", ",", "other", ".", "getUniqueId", "(", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "getMetadata", "(", ")", ".", "equals", "(", "other", ".", "getMetadata", "(", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "getPayloadCount", "(", ")", "!=", "other", ".", "getPayloadCount", "(", ")", ")", "{", "return", "false", ";", "}", "for", "(", "String", "id", ":", "payloads", ".", "keySet", "(", ")", ")", "{", "if", "(", "!", "other", ".", "hasPayloadId", "(", "id", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "!", "Arrays", ".", "equals", "(", "getPayload", "(", "id", ")", ",", "other", ".", "getPayload", "(", "id", ")", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "!", "StringUtils", ".", "equals", "(", "getContentEncoding", "(", "id", ")", ",", "other", ".", "getContentEncoding", "(", "id", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "/**\n * Set the current payload data.\n *\n * @param bytes\n * The payload data.\n * @see AdaptrisMessage#setPayload(byte[])\n */", "@", "Override", "public", "void", "setPayload", "(", "byte", "[", "]", "bytes", ")", "{", "addPayload", "(", "currentPayloadId", ",", "bytes", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "addPayload", "(", "@", "NotNull", "String", "payloadId", ",", "byte", "[", "]", "bytes", ")", "{", "byte", "[", "]", "pb", ";", "if", "(", "bytes", "==", "null", ")", "{", "pb", "=", "new", "byte", "[", "0", "]", ";", "}", "else", "{", "pb", "=", "bytes", ";", "}", "Payload", "payload", ";", "if", "(", "payloads", ".", "containsKey", "(", "payloadId", ")", ")", "{", "payload", "=", "payloads", ".", "get", "(", "payloadId", ")", ";", "payload", ".", "data", "=", "pb", ";", "}", "else", "{", "payload", "=", "new", "Payload", "(", "pb", ")", ";", "}", "payloads", ".", "put", "(", "payloadId", ",", "payload", ")", ";", "currentPayloadId", "=", "payloadId", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "deletePayload", "(", "@", "NotNull", "String", "payloadId", ")", "{", "payloads", ".", "remove", "(", "payloadId", ")", ";", "}", "/**\n * Get the current payload data.\n *\n * @return The payload data.\n * @see AdaptrisMessage#getPayload()\n */", "@", "Override", "public", "byte", "[", "]", "getPayload", "(", ")", "{", "return", "getPayload", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "byte", "[", "]", "getPayload", "(", "@", "NotNull", "String", "payloadId", ")", "{", "return", "payloads", ".", "get", "(", "payloadId", ")", ".", "payload", "(", ")", ";", "}", "/**\n * Get the current payload size.\n *\n * @return The payload size.\n * @see AdaptrisMessage#getSize()\n */", "@", "Override", "public", "long", "getSize", "(", ")", "{", "return", "getSize", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "public", "int", "getPayloadCount", "(", ")", "{", "return", "payloads", ".", "size", "(", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "long", "getSize", "(", "@", "NotNull", "String", "payloadId", ")", "{", "return", "getPayload", "(", "payloadId", ")", ".", "length", ";", "}", "/**\n * @see InterlokMessage#setContent(String, String).\n */", "@", "Override", "public", "void", "setContent", "(", "String", "payloadString", ",", "String", "charEnc", ")", "{", "addContent", "(", "currentPayloadId", ",", "payloadString", ",", "charEnc", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "setContent", "(", "String", "payloadId", ",", "String", "payloadString", ",", "String", "charEnc", ")", "{", "addContent", "(", "payloadId", ",", "payloadString", ",", "charEnc", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "addContent", "(", "@", "NotNull", "String", "payloadId", ",", "String", "payloadString", ")", "{", "String", "encoding", "=", "null", ";", "if", "(", "payloads", ".", "containsKey", "(", "payloadId", ")", ")", "{", "encoding", "=", "getContentEncoding", "(", "payloadId", ")", ";", "}", "addContent", "(", "payloadId", ",", "payloadString", ",", "encoding", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "addContent", "(", "@", "NotNull", "String", "payloadId", ",", "String", "payloadString", ",", "String", "charEnc", ")", "{", "byte", "[", "]", "payload", ";", "if", "(", "payloadString", "!=", "null", ")", "{", "Charset", "charset", "=", "Charset", ".", "forName", "(", "StringUtils", ".", "defaultIfBlank", "(", "charEnc", ",", "Charset", ".", "defaultCharset", "(", ")", ".", "name", "(", ")", ")", ")", ";", "payload", "=", "payloadString", ".", "getBytes", "(", "charset", ")", ";", "}", "else", "{", "payload", "=", "new", "byte", "[", "0", "]", ";", "}", "setContentEncoding", "(", "payloadId", ",", "charEnc", ")", ";", "addPayload", "(", "payloadId", ",", "payload", ")", ";", "}", "/**\n * Get the current payload content.\n *\n * @return The payload content.\n * @see AdaptrisMessage#getContent()\n */", "@", "Override", "public", "String", "getContent", "(", ")", "{", "return", "getContent", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "String", "getContent", "(", "@", "NotNull", "String", "payloadId", ")", "{", "byte", "[", "]", "payload", "=", "getPayload", "(", "payloadId", ")", ";", "if", "(", "isEmpty", "(", "getContentEncoding", "(", ")", ")", ")", "{", "return", "new", "String", "(", "payload", ")", ";", "}", "else", "{", "return", "new", "String", "(", "payload", ",", "Charset", ".", "forName", "(", "getContentEncoding", "(", ")", ")", ")", ";", "}", "}", "@", "Override", "public", "String", "getPayloadForLogging", "(", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "\"", "{", "\"", ")", ";", "boolean", "c", "=", "false", ";", "for", "(", "String", "id", ":", "payloads", ".", "keySet", "(", ")", ")", "{", "if", "(", "c", ")", "{", "sb", ".", "append", "(", "\"", ",", "\"", ")", ";", "}", "else", "{", "c", "=", "true", ";", "}", "sb", ".", "append", "(", "id", ")", ";", "if", "(", "id", ".", "equals", "(", "currentPayloadId", ")", ")", "{", "sb", ".", "append", "(", "\"", ":", "\"", ")", ";", "sb", ".", "append", "(", "getContent", "(", "id", ")", ")", ";", "}", "}", "return", "sb", ".", "append", "(", "\"", "}", "\"", ")", ".", "toString", "(", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "setContentEncoding", "(", "String", "enc", ")", "{", "setContentEncoding", "(", "currentPayloadId", ",", "enc", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "void", "setContentEncoding", "(", "@", "NotNull", "String", "payloadId", ",", "String", "enc", ")", "{", "String", "contentEncoding", "=", "enc", "!=", "null", "?", "Charset", ".", "forName", "(", "enc", ")", ".", "name", "(", ")", ":", "getFactory", "(", ")", ".", "getDefaultCharEncoding", "(", ")", ";", "Payload", "payload", ";", "if", "(", "payloads", ".", "containsKey", "(", "payloadId", ")", ")", "{", "payload", "=", "payloads", ".", "get", "(", "payloadId", ")", ";", "payload", ".", "encoding", "=", "contentEncoding", ";", "}", "else", "{", "payload", "=", "new", "Payload", "(", "contentEncoding", ",", "new", "byte", "[", "0", "]", ")", ";", "}", "payloads", ".", "put", "(", "payloadId", ",", "payload", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "String", "getContentEncoding", "(", ")", "{", "return", "getContentEncoding", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "String", "getContentEncoding", "(", "@", "NotNull", "String", "payloadId", ")", "{", "return", "payloads", ".", "containsKey", "(", "payloadId", ")", "?", "payloads", ".", "get", "(", "payloadId", ")", ".", "encoding", ":", "getFactory", "(", ")", ".", "getDefaultCharEncoding", "(", ")", ";", "}", "/**\n * @see Object#clone()\n */", "@", "Override", "public", "Object", "clone", "(", ")", "throws", "CloneNotSupportedException", "{", "MultiPayloadAdaptrisMessageImp", "result", "=", "(", "MultiPayloadAdaptrisMessageImp", ")", "super", ".", "clone", "(", ")", ";", "result", ".", "payloads", "=", "new", "HashMap", "<", ">", "(", ")", ";", "for", "(", "String", "payloadId", ":", "payloads", ".", "keySet", "(", ")", ")", "{", "Payload", "payload", "=", "payloads", ".", "get", "(", "payloadId", ")", ";", "result", ".", "addPayload", "(", "payloadId", ",", "payload", ".", "payload", "(", ")", ")", ";", "result", ".", "setContentEncoding", "(", "payloadId", ",", "payload", ".", "encoding", ")", ";", "}", "result", ".", "switchPayload", "(", "currentPayloadId", ")", ";", "return", "result", ";", "}", "/**\n * @see AdaptrisMessage#getInputStream()\n */", "@", "Override", "public", "InputStream", "getInputStream", "(", ")", "{", "return", "getInputStream", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "InputStream", "getInputStream", "(", "@", "NotNull", "String", "payloadId", ")", "{", "byte", "[", "]", "payload", "=", "getPayload", "(", "payloadId", ")", ";", "return", "payload", "!=", "null", "?", "new", "ByteArrayInputStream", "(", "payload", ")", ":", "new", "ByteArrayInputStream", "(", "new", "byte", "[", "0", "]", ")", ";", "}", "/**\n * @see AdaptrisMessage#getOutputStream()\n */", "@", "Override", "public", "OutputStream", "getOutputStream", "(", ")", "{", "return", "getOutputStream", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "OutputStream", "getOutputStream", "(", "@", "NotNull", "String", "payloadId", ")", "{", "return", "new", "ByteFilterStream", "(", "payloadId", ",", "new", "ByteArrayOutputStream", "(", ")", ")", ";", "}", "/**\n * @see InterlokMessage#getWriter()\n */", "@", "Override", "public", "Writer", "getWriter", "(", ")", "throws", "IOException", "{", "return", "getWriter", "(", "currentPayloadId", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "Writer", "getWriter", "(", "@", "NotNull", "String", "payloadId", ")", "throws", "IOException", "{", "return", "getWriter", "(", "payloadId", ",", "getContentEncoding", "(", "payloadId", ")", ")", ";", "}", "/**\n * {@inheritDoc}.\n */", "@", "Override", "public", "Writer", "getWriter", "(", "@", "NotNull", "String", "payloadId", ",", "String", "encoding", ")", "throws", "IOException", "{", "OutputStream", "outputStream", "=", "getOutputStream", "(", "payloadId", ")", ";", "return", "encoding", "!=", "null", "?", "new", "OutputStreamWriter", "(", "outputStream", ",", "encoding", ")", ":", "new", "OutputStreamWriter", "(", "outputStream", ")", ";", "}", "/**\n * Resolve against this message's payloads or metadata.\n *\n * This is a helper method that allows you to pass in {@code %payload_id{pl1}}\n * and get the payload associated with {@code pl1}, or {@code %message{key1}}\n * and get the metadata associated with {@code key1}. Strings that do not match\n * that format will be returned as is. Support for punctuation characters is\n * down to the implementation; the standard implementations only support a\n * limited subset of punctuation characters in addition to standard word\n * characters ({@code [a-zA-Z_0-9]}); they are {@code _!\"#&'+,-.:=}. The magic\n * values {@code %message{%uniqueId}} and {@code %message{%size}} should return\n * the message unique-id and message size respectively.\n *\n * @param target\n * The string to resolve.\n * @param dotAll\n * Whether to resolve in {@link java.util.regex.Pattern#DOTALL} mode,\n * allowing you to match against multiple lines.\n * @return The original string, the matched payload, an item of metadata, or\n * null (if none exists).\n */", "@", "Override", "public", "String", "resolve", "(", "String", "target", ",", "boolean", "dotAll", ")", "{", "if", "(", "target", "==", "null", ")", "{", "return", "null", ";", "}", "target", "=", "super", ".", "resolve", "(", "target", ",", "dotAll", ")", ";", "Pattern", "pattern", "=", "dotAll", "?", "normalPayloadResolver2", ":", "dotAllPayloadResolver2", ";", "target", "=", "resolve", "(", "target", ",", "pattern", ",", "false", ")", ";", "pattern", "=", "dotAll", "?", "normalPayloadResolver", ":", "dotAllPayloadResolver", ";", "return", "resolve", "(", "target", ",", "pattern", ",", "true", ")", ";", "}", "private", "String", "resolve", "(", "String", "target", ",", "Pattern", "pattern", ",", "boolean", "defaultPattern", ")", "{", "Matcher", "m", "=", "pattern", ".", "matcher", "(", "target", ")", ";", "while", "(", "m", ".", "matches", "(", ")", ")", "{", "String", "key", "=", "m", ".", "group", "(", "1", ")", ";", "if", "(", "!", "hasPayloadId", "(", "key", ")", ")", "{", "throw", "new", "UnresolvableException", "(", "\"", "Could not resolve payload ID [", "\"", "+", "key", "+", "\"", "]", "\"", ")", ";", "}", "target", "=", "target", ".", "replace", "(", "String", ".", "format", "(", "defaultPattern", "?", "\"", "%%payload_id{%s}", "\"", ":", "\"", "%%payload{id:%s}", "\"", ",", "key", ")", ",", "getContent", "(", "key", ")", ")", ";", "m", "=", "pattern", ".", "matcher", "(", "target", ")", ";", "}", "return", "target", ";", "}", "private", "class", "ByteFilterStream", "extends", "FilterOutputStream", "{", "private", "final", "String", "payloadId", ";", "ByteFilterStream", "(", "@", "NotNull", "String", "payloadId", ",", "ByteArrayOutputStream", "out", ")", "{", "super", "(", "out", ")", ";", "this", ".", "payloadId", "=", "payloadId", ";", "payloads", ".", "put", "(", "payloadId", ",", "new", "Payload", "(", "out", ")", ")", ";", "}", "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "super", ".", "close", "(", ")", ";", "addPayload", "(", "payloadId", ",", "(", "(", "ByteArrayOutputStream", ")", "super", ".", "out", ")", ".", "toByteArray", "(", ")", ")", ";", "}", "}", "private", "class", "Payload", "{", "String", "encoding", "=", "getFactory", "(", ")", ".", "getDefaultCharEncoding", "(", ")", ";", "private", "byte", "[", "]", "data", ";", "private", "ByteArrayOutputStream", "stream", ";", "Payload", "(", "String", "encoding", ",", "@", "NotNull", "byte", "[", "]", "data", ")", "{", "this", ".", "encoding", "=", "encoding", ";", "this", ".", "data", "=", "data", ";", "}", "Payload", "(", "@", "NotNull", "byte", "[", "]", "data", ")", "{", "this", ".", "data", "=", "data", ";", "}", "Payload", "(", "@", "NotNull", "ByteArrayOutputStream", "stream", ")", "{", "this", ".", "stream", "=", "stream", ";", "}", "byte", "[", "]", "payload", "(", ")", "{", "if", "(", "stream", "!=", "null", ")", "{", "return", "stream", ".", "toByteArray", "(", ")", ";", "}", "return", "data", ";", "}", "}", "}" ]
The standard implementation of multi-payload messages; {@link MultiPayloadAdaptrisMessage} implementation created by {@link MultiPayloadMessageFactory}.
[ "The", "standard", "implementation", "of", "multi", "-", "payload", "messages", ";", "{", "@link", "MultiPayloadAdaptrisMessage", "}", "implementation", "created", "by", "{", "@link", "MultiPayloadMessageFactory", "}", "." ]
[ "// clone the payloads.", "// resolve any %payload{id:...}'s or %payload_id{...}'s before attempting any %message{...}'s" ]
[ { "param": "AdaptrisMessageImp", "type": null }, { "param": "MultiPayloadAdaptrisMessage", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AdaptrisMessageImp", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "MultiPayloadAdaptrisMessage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7be4a339e57863b2915bf54efdaa2dacc3d6eecf
yahoo/metrics-api
src/main/java/com/yahoo/cloud/metrics/api/RequestMetric.java
[ "Apache-2.0" ]
Java
RequestMetric
/** * A metric created during a request. */
A metric created during a request.
[ "A", "metric", "created", "during", "a", "request", "." ]
public class RequestMetric { final long taskId; final Metric metric; RequestMetric(long taskId, Metric metric) { if(taskId < 0) { throw new IllegalArgumentException("invalid taskid: " + taskId); } this.taskId = taskId; this.metric = metric; } public long getTaskId() { return taskId; } public Metric getMetric() { return metric; } }
[ "public", "class", "RequestMetric", "{", "final", "long", "taskId", ";", "final", "Metric", "metric", ";", "RequestMetric", "(", "long", "taskId", ",", "Metric", "metric", ")", "{", "if", "(", "taskId", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "invalid taskid: ", "\"", "+", "taskId", ")", ";", "}", "this", ".", "taskId", "=", "taskId", ";", "this", ".", "metric", "=", "metric", ";", "}", "public", "long", "getTaskId", "(", ")", "{", "return", "taskId", ";", "}", "public", "Metric", "getMetric", "(", ")", "{", "return", "metric", ";", "}", "}" ]
A metric created during a request.
[ "A", "metric", "created", "during", "a", "request", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7be641cef4edf38ce25fa4019a541d9698c2bb93
phax/ph-oton
ph-oton-bootstrap4-pages/src/main/java/com/helger/photon/bootstrap4/pages/utils/BasePageUtilsBase64Decode.java
[ "Apache-2.0" ]
Java
BasePageUtilsBase64Decode
/** * Base64 decoder * * @author Philip Helger * @param <WPECTYPE> * Web Page Execution Context type * @since 8.3.2 */
Base64 decoder @author Philip Helger @param Web Page Execution Context type @since 8.3.2
[ "Base64", "decoder", "@author", "Philip", "Helger", "@param", "Web", "Page", "Execution", "Context", "type", "@since", "8", ".", "3", ".", "2" ]
public class BasePageUtilsBase64Decode <WPECTYPE extends IWebPageExecutionContext> extends AbstractBootstrapWebPage <WPECTYPE> { public static class Decoded extends AbstractSessionWebSingleton { private byte [] m_aData; private IMimeType m_aMimeType; @Deprecated @UsedViaReflection public Decoded () {} public static Decoded getInstance () { return getSessionSingleton (Decoded.class); } public void setData (@Nullable final byte [] aData, @Nullable final IMimeType aMimeType) { m_aData = aData; m_aMimeType = aMimeType; } public boolean hasData () { return m_aData != null && m_aMimeType != null; } } private static final String FIELD_CHARSET = "charset"; private static final String FIELD_DECODE = "decode"; private static final String FIELD_SHOW_AS_STRING = "showasstring"; private static final boolean DEFAULT_SHOW_AS_STRING = false; private static AjaxFunctionDeclaration AJAX_GET_DECODED; static { AJAX_GET_DECODED = addAjax ( (aRequestScope, aAjaxResponse) -> { final Decoded aDecoded = Decoded.getInstance (); if (aDecoded.hasData ()) { aAjaxResponse.setContent (aDecoded.m_aData); aAjaxResponse.setMimeType (aDecoded.m_aMimeType); aAjaxResponse.setContentDispositionType (EContentDispositionType.ATTACHMENT); aAjaxResponse.setContentDispositionFilename ("base64-decoded-file.dat"); aAjaxResponse.disableCaching (); } else aAjaxResponse.createBadRequest (); }); } public BasePageUtilsBase64Decode (@Nonnull @Nonempty final String sID) { super (sID, EWebPageText.PAGE_NAME_UTILS_BASE64_DECODE.getAsMLT ()); } public BasePageUtilsBase64Decode (@Nonnull @Nonempty final String sID, @Nonnull final String sName) { super (sID, sName); } public BasePageUtilsBase64Decode (@Nonnull @Nonempty final String sID, @Nonnull final String sName, @Nullable final String sDescription) { super (sID, sName, sDescription); } public BasePageUtilsBase64Decode (@Nonnull @Nonempty final String sID, @Nonnull final IMultilingualText aName, @Nullable final IMultilingualText aDescription) { super (sID, aName, aDescription); } @Override public void fillContent (@Nonnull final WPECTYPE aWPEC) { final Locale aDisplayLocale = aWPEC.getDisplayLocale (); final HCNodeList aNodeList = aWPEC.getNodeList (); final IRequestWebScopeWithoutResponse aRequestScope = aWPEC.getRequestScope (); final boolean bShowAsString = aWPEC.params ().isCheckBoxChecked (FIELD_SHOW_AS_STRING, DEFAULT_SHOW_AS_STRING); final FormErrorList aFormErrors = new FormErrorList (); if (aWPEC.params ().hasStringValue (CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM)) { final String sCharset = aWPEC.params ().getAsString (FIELD_CHARSET); final Charset aCharset = CharsetHelper.getCharsetFromNameOrNull (sCharset); final String sDecode = aWPEC.params ().getAsString (FIELD_DECODE); if (aCharset == null && bShowAsString) aFormErrors.addFieldError (FIELD_CHARSET, "To show result as String, a Charset must be selected!"); if (StringHelper.hasNoText (sDecode)) aFormErrors.addFieldError (FIELD_DECODE, "Please provide a String to decode!"); byte [] aDecoded = null; if (aFormErrors.isEmpty ()) { aDecoded = Base64.safeDecode (sDecode); if (aDecoded == null) aFormErrors.addFieldError (FIELD_DECODE, "The provided String to decode is not Base64 encoded!"); } if (aFormErrors.isEmpty ()) { aNodeList.addChild (success ("Content decoded from " + sDecode.length () + " characters to " + aDecoded.length + " bytes (=" + LocaleFormatter.getFormattedPercent ((double) aDecoded.length / sDecode.length (), 2, aDisplayLocale) + ")!" + (bShowAsString ? " Showing result in charset '" + aCharset.name () + "'" : ""))); if (bShowAsString) { // Show as string final String sDecoded = new String (aDecoded, aCharset); final HCTextArea aTextArea = new HCTextArea ().setReadOnly (true) .setValue (sDecoded) .addStyle (CCSSProperties.FONT_FAMILY.newValue (CCSSValue.MONOSPACE)); BootstrapFormHelper.markAsFormControl (aTextArea); aNodeList.addChild (aTextArea); } else { // Publish for download IMimeType aMimeType = MimeTypeDeterminator.getInstance ().getMimeTypeFromBytes (aDecoded, null); if (aMimeType == null) aMimeType = CMimeType.APPLICATION_OCTET_STREAM; // Remember in session Decoded.getInstance ().setData (aDecoded, aMimeType); // Print download link aNodeList.addChild (success (a (AJAX_GET_DECODED.getInvocationURL (aRequestScope)).addChild ("Download decoded result file"))); } } } if (aFormErrors.isNotEmpty ()) aNodeList.addChild (getUIHandler ().createIncorrectInputBox (aWPEC)); final BootstrapForm aForm = aNodeList.addAndReturnChild (getUIHandler ().createFormSelf (aWPEC)); aForm.setEncTypeFileUpload (); aForm.addChild (new HCHiddenField (CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM)); aForm.addFormGroup (new BootstrapFormGroup ().setLabelMandatory ("Content to decode") .setCtrl (new HCTextArea (new RequestField (FIELD_DECODE)).setRows (10) .addClass (CBootstrapCSS.TEXT_MONOSPACE) .setPlaceholder ("Text to be Base64 decoded")) .setErrorList (aFormErrors.getListOfField (FIELD_DECODE))); final HCCheckBox aShowAsString = new HCCheckBox (new RequestFieldBoolean (FIELD_SHOW_AS_STRING, DEFAULT_SHOW_AS_STRING)); aForm.addFormGroup (new BootstrapFormGroup ().setLabel ("Show result as String?") .setCtrl (aShowAsString) .setErrorList (aFormErrors.getListOfField (FIELD_SHOW_AS_STRING))); aForm.addFormGroup (new BootstrapFormGroup ().setLabel ("Charset") .setCtrl (new HCCharsetSelect (new RequestField (FIELD_CHARSET, StandardCharsets.UTF_8.name ()), true, aDisplayLocale)) .setErrorList (aFormErrors.getListOfField (FIELD_CHARSET))); final BootstrapRow aCharsetRow = (BootstrapRow) aForm.getLastChild (); if (!bShowAsString) aCharsetRow.addStyle (CCSSProperties.DISPLAY_NONE); aShowAsString.addEventHandler (EJSEvent.CLICK, JQuery.idRef (aCharsetRow).toggle ()); aForm.addChild (new BootstrapSubmitButton ().addChild ("Create Base64 decoded version").setIcon (EDefaultIcon.YES)); } }
[ "public", "class", "BasePageUtilsBase64Decode", "<", "WPECTYPE", "extends", "IWebPageExecutionContext", ">", "extends", "AbstractBootstrapWebPage", "<", "WPECTYPE", ">", "{", "public", "static", "class", "Decoded", "extends", "AbstractSessionWebSingleton", "{", "private", "byte", "[", "]", "m_aData", ";", "private", "IMimeType", "m_aMimeType", ";", "@", "Deprecated", "@", "UsedViaReflection", "public", "Decoded", "(", ")", "{", "}", "public", "static", "Decoded", "getInstance", "(", ")", "{", "return", "getSessionSingleton", "(", "Decoded", ".", "class", ")", ";", "}", "public", "void", "setData", "(", "@", "Nullable", "final", "byte", "[", "]", "aData", ",", "@", "Nullable", "final", "IMimeType", "aMimeType", ")", "{", "m_aData", "=", "aData", ";", "m_aMimeType", "=", "aMimeType", ";", "}", "public", "boolean", "hasData", "(", ")", "{", "return", "m_aData", "!=", "null", "&&", "m_aMimeType", "!=", "null", ";", "}", "}", "private", "static", "final", "String", "FIELD_CHARSET", "=", "\"", "charset", "\"", ";", "private", "static", "final", "String", "FIELD_DECODE", "=", "\"", "decode", "\"", ";", "private", "static", "final", "String", "FIELD_SHOW_AS_STRING", "=", "\"", "showasstring", "\"", ";", "private", "static", "final", "boolean", "DEFAULT_SHOW_AS_STRING", "=", "false", ";", "private", "static", "AjaxFunctionDeclaration", "AJAX_GET_DECODED", ";", "static", "{", "AJAX_GET_DECODED", "=", "addAjax", "(", "(", "aRequestScope", ",", "aAjaxResponse", ")", "->", "{", "final", "Decoded", "aDecoded", "=", "Decoded", ".", "getInstance", "(", ")", ";", "if", "(", "aDecoded", ".", "hasData", "(", ")", ")", "{", "aAjaxResponse", ".", "setContent", "(", "aDecoded", ".", "m_aData", ")", ";", "aAjaxResponse", ".", "setMimeType", "(", "aDecoded", ".", "m_aMimeType", ")", ";", "aAjaxResponse", ".", "setContentDispositionType", "(", "EContentDispositionType", ".", "ATTACHMENT", ")", ";", "aAjaxResponse", ".", "setContentDispositionFilename", "(", "\"", "base64-decoded-file.dat", "\"", ")", ";", "aAjaxResponse", ".", "disableCaching", "(", ")", ";", "}", "else", "aAjaxResponse", ".", "createBadRequest", "(", ")", ";", "}", ")", ";", "}", "public", "BasePageUtilsBase64Decode", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sID", ")", "{", "super", "(", "sID", ",", "EWebPageText", ".", "PAGE_NAME_UTILS_BASE64_DECODE", ".", "getAsMLT", "(", ")", ")", ";", "}", "public", "BasePageUtilsBase64Decode", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sID", ",", "@", "Nonnull", "final", "String", "sName", ")", "{", "super", "(", "sID", ",", "sName", ")", ";", "}", "public", "BasePageUtilsBase64Decode", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sID", ",", "@", "Nonnull", "final", "String", "sName", ",", "@", "Nullable", "final", "String", "sDescription", ")", "{", "super", "(", "sID", ",", "sName", ",", "sDescription", ")", ";", "}", "public", "BasePageUtilsBase64Decode", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sID", ",", "@", "Nonnull", "final", "IMultilingualText", "aName", ",", "@", "Nullable", "final", "IMultilingualText", "aDescription", ")", "{", "super", "(", "sID", ",", "aName", ",", "aDescription", ")", ";", "}", "@", "Override", "public", "void", "fillContent", "(", "@", "Nonnull", "final", "WPECTYPE", "aWPEC", ")", "{", "final", "Locale", "aDisplayLocale", "=", "aWPEC", ".", "getDisplayLocale", "(", ")", ";", "final", "HCNodeList", "aNodeList", "=", "aWPEC", ".", "getNodeList", "(", ")", ";", "final", "IRequestWebScopeWithoutResponse", "aRequestScope", "=", "aWPEC", ".", "getRequestScope", "(", ")", ";", "final", "boolean", "bShowAsString", "=", "aWPEC", ".", "params", "(", ")", ".", "isCheckBoxChecked", "(", "FIELD_SHOW_AS_STRING", ",", "DEFAULT_SHOW_AS_STRING", ")", ";", "final", "FormErrorList", "aFormErrors", "=", "new", "FormErrorList", "(", ")", ";", "if", "(", "aWPEC", ".", "params", "(", ")", ".", "hasStringValue", "(", "CPageParam", ".", "PARAM_ACTION", ",", "CPageParam", ".", "ACTION_PERFORM", ")", ")", "{", "final", "String", "sCharset", "=", "aWPEC", ".", "params", "(", ")", ".", "getAsString", "(", "FIELD_CHARSET", ")", ";", "final", "Charset", "aCharset", "=", "CharsetHelper", ".", "getCharsetFromNameOrNull", "(", "sCharset", ")", ";", "final", "String", "sDecode", "=", "aWPEC", ".", "params", "(", ")", ".", "getAsString", "(", "FIELD_DECODE", ")", ";", "if", "(", "aCharset", "==", "null", "&&", "bShowAsString", ")", "aFormErrors", ".", "addFieldError", "(", "FIELD_CHARSET", ",", "\"", "To show result as String, a Charset must be selected!", "\"", ")", ";", "if", "(", "StringHelper", ".", "hasNoText", "(", "sDecode", ")", ")", "aFormErrors", ".", "addFieldError", "(", "FIELD_DECODE", ",", "\"", "Please provide a String to decode!", "\"", ")", ";", "byte", "[", "]", "aDecoded", "=", "null", ";", "if", "(", "aFormErrors", ".", "isEmpty", "(", ")", ")", "{", "aDecoded", "=", "Base64", ".", "safeDecode", "(", "sDecode", ")", ";", "if", "(", "aDecoded", "==", "null", ")", "aFormErrors", ".", "addFieldError", "(", "FIELD_DECODE", ",", "\"", "The provided String to decode is not Base64 encoded!", "\"", ")", ";", "}", "if", "(", "aFormErrors", ".", "isEmpty", "(", ")", ")", "{", "aNodeList", ".", "addChild", "(", "success", "(", "\"", "Content decoded from ", "\"", "+", "sDecode", ".", "length", "(", ")", "+", "\"", " characters to ", "\"", "+", "aDecoded", ".", "length", "+", "\"", " bytes (=", "\"", "+", "LocaleFormatter", ".", "getFormattedPercent", "(", "(", "double", ")", "aDecoded", ".", "length", "/", "sDecode", ".", "length", "(", ")", ",", "2", ",", "aDisplayLocale", ")", "+", "\"", ")!", "\"", "+", "(", "bShowAsString", "?", "\"", " Showing result in charset '", "\"", "+", "aCharset", ".", "name", "(", ")", "+", "\"", "'", "\"", ":", "\"", "\"", ")", ")", ")", ";", "if", "(", "bShowAsString", ")", "{", "final", "String", "sDecoded", "=", "new", "String", "(", "aDecoded", ",", "aCharset", ")", ";", "final", "HCTextArea", "aTextArea", "=", "new", "HCTextArea", "(", ")", ".", "setReadOnly", "(", "true", ")", ".", "setValue", "(", "sDecoded", ")", ".", "addStyle", "(", "CCSSProperties", ".", "FONT_FAMILY", ".", "newValue", "(", "CCSSValue", ".", "MONOSPACE", ")", ")", ";", "BootstrapFormHelper", ".", "markAsFormControl", "(", "aTextArea", ")", ";", "aNodeList", ".", "addChild", "(", "aTextArea", ")", ";", "}", "else", "{", "IMimeType", "aMimeType", "=", "MimeTypeDeterminator", ".", "getInstance", "(", ")", ".", "getMimeTypeFromBytes", "(", "aDecoded", ",", "null", ")", ";", "if", "(", "aMimeType", "==", "null", ")", "aMimeType", "=", "CMimeType", ".", "APPLICATION_OCTET_STREAM", ";", "Decoded", ".", "getInstance", "(", ")", ".", "setData", "(", "aDecoded", ",", "aMimeType", ")", ";", "aNodeList", ".", "addChild", "(", "success", "(", "a", "(", "AJAX_GET_DECODED", ".", "getInvocationURL", "(", "aRequestScope", ")", ")", ".", "addChild", "(", "\"", "Download decoded result file", "\"", ")", ")", ")", ";", "}", "}", "}", "if", "(", "aFormErrors", ".", "isNotEmpty", "(", ")", ")", "aNodeList", ".", "addChild", "(", "getUIHandler", "(", ")", ".", "createIncorrectInputBox", "(", "aWPEC", ")", ")", ";", "final", "BootstrapForm", "aForm", "=", "aNodeList", ".", "addAndReturnChild", "(", "getUIHandler", "(", ")", ".", "createFormSelf", "(", "aWPEC", ")", ")", ";", "aForm", ".", "setEncTypeFileUpload", "(", ")", ";", "aForm", ".", "addChild", "(", "new", "HCHiddenField", "(", "CPageParam", ".", "PARAM_ACTION", ",", "CPageParam", ".", "ACTION_PERFORM", ")", ")", ";", "aForm", ".", "addFormGroup", "(", "new", "BootstrapFormGroup", "(", ")", ".", "setLabelMandatory", "(", "\"", "Content to decode", "\"", ")", ".", "setCtrl", "(", "new", "HCTextArea", "(", "new", "RequestField", "(", "FIELD_DECODE", ")", ")", ".", "setRows", "(", "10", ")", ".", "addClass", "(", "CBootstrapCSS", ".", "TEXT_MONOSPACE", ")", ".", "setPlaceholder", "(", "\"", "Text to be Base64 decoded", "\"", ")", ")", ".", "setErrorList", "(", "aFormErrors", ".", "getListOfField", "(", "FIELD_DECODE", ")", ")", ")", ";", "final", "HCCheckBox", "aShowAsString", "=", "new", "HCCheckBox", "(", "new", "RequestFieldBoolean", "(", "FIELD_SHOW_AS_STRING", ",", "DEFAULT_SHOW_AS_STRING", ")", ")", ";", "aForm", ".", "addFormGroup", "(", "new", "BootstrapFormGroup", "(", ")", ".", "setLabel", "(", "\"", "Show result as String?", "\"", ")", ".", "setCtrl", "(", "aShowAsString", ")", ".", "setErrorList", "(", "aFormErrors", ".", "getListOfField", "(", "FIELD_SHOW_AS_STRING", ")", ")", ")", ";", "aForm", ".", "addFormGroup", "(", "new", "BootstrapFormGroup", "(", ")", ".", "setLabel", "(", "\"", "Charset", "\"", ")", ".", "setCtrl", "(", "new", "HCCharsetSelect", "(", "new", "RequestField", "(", "FIELD_CHARSET", ",", "StandardCharsets", ".", "UTF_8", ".", "name", "(", ")", ")", ",", "true", ",", "aDisplayLocale", ")", ")", ".", "setErrorList", "(", "aFormErrors", ".", "getListOfField", "(", "FIELD_CHARSET", ")", ")", ")", ";", "final", "BootstrapRow", "aCharsetRow", "=", "(", "BootstrapRow", ")", "aForm", ".", "getLastChild", "(", ")", ";", "if", "(", "!", "bShowAsString", ")", "aCharsetRow", ".", "addStyle", "(", "CCSSProperties", ".", "DISPLAY_NONE", ")", ";", "aShowAsString", ".", "addEventHandler", "(", "EJSEvent", ".", "CLICK", ",", "JQuery", ".", "idRef", "(", "aCharsetRow", ")", ".", "toggle", "(", ")", ")", ";", "aForm", ".", "addChild", "(", "new", "BootstrapSubmitButton", "(", ")", ".", "addChild", "(", "\"", "Create Base64 decoded version", "\"", ")", ".", "setIcon", "(", "EDefaultIcon", ".", "YES", ")", ")", ";", "}", "}" ]
Base64 decoder @author Philip Helger @param <WPECTYPE> Web Page Execution Context type @since 8.3.2
[ "Base64", "decoder", "@author", "Philip", "Helger", "@param", "<WPECTYPE", ">", "Web", "Page", "Execution", "Context", "type", "@since", "8", ".", "3", ".", "2" ]
[ "// Show as string", "// Publish for download", "// Remember in session", "// Print download link" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7be89b1c5a6fa45aba166fbe787175f3b5a475f6
vimaier/conqat
org.conqat.engine.code_clones/src/org/conqat/engine/code_clones/index/CloneIndex.java
[ "Apache-2.0" ]
Java
CloneIndex
/** * An index used to store cloning information. This class supports both querying * the index and modifying it. * * @author $Author: hummelb $ * @version $Rev: 45617 $ * @ConQAT.Rating YELLOW Hash: AA34CAF83E5A5CB14891EBC6EC471492 */
An index used to store cloning information. This class supports both querying the index and modifying it.
[ "An", "index", "used", "to", "store", "cloning", "information", ".", "This", "class", "supports", "both", "querying", "the", "index", "and", "modifying", "it", "." ]
public class CloneIndex { /** The store used for the operations. */ private final ICloneIndexStore store; /** The options of the store. */ private final PersistedOptions options; /** The logger used. */ private final IConQATLogger logger; /** Milliseconds used for reading access to the store. */ private long readMilliSeconds = 0; /** Milliseconds used for processing of read data. */ private long readProcessMilliSeconds = 0; /** Milliseconds used for writing data into the store. */ private long writeMilliSeconds = 0; /** Milliseconds used for preparing the data for writing. */ private long writeProcessMilliSeconds = 0; /** Constructor. */ public CloneIndex(ICloneIndexStore store, IConQATLogger logger) { this.store = store; options = new PersistedOptions(store); this.logger = logger; } /** * Reports all ungapped clones for the given originId. * * @param onlyStartingHere * if this is true, only clone classes for which this origin * contributes the first clone instance are reported. If this is * false, all clone classes are reported. This should be set to * true when querying all origins consecutively to avoid * duplicate clone groups. * * @return true, if this originId is found in the database, false if the * originId could not be found (might also indicate origins without * units (ignored files)) */ public boolean reportClones(String originId, ICloneClassReporter reporter, boolean onlyStartingHere, int minLength) throws StorageException, ConQATException { return reportClones(originId, reporter, onlyStartingHere, minLength, false); } /** * Reports all clones for the given originId. * * @param onlyStartingHere * if this is true, only clone classes for which this origin * contributes the first clone instance are reported. If this is * false, all clone classes are reported. This should be set to * true when querying all origins consecutively to avoid * duplicate clone groups. * @param allowGaps * if this is true, the clone classes will also include clones * with gaps. Note that the algorithm used has slightly different * characteristics, hence you are not guaranteed to get all * ungapped clones as well (but most should be found). * * @return true, if this originId is found in the database, false if the * originId could not be found (might also indicate origins without * units (ignored files)) */ public boolean reportClones(String originId, ICloneClassReporter reporter, boolean onlyStartingHere, int minLength, boolean allowGaps) throws StorageException, ConQATException { long startTime = System.currentTimeMillis(); List<Chunk> chunks = store.getChunksByOrigin(originId); if (chunks == null) { return false; } List<ChunkList> orderedChunks = ChunkUtils.obtainOrderedChunks(store, chunks); readMilliSeconds += System.currentTimeMillis() - startTime; startTime = System.currentTimeMillis(); if (allowGaps) { new CloneIndexGappedCloneSearcher(originId, reporter, onlyStartingHere, minLength, orderedChunks, options.getChunkLength()).reportClones(); } else { new CloneIndexCloneSearcher(originId, reporter, onlyStartingHere, minLength, orderedChunks, options.getChunkLength()) .reportClones(); } readProcessMilliSeconds += System.currentTimeMillis() - startTime; return true; } /** * Advances the head index so far, that its entry in headList corresponds to * the given <code>tail</code> chunk (after correcting the unit index by the * given amount). This works, as we know that the list is sorted and * contains all chunks corresponding to the head list. * * @return the new head index. */ static int advanceHeadIndex(Chunk tail, List<Chunk> headList, int headIndex, int unitSkip) { while (true) { boolean indexMatches = tail.getFirstUnitIndex() == headList.get( headIndex).getFirstUnitIndex() + unitSkip; boolean originMatches = tail.getOriginId().equals( headList.get(headIndex).getOriginId()); if (indexMatches && originMatches) { return headIndex; } ++headIndex; } } /** Removes the given element from the underlying store. */ public void removeFile(ITextElement element) throws StorageException { store.removeChunks(element.getUniformPath()); } /** * Inserts a file into the index. * * @return the number of units processed. */ public int insertFile(ITokenElement element) throws ConQATException { IUnitProvider<ITextResource, Unit> normalizer = obtainNormalization(element .getLanguage()); long start = System.currentTimeMillis(); normalizer.init(element, logger); List<Unit> units = new ArrayList<Unit>(); Unit unit = null; int unitCount = 0; while ((unit = normalizer.getNext()) != null) { if (!unit.isSynthetic()) { unitCount += 1; } units.add(unit); } if (unitCount == 0) { return 0; } List<Chunk> chunks = ChunkUtils.calculateChunks(units, options.getChunkLength(), element, unitCount); writeProcessMilliSeconds += System.currentTimeMillis() - start; start = System.currentTimeMillis(); store.batchInsertChunks(chunks); writeMilliSeconds += System.currentTimeMillis() - start; return unitCount; } /** Returns the normalization to be used. */ private IUnitProvider<ITextResource, Unit> obtainNormalization( ELanguage language) throws StorageException { IUnitProvider<ITextResource, Unit> normalizer = options .getNormalization(language); if (normalizer == null) { throw new StorageException("No normalization for language " + language + " found!"); } return normalizer; } /** Returns a string which summarizes current performance characteristics. */ public String getPerformanceInfo() { return "read from store: " + readMilliSeconds / 1000. + " sec, read postprocessing: " + readProcessMilliSeconds / 1000. + " sec, write preprocessing: " + writeProcessMilliSeconds / 1000. + " sec, write to store: " + writeMilliSeconds / 1000. + " sec"; } }
[ "public", "class", "CloneIndex", "{", "/** The store used for the operations. */", "private", "final", "ICloneIndexStore", "store", ";", "/** The options of the store. */", "private", "final", "PersistedOptions", "options", ";", "/** The logger used. */", "private", "final", "IConQATLogger", "logger", ";", "/** Milliseconds used for reading access to the store. */", "private", "long", "readMilliSeconds", "=", "0", ";", "/** Milliseconds used for processing of read data. */", "private", "long", "readProcessMilliSeconds", "=", "0", ";", "/** Milliseconds used for writing data into the store. */", "private", "long", "writeMilliSeconds", "=", "0", ";", "/** Milliseconds used for preparing the data for writing. */", "private", "long", "writeProcessMilliSeconds", "=", "0", ";", "/** Constructor. */", "public", "CloneIndex", "(", "ICloneIndexStore", "store", ",", "IConQATLogger", "logger", ")", "{", "this", ".", "store", "=", "store", ";", "options", "=", "new", "PersistedOptions", "(", "store", ")", ";", "this", ".", "logger", "=", "logger", ";", "}", "/**\n\t * Reports all ungapped clones for the given originId.\n\t * \n\t * @param onlyStartingHere\n\t * if this is true, only clone classes for which this origin\n\t * contributes the first clone instance are reported. If this is\n\t * false, all clone classes are reported. This should be set to\n\t * true when querying all origins consecutively to avoid\n\t * duplicate clone groups.\n\t * \n\t * @return true, if this originId is found in the database, false if the\n\t * originId could not be found (might also indicate origins without\n\t * units (ignored files))\n\t */", "public", "boolean", "reportClones", "(", "String", "originId", ",", "ICloneClassReporter", "reporter", ",", "boolean", "onlyStartingHere", ",", "int", "minLength", ")", "throws", "StorageException", ",", "ConQATException", "{", "return", "reportClones", "(", "originId", ",", "reporter", ",", "onlyStartingHere", ",", "minLength", ",", "false", ")", ";", "}", "/**\n\t * Reports all clones for the given originId.\n\t * \n\t * @param onlyStartingHere\n\t * if this is true, only clone classes for which this origin\n\t * contributes the first clone instance are reported. If this is\n\t * false, all clone classes are reported. This should be set to\n\t * true when querying all origins consecutively to avoid\n\t * duplicate clone groups.\n\t * @param allowGaps\n\t * if this is true, the clone classes will also include clones\n\t * with gaps. Note that the algorithm used has slightly different\n\t * characteristics, hence you are not guaranteed to get all\n\t * ungapped clones as well (but most should be found).\n\t * \n\t * @return true, if this originId is found in the database, false if the\n\t * originId could not be found (might also indicate origins without\n\t * units (ignored files))\n\t */", "public", "boolean", "reportClones", "(", "String", "originId", ",", "ICloneClassReporter", "reporter", ",", "boolean", "onlyStartingHere", ",", "int", "minLength", ",", "boolean", "allowGaps", ")", "throws", "StorageException", ",", "ConQATException", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "List", "<", "Chunk", ">", "chunks", "=", "store", ".", "getChunksByOrigin", "(", "originId", ")", ";", "if", "(", "chunks", "==", "null", ")", "{", "return", "false", ";", "}", "List", "<", "ChunkList", ">", "orderedChunks", "=", "ChunkUtils", ".", "obtainOrderedChunks", "(", "store", ",", "chunks", ")", ";", "readMilliSeconds", "+=", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ";", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "allowGaps", ")", "{", "new", "CloneIndexGappedCloneSearcher", "(", "originId", ",", "reporter", ",", "onlyStartingHere", ",", "minLength", ",", "orderedChunks", ",", "options", ".", "getChunkLength", "(", ")", ")", ".", "reportClones", "(", ")", ";", "}", "else", "{", "new", "CloneIndexCloneSearcher", "(", "originId", ",", "reporter", ",", "onlyStartingHere", ",", "minLength", ",", "orderedChunks", ",", "options", ".", "getChunkLength", "(", ")", ")", ".", "reportClones", "(", ")", ";", "}", "readProcessMilliSeconds", "+=", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ";", "return", "true", ";", "}", "/**\n\t * Advances the head index so far, that its entry in headList corresponds to\n\t * the given <code>tail</code> chunk (after correcting the unit index by the\n\t * given amount). This works, as we know that the list is sorted and\n\t * contains all chunks corresponding to the head list.\n\t * \n\t * @return the new head index.\n\t */", "static", "int", "advanceHeadIndex", "(", "Chunk", "tail", ",", "List", "<", "Chunk", ">", "headList", ",", "int", "headIndex", ",", "int", "unitSkip", ")", "{", "while", "(", "true", ")", "{", "boolean", "indexMatches", "=", "tail", ".", "getFirstUnitIndex", "(", ")", "==", "headList", ".", "get", "(", "headIndex", ")", ".", "getFirstUnitIndex", "(", ")", "+", "unitSkip", ";", "boolean", "originMatches", "=", "tail", ".", "getOriginId", "(", ")", ".", "equals", "(", "headList", ".", "get", "(", "headIndex", ")", ".", "getOriginId", "(", ")", ")", ";", "if", "(", "indexMatches", "&&", "originMatches", ")", "{", "return", "headIndex", ";", "}", "++", "headIndex", ";", "}", "}", "/** Removes the given element from the underlying store. */", "public", "void", "removeFile", "(", "ITextElement", "element", ")", "throws", "StorageException", "{", "store", ".", "removeChunks", "(", "element", ".", "getUniformPath", "(", ")", ")", ";", "}", "/**\n\t * Inserts a file into the index.\n\t * \n\t * @return the number of units processed.\n\t */", "public", "int", "insertFile", "(", "ITokenElement", "element", ")", "throws", "ConQATException", "{", "IUnitProvider", "<", "ITextResource", ",", "Unit", ">", "normalizer", "=", "obtainNormalization", "(", "element", ".", "getLanguage", "(", ")", ")", ";", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "normalizer", ".", "init", "(", "element", ",", "logger", ")", ";", "List", "<", "Unit", ">", "units", "=", "new", "ArrayList", "<", "Unit", ">", "(", ")", ";", "Unit", "unit", "=", "null", ";", "int", "unitCount", "=", "0", ";", "while", "(", "(", "unit", "=", "normalizer", ".", "getNext", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "!", "unit", ".", "isSynthetic", "(", ")", ")", "{", "unitCount", "+=", "1", ";", "}", "units", ".", "add", "(", "unit", ")", ";", "}", "if", "(", "unitCount", "==", "0", ")", "{", "return", "0", ";", "}", "List", "<", "Chunk", ">", "chunks", "=", "ChunkUtils", ".", "calculateChunks", "(", "units", ",", "options", ".", "getChunkLength", "(", ")", ",", "element", ",", "unitCount", ")", ";", "writeProcessMilliSeconds", "+=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "store", ".", "batchInsertChunks", "(", "chunks", ")", ";", "writeMilliSeconds", "+=", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ";", "return", "unitCount", ";", "}", "/** Returns the normalization to be used. */", "private", "IUnitProvider", "<", "ITextResource", ",", "Unit", ">", "obtainNormalization", "(", "ELanguage", "language", ")", "throws", "StorageException", "{", "IUnitProvider", "<", "ITextResource", ",", "Unit", ">", "normalizer", "=", "options", ".", "getNormalization", "(", "language", ")", ";", "if", "(", "normalizer", "==", "null", ")", "{", "throw", "new", "StorageException", "(", "\"", "No normalization for language ", "\"", "+", "language", "+", "\"", " found!", "\"", ")", ";", "}", "return", "normalizer", ";", "}", "/** Returns a string which summarizes current performance characteristics. */", "public", "String", "getPerformanceInfo", "(", ")", "{", "return", "\"", "read from store: ", "\"", "+", "readMilliSeconds", "/", "1000.", "+", "\"", " sec, read postprocessing: ", "\"", "+", "readProcessMilliSeconds", "/", "1000.", "+", "\"", " sec, write preprocessing: ", "\"", "+", "writeProcessMilliSeconds", "/", "1000.", "+", "\"", " sec, write to store: ", "\"", "+", "writeMilliSeconds", "/", "1000.", "+", "\"", " sec", "\"", ";", "}", "}" ]
An index used to store cloning information.
[ "An", "index", "used", "to", "store", "cloning", "information", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7be9ed33fdb9182b3cc314b7ef6af7b04bb4f292
CoimLuo/incubator-shenyu
shenyu-common/src/main/java/org/apache/shenyu/common/dto/convert/selector/DubboSelectorHandle.java
[ "Apache-2.0" ]
Java
DubboSelectorHandle
/** * The type Dubbo selector handle. */
The type Dubbo selector handle.
[ "The", "type", "Dubbo", "selector", "handle", "." ]
public class DubboSelectorHandle { /** * zookeeper url is required. */ private String registry; /** * dubbo application name is required. */ private String appName; /** * dubbo protocol. */ private String protocol; /** * port. */ private int port; /** * upstreamUrl. */ private String upstreamUrl; /** * gray status. */ private Boolean gray; /** * group. */ private String group; /** * version. */ private String version; /** * weight. */ private int weight; /** * false close/ true open. */ private boolean status = true; /** * startup time. */ private long timestamp; /** * warmup. */ private int warmup; /** * get registry. * * @return registry */ public String getRegistry() { return registry; } /** * set registry. * * @param registry registry */ public void setRegistry(final String registry) { this.registry = registry; } /** * get appName. * * @return appName */ public String getAppName() { return appName; } /** * set appName. * * @param appName appName */ public void setAppName(final String appName) { this.appName = appName; } /** * get protocol. * * @return protocol */ public String getProtocol() { return protocol; } /** * set protocol. * * @param protocol protocol */ public void setProtocol(final String protocol) { this.protocol = protocol; } /** * get port. * * @return port */ public int getPort() { return port; } /** * set port. * * @param port port */ public void setPort(final int port) { this.port = port; } /** * Gets the value of gray. * * @return the value of gray */ public Boolean isGray() { return gray; } /** * Sets the gray. * * @param gray gray */ public void setGray(final Boolean gray) { this.gray = gray; } /** * Gets the value of upstreamUrl. * * @return the value of upstreamUrl */ public String getUpstreamUrl() { return upstreamUrl; } /** * Sets the upstreamUrl. * * @param upstreamUrl upstreamUrl */ public void setUpstreamUrl(final String upstreamUrl) { this.upstreamUrl = upstreamUrl; } /** * Gets the value of weight. * * @return the value of weight */ public int getWeight() { return weight; } /** * Sets the weight. * * @param weight weight */ public void setWeight(final int weight) { this.weight = weight; } /** * Gets the value of status. * * @return the value of status */ public boolean isStatus() { return status; } /** * Sets the status. * * @param status status */ public void setStatus(final boolean status) { this.status = status; } /** * Gets the value of timestamp. * * @return the value of timestamp */ public long getTimestamp() { return timestamp; } /** * Sets the timestamp. * * @param timestamp timestamp */ public void setTimestamp(final long timestamp) { this.timestamp = timestamp; } /** * Gets the value of warmup. * * @return the value of warmup */ public int getWarmup() { return warmup; } /** * Sets the warmup. * * @param warmup warmup */ public void setWarmup(final int warmup) { this.warmup = warmup; } /** * Gets the value of group. * * @return the value of group */ public String getGroup() { return group; } /** * Sets the group. * * @param group group */ public void setGroup(final String group) { this.group = group; } /** * Gets the value of version. * * @return the value of version */ public String getVersion() { return version; } /** * Sets the version. * * @param version version */ public void setVersion(final String version) { this.version = version; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof DubboSelectorHandle)) { return false; } DubboSelectorHandle that = (DubboSelectorHandle) o; return port == that.port && weight == that.weight && status == that.status && timestamp == that.timestamp && warmup == that.warmup && Objects.equals(registry, that.registry) && Objects.equals(appName, that.appName) && Objects.equals(protocol, that.protocol) && Objects.equals(upstreamUrl, that.upstreamUrl) && Objects.equals(gray, that.gray) && Objects.equals(group, that.group) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(registry, appName, protocol, port, upstreamUrl, gray, weight, status, timestamp, warmup, group, version); } @Override public String toString() { return "DubboSelectorHandle{" + "registry='" + registry + ", appName='" + appName + ", protocol='" + protocol + ", port=" + port + ", upstreamUrl='" + upstreamUrl + ", gray=" + gray + ", weight=" + weight + ", status=" + status + ", timestamp=" + timestamp + ", warmup=" + warmup + ", group='" + group + ", version='" + version + '}'; } }
[ "public", "class", "DubboSelectorHandle", "{", "/**\n * zookeeper url is required.\n */", "private", "String", "registry", ";", "/**\n * dubbo application name is required.\n */", "private", "String", "appName", ";", "/**\n * dubbo protocol.\n */", "private", "String", "protocol", ";", "/**\n * port.\n */", "private", "int", "port", ";", "/**\n * upstreamUrl.\n */", "private", "String", "upstreamUrl", ";", "/**\n * gray status.\n */", "private", "Boolean", "gray", ";", "/**\n * group.\n */", "private", "String", "group", ";", "/**\n * version.\n */", "private", "String", "version", ";", "/**\n * weight.\n */", "private", "int", "weight", ";", "/**\n * false close/ true open.\n */", "private", "boolean", "status", "=", "true", ";", "/**\n * startup time.\n */", "private", "long", "timestamp", ";", "/**\n * warmup.\n */", "private", "int", "warmup", ";", "/**\n * get registry.\n *\n * @return registry\n */", "public", "String", "getRegistry", "(", ")", "{", "return", "registry", ";", "}", "/**\n * set registry.\n *\n * @param registry registry\n */", "public", "void", "setRegistry", "(", "final", "String", "registry", ")", "{", "this", ".", "registry", "=", "registry", ";", "}", "/**\n * get appName.\n *\n * @return appName\n */", "public", "String", "getAppName", "(", ")", "{", "return", "appName", ";", "}", "/**\n * set appName.\n *\n * @param appName appName\n */", "public", "void", "setAppName", "(", "final", "String", "appName", ")", "{", "this", ".", "appName", "=", "appName", ";", "}", "/**\n * get protocol.\n *\n * @return protocol\n */", "public", "String", "getProtocol", "(", ")", "{", "return", "protocol", ";", "}", "/**\n * set protocol.\n *\n * @param protocol protocol\n */", "public", "void", "setProtocol", "(", "final", "String", "protocol", ")", "{", "this", ".", "protocol", "=", "protocol", ";", "}", "/**\n * get port.\n *\n * @return port\n */", "public", "int", "getPort", "(", ")", "{", "return", "port", ";", "}", "/**\n * set port.\n *\n * @param port port\n */", "public", "void", "setPort", "(", "final", "int", "port", ")", "{", "this", ".", "port", "=", "port", ";", "}", "/**\n * Gets the value of gray.\n *\n * @return the value of gray\n */", "public", "Boolean", "isGray", "(", ")", "{", "return", "gray", ";", "}", "/**\n * Sets the gray.\n *\n * @param gray gray\n */", "public", "void", "setGray", "(", "final", "Boolean", "gray", ")", "{", "this", ".", "gray", "=", "gray", ";", "}", "/**\n * Gets the value of upstreamUrl.\n *\n * @return the value of upstreamUrl\n */", "public", "String", "getUpstreamUrl", "(", ")", "{", "return", "upstreamUrl", ";", "}", "/**\n * Sets the upstreamUrl.\n *\n * @param upstreamUrl upstreamUrl\n */", "public", "void", "setUpstreamUrl", "(", "final", "String", "upstreamUrl", ")", "{", "this", ".", "upstreamUrl", "=", "upstreamUrl", ";", "}", "/**\n * Gets the value of weight.\n *\n * @return the value of weight\n */", "public", "int", "getWeight", "(", ")", "{", "return", "weight", ";", "}", "/**\n * Sets the weight.\n *\n * @param weight weight\n */", "public", "void", "setWeight", "(", "final", "int", "weight", ")", "{", "this", ".", "weight", "=", "weight", ";", "}", "/**\n * Gets the value of status.\n *\n * @return the value of status\n */", "public", "boolean", "isStatus", "(", ")", "{", "return", "status", ";", "}", "/**\n * Sets the status.\n *\n * @param status status\n */", "public", "void", "setStatus", "(", "final", "boolean", "status", ")", "{", "this", ".", "status", "=", "status", ";", "}", "/**\n * Gets the value of timestamp.\n *\n * @return the value of timestamp\n */", "public", "long", "getTimestamp", "(", ")", "{", "return", "timestamp", ";", "}", "/**\n * Sets the timestamp.\n *\n * @param timestamp timestamp\n */", "public", "void", "setTimestamp", "(", "final", "long", "timestamp", ")", "{", "this", ".", "timestamp", "=", "timestamp", ";", "}", "/**\n * Gets the value of warmup.\n *\n * @return the value of warmup\n */", "public", "int", "getWarmup", "(", ")", "{", "return", "warmup", ";", "}", "/**\n * Sets the warmup.\n *\n * @param warmup warmup\n */", "public", "void", "setWarmup", "(", "final", "int", "warmup", ")", "{", "this", ".", "warmup", "=", "warmup", ";", "}", "/**\n * Gets the value of group.\n *\n * @return the value of group\n */", "public", "String", "getGroup", "(", ")", "{", "return", "group", ";", "}", "/**\n * Sets the group.\n *\n * @param group group\n */", "public", "void", "setGroup", "(", "final", "String", "group", ")", "{", "this", ".", "group", "=", "group", ";", "}", "/**\n * Gets the value of version.\n *\n * @return the value of version\n */", "public", "String", "getVersion", "(", ")", "{", "return", "version", ";", "}", "/**\n * Sets the version.\n *\n * @param version version\n */", "public", "void", "setVersion", "(", "final", "String", "version", ")", "{", "this", ".", "version", "=", "version", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "final", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "!", "(", "o", "instanceof", "DubboSelectorHandle", ")", ")", "{", "return", "false", ";", "}", "DubboSelectorHandle", "that", "=", "(", "DubboSelectorHandle", ")", "o", ";", "return", "port", "==", "that", ".", "port", "&&", "weight", "==", "that", ".", "weight", "&&", "status", "==", "that", ".", "status", "&&", "timestamp", "==", "that", ".", "timestamp", "&&", "warmup", "==", "that", ".", "warmup", "&&", "Objects", ".", "equals", "(", "registry", ",", "that", ".", "registry", ")", "&&", "Objects", ".", "equals", "(", "appName", ",", "that", ".", "appName", ")", "&&", "Objects", ".", "equals", "(", "protocol", ",", "that", ".", "protocol", ")", "&&", "Objects", ".", "equals", "(", "upstreamUrl", ",", "that", ".", "upstreamUrl", ")", "&&", "Objects", ".", "equals", "(", "gray", ",", "that", ".", "gray", ")", "&&", "Objects", ".", "equals", "(", "group", ",", "that", ".", "group", ")", "&&", "Objects", ".", "equals", "(", "version", ",", "that", ".", "version", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "registry", ",", "appName", ",", "protocol", ",", "port", ",", "upstreamUrl", ",", "gray", ",", "weight", ",", "status", ",", "timestamp", ",", "warmup", ",", "group", ",", "version", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "DubboSelectorHandle{", "\"", "+", "\"", "registry='", "\"", "+", "registry", "+", "\"", ", appName='", "\"", "+", "appName", "+", "\"", ", protocol='", "\"", "+", "protocol", "+", "\"", ", port=", "\"", "+", "port", "+", "\"", ", upstreamUrl='", "\"", "+", "upstreamUrl", "+", "\"", ", gray=", "\"", "+", "gray", "+", "\"", ", weight=", "\"", "+", "weight", "+", "\"", ", status=", "\"", "+", "status", "+", "\"", ", timestamp=", "\"", "+", "timestamp", "+", "\"", ", warmup=", "\"", "+", "warmup", "+", "\"", ", group='", "\"", "+", "group", "+", "\"", ", version='", "\"", "+", "version", "+", "'}'", ";", "}", "}" ]
The type Dubbo selector handle.
[ "The", "type", "Dubbo", "selector", "handle", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bf0ef77896e3c7fc77eba6ae40cc6cdd840d733
wizzardo/tools
modules/tools-reflection/src/main/java/com/wizzardo/tools/reflection/GenericMethod.java
[ "MIT" ]
Java
GenericMethod
/** * Created by wizzardo on 14/03/17. */
Created by wizzardo on 14/03/17.
[ "Created", "by", "wizzardo", "on", "14", "/", "03", "/", "17", "." ]
public class GenericMethod { public final Method method; public final Generic returnType; public final List<Generic> args; public GenericMethod(Method method, Generic returnType, List<Generic> args) { this.method = method; this.returnType = returnType; this.args = args; } @Override public String toString() { return join(new StringBuilder(32) .append(returnType) .append(' ') .append(method.getName()) .append('(') , args, ",") .append(')') .toString(); } }
[ "public", "class", "GenericMethod", "{", "public", "final", "Method", "method", ";", "public", "final", "Generic", "returnType", ";", "public", "final", "List", "<", "Generic", ">", "args", ";", "public", "GenericMethod", "(", "Method", "method", ",", "Generic", "returnType", ",", "List", "<", "Generic", ">", "args", ")", "{", "this", ".", "method", "=", "method", ";", "this", ".", "returnType", "=", "returnType", ";", "this", ".", "args", "=", "args", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "join", "(", "new", "StringBuilder", "(", "32", ")", ".", "append", "(", "returnType", ")", ".", "append", "(", "' '", ")", ".", "append", "(", "method", ".", "getName", "(", ")", ")", ".", "append", "(", "'('", ")", ",", "args", ",", "\"", ",", "\"", ")", ".", "append", "(", "')'", ")", ".", "toString", "(", ")", ";", "}", "}" ]
Created by wizzardo on 14/03/17.
[ "Created", "by", "wizzardo", "on", "14", "/", "03", "/", "17", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bf24008703e165cd415895acbca26c080edcfa4
greyhawk/learning-akka
hello-world/src/main/java/com/example/actors/SupervisingActor.java
[ "MIT" ]
Java
SupervisingActor
/** * SupervisingActor * @author ging wu * @date 2018/12/11 */
SupervisingActor @author ging wu @date 2018/12/11
[ "SupervisingActor", "@author", "ging", "wu", "@date", "2018", "/", "12", "/", "11" ]
public class SupervisingActor extends AbstractActor { public static Props props() { return Props.create(SupervisingActor.class, SupervisingActor::new); } ActorRef child = getContext().actorOf(SupervisedActor.props(), "supervised-actor"); @Override public Receive createReceive() { return receiveBuilder() .matchEquals("failChild", f -> { child.tell("fail", getSelf()); }).build(); } }
[ "public", "class", "SupervisingActor", "extends", "AbstractActor", "{", "public", "static", "Props", "props", "(", ")", "{", "return", "Props", ".", "create", "(", "SupervisingActor", ".", "class", ",", "SupervisingActor", "::", "new", ")", ";", "}", "ActorRef", "child", "=", "getContext", "(", ")", ".", "actorOf", "(", "SupervisedActor", ".", "props", "(", ")", ",", "\"", "supervised-actor", "\"", ")", ";", "@", "Override", "public", "Receive", "createReceive", "(", ")", "{", "return", "receiveBuilder", "(", ")", ".", "matchEquals", "(", "\"", "failChild", "\"", ",", "f", "->", "{", "child", ".", "tell", "(", "\"", "fail", "\"", ",", "getSelf", "(", ")", ")", ";", "}", ")", ".", "build", "(", ")", ";", "}", "}" ]
SupervisingActor @author ging wu @date 2018/12/11
[ "SupervisingActor", "@author", "ging", "wu", "@date", "2018", "/", "12", "/", "11" ]
[]
[ { "param": "AbstractActor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractActor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bf3c32c93d779e40dafeed7cc0cdcd5d1795b7f
apache/tuscany-sca-2.x
modules/contribution/src/main/java/org/apache/tuscany/sca/contribution/namespace/impl/NamespaceExportModelResolver.java
[ "Apache-2.0" ]
Java
NamespaceExportModelResolver
/** * A model resolver for namespace exports. * * @version $Rev$ $Date$ */
A model resolver for namespace exports. @version $Rev$ $Date$
[ "A", "model", "resolver", "for", "namespace", "exports", ".", "@version", "$Rev$", "$Date$" ]
public class NamespaceExportModelResolver implements ModelResolver { private ModelResolver resolver; public NamespaceExportModelResolver(ModelResolver resolver) { this.resolver = resolver; } public void addModel(Object resolved, ProcessorContext context) { throw new IllegalStateException(); } public Object removeModel(Object resolved, ProcessorContext context) { throw new IllegalStateException(); } public <T> T resolveModel(Class<T> modelClass, T unresolved, ProcessorContext context) { // Just delegate to the contribution's model resolver, namespace // based filtering is implemented in the model specific model // resolver, which know how to get the namespace of the particular // type of model that they handle return resolver.resolveModel(modelClass, unresolved, context); } }
[ "public", "class", "NamespaceExportModelResolver", "implements", "ModelResolver", "{", "private", "ModelResolver", "resolver", ";", "public", "NamespaceExportModelResolver", "(", "ModelResolver", "resolver", ")", "{", "this", ".", "resolver", "=", "resolver", ";", "}", "public", "void", "addModel", "(", "Object", "resolved", ",", "ProcessorContext", "context", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "public", "Object", "removeModel", "(", "Object", "resolved", ",", "ProcessorContext", "context", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "public", "<", "T", ">", "T", "resolveModel", "(", "Class", "<", "T", ">", "modelClass", ",", "T", "unresolved", ",", "ProcessorContext", "context", ")", "{", "return", "resolver", ".", "resolveModel", "(", "modelClass", ",", "unresolved", ",", "context", ")", ";", "}", "}" ]
A model resolver for namespace exports.
[ "A", "model", "resolver", "for", "namespace", "exports", "." ]
[ "// Just delegate to the contribution's model resolver, namespace", "// based filtering is implemented in the model specific model", "// resolver, which know how to get the namespace of the particular", "// type of model that they handle " ]
[ { "param": "ModelResolver", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ModelResolver", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bf5abf83c6070551d26f066bf698d446a254705
Colbys/smartactors-core
CoreFeatures/Endpoint/IEnvironmentHandler/src/main/java/info/smart_tools/smartactors/endpoint/interfaces/ienvironment_handler/exception/EnvironmentHandleException.java
[ "Apache-2.0" ]
Java
EnvironmentHandleException
/** * Exception for error in {@link IEnvironmentHandler} method */
Exception for error in IEnvironmentHandler method
[ "Exception", "for", "error", "in", "IEnvironmentHandler", "method" ]
public class EnvironmentHandleException extends Exception { /** * Constructor with specific error message as argument * @param message specific error message */ public EnvironmentHandleException(final String message) { super(message); } /** * Constructor with specific error message and specific cause as arguments * @param message specific error message * @param cause specific cause */ public EnvironmentHandleException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor with specific cause as argument * @param cause specific cause */ public EnvironmentHandleException(final Throwable cause) { super(cause); } }
[ "public", "class", "EnvironmentHandleException", "extends", "Exception", "{", "/**\n * Constructor with specific error message as argument\n * @param message specific error message\n */", "public", "EnvironmentHandleException", "(", "final", "String", "message", ")", "{", "super", "(", "message", ")", ";", "}", "/**\n * Constructor with specific error message and specific cause as arguments\n * @param message specific error message\n * @param cause specific cause\n */", "public", "EnvironmentHandleException", "(", "final", "String", "message", ",", "final", "Throwable", "cause", ")", "{", "super", "(", "message", ",", "cause", ")", ";", "}", "/**\n * Constructor with specific cause as argument\n * @param cause specific cause\n */", "public", "EnvironmentHandleException", "(", "final", "Throwable", "cause", ")", "{", "super", "(", "cause", ")", ";", "}", "}" ]
Exception for error in {@link IEnvironmentHandler} method
[ "Exception", "for", "error", "in", "{", "@link", "IEnvironmentHandler", "}", "method" ]
[]
[ { "param": "Exception", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Exception", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bfc8a3c90a5d053c8a72590e277f75512d5803d
yoyooli8/jackrabbit-oak
oak-it/mk/src/main/java/org/apache/jackrabbit/mk/test/AbstractMicroKernelIT.java
[ "Apache-2.0" ]
Java
AbstractMicroKernelIT
/** * Abstract base class for {@link MicroKernel} integration tests. */
Abstract base class for MicroKernel integration tests.
[ "Abstract", "base", "class", "for", "MicroKernel", "integration", "tests", "." ]
public abstract class AbstractMicroKernelIT { /** * Finds and returns all {@link MicroKernelFixture} services available * in the current classpath. * * @return available {@link MicroKernelFixture} services */ @Parameters public static Collection<Object[]> loadFixtures() { Collection<Object[]> fixtures = new ArrayList<Object[]>(); Class<MicroKernelFixture> iface = MicroKernelFixture.class; ServiceLoader<MicroKernelFixture> loader = ServiceLoader.load(iface, iface.getClassLoader()); for (MicroKernelFixture fixture : loader) { if (fixture.isAvailable()) { fixtures.add(new Object[] { fixture }); } } return fixtures; } /** * The {@link MicroKernelFixture} service used by this test case instance. */ protected final MicroKernelFixture fixture; /** * The {@link MicroKernel} cluster node instances used by this test case. */ protected final MicroKernel[] mks; /** * The {@link MicroKernel} instance used by this test case. * In a clustered setup this is the first node of the cluster. */ protected MicroKernel mk; /** * A JSON parser instance that can be used for parsing JSON-format data; * {@code JSONParser} instances are not <i>not</i> thread-safe. * @see #getJSONParser() */ private JSONParser parser; /** * Creates a {@link MicroKernel} test case for a cluster of the given * size created using the given {@link MicroKernelFixture} service. * * @param fixture {@link MicroKernelFixture} service * @param nodeCount number of nodes that the test cluster should contain */ protected AbstractMicroKernelIT(MicroKernelFixture fixture, int nodeCount) { checkArgument(nodeCount > 0); this.fixture = fixture; this.mks = new MicroKernel[nodeCount]; } /** * Prepares the test case by initializing the {@link #mks} and * {@link #mk} variables with a new {@link MicroKernel} cluster * from the {@link MicroKernelFixture} service associated with * this test case. */ @Before public void setUp() throws Exception { fixture.setUpCluster(mks); mk = mks[0]; addInitialTestContent(); } /** * Adds initial content used by the test case. This method is * called by the {@link #setUp()} method after the {@link MicroKernel} * cluster has been set up and before the actual test is run. * The default implementation does nothing, but subclasses can * override this method to perform extra initialization. */ protected void addInitialTestContent() { } /** * Releases the {@link MicroKernel} cluster used by this test case. */ @After public void tearDown() { fixture.tearDownCluster(mks); // Clear fields to avoid consuming memory after the test has run. // It looks like JUnit keeps references to all test instances until // the entire test suite has been run. Arrays.fill(mks, null); mk = null; parser = null; } //--------------------------------< utility methods for parsing json data > /** * Returns a {@code JSONParser} instance for parsing JSON format data. * This method returns a cached instance. * <p/> * {@code JSONParser} instances are <i>not</i> thread-safe. Multi-threaded * unit tests should therefore override this method and return a fresh * instance on every invocation. * * @return a {@code JSONParser} instance */ protected synchronized JSONParser getJSONParser() { if (parser == null) { parser = new JSONParser(); } return parser; } /** * Parses the provided string into a {@code JSONObject}. * * @param json string to be parsed * @return a {@code JSONObject} * @throws {@code AssertionError} if the string cannot be parsed into a {@code JSONObject} */ protected JSONObject parseJSONObject(String json) throws AssertionError { JSONParser parser = getJSONParser(); try { Object obj = parser.parse(json); assertTrue(obj instanceof JSONObject); return (JSONObject) obj; } catch (Exception e) { throw new AssertionError("not a valid JSON object: " + e.getMessage()); } } /** * Parses the provided string into a {@code JSONArray}. * * @param json string to be parsed * @return a {@code JSONArray} * @throws {@code AssertionError} if the string cannot be parsed into a {@code JSONArray} */ protected JSONArray parseJSONArray(String json) throws AssertionError { JSONParser parser = getJSONParser(); try { Object obj = parser.parse(json); assertTrue(obj instanceof JSONArray); return (JSONArray) obj; } catch (Exception e) { throw new AssertionError("not a valid JSON array: " + e.getMessage()); } } protected Set<String> getNodeNames(JSONObject obj) { Set<String> names = new HashSet<String>(); Set<Map.Entry> entries = obj.entrySet(); for (Map.Entry entry : entries) { if (entry.getValue() instanceof JSONObject) { names.add((String) entry.getKey()); } } return names; } protected Set<String> getPropertyNames(JSONObject obj) { Set<String> names = new HashSet<String>(); Set<Map.Entry> entries = obj.entrySet(); for (Map.Entry entry : entries) { if (! (entry.getValue() instanceof JSONObject)) { names.add((String) entry.getKey()); } } return names; } protected void assertPropertyExists(JSONObject obj, String relPath) throws AssertionError { Object val = resolveValue(obj, relPath); assertNotNull("not found: " + relPath, val); } protected void assertPropertyNotExists(JSONObject obj, String relPath) throws AssertionError { Object val = resolveValue(obj, relPath); assertNull(val); } protected void assertPropertyExists(JSONObject obj, String relPath, Class type) throws AssertionError { Object val = resolveValue(obj, relPath); assertNotNull("not found: " + relPath, val); assertTrue(type.isInstance(val)); } protected void assertPropertyValue(JSONObject obj, String relPath, Double expected) throws AssertionError { Object val = resolveValue(obj, relPath); assertNotNull("not found: " + relPath, val); assertEquals(expected, val); } protected void assertPropertyValue(JSONObject obj, String relPath, Long expected) throws AssertionError { Object val = resolveValue(obj, relPath); assertNotNull("not found: " + relPath, val); assertEquals(expected, val); } protected void assertPropertyValue(JSONObject obj, String relPath, Boolean expected) throws AssertionError { Object val = resolveValue(obj, relPath); assertNotNull("not found: " + relPath, val); assertEquals(expected, val); } protected void assertPropertyValue(JSONObject obj, String relPath, String expected) throws AssertionError { Object val = resolveValue(obj, relPath); assertNotNull("not found: " + relPath, val); assertEquals(expected, val); } protected void assertPropertyValue(JSONObject obj, String relPath, Object[] expected) throws AssertionError { JSONArray array = resolveArrayValue(obj, relPath); assertNotNull("not found: " + relPath, array); assertEquals(expected.length, array.size()); // JSON numeric types: Double, Long // convert types as necessary for comparison using equals method for (int i = 0; i < array.size(); i++) { Object o1 = expected[i]; Object o2 = array.get(i); if (o1 instanceof Number && o2 instanceof Number) { if (o1 instanceof Integer) { o1 = new Long((Integer) o1); } else if (o1 instanceof Short) { o1 = new Long((Short) o1); } else if (o1 instanceof Float) { o1 = new Double((Float) o1); } } assertEquals(o1, o2); } } protected JSONObject resolveObjectValue(JSONObject obj, String relPath) { Object val = resolveValue(obj, relPath); if (val instanceof JSONObject) { return (JSONObject) val; } throw new AssertionError("failed to resolve JSONObject value at " + relPath + ": " + val); } protected JSONObject getObjectArrayEntry(JSONArray array, int pos) { assertTrue(pos >= 0 && pos < array.size()); Object entry = array.get(pos); if (entry instanceof JSONObject) { return (JSONObject) entry; } throw new AssertionError("failed to resolve JSONObject array entry at pos " + pos + ": " + entry); } protected JSONArray resolveArrayValue(JSONObject obj, String relPath) { Object val = resolveValue(obj, relPath); if (val instanceof JSONArray) { return (JSONArray) val; } throw new AssertionError("failed to resolve JSONArray value at " + relPath + ": " + val); } protected Object resolveValue(JSONObject obj, String relPath) { String names[] = relPath.split("/"); Object val = obj; for (String name : names) { if (! (val instanceof JSONObject)) { throw new AssertionError("not found: " + relPath); } val = ((JSONObject) val).get(name); } return val; } protected void assertPropExists(String rev, String path, String property) { String nodes = mk.getNodes(path, rev, -1 /*depth*/, 0 /*offset*/, -1 /*maxChildNodes*/, null /*filter*/); JSONObject obj = parseJSONObject(nodes); assertPropertyExists(obj, property); } protected void assertPropNotExists(String rev, String path, String property) { String nodes = mk.getNodes(path, rev, -1 /*depth*/, 0 /*offset*/, -1 /*maxChildNodes*/, null /*filter*/); if (nodes == null) { return; } JSONObject obj = parseJSONObject(nodes); assertPropertyNotExists(obj, property); } protected void assertPropValue(String rev, String path, String property, String value) { String nodes = mk.getNodes(path, rev, -1 /*depth*/, 0 /*offset*/, -1 /*maxChildNodes*/, null /*filter*/); JSONObject obj = parseJSONObject(nodes); assertPropertyValue(obj, property, value); } protected String addNodes(String rev, String...nodes) { String newRev = rev; for (String node : nodes) { newRev = mk.commit("", "+\"" + node + "\":{}", newRev, ""); } return newRev; } protected String removeNodes(String rev, String...nodes) { String newRev = rev; for (String node : nodes) { newRev = mk.commit("", "-\"" + node + "\"", newRev, ""); } return newRev; } protected String setProp(String rev, String prop, Object value) { value = value == null? null : "\"" + value + "\""; return mk.commit("", "^\"" + prop + "\" : " + value, rev, ""); } protected void assertNodesExist(String revision, String...paths) { doAssertNodes(true, revision, paths); } protected void assertNodesNotExist(String revision, String...paths) { doAssertNodes(false, revision, paths); } protected void doAssertNodes(boolean checkExists, String revision, String...paths) { for (String path : paths) { boolean exists = mk.nodeExists(path, revision); if (checkExists) { assertTrue(path + " does not exist", exists); } else { assertFalse(path + " should not exist", exists); } } } }
[ "public", "abstract", "class", "AbstractMicroKernelIT", "{", "/**\n * Finds and returns all {@link MicroKernelFixture} services available\n * in the current classpath.\n *\n * @return available {@link MicroKernelFixture} services\n */", "@", "Parameters", "public", "static", "Collection", "<", "Object", "[", "]", ">", "loadFixtures", "(", ")", "{", "Collection", "<", "Object", "[", "]", ">", "fixtures", "=", "new", "ArrayList", "<", "Object", "[", "]", ">", "(", ")", ";", "Class", "<", "MicroKernelFixture", ">", "iface", "=", "MicroKernelFixture", ".", "class", ";", "ServiceLoader", "<", "MicroKernelFixture", ">", "loader", "=", "ServiceLoader", ".", "load", "(", "iface", ",", "iface", ".", "getClassLoader", "(", ")", ")", ";", "for", "(", "MicroKernelFixture", "fixture", ":", "loader", ")", "{", "if", "(", "fixture", ".", "isAvailable", "(", ")", ")", "{", "fixtures", ".", "add", "(", "new", "Object", "[", "]", "{", "fixture", "}", ")", ";", "}", "}", "return", "fixtures", ";", "}", "/**\n * The {@link MicroKernelFixture} service used by this test case instance.\n */", "protected", "final", "MicroKernelFixture", "fixture", ";", "/**\n * The {@link MicroKernel} cluster node instances used by this test case.\n */", "protected", "final", "MicroKernel", "[", "]", "mks", ";", "/**\n * The {@link MicroKernel} instance used by this test case.\n * In a clustered setup this is the first node of the cluster.\n */", "protected", "MicroKernel", "mk", ";", "/**\n * A JSON parser instance that can be used for parsing JSON-format data;\n * {@code JSONParser} instances are not <i>not</i> thread-safe.\n * @see #getJSONParser()\n */", "private", "JSONParser", "parser", ";", "/**\n * Creates a {@link MicroKernel} test case for a cluster of the given\n * size created using the given {@link MicroKernelFixture} service.\n *\n * @param fixture {@link MicroKernelFixture} service\n * @param nodeCount number of nodes that the test cluster should contain\n */", "protected", "AbstractMicroKernelIT", "(", "MicroKernelFixture", "fixture", ",", "int", "nodeCount", ")", "{", "checkArgument", "(", "nodeCount", ">", "0", ")", ";", "this", ".", "fixture", "=", "fixture", ";", "this", ".", "mks", "=", "new", "MicroKernel", "[", "nodeCount", "]", ";", "}", "/**\n * Prepares the test case by initializing the {@link #mks} and\n * {@link #mk} variables with a new {@link MicroKernel} cluster\n * from the {@link MicroKernelFixture} service associated with\n * this test case.\n */", "@", "Before", "public", "void", "setUp", "(", ")", "throws", "Exception", "{", "fixture", ".", "setUpCluster", "(", "mks", ")", ";", "mk", "=", "mks", "[", "0", "]", ";", "addInitialTestContent", "(", ")", ";", "}", "/**\n * Adds initial content used by the test case. This method is\n * called by the {@link #setUp()} method after the {@link MicroKernel}\n * cluster has been set up and before the actual test is run.\n * The default implementation does nothing, but subclasses can\n * override this method to perform extra initialization.\n */", "protected", "void", "addInitialTestContent", "(", ")", "{", "}", "/**\n * Releases the {@link MicroKernel} cluster used by this test case.\n */", "@", "After", "public", "void", "tearDown", "(", ")", "{", "fixture", ".", "tearDownCluster", "(", "mks", ")", ";", "Arrays", ".", "fill", "(", "mks", ",", "null", ")", ";", "mk", "=", "null", ";", "parser", "=", "null", ";", "}", "/**\n * Returns a {@code JSONParser} instance for parsing JSON format data.\n * This method returns a cached instance.\n * <p/>\n * {@code JSONParser} instances are <i>not</i> thread-safe. Multi-threaded\n * unit tests should therefore override this method and return a fresh\n * instance on every invocation.\n *\n * @return a {@code JSONParser} instance\n */", "protected", "synchronized", "JSONParser", "getJSONParser", "(", ")", "{", "if", "(", "parser", "==", "null", ")", "{", "parser", "=", "new", "JSONParser", "(", ")", ";", "}", "return", "parser", ";", "}", "/**\n * Parses the provided string into a {@code JSONObject}.\n *\n * @param json string to be parsed\n * @return a {@code JSONObject}\n * @throws {@code AssertionError} if the string cannot be parsed into a {@code JSONObject}\n */", "protected", "JSONObject", "parseJSONObject", "(", "String", "json", ")", "throws", "AssertionError", "{", "JSONParser", "parser", "=", "getJSONParser", "(", ")", ";", "try", "{", "Object", "obj", "=", "parser", ".", "parse", "(", "json", ")", ";", "assertTrue", "(", "obj", "instanceof", "JSONObject", ")", ";", "return", "(", "JSONObject", ")", "obj", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "AssertionError", "(", "\"", "not a valid JSON object: ", "\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "/**\n * Parses the provided string into a {@code JSONArray}.\n *\n * @param json string to be parsed\n * @return a {@code JSONArray}\n * @throws {@code AssertionError} if the string cannot be parsed into a {@code JSONArray}\n */", "protected", "JSONArray", "parseJSONArray", "(", "String", "json", ")", "throws", "AssertionError", "{", "JSONParser", "parser", "=", "getJSONParser", "(", ")", ";", "try", "{", "Object", "obj", "=", "parser", ".", "parse", "(", "json", ")", ";", "assertTrue", "(", "obj", "instanceof", "JSONArray", ")", ";", "return", "(", "JSONArray", ")", "obj", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "AssertionError", "(", "\"", "not a valid JSON array: ", "\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "protected", "Set", "<", "String", ">", "getNodeNames", "(", "JSONObject", "obj", ")", "{", "Set", "<", "String", ">", "names", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "Set", "<", "Map", ".", "Entry", ">", "entries", "=", "obj", ".", "entrySet", "(", ")", ";", "for", "(", "Map", ".", "Entry", "entry", ":", "entries", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", "instanceof", "JSONObject", ")", "{", "names", ".", "add", "(", "(", "String", ")", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "return", "names", ";", "}", "protected", "Set", "<", "String", ">", "getPropertyNames", "(", "JSONObject", "obj", ")", "{", "Set", "<", "String", ">", "names", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "Set", "<", "Map", ".", "Entry", ">", "entries", "=", "obj", ".", "entrySet", "(", ")", ";", "for", "(", "Map", ".", "Entry", "entry", ":", "entries", ")", "{", "if", "(", "!", "(", "entry", ".", "getValue", "(", ")", "instanceof", "JSONObject", ")", ")", "{", "names", ".", "add", "(", "(", "String", ")", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "return", "names", ";", "}", "protected", "void", "assertPropertyExists", "(", "JSONObject", "obj", ",", "String", "relPath", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "val", ")", ";", "}", "protected", "void", "assertPropertyNotExists", "(", "JSONObject", "obj", ",", "String", "relPath", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNull", "(", "val", ")", ";", "}", "protected", "void", "assertPropertyExists", "(", "JSONObject", "obj", ",", "String", "relPath", ",", "Class", "type", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "val", ")", ";", "assertTrue", "(", "type", ".", "isInstance", "(", "val", ")", ")", ";", "}", "protected", "void", "assertPropertyValue", "(", "JSONObject", "obj", ",", "String", "relPath", ",", "Double", "expected", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "val", ")", ";", "assertEquals", "(", "expected", ",", "val", ")", ";", "}", "protected", "void", "assertPropertyValue", "(", "JSONObject", "obj", ",", "String", "relPath", ",", "Long", "expected", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "val", ")", ";", "assertEquals", "(", "expected", ",", "val", ")", ";", "}", "protected", "void", "assertPropertyValue", "(", "JSONObject", "obj", ",", "String", "relPath", ",", "Boolean", "expected", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "val", ")", ";", "assertEquals", "(", "expected", ",", "val", ")", ";", "}", "protected", "void", "assertPropertyValue", "(", "JSONObject", "obj", ",", "String", "relPath", ",", "String", "expected", ")", "throws", "AssertionError", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "val", ")", ";", "assertEquals", "(", "expected", ",", "val", ")", ";", "}", "protected", "void", "assertPropertyValue", "(", "JSONObject", "obj", ",", "String", "relPath", ",", "Object", "[", "]", "expected", ")", "throws", "AssertionError", "{", "JSONArray", "array", "=", "resolveArrayValue", "(", "obj", ",", "relPath", ")", ";", "assertNotNull", "(", "\"", "not found: ", "\"", "+", "relPath", ",", "array", ")", ";", "assertEquals", "(", "expected", ".", "length", ",", "array", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Object", "o1", "=", "expected", "[", "i", "]", ";", "Object", "o2", "=", "array", ".", "get", "(", "i", ")", ";", "if", "(", "o1", "instanceof", "Number", "&&", "o2", "instanceof", "Number", ")", "{", "if", "(", "o1", "instanceof", "Integer", ")", "{", "o1", "=", "new", "Long", "(", "(", "Integer", ")", "o1", ")", ";", "}", "else", "if", "(", "o1", "instanceof", "Short", ")", "{", "o1", "=", "new", "Long", "(", "(", "Short", ")", "o1", ")", ";", "}", "else", "if", "(", "o1", "instanceof", "Float", ")", "{", "o1", "=", "new", "Double", "(", "(", "Float", ")", "o1", ")", ";", "}", "}", "assertEquals", "(", "o1", ",", "o2", ")", ";", "}", "}", "protected", "JSONObject", "resolveObjectValue", "(", "JSONObject", "obj", ",", "String", "relPath", ")", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "if", "(", "val", "instanceof", "JSONObject", ")", "{", "return", "(", "JSONObject", ")", "val", ";", "}", "throw", "new", "AssertionError", "(", "\"", "failed to resolve JSONObject value at ", "\"", "+", "relPath", "+", "\"", ": ", "\"", "+", "val", ")", ";", "}", "protected", "JSONObject", "getObjectArrayEntry", "(", "JSONArray", "array", ",", "int", "pos", ")", "{", "assertTrue", "(", "pos", ">=", "0", "&&", "pos", "<", "array", ".", "size", "(", ")", ")", ";", "Object", "entry", "=", "array", ".", "get", "(", "pos", ")", ";", "if", "(", "entry", "instanceof", "JSONObject", ")", "{", "return", "(", "JSONObject", ")", "entry", ";", "}", "throw", "new", "AssertionError", "(", "\"", "failed to resolve JSONObject array entry at pos ", "\"", "+", "pos", "+", "\"", ": ", "\"", "+", "entry", ")", ";", "}", "protected", "JSONArray", "resolveArrayValue", "(", "JSONObject", "obj", ",", "String", "relPath", ")", "{", "Object", "val", "=", "resolveValue", "(", "obj", ",", "relPath", ")", ";", "if", "(", "val", "instanceof", "JSONArray", ")", "{", "return", "(", "JSONArray", ")", "val", ";", "}", "throw", "new", "AssertionError", "(", "\"", "failed to resolve JSONArray value at ", "\"", "+", "relPath", "+", "\"", ": ", "\"", "+", "val", ")", ";", "}", "protected", "Object", "resolveValue", "(", "JSONObject", "obj", ",", "String", "relPath", ")", "{", "String", "names", "[", "]", "=", "relPath", ".", "split", "(", "\"", "/", "\"", ")", ";", "Object", "val", "=", "obj", ";", "for", "(", "String", "name", ":", "names", ")", "{", "if", "(", "!", "(", "val", "instanceof", "JSONObject", ")", ")", "{", "throw", "new", "AssertionError", "(", "\"", "not found: ", "\"", "+", "relPath", ")", ";", "}", "val", "=", "(", "(", "JSONObject", ")", "val", ")", ".", "get", "(", "name", ")", ";", "}", "return", "val", ";", "}", "protected", "void", "assertPropExists", "(", "String", "rev", ",", "String", "path", ",", "String", "property", ")", "{", "String", "nodes", "=", "mk", ".", "getNodes", "(", "path", ",", "rev", ",", "-", "1", "/*depth*/", ",", "0", "/*offset*/", ",", "-", "1", "/*maxChildNodes*/", ",", "null", "/*filter*/", ")", ";", "JSONObject", "obj", "=", "parseJSONObject", "(", "nodes", ")", ";", "assertPropertyExists", "(", "obj", ",", "property", ")", ";", "}", "protected", "void", "assertPropNotExists", "(", "String", "rev", ",", "String", "path", ",", "String", "property", ")", "{", "String", "nodes", "=", "mk", ".", "getNodes", "(", "path", ",", "rev", ",", "-", "1", "/*depth*/", ",", "0", "/*offset*/", ",", "-", "1", "/*maxChildNodes*/", ",", "null", "/*filter*/", ")", ";", "if", "(", "nodes", "==", "null", ")", "{", "return", ";", "}", "JSONObject", "obj", "=", "parseJSONObject", "(", "nodes", ")", ";", "assertPropertyNotExists", "(", "obj", ",", "property", ")", ";", "}", "protected", "void", "assertPropValue", "(", "String", "rev", ",", "String", "path", ",", "String", "property", ",", "String", "value", ")", "{", "String", "nodes", "=", "mk", ".", "getNodes", "(", "path", ",", "rev", ",", "-", "1", "/*depth*/", ",", "0", "/*offset*/", ",", "-", "1", "/*maxChildNodes*/", ",", "null", "/*filter*/", ")", ";", "JSONObject", "obj", "=", "parseJSONObject", "(", "nodes", ")", ";", "assertPropertyValue", "(", "obj", ",", "property", ",", "value", ")", ";", "}", "protected", "String", "addNodes", "(", "String", "rev", ",", "String", "...", "nodes", ")", "{", "String", "newRev", "=", "rev", ";", "for", "(", "String", "node", ":", "nodes", ")", "{", "newRev", "=", "mk", ".", "commit", "(", "\"", "\"", ",", "\"", "+", "\\\"", "\"", "+", "node", "+", "\"", "\\\"", ":{}", "\"", ",", "newRev", ",", "\"", "\"", ")", ";", "}", "return", "newRev", ";", "}", "protected", "String", "removeNodes", "(", "String", "rev", ",", "String", "...", "nodes", ")", "{", "String", "newRev", "=", "rev", ";", "for", "(", "String", "node", ":", "nodes", ")", "{", "newRev", "=", "mk", ".", "commit", "(", "\"", "\"", ",", "\"", "-", "\\\"", "\"", "+", "node", "+", "\"", "\\\"", "\"", ",", "newRev", ",", "\"", "\"", ")", ";", "}", "return", "newRev", ";", "}", "protected", "String", "setProp", "(", "String", "rev", ",", "String", "prop", ",", "Object", "value", ")", "{", "value", "=", "value", "==", "null", "?", "null", ":", "\"", "\\\"", "\"", "+", "value", "+", "\"", "\\\"", "\"", ";", "return", "mk", ".", "commit", "(", "\"", "\"", ",", "\"", "^", "\\\"", "\"", "+", "prop", "+", "\"", "\\\"", " : ", "\"", "+", "value", ",", "rev", ",", "\"", "\"", ")", ";", "}", "protected", "void", "assertNodesExist", "(", "String", "revision", ",", "String", "...", "paths", ")", "{", "doAssertNodes", "(", "true", ",", "revision", ",", "paths", ")", ";", "}", "protected", "void", "assertNodesNotExist", "(", "String", "revision", ",", "String", "...", "paths", ")", "{", "doAssertNodes", "(", "false", ",", "revision", ",", "paths", ")", ";", "}", "protected", "void", "doAssertNodes", "(", "boolean", "checkExists", ",", "String", "revision", ",", "String", "...", "paths", ")", "{", "for", "(", "String", "path", ":", "paths", ")", "{", "boolean", "exists", "=", "mk", ".", "nodeExists", "(", "path", ",", "revision", ")", ";", "if", "(", "checkExists", ")", "{", "assertTrue", "(", "path", "+", "\"", " does not exist", "\"", ",", "exists", ")", ";", "}", "else", "{", "assertFalse", "(", "path", "+", "\"", " should not exist", "\"", ",", "exists", ")", ";", "}", "}", "}", "}" ]
Abstract base class for {@link MicroKernel} integration tests.
[ "Abstract", "base", "class", "for", "{", "@link", "MicroKernel", "}", "integration", "tests", "." ]
[ "// Clear fields to avoid consuming memory after the test has run.", "// It looks like JUnit keeps references to all test instances until", "// the entire test suite has been run.", "//--------------------------------< utility methods for parsing json data >", "// JSON numeric types: Double, Long", "// convert types as necessary for comparison using equals method" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7bfd1791bfcfbec6d0f999fddb89310078ad1cc2
wlclimaco85/econtabil-001
src/main/java/com/econtabil/integration/domain/util/model/Atributos.java
[ "Apache-2.0" ]
Java
Atributos
/** * This class is a representation of an Account (i.e Checking, Savings, etc.). This represents an account for a transfer * setting. */
This class is a representation of an Account . This represents an account for a transfer setting.
[ "This", "class", "is", "a", "representation", "of", "an", "Account", ".", "This", "represents", "an", "account", "for", "a", "transfer", "setting", "." ]
@SuppressWarnings("serial") public class Atributos extends ModelCosmeDamiao { /** The SendSolv id for the account. */ private Integer id; /** The description. */ private String description; /** The numero. */ private String tamanho; /** The nome. */ private boolean obrigatorio; /** The left. */ private boolean chavePrimaria; /** The top. */ private boolean chaveSecundaria; /** The width. */ private Tabela tabelaSecundaria; /** The height. */ private String nome; /** * Default constructor. */ public Atributos() { super(); } /** * Gets the id. * * @return the id */ public Integer getId() { return id; } /** * Sets the id. * * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * Gets the description. * * @return the description */ public String getDescription() { return description; } /** * Sets the description. * * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * Gets the tamanho. * * @return the tamanho */ public String getTamanho() { return tamanho; } /** * Sets the tamanho. * * @param tamanho the new tamanho */ public void setTamanho(String tamanho) { this.tamanho = tamanho; } /** * Checks if is obrigatorio. * * @return true, if is obrigatorio */ public boolean isObrigatorio() { return obrigatorio; } /** * Sets the obrigatorio. * * @param obrigatorio the new obrigatorio */ public void setObrigatorio(boolean obrigatorio) { this.obrigatorio = obrigatorio; } /** * Checks if is chave primaria. * * @return true, if is chave primaria */ public boolean isChavePrimaria() { return chavePrimaria; } /** * Sets the chave primaria. * * @param chavePrimaria the new chave primaria */ public void setChavePrimaria(boolean chavePrimaria) { this.chavePrimaria = chavePrimaria; } /** * Checks if is chave secundaria. * * @return true, if is chave secundaria */ public boolean isChaveSecundaria() { return chaveSecundaria; } /** * Sets the chave secundaria. * * @param chaveSecundaria the new chave secundaria */ public void setChaveSecundaria(boolean chaveSecundaria) { this.chaveSecundaria = chaveSecundaria; } /** * Gets the tabela secundaria. * * @return the tabela secundaria */ public Tabela getTabelaSecundaria() { return tabelaSecundaria; } /** * Sets the tabela secundaria. * * @param tabelaSecundaria the new tabela secundaria */ public void setTabelaSecundaria(Tabela tabelaSecundaria) { this.tabelaSecundaria = tabelaSecundaria; } /** * Gets the nome. * * @return the nome */ public String getNome() { return nome; } /** * Sets the nome. * * @param nome the new nome */ public void setNome(String nome) { this.nome = nome; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Atributos [getId()=" + getId() + ", getType()=" + getType() + ", getDescription()=" + getDescription() + ", getTamanho()=" + getTamanho() + ", isObrigatorio()=" + isObrigatorio() + ", isChavePrimaria()=" + isChavePrimaria() + ", isChaveSecundaria()=" + isChaveSecundaria() + ", getTabelaSecundaria()=" + getTabelaSecundaria() + ", getNome()=" + getNome() + ", toString()=" + super.toString() + "]"; } }
[ "@", "SuppressWarnings", "(", "\"", "serial", "\"", ")", "public", "class", "Atributos", "extends", "ModelCosmeDamiao", "{", "/** The SendSolv id for the account. */", "private", "Integer", "id", ";", "/** The description. */", "private", "String", "description", ";", "/** The numero. */", "private", "String", "tamanho", ";", "/** The nome. */", "private", "boolean", "obrigatorio", ";", "/** The left. */", "private", "boolean", "chavePrimaria", ";", "/** The top. */", "private", "boolean", "chaveSecundaria", ";", "/** The width. */", "private", "Tabela", "tabelaSecundaria", ";", "/** The height. */", "private", "String", "nome", ";", "/**\r\n\t * Default constructor.\r\n\t */", "public", "Atributos", "(", ")", "{", "super", "(", ")", ";", "}", "/**\r\n\t * Gets the id.\r\n\t * \r\n\t * @return the id\r\n\t */", "public", "Integer", "getId", "(", ")", "{", "return", "id", ";", "}", "/**\r\n\t * Sets the id.\r\n\t * \r\n\t * @param id the id to set\r\n\t */", "public", "void", "setId", "(", "Integer", "id", ")", "{", "this", ".", "id", "=", "id", ";", "}", "/**\r\n\t * Gets the description.\r\n\t * \r\n\t * @return the description\r\n\t */", "public", "String", "getDescription", "(", ")", "{", "return", "description", ";", "}", "/**\r\n\t * Sets the description.\r\n\t * \r\n\t * @param description the description to set\r\n\t */", "public", "void", "setDescription", "(", "String", "description", ")", "{", "this", ".", "description", "=", "description", ";", "}", "/**\r\n\t * Gets the tamanho.\r\n\t * \r\n\t * @return the tamanho\r\n\t */", "public", "String", "getTamanho", "(", ")", "{", "return", "tamanho", ";", "}", "/**\r\n\t * Sets the tamanho.\r\n\t * \r\n\t * @param tamanho the new tamanho\r\n\t */", "public", "void", "setTamanho", "(", "String", "tamanho", ")", "{", "this", ".", "tamanho", "=", "tamanho", ";", "}", "/**\r\n\t * Checks if is obrigatorio.\r\n\t * \r\n\t * @return true, if is obrigatorio\r\n\t */", "public", "boolean", "isObrigatorio", "(", ")", "{", "return", "obrigatorio", ";", "}", "/**\r\n\t * Sets the obrigatorio.\r\n\t * \r\n\t * @param obrigatorio the new obrigatorio\r\n\t */", "public", "void", "setObrigatorio", "(", "boolean", "obrigatorio", ")", "{", "this", ".", "obrigatorio", "=", "obrigatorio", ";", "}", "/**\r\n\t * Checks if is chave primaria.\r\n\t * \r\n\t * @return true, if is chave primaria\r\n\t */", "public", "boolean", "isChavePrimaria", "(", ")", "{", "return", "chavePrimaria", ";", "}", "/**\r\n\t * Sets the chave primaria.\r\n\t * \r\n\t * @param chavePrimaria the new chave primaria\r\n\t */", "public", "void", "setChavePrimaria", "(", "boolean", "chavePrimaria", ")", "{", "this", ".", "chavePrimaria", "=", "chavePrimaria", ";", "}", "/**\r\n\t * Checks if is chave secundaria.\r\n\t * \r\n\t * @return true, if is chave secundaria\r\n\t */", "public", "boolean", "isChaveSecundaria", "(", ")", "{", "return", "chaveSecundaria", ";", "}", "/**\r\n\t * Sets the chave secundaria.\r\n\t * \r\n\t * @param chaveSecundaria the new chave secundaria\r\n\t */", "public", "void", "setChaveSecundaria", "(", "boolean", "chaveSecundaria", ")", "{", "this", ".", "chaveSecundaria", "=", "chaveSecundaria", ";", "}", "/**\r\n\t * Gets the tabela secundaria.\r\n\t * \r\n\t * @return the tabela secundaria\r\n\t */", "public", "Tabela", "getTabelaSecundaria", "(", ")", "{", "return", "tabelaSecundaria", ";", "}", "/**\r\n\t * Sets the tabela secundaria.\r\n\t * \r\n\t * @param tabelaSecundaria the new tabela secundaria\r\n\t */", "public", "void", "setTabelaSecundaria", "(", "Tabela", "tabelaSecundaria", ")", "{", "this", ".", "tabelaSecundaria", "=", "tabelaSecundaria", ";", "}", "/**\r\n\t * Gets the nome.\r\n\t * \r\n\t * @return the nome\r\n\t */", "public", "String", "getNome", "(", ")", "{", "return", "nome", ";", "}", "/**\r\n\t * Sets the nome.\r\n\t * \r\n\t * @param nome the new nome\r\n\t */", "public", "void", "setNome", "(", "String", "nome", ")", "{", "this", ".", "nome", "=", "nome", ";", "}", "/*\r\n\t * (non-Javadoc)\r\n\t * @see java.lang.Object#toString()\r\n\t */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "Atributos [getId()=", "\"", "+", "getId", "(", ")", "+", "\"", ", getType()=", "\"", "+", "getType", "(", ")", "+", "\"", ", getDescription()=", "\"", "+", "getDescription", "(", ")", "+", "\"", ", getTamanho()=", "\"", "+", "getTamanho", "(", ")", "+", "\"", ", isObrigatorio()=", "\"", "+", "isObrigatorio", "(", ")", "+", "\"", ", isChavePrimaria()=", "\"", "+", "isChavePrimaria", "(", ")", "+", "\"", ", isChaveSecundaria()=", "\"", "+", "isChaveSecundaria", "(", ")", "+", "\"", ", getTabelaSecundaria()=", "\"", "+", "getTabelaSecundaria", "(", ")", "+", "\"", ", getNome()=", "\"", "+", "getNome", "(", ")", "+", "\"", ", toString()=", "\"", "+", "super", ".", "toString", "(", ")", "+", "\"", "]", "\"", ";", "}", "}" ]
This class is a representation of an Account (i.e Checking, Savings, etc.).
[ "This", "class", "is", "a", "representation", "of", "an", "Account", "(", "i", ".", "e", "Checking", "Savings", "etc", ".", ")", "." ]
[]
[ { "param": "ModelCosmeDamiao", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ModelCosmeDamiao", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7bfe829c94b2f2254f0722aa70fd2b126d8dd1f1
ExilantTechnologies/ExilityCore-5.0.0
client/com/exilant/exility/core/SecurityGuard.java
[ "MIT" ]
Java
SecurityGuard
/*** * It is all in the name !! security guard for an HTTP request. Functionality * from here is in-lined into httpRequestHandler. This is used only by the old * version htmlrequestHandler */
It is all in the name !. security guard for an HTTP request. Functionality from here is in-lined into httpRequestHandler. This is used only by the old version htmlrequestHandler
[ "It", "is", "all", "in", "the", "name", "!", ".", "security", "guard", "for", "an", "HTTP", "request", ".", "Functionality", "from", "here", "is", "in", "-", "lined", "into", "httpRequestHandler", ".", "This", "is", "used", "only", "by", "the", "old", "version", "htmlrequestHandler" ]
public class SecurityGuard { /*** * to be re-factored into enumerations */ public static final int CLEARED = 0; /** * we find userId in cookie, but not in session */ public static final int SESSIONEXPIRED = 1; /** * userId cookie is not found */ public static final int NOTLOGGEDIN = 2; /** * userId mismatch between cookie and session. S */ public static final int HACKERATTEMPT = 5; /** * field in dc that has the authentication status */ public static final String AUTHENTICATION_FIELD_NAME = "authenticationStatus"; private static final SecurityGuard singletonInstance = new SecurityGuard(); private SecurityGuard() { } /*** * get an instance. * * @return instance */ public static SecurityGuard getGuard() { return SecurityGuard.singletonInstance; } /*** * do thorough security check * * @param request * @param outData * message for any security failure is put into this * @return true if security cleared */ public boolean cleared(HttpServletRequest request, ServiceData outData) { int authenticationStatus = this.authenticate(request, outData); outData.addValue(SecurityGuard.AUTHENTICATION_FIELD_NAME, Integer.toString(authenticationStatus)); if (authenticationStatus == SecurityGuard.CLEARED) { return true; } return false; } /*** * worker method for authentication * * @param request * @param outData * @return 0 if cleared, or one of the constants defined at the class level */ int authenticate(HttpServletRequest request, ServiceData outData) { if (!AP.securityEnabled) { Object o = request.getSession().getAttribute( AP.loggedInUserFieldName); if (o == null) { return SecurityGuard.SESSIONEXPIRED; } return SecurityGuard.CLEARED; } // hurdle 1: request should come from a page, and not be typed on // address bar /* * commented referrer part as per bhandi's suggestion. // url would be * null if some one typed it from the adress bar. String refUrl = * request.getHeader("referer"); // Dec 31 2009 : Bug 841 - Regarding * Session Timeout - SAB Miller: Venkat if (refUrl == null) { * outData.addMessage("exilNoReferrer"); return * SecurityGuard.NOREFERRER; } * * // hurdel 2: referrer should be the same as this host String reqHost * = request.getServerName(); URI uri = null; String refHost = null; try * { uri = new URI(refUrl); refHost = uri.getHost(); } catch (Exception * e) { //we just tried } * * if (!reqHost.equals(refHost)) { outData.addMessage("exilNoReferrer"); * return SecurityGuard.NOTMYHOST; } */ // hurdle 3: User should have logged in // If user is logged in, we will get the user id in cookies, and a // matching entry in session // check userId from session. Object o = request.getSession().getAttribute(AP.loggedInUserFieldName); if (o == null) { outData.addMessage("exilSessionExpired"); return SecurityGuard.SESSIONEXPIRED; } Cookie c = null; Cookie reqCookie[] = request.getCookies(); if (reqCookie != null) { for (Cookie cookie : reqCookie) { if (cookie.getName().equals(AP.loggedInUserFieldName)) { c = cookie; break; } } } if (c == null) { outData.addMessage("exilNotLoggedIn"); return SecurityGuard.NOTLOGGEDIN; } String cookieUserID = c.getValue(); String sessionUserID = o.toString(); if (!cookieUserID.equals(sessionUserID)) { outData.addMessage("exilNotLoggedIn"); return SecurityGuard.HACKERATTEMPT; } return SecurityGuard.CLEARED; } /** * security implemented thru CSRF-token rather than cookie * * @param request * @param inData * @param outData * @return true if we cleared it all */ public boolean cleared(HttpServletRequest request, ServiceData inData, ServiceData outData) { HttpSession session = request.getSession(true); boolean allOk = false; // check if we are using CSRF-token String token = request.getHeader(CommonFieldNames.CSRF_HEADER); if (token == null) { token = inData.getValue(CommonFieldNames.CSRF_HEADER); } Spit.out("CSRF = " + token); if (token != null) { allOk = session.getAttribute(token) != null; Spit.out("Security cleared with " + allOk); } else { /** * uses cookie for authentication */ Cookie c = null; Cookie reqCookie[] = request.getCookies(); if (reqCookie != null) { for (Cookie cookie : reqCookie) { if (cookie.getName().equals(AP.loggedInUserFieldName)) { c = cookie; break; } } } if (c == null) { allOk = false; } else { String sessionUserId = c.getValue(); Object o = session.getAttribute(AP.loggedInUserFieldName); if (o != null && sessionUserId.equals(o.toString())) { allOk = true; } else { allOk = false; } } } if (!allOk) { outData.addMessage("exilNotLoggedIn"); } return allOk; } }
[ "public", "class", "SecurityGuard", "{", "/***\n\t * to be re-factored into enumerations\n\t */", "public", "static", "final", "int", "CLEARED", "=", "0", ";", "/**\n\t * we find userId in cookie, but not in session\n\t */", "public", "static", "final", "int", "SESSIONEXPIRED", "=", "1", ";", "/**\n\t * userId cookie is not found\n\t */", "public", "static", "final", "int", "NOTLOGGEDIN", "=", "2", ";", "/**\n\t * userId mismatch between cookie and session. S\n\t */", "public", "static", "final", "int", "HACKERATTEMPT", "=", "5", ";", "/**\n\t * field in dc that has the authentication status\n\t */", "public", "static", "final", "String", "AUTHENTICATION_FIELD_NAME", "=", "\"", "authenticationStatus", "\"", ";", "private", "static", "final", "SecurityGuard", "singletonInstance", "=", "new", "SecurityGuard", "(", ")", ";", "private", "SecurityGuard", "(", ")", "{", "}", "/***\n\t * get an instance.\n\t * \n\t * @return instance\n\t */", "public", "static", "SecurityGuard", "getGuard", "(", ")", "{", "return", "SecurityGuard", ".", "singletonInstance", ";", "}", "/***\n\t * do thorough security check\n\t * \n\t * @param request\n\t * @param outData\n\t * message for any security failure is put into this\n\t * @return true if security cleared\n\t */", "public", "boolean", "cleared", "(", "HttpServletRequest", "request", ",", "ServiceData", "outData", ")", "{", "int", "authenticationStatus", "=", "this", ".", "authenticate", "(", "request", ",", "outData", ")", ";", "outData", ".", "addValue", "(", "SecurityGuard", ".", "AUTHENTICATION_FIELD_NAME", ",", "Integer", ".", "toString", "(", "authenticationStatus", ")", ")", ";", "if", "(", "authenticationStatus", "==", "SecurityGuard", ".", "CLEARED", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "/***\n\t * worker method for authentication\n\t * \n\t * @param request\n\t * @param outData\n\t * @return 0 if cleared, or one of the constants defined at the class level\n\t */", "int", "authenticate", "(", "HttpServletRequest", "request", ",", "ServiceData", "outData", ")", "{", "if", "(", "!", "AP", ".", "securityEnabled", ")", "{", "Object", "o", "=", "request", ".", "getSession", "(", ")", ".", "getAttribute", "(", "AP", ".", "loggedInUserFieldName", ")", ";", "if", "(", "o", "==", "null", ")", "{", "return", "SecurityGuard", ".", "SESSIONEXPIRED", ";", "}", "return", "SecurityGuard", ".", "CLEARED", ";", "}", "/*\n\t\t * commented referrer part as per bhandi's suggestion. // url would be\n\t\t * null if some one typed it from the adress bar. String refUrl =\n\t\t * request.getHeader(\"referer\"); // Dec 31 2009 : Bug 841 - Regarding\n\t\t * Session Timeout - SAB Miller: Venkat if (refUrl == null) {\n\t\t * outData.addMessage(\"exilNoReferrer\"); return\n\t\t * SecurityGuard.NOREFERRER; }\n\t\t * \n\t\t * // hurdel 2: referrer should be the same as this host String reqHost\n\t\t * = request.getServerName(); URI uri = null; String refHost = null; try\n\t\t * { uri = new URI(refUrl); refHost = uri.getHost(); } catch (Exception\n\t\t * e) { //we just tried }\n\t\t * \n\t\t * if (!reqHost.equals(refHost)) { outData.addMessage(\"exilNoReferrer\");\n\t\t * return SecurityGuard.NOTMYHOST; }\n\t\t */", "Object", "o", "=", "request", ".", "getSession", "(", ")", ".", "getAttribute", "(", "AP", ".", "loggedInUserFieldName", ")", ";", "if", "(", "o", "==", "null", ")", "{", "outData", ".", "addMessage", "(", "\"", "exilSessionExpired", "\"", ")", ";", "return", "SecurityGuard", ".", "SESSIONEXPIRED", ";", "}", "Cookie", "c", "=", "null", ";", "Cookie", "reqCookie", "[", "]", "=", "request", ".", "getCookies", "(", ")", ";", "if", "(", "reqCookie", "!=", "null", ")", "{", "for", "(", "Cookie", "cookie", ":", "reqCookie", ")", "{", "if", "(", "cookie", ".", "getName", "(", ")", ".", "equals", "(", "AP", ".", "loggedInUserFieldName", ")", ")", "{", "c", "=", "cookie", ";", "break", ";", "}", "}", "}", "if", "(", "c", "==", "null", ")", "{", "outData", ".", "addMessage", "(", "\"", "exilNotLoggedIn", "\"", ")", ";", "return", "SecurityGuard", ".", "NOTLOGGEDIN", ";", "}", "String", "cookieUserID", "=", "c", ".", "getValue", "(", ")", ";", "String", "sessionUserID", "=", "o", ".", "toString", "(", ")", ";", "if", "(", "!", "cookieUserID", ".", "equals", "(", "sessionUserID", ")", ")", "{", "outData", ".", "addMessage", "(", "\"", "exilNotLoggedIn", "\"", ")", ";", "return", "SecurityGuard", ".", "HACKERATTEMPT", ";", "}", "return", "SecurityGuard", ".", "CLEARED", ";", "}", "/**\n\t * security implemented thru CSRF-token rather than cookie\n\t * \n\t * @param request\n\t * @param inData\n\t * @param outData\n\t * @return true if we cleared it all\n\t */", "public", "boolean", "cleared", "(", "HttpServletRequest", "request", ",", "ServiceData", "inData", ",", "ServiceData", "outData", ")", "{", "HttpSession", "session", "=", "request", ".", "getSession", "(", "true", ")", ";", "boolean", "allOk", "=", "false", ";", "String", "token", "=", "request", ".", "getHeader", "(", "CommonFieldNames", ".", "CSRF_HEADER", ")", ";", "if", "(", "token", "==", "null", ")", "{", "token", "=", "inData", ".", "getValue", "(", "CommonFieldNames", ".", "CSRF_HEADER", ")", ";", "}", "Spit", ".", "out", "(", "\"", "CSRF = ", "\"", "+", "token", ")", ";", "if", "(", "token", "!=", "null", ")", "{", "allOk", "=", "session", ".", "getAttribute", "(", "token", ")", "!=", "null", ";", "Spit", ".", "out", "(", "\"", "Security cleared with ", "\"", "+", "allOk", ")", ";", "}", "else", "{", "/**\n\t\t\t * uses cookie for authentication\n\t\t\t */", "Cookie", "c", "=", "null", ";", "Cookie", "reqCookie", "[", "]", "=", "request", ".", "getCookies", "(", ")", ";", "if", "(", "reqCookie", "!=", "null", ")", "{", "for", "(", "Cookie", "cookie", ":", "reqCookie", ")", "{", "if", "(", "cookie", ".", "getName", "(", ")", ".", "equals", "(", "AP", ".", "loggedInUserFieldName", ")", ")", "{", "c", "=", "cookie", ";", "break", ";", "}", "}", "}", "if", "(", "c", "==", "null", ")", "{", "allOk", "=", "false", ";", "}", "else", "{", "String", "sessionUserId", "=", "c", ".", "getValue", "(", ")", ";", "Object", "o", "=", "session", ".", "getAttribute", "(", "AP", ".", "loggedInUserFieldName", ")", ";", "if", "(", "o", "!=", "null", "&&", "sessionUserId", ".", "equals", "(", "o", ".", "toString", "(", ")", ")", ")", "{", "allOk", "=", "true", ";", "}", "else", "{", "allOk", "=", "false", ";", "}", "}", "}", "if", "(", "!", "allOk", ")", "{", "outData", ".", "addMessage", "(", "\"", "exilNotLoggedIn", "\"", ")", ";", "}", "return", "allOk", ";", "}", "}" ]
It is all in the name !
[ "It", "is", "all", "in", "the", "name", "!" ]
[ "// hurdle 1: request should come from a page, and not be typed on", "// address bar", "// hurdle 3: User should have logged in", "// If user is logged in, we will get the user id in cookies, and a", "// matching entry in session", "// check userId from session.", "// check if we are using CSRF-token" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4fe40ad90bf98c1c17167583e94442ac6d925809
fregaham/KiWi
extensions/dashboard/src/kiwi/dashboard/action/StreamOfActivitiesAction.java
[ "BSD-3-Clause" ]
Java
StreamOfActivitiesAction
/** * The StreamOfActivitiesAction is a component for supporting the listing of the stream of * activities for the current user. * * At the moment, this component simply lists all activities around content items that are on a * user's watchlist. In a later stage, the stream of activities should consist of more complex * queries, allow aggregation, grouping, ... * * @author Sebastian Schaffert * */
The StreamOfActivitiesAction is a component for supporting the listing of the stream of activities for the current user. At the moment, this component simply lists all activities around content items that are on a user's watchlist. In a later stage, the stream of activities should consist of more complex queries, allow aggregation, grouping. @author Sebastian Schaffert
[ "The", "StreamOfActivitiesAction", "is", "a", "component", "for", "supporting", "the", "listing", "of", "the", "stream", "of", "activities", "for", "the", "current", "user", ".", "At", "the", "moment", "this", "component", "simply", "lists", "all", "activities", "around", "content", "items", "that", "are", "on", "a", "user", "'", "s", "watchlist", ".", "In", "a", "later", "stage", "the", "stream", "of", "activities", "should", "consist", "of", "more", "complex", "queries", "allow", "aggregation", "grouping", ".", "@author", "Sebastian", "Schaffert" ]
@Name("kiwi.dashboard.streamOfActivitiesAction") @Scope(ScopeType.PAGE) public class StreamOfActivitiesAction implements Serializable { /** * */ private static final long serialVersionUID = 1L; @In private User currentUser; @In protected Map<String, String> messages; @In private EntityManager entityManager; private List<Activity> activities; private List<Activity> tweetActivities; private int number = 5; private boolean numberChanged = true; /** * It lists activities by users including his friend activities ordered by date * @return */ public List<Activity> getActivities() { if(activities == null || numberChanged) { Query q = entityManager.createNamedQuery("activities.listActivitiesByUser"); q.setMaxResults(number); q.setParameter("user", currentUser); q.setHint("org.hibernate.cacheable", true); activities = q.getResultList(); numberChanged = false; } return activities; } /** * @return */ public List<Activity> getTweetActivities() { if(tweetActivities == null) { Query q = entityManager.createNamedQuery("activities.listTweetActivitiesByUser"); q.setMaxResults(100); q.setParameter("user", currentUser); q.setHint("org.hibernate.cacheable", true); tweetActivities = q.getResultList(); } return tweetActivities; } @Observer(value="updateActivities", create=false) public void clear() { activities = null; tweetActivities = null; } public String getMessageIdentifier(Activity activity) { if(activity.getMessageIdentifier() != null) { // String msgProp = SeamResourceBundle.getBundle().getString(activity.getMessageIdentifier()); String msgProp = messages.get(activity.getMessageIdentifier()); return msgProp; } else { return ""; } } public void showMore() { numberChanged = true; number = number +5; } }
[ "@", "Name", "(", "\"", "kiwi.dashboard.streamOfActivitiesAction", "\"", ")", "@", "Scope", "(", "ScopeType", ".", "PAGE", ")", "public", "class", "StreamOfActivitiesAction", "implements", "Serializable", "{", "/**\n\t * \n\t */", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "In", "private", "User", "currentUser", ";", "@", "In", "protected", "Map", "<", "String", ",", "String", ">", "messages", ";", "@", "In", "private", "EntityManager", "entityManager", ";", "private", "List", "<", "Activity", ">", "activities", ";", "private", "List", "<", "Activity", ">", "tweetActivities", ";", "private", "int", "number", "=", "5", ";", "private", "boolean", "numberChanged", "=", "true", ";", "/**\n\t * It lists activities by users including his friend activities ordered by date\n\t * @return\n\t */", "public", "List", "<", "Activity", ">", "getActivities", "(", ")", "{", "if", "(", "activities", "==", "null", "||", "numberChanged", ")", "{", "Query", "q", "=", "entityManager", ".", "createNamedQuery", "(", "\"", "activities.listActivitiesByUser", "\"", ")", ";", "q", ".", "setMaxResults", "(", "number", ")", ";", "q", ".", "setParameter", "(", "\"", "user", "\"", ",", "currentUser", ")", ";", "q", ".", "setHint", "(", "\"", "org.hibernate.cacheable", "\"", ",", "true", ")", ";", "activities", "=", "q", ".", "getResultList", "(", ")", ";", "numberChanged", "=", "false", ";", "}", "return", "activities", ";", "}", "/**\n\t * @return\n\t */", "public", "List", "<", "Activity", ">", "getTweetActivities", "(", ")", "{", "if", "(", "tweetActivities", "==", "null", ")", "{", "Query", "q", "=", "entityManager", ".", "createNamedQuery", "(", "\"", "activities.listTweetActivitiesByUser", "\"", ")", ";", "q", ".", "setMaxResults", "(", "100", ")", ";", "q", ".", "setParameter", "(", "\"", "user", "\"", ",", "currentUser", ")", ";", "q", ".", "setHint", "(", "\"", "org.hibernate.cacheable", "\"", ",", "true", ")", ";", "tweetActivities", "=", "q", ".", "getResultList", "(", ")", ";", "}", "return", "tweetActivities", ";", "}", "@", "Observer", "(", "value", "=", "\"", "updateActivities", "\"", ",", "create", "=", "false", ")", "public", "void", "clear", "(", ")", "{", "activities", "=", "null", ";", "tweetActivities", "=", "null", ";", "}", "public", "String", "getMessageIdentifier", "(", "Activity", "activity", ")", "{", "if", "(", "activity", ".", "getMessageIdentifier", "(", ")", "!=", "null", ")", "{", "String", "msgProp", "=", "messages", ".", "get", "(", "activity", ".", "getMessageIdentifier", "(", ")", ")", ";", "return", "msgProp", ";", "}", "else", "{", "return", "\"", "\"", ";", "}", "}", "public", "void", "showMore", "(", ")", "{", "numberChanged", "=", "true", ";", "number", "=", "number", "+", "5", ";", "}", "}" ]
The StreamOfActivitiesAction is a component for supporting the listing of the stream of activities for the current user.
[ "The", "StreamOfActivitiesAction", "is", "a", "component", "for", "supporting", "the", "listing", "of", "the", "stream", "of", "activities", "for", "the", "current", "user", "." ]
[ "//\t\t\tString msgProp = SeamResourceBundle.getBundle().getString(activity.getMessageIdentifier());" ]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4fe4178d2ed2e29d1b4177aa5e9d59a4c87a7106
paullewallencom/hbase-978-1-7839-8306-3
_src/Chapter09/InputDriver.java
[ "Apache-2.0" ]
Java
InputDriver
/** * This class converts text files containing space-delimited floating point numbers into * Mahout sequence files of VectorWritable suitable for input to the clustering jobs in * particular, and any Mahout job requiring this input in general. * */
This class converts text files containing space-delimited floating point numbers into Mahout sequence files of VectorWritable suitable for input to the clustering jobs in particular, and any Mahout job requiring this input in general.
[ "This", "class", "converts", "text", "files", "containing", "space", "-", "delimited", "floating", "point", "numbers", "into", "Mahout", "sequence", "files", "of", "VectorWritable", "suitable", "for", "input", "to", "the", "clustering", "jobs", "in", "particular", "and", "any", "Mahout", "job", "requiring", "this", "input", "in", "general", "." ]
public final class InputDriver { private static final Logger log = LoggerFactory.getLogger(InputDriver.class); private InputDriver() { } public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = DefaultOptionCreator.inputOption().withRequired(false).create(); Option outputOpt = DefaultOptionCreator.outputOption().withRequired(false).create(); Option vectorOpt = obuilder.withLongName("vector").withRequired(false).withArgument( abuilder.withName("v").withMinimum(1).withMaximum(1).create()).withDescription( "The vector implementation to use.").withShortName("v").create(); Option helpOpt = DefaultOptionCreator.helpOption(); Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(outputOpt).withOption( vectorOpt).withOption(helpOpt).create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } Path input = new Path(cmdLine.getValue(inputOpt, "testdata").toString()); Path output = new Path(cmdLine.getValue(outputOpt, "output").toString()); String vectorClassName = cmdLine.getValue(vectorOpt, "org.apache.mahout.math.RandomAccessSparseVector").toString(); //runJob(input, output, vectorClassName); } catch (OptionException e) { InputDriver.log.error("Exception parsing command line: ", e); CommandLineUtil.printHelp(group); } } public static void runJob(Path input, Path output, String vectorClassName,Configuration config) throws IOException, InterruptedException, ClassNotFoundException { Configuration conf = config; conf.set("vector.implementation.class.name", vectorClassName); Job job = new Job(conf, "Input Driver running over input: " + input); job.setOutputKeyClass(Text.class); job.setOutputValueClass(VectorWritable.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); job.setMapperClass(InputMapper.class); job.setNumReduceTasks(0); job.setJarByClass(InputDriver.class); FileInputFormat.addInputPath(job, input); FileOutputFormat.setOutputPath(job, output); job.waitForCompletion(true); } }
[ "public", "final", "class", "InputDriver", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "InputDriver", ".", "class", ")", ";", "private", "InputDriver", "(", ")", "{", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", ",", "InterruptedException", ",", "ClassNotFoundException", "{", "DefaultOptionBuilder", "obuilder", "=", "new", "DefaultOptionBuilder", "(", ")", ";", "ArgumentBuilder", "abuilder", "=", "new", "ArgumentBuilder", "(", ")", ";", "GroupBuilder", "gbuilder", "=", "new", "GroupBuilder", "(", ")", ";", "Option", "inputOpt", "=", "DefaultOptionCreator", ".", "inputOption", "(", ")", ".", "withRequired", "(", "false", ")", ".", "create", "(", ")", ";", "Option", "outputOpt", "=", "DefaultOptionCreator", ".", "outputOption", "(", ")", ".", "withRequired", "(", "false", ")", ".", "create", "(", ")", ";", "Option", "vectorOpt", "=", "obuilder", ".", "withLongName", "(", "\"", "vector", "\"", ")", ".", "withRequired", "(", "false", ")", ".", "withArgument", "(", "abuilder", ".", "withName", "(", "\"", "v", "\"", ")", ".", "withMinimum", "(", "1", ")", ".", "withMaximum", "(", "1", ")", ".", "create", "(", ")", ")", ".", "withDescription", "(", "\"", "The vector implementation to use.", "\"", ")", ".", "withShortName", "(", "\"", "v", "\"", ")", ".", "create", "(", ")", ";", "Option", "helpOpt", "=", "DefaultOptionCreator", ".", "helpOption", "(", ")", ";", "Group", "group", "=", "gbuilder", ".", "withName", "(", "\"", "Options", "\"", ")", ".", "withOption", "(", "inputOpt", ")", ".", "withOption", "(", "outputOpt", ")", ".", "withOption", "(", "vectorOpt", ")", ".", "withOption", "(", "helpOpt", ")", ".", "create", "(", ")", ";", "try", "{", "Parser", "parser", "=", "new", "Parser", "(", ")", ";", "parser", ".", "setGroup", "(", "group", ")", ";", "CommandLine", "cmdLine", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "cmdLine", ".", "hasOption", "(", "helpOpt", ")", ")", "{", "CommandLineUtil", ".", "printHelp", "(", "group", ")", ";", "return", ";", "}", "Path", "input", "=", "new", "Path", "(", "cmdLine", ".", "getValue", "(", "inputOpt", ",", "\"", "testdata", "\"", ")", ".", "toString", "(", ")", ")", ";", "Path", "output", "=", "new", "Path", "(", "cmdLine", ".", "getValue", "(", "outputOpt", ",", "\"", "output", "\"", ")", ".", "toString", "(", ")", ")", ";", "String", "vectorClassName", "=", "cmdLine", ".", "getValue", "(", "vectorOpt", ",", "\"", "org.apache.mahout.math.RandomAccessSparseVector", "\"", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "OptionException", "e", ")", "{", "InputDriver", ".", "log", ".", "error", "(", "\"", "Exception parsing command line: ", "\"", ",", "e", ")", ";", "CommandLineUtil", ".", "printHelp", "(", "group", ")", ";", "}", "}", "public", "static", "void", "runJob", "(", "Path", "input", ",", "Path", "output", ",", "String", "vectorClassName", ",", "Configuration", "config", ")", "throws", "IOException", ",", "InterruptedException", ",", "ClassNotFoundException", "{", "Configuration", "conf", "=", "config", ";", "conf", ".", "set", "(", "\"", "vector.implementation.class.name", "\"", ",", "vectorClassName", ")", ";", "Job", "job", "=", "new", "Job", "(", "conf", ",", "\"", "Input Driver running over input: ", "\"", "+", "input", ")", ";", "job", ".", "setOutputKeyClass", "(", "Text", ".", "class", ")", ";", "job", ".", "setOutputValueClass", "(", "VectorWritable", ".", "class", ")", ";", "job", ".", "setOutputFormatClass", "(", "SequenceFileOutputFormat", ".", "class", ")", ";", "job", ".", "setMapperClass", "(", "InputMapper", ".", "class", ")", ";", "job", ".", "setNumReduceTasks", "(", "0", ")", ";", "job", ".", "setJarByClass", "(", "InputDriver", ".", "class", ")", ";", "FileInputFormat", ".", "addInputPath", "(", "job", ",", "input", ")", ";", "FileOutputFormat", ".", "setOutputPath", "(", "job", ",", "output", ")", ";", "job", ".", "waitForCompletion", "(", "true", ")", ";", "}", "}" ]
This class converts text files containing space-delimited floating point numbers into Mahout sequence files of VectorWritable suitable for input to the clustering jobs in particular, and any Mahout job requiring this input in general.
[ "This", "class", "converts", "text", "files", "containing", "space", "-", "delimited", "floating", "point", "numbers", "into", "Mahout", "sequence", "files", "of", "VectorWritable", "suitable", "for", "input", "to", "the", "clustering", "jobs", "in", "particular", "and", "any", "Mahout", "job", "requiring", "this", "input", "in", "general", "." ]
[ "//runJob(input, output, vectorClassName);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4fe54d65bb67e23b83533da1726d248c436cc1fa
virdio/mediapipe
mediapipe/examples/android/src/java/com/google/mediapipe/apps/handtrackinggpu/MainActivity.java
[ "Apache-2.0" ]
Java
MainActivity
/** Main activity of MediaPipe hand tracking app. */
Main activity of MediaPipe hand tracking app.
[ "Main", "activity", "of", "MediaPipe", "hand", "tracking", "app", "." ]
public class MainActivity extends com.google.mediapipe.apps.basic.MainActivity { private static final String TAG = "MainActivity"; private static final String INPUT_NUM_HANDS_SIDE_PACKET_NAME = "num_hands"; private static final String INPUT_MODEL_COMPLEXITY = "model_complexity"; private static final String OUTPUT_LANDMARKS_STREAM_NAME = "hand_landmarks"; // Max number of hands to detect/process. private static final int NUM_HANDS = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ApplicationInfo applicationInfo; try { applicationInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { throw new AssertionError(e); } AndroidPacketCreator packetCreator = processor.getPacketCreator(); Map<String, Packet> inputSidePackets = new HashMap<>(); inputSidePackets.put(INPUT_NUM_HANDS_SIDE_PACKET_NAME, packetCreator.createInt32(NUM_HANDS)); if (applicationInfo.metaData.containsKey("modelComplexity")) { inputSidePackets.put( INPUT_MODEL_COMPLEXITY, packetCreator.createInt32(applicationInfo.metaData.getInt("modelComplexity"))); } processor.setInputSidePackets(inputSidePackets); // To show verbose logging, run: // adb shell setprop log.tag.MainActivity VERBOSE if (Log.isLoggable(TAG, Log.VERBOSE)) { processor.addPacketCallback( OUTPUT_LANDMARKS_STREAM_NAME, (packet) -> { Log.v(TAG, "Received multi-hand landmarks packet."); List<NormalizedLandmarkList> multiHandLandmarks = PacketGetter.getProtoVector(packet, NormalizedLandmarkList.parser()); Log.v( TAG, "[TS:" + packet.getTimestamp() + "] " + getMultiHandLandmarksDebugString(multiHandLandmarks)); }); } } private String getMultiHandLandmarksDebugString(List<NormalizedLandmarkList> multiHandLandmarks) { if (multiHandLandmarks.isEmpty()) { return "No hand landmarks"; } String multiHandLandmarksStr = "Number of hands detected: " + multiHandLandmarks.size() + "\n"; int handIndex = 0; for (NormalizedLandmarkList landmarks : multiHandLandmarks) { multiHandLandmarksStr += "\t#Hand landmarks for hand[" + handIndex + "]: " + landmarks.getLandmarkCount() + "\n"; int landmarkIndex = 0; for (NormalizedLandmark landmark : landmarks.getLandmarkList()) { multiHandLandmarksStr += "\t\tLandmark [" + landmarkIndex + "]: (" + landmark.getX() + ", " + landmark.getY() + ", " + landmark.getZ() + ")\n"; ++landmarkIndex; } ++handIndex; } return multiHandLandmarksStr; } }
[ "public", "class", "MainActivity", "extends", "com", ".", "google", ".", "mediapipe", ".", "apps", ".", "basic", ".", "MainActivity", "{", "private", "static", "final", "String", "TAG", "=", "\"", "MainActivity", "\"", ";", "private", "static", "final", "String", "INPUT_NUM_HANDS_SIDE_PACKET_NAME", "=", "\"", "num_hands", "\"", ";", "private", "static", "final", "String", "INPUT_MODEL_COMPLEXITY", "=", "\"", "model_complexity", "\"", ";", "private", "static", "final", "String", "OUTPUT_LANDMARKS_STREAM_NAME", "=", "\"", "hand_landmarks", "\"", ";", "private", "static", "final", "int", "NUM_HANDS", "=", "2", ";", "@", "Override", "protected", "void", "onCreate", "(", "Bundle", "savedInstanceState", ")", "{", "super", ".", "onCreate", "(", "savedInstanceState", ")", ";", "ApplicationInfo", "applicationInfo", ";", "try", "{", "applicationInfo", "=", "getPackageManager", "(", ")", ".", "getApplicationInfo", "(", "getPackageName", "(", ")", ",", "PackageManager", ".", "GET_META_DATA", ")", ";", "}", "catch", "(", "NameNotFoundException", "e", ")", "{", "throw", "new", "AssertionError", "(", "e", ")", ";", "}", "AndroidPacketCreator", "packetCreator", "=", "processor", ".", "getPacketCreator", "(", ")", ";", "Map", "<", "String", ",", "Packet", ">", "inputSidePackets", "=", "new", "HashMap", "<", ">", "(", ")", ";", "inputSidePackets", ".", "put", "(", "INPUT_NUM_HANDS_SIDE_PACKET_NAME", ",", "packetCreator", ".", "createInt32", "(", "NUM_HANDS", ")", ")", ";", "if", "(", "applicationInfo", ".", "metaData", ".", "containsKey", "(", "\"", "modelComplexity", "\"", ")", ")", "{", "inputSidePackets", ".", "put", "(", "INPUT_MODEL_COMPLEXITY", ",", "packetCreator", ".", "createInt32", "(", "applicationInfo", ".", "metaData", ".", "getInt", "(", "\"", "modelComplexity", "\"", ")", ")", ")", ";", "}", "processor", ".", "setInputSidePackets", "(", "inputSidePackets", ")", ";", "if", "(", "Log", ".", "isLoggable", "(", "TAG", ",", "Log", ".", "VERBOSE", ")", ")", "{", "processor", ".", "addPacketCallback", "(", "OUTPUT_LANDMARKS_STREAM_NAME", ",", "(", "packet", ")", "->", "{", "Log", ".", "v", "(", "TAG", ",", "\"", "Received multi-hand landmarks packet.", "\"", ")", ";", "List", "<", "NormalizedLandmarkList", ">", "multiHandLandmarks", "=", "PacketGetter", ".", "getProtoVector", "(", "packet", ",", "NormalizedLandmarkList", ".", "parser", "(", ")", ")", ";", "Log", ".", "v", "(", "TAG", ",", "\"", "[TS:", "\"", "+", "packet", ".", "getTimestamp", "(", ")", "+", "\"", "] ", "\"", "+", "getMultiHandLandmarksDebugString", "(", "multiHandLandmarks", ")", ")", ";", "}", ")", ";", "}", "}", "private", "String", "getMultiHandLandmarksDebugString", "(", "List", "<", "NormalizedLandmarkList", ">", "multiHandLandmarks", ")", "{", "if", "(", "multiHandLandmarks", ".", "isEmpty", "(", ")", ")", "{", "return", "\"", "No hand landmarks", "\"", ";", "}", "String", "multiHandLandmarksStr", "=", "\"", "Number of hands detected: ", "\"", "+", "multiHandLandmarks", ".", "size", "(", ")", "+", "\"", "\\n", "\"", ";", "int", "handIndex", "=", "0", ";", "for", "(", "NormalizedLandmarkList", "landmarks", ":", "multiHandLandmarks", ")", "{", "multiHandLandmarksStr", "+=", "\"", "\\t", "#Hand landmarks for hand[", "\"", "+", "handIndex", "+", "\"", "]: ", "\"", "+", "landmarks", ".", "getLandmarkCount", "(", ")", "+", "\"", "\\n", "\"", ";", "int", "landmarkIndex", "=", "0", ";", "for", "(", "NormalizedLandmark", "landmark", ":", "landmarks", ".", "getLandmarkList", "(", ")", ")", "{", "multiHandLandmarksStr", "+=", "\"", "\\t", "\\t", "Landmark [", "\"", "+", "landmarkIndex", "+", "\"", "]: (", "\"", "+", "landmark", ".", "getX", "(", ")", "+", "\"", ", ", "\"", "+", "landmark", ".", "getY", "(", ")", "+", "\"", ", ", "\"", "+", "landmark", ".", "getZ", "(", ")", "+", "\"", ")", "\\n", "\"", ";", "++", "landmarkIndex", ";", "}", "++", "handIndex", ";", "}", "return", "multiHandLandmarksStr", ";", "}", "}" ]
Main activity of MediaPipe hand tracking app.
[ "Main", "activity", "of", "MediaPipe", "hand", "tracking", "app", "." ]
[ "// Max number of hands to detect/process.", "// To show verbose logging, run:", "// adb shell setprop log.tag.MainActivity VERBOSE" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4fe7d031c0624c857529dd6cfe8e08e1daa7a1e6
cmzfusion/OpenAdaptorBhavaya
src/java/org/bhavaya/beans/generator/BCELFactory.java
[ "MIT" ]
Java
BCELFactory
/** * Factory creates il.append() statements, and sets instruction targets. * A helper class for BCELifier. * * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A> * @version $Id: BCELFactory.java,v 1.2 2004/09/23 10:13:22 haass Exp $ * @see BCELifier */
Factory creates il.append() statements, and sets instruction targets. A helper class for BCELifier. @author M.
[ "Factory", "creates", "il", ".", "append", "()", "statements", "and", "sets", "instruction", "targets", ".", "A", "helper", "class", "for", "BCELifier", ".", "@author", "M", "." ]
public class BCELFactory extends EmptyVisitor { private MethodGen _mg; private PrintWriter _out; private ConstantPoolGen _cp; BCELFactory(MethodGen mg, PrintWriter out) { _mg = mg; _cp = mg.getConstantPool(); _out = out; } private HashMap branch_map = new HashMap(); // Map<Instruction, InstructionHandle> public void start() { if (!_mg.isAbstract() && !_mg.isNative()) { for (InstructionHandle ih = _mg.getInstructionList().getStart(); ih != null; ih = ih.getNext()) { Instruction i = ih.getInstruction(); if (i instanceof BranchInstruction) { branch_map.put(i, ih); // memorize container } if (ih.hasTargeters()) { if (i instanceof BranchInstruction) { _out.println(" InstructionHandle ih_" + ih.getPosition() + ";"); } else { _out.print(" InstructionHandle ih_" + ih.getPosition() + " = "); } } else { _out.print(" "); } if (!visitInstruction(i)) i.accept(this); } updateBranchTargets(); updateExceptionHandlers(); } } private boolean visitInstruction(Instruction i) { short opcode = i.getOpcode(); if ((InstructionConstants.INSTRUCTIONS[opcode] != null) && !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)) { // Handled below _out.println("il.append(InstructionConstants." + i.getName().toUpperCase() + ");"); return true; } return false; } public void visitLocalVariableInstruction(LocalVariableInstruction i) { short opcode = i.getOpcode(); Type type = i.getType(_cp); if (opcode == Constants.IINC) { _out.println("il.append(new IINC(" + i.getIndex() + ", " + ((IINC) i).getIncrement() + "));"); } else { String kind = (opcode < Constants.ISTORE) ? "Load" : "Store"; _out.println("il.append(_factory.create" + kind + "(" + BCELifier.printType(type) + ", " + i.getIndex() + "));"); } } public void visitArrayInstruction(ArrayInstruction i) { short opcode = i.getOpcode(); Type type = i.getType(_cp); String kind = (opcode < Constants.IASTORE) ? "Load" : "Store"; _out.println("il.append(_factory.createArray" + kind + "(" + BCELifier.printType(type) + "));"); } public void visitFieldInstruction(FieldInstruction i) { short opcode = i.getOpcode(); String class_name = i.getClassName(_cp); String field_name = i.getFieldName(_cp); Type type = i.getFieldType(_cp); _out.println("il.append(_factory.createFieldAccess(\"" + class_name + "\", \"" + field_name + "\", " + BCELifier.printType(type) + ", " + "Constants." + Constants.OPCODE_NAMES[opcode].toUpperCase() + "));"); } public void visitInvokeInstruction(InvokeInstruction i) { short opcode = i.getOpcode(); String class_name = i.getClassName(_cp); String method_name = i.getMethodName(_cp); Type type = i.getReturnType(_cp); Type[] arg_types = i.getArgumentTypes(_cp); _out.println("il.append(_factory.createInvoke(\"" + class_name + "\", \"" + method_name + "\", " + BCELifier.printType(type) + ", " + BCELifier.printArgumentTypes(arg_types) + ", " + "Constants." + Constants.OPCODE_NAMES[opcode].toUpperCase() + "));"); } public void visitAllocationInstruction(AllocationInstruction i) { Type type; if (i instanceof CPInstruction) { type = ((CPInstruction) i).getType(_cp); } else { type = ((NEWARRAY) i).getType(); } short opcode = ((Instruction) i).getOpcode(); int dim = 1; switch (opcode) { case Constants.NEW: _out.println("il.append(_factory.createNew(\"" + ((ObjectType) type).getClassName() + "\"));"); break; case Constants.MULTIANEWARRAY: dim = ((MULTIANEWARRAY) i).getDimensions(); case Constants.ANEWARRAY: case Constants.NEWARRAY: _out.println("il.append(_factory.createNewArray(" + BCELifier.printType(type) + ", (short) " + dim + "));"); break; default: throw new RuntimeException("Oops: " + opcode); } } private void createConstant(Object value) { String embed = value.toString(); if (value instanceof String) embed = '"' + Utility.convertString(value.toString()) + '"'; else if (value instanceof Character) embed = "(char)0x" + Integer.toHexString(((Character) value).charValue()); _out.println("il.append(new PUSH(_cp, " + embed + "));"); } public void visitLDC(LDC i) { createConstant(i.getValue(_cp)); } public void visitLDC2_W(LDC2_W i) { createConstant(i.getValue(_cp)); } public void visitConstantPushInstruction(ConstantPushInstruction i) { createConstant(i.getValue()); } public void visitINSTANCEOF(INSTANCEOF i) { Type type = i.getType(_cp); _out.println("il.append(new INSTANCEOF(_cp.addClass(" + BCELifier.printType(type) + ")));"); } public void visitCHECKCAST(CHECKCAST i) { Type type = i.getType(_cp); _out.println("il.append(_factory.createCheckCast(" + BCELifier.printType(type) + "));"); } public void visitReturnInstruction(ReturnInstruction i) { Type type = i.getType(_cp); _out.println("il.append(_factory.createReturn(" + BCELifier.printType(type) + "));"); } // Memorize BranchInstructions that need an update private ArrayList branches = new ArrayList(); public void visitBranchInstruction(BranchInstruction bi) { BranchHandle bh = (BranchHandle) branch_map.get(bi); int pos = bh.getPosition(); String name = bi.getName() + "_" + pos; if (bi instanceof Select) { Select s = (Select) bi; branches.add(bi); StringBuffer args = new StringBuffer("new int[] { "); int[] matchs = s.getMatchs(); for (int i = 0; i < matchs.length; i++) { args.append(matchs[i]); if (i < matchs.length - 1) args.append(", "); } args.append(" }"); _out.print(" Select " + name + " = new " + bi.getName().toUpperCase() + "(" + args + ", new InstructionHandle[] { "); for (int i = 0; i < matchs.length; i++) { _out.print("null"); if (i < matchs.length - 1) _out.print(", "); } _out.println(");"); } else { int t_pos = bh.getTarget().getPosition(); String target; if (pos > t_pos) { target = "ih_" + t_pos; } else { branches.add(bi); target = "null"; } _out.println(" BranchInstruction " + name + " = _factory.createBranchInstruction(" + "Constants." + bi.getName().toUpperCase() + ", " + target + ");"); } if (bh.hasTargeters()) _out.println(" ih_" + pos + " = il.append(" + name + ");"); else _out.println(" il.append(" + name + ");"); } public void visitRET(RET i) { _out.println("il.append(new RET(" + i.getIndex() + ")));"); } private void updateBranchTargets() { for (Iterator i = branches.iterator(); i.hasNext();) { BranchInstruction bi = (BranchInstruction) i.next(); BranchHandle bh = (BranchHandle) branch_map.get(bi); int pos = bh.getPosition(); String name = bi.getName() + "_" + pos; int t_pos = bh.getTarget().getPosition(); _out.println(" " + name + ".setTarget(ih_" + t_pos + ");"); if (bi instanceof Select) { InstructionHandle[] ihs = ((Select) bi).getTargets(); for (int j = 0; j < ihs.length; j++) { t_pos = ihs[j].getPosition(); _out.println(" " + name + ".setTarget(" + j + ", ih_" + t_pos + ");"); } } } } private void updateExceptionHandlers() { CodeExceptionGen[] handlers = _mg.getExceptionHandlers(); for (int i = 0; i < handlers.length; i++) { CodeExceptionGen h = handlers[i]; String type = (h.getCatchType() == null) ? "null" : BCELifier.printType(h.getCatchType()); _out.println(" method.addExceptionHandler(" + "ih_" + h.getStartPC().getPosition() + ", " + "ih_" + h.getEndPC().getPosition() + ", " + "ih_" + h.getHandlerPC().getPosition() + ", " + type + ");"); } } }
[ "public", "class", "BCELFactory", "extends", "EmptyVisitor", "{", "private", "MethodGen", "_mg", ";", "private", "PrintWriter", "_out", ";", "private", "ConstantPoolGen", "_cp", ";", "BCELFactory", "(", "MethodGen", "mg", ",", "PrintWriter", "out", ")", "{", "_mg", "=", "mg", ";", "_cp", "=", "mg", ".", "getConstantPool", "(", ")", ";", "_out", "=", "out", ";", "}", "private", "HashMap", "branch_map", "=", "new", "HashMap", "(", ")", ";", "public", "void", "start", "(", ")", "{", "if", "(", "!", "_mg", ".", "isAbstract", "(", ")", "&&", "!", "_mg", ".", "isNative", "(", ")", ")", "{", "for", "(", "InstructionHandle", "ih", "=", "_mg", ".", "getInstructionList", "(", ")", ".", "getStart", "(", ")", ";", "ih", "!=", "null", ";", "ih", "=", "ih", ".", "getNext", "(", ")", ")", "{", "Instruction", "i", "=", "ih", ".", "getInstruction", "(", ")", ";", "if", "(", "i", "instanceof", "BranchInstruction", ")", "{", "branch_map", ".", "put", "(", "i", ",", "ih", ")", ";", "}", "if", "(", "ih", ".", "hasTargeters", "(", ")", ")", "{", "if", "(", "i", "instanceof", "BranchInstruction", ")", "{", "_out", ".", "println", "(", "\"", " InstructionHandle ih_", "\"", "+", "ih", ".", "getPosition", "(", ")", "+", "\"", ";", "\"", ")", ";", "}", "else", "{", "_out", ".", "print", "(", "\"", " InstructionHandle ih_", "\"", "+", "ih", ".", "getPosition", "(", ")", "+", "\"", " = ", "\"", ")", ";", "}", "}", "else", "{", "_out", ".", "print", "(", "\"", " ", "\"", ")", ";", "}", "if", "(", "!", "visitInstruction", "(", "i", ")", ")", "i", ".", "accept", "(", "this", ")", ";", "}", "updateBranchTargets", "(", ")", ";", "updateExceptionHandlers", "(", ")", ";", "}", "}", "private", "boolean", "visitInstruction", "(", "Instruction", "i", ")", "{", "short", "opcode", "=", "i", ".", "getOpcode", "(", ")", ";", "if", "(", "(", "InstructionConstants", ".", "INSTRUCTIONS", "[", "opcode", "]", "!=", "null", ")", "&&", "!", "(", "i", "instanceof", "ConstantPushInstruction", ")", "&&", "!", "(", "i", "instanceof", "ReturnInstruction", ")", ")", "{", "_out", ".", "println", "(", "\"", "il.append(InstructionConstants.", "\"", "+", "i", ".", "getName", "(", ")", ".", "toUpperCase", "(", ")", "+", "\"", ");", "\"", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "public", "void", "visitLocalVariableInstruction", "(", "LocalVariableInstruction", "i", ")", "{", "short", "opcode", "=", "i", ".", "getOpcode", "(", ")", ";", "Type", "type", "=", "i", ".", "getType", "(", "_cp", ")", ";", "if", "(", "opcode", "==", "Constants", ".", "IINC", ")", "{", "_out", ".", "println", "(", "\"", "il.append(new IINC(", "\"", "+", "i", ".", "getIndex", "(", ")", "+", "\"", ", ", "\"", "+", "(", "(", "IINC", ")", "i", ")", ".", "getIncrement", "(", ")", "+", "\"", "));", "\"", ")", ";", "}", "else", "{", "String", "kind", "=", "(", "opcode", "<", "Constants", ".", "ISTORE", ")", "?", "\"", "Load", "\"", ":", "\"", "Store", "\"", ";", "_out", ".", "println", "(", "\"", "il.append(_factory.create", "\"", "+", "kind", "+", "\"", "(", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", ", ", "\"", "+", "i", ".", "getIndex", "(", ")", "+", "\"", "));", "\"", ")", ";", "}", "}", "public", "void", "visitArrayInstruction", "(", "ArrayInstruction", "i", ")", "{", "short", "opcode", "=", "i", ".", "getOpcode", "(", ")", ";", "Type", "type", "=", "i", ".", "getType", "(", "_cp", ")", ";", "String", "kind", "=", "(", "opcode", "<", "Constants", ".", "IASTORE", ")", "?", "\"", "Load", "\"", ":", "\"", "Store", "\"", ";", "_out", ".", "println", "(", "\"", "il.append(_factory.createArray", "\"", "+", "kind", "+", "\"", "(", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", "));", "\"", ")", ";", "}", "public", "void", "visitFieldInstruction", "(", "FieldInstruction", "i", ")", "{", "short", "opcode", "=", "i", ".", "getOpcode", "(", ")", ";", "String", "class_name", "=", "i", ".", "getClassName", "(", "_cp", ")", ";", "String", "field_name", "=", "i", ".", "getFieldName", "(", "_cp", ")", ";", "Type", "type", "=", "i", ".", "getFieldType", "(", "_cp", ")", ";", "_out", ".", "println", "(", "\"", "il.append(_factory.createFieldAccess(", "\\\"", "\"", "+", "class_name", "+", "\"", "\\\"", ", ", "\\\"", "\"", "+", "field_name", "+", "\"", "\\\"", ", ", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", ", ", "\"", "+", "\"", "Constants.", "\"", "+", "Constants", ".", "OPCODE_NAMES", "[", "opcode", "]", ".", "toUpperCase", "(", ")", "+", "\"", "));", "\"", ")", ";", "}", "public", "void", "visitInvokeInstruction", "(", "InvokeInstruction", "i", ")", "{", "short", "opcode", "=", "i", ".", "getOpcode", "(", ")", ";", "String", "class_name", "=", "i", ".", "getClassName", "(", "_cp", ")", ";", "String", "method_name", "=", "i", ".", "getMethodName", "(", "_cp", ")", ";", "Type", "type", "=", "i", ".", "getReturnType", "(", "_cp", ")", ";", "Type", "[", "]", "arg_types", "=", "i", ".", "getArgumentTypes", "(", "_cp", ")", ";", "_out", ".", "println", "(", "\"", "il.append(_factory.createInvoke(", "\\\"", "\"", "+", "class_name", "+", "\"", "\\\"", ", ", "\\\"", "\"", "+", "method_name", "+", "\"", "\\\"", ", ", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", ", ", "\"", "+", "BCELifier", ".", "printArgumentTypes", "(", "arg_types", ")", "+", "\"", ", ", "\"", "+", "\"", "Constants.", "\"", "+", "Constants", ".", "OPCODE_NAMES", "[", "opcode", "]", ".", "toUpperCase", "(", ")", "+", "\"", "));", "\"", ")", ";", "}", "public", "void", "visitAllocationInstruction", "(", "AllocationInstruction", "i", ")", "{", "Type", "type", ";", "if", "(", "i", "instanceof", "CPInstruction", ")", "{", "type", "=", "(", "(", "CPInstruction", ")", "i", ")", ".", "getType", "(", "_cp", ")", ";", "}", "else", "{", "type", "=", "(", "(", "NEWARRAY", ")", "i", ")", ".", "getType", "(", ")", ";", "}", "short", "opcode", "=", "(", "(", "Instruction", ")", "i", ")", ".", "getOpcode", "(", ")", ";", "int", "dim", "=", "1", ";", "switch", "(", "opcode", ")", "{", "case", "Constants", ".", "NEW", ":", "_out", ".", "println", "(", "\"", "il.append(_factory.createNew(", "\\\"", "\"", "+", "(", "(", "ObjectType", ")", "type", ")", ".", "getClassName", "(", ")", "+", "\"", "\\\"", "));", "\"", ")", ";", "break", ";", "case", "Constants", ".", "MULTIANEWARRAY", ":", "dim", "=", "(", "(", "MULTIANEWARRAY", ")", "i", ")", ".", "getDimensions", "(", ")", ";", "case", "Constants", ".", "ANEWARRAY", ":", "case", "Constants", ".", "NEWARRAY", ":", "_out", ".", "println", "(", "\"", "il.append(_factory.createNewArray(", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", ", (short) ", "\"", "+", "dim", "+", "\"", "));", "\"", ")", ";", "break", ";", "default", ":", "throw", "new", "RuntimeException", "(", "\"", "Oops: ", "\"", "+", "opcode", ")", ";", "}", "}", "private", "void", "createConstant", "(", "Object", "value", ")", "{", "String", "embed", "=", "value", ".", "toString", "(", ")", ";", "if", "(", "value", "instanceof", "String", ")", "embed", "=", "'\"'", "+", "Utility", ".", "convertString", "(", "value", ".", "toString", "(", ")", ")", "+", "'\"'", ";", "else", "if", "(", "value", "instanceof", "Character", ")", "embed", "=", "\"", "(char)0x", "\"", "+", "Integer", ".", "toHexString", "(", "(", "(", "Character", ")", "value", ")", ".", "charValue", "(", ")", ")", ";", "_out", ".", "println", "(", "\"", "il.append(new PUSH(_cp, ", "\"", "+", "embed", "+", "\"", "));", "\"", ")", ";", "}", "public", "void", "visitLDC", "(", "LDC", "i", ")", "{", "createConstant", "(", "i", ".", "getValue", "(", "_cp", ")", ")", ";", "}", "public", "void", "visitLDC2_W", "(", "LDC2_W", "i", ")", "{", "createConstant", "(", "i", ".", "getValue", "(", "_cp", ")", ")", ";", "}", "public", "void", "visitConstantPushInstruction", "(", "ConstantPushInstruction", "i", ")", "{", "createConstant", "(", "i", ".", "getValue", "(", ")", ")", ";", "}", "public", "void", "visitINSTANCEOF", "(", "INSTANCEOF", "i", ")", "{", "Type", "type", "=", "i", ".", "getType", "(", "_cp", ")", ";", "_out", ".", "println", "(", "\"", "il.append(new INSTANCEOF(_cp.addClass(", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", ")));", "\"", ")", ";", "}", "public", "void", "visitCHECKCAST", "(", "CHECKCAST", "i", ")", "{", "Type", "type", "=", "i", ".", "getType", "(", "_cp", ")", ";", "_out", ".", "println", "(", "\"", "il.append(_factory.createCheckCast(", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", "));", "\"", ")", ";", "}", "public", "void", "visitReturnInstruction", "(", "ReturnInstruction", "i", ")", "{", "Type", "type", "=", "i", ".", "getType", "(", "_cp", ")", ";", "_out", ".", "println", "(", "\"", "il.append(_factory.createReturn(", "\"", "+", "BCELifier", ".", "printType", "(", "type", ")", "+", "\"", "));", "\"", ")", ";", "}", "private", "ArrayList", "branches", "=", "new", "ArrayList", "(", ")", ";", "public", "void", "visitBranchInstruction", "(", "BranchInstruction", "bi", ")", "{", "BranchHandle", "bh", "=", "(", "BranchHandle", ")", "branch_map", ".", "get", "(", "bi", ")", ";", "int", "pos", "=", "bh", ".", "getPosition", "(", ")", ";", "String", "name", "=", "bi", ".", "getName", "(", ")", "+", "\"", "_", "\"", "+", "pos", ";", "if", "(", "bi", "instanceof", "Select", ")", "{", "Select", "s", "=", "(", "Select", ")", "bi", ";", "branches", ".", "add", "(", "bi", ")", ";", "StringBuffer", "args", "=", "new", "StringBuffer", "(", "\"", "new int[] { ", "\"", ")", ";", "int", "[", "]", "matchs", "=", "s", ".", "getMatchs", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "matchs", ".", "length", ";", "i", "++", ")", "{", "args", ".", "append", "(", "matchs", "[", "i", "]", ")", ";", "if", "(", "i", "<", "matchs", ".", "length", "-", "1", ")", "args", ".", "append", "(", "\"", ", ", "\"", ")", ";", "}", "args", ".", "append", "(", "\"", " }", "\"", ")", ";", "_out", ".", "print", "(", "\"", " Select ", "\"", "+", "name", "+", "\"", " = new ", "\"", "+", "bi", ".", "getName", "(", ")", ".", "toUpperCase", "(", ")", "+", "\"", "(", "\"", "+", "args", "+", "\"", ", new InstructionHandle[] { ", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "matchs", ".", "length", ";", "i", "++", ")", "{", "_out", ".", "print", "(", "\"", "null", "\"", ")", ";", "if", "(", "i", "<", "matchs", ".", "length", "-", "1", ")", "_out", ".", "print", "(", "\"", ", ", "\"", ")", ";", "}", "_out", ".", "println", "(", "\"", ");", "\"", ")", ";", "}", "else", "{", "int", "t_pos", "=", "bh", ".", "getTarget", "(", ")", ".", "getPosition", "(", ")", ";", "String", "target", ";", "if", "(", "pos", ">", "t_pos", ")", "{", "target", "=", "\"", "ih_", "\"", "+", "t_pos", ";", "}", "else", "{", "branches", ".", "add", "(", "bi", ")", ";", "target", "=", "\"", "null", "\"", ";", "}", "_out", ".", "println", "(", "\"", " BranchInstruction ", "\"", "+", "name", "+", "\"", " = _factory.createBranchInstruction(", "\"", "+", "\"", "Constants.", "\"", "+", "bi", ".", "getName", "(", ")", ".", "toUpperCase", "(", ")", "+", "\"", ", ", "\"", "+", "target", "+", "\"", ");", "\"", ")", ";", "}", "if", "(", "bh", ".", "hasTargeters", "(", ")", ")", "_out", ".", "println", "(", "\"", " ih_", "\"", "+", "pos", "+", "\"", " = il.append(", "\"", "+", "name", "+", "\"", ");", "\"", ")", ";", "else", "_out", ".", "println", "(", "\"", " il.append(", "\"", "+", "name", "+", "\"", ");", "\"", ")", ";", "}", "public", "void", "visitRET", "(", "RET", "i", ")", "{", "_out", ".", "println", "(", "\"", "il.append(new RET(", "\"", "+", "i", ".", "getIndex", "(", ")", "+", "\"", ")));", "\"", ")", ";", "}", "private", "void", "updateBranchTargets", "(", ")", "{", "for", "(", "Iterator", "i", "=", "branches", ".", "iterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "BranchInstruction", "bi", "=", "(", "BranchInstruction", ")", "i", ".", "next", "(", ")", ";", "BranchHandle", "bh", "=", "(", "BranchHandle", ")", "branch_map", ".", "get", "(", "bi", ")", ";", "int", "pos", "=", "bh", ".", "getPosition", "(", ")", ";", "String", "name", "=", "bi", ".", "getName", "(", ")", "+", "\"", "_", "\"", "+", "pos", ";", "int", "t_pos", "=", "bh", ".", "getTarget", "(", ")", ".", "getPosition", "(", ")", ";", "_out", ".", "println", "(", "\"", " ", "\"", "+", "name", "+", "\"", ".setTarget(ih_", "\"", "+", "t_pos", "+", "\"", ");", "\"", ")", ";", "if", "(", "bi", "instanceof", "Select", ")", "{", "InstructionHandle", "[", "]", "ihs", "=", "(", "(", "Select", ")", "bi", ")", ".", "getTargets", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "ihs", ".", "length", ";", "j", "++", ")", "{", "t_pos", "=", "ihs", "[", "j", "]", ".", "getPosition", "(", ")", ";", "_out", ".", "println", "(", "\"", " ", "\"", "+", "name", "+", "\"", ".setTarget(", "\"", "+", "j", "+", "\"", ", ih_", "\"", "+", "t_pos", "+", "\"", ");", "\"", ")", ";", "}", "}", "}", "}", "private", "void", "updateExceptionHandlers", "(", ")", "{", "CodeExceptionGen", "[", "]", "handlers", "=", "_mg", ".", "getExceptionHandlers", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "handlers", ".", "length", ";", "i", "++", ")", "{", "CodeExceptionGen", "h", "=", "handlers", "[", "i", "]", ";", "String", "type", "=", "(", "h", ".", "getCatchType", "(", ")", "==", "null", ")", "?", "\"", "null", "\"", ":", "BCELifier", ".", "printType", "(", "h", ".", "getCatchType", "(", ")", ")", ";", "_out", ".", "println", "(", "\"", " method.addExceptionHandler(", "\"", "+", "\"", "ih_", "\"", "+", "h", ".", "getStartPC", "(", ")", ".", "getPosition", "(", ")", "+", "\"", ", ", "\"", "+", "\"", "ih_", "\"", "+", "h", ".", "getEndPC", "(", ")", ".", "getPosition", "(", ")", "+", "\"", ", ", "\"", "+", "\"", "ih_", "\"", "+", "h", ".", "getHandlerPC", "(", ")", ".", "getPosition", "(", ")", "+", "\"", ", ", "\"", "+", "type", "+", "\"", ");", "\"", ")", ";", "}", "}", "}" ]
Factory creates il.append() statements, and sets instruction targets.
[ "Factory", "creates", "il", ".", "append", "()", "statements", "and", "sets", "instruction", "targets", "." ]
[ "// Map<Instruction, InstructionHandle>", "// memorize container", "// Handled below", "// Memorize BranchInstructions that need an update" ]
[ { "param": "EmptyVisitor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EmptyVisitor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4fe8b6fe7ffe090a5a194139ac965f9630865e21
Jelly-Fish/jellyfish
src/main/java/fr/com/jellyfish/jfgjellyfishchess/jellyfishchess/jellyfish/constants/CommonConst.java
[ "BSD-3-Clause" ]
Java
CommonConst
/** * General constants. * @author Thomas Warner 2014 */
General constants. @author Thomas Warner 2014
[ "General", "constants", ".", "@author", "Thomas", "Warner", "2014" ]
public class CommonConst { /** * Path to chessmen entities package. */ public static final String CHESSMEN_PACKAGE = "fr.com.jellyfish.jfgjellyfishchess.jellyfishchess.jellyfish.entities.chessmen"; /** * String value of "white". */ public static final String WHITE_STR = "white"; /** * String value of "black". */ public static final String BLACK_STR = "black"; /** * A dummy char. */ public static final char DUMMY = '£'; /** * Back slash n : \n. */ public static final String BACKSLASH_N = "\n"; /** * @ as a string. */ public static final String AT = "@"; /** * Up dash. */ public static final String UPPER_DASH = "-"; /** * R.I.P. */ public static final String REST_IN_PEACE = "R.I.P"; /** * Empty string. */ public static final String EMPTY_STR = ""; /** * Space string. */ public static final String SPACE_STR = " "; /** * Dot string. */ public static final String DOT = "."; /** * Space string. */ public static final String SEARCH_BESTMOVE = "bestmove "; /** * Space string. */ public static final String SEARCH_PONDER = " ponder"; /** * char == u. */ public static final char U_CHAR_LOWERCASE = 'u'; /** * char == d. */ public static final char D_CHAR_LOWERCASE = 'd'; /** * char == l. */ public static final char L_CHAR_LOWERCASE = 'l'; /** * char == r. */ public static final char R_CHAR_LOWERCASE = 'r'; /** * Word queen as string. */ public static final String STR_QUEEN = "queen"; /** * Word bishop as string. */ public static final String STR_BISHOP = "bishop"; /** * Word knight as string. */ public static final String STR_KNIGHT = "knight"; /** * Word rook as string. */ public static final String STR_ROOK = "rook"; /** * Word king as string. */ public static final String STR_KING = "king"; /** * Word pawn as string. */ public static final String STR_PAWN = "pawn"; /** * Move count display prefix. */ public static final String MOVE_COUNT = "Move count: "; /** * In check king display prefix. */ public static final String IN_CHECK_DISPLAY = "In check: "; /** * Promotion display prefix for pawns. */ public static final String PROMOTION_DISPLAY = "Promotion type: "; /** * String value of ":". */ public static final String DOTS = ":"; /** * String representation for 0 (zero number). */ public static final String ZERO_STR = "0"; }
[ "public", "class", "CommonConst", "{", "/**\r\n * Path to chessmen entities package.\r\n */", "public", "static", "final", "String", "CHESSMEN_PACKAGE", "=", "\"", "fr.com.jellyfish.jfgjellyfishchess.jellyfishchess.jellyfish.entities.chessmen", "\"", ";", "/**\r\n * String value of \"white\".\r\n */", "public", "static", "final", "String", "WHITE_STR", "=", "\"", "white", "\"", ";", "/**\r\n * String value of \"black\".\r\n */", "public", "static", "final", "String", "BLACK_STR", "=", "\"", "black", "\"", ";", "/**\r\n * A dummy char.\r\n */", "public", "static", "final", "char", "DUMMY", "=", "'£';", "\r", "/**\r\n * Back slash n : \\n.\r\n */", "public", "static", "final", "String", "BACKSLASH_N", "=", "\"", "\\n", "\"", ";", "/**\r\n * @ as a string.\r\n */", "public", "static", "final", "String", "AT", "=", "\"", "@", "\"", ";", "/**\r\n * Up dash.\r\n */", "public", "static", "final", "String", "UPPER_DASH", "=", "\"", "-", "\"", ";", "/**\r\n * R.I.P.\r\n */", "public", "static", "final", "String", "REST_IN_PEACE", "=", "\"", "R.I.P", "\"", ";", "/**\r\n * Empty string.\r\n */", "public", "static", "final", "String", "EMPTY_STR", "=", "\"", "\"", ";", "/**\r\n * Space string.\r\n */", "public", "static", "final", "String", "SPACE_STR", "=", "\"", " ", "\"", ";", "/**\r\n * Dot string.\r\n */", "public", "static", "final", "String", "DOT", "=", "\"", ".", "\"", ";", "/**\r\n * Space string.\r\n */", "public", "static", "final", "String", "SEARCH_BESTMOVE", "=", "\"", "bestmove ", "\"", ";", "/**\r\n * Space string.\r\n */", "public", "static", "final", "String", "SEARCH_PONDER", "=", "\"", " ponder", "\"", ";", "/**\r\n * char == u.\r\n */", "public", "static", "final", "char", "U_CHAR_LOWERCASE", "=", "'u'", ";", "/**\r\n * char == d.\r\n */", "public", "static", "final", "char", "D_CHAR_LOWERCASE", "=", "'d'", ";", "/**\r\n * char == l.\r\n */", "public", "static", "final", "char", "L_CHAR_LOWERCASE", "=", "'l'", ";", "/**\r\n * char == r.\r\n */", "public", "static", "final", "char", "R_CHAR_LOWERCASE", "=", "'r'", ";", "/**\r\n * Word queen as string.\r\n */", "public", "static", "final", "String", "STR_QUEEN", "=", "\"", "queen", "\"", ";", "/**\r\n * Word bishop as string.\r\n */", "public", "static", "final", "String", "STR_BISHOP", "=", "\"", "bishop", "\"", ";", "/**\r\n * Word knight as string.\r\n */", "public", "static", "final", "String", "STR_KNIGHT", "=", "\"", "knight", "\"", ";", "/**\r\n * Word rook as string.\r\n */", "public", "static", "final", "String", "STR_ROOK", "=", "\"", "rook", "\"", ";", "/**\r\n * Word king as string.\r\n */", "public", "static", "final", "String", "STR_KING", "=", "\"", "king", "\"", ";", "/**\r\n * Word pawn as string.\r\n */", "public", "static", "final", "String", "STR_PAWN", "=", "\"", "pawn", "\"", ";", "/**\r\n * Move count display prefix.\r\n */", "public", "static", "final", "String", "MOVE_COUNT", "=", "\"", "Move count: ", "\"", ";", "/**\r\n * In check king display prefix.\r\n */", "public", "static", "final", "String", "IN_CHECK_DISPLAY", "=", "\"", "In check: ", "\"", ";", "/**\r\n * Promotion display prefix for pawns.\r\n */", "public", "static", "final", "String", "PROMOTION_DISPLAY", "=", "\"", "Promotion type: ", "\"", ";", "/**\r\n * String value of \":\".\r\n */", "public", "static", "final", "String", "DOTS", "=", "\"", ":", "\"", ";", "/**\r\n * String representation for 0 (zero number).\r\n */", "public", "static", "final", "String", "ZERO_STR", "=", "\"", "0", "\"", ";", "}" ]
General constants.
[ "General", "constants", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4fec3332bcf125b2d6bc55eb4bf6cb49438b7e31
lpcsmath/QTReader
src/main/java/de/csmath/QT/QTAtom.java
[ "MIT" ]
Java
QTAtom
/** * This class represents an atom of a QuickTime file. * @author lpfeiler */
This class represents an atom of a QuickTime file. @author lpfeiler
[ "This", "class", "represents", "an", "atom", "of", "a", "QuickTime", "file", ".", "@author", "lpfeiler" ]
public class QTAtom { /** * The brand 'qt ' indicates a QuickTime file. */ public final static int QT = 0x71742020; //'qt ' /** * The atom type 'ftyp' */ public final static int FTYP = 0x66747970; //'ftyp' /** * The atom container type 'moov' */ public final static int MOOV = 0x6D6F6F76; //'moov' /** * The atom type 'mvhd' */ public final static int MVHD = 0x6D766864; //'mvhd' /** * The atom container type 'trak' */ public final static int TRAK = 0x7472616B; //'trak' /** * The atom container type 'mdia' */ public final static int MDIA = 0x6D646961; //'mdia' /** * The atom container type 'minf' */ public final static int MINF = 0x6D696E66; //'minf' /** * The atom container type 'stbl' */ public final static int STBL = 0x7374626C; //'stbl' /** * The atom type 'stsd' */ public final static int STSD = 0x73747364; //'stsd' /** * The video sample desc. extension type 'colr' */ public final static int COLR = 0x636F6C72; //'colr' /** * The video sample desc. extension type 'avcC' */ public final static int AVCC = 0x61766343; //'avcC' /** * The size of the atom in the file. */ private final int size; /** * The type of the atom. */ private final int type; /** * The contents of the atom (if not further specified). */ private final byte[] contents; /** * Constructs a QTAtom * @param size the size of the atom in the file * @param type the type of the atom */ public QTAtom(int size, int type) { this.size = size; this.type = type; this.contents = null; } /** * Constructs a QTAtom * @param size the size of the atom in the file * @param type the type of the atom * @param contents the contents of the atom */ public QTAtom(int size, int type, byte[] contents) { this.size = size; this.type = type; if (contents.length != (size - 8)) throw new IllegalArgumentException("contents size mismatch"); this.contents = Arrays.copyOf(contents,contents.length); } /** * Returns the size of the atom in the file. * @return the size of the atom in the file */ public int getSize() { return size; } /** * Returns the type of the atom. * @return the type of the atom */ public int getType() { return type; } /** * Returns an iterator over the contents of the atom. * @return an iterator over the contents of the atom */ public Iterator<Byte> getContentsIterator() { return new ContentsIterator(); } /** * Returns the type as a string * @return the type as a string */ protected String typeAsString() { StringBuilder sb = new StringBuilder(); sb.append((char)(type >> 24)); sb.append((char)((type >> 16) & 0xFF)); sb.append((char)((type >> 8) & 0xFF)); sb.append((char)(type & 0xFF)); return sb.toString(); } @Override public String toString() { StringBuffer sb = new StringBuffer(this.getClass().getName() + ": ") .append("(") .append(getSize()) .append(", ") .append(typeAsString()) .append(")"); return sb.toString(); } /** * This class is an iterator over the contents of the atom. */ private class ContentsIterator implements Iterator<Byte> { /** * The current index of the array. */ int index = 0; @Override public boolean hasNext() { return index < contents.length; } @Override public java.lang.Byte next() { return contents[index++]; } } }
[ "public", "class", "QTAtom", "{", "/**\n * The brand 'qt ' indicates a QuickTime file.\n */", "public", "final", "static", "int", "QT", "=", "0x71742020", ";", "/**\n * The atom type 'ftyp'\n */", "public", "final", "static", "int", "FTYP", "=", "0x66747970", ";", "/**\n * The atom container type 'moov'\n */", "public", "final", "static", "int", "MOOV", "=", "0x6D6F6F76", ";", "/**\n * The atom type 'mvhd'\n */", "public", "final", "static", "int", "MVHD", "=", "0x6D766864", ";", "/**\n * The atom container type 'trak'\n */", "public", "final", "static", "int", "TRAK", "=", "0x7472616B", ";", "/**\n * The atom container type 'mdia'\n */", "public", "final", "static", "int", "MDIA", "=", "0x6D646961", ";", "/**\n * The atom container type 'minf'\n */", "public", "final", "static", "int", "MINF", "=", "0x6D696E66", ";", "/**\n * The atom container type 'stbl'\n */", "public", "final", "static", "int", "STBL", "=", "0x7374626C", ";", "/**\n * The atom type 'stsd'\n */", "public", "final", "static", "int", "STSD", "=", "0x73747364", ";", "/**\n * The video sample desc. extension type 'colr'\n */", "public", "final", "static", "int", "COLR", "=", "0x636F6C72", ";", "/**\n * The video sample desc. extension type 'avcC'\n */", "public", "final", "static", "int", "AVCC", "=", "0x61766343", ";", "/**\n * The size of the atom in the file.\n */", "private", "final", "int", "size", ";", "/**\n * The type of the atom.\n */", "private", "final", "int", "type", ";", "/**\n * The contents of the atom (if not further specified).\n */", "private", "final", "byte", "[", "]", "contents", ";", "/**\n * Constructs a QTAtom\n * @param size the size of the atom in the file\n * @param type the type of the atom\n */", "public", "QTAtom", "(", "int", "size", ",", "int", "type", ")", "{", "this", ".", "size", "=", "size", ";", "this", ".", "type", "=", "type", ";", "this", ".", "contents", "=", "null", ";", "}", "/**\n * Constructs a QTAtom\n * @param size the size of the atom in the file\n * @param type the type of the atom\n * @param contents the contents of the atom\n */", "public", "QTAtom", "(", "int", "size", ",", "int", "type", ",", "byte", "[", "]", "contents", ")", "{", "this", ".", "size", "=", "size", ";", "this", ".", "type", "=", "type", ";", "if", "(", "contents", ".", "length", "!=", "(", "size", "-", "8", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "contents size mismatch", "\"", ")", ";", "this", ".", "contents", "=", "Arrays", ".", "copyOf", "(", "contents", ",", "contents", ".", "length", ")", ";", "}", "/**\n * Returns the size of the atom in the file.\n * @return the size of the atom in the file\n */", "public", "int", "getSize", "(", ")", "{", "return", "size", ";", "}", "/**\n * Returns the type of the atom.\n * @return the type of the atom\n */", "public", "int", "getType", "(", ")", "{", "return", "type", ";", "}", "/**\n * Returns an iterator over the contents of the atom.\n * @return an iterator over the contents of the atom\n */", "public", "Iterator", "<", "Byte", ">", "getContentsIterator", "(", ")", "{", "return", "new", "ContentsIterator", "(", ")", ";", "}", "/**\n * Returns the type as a string\n * @return the type as a string\n */", "protected", "String", "typeAsString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "(", "char", ")", "(", "type", ">>", "24", ")", ")", ";", "sb", ".", "append", "(", "(", "char", ")", "(", "(", "type", ">>", "16", ")", "&", "0xFF", ")", ")", ";", "sb", ".", "append", "(", "(", "char", ")", "(", "(", "type", ">>", "8", ")", "&", "0xFF", ")", ")", ";", "sb", ".", "append", "(", "(", "char", ")", "(", "type", "&", "0xFF", ")", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\"", ": ", "\"", ")", ".", "append", "(", "\"", "(", "\"", ")", ".", "append", "(", "getSize", "(", ")", ")", ".", "append", "(", "\"", ", ", "\"", ")", ".", "append", "(", "typeAsString", "(", ")", ")", ".", "append", "(", "\"", ")", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * This class is an iterator over the contents of the atom.\n */", "private", "class", "ContentsIterator", "implements", "Iterator", "<", "Byte", ">", "{", "/**\n * The current index of the array.\n */", "int", "index", "=", "0", ";", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "return", "index", "<", "contents", ".", "length", ";", "}", "@", "Override", "public", "java", ".", "lang", ".", "Byte", "next", "(", ")", "{", "return", "contents", "[", "index", "++", "]", ";", "}", "}", "}" ]
This class represents an atom of a QuickTime file.
[ "This", "class", "represents", "an", "atom", "of", "a", "QuickTime", "file", "." ]
[ "//'qt '", "//'ftyp'", "//'moov'", "//'mvhd'", "//'trak'", "//'mdia'", "//'minf'", "//'stbl'", "//'stsd'", "//'colr'", "//'avcC'" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4fec3332bcf125b2d6bc55eb4bf6cb49438b7e31
lpcsmath/QTReader
src/main/java/de/csmath/QT/QTAtom.java
[ "MIT" ]
Java
ContentsIterator
/** * This class is an iterator over the contents of the atom. */
This class is an iterator over the contents of the atom.
[ "This", "class", "is", "an", "iterator", "over", "the", "contents", "of", "the", "atom", "." ]
private class ContentsIterator implements Iterator<Byte> { /** * The current index of the array. */ int index = 0; @Override public boolean hasNext() { return index < contents.length; } @Override public java.lang.Byte next() { return contents[index++]; } }
[ "private", "class", "ContentsIterator", "implements", "Iterator", "<", "Byte", ">", "{", "/**\n * The current index of the array.\n */", "int", "index", "=", "0", ";", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "return", "index", "<", "contents", ".", "length", ";", "}", "@", "Override", "public", "java", ".", "lang", ".", "Byte", "next", "(", ")", "{", "return", "contents", "[", "index", "++", "]", ";", "}", "}" ]
This class is an iterator over the contents of the atom.
[ "This", "class", "is", "an", "iterator", "over", "the", "contents", "of", "the", "atom", "." ]
[]
[ { "param": "Iterator<Byte>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Iterator<Byte>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4fec45a60917259c24cc06468c623e980729641d
albangaignard/galaxy-PROV
galaxy-PROV/src/main/java/fr/univnantes/galaxyld/Util.java
[ "MIT" ]
Java
Util
/** * * @author Alban Gaignard <alban.gaignard@univ-nantes.fr> */
@author Alban Gaignard
[ "@author", "Alban", "Gaignard" ]
public class Util { private static Logger logger = Logger.getLogger(Util.class); public static String provPrefix = "http://www.w3.org/ns/prov#"; public static String dataPrefix = "http://data.symetric.org/"; public static void jsonPP(String json) { Gson gson = new Gson(); Object ob = gson.fromJson(json, Object.class ); logger.info(new GsonBuilder().setPrettyPrinting().create().toJson(ob)); } public static String getProperty(String key) throws GalaxyProvenanceException { Properties prop = new Properties(); InputStream input = null; try { input = Util.class.getClassLoader().getResourceAsStream("config.properties"); prop.load(input); return prop.getProperty(key); } catch (IOException ex) { throw new GalaxyProvenanceException("Impossible to retrieve configuration from config.properties"); } finally { if (input != null) { try { input.close(); } catch (IOException e) { throw new GalaxyProvenanceException("Impossible to retrieve configuration from config.properties"); } } } } private static String output(InputStream inputStream) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = br.readLine()) != null) { sb.append(line + System.getProperty("line.separator")); } } finally { br.close(); } return sb.toString(); } public static String htmlOutTemplate = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + " <script type=\"text/javascript\" src=\"http://mbostock.github.com/d3/d3.js\"></script>\n" + " <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n" + " <style media=\"screen\" type=\"text/css\">\n" + " .node text {\n" + " /*pointer-events: none;*/\n" + " font: 10px sans-serif;\n" + " }\n" + " .link {\n" + " stroke: #999;\n" // + " stroke-opacity: .6;\n" + " fill: none;\n" + " }\n" + " .arrow {\n" + " stroke: #999;\n" + " stroke-width: 2;\n" + " fill: #999;\n" // + " stroke-opacity: .6;\n" + " }\n" + " .text {\n" + " fill: #000;\n" + " font: 10px sans-serif;\n" + " pointer-events: none;\n" + " }\n" + " </style>\n" + "</head>" + "<body>\n" + " <div id=\"viz\"></div>\n" + " <script type=\"text/javascript\">\n" + "\n" + "data = **jsonData** ;\n" + "renderD3(data, \"#viz\"); \n" + "function renderD3(data, htmlCompId) {\n" + " var d3Data = data.d3;\n" + " var mappings = data.mappings;\n" + " var sMaps = JSON.stringify(mappings);\n" + "\n" + " var width = $(htmlCompId).parent().width();\n" + "// var height = $(\"svg\").parent().height();\n" + " var height = 600;\n" + " var color = d3.scale.category20();\n" + "\n" + " var force = d3.layout.force()\n" + " .charge(-300)\n" + " .linkDistance(100)\n" + " .friction(.8)\n" + " .size([width, height]);\n" + "\n" + " var svg = d3.select(htmlCompId).append(\"svg\")\n" + "// .attr(\"width\", width)\n" + "// .attr(\"height\", height)\n" + " .attr(\"viewBox\", \"0 0 600 600\")\n" + " .attr(\"width\", \"100%\")\n" + " .attr(\"height\", 600)\n" + " .attr(\"preserveAspectRatio\", \"xMidYMid\")\n" + " .style(\"background-color\", \"#F4F2F5\");\n" + "// build the arrow.\n" + " svg.append(\"svg:defs\").selectAll(\"marker\")\n" + " .data([\"end\"]) // Different link/path types can be defined here\n" + " .enter().append(\"svg:marker\") // This section adds in the arrows\n" + " .attr(\"id\", String)\n" + " .attr(\"viewBox\", \"0 -5 10 10\")\n" + " .attr(\"refX\", 21)\n" + " .attr(\"refY\", -1.5)\n" + " .attr(\"markerWidth\", 4)\n" + " .attr(\"markerHeight\", 4)\n" + " .attr(\"orient\", \"auto\")\n" + " .attr(\"class\", \"arrow\")\n" + " .append(\"svg:path\")\n" + " .attr(\"d\", \"M0,-5L10,0L0,5\");" + "\n" + " force.nodes(d3Data.nodes).links(d3Data.edges).start();\n" + "\n" + " var link = svg.selectAll(\".link\")\n" + " .data(d3Data.edges)\n" + " .enter().append(\"path\")\n" + " .attr(\"d\", \"M0,-5L10,0L0,5\")\n" + " // .enter().append(\"line\")\n" + " .attr(\"class\", \"link\")\n" + " .attr(\"marker-end\", \"url(#end)\")\n" + " .style(\"stroke-width\", function(d) {\n" + " if (d.label.indexOf(\"prov#\") !== -1) {\n" + " return 3;\n" + " }\n" + " return 3;\n" + " });\n" // + " .on(\"mouseout\", function(d, i) {\n" // + " d3.select(this).style(\"stroke\", \" #a0a0a0\");\n" // + " })\n" // + " .on(\"mouseover\", function(d, i) {\n" // + " d3.select(this).style(\"stroke\", \" #000000\");\n" // + " });\n" + "\n" + " link.append(\"title\")\n" + " .text(function(d) {\n" + " return d.label;\n" + " });\n" + "\n" + "\n" + " var node_drag = d3.behavior.drag()\n" + " .on(\"dragstart\", dragstart)\n" + " .on(\"drag\", dragmove)\n" + " .on(\"dragend\", dragend);\n" + "\n" + " function dragstart(d, i) {\n" + " force.stop() // stops the force auto positioning before you start dragging\n" + " }\n" + "\n" + " function dragmove(d, i) {\n" + " d.px += d3.event.dx;\n" + " d.py += d3.event.dy;\n" + " d.x += d3.event.dx;\n" + " d.y += d3.event.dy;\n" + " tick(); // this is the key to make it work together with updating both px,py,x,y on d !\n" + " }\n" + "\n" + " function dragend(d, i) {\n" + " d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff\n" + " tick();\n" + " force.resume();\n" + " }\n" + "\n" + " var node = svg.selectAll(\"g.node\")\n" + " .data(d3Data.nodes)\n" + " .enter().append(\"g\")\n" + " .attr(\"class\", \"node\")\n" + " // .call(force.drag);\n" + " .call(node_drag);\n" + "\n" + " node.append(\"title\")\n" + " .text(function(d) {\n" + " return d.name;\n" + " });\n" + "\n" + " node.append(\"circle\")\n" + " .attr(\"class\", \"node\")\n" + " .attr(\"r\", function(d) {\n" + " if (d.group === 0) {\n" + " return 6;\n" + " }\n" + " return 12;\n" + " })\n" + " .on(\"dblclick\", function(d) {\n" + " d.fixed = false;\n" + " })\n" + " .on(\"mouseover\", fade(.1)).on(\"mouseout\", fade(1))\n" + " .style(\"stroke\", function(d) {\n" + " return color(d.group);\n" + " })\n" + " .style(\"stroke\", \"#F4F2F5\")\n" + " .style(\"stroke-width\", 2)\n" // + " .style(\"stroke-width\", function(d) {\n" // + " if (sMaps.indexOf(d.name) !== -1) {\n" // + " return 8;\n" // + " }\n" // + " return 3;\n" // + " })\n" + " // .style(\"stroke-dasharray\",function(d) {\n" + " // if (sMaps.indexOf(d.name) !== -1) {\n" + " // return \"5,5\";\n" + " // }\n" + " // return \"none\";\n" + " // })\n" + " // .style(\"fill\", \"white\")\n" + " .style(\"fill\", function(d) {\n" + " return color(d.group);\n" + " });\n" + " // .on(\"mouseout\", function(d, i) {\n" + " // d3.select(this).style(\"fill\", \"white\");\n" + " // })\n" + " // .on(\"mouseover\", function(d, i) {\n" + " // d3.select(this).style(\"fill\", function(d) { return color(d.group); });\n" + " // }) ;\n" + "\n" + "node.append(\"text\")\n" + " .attr(\"x\", 20)\n" + " .attr(\"dy\", \".35em\")\n" + " .text(function(d) { \n" + " return d.name ;\n" + " });" + "\n" + " var linkedByIndex = {};\n" + " d3Data.edges.forEach(function(d) {\n" + " linkedByIndex[d.source.index + \",\" + d.target.index] = 1;\n" + " });\n" + "\n" + " function isConnected(a, b) {\n" + " return linkedByIndex[a.index + \",\" + b.index] || linkedByIndex[b.index + \",\" + a.index] || a.index === b.index;\n" + " }\n" + "\n" + " force.on(\"tick\", tick);\n" + "\n" + " function tick() {\n" + " link.attr(\"x1\", function(d) {\n" + " return d.source.x;\n" + " })\n" + " .attr(\"y1\", function(d) {\n" + " return d.source.y;\n" + " })\n" + " .attr(\"x2\", function(d) {\n" + " return d.target.x;\n" + " })\n" + " .attr(\"y2\", function(d) {\n" + " return d.target.y;\n" + " });\n" + "\n" + " node.attr(\"transform\", function(d) {\n" + " return \"translate(\" + d.x + \",\" + d.y + \")\";\n" + " });\n" + "\n" + " link.attr(\"d\", function(d) {\n" + " var dx = d.target.x - d.source.x,\n" + " dy = d.target.y - d.source.y,\n" + " dr = Math.sqrt(dx * dx + dy * dy);\n" + "\n" + " return \"M\" + d.source.x + \",\" + d.source.y + \"A\" + dr + \",\" + dr + \" 0 0,1 \" + d.target.x + \",\" + d.target.y;\n" + " });\n" + " }\n" + " ;\n" + "\n" + " function fade(opacity) {\n" + " return function(d) {\n" + " node.style(\"opacity\", function(o) {\n" + " thisOpacity = isConnected(d, o) ? 1 : opacity;\n" + " this.setAttribute('fill-opacity', thisOpacity);\n" + " return thisOpacity;\n" + " });\n" + "\n" + " link.style(\"opacity\", function(o) {\n" + " return o.source === d || o.target === d ? 1 : opacity;\n" + " });\n" + "\n" + " };\n" + " }\n" + "}" + " </script>\n" + "</body>\n" + "</html>"; public static String genHtmlViz(String jsonData) { String out = htmlOutTemplate.replaceAll(Pattern.quote("**jsonData**"), jsonData); return out; } public static String simulateWfExec(Workflow wf) { StringBuilder toDOT = new StringBuilder(); StringBuilder toPROV = new StringBuilder(); toDOT.append("digraph G {\n"); toPROV.append("PREFIX prov:<" + Util.provPrefix + "> insert data {\n"); for (Step s : wf.getSteps().values()) { String step = "A" + s.getId() + "_" + s.getName().replaceAll(":", "").replaceAll(" ", "").replaceAll("/", ""); toDOT.append("\t" + step + " [shape=box]\n"); toPROV.append("<" + Util.dataPrefix + step + "> rdf:type prov:Activity . \n"); for (Output o : s.getOutputs()) { // create produced data String data = "D" + s.getId() + "_" + o.getName(); toDOT.append("\t" + data + " [shape=box]\n"); toDOT.append("\t" + data + " -> " + step + "\n"); toPROV.append("<" + Util.dataPrefix + data + "> rdf:type prov:Entity ; \n"); toPROV.append("\t prov:wasGeneratedBy <" + Util.dataPrefix + step + "> . \n"); for (String k : s.getInput_connections().keySet()) { //iterate over list of outputs ? // for (Connection c : s.getInput_connections().get(k)) { // // String origData = "D" + c.getId() + "_" + c.getOutput_name(); //// // create data lineage // toDOT.append("\t" + data + " -> " + origData + "[style=\"dotted\"]\n"); // toPROV.append("<" + Util.dataPrefix + data + "> prov:wasDerivedFrom <" + Util.dataPrefix + origData + "> . \n"); // } String origData = "D" + s.getInput_connections().get(k).getId() + "_" + s.getInput_connections().get(k).getOutput_name(); // create data lineage toDOT.append("\t" + data + " -> " + origData + "[style=\"dotted\"]\n"); toPROV.append("<" + Util.dataPrefix + data + "> prov:wasDerivedFrom <" + Util.dataPrefix + origData + "> . \n"); } } } toPROV.append("}\n"); toDOT.append("}\n"); // return toDOT.toString(); return toPROV.toString(); } }
[ "public", "class", "Util", "{", "private", "static", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "Util", ".", "class", ")", ";", "public", "static", "String", "provPrefix", "=", "\"", "http://www.w3.org/ns/prov#", "\"", ";", "public", "static", "String", "dataPrefix", "=", "\"", "http://data.symetric.org/", "\"", ";", "public", "static", "void", "jsonPP", "(", "String", "json", ")", "{", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", "Object", "ob", "=", "gson", ".", "fromJson", "(", "json", ",", "Object", ".", "class", ")", ";", "logger", ".", "info", "(", "new", "GsonBuilder", "(", ")", ".", "setPrettyPrinting", "(", ")", ".", "create", "(", ")", ".", "toJson", "(", "ob", ")", ")", ";", "}", "public", "static", "String", "getProperty", "(", "String", "key", ")", "throws", "GalaxyProvenanceException", "{", "Properties", "prop", "=", "new", "Properties", "(", ")", ";", "InputStream", "input", "=", "null", ";", "try", "{", "input", "=", "Util", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "\"", "config.properties", "\"", ")", ";", "prop", ".", "load", "(", "input", ")", ";", "return", "prop", ".", "getProperty", "(", "key", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "GalaxyProvenanceException", "(", "\"", "Impossible to retrieve configuration from config.properties", "\"", ")", ";", "}", "finally", "{", "if", "(", "input", "!=", "null", ")", "{", "try", "{", "input", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "GalaxyProvenanceException", "(", "\"", "Impossible to retrieve configuration from config.properties", "\"", ")", ";", "}", "}", "}", "}", "private", "static", "String", "output", "(", "InputStream", "inputStream", ")", "throws", "IOException", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "BufferedReader", "br", "=", "null", ";", "try", "{", "br", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "inputStream", ")", ")", ";", "String", "line", "=", "null", ";", "while", "(", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "sb", ".", "append", "(", "line", "+", "System", ".", "getProperty", "(", "\"", "line.separator", "\"", ")", ")", ";", "}", "}", "finally", "{", "br", ".", "close", "(", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "public", "static", "String", "htmlOutTemplate", "=", "\"", "<!DOCTYPE html>", "\\n", "\"", "+", "\"", "<html>", "\\n", "\"", "+", "\"", "<head>", "\\n", "\"", "+", "\"", " <script type=", "\\\"", "text/javascript", "\\\"", " src=", "\\\"", "http://mbostock.github.com/d3/d3.js", "\\\"", "></script>", "\\n", "\"", "+", "\"", " <script src=", "\\\"", "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", "\\\"", "></script>", "\\n", "\"", "+", "\"", " <style media=", "\\\"", "screen", "\\\"", " type=", "\\\"", "text/css", "\\\"", ">", "\\n", "\"", "+", "\"", " .node text {", "\\n", "\"", "+", "\"", " /*pointer-events: none;*/", "\\n", "\"", "+", "\"", " font: 10px sans-serif;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " .link {", "\\n", "\"", "+", "\"", " stroke: #999;", "\\n", "\"", "+", "\"", " fill: none;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " .arrow {", "\\n", "\"", "+", "\"", " stroke: #999;", "\\n", "\"", "+", "\"", " stroke-width: 2;", "\\n", "\"", "+", "\"", " fill: #999;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " .text {", "\\n", "\"", "+", "\"", " fill: #000;", "\\n", "\"", "+", "\"", " font: 10px sans-serif;", "\\n", "\"", "+", "\"", " pointer-events: none;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " </style>", "\\n", "\"", "+", "\"", "</head>", "\"", "+", "\"", "<body>", "\\n", "\"", "+", "\"", " <div id=", "\\\"", "viz", "\\\"", "></div>", "\\n", "\"", "+", "\"", " <script type=", "\\\"", "text/javascript", "\\\"", ">", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "data = **jsonData** ;", "\\n", "\"", "+", "\"", "renderD3(data, ", "\\\"", "#viz", "\\\"", "); ", "\\n", "\"", "+", "\"", "function renderD3(data, htmlCompId) {", "\\n", "\"", "+", "\"", " var d3Data = data.d3;", "\\n", "\"", "+", "\"", " var mappings = data.mappings;", "\\n", "\"", "+", "\"", " var sMaps = JSON.stringify(mappings);", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var width = $(htmlCompId).parent().width();", "\\n", "\"", "+", "\"", "// var height = $(", "\\\"", "svg", "\\\"", ").parent().height();", "\\n", "\"", "+", "\"", " var height = 600;", "\\n", "\"", "+", "\"", " var color = d3.scale.category20();", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var force = d3.layout.force()", "\\n", "\"", "+", "\"", " .charge(-300)", "\\n", "\"", "+", "\"", " .linkDistance(100)", "\\n", "\"", "+", "\"", " .friction(.8)", "\\n", "\"", "+", "\"", " .size([width, height]);", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var svg = d3.select(htmlCompId).append(", "\\\"", "svg", "\\\"", ")", "\\n", "\"", "+", "\"", "// \t.attr(", "\\\"", "width", "\\\"", ", width)", "\\n", "\"", "+", "\"", "// \t.attr(", "\\\"", "height", "\\\"", ", height)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "viewBox", "\\\"", ", ", "\\\"", "0 0 600 600", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "width", "\\\"", ", ", "\\\"", "100%", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "height", "\\\"", ", 600)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "preserveAspectRatio", "\\\"", ", ", "\\\"", "xMidYMid", "\\\"", ")", "\\n", "\"", "+", "\"", " .style(", "\\\"", "background-color", "\\\"", ", ", "\\\"", "#F4F2F5", "\\\"", ");", "\\n", "\"", "+", "\"", "// build the arrow.", "\\n", "\"", "+", "\"", " svg.append(", "\\\"", "svg:defs", "\\\"", ").selectAll(", "\\\"", "marker", "\\\"", ")", "\\n", "\"", "+", "\"", " .data([", "\\\"", "end", "\\\"", "]) // Different link/path types can be defined here", "\\n", "\"", "+", "\"", " .enter().append(", "\\\"", "svg:marker", "\\\"", ") // This section adds in the arrows", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "id", "\\\"", ", String)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "viewBox", "\\\"", ", ", "\\\"", "0 -5 10 10", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "refX", "\\\"", ", 21)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "refY", "\\\"", ", -1.5)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "markerWidth", "\\\"", ", 4)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "markerHeight", "\\\"", ", 4)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "orient", "\\\"", ", ", "\\\"", "auto", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "class", "\\\"", ", ", "\\\"", "arrow", "\\\"", ")", "\\n", "\"", "+", "\"", " .append(", "\\\"", "svg:path", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "d", "\\\"", ", ", "\\\"", "M0,-5L10,0L0,5", "\\\"", ");", "\"", "+", "\"", "\\n", "\"", "+", "\"", " force.nodes(d3Data.nodes).links(d3Data.edges).start();", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var link = svg.selectAll(", "\\\"", ".link", "\\\"", ")", "\\n", "\"", "+", "\"", " .data(d3Data.edges)", "\\n", "\"", "+", "\"", " .enter().append(", "\\\"", "path", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "d", "\\\"", ", ", "\\\"", "M0,-5L10,0L0,5", "\\\"", ")", "\\n", "\"", "+", "\"", " // .enter().append(", "\\\"", "line", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "class", "\\\"", ", ", "\\\"", "link", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "marker-end", "\\\"", ", ", "\\\"", "url(#end)", "\\\"", ")", "\\n", "\"", "+", "\"", " .style(", "\\\"", "stroke-width", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " if (d.label.indexOf(", "\\\"", "prov#", "\\\"", ") !== -1) {", "\\n", "\"", "+", "\"", " return 3;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " return 3;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " link.append(", "\\\"", "title", "\\\"", ")", "\\n", "\"", "+", "\"", " .text(function(d) {", "\\n", "\"", "+", "\"", " return d.label;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var node_drag = d3.behavior.drag()", "\\n", "\"", "+", "\"", " .on(", "\\\"", "dragstart", "\\\"", ", dragstart)", "\\n", "\"", "+", "\"", " .on(", "\\\"", "drag", "\\\"", ", dragmove)", "\\n", "\"", "+", "\"", " .on(", "\\\"", "dragend", "\\\"", ", dragend);", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " function dragstart(d, i) {", "\\n", "\"", "+", "\"", " force.stop() // stops the force auto positioning before you start dragging", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " function dragmove(d, i) {", "\\n", "\"", "+", "\"", " d.px += d3.event.dx;", "\\n", "\"", "+", "\"", " d.py += d3.event.dy;", "\\n", "\"", "+", "\"", " d.x += d3.event.dx;", "\\n", "\"", "+", "\"", " d.y += d3.event.dy;", "\\n", "\"", "+", "\"", " tick(); // this is the key to make it work together with updating both px,py,x,y on d !", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " function dragend(d, i) {", "\\n", "\"", "+", "\"", " d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff", "\\n", "\"", "+", "\"", " tick();", "\\n", "\"", "+", "\"", " force.resume();", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var node = svg.selectAll(", "\\\"", "g.node", "\\\"", ")", "\\n", "\"", "+", "\"", " .data(d3Data.nodes)", "\\n", "\"", "+", "\"", " .enter().append(", "\\\"", "g", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "class", "\\\"", ", ", "\\\"", "node", "\\\"", ")", "\\n", "\"", "+", "\"", " // .call(force.drag);", "\\n", "\"", "+", "\"", " .call(node_drag);", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " node.append(", "\\\"", "title", "\\\"", ")", "\\n", "\"", "+", "\"", " .text(function(d) {", "\\n", "\"", "+", "\"", " return d.name;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " node.append(", "\\\"", "circle", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "class", "\\\"", ", ", "\\\"", "node", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "r", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " if (d.group === 0) {", "\\n", "\"", "+", "\"", " return 6;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " return 12;", "\\n", "\"", "+", "\"", " })", "\\n", "\"", "+", "\"", " .on(", "\\\"", "dblclick", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " d.fixed = false;", "\\n", "\"", "+", "\"", " })", "\\n", "\"", "+", "\"", " .on(", "\\\"", "mouseover", "\\\"", ", fade(.1)).on(", "\\\"", "mouseout", "\\\"", ", fade(1))", "\\n", "\"", "+", "\"", " .style(", "\\\"", "stroke", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return color(d.group);", "\\n", "\"", "+", "\"", " })", "\\n", "\"", "+", "\"", " .style(", "\\\"", "stroke", "\\\"", ", ", "\\\"", "#F4F2F5", "\\\"", ")", "\\n", "\"", "+", "\"", " .style(", "\\\"", "stroke-width", "\\\"", ", 2)", "\\n", "\"", "+", "\"", " // \t.style(", "\\\"", "stroke-dasharray", "\\\"", ",function(d) {", "\\n", "\"", "+", "\"", " // if (sMaps.indexOf(d.name) !== -1) {", "\\n", "\"", "+", "\"", " // \t\treturn ", "\\\"", "5,5", "\\\"", ";", "\\n", "\"", "+", "\"", " // }", "\\n", "\"", "+", "\"", " // \t\treturn ", "\\\"", "none", "\\\"", ";", "\\n", "\"", "+", "\"", " // \t})", "\\n", "\"", "+", "\"", " // .style(", "\\\"", "fill", "\\\"", ", ", "\\\"", "white", "\\\"", ")", "\\n", "\"", "+", "\"", " .style(", "\\\"", "fill", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return color(d.group);", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", " // .on(", "\\\"", "mouseout", "\\\"", ", function(d, i) {", "\\n", "\"", "+", "\"", " // \td3.select(this).style(", "\\\"", "fill", "\\\"", ", ", "\\\"", "white", "\\\"", ");", "\\n", "\"", "+", "\"", " // })", "\\n", "\"", "+", "\"", " // .on(", "\\\"", "mouseover", "\\\"", ", function(d, i) {", "\\n", "\"", "+", "\"", " // \td3.select(this).style(", "\\\"", "fill", "\\\"", ", function(d) { return color(d.group); });", "\\n", "\"", "+", "\"", " // }) ;", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "node.append(", "\\\"", "text", "\\\"", ")", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "x", "\\\"", ", 20)", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "dy", "\\\"", ", ", "\\\"", ".35em", "\\\"", ")", "\\n", "\"", "+", "\"", " .text(function(d) { ", "\\n", "\"", "+", "\"", " return d.name ;", "\\n", "\"", "+", "\"", " });", "\"", "+", "\"", "\\n", "\"", "+", "\"", " var linkedByIndex = {};", "\\n", "\"", "+", "\"", " d3Data.edges.forEach(function(d) {", "\\n", "\"", "+", "\"", " linkedByIndex[d.source.index + ", "\\\"", ",", "\\\"", " + d.target.index] = 1;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " function isConnected(a, b) {", "\\n", "\"", "+", "\"", " return linkedByIndex[a.index + ", "\\\"", ",", "\\\"", " + b.index] || linkedByIndex[b.index + ", "\\\"", ",", "\\\"", " + a.index] || a.index === b.index;", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " force.on(", "\\\"", "tick", "\\\"", ", tick);", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " function tick() {", "\\n", "\"", "+", "\"", " link.attr(", "\\\"", "x1", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return d.source.x;", "\\n", "\"", "+", "\"", " })", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "y1", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return d.source.y;", "\\n", "\"", "+", "\"", " })", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "x2", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return d.target.x;", "\\n", "\"", "+", "\"", " })", "\\n", "\"", "+", "\"", " .attr(", "\\\"", "y2", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return d.target.y;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " node.attr(", "\\\"", "transform", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " return ", "\\\"", "translate(", "\\\"", " + d.x + ", "\\\"", ",", "\\\"", " + d.y + ", "\\\"", ")", "\\\"", ";", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " link.attr(", "\\\"", "d", "\\\"", ", function(d) {", "\\n", "\"", "+", "\"", " var dx = d.target.x - d.source.x,", "\\n", "\"", "+", "\"", " dy = d.target.y - d.source.y,", "\\n", "\"", "+", "\"", " dr = Math.sqrt(dx * dx + dy * dy);", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " return ", "\\\"", "M", "\\\"", " + d.source.x + ", "\\\"", ",", "\\\"", " + d.source.y + ", "\\\"", "A", "\\\"", " + dr + ", "\\\"", ",", "\\\"", " + dr + ", "\\\"", " 0 0,1 ", "\\\"", " + d.target.x + ", "\\\"", ",", "\\\"", " + d.target.y;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", " ;", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " function fade(opacity) {", "\\n", "\"", "+", "\"", " return function(d) {", "\\n", "\"", "+", "\"", " node.style(", "\\\"", "opacity", "\\\"", ", function(o) {", "\\n", "\"", "+", "\"", " thisOpacity = isConnected(d, o) ? 1 : opacity;", "\\n", "\"", "+", "\"", " this.setAttribute('fill-opacity', thisOpacity);", "\\n", "\"", "+", "\"", " return thisOpacity;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " link.style(", "\\\"", "opacity", "\\\"", ", function(o) {", "\\n", "\"", "+", "\"", " return o.source === d || o.target === d ? 1 : opacity;", "\\n", "\"", "+", "\"", " });", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", " };", "\\n", "\"", "+", "\"", " }", "\\n", "\"", "+", "\"", "}", "\"", "+", "\"", " </script>", "\\n", "\"", "+", "\"", "</body>", "\\n", "\"", "+", "\"", "</html>", "\"", ";", "public", "static", "String", "genHtmlViz", "(", "String", "jsonData", ")", "{", "String", "out", "=", "htmlOutTemplate", ".", "replaceAll", "(", "Pattern", ".", "quote", "(", "\"", "**jsonData**", "\"", ")", ",", "jsonData", ")", ";", "return", "out", ";", "}", "public", "static", "String", "simulateWfExec", "(", "Workflow", "wf", ")", "{", "StringBuilder", "toDOT", "=", "new", "StringBuilder", "(", ")", ";", "StringBuilder", "toPROV", "=", "new", "StringBuilder", "(", ")", ";", "toDOT", ".", "append", "(", "\"", "digraph G {", "\\n", "\"", ")", ";", "toPROV", ".", "append", "(", "\"", "PREFIX prov:<", "\"", "+", "Util", ".", "provPrefix", "+", "\"", "> insert data {", "\\n", "\"", ")", ";", "for", "(", "Step", "s", ":", "wf", ".", "getSteps", "(", ")", ".", "values", "(", ")", ")", "{", "String", "step", "=", "\"", "A", "\"", "+", "s", ".", "getId", "(", ")", "+", "\"", "_", "\"", "+", "s", ".", "getName", "(", ")", ".", "replaceAll", "(", "\"", ":", "\"", ",", "\"", "\"", ")", ".", "replaceAll", "(", "\"", " ", "\"", ",", "\"", "\"", ")", ".", "replaceAll", "(", "\"", "/", "\"", ",", "\"", "\"", ")", ";", "toDOT", ".", "append", "(", "\"", "\\t", "\"", "+", "step", "+", "\"", " [shape=box]", "\\n", "\"", ")", ";", "toPROV", ".", "append", "(", "\"", "<", "\"", "+", "Util", ".", "dataPrefix", "+", "step", "+", "\"", "> rdf:type prov:Activity . ", "\\n", "\"", ")", ";", "for", "(", "Output", "o", ":", "s", ".", "getOutputs", "(", ")", ")", "{", "String", "data", "=", "\"", "D", "\"", "+", "s", ".", "getId", "(", ")", "+", "\"", "_", "\"", "+", "o", ".", "getName", "(", ")", ";", "toDOT", ".", "append", "(", "\"", "\\t", "\"", "+", "data", "+", "\"", " [shape=box]", "\\n", "\"", ")", ";", "toDOT", ".", "append", "(", "\"", "\\t", "\"", "+", "data", "+", "\"", " -> ", "\"", "+", "step", "+", "\"", "\\n", "\"", ")", ";", "toPROV", ".", "append", "(", "\"", "<", "\"", "+", "Util", ".", "dataPrefix", "+", "data", "+", "\"", "> rdf:type prov:Entity ; ", "\\n", "\"", ")", ";", "toPROV", ".", "append", "(", "\"", "\\t", " prov:wasGeneratedBy <", "\"", "+", "Util", ".", "dataPrefix", "+", "step", "+", "\"", "> . ", "\\n", "\"", ")", ";", "for", "(", "String", "k", ":", "s", ".", "getInput_connections", "(", ")", ".", "keySet", "(", ")", ")", "{", "String", "origData", "=", "\"", "D", "\"", "+", "s", ".", "getInput_connections", "(", ")", ".", "get", "(", "k", ")", ".", "getId", "(", ")", "+", "\"", "_", "\"", "+", "s", ".", "getInput_connections", "(", ")", ".", "get", "(", "k", ")", ".", "getOutput_name", "(", ")", ";", "toDOT", ".", "append", "(", "\"", "\\t", "\"", "+", "data", "+", "\"", " -> ", "\"", "+", "origData", "+", "\"", "[style=", "\\\"", "dotted", "\\\"", "]", "\\n", "\"", ")", ";", "toPROV", ".", "append", "(", "\"", "<", "\"", "+", "Util", ".", "dataPrefix", "+", "data", "+", "\"", "> prov:wasDerivedFrom <", "\"", "+", "Util", ".", "dataPrefix", "+", "origData", "+", "\"", "> . ", "\\n", "\"", ")", ";", "}", "}", "}", "toPROV", ".", "append", "(", "\"", "}", "\\n", "\"", ")", ";", "toDOT", ".", "append", "(", "\"", "}", "\\n", "\"", ")", ";", "return", "toPROV", ".", "toString", "(", ")", ";", "}", "}" ]
@author Alban Gaignard <alban.gaignard@univ-nantes.fr>
[ "@author", "Alban", "Gaignard", "<alban", ".", "gaignard@univ", "-", "nantes", ".", "fr", ">" ]
[ "// + \" stroke-opacity: .6;\\n\"", "// + \" stroke-opacity: .6;\\n\"", "// + \" .on(\\\"mouseout\\\", function(d, i) {\\n\"", "// + \" d3.select(this).style(\\\"stroke\\\", \\\" #a0a0a0\\\");\\n\"", "// + \" })\\n\"", "// + \" .on(\\\"mouseover\\\", function(d, i) {\\n\"", "// + \" d3.select(this).style(\\\"stroke\\\", \\\" #000000\\\");\\n\"", "// + \" });\\n\"", "// + \" .style(\\\"stroke-width\\\", function(d) {\\n\"", "// + \" if (sMaps.indexOf(d.name) !== -1) {\\n\"", "// + \" return 8;\\n\"", "// + \" }\\n\"", "// + \" return 3;\\n\"", "// + \" })\\n\"", "// create produced data", "//iterate over list of outputs ?", "// for (Connection c : s.getInput_connections().get(k)) {", "// ", "// String origData = \"D\" + c.getId() + \"_\" + c.getOutput_name();", "//// // create data lineage", "// toDOT.append(\"\\t\" + data + \" -> \" + origData + \"[style=\\\"dotted\\\"]\\n\");", "// toPROV.append(\"<\" + Util.dataPrefix + data + \"> prov:wasDerivedFrom <\" + Util.dataPrefix + origData + \"> . \\n\");", "// }", "// create data lineage", "// return toDOT.toString();" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4ff0ddb3826cedf875e8dc39b769f3e6708b018b
a-mogilevtsev/job4j
chapter_002/src/main/java/ru/job4j/pseudo/Paint.java
[ "Apache-2.0" ]
Java
Paint
/** * Created by a.mogilevtsev on 1/8/2019. */
Created by a.mogilevtsev on 1/8/2019.
[ "Created", "by", "a", ".", "mogilevtsev", "on", "1", "/", "8", "/", "2019", "." ]
public class Paint { public void draw(Shape shape) { System.out.println(shape.draw()); } public static void main(String[] args) { Shape tr = new Triangle(); Shape sq = new Square(); } }
[ "public", "class", "Paint", "{", "public", "void", "draw", "(", "Shape", "shape", ")", "{", "System", ".", "out", ".", "println", "(", "shape", ".", "draw", "(", ")", ")", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "Shape", "tr", "=", "new", "Triangle", "(", ")", ";", "Shape", "sq", "=", "new", "Square", "(", ")", ";", "}", "}" ]
Created by a.mogilevtsev on 1/8/2019.
[ "Created", "by", "a", ".", "mogilevtsev", "on", "1", "/", "8", "/", "2019", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4ff2de364a24041671ff8f5a78f806232b4943ff
specs-feup/java-libs
GuiHelper/src/pt/up/fe/specs/guihelper/BaseTypes/ListOfSetups.java
[ "Apache-2.0" ]
Java
ListOfSetups
// public class ListOfSetups implements Serializable {
public class ListOfSetups implements Serializable {
[ "public", "class", "ListOfSetups", "implements", "Serializable", "{" ]
public class ListOfSetups { // Consider replace with LinkedHashMap private List<SetupData> setupList; private Map<String, SetupData> mapOfSetups; private Integer preferredIndex; public ListOfSetups(List<SetupData> listOfSetups) { this.mapOfSetups = SpecsFactory.newLinkedHashMap(); for (SetupData setup : listOfSetups) { this.mapOfSetups.put(setup.getSetupName(), setup); } setupList = SpecsFactory.newArrayList(listOfSetups); // this.listOfSetups = listOfSetups; preferredIndex = null; } public static ListOfSetups create(ListOfSetupDefinitions listOfSetupDefinitions) { List<SetupData> setups = new ArrayList<>(); for (SetupDefinition setupDefinition : listOfSetupDefinitions.getSetupKeysList()) { SetupData newSetup = SetupData.create(setupDefinition); setups.add(newSetup); } return new ListOfSetups(setups); } public List<SetupData> getMapOfSetups() { // return listOfSetups; return setupList; } /** * @return the listOfSetups */ public Map<String, SetupData> getMap() { return mapOfSetups; } public void setPreferredIndex(Integer preferredIndex) { this.preferredIndex = preferredIndex; } public Integer getPreferredIndex() { return preferredIndex; } public SetupData getPreferredSetup() { if (mapOfSetups.isEmpty()) { SpecsLogs.warn("There are no setups."); return null; } if (preferredIndex == null) { SpecsLogs.warn("Preferred index not set, returning first setup."); return mapOfSetups.get(0); } String setupName = setupList.get(preferredIndex).getSetupName(); // return mapOfSetups.get(preferredIndex); return mapOfSetups.get(setupName); } /** * @return */ public int getNumSetups() { return setupList.size(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return mapOfSetups.toString(); } // Variable needed for serialization. // private static final long serialVersionUID = 1; }
[ "public", "class", "ListOfSetups", "{", "private", "List", "<", "SetupData", ">", "setupList", ";", "private", "Map", "<", "String", ",", "SetupData", ">", "mapOfSetups", ";", "private", "Integer", "preferredIndex", ";", "public", "ListOfSetups", "(", "List", "<", "SetupData", ">", "listOfSetups", ")", "{", "this", ".", "mapOfSetups", "=", "SpecsFactory", ".", "newLinkedHashMap", "(", ")", ";", "for", "(", "SetupData", "setup", ":", "listOfSetups", ")", "{", "this", ".", "mapOfSetups", ".", "put", "(", "setup", ".", "getSetupName", "(", ")", ",", "setup", ")", ";", "}", "setupList", "=", "SpecsFactory", ".", "newArrayList", "(", "listOfSetups", ")", ";", "preferredIndex", "=", "null", ";", "}", "public", "static", "ListOfSetups", "create", "(", "ListOfSetupDefinitions", "listOfSetupDefinitions", ")", "{", "List", "<", "SetupData", ">", "setups", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "SetupDefinition", "setupDefinition", ":", "listOfSetupDefinitions", ".", "getSetupKeysList", "(", ")", ")", "{", "SetupData", "newSetup", "=", "SetupData", ".", "create", "(", "setupDefinition", ")", ";", "setups", ".", "add", "(", "newSetup", ")", ";", "}", "return", "new", "ListOfSetups", "(", "setups", ")", ";", "}", "public", "List", "<", "SetupData", ">", "getMapOfSetups", "(", ")", "{", "return", "setupList", ";", "}", "/**\n * @return the listOfSetups\n */", "public", "Map", "<", "String", ",", "SetupData", ">", "getMap", "(", ")", "{", "return", "mapOfSetups", ";", "}", "public", "void", "setPreferredIndex", "(", "Integer", "preferredIndex", ")", "{", "this", ".", "preferredIndex", "=", "preferredIndex", ";", "}", "public", "Integer", "getPreferredIndex", "(", ")", "{", "return", "preferredIndex", ";", "}", "public", "SetupData", "getPreferredSetup", "(", ")", "{", "if", "(", "mapOfSetups", ".", "isEmpty", "(", ")", ")", "{", "SpecsLogs", ".", "warn", "(", "\"", "There are no setups.", "\"", ")", ";", "return", "null", ";", "}", "if", "(", "preferredIndex", "==", "null", ")", "{", "SpecsLogs", ".", "warn", "(", "\"", "Preferred index not set, returning first setup.", "\"", ")", ";", "return", "mapOfSetups", ".", "get", "(", "0", ")", ";", "}", "String", "setupName", "=", "setupList", ".", "get", "(", "preferredIndex", ")", ".", "getSetupName", "(", ")", ";", "return", "mapOfSetups", ".", "get", "(", "setupName", ")", ";", "}", "/**\n * @return\n */", "public", "int", "getNumSetups", "(", ")", "{", "return", "setupList", ".", "size", "(", ")", ";", "}", "/* (non-Javadoc)\n * @see java.lang.Object#toString()\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "mapOfSetups", ".", "toString", "(", ")", ";", "}", "}" ]
public class ListOfSetups implements Serializable {
[ "public", "class", "ListOfSetups", "implements", "Serializable", "{" ]
[ "// Consider replace with LinkedHashMap", "// this.listOfSetups = listOfSetups;", "// return listOfSetups;", "// return mapOfSetups.get(preferredIndex);", "// Variable needed for serialization.", "// private static final long serialVersionUID = 1;" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4ff579efcd514464e7bab36b6f86fe348ec9f4a6
dpicheo/j2mod
src/main/java/com/ghgande/j2mod/modbus/net/SerialConnection.java
[ "Apache-2.0" ]
Java
SerialConnection
/** * Class that implements a serial connection which can be used for master and * slave implementations. * * @author Dieter Wimberger * @author John Charlton * @author Steve O'Hara (4NG) * @version 2.0 (March 2016) */
Class that implements a serial connection which can be used for master and slave implementations. @author Dieter Wimberger @author John Charlton @author Steve O'Hara (4NG) @version 2.0 (March 2016)
[ "Class", "that", "implements", "a", "serial", "connection", "which", "can", "be", "used", "for", "master", "and", "slave", "implementations", ".", "@author", "Dieter", "Wimberger", "@author", "John", "Charlton", "@author", "Steve", "O", "'", "Hara", "(", "4NG", ")", "@version", "2", ".", "0", "(", "March", "2016", ")" ]
public class SerialConnection extends AbstractSerialConnection { private static final Logger logger = LogManager.getLogger(SerialConnection.class); public static final int CONNECT_RETRY_DELAY = 100; public static final int CONNECT_RETRIES = 3; private SerialParameters parameters; private ModbusSerialTransport transport; private SerialPort serialPort; private InputStream inputStream; private int timeout = Modbus.DEFAULT_TIMEOUT; /** * Default constructor */ public SerialConnection() { } /** * Creates a SerialConnection object and initializes variables passed in as * params. * * @param parameters A SerialParameters object. */ public SerialConnection(SerialParameters parameters) { this.parameters = parameters; } /** * Returns a JSerialComm implementation for the given comms port * * @param commPort Comms port e.g. /dev/ttyAMA0 * @return JSerialComm implementation */ public static AbstractSerialConnection getCommPort(String commPort) { SerialConnection jSerialCommPort = new SerialConnection(); jSerialCommPort.serialPort = SerialPort.getCommPort(commPort); return jSerialCommPort; } @Override public AbstractModbusTransport getModbusTransport() { return transport; } @Override public synchronized void open() throws IOException { if (serialPort == null) { serialPort = SerialPort.getCommPort(parameters.getPortName()); if (serialPort.getDescriptivePortName().contains("Bad Port")) { close(); throw new IOException(String.format("Port %s is not a valid name for a port on this platform", parameters.getPortName())); } } serialPort.closePort(); applyConnectionParameters(); if (Modbus.SERIAL_ENCODING_ASCII.equals(parameters.getEncoding())) { transport = new ModbusASCIITransport(); } else if (Modbus.SERIAL_ENCODING_RTU.equals(parameters.getEncoding())) { transport = new ModbusRTUTransport(); } else { transport = new ModbusRTUTransport(); logger.warn("Unknown transport encoding [{}] - reverting to RTU", parameters.getEncoding()); } transport.setEcho(parameters.isEcho()); transport.setTimeout(timeout); // Open the input and output streams for the connection. If they won't // open, close the port before throwing an exception. transport.setCommPort(this); // Open the port so that we can get it's input stream int attempts = 0; while (!serialPort.openPort(parameters.getOpenDelay()) && attempts < CONNECT_RETRIES) { serialPort.closePort(); ModbusUtil.sleep(CONNECT_RETRY_DELAY); attempts++; logger.debug("Retrying to open port [{}] - attempt [{}}", parameters.getPortName(), attempts); } if (!serialPort.isOpen()) { Set<String> ports = getCommPorts(); StringBuilder portList = new StringBuilder("<NONE>"); if (!ports.isEmpty()) { portList = new StringBuilder(); for (String port : ports) { portList.append(portList.length() == 0 ? "" : ",").append(port); } } throw new IOException(String.format("Port [%s] cannot be opened after [%d] attempts - valid ports are: [%s]", parameters.getPortName(), attempts, portList.toString())); } inputStream = serialPort.getInputStream(); } /** * Applies the serial parameters to the actual hardware */ private void applyConnectionParameters() { // Set connection parameters, if set fails return parameters object // to original state if (serialPort != null) { serialPort.setComPortParameters(parameters.getBaudRate(), parameters.getDatabits(), parameters.getStopbits(), parameters.getParity()); serialPort.setFlowControl(parameters.getFlowControlIn() | parameters.getFlowControlOut()); serialPort.setRs485ModeParameters(parameters.getRs485Mode(), parameters.getRs485TxEnableActiveHigh(), parameters.getRs485DelayBeforeTxMicroseconds(), parameters.getRs485DelayAfterTxMicroseconds()); } } @Override public synchronized void close() { // Check to make sure serial port has reference to avoid a NPE if (serialPort != null) { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { logger.debug(e.getMessage()); } finally { // Close the port. serialPort.closePort(); } } serialPort = null; } @Override public synchronized boolean isOpen() { return serialPort != null && serialPort.isOpen(); } @Override public synchronized int getTimeout() { return timeout; } @Override public synchronized void setTimeout(int timeout) { this.timeout = timeout; if (transport != null) { transport.setTimeout(timeout); } } @Override public int readBytes(byte[] buffer, long bytesToRead) { return serialPort == null ? 0 : serialPort.readBytes(buffer, bytesToRead); } @Override public int writeBytes(byte[] buffer, long bytesToWrite) { return serialPort == null ? 0 : serialPort.writeBytes(buffer, bytesToWrite); } @Override public int bytesAvailable() { return serialPort == null ? 0 : serialPort.bytesAvailable(); } @Override public int getBaudRate() { return parameters.getBaudRate(); } @Override public int getNumDataBits() { return parameters.getDatabits(); } @Override public int getNumStopBits() { return parameters.getStopbits(); } @Override public int getParity() { return parameters.getParity(); } @Override public String getPortName() { return parameters.getPortName(); } @Override public String getDescriptivePortName() { return serialPort == null ? parameters.getPortName() : serialPort.getDescriptivePortName(); } @Override public void setComPortTimeouts(int newTimeoutMode, int newReadTimeout, int newWriteTimeout) { if (serialPort != null) { serialPort.setComPortTimeouts(newTimeoutMode, newReadTimeout, newWriteTimeout); } } @Override public Set<String> getCommPorts() { Set<String> returnValue = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); SerialPort[] ports = SerialPort.getCommPorts(); if (ports != null && ports.length > 0) { for (SerialPort port : ports) { returnValue.add(port.getSystemPortName()); } } return returnValue; } }
[ "public", "class", "SerialConnection", "extends", "AbstractSerialConnection", "{", "private", "static", "final", "Logger", "logger", "=", "LogManager", ".", "getLogger", "(", "SerialConnection", ".", "class", ")", ";", "public", "static", "final", "int", "CONNECT_RETRY_DELAY", "=", "100", ";", "public", "static", "final", "int", "CONNECT_RETRIES", "=", "3", ";", "private", "SerialParameters", "parameters", ";", "private", "ModbusSerialTransport", "transport", ";", "private", "SerialPort", "serialPort", ";", "private", "InputStream", "inputStream", ";", "private", "int", "timeout", "=", "Modbus", ".", "DEFAULT_TIMEOUT", ";", "/**\n * Default constructor\n */", "public", "SerialConnection", "(", ")", "{", "}", "/**\n * Creates a SerialConnection object and initializes variables passed in as\n * params.\n *\n * @param parameters A SerialParameters object.\n */", "public", "SerialConnection", "(", "SerialParameters", "parameters", ")", "{", "this", ".", "parameters", "=", "parameters", ";", "}", "/**\n * Returns a JSerialComm implementation for the given comms port\n *\n * @param commPort Comms port e.g. /dev/ttyAMA0\n * @return JSerialComm implementation\n */", "public", "static", "AbstractSerialConnection", "getCommPort", "(", "String", "commPort", ")", "{", "SerialConnection", "jSerialCommPort", "=", "new", "SerialConnection", "(", ")", ";", "jSerialCommPort", ".", "serialPort", "=", "SerialPort", ".", "getCommPort", "(", "commPort", ")", ";", "return", "jSerialCommPort", ";", "}", "@", "Override", "public", "AbstractModbusTransport", "getModbusTransport", "(", ")", "{", "return", "transport", ";", "}", "@", "Override", "public", "synchronized", "void", "open", "(", ")", "throws", "IOException", "{", "if", "(", "serialPort", "==", "null", ")", "{", "serialPort", "=", "SerialPort", ".", "getCommPort", "(", "parameters", ".", "getPortName", "(", ")", ")", ";", "if", "(", "serialPort", ".", "getDescriptivePortName", "(", ")", ".", "contains", "(", "\"", "Bad Port", "\"", ")", ")", "{", "close", "(", ")", ";", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"", "Port %s is not a valid name for a port on this platform", "\"", ",", "parameters", ".", "getPortName", "(", ")", ")", ")", ";", "}", "}", "serialPort", ".", "closePort", "(", ")", ";", "applyConnectionParameters", "(", ")", ";", "if", "(", "Modbus", ".", "SERIAL_ENCODING_ASCII", ".", "equals", "(", "parameters", ".", "getEncoding", "(", ")", ")", ")", "{", "transport", "=", "new", "ModbusASCIITransport", "(", ")", ";", "}", "else", "if", "(", "Modbus", ".", "SERIAL_ENCODING_RTU", ".", "equals", "(", "parameters", ".", "getEncoding", "(", ")", ")", ")", "{", "transport", "=", "new", "ModbusRTUTransport", "(", ")", ";", "}", "else", "{", "transport", "=", "new", "ModbusRTUTransport", "(", ")", ";", "logger", ".", "warn", "(", "\"", "Unknown transport encoding [{}] - reverting to RTU", "\"", ",", "parameters", ".", "getEncoding", "(", ")", ")", ";", "}", "transport", ".", "setEcho", "(", "parameters", ".", "isEcho", "(", ")", ")", ";", "transport", ".", "setTimeout", "(", "timeout", ")", ";", "transport", ".", "setCommPort", "(", "this", ")", ";", "int", "attempts", "=", "0", ";", "while", "(", "!", "serialPort", ".", "openPort", "(", "parameters", ".", "getOpenDelay", "(", ")", ")", "&&", "attempts", "<", "CONNECT_RETRIES", ")", "{", "serialPort", ".", "closePort", "(", ")", ";", "ModbusUtil", ".", "sleep", "(", "CONNECT_RETRY_DELAY", ")", ";", "attempts", "++", ";", "logger", ".", "debug", "(", "\"", "Retrying to open port [{}] - attempt [{}}", "\"", ",", "parameters", ".", "getPortName", "(", ")", ",", "attempts", ")", ";", "}", "if", "(", "!", "serialPort", ".", "isOpen", "(", ")", ")", "{", "Set", "<", "String", ">", "ports", "=", "getCommPorts", "(", ")", ";", "StringBuilder", "portList", "=", "new", "StringBuilder", "(", "\"", "<NONE>", "\"", ")", ";", "if", "(", "!", "ports", ".", "isEmpty", "(", ")", ")", "{", "portList", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "port", ":", "ports", ")", "{", "portList", ".", "append", "(", "portList", ".", "length", "(", ")", "==", "0", "?", "\"", "\"", ":", "\"", ",", "\"", ")", ".", "append", "(", "port", ")", ";", "}", "}", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"", "Port [%s] cannot be opened after [%d] attempts - valid ports are: [%s]", "\"", ",", "parameters", ".", "getPortName", "(", ")", ",", "attempts", ",", "portList", ".", "toString", "(", ")", ")", ")", ";", "}", "inputStream", "=", "serialPort", ".", "getInputStream", "(", ")", ";", "}", "/**\n * Applies the serial parameters to the actual hardware\n */", "private", "void", "applyConnectionParameters", "(", ")", "{", "if", "(", "serialPort", "!=", "null", ")", "{", "serialPort", ".", "setComPortParameters", "(", "parameters", ".", "getBaudRate", "(", ")", ",", "parameters", ".", "getDatabits", "(", ")", ",", "parameters", ".", "getStopbits", "(", ")", ",", "parameters", ".", "getParity", "(", ")", ")", ";", "serialPort", ".", "setFlowControl", "(", "parameters", ".", "getFlowControlIn", "(", ")", "|", "parameters", ".", "getFlowControlOut", "(", ")", ")", ";", "serialPort", ".", "setRs485ModeParameters", "(", "parameters", ".", "getRs485Mode", "(", ")", ",", "parameters", ".", "getRs485TxEnableActiveHigh", "(", ")", ",", "parameters", ".", "getRs485DelayBeforeTxMicroseconds", "(", ")", ",", "parameters", ".", "getRs485DelayAfterTxMicroseconds", "(", ")", ")", ";", "}", "}", "@", "Override", "public", "synchronized", "void", "close", "(", ")", "{", "if", "(", "serialPort", "!=", "null", ")", "{", "try", "{", "if", "(", "inputStream", "!=", "null", ")", "{", "inputStream", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "debug", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "serialPort", ".", "closePort", "(", ")", ";", "}", "}", "serialPort", "=", "null", ";", "}", "@", "Override", "public", "synchronized", "boolean", "isOpen", "(", ")", "{", "return", "serialPort", "!=", "null", "&&", "serialPort", ".", "isOpen", "(", ")", ";", "}", "@", "Override", "public", "synchronized", "int", "getTimeout", "(", ")", "{", "return", "timeout", ";", "}", "@", "Override", "public", "synchronized", "void", "setTimeout", "(", "int", "timeout", ")", "{", "this", ".", "timeout", "=", "timeout", ";", "if", "(", "transport", "!=", "null", ")", "{", "transport", ".", "setTimeout", "(", "timeout", ")", ";", "}", "}", "@", "Override", "public", "int", "readBytes", "(", "byte", "[", "]", "buffer", ",", "long", "bytesToRead", ")", "{", "return", "serialPort", "==", "null", "?", "0", ":", "serialPort", ".", "readBytes", "(", "buffer", ",", "bytesToRead", ")", ";", "}", "@", "Override", "public", "int", "writeBytes", "(", "byte", "[", "]", "buffer", ",", "long", "bytesToWrite", ")", "{", "return", "serialPort", "==", "null", "?", "0", ":", "serialPort", ".", "writeBytes", "(", "buffer", ",", "bytesToWrite", ")", ";", "}", "@", "Override", "public", "int", "bytesAvailable", "(", ")", "{", "return", "serialPort", "==", "null", "?", "0", ":", "serialPort", ".", "bytesAvailable", "(", ")", ";", "}", "@", "Override", "public", "int", "getBaudRate", "(", ")", "{", "return", "parameters", ".", "getBaudRate", "(", ")", ";", "}", "@", "Override", "public", "int", "getNumDataBits", "(", ")", "{", "return", "parameters", ".", "getDatabits", "(", ")", ";", "}", "@", "Override", "public", "int", "getNumStopBits", "(", ")", "{", "return", "parameters", ".", "getStopbits", "(", ")", ";", "}", "@", "Override", "public", "int", "getParity", "(", ")", "{", "return", "parameters", ".", "getParity", "(", ")", ";", "}", "@", "Override", "public", "String", "getPortName", "(", ")", "{", "return", "parameters", ".", "getPortName", "(", ")", ";", "}", "@", "Override", "public", "String", "getDescriptivePortName", "(", ")", "{", "return", "serialPort", "==", "null", "?", "parameters", ".", "getPortName", "(", ")", ":", "serialPort", ".", "getDescriptivePortName", "(", ")", ";", "}", "@", "Override", "public", "void", "setComPortTimeouts", "(", "int", "newTimeoutMode", ",", "int", "newReadTimeout", ",", "int", "newWriteTimeout", ")", "{", "if", "(", "serialPort", "!=", "null", ")", "{", "serialPort", ".", "setComPortTimeouts", "(", "newTimeoutMode", ",", "newReadTimeout", ",", "newWriteTimeout", ")", ";", "}", "}", "@", "Override", "public", "Set", "<", "String", ">", "getCommPorts", "(", ")", "{", "Set", "<", "String", ">", "returnValue", "=", "new", "TreeSet", "<", "String", ">", "(", "String", ".", "CASE_INSENSITIVE_ORDER", ")", ";", "SerialPort", "[", "]", "ports", "=", "SerialPort", ".", "getCommPorts", "(", ")", ";", "if", "(", "ports", "!=", "null", "&&", "ports", ".", "length", ">", "0", ")", "{", "for", "(", "SerialPort", "port", ":", "ports", ")", "{", "returnValue", ".", "add", "(", "port", ".", "getSystemPortName", "(", ")", ")", ";", "}", "}", "return", "returnValue", ";", "}", "}" ]
Class that implements a serial connection which can be used for master and slave implementations.
[ "Class", "that", "implements", "a", "serial", "connection", "which", "can", "be", "used", "for", "master", "and", "slave", "implementations", "." ]
[ "// Open the input and output streams for the connection. If they won't", "// open, close the port before throwing an exception.", "// Open the port so that we can get it's input stream", "// Set connection parameters, if set fails return parameters object", "// to original state", "// Check to make sure serial port has reference to avoid a NPE", "// Close the port." ]
[ { "param": "AbstractSerialConnection", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractSerialConnection", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4ff6778dd414c418fd3679346f60ad7538872db2
silladus/basiclib
app/src/main/java/silladus/sample/adapter/ViewHolder.java
[ "Apache-2.0" ]
Java
ViewHolder
/** * Created by silladus on 2017/3/3. * GitHub: https://github.com/silladus * Description: Use RecyclerView to instead. */
Created by silladus on 2017/3/3.
[ "Created", "by", "silladus", "on", "2017", "/", "3", "/", "3", "." ]
@Deprecated public class ViewHolder { private SparseArray<View> mViews; private View mConvertView; public ViewHolder(ViewGroup parent, int layoutId) { this.mViews = new SparseArray<>(); mConvertView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false); mConvertView.setTag(this); } public static ViewHolder get(View convertView, ViewGroup parent, int layoutId) { if (convertView == null) { return new ViewHolder(parent, layoutId); } else { return (ViewHolder) convertView.getTag(); } } /** * 通过viewId获取控件 * * @param viewId viewId * @return view */ @SuppressWarnings("unchecked") public <T extends View> T getView(int viewId) { View view = mViews.get(viewId); if (view == null) { view = mConvertView.findViewById(viewId); mViews.put(viewId, view); } return (T) view; } public View getConvertView() { return mConvertView; } }
[ "@", "Deprecated", "public", "class", "ViewHolder", "{", "private", "SparseArray", "<", "View", ">", "mViews", ";", "private", "View", "mConvertView", ";", "public", "ViewHolder", "(", "ViewGroup", "parent", ",", "int", "layoutId", ")", "{", "this", ".", "mViews", "=", "new", "SparseArray", "<", ">", "(", ")", ";", "mConvertView", "=", "LayoutInflater", ".", "from", "(", "parent", ".", "getContext", "(", ")", ")", ".", "inflate", "(", "layoutId", ",", "parent", ",", "false", ")", ";", "mConvertView", ".", "setTag", "(", "this", ")", ";", "}", "public", "static", "ViewHolder", "get", "(", "View", "convertView", ",", "ViewGroup", "parent", ",", "int", "layoutId", ")", "{", "if", "(", "convertView", "==", "null", ")", "{", "return", "new", "ViewHolder", "(", "parent", ",", "layoutId", ")", ";", "}", "else", "{", "return", "(", "ViewHolder", ")", "convertView", ".", "getTag", "(", ")", ";", "}", "}", "/**\n * 通过viewId获取控件\n *\n * @param viewId viewId\n * @return view\n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "public", "<", "T", "extends", "View", ">", "T", "getView", "(", "int", "viewId", ")", "{", "View", "view", "=", "mViews", ".", "get", "(", "viewId", ")", ";", "if", "(", "view", "==", "null", ")", "{", "view", "=", "mConvertView", ".", "findViewById", "(", "viewId", ")", ";", "mViews", ".", "put", "(", "viewId", ",", "view", ")", ";", "}", "return", "(", "T", ")", "view", ";", "}", "public", "View", "getConvertView", "(", ")", "{", "return", "mConvertView", ";", "}", "}" ]
Created by silladus on 2017/3/3.
[ "Created", "by", "silladus", "on", "2017", "/", "3", "/", "3", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4ff724af7975ae7bae40204b9af439726e5e7f6f
Rosanio/Pocket-Pomodoro
app/src/main/java/com/epicodus/pocketpomodoro/Constants.java
[ "Unlicense", "MIT" ]
Java
Constants
/** * Created by Guest on 4/29/16. */
Created by Guest on 4/29/16.
[ "Created", "by", "Guest", "on", "4", "/", "29", "/", "16", "." ]
public class Constants { public static final String YANDEX_API_KEY = BuildConfig.YANDEX_API_KEY; public static final String YANDEX_BASE_URL = "https://translate.yandex.net/"; public static final String YANDEX_TEXT_QUERY_PARAMETER = "text"; public static final String YANDEX_LANGUAGE_QUERY_PARAMETER = "lang"; public static final String YANDEX_KEY_QUERY_PARAMETER = "key"; public static final String FIREBASE_ROOT_URL = BuildConfig.FIREBASE_ROOT_URL; public static final String FIREBASE_LOCATION_USERS = "users"; public static final String FIREBASE_PROPERTY_EMAIL = "email"; public static final String KEY_UID = "UID"; public static final String FIREBASE_URL_USERS = FIREBASE_ROOT_URL + "/" + FIREBASE_LOCATION_USERS; public static final String FIREBASE_LOCATION_DECKS = "decks"; public static final String FIREBASE_URL_DECKS = FIREBASE_ROOT_URL + "/" + FIREBASE_LOCATION_DECKS; public static final String FIREBASE_LOCATION_CARDS = "cards"; public static final String FIREBASE_URL_CARDS = FIREBASE_ROOT_URL + "/" + FIREBASE_LOCATION_CARDS; public static final String KEY_USER_EMAIL = "email"; }
[ "public", "class", "Constants", "{", "public", "static", "final", "String", "YANDEX_API_KEY", "=", "BuildConfig", ".", "YANDEX_API_KEY", ";", "public", "static", "final", "String", "YANDEX_BASE_URL", "=", "\"", "https://translate.yandex.net/", "\"", ";", "public", "static", "final", "String", "YANDEX_TEXT_QUERY_PARAMETER", "=", "\"", "text", "\"", ";", "public", "static", "final", "String", "YANDEX_LANGUAGE_QUERY_PARAMETER", "=", "\"", "lang", "\"", ";", "public", "static", "final", "String", "YANDEX_KEY_QUERY_PARAMETER", "=", "\"", "key", "\"", ";", "public", "static", "final", "String", "FIREBASE_ROOT_URL", "=", "BuildConfig", ".", "FIREBASE_ROOT_URL", ";", "public", "static", "final", "String", "FIREBASE_LOCATION_USERS", "=", "\"", "users", "\"", ";", "public", "static", "final", "String", "FIREBASE_PROPERTY_EMAIL", "=", "\"", "email", "\"", ";", "public", "static", "final", "String", "KEY_UID", "=", "\"", "UID", "\"", ";", "public", "static", "final", "String", "FIREBASE_URL_USERS", "=", "FIREBASE_ROOT_URL", "+", "\"", "/", "\"", "+", "FIREBASE_LOCATION_USERS", ";", "public", "static", "final", "String", "FIREBASE_LOCATION_DECKS", "=", "\"", "decks", "\"", ";", "public", "static", "final", "String", "FIREBASE_URL_DECKS", "=", "FIREBASE_ROOT_URL", "+", "\"", "/", "\"", "+", "FIREBASE_LOCATION_DECKS", ";", "public", "static", "final", "String", "FIREBASE_LOCATION_CARDS", "=", "\"", "cards", "\"", ";", "public", "static", "final", "String", "FIREBASE_URL_CARDS", "=", "FIREBASE_ROOT_URL", "+", "\"", "/", "\"", "+", "FIREBASE_LOCATION_CARDS", ";", "public", "static", "final", "String", "KEY_USER_EMAIL", "=", "\"", "email", "\"", ";", "}" ]
Created by Guest on 4/29/16.
[ "Created", "by", "Guest", "on", "4", "/", "29", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
4ff978db263253ac75381a06b4d805de3a34491b
tmhanus/jVb-Designer-intellij-plugin
src/designer/ui/palette/components/FailComponent.java
[ "Apache-2.0" ]
Java
FailComponent
/** * Created by Tomas Hanus on 4/15/2015. */
Created by Tomas Hanus on 4/15/2015.
[ "Created", "by", "Tomas", "Hanus", "on", "4", "/", "15", "/", "2015", "." ]
public class FailComponent extends PaletteComponent { private static final String FAIL_COMPONENT_TYPE = "Fail"; public FailComponent(PalettePanel panel) { super(FAIL_COMPONENT_TYPE, panel); } public void setIcon(Icon icon) { super.setIcon(new ImageIcon(getClass().getResource("/designer/resources/paletteIcons/Fail32.png"))); } }
[ "public", "class", "FailComponent", "extends", "PaletteComponent", "{", "private", "static", "final", "String", "FAIL_COMPONENT_TYPE", "=", "\"", "Fail", "\"", ";", "public", "FailComponent", "(", "PalettePanel", "panel", ")", "{", "super", "(", "FAIL_COMPONENT_TYPE", ",", "panel", ")", ";", "}", "public", "void", "setIcon", "(", "Icon", "icon", ")", "{", "super", ".", "setIcon", "(", "new", "ImageIcon", "(", "getClass", "(", ")", ".", "getResource", "(", "\"", "/designer/resources/paletteIcons/Fail32.png", "\"", ")", ")", ")", ";", "}", "}" ]
Created by Tomas Hanus on 4/15/2015.
[ "Created", "by", "Tomas", "Hanus", "on", "4", "/", "15", "/", "2015", "." ]
[]
[ { "param": "PaletteComponent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PaletteComponent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4ffa9caae7e214552cdb403ea9cee6635d8f527a
MediaMonks/tilt
app/src/main/java/com/mediamonks/googleflip/pages/game/physics/levels/Level11.java
[ "MIT" ]
Java
Level11
/** * UI/physics implementation of game level */
UI/physics implementation of game level
[ "UI", "/", "physics", "implementation", "of", "game", "level" ]
public class Level11 extends AbstractGameLevel implements GameLevel { public Level11() { } @Override public void createLevel(PhysicsWorld world, FixtureDef fixtureDef) { createWave(world, fixtureDef, 141, 0.6f, 0, 470, 874, 8); createWave(world, fixtureDef, 155, 0.6f, 0, 1124, 874, 8); createWave(world, fixtureDef, 141, 0.6f, 0, 1124, 874, 8); createWave(world, fixtureDef, 161, 0.4f, 0, 1841, 683, 0); } @Override public Vector2 getBallSpawnLocation() { return getScaledVector(133, 202); } @Override public Vector2 getSinkholeLocation() { return getScaledVector(923, 1757); } @Override public String getBackgroundUrl() { return "background_level11.png"; } }
[ "public", "class", "Level11", "extends", "AbstractGameLevel", "implements", "GameLevel", "{", "public", "Level11", "(", ")", "{", "}", "@", "Override", "public", "void", "createLevel", "(", "PhysicsWorld", "world", ",", "FixtureDef", "fixtureDef", ")", "{", "createWave", "(", "world", ",", "fixtureDef", ",", "141", ",", "0.6f", ",", "0", ",", "470", ",", "874", ",", "8", ")", ";", "createWave", "(", "world", ",", "fixtureDef", ",", "155", ",", "0.6f", ",", "0", ",", "1124", ",", "874", ",", "8", ")", ";", "createWave", "(", "world", ",", "fixtureDef", ",", "141", ",", "0.6f", ",", "0", ",", "1124", ",", "874", ",", "8", ")", ";", "createWave", "(", "world", ",", "fixtureDef", ",", "161", ",", "0.4f", ",", "0", ",", "1841", ",", "683", ",", "0", ")", ";", "}", "@", "Override", "public", "Vector2", "getBallSpawnLocation", "(", ")", "{", "return", "getScaledVector", "(", "133", ",", "202", ")", ";", "}", "@", "Override", "public", "Vector2", "getSinkholeLocation", "(", ")", "{", "return", "getScaledVector", "(", "923", ",", "1757", ")", ";", "}", "@", "Override", "public", "String", "getBackgroundUrl", "(", ")", "{", "return", "\"", "background_level11.png", "\"", ";", "}", "}" ]
UI/physics implementation of game level
[ "UI", "/", "physics", "implementation", "of", "game", "level" ]
[]
[ { "param": "AbstractGameLevel", "type": null }, { "param": "GameLevel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractGameLevel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "GameLevel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4fff9fa5771e1702725fdbd1bb8dcaa4e99edeb7
cyberscorpion/jxls
jxls-poi/src/test/java/org/jxls/templatebasedtests/Issue93Test.java
[ "Apache-2.0" ]
Java
Issue93Test
/** * Checks whether EachCommand saves varIndex before the loop and restores it after the loop. (issues 93, 108) */
Checks whether EachCommand saves varIndex before the loop and restores it after the loop.
[ "Checks", "whether", "EachCommand", "saves", "varIndex", "before", "the", "loop", "and", "restores", "it", "after", "the", "loop", "." ]
public class Issue93Test { @Test public void test() { // Prepare Context context = new Context() { public Object getVar(String name) { if (name.substring(0, 1) == "m") { // Do an operation that could result in a NPE. System.out.println("getVar: var starts with 'm'"); } return super.getVar(name); } }; context.putVar("list", new ArrayList<>(Arrays.asList("A", "B", "C"))); context.putVar("list2", new ArrayList<>(Arrays.asList("D", "E"))); context.putVar("i", -42d); // Test JxlsTester tester = JxlsTester.xlsx(getClass()); tester.processTemplate(context); // Verify try (TestWorkbook w = tester.getWorkbook()) { w.selectSheet(0); Assert.assertEquals("varIndex was not saved!", -42d, w.getCellValueAsDouble(7, 2), 0.1d); Assert.assertEquals("E", w.getCellValueAsString(10, 1)); } } @Test public void wrongLastCellInTemplate() { Context context = new Context(); context.putVar("list2", new ArrayList<>(Arrays.asList("D", "E"))); JxlsTester tester = JxlsTester.xlsx(getClass(), "illegalArea"); try { tester.processTemplate(context); Assert.fail("JxlsException expected!"); } catch (JxlsException e) { Assert.assertTrue("Unexpected exception: " + e.getMessage(), e.getMessage().contains("Illegal area")); } } }
[ "public", "class", "Issue93Test", "{", "@", "Test", "public", "void", "test", "(", ")", "{", "Context", "context", "=", "new", "Context", "(", ")", "{", "public", "Object", "getVar", "(", "String", "name", ")", "{", "if", "(", "name", ".", "substring", "(", "0", ",", "1", ")", "==", "\"", "m", "\"", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "getVar: var starts with 'm'", "\"", ")", ";", "}", "return", "super", ".", "getVar", "(", "name", ")", ";", "}", "}", ";", "context", ".", "putVar", "(", "\"", "list", "\"", ",", "new", "ArrayList", "<", ">", "(", "Arrays", ".", "asList", "(", "\"", "A", "\"", ",", "\"", "B", "\"", ",", "\"", "C", "\"", ")", ")", ")", ";", "context", ".", "putVar", "(", "\"", "list2", "\"", ",", "new", "ArrayList", "<", ">", "(", "Arrays", ".", "asList", "(", "\"", "D", "\"", ",", "\"", "E", "\"", ")", ")", ")", ";", "context", ".", "putVar", "(", "\"", "i", "\"", ",", "-", "42d", ")", ";", "JxlsTester", "tester", "=", "JxlsTester", ".", "xlsx", "(", "getClass", "(", ")", ")", ";", "tester", ".", "processTemplate", "(", "context", ")", ";", "try", "(", "TestWorkbook", "w", "=", "tester", ".", "getWorkbook", "(", ")", ")", "{", "w", ".", "selectSheet", "(", "0", ")", ";", "Assert", ".", "assertEquals", "(", "\"", "varIndex was not saved!", "\"", ",", "-", "42d", ",", "w", ".", "getCellValueAsDouble", "(", "7", ",", "2", ")", ",", "0.1d", ")", ";", "Assert", ".", "assertEquals", "(", "\"", "E", "\"", ",", "w", ".", "getCellValueAsString", "(", "10", ",", "1", ")", ")", ";", "}", "}", "@", "Test", "public", "void", "wrongLastCellInTemplate", "(", ")", "{", "Context", "context", "=", "new", "Context", "(", ")", ";", "context", ".", "putVar", "(", "\"", "list2", "\"", ",", "new", "ArrayList", "<", ">", "(", "Arrays", ".", "asList", "(", "\"", "D", "\"", ",", "\"", "E", "\"", ")", ")", ")", ";", "JxlsTester", "tester", "=", "JxlsTester", ".", "xlsx", "(", "getClass", "(", ")", ",", "\"", "illegalArea", "\"", ")", ";", "try", "{", "tester", ".", "processTemplate", "(", "context", ")", ";", "Assert", ".", "fail", "(", "\"", "JxlsException expected!", "\"", ")", ";", "}", "catch", "(", "JxlsException", "e", ")", "{", "Assert", ".", "assertTrue", "(", "\"", "Unexpected exception: ", "\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ".", "getMessage", "(", ")", ".", "contains", "(", "\"", "Illegal area", "\"", ")", ")", ";", "}", "}", "}" ]
Checks whether EachCommand saves varIndex before the loop and restores it after the loop.
[ "Checks", "whether", "EachCommand", "saves", "varIndex", "before", "the", "loop", "and", "restores", "it", "after", "the", "loop", "." ]
[ "// Prepare", "// Do an operation that could result in a NPE.", "// Test", "// Verify" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b00b84aaf326b7d7ea7dc893c88fe7d189aa1c3
suriruhani/main
src/main/java/seedu/address/logic/commands/EmptyBinCommand.java
[ "MIT" ]
Java
EmptyBinCommand
/** * Clears sources in the recycle bin. */
Clears sources in the recycle bin.
[ "Clears", "sources", "in", "the", "recycle", "bin", "." ]
public class EmptyBinCommand extends Command { public static final String COMMAND_WORD = "empty-bin"; public static final String MESSAGE_EMPTY_BIN_SUCCESS = "Recycle Bin has been emptied!"; @Override public CommandResult execute(Model model, CommandHistory history) { requireNonNull(model); model.setDeletedSources(new DeletedSources()); model.commitDeletedSources(); return new CommandResult(MESSAGE_EMPTY_BIN_SUCCESS); } }
[ "public", "class", "EmptyBinCommand", "extends", "Command", "{", "public", "static", "final", "String", "COMMAND_WORD", "=", "\"", "empty-bin", "\"", ";", "public", "static", "final", "String", "MESSAGE_EMPTY_BIN_SUCCESS", "=", "\"", "Recycle Bin has been emptied!", "\"", ";", "@", "Override", "public", "CommandResult", "execute", "(", "Model", "model", ",", "CommandHistory", "history", ")", "{", "requireNonNull", "(", "model", ")", ";", "model", ".", "setDeletedSources", "(", "new", "DeletedSources", "(", ")", ")", ";", "model", ".", "commitDeletedSources", "(", ")", ";", "return", "new", "CommandResult", "(", "MESSAGE_EMPTY_BIN_SUCCESS", ")", ";", "}", "}" ]
Clears sources in the recycle bin.
[ "Clears", "sources", "in", "the", "recycle", "bin", "." ]
[]
[ { "param": "Command", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Command", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b08a91393e34a9c61571a170fd7650ed7a300f8
karreypradeep/BlueSpaceTechEmailApp
EmailApp/src/main/java/com/bluespacetech/notifications/email/service/EmailContactGroupServiceImpl.java
[ "Apache-2.0" ]
Java
EmailContactGroupServiceImpl
/** * class for EmailContactGroupService * * @author pradeep created date 25-June-2015 */
@author pradeep created date 25-June-2015
[ "@author", "pradeep", "created", "date", "25", "-", "June", "-", "2015" ]
@Service @Transactional(rollbackFor = { Exception.class, RuntimeException.class, BusinessException.class, ApplicationException.class }) @PreAuthorize("hasAuthority('EXCLUDE_ALL')") public class EmailContactGroupServiceImpl implements EmailContactGroupService { @Autowired private EmailContactGroupRepository emailContactGroupRepository; @Override @PreAuthorize("hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')") public EmailContactGroup createEmailContactGroup(final EmailContactGroup emailContactGroup) throws BusinessException { final EmailContactGroup newEmailContactGroup = emailContactGroupRepository.save(emailContactGroup); return newEmailContactGroup; } @Override @PreAuthorize("hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')") public List<EmailContactGroup> createEmailContactGroups(final List<EmailContactGroup> emailContactGroups) throws BusinessException { final List<EmailContactGroup> result = emailContactGroupRepository.save(emailContactGroups); return result; } @Override @PreAuthorize("hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')") public List<EmailContactGroup> findAll() { return emailContactGroupRepository.findAll(); } @Override @PreAuthorize("hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')") public EmailContactGroup findByContactIdAndGroupIdAndRandomNumber(Long contactId, Long groupId, Long randomNumber) { return emailContactGroupRepository.findByContactIdAndGroupIdAndRandomNumber(contactId, groupId, randomNumber); } @Override @PreAuthorize("hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')") public EmailContactGroup updateEmailContactGroup(EmailContactGroup emailContactGroup) throws BusinessException { final EmailContactGroup newEmailContactGroup = emailContactGroupRepository.save(emailContactGroup); return newEmailContactGroup; } }
[ "@", "Service", "@", "Transactional", "(", "rollbackFor", "=", "{", "Exception", ".", "class", ",", "RuntimeException", ".", "class", ",", "BusinessException", ".", "class", ",", "ApplicationException", ".", "class", "}", ")", "@", "PreAuthorize", "(", "\"", "hasAuthority('EXCLUDE_ALL')", "\"", ")", "public", "class", "EmailContactGroupServiceImpl", "implements", "EmailContactGroupService", "{", "@", "Autowired", "private", "EmailContactGroupRepository", "emailContactGroupRepository", ";", "@", "Override", "@", "PreAuthorize", "(", "\"", "hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')", "\"", ")", "public", "EmailContactGroup", "createEmailContactGroup", "(", "final", "EmailContactGroup", "emailContactGroup", ")", "throws", "BusinessException", "{", "final", "EmailContactGroup", "newEmailContactGroup", "=", "emailContactGroupRepository", ".", "save", "(", "emailContactGroup", ")", ";", "return", "newEmailContactGroup", ";", "}", "@", "Override", "@", "PreAuthorize", "(", "\"", "hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')", "\"", ")", "public", "List", "<", "EmailContactGroup", ">", "createEmailContactGroups", "(", "final", "List", "<", "EmailContactGroup", ">", "emailContactGroups", ")", "throws", "BusinessException", "{", "final", "List", "<", "EmailContactGroup", ">", "result", "=", "emailContactGroupRepository", ".", "save", "(", "emailContactGroups", ")", ";", "return", "result", ";", "}", "@", "Override", "@", "PreAuthorize", "(", "\"", "hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')", "\"", ")", "public", "List", "<", "EmailContactGroup", ">", "findAll", "(", ")", "{", "return", "emailContactGroupRepository", ".", "findAll", "(", ")", ";", "}", "@", "Override", "@", "PreAuthorize", "(", "\"", "hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')", "\"", ")", "public", "EmailContactGroup", "findByContactIdAndGroupIdAndRandomNumber", "(", "Long", "contactId", ",", "Long", "groupId", ",", "Long", "randomNumber", ")", "{", "return", "emailContactGroupRepository", ".", "findByContactIdAndGroupIdAndRandomNumber", "(", "contactId", ",", "groupId", ",", "randomNumber", ")", ";", "}", "@", "Override", "@", "PreAuthorize", "(", "\"", "hasAuthority('ACC_TYPE_SUPER_ADMIN') or hasAuthority('ACCESS_SEND_EMAIL')", "\"", ")", "public", "EmailContactGroup", "updateEmailContactGroup", "(", "EmailContactGroup", "emailContactGroup", ")", "throws", "BusinessException", "{", "final", "EmailContactGroup", "newEmailContactGroup", "=", "emailContactGroupRepository", ".", "save", "(", "emailContactGroup", ")", ";", "return", "newEmailContactGroup", ";", "}", "}" ]
class for EmailContactGroupService
[ "class", "for", "EmailContactGroupService" ]
[]
[ { "param": "EmailContactGroupService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EmailContactGroupService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b0a4088be118feaece281c5d81b0ce9616e6752
aviraljanveja/Java
Tutorials/Chapter 4 - Control Statements/36 - Switch.java
[ "MIT" ]
Java
Switch
/** * @author AviralJanveja * An improved version of the if-else-ef season program. * Using switch without the optional 'break' statement. */
@author AviralJanveja An improved version of the if-else-ef season program. Using switch without the optional 'break' statement.
[ "@author", "AviralJanveja", "An", "improved", "version", "of", "the", "if", "-", "else", "-", "ef", "season", "program", ".", "Using", "switch", "without", "the", "optional", "'", "break", "'", "statement", "." ]
public class Switch { public static void main(String[] args) { int month = 4; String season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; default: season = "No month like that!"; } System.out.println("April falls in the " + season + " season."); } }
[ "public", "class", "Switch", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "int", "month", "=", "4", ";", "String", "season", ";", "switch", "(", "month", ")", "{", "case", "12", ":", "case", "1", ":", "case", "2", ":", "season", "=", "\"", "Winter", "\"", ";", "break", ";", "case", "3", ":", "case", "4", ":", "case", "5", ":", "season", "=", "\"", "Spring", "\"", ";", "break", ";", "case", "6", ":", "case", "7", ":", "case", "8", ":", "season", "=", "\"", "Summer", "\"", ";", "break", ";", "default", ":", "season", "=", "\"", "No month like that!", "\"", ";", "}", "System", ".", "out", ".", "println", "(", "\"", "April falls in the ", "\"", "+", "season", "+", "\"", " season.", "\"", ")", ";", "}", "}" ]
@author AviralJanveja An improved version of the if-else-ef season program.
[ "@author", "AviralJanveja", "An", "improved", "version", "of", "the", "if", "-", "else", "-", "ef", "season", "program", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b0a7cf4330a00b29ff9c3609045ae536ae92e36
kennylbj/thread-homework
src/main/java/timer/Timer.java
[ "MIT" ]
Java
Timer
/** * Created by kennylbj on 16/8/27. * Timer is designed to be thread-safe. * */
Created by kennylbj on 16/8/27. Timer is designed to be thread-safe.
[ "Created", "by", "kennylbj", "on", "16", "/", "8", "/", "27", ".", "Timer", "is", "designed", "to", "be", "thread", "-", "safe", "." ]
@ThreadSafe public class Timer { private static final int SECONDS_TO_NANOSECONDS = 1000 * 1000 * 1000; //in order to add task from other threads. private final BlockingQueue<TimerEvent> timers; private volatile boolean stop = false; public Timer() { timers = new PriorityBlockingQueue<>(); } public void addTimerEventInSeconds(long expirationTime, Runnable task) { addTimerEventInNanoSeconds(expirationTime * SECONDS_TO_NANOSECONDS, task); } public void addTimerEventInNanoSeconds(long expirationTime, Runnable task) { checkArgument(expirationTime >= 0, "expiration time can't not less than 0"); checkNotNull(task); long expirationNs = System.nanoTime() + expirationTime; timers.add(new TimerEvent(expirationNs, task)); } //FIXME wait and notify public void loop() { while (!stop) { triggerExpiredTimers(System.nanoTime()); } } public void stop() { stop = true; } //FIXME should we synchronize it? timers will only be add but never //removed from other thread, so it's safe to do in this way. private void triggerExpiredTimers(long currentTime) { while (!timers.isEmpty()) { long nextExpiredTime = timers.peek().getExpirationTime(); if (nextExpiredTime <= currentTime) { timers.poll().getTask().run(); } else { return; } } } private static class TimerEvent implements Comparable<TimerEvent> { private final long expirationTime; private final Runnable task; TimerEvent(long expirationTime, Runnable task) { this.expirationTime = expirationTime; this.task = task; } @Override public int compareTo(TimerEvent other) { return Long.compare(expirationTime, other.expirationTime); } public long getExpirationTime() { return expirationTime; } public Runnable getTask() { return task; } } }
[ "@", "ThreadSafe", "public", "class", "Timer", "{", "private", "static", "final", "int", "SECONDS_TO_NANOSECONDS", "=", "1000", "*", "1000", "*", "1000", ";", "private", "final", "BlockingQueue", "<", "TimerEvent", ">", "timers", ";", "private", "volatile", "boolean", "stop", "=", "false", ";", "public", "Timer", "(", ")", "{", "timers", "=", "new", "PriorityBlockingQueue", "<", ">", "(", ")", ";", "}", "public", "void", "addTimerEventInSeconds", "(", "long", "expirationTime", ",", "Runnable", "task", ")", "{", "addTimerEventInNanoSeconds", "(", "expirationTime", "*", "SECONDS_TO_NANOSECONDS", ",", "task", ")", ";", "}", "public", "void", "addTimerEventInNanoSeconds", "(", "long", "expirationTime", ",", "Runnable", "task", ")", "{", "checkArgument", "(", "expirationTime", ">=", "0", ",", "\"", "expiration time can't not less than 0", "\"", ")", ";", "checkNotNull", "(", "task", ")", ";", "long", "expirationNs", "=", "System", ".", "nanoTime", "(", ")", "+", "expirationTime", ";", "timers", ".", "add", "(", "new", "TimerEvent", "(", "expirationNs", ",", "task", ")", ")", ";", "}", "public", "void", "loop", "(", ")", "{", "while", "(", "!", "stop", ")", "{", "triggerExpiredTimers", "(", "System", ".", "nanoTime", "(", ")", ")", ";", "}", "}", "public", "void", "stop", "(", ")", "{", "stop", "=", "true", ";", "}", "private", "void", "triggerExpiredTimers", "(", "long", "currentTime", ")", "{", "while", "(", "!", "timers", ".", "isEmpty", "(", ")", ")", "{", "long", "nextExpiredTime", "=", "timers", ".", "peek", "(", ")", ".", "getExpirationTime", "(", ")", ";", "if", "(", "nextExpiredTime", "<=", "currentTime", ")", "{", "timers", ".", "poll", "(", ")", ".", "getTask", "(", ")", ".", "run", "(", ")", ";", "}", "else", "{", "return", ";", "}", "}", "}", "private", "static", "class", "TimerEvent", "implements", "Comparable", "<", "TimerEvent", ">", "{", "private", "final", "long", "expirationTime", ";", "private", "final", "Runnable", "task", ";", "TimerEvent", "(", "long", "expirationTime", ",", "Runnable", "task", ")", "{", "this", ".", "expirationTime", "=", "expirationTime", ";", "this", ".", "task", "=", "task", ";", "}", "@", "Override", "public", "int", "compareTo", "(", "TimerEvent", "other", ")", "{", "return", "Long", ".", "compare", "(", "expirationTime", ",", "other", ".", "expirationTime", ")", ";", "}", "public", "long", "getExpirationTime", "(", ")", "{", "return", "expirationTime", ";", "}", "public", "Runnable", "getTask", "(", ")", "{", "return", "task", ";", "}", "}", "}" ]
Created by kennylbj on 16/8/27.
[ "Created", "by", "kennylbj", "on", "16", "/", "8", "/", "27", "." ]
[ "//in order to add task from other threads.", "//FIXME wait and notify", "//FIXME should we synchronize it? timers will only be add but never", "//removed from other thread, so it's safe to do in this way." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b0c4520b6b71d2b0775b4f2d2e111fe5ea6f870
Sophos06/spice86
src/main/java/spice86/emulator/callback/IndexBasedDispatcher.java
[ "Apache-2.0" ]
Java
IndexBasedDispatcher
/** * Base class for most classes having to dispatch operations depending on a numeric value, like interrupts. */
Base class for most classes having to dispatch operations depending on a numeric value, like interrupts.
[ "Base", "class", "for", "most", "classes", "having", "to", "dispatch", "operations", "depending", "on", "a", "numeric", "value", "like", "interrupts", "." ]
public abstract class IndexBasedDispatcher<T extends CheckedRunnable<UnhandledOperationException>> { protected Map<Integer, T> dispatchTable = new HashMap<>(); public void run(Integer index) throws UnhandledOperationException { T handler = dispatchTable.get(index); if (handler == null) { throw generateUnhandledOperationException(index); } handler.run(); } public void addService(int index, T runnable) { this.dispatchTable.put(index, runnable); } protected abstract UnhandledOperationException generateUnhandledOperationException(int index); }
[ "public", "abstract", "class", "IndexBasedDispatcher", "<", "T", "extends", "CheckedRunnable", "<", "UnhandledOperationException", ">", ">", "{", "protected", "Map", "<", "Integer", ",", "T", ">", "dispatchTable", "=", "new", "HashMap", "<", ">", "(", ")", ";", "public", "void", "run", "(", "Integer", "index", ")", "throws", "UnhandledOperationException", "{", "T", "handler", "=", "dispatchTable", ".", "get", "(", "index", ")", ";", "if", "(", "handler", "==", "null", ")", "{", "throw", "generateUnhandledOperationException", "(", "index", ")", ";", "}", "handler", ".", "run", "(", ")", ";", "}", "public", "void", "addService", "(", "int", "index", ",", "T", "runnable", ")", "{", "this", ".", "dispatchTable", ".", "put", "(", "index", ",", "runnable", ")", ";", "}", "protected", "abstract", "UnhandledOperationException", "generateUnhandledOperationException", "(", "int", "index", ")", ";", "}" ]
Base class for most classes having to dispatch operations depending on a numeric value, like interrupts.
[ "Base", "class", "for", "most", "classes", "having", "to", "dispatch", "operations", "depending", "on", "a", "numeric", "value", "like", "interrupts", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b0e52011ed2b61ac2402b004de48375a152bda0
adamkorynta/opendcs
src/main/java/lrgs/drgs/DrgsEvtThread.java
[ "Apache-2.0" ]
Java
DrgsEvtThread
/** This thread handles interaction with the DRGS events socket. The client (me) sends a Poll sequence. The Server (DRGS) responds with an event or a code indicating that no events are currently available. */
This thread handles interaction with the DRGS events socket. The client (me) sends a Poll sequence. The Server (DRGS) responds with an event or a code indicating that no events are currently available.
[ "This", "thread", "handles", "interaction", "with", "the", "DRGS", "events", "socket", ".", "The", "client", "(", "me", ")", "sends", "a", "Poll", "sequence", ".", "The", "Server", "(", "DRGS", ")", "responds", "with", "an", "event", "or", "a", "code", "indicating", "that", "no", "events", "are", "currently", "available", "." ]
public class DrgsEvtThread extends BasicClient implements Runnable { boolean configChanged; boolean running; boolean enabled; long lastConnectAttempt; static byte EventPoll[] = {(byte)'P', (byte)'\r', (byte)'\n' }; private StringBuffer linebuf; private static SimpleDateFormat goesDateFormat = null; /** Constructor. Configuration is handled by the configure method. */ public DrgsEvtThread() { super("", 17011); configChanged = true; running = true; enabled = true; linebuf = new StringBuffer(); if (goesDateFormat == null) { goesDateFormat = new SimpleDateFormat("yyDDDHHmmss"); java.util.TimeZone jtz=java.util.TimeZone.getTimeZone("UTC"); goesDateFormat.setCalendar(Calendar.getInstance(jtz)); } } /** Thread run method. Until shutdown call is received, this method continually polls for new events. If no events available, sleep 1 sec before trying again. */ public void run() { try{ Thread.sleep(4000L); } // sleep 4 sec. before going. catch(InterruptedException ex) {} while(running) { long now = System.currentTimeMillis(); if (configChanged) { configChanged = false; disconnect(); if (enabled) tryConnect(); } if (enabled && !isConnected() && now - getLastConnectAttempt() > 10000L) tryConnect(); if (!isConnected()) { try{ Thread.sleep(1000L); } catch(InterruptedException ex) {} } else { try { DrgsEvent evt = getEvent(); if (evt != null) logEvent(evt); else { // 1 sec. pause waiting for more data to arrive. try { Thread.sleep(1000L); } catch(InterruptedException ex) {} } } catch(IOException ex) { log(Logger.E_WARNING, "Error on DAMS-NT Event Socket: " + ex); disconnect(); } } } disconnect(); if (enabled) log(Logger.E_INFORMATION, "Shutting down and exiting."); } /** Configures the event thread. @param host DRGS host name @param port Port number for events @param enable true if the events interface is enabled. */ void configure(String host, int port, boolean enable) { this.enabled = enable; if (!enabled) disconnect(); if (!getHost().equalsIgnoreCase(host) || getPort() != port) { setHost(host); setPort(port); configChanged = true; } log(Logger.E_INFORMATION, " configured with " + host + ":" + port + " enabled=" + enabled); } /** Tells this thread to shutdown and exit. */ void shutdown() { running = false; } private void tryConnect() { log(Logger.E_DEBUG1, "Attempting connection."); try { connect(); } catch(IOException ex) { log(Logger.E_WARNING, "Connection failed: " + ex); return; } log(Logger.E_INFORMATION, "Connected."); } /** Prints a log message with a host/port prefix. */ private void log(int level, String text) { Logger.instance().log(level, getName() + ": " + text); } /** Returns string of the form "EvtSock(host:port)". */ public String getName() { return "EvtSock(" + super.getName() + ")"; } /** Internal method that sends the poll and then gets the response. */ private DrgsEvent getEvent() throws IOException { output.write(EventPoll); output.flush(); // Wait as long as 5 seconds for the response. linebuf.setLength(0); long now = System.currentTimeMillis(); while(System.currentTimeMillis() - now < 5000L) { int avail = input.available(); while(avail-- > 0) { char c = (char)input.read(); if (c == '\n') return processLine(linebuf.toString()); linebuf.append(c); } try { Thread.sleep(100L);} catch(InterruptedException ex) {} } // timeout waiting for response. disconnect to force re-sync. log(Logger.E_INFORMATION, "Timeout waiting for response to poll -- disconnecting."); disconnect(); return null; } /** Logs the event to the current default logger. */ private void logEvent(DrgsEvent evt) { // For now, just log this event to the default logger. log(evt.priority, "DRGS Event Received: " + evt.text); } /** Processes the response from the DRGS. */ private DrgsEvent processLine(String line) { StringTokenizer tokenizer = new StringTokenizer(line); int count = tokenizer.countTokens(); if (count < 0) { log(Logger.E_WARNING, "Empty event response received."); return null; } String s = tokenizer.nextToken(); if (s.equalsIgnoreCase("none")) return null; char c = s.charAt(0); if (!Character.isDigit(c)) { log(Logger.E_WARNING, "Improper priority value in response '" + line + "'"); return null; } int priority = (int)c - (int)'0'; // DRGS priorities are inverted from LRGS. Convert to one of the // value in Logger. priority = 7 - priority; if (priority < Logger.E_DEBUG3) priority = Logger.E_DEBUG3; if (priority > Logger.E_FATAL) priority = Logger.E_FATAL; if (!tokenizer.hasMoreTokens()) { log(Logger.E_WARNING, "Missing timestamp value in response '" + line + "'"); return null; } s = tokenizer.nextToken(); Date timestamp = goesDateFormat.parse(s, new ParsePosition(0)); if (timestamp == null) { log(Logger.E_WARNING, "Invalid timestamp '" + s + "' in response '" + line + "'"); return null; } StringBuffer text = new StringBuffer(); for(int i=0; tokenizer.hasMoreTokens(); i++) { if (i > 0) text.append(' '); text.append(tokenizer.nextToken()); } return new DrgsEvent(priority, timestamp, text.toString()); } }
[ "public", "class", "DrgsEvtThread", "extends", "BasicClient", "implements", "Runnable", "{", "boolean", "configChanged", ";", "boolean", "running", ";", "boolean", "enabled", ";", "long", "lastConnectAttempt", ";", "static", "byte", "EventPoll", "[", "]", "=", "{", "(", "byte", ")", "'P'", ",", "(", "byte", ")", "'\\r'", ",", "(", "byte", ")", "'\\n'", "}", ";", "private", "StringBuffer", "linebuf", ";", "private", "static", "SimpleDateFormat", "goesDateFormat", "=", "null", ";", "/**\n\t Constructor.\n\t Configuration is handled by the configure method.\n\t*/", "public", "DrgsEvtThread", "(", ")", "{", "super", "(", "\"", "\"", ",", "17011", ")", ";", "configChanged", "=", "true", ";", "running", "=", "true", ";", "enabled", "=", "true", ";", "linebuf", "=", "new", "StringBuffer", "(", ")", ";", "if", "(", "goesDateFormat", "==", "null", ")", "{", "goesDateFormat", "=", "new", "SimpleDateFormat", "(", "\"", "yyDDDHHmmss", "\"", ")", ";", "java", ".", "util", ".", "TimeZone", "jtz", "=", "java", ".", "util", ".", "TimeZone", ".", "getTimeZone", "(", "\"", "UTC", "\"", ")", ";", "goesDateFormat", ".", "setCalendar", "(", "Calendar", ".", "getInstance", "(", "jtz", ")", ")", ";", "}", "}", "/**\n\t Thread run method.\n\t Until shutdown call is received, this method continually polls\n\t for new events. If no events available, sleep 1 sec before trying\n\t again.\n\t*/", "public", "void", "run", "(", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "4000L", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "}", "while", "(", "running", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "configChanged", ")", "{", "configChanged", "=", "false", ";", "disconnect", "(", ")", ";", "if", "(", "enabled", ")", "tryConnect", "(", ")", ";", "}", "if", "(", "enabled", "&&", "!", "isConnected", "(", ")", "&&", "now", "-", "getLastConnectAttempt", "(", ")", ">", "10000L", ")", "tryConnect", "(", ")", ";", "if", "(", "!", "isConnected", "(", ")", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "1000L", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "}", "}", "else", "{", "try", "{", "DrgsEvent", "evt", "=", "getEvent", "(", ")", ";", "if", "(", "evt", "!=", "null", ")", "logEvent", "(", "evt", ")", ";", "else", "{", "try", "{", "Thread", ".", "sleep", "(", "1000L", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "}", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "log", "(", "Logger", ".", "E_WARNING", ",", "\"", "Error on DAMS-NT Event Socket: ", "\"", "+", "ex", ")", ";", "disconnect", "(", ")", ";", "}", "}", "}", "disconnect", "(", ")", ";", "if", "(", "enabled", ")", "log", "(", "Logger", ".", "E_INFORMATION", ",", "\"", "Shutting down and exiting.", "\"", ")", ";", "}", "/**\n\t Configures the event thread.\n\t @param host DRGS host name\n\t @param port Port number for events\n\t @param enable true if the events interface is enabled.\n\t*/", "void", "configure", "(", "String", "host", ",", "int", "port", ",", "boolean", "enable", ")", "{", "this", ".", "enabled", "=", "enable", ";", "if", "(", "!", "enabled", ")", "disconnect", "(", ")", ";", "if", "(", "!", "getHost", "(", ")", ".", "equalsIgnoreCase", "(", "host", ")", "||", "getPort", "(", ")", "!=", "port", ")", "{", "setHost", "(", "host", ")", ";", "setPort", "(", "port", ")", ";", "configChanged", "=", "true", ";", "}", "log", "(", "Logger", ".", "E_INFORMATION", ",", "\"", " configured with ", "\"", "+", "host", "+", "\"", ":", "\"", "+", "port", "+", "\"", " enabled=", "\"", "+", "enabled", ")", ";", "}", "/**\n\t Tells this thread to shutdown and exit.\n\t*/", "void", "shutdown", "(", ")", "{", "running", "=", "false", ";", "}", "private", "void", "tryConnect", "(", ")", "{", "log", "(", "Logger", ".", "E_DEBUG1", ",", "\"", "Attempting connection.", "\"", ")", ";", "try", "{", "connect", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "log", "(", "Logger", ".", "E_WARNING", ",", "\"", "Connection failed: ", "\"", "+", "ex", ")", ";", "return", ";", "}", "log", "(", "Logger", ".", "E_INFORMATION", ",", "\"", "Connected.", "\"", ")", ";", "}", "/** Prints a log message with a host/port prefix. */", "private", "void", "log", "(", "int", "level", ",", "String", "text", ")", "{", "Logger", ".", "instance", "(", ")", ".", "log", "(", "level", ",", "getName", "(", ")", "+", "\"", ": ", "\"", "+", "text", ")", ";", "}", "/** Returns string of the form \"EvtSock(host:port)\". */", "public", "String", "getName", "(", ")", "{", "return", "\"", "EvtSock(", "\"", "+", "super", ".", "getName", "(", ")", "+", "\"", ")", "\"", ";", "}", "/**\n\t Internal method that sends the poll and then gets the response.\n\t*/", "private", "DrgsEvent", "getEvent", "(", ")", "throws", "IOException", "{", "output", ".", "write", "(", "EventPoll", ")", ";", "output", ".", "flush", "(", ")", ";", "linebuf", ".", "setLength", "(", "0", ")", ";", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "while", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "now", "<", "5000L", ")", "{", "int", "avail", "=", "input", ".", "available", "(", ")", ";", "while", "(", "avail", "--", ">", "0", ")", "{", "char", "c", "=", "(", "char", ")", "input", ".", "read", "(", ")", ";", "if", "(", "c", "==", "'\\n'", ")", "return", "processLine", "(", "linebuf", ".", "toString", "(", ")", ")", ";", "linebuf", ".", "append", "(", "c", ")", ";", "}", "try", "{", "Thread", ".", "sleep", "(", "100L", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "}", "}", "log", "(", "Logger", ".", "E_INFORMATION", ",", "\"", "Timeout waiting for response to poll -- disconnecting.", "\"", ")", ";", "disconnect", "(", ")", ";", "return", "null", ";", "}", "/**\n\t Logs the event to the current default logger.\n\t*/", "private", "void", "logEvent", "(", "DrgsEvent", "evt", ")", "{", "log", "(", "evt", ".", "priority", ",", "\"", "DRGS Event Received: ", "\"", "+", "evt", ".", "text", ")", ";", "}", "/** Processes the response from the DRGS. */", "private", "DrgsEvent", "processLine", "(", "String", "line", ")", "{", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "line", ")", ";", "int", "count", "=", "tokenizer", ".", "countTokens", "(", ")", ";", "if", "(", "count", "<", "0", ")", "{", "log", "(", "Logger", ".", "E_WARNING", ",", "\"", "Empty event response received.", "\"", ")", ";", "return", "null", ";", "}", "String", "s", "=", "tokenizer", ".", "nextToken", "(", ")", ";", "if", "(", "s", ".", "equalsIgnoreCase", "(", "\"", "none", "\"", ")", ")", "return", "null", ";", "char", "c", "=", "s", ".", "charAt", "(", "0", ")", ";", "if", "(", "!", "Character", ".", "isDigit", "(", "c", ")", ")", "{", "log", "(", "Logger", ".", "E_WARNING", ",", "\"", "Improper priority value in response '", "\"", "+", "line", "+", "\"", "'", "\"", ")", ";", "return", "null", ";", "}", "int", "priority", "=", "(", "int", ")", "c", "-", "(", "int", ")", "'0'", ";", "priority", "=", "7", "-", "priority", ";", "if", "(", "priority", "<", "Logger", ".", "E_DEBUG3", ")", "priority", "=", "Logger", ".", "E_DEBUG3", ";", "if", "(", "priority", ">", "Logger", ".", "E_FATAL", ")", "priority", "=", "Logger", ".", "E_FATAL", ";", "if", "(", "!", "tokenizer", ".", "hasMoreTokens", "(", ")", ")", "{", "log", "(", "Logger", ".", "E_WARNING", ",", "\"", "Missing timestamp value in response '", "\"", "+", "line", "+", "\"", "'", "\"", ")", ";", "return", "null", ";", "}", "s", "=", "tokenizer", ".", "nextToken", "(", ")", ";", "Date", "timestamp", "=", "goesDateFormat", ".", "parse", "(", "s", ",", "new", "ParsePosition", "(", "0", ")", ")", ";", "if", "(", "timestamp", "==", "null", ")", "{", "log", "(", "Logger", ".", "E_WARNING", ",", "\"", "Invalid timestamp '", "\"", "+", "s", "+", "\"", "' in response '", "\"", "+", "line", "+", "\"", "'", "\"", ")", ";", "return", "null", ";", "}", "StringBuffer", "text", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "tokenizer", ".", "hasMoreTokens", "(", ")", ";", "i", "++", ")", "{", "if", "(", "i", ">", "0", ")", "text", ".", "append", "(", "' '", ")", ";", "text", ".", "append", "(", "tokenizer", ".", "nextToken", "(", ")", ")", ";", "}", "return", "new", "DrgsEvent", "(", "priority", ",", "timestamp", ",", "text", ".", "toString", "(", ")", ")", ";", "}", "}" ]
This thread handles interaction with the DRGS events socket.
[ "This", "thread", "handles", "interaction", "with", "the", "DRGS", "events", "socket", "." ]
[ "// sleep 4 sec. before going.", "// 1 sec. pause waiting for more data to arrive.", "// Wait as long as 5 seconds for the response.", "// timeout waiting for response. disconnect to force re-sync.", "// For now, just log this event to the default logger.", "// DRGS priorities are inverted from LRGS. Convert to one of the", "// value in Logger." ]
[ { "param": "BasicClient", "type": null }, { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BasicClient", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b0ea0fe3a1b7eb529fe5c193deccdc0ee709c84
autophagy/crate
server/src/main/java/io/crate/execution/engine/aggregation/PrimitiveMapWithNulls.java
[ "Apache-2.0" ]
Java
PrimitiveMapWithNulls
/** * Map that extends primitive maps like {@link io.netty.util.collection.IntObjectMap} with support for null keys (but no null values) */
Map that extends primitive maps like io.netty.util.collection.IntObjectMap with support for null keys (but no null values)
[ "Map", "that", "extends", "primitive", "maps", "like", "io", ".", "netty", ".", "util", ".", "collection", ".", "IntObjectMap", "with", "support", "for", "null", "keys", "(", "but", "no", "null", "values", ")" ]
public class PrimitiveMapWithNulls<K, V> implements Map<K, V> { private final Map<K, V> delegate; private V nullKeyValue = null; public PrimitiveMapWithNulls(Map<K, V> delegate) { this.delegate = delegate; } @Override public int size() { return delegate.size() + (nullKeyValue == null ? 0 : 1); } @Override public boolean isEmpty() { return delegate.isEmpty() && nullKeyValue == null; } @Override public boolean containsKey(Object key) { if (key == null) { return nullKeyValue != null; } return delegate.containsKey(key); } @Override public boolean containsValue(Object value) { return delegate.containsValue(value) || value.equals(nullKeyValue); } @Override public V get(Object key) { if (key == null) { return nullKeyValue; } return delegate.get(key); } @Override public V put(K key, V value) { if (key == null) { V v = this.nullKeyValue; this.nullKeyValue = value; return v; } else { return delegate.put(key, value); } } @Override public V remove(Object key) { if (key == null) { V v = this.nullKeyValue; this.nullKeyValue = null; return v; } else { return delegate.remove(key); } } @Override public void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException("putAll is not supported on PrimitiveMapWithNulls"); } @Override public void clear() { nullKeyValue = null; delegate.clear(); } @Override public Set<K> keySet() { if (nullKeyValue == null) { return delegate.keySet(); } else { HashSet<K> ks = new HashSet<>(delegate.keySet()); ks.add(null); return ks; } } @Override public Collection<V> values() { if (nullKeyValue == null) { return delegate.values(); } else { return Lists2.concat(delegate.values(), nullKeyValue); } } @Override public Set<Entry<K, V>> entrySet() { if (nullKeyValue == null) { return delegate.entrySet(); } else { Set<Entry<K, V>> entries = delegate.entrySet(); return new Set<>() { @Override public int size() { return entries.size() + 1; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(Object o) { throw new UnsupportedOperationException(""); } @Override public Iterator<Entry<K, V>> iterator() { Iterator<Entry<K, V>> it = entries.iterator(); return new Iterator<>() { boolean visitedNullKey = false; @Override public boolean hasNext() { if (visitedNullKey == false) { return true; } return it.hasNext(); } @Override public Entry<K, V> next() { if (visitedNullKey == false) { visitedNullKey = true; return new Entry<>() { @Override public K getKey() { return null; } @Override public V getValue() { return nullKeyValue; } @Override public V setValue(V value) { V v = PrimitiveMapWithNulls.this.nullKeyValue; PrimitiveMapWithNulls.this.nullKeyValue = value; return v; } }; } return it.next(); } }; } @Override public Object[] toArray() { throw new UnsupportedOperationException(""); } @Override public <T> T[] toArray(T[] a) { throw new UnsupportedOperationException(""); } @Override public boolean add(Entry<K, V> kvEntry) { throw new UnsupportedOperationException(""); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(""); } @Override public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException(""); } @Override public boolean addAll(Collection<? extends Entry<K, V>> c) { throw new UnsupportedOperationException(""); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(""); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(""); } @Override public void clear() { throw new UnsupportedOperationException(""); } }; } } @Override public V getOrDefault(Object key, V defaultValue) { if (key == null) { return nullKeyValue == null ? defaultValue : nullKeyValue; } return delegate.getOrDefault(key, defaultValue); } @Override public void forEach(BiConsumer<? super K, ? super V> action) { action.accept(null, nullKeyValue); delegate.forEach(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { nullKeyValue = function.apply(null, nullKeyValue); delegate.replaceAll(function); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException("putIfAbsent not implemented"); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException("remove not implemented"); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException("replace not implemented"); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException("replace not implemented"); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException("computeIfAbsent not implemented"); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("computeIfPresent not implemented"); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("compute not implemented"); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("merge not implemented"); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PrimitiveMapWithNulls<?, ?> that = (PrimitiveMapWithNulls<?, ?>) o; if (!delegate.equals(that.delegate)) { return false; } return Objects.equals(nullKeyValue, that.nullKeyValue); } @Override public int hashCode() { int result = delegate.hashCode(); result = 31 * result + (nullKeyValue != null ? nullKeyValue.hashCode() : 0); return result; } }
[ "public", "class", "PrimitiveMapWithNulls", "<", "K", ",", "V", ">", "implements", "Map", "<", "K", ",", "V", ">", "{", "private", "final", "Map", "<", "K", ",", "V", ">", "delegate", ";", "private", "V", "nullKeyValue", "=", "null", ";", "public", "PrimitiveMapWithNulls", "(", "Map", "<", "K", ",", "V", ">", "delegate", ")", "{", "this", ".", "delegate", "=", "delegate", ";", "}", "@", "Override", "public", "int", "size", "(", ")", "{", "return", "delegate", ".", "size", "(", ")", "+", "(", "nullKeyValue", "==", "null", "?", "0", ":", "1", ")", ";", "}", "@", "Override", "public", "boolean", "isEmpty", "(", ")", "{", "return", "delegate", ".", "isEmpty", "(", ")", "&&", "nullKeyValue", "==", "null", ";", "}", "@", "Override", "public", "boolean", "containsKey", "(", "Object", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", "nullKeyValue", "!=", "null", ";", "}", "return", "delegate", ".", "containsKey", "(", "key", ")", ";", "}", "@", "Override", "public", "boolean", "containsValue", "(", "Object", "value", ")", "{", "return", "delegate", ".", "containsValue", "(", "value", ")", "||", "value", ".", "equals", "(", "nullKeyValue", ")", ";", "}", "@", "Override", "public", "V", "get", "(", "Object", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", "nullKeyValue", ";", "}", "return", "delegate", ".", "get", "(", "key", ")", ";", "}", "@", "Override", "public", "V", "put", "(", "K", "key", ",", "V", "value", ")", "{", "if", "(", "key", "==", "null", ")", "{", "V", "v", "=", "this", ".", "nullKeyValue", ";", "this", ".", "nullKeyValue", "=", "value", ";", "return", "v", ";", "}", "else", "{", "return", "delegate", ".", "put", "(", "key", ",", "value", ")", ";", "}", "}", "@", "Override", "public", "V", "remove", "(", "Object", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "V", "v", "=", "this", ".", "nullKeyValue", ";", "this", ".", "nullKeyValue", "=", "null", ";", "return", "v", ";", "}", "else", "{", "return", "delegate", ".", "remove", "(", "key", ")", ";", "}", "}", "@", "Override", "public", "void", "putAll", "(", "Map", "<", "?", "extends", "K", ",", "?", "extends", "V", ">", "m", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "putAll is not supported on PrimitiveMapWithNulls", "\"", ")", ";", "}", "@", "Override", "public", "void", "clear", "(", ")", "{", "nullKeyValue", "=", "null", ";", "delegate", ".", "clear", "(", ")", ";", "}", "@", "Override", "public", "Set", "<", "K", ">", "keySet", "(", ")", "{", "if", "(", "nullKeyValue", "==", "null", ")", "{", "return", "delegate", ".", "keySet", "(", ")", ";", "}", "else", "{", "HashSet", "<", "K", ">", "ks", "=", "new", "HashSet", "<", ">", "(", "delegate", ".", "keySet", "(", ")", ")", ";", "ks", ".", "add", "(", "null", ")", ";", "return", "ks", ";", "}", "}", "@", "Override", "public", "Collection", "<", "V", ">", "values", "(", ")", "{", "if", "(", "nullKeyValue", "==", "null", ")", "{", "return", "delegate", ".", "values", "(", ")", ";", "}", "else", "{", "return", "Lists2", ".", "concat", "(", "delegate", ".", "values", "(", ")", ",", "nullKeyValue", ")", ";", "}", "}", "@", "Override", "public", "Set", "<", "Entry", "<", "K", ",", "V", ">", ">", "entrySet", "(", ")", "{", "if", "(", "nullKeyValue", "==", "null", ")", "{", "return", "delegate", ".", "entrySet", "(", ")", ";", "}", "else", "{", "Set", "<", "Entry", "<", "K", ",", "V", ">", ">", "entries", "=", "delegate", ".", "entrySet", "(", ")", ";", "return", "new", "Set", "<", ">", "(", ")", "{", "@", "Override", "public", "int", "size", "(", ")", "{", "return", "entries", ".", "size", "(", ")", "+", "1", ";", "}", "@", "Override", "public", "boolean", "isEmpty", "(", ")", "{", "return", "false", ";", "}", "@", "Override", "public", "boolean", "contains", "(", "Object", "o", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "Iterator", "<", "Entry", "<", "K", ",", "V", ">", ">", "iterator", "(", ")", "{", "Iterator", "<", "Entry", "<", "K", ",", "V", ">", ">", "it", "=", "entries", ".", "iterator", "(", ")", ";", "return", "new", "Iterator", "<", ">", "(", ")", "{", "boolean", "visitedNullKey", "=", "false", ";", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "if", "(", "visitedNullKey", "==", "false", ")", "{", "return", "true", ";", "}", "return", "it", ".", "hasNext", "(", ")", ";", "}", "@", "Override", "public", "Entry", "<", "K", ",", "V", ">", "next", "(", ")", "{", "if", "(", "visitedNullKey", "==", "false", ")", "{", "visitedNullKey", "=", "true", ";", "return", "new", "Entry", "<", ">", "(", ")", "{", "@", "Override", "public", "K", "getKey", "(", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "V", "getValue", "(", ")", "{", "return", "nullKeyValue", ";", "}", "@", "Override", "public", "V", "setValue", "(", "V", "value", ")", "{", "V", "v", "=", "PrimitiveMapWithNulls", ".", "this", ".", "nullKeyValue", ";", "PrimitiveMapWithNulls", ".", "this", ".", "nullKeyValue", "=", "value", ";", "return", "v", ";", "}", "}", ";", "}", "return", "it", ".", "next", "(", ")", ";", "}", "}", ";", "}", "@", "Override", "public", "Object", "[", "]", "toArray", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "<", "T", ">", "T", "[", "]", "toArray", "(", "T", "[", "]", "a", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "add", "(", "Entry", "<", "K", ",", "V", ">", "kvEntry", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "remove", "(", "Object", "o", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "containsAll", "(", "Collection", "<", "?", ">", "c", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "addAll", "(", "Collection", "<", "?", "extends", "Entry", "<", "K", ",", "V", ">", ">", "c", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "retainAll", "(", "Collection", "<", "?", ">", "c", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "removeAll", "(", "Collection", "<", "?", ">", "c", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "@", "Override", "public", "void", "clear", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "\"", ")", ";", "}", "}", ";", "}", "}", "@", "Override", "public", "V", "getOrDefault", "(", "Object", "key", ",", "V", "defaultValue", ")", "{", "if", "(", "key", "==", "null", ")", "{", "return", "nullKeyValue", "==", "null", "?", "defaultValue", ":", "nullKeyValue", ";", "}", "return", "delegate", ".", "getOrDefault", "(", "key", ",", "defaultValue", ")", ";", "}", "@", "Override", "public", "void", "forEach", "(", "BiConsumer", "<", "?", "super", "K", ",", "?", "super", "V", ">", "action", ")", "{", "action", ".", "accept", "(", "null", ",", "nullKeyValue", ")", ";", "delegate", ".", "forEach", "(", "action", ")", ";", "}", "@", "Override", "public", "void", "replaceAll", "(", "BiFunction", "<", "?", "super", "K", ",", "?", "super", "V", ",", "?", "extends", "V", ">", "function", ")", "{", "nullKeyValue", "=", "function", ".", "apply", "(", "null", ",", "nullKeyValue", ")", ";", "delegate", ".", "replaceAll", "(", "function", ")", ";", "}", "@", "Override", "public", "V", "putIfAbsent", "(", "K", "key", ",", "V", "value", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "putIfAbsent not implemented", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "remove", "(", "Object", "key", ",", "Object", "value", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "remove not implemented", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "replace", "(", "K", "key", ",", "V", "oldValue", ",", "V", "newValue", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "replace not implemented", "\"", ")", ";", "}", "@", "Override", "public", "V", "replace", "(", "K", "key", ",", "V", "value", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "replace not implemented", "\"", ")", ";", "}", "@", "Override", "public", "V", "computeIfAbsent", "(", "K", "key", ",", "Function", "<", "?", "super", "K", ",", "?", "extends", "V", ">", "mappingFunction", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "computeIfAbsent not implemented", "\"", ")", ";", "}", "@", "Override", "public", "V", "computeIfPresent", "(", "K", "key", ",", "BiFunction", "<", "?", "super", "K", ",", "?", "super", "V", ",", "?", "extends", "V", ">", "remappingFunction", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "computeIfPresent not implemented", "\"", ")", ";", "}", "@", "Override", "public", "V", "compute", "(", "K", "key", ",", "BiFunction", "<", "?", "super", "K", ",", "?", "super", "V", ",", "?", "extends", "V", ">", "remappingFunction", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "compute not implemented", "\"", ")", ";", "}", "@", "Override", "public", "V", "merge", "(", "K", "key", ",", "V", "value", ",", "BiFunction", "<", "?", "super", "V", ",", "?", "super", "V", ",", "?", "extends", "V", ">", "remappingFunction", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "merge not implemented", "\"", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "PrimitiveMapWithNulls", "<", "?", ",", "?", ">", "that", "=", "(", "PrimitiveMapWithNulls", "<", "?", ",", "?", ">", ")", "o", ";", "if", "(", "!", "delegate", ".", "equals", "(", "that", ".", "delegate", ")", ")", "{", "return", "false", ";", "}", "return", "Objects", ".", "equals", "(", "nullKeyValue", ",", "that", ".", "nullKeyValue", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "int", "result", "=", "delegate", ".", "hashCode", "(", ")", ";", "result", "=", "31", "*", "result", "+", "(", "nullKeyValue", "!=", "null", "?", "nullKeyValue", ".", "hashCode", "(", ")", ":", "0", ")", ";", "return", "result", ";", "}", "}" ]
Map that extends primitive maps like {@link io.netty.util.collection.IntObjectMap} with support for null keys (but no null values)
[ "Map", "that", "extends", "primitive", "maps", "like", "{", "@link", "io", ".", "netty", ".", "util", ".", "collection", ".", "IntObjectMap", "}", "with", "support", "for", "null", "keys", "(", "but", "no", "null", "values", ")" ]
[]
[ { "param": "Map<K, V>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Map<K, V>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b14906d8b88504f002a7b2df65507ba35d46cf0
w-gates/analysis-model
src/main/java/edu/hm/hafner/analysis/parser/AcuCobolParser.java
[ "MIT" ]
Java
AcuCobolParser
/** * A parser for the Acu Cobol compile. * * @author jerryshea */
A parser for the Acu Cobol compile. @author jerryshea
[ "A", "parser", "for", "the", "Acu", "Cobol", "compile", ".", "@author", "jerryshea" ]
public class AcuCobolParser extends LookaheadParser { private static final long serialVersionUID = -894639209290549425L; private static final String ACU_COBOL_WARNING_PATTERN = "^\\s*(\\[.*\\])?\\s*?(.*), line ([0-9]*): Warning: (.*)$"; /** * Creates a new instance of {@link AcuCobolParser}. */ public AcuCobolParser() { super(ACU_COBOL_WARNING_PATTERN); } @Override protected boolean isLineInteresting(final String line) { return line.contains("Warning"); } @Override protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStream lookahead, final IssueBuilder builder) { return builder.setFileName(matcher.group(2)) .setLineStart(matcher.group(3)) .setCategory(guessCategory(matcher.group(4))) .setMessage(matcher.group(4)) .buildOptional(); } }
[ "public", "class", "AcuCobolParser", "extends", "LookaheadParser", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "894639209290549425L", ";", "private", "static", "final", "String", "ACU_COBOL_WARNING_PATTERN", "=", "\"", "^", "\\\\", "s*(", "\\\\", "[.*", "\\\\", "])?", "\\\\", "s*?(.*), line ([0-9]*): Warning: (.*)$", "\"", ";", "/**\n * Creates a new instance of {@link AcuCobolParser}.\n */", "public", "AcuCobolParser", "(", ")", "{", "super", "(", "ACU_COBOL_WARNING_PATTERN", ")", ";", "}", "@", "Override", "protected", "boolean", "isLineInteresting", "(", "final", "String", "line", ")", "{", "return", "line", ".", "contains", "(", "\"", "Warning", "\"", ")", ";", "}", "@", "Override", "protected", "Optional", "<", "Issue", ">", "createIssue", "(", "final", "Matcher", "matcher", ",", "final", "LookaheadStream", "lookahead", ",", "final", "IssueBuilder", "builder", ")", "{", "return", "builder", ".", "setFileName", "(", "matcher", ".", "group", "(", "2", ")", ")", ".", "setLineStart", "(", "matcher", ".", "group", "(", "3", ")", ")", ".", "setCategory", "(", "guessCategory", "(", "matcher", ".", "group", "(", "4", ")", ")", ")", ".", "setMessage", "(", "matcher", ".", "group", "(", "4", ")", ")", ".", "buildOptional", "(", ")", ";", "}", "}" ]
A parser for the Acu Cobol compile.
[ "A", "parser", "for", "the", "Acu", "Cobol", "compile", "." ]
[]
[ { "param": "LookaheadParser", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LookaheadParser", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b16a079a47b905577382261fa5225ead85b51ac
dolfly/crate
sql/src/main/java/io/crate/metadata/shard/unassigned/UnassignedShard.java
[ "ECL-2.0", "Apache-2.0" ]
Java
UnassignedShard
/** * This class represents an unassigned shard * * An UnassignedShard is a shard that is not yet assigned to any node and therefore doesn't really exist anywhere. * * The {@link io.crate.metadata.sys.SysShardsTableInfo} will encode any shards that aren't assigned to a node * by negating them using {@link #markUnassigned(int)} * * The {@link io.crate.operation.collect.sources.ShardCollectSource} will then collect UnassignedShard * instances for all shardIds that are negative. * * This is only for "select ... from sys.shards" queries. */
This class represents an unassigned shard An UnassignedShard is a shard that is not yet assigned to any node and therefore doesn't really exist anywhere. The io.crate.metadata.sys.SysShardsTableInfo will encode any shards that aren't assigned to a node by negating them using #markUnassigned(int) The io.crate.operation.collect.sources.ShardCollectSource will then collect UnassignedShard instances for all shardIds that are negative. This is only for "select ...
[ "This", "class", "represents", "an", "unassigned", "shard", "An", "UnassignedShard", "is", "a", "shard", "that", "is", "not", "yet", "assigned", "to", "any", "node", "and", "therefore", "doesn", "'", "t", "really", "exist", "anywhere", ".", "The", "io", ".", "crate", ".", "metadata", ".", "sys", ".", "SysShardsTableInfo", "will", "encode", "any", "shards", "that", "aren", "'", "t", "assigned", "to", "a", "node", "by", "negating", "them", "using", "#markUnassigned", "(", "int", ")", "The", "io", ".", "crate", ".", "operation", ".", "collect", ".", "sources", ".", "ShardCollectSource", "will", "then", "collect", "UnassignedShard", "instances", "for", "all", "shardIds", "that", "are", "negative", ".", "This", "is", "only", "for", "\"", "select", "..." ]
public class UnassignedShard { public static boolean isUnassigned(int shardId) { return shardId < 0; } /** * valid shard ids are vom 0 to int.max * this method negates a shard id (0 becomes -1, 1 becomes -2, etc.) * * if the given id is already negative it is returned as is */ public static int markUnassigned(int id) { if (id >= 0) { return (id + 1) * -1; } return id; } /** * converts negative shard ids back to positive * (-1 becomes 0, -2 becomes 1 - the opposite of {@link #markUnassigned(int)} */ public static int markAssigned(int shard) { if (shard < 0) { return (shard * -1) - 1; } return shard; } private final String schemaName; private final String tableName; private final Boolean primary; private final int id; private final String partitionIdent; private final BytesRef state; private static final BytesRef UNASSIGNED = new BytesRef("UNASSIGNED"); private static final BytesRef INITIALIZING = new BytesRef("INITIALIZING"); private Boolean orphanedPartition = false; public UnassignedShard(ShardId shardId, ClusterService clusterService, Boolean primary, ShardRoutingState state) { String index = shardId.index().name(); boolean isBlobIndex = BlobIndices.isBlobIndex(index); String tableName; String ident = ""; if (isBlobIndex) { this.schemaName = BlobSchemaInfo.NAME; tableName = BlobIndices.STRIP_PREFIX.apply(index); } else if (PartitionName.isPartition(index)) { PartitionName partitionName = PartitionName.fromIndexOrTemplate(index); schemaName = partitionName.tableIdent().schema(); tableName = partitionName.tableIdent().name(); ident = partitionName.ident(); if (!clusterService.state().metaData().hasConcreteIndex(tableName)) { orphanedPartition = true; } } else { Matcher matcher = Schemas.SCHEMA_PATTERN.matcher(index); if (matcher.matches()) { this.schemaName = matcher.group(1); tableName = matcher.group(2); } else { this.schemaName = Schemas.DEFAULT_SCHEMA_NAME; tableName = index; } } this.tableName = tableName; partitionIdent = ident; this.primary = primary; this.id = shardId.id(); this.state = state == ShardRoutingState.UNASSIGNED ? UNASSIGNED : INITIALIZING; } public String tableName() { return tableName; } public int id() { return id; } public String schemaName() { return schemaName; } public String partitionIdent() { return partitionIdent; } public Boolean primary() { return primary; } public BytesRef state() { return state; } public Boolean orphanedPartition() { return orphanedPartition; } }
[ "public", "class", "UnassignedShard", "{", "public", "static", "boolean", "isUnassigned", "(", "int", "shardId", ")", "{", "return", "shardId", "<", "0", ";", "}", "/**\n * valid shard ids are vom 0 to int.max\n * this method negates a shard id (0 becomes -1, 1 becomes -2, etc.)\n *\n * if the given id is already negative it is returned as is\n */", "public", "static", "int", "markUnassigned", "(", "int", "id", ")", "{", "if", "(", "id", ">=", "0", ")", "{", "return", "(", "id", "+", "1", ")", "*", "-", "1", ";", "}", "return", "id", ";", "}", "/**\n * converts negative shard ids back to positive\n * (-1 becomes 0, -2 becomes 1 - the opposite of {@link #markUnassigned(int)}\n */", "public", "static", "int", "markAssigned", "(", "int", "shard", ")", "{", "if", "(", "shard", "<", "0", ")", "{", "return", "(", "shard", "*", "-", "1", ")", "-", "1", ";", "}", "return", "shard", ";", "}", "private", "final", "String", "schemaName", ";", "private", "final", "String", "tableName", ";", "private", "final", "Boolean", "primary", ";", "private", "final", "int", "id", ";", "private", "final", "String", "partitionIdent", ";", "private", "final", "BytesRef", "state", ";", "private", "static", "final", "BytesRef", "UNASSIGNED", "=", "new", "BytesRef", "(", "\"", "UNASSIGNED", "\"", ")", ";", "private", "static", "final", "BytesRef", "INITIALIZING", "=", "new", "BytesRef", "(", "\"", "INITIALIZING", "\"", ")", ";", "private", "Boolean", "orphanedPartition", "=", "false", ";", "public", "UnassignedShard", "(", "ShardId", "shardId", ",", "ClusterService", "clusterService", ",", "Boolean", "primary", ",", "ShardRoutingState", "state", ")", "{", "String", "index", "=", "shardId", ".", "index", "(", ")", ".", "name", "(", ")", ";", "boolean", "isBlobIndex", "=", "BlobIndices", ".", "isBlobIndex", "(", "index", ")", ";", "String", "tableName", ";", "String", "ident", "=", "\"", "\"", ";", "if", "(", "isBlobIndex", ")", "{", "this", ".", "schemaName", "=", "BlobSchemaInfo", ".", "NAME", ";", "tableName", "=", "BlobIndices", ".", "STRIP_PREFIX", ".", "apply", "(", "index", ")", ";", "}", "else", "if", "(", "PartitionName", ".", "isPartition", "(", "index", ")", ")", "{", "PartitionName", "partitionName", "=", "PartitionName", ".", "fromIndexOrTemplate", "(", "index", ")", ";", "schemaName", "=", "partitionName", ".", "tableIdent", "(", ")", ".", "schema", "(", ")", ";", "tableName", "=", "partitionName", ".", "tableIdent", "(", ")", ".", "name", "(", ")", ";", "ident", "=", "partitionName", ".", "ident", "(", ")", ";", "if", "(", "!", "clusterService", ".", "state", "(", ")", ".", "metaData", "(", ")", ".", "hasConcreteIndex", "(", "tableName", ")", ")", "{", "orphanedPartition", "=", "true", ";", "}", "}", "else", "{", "Matcher", "matcher", "=", "Schemas", ".", "SCHEMA_PATTERN", ".", "matcher", "(", "index", ")", ";", "if", "(", "matcher", ".", "matches", "(", ")", ")", "{", "this", ".", "schemaName", "=", "matcher", ".", "group", "(", "1", ")", ";", "tableName", "=", "matcher", ".", "group", "(", "2", ")", ";", "}", "else", "{", "this", ".", "schemaName", "=", "Schemas", ".", "DEFAULT_SCHEMA_NAME", ";", "tableName", "=", "index", ";", "}", "}", "this", ".", "tableName", "=", "tableName", ";", "partitionIdent", "=", "ident", ";", "this", ".", "primary", "=", "primary", ";", "this", ".", "id", "=", "shardId", ".", "id", "(", ")", ";", "this", ".", "state", "=", "state", "==", "ShardRoutingState", ".", "UNASSIGNED", "?", "UNASSIGNED", ":", "INITIALIZING", ";", "}", "public", "String", "tableName", "(", ")", "{", "return", "tableName", ";", "}", "public", "int", "id", "(", ")", "{", "return", "id", ";", "}", "public", "String", "schemaName", "(", ")", "{", "return", "schemaName", ";", "}", "public", "String", "partitionIdent", "(", ")", "{", "return", "partitionIdent", ";", "}", "public", "Boolean", "primary", "(", ")", "{", "return", "primary", ";", "}", "public", "BytesRef", "state", "(", ")", "{", "return", "state", ";", "}", "public", "Boolean", "orphanedPartition", "(", ")", "{", "return", "orphanedPartition", ";", "}", "}" ]
This class represents an unassigned shard An UnassignedShard is a shard that is not yet assigned to any node and therefore doesn't really exist anywhere.
[ "This", "class", "represents", "an", "unassigned", "shard", "An", "UnassignedShard", "is", "a", "shard", "that", "is", "not", "yet", "assigned", "to", "any", "node", "and", "therefore", "doesn", "'", "t", "really", "exist", "anywhere", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b1d031fd3b242f97d006c5d96224837f3fa1d65
apache/incubator-taverna-workbench
taverna-ui/src/main/java/org/apache/taverna/lang/ui/treetable/TreeTableModelAdapter.java
[ "Apache-2.0" ]
Java
TreeTableModelAdapter
/** * This is a wrapper class takes a TreeTableModel and implements * the table model interface. The implementation is trivial, with * all of the event dispatching support provided by the superclass: * the AbstractTableModel. * * @version 1.2 10/27/98 * * @author Philip Milne * @author Scott Violet */
This is a wrapper class takes a TreeTableModel and implements the table model interface. The implementation is trivial, with all of the event dispatching support provided by the superclass: the AbstractTableModel. @author Philip Milne @author Scott Violet
[ "This", "is", "a", "wrapper", "class", "takes", "a", "TreeTableModel", "and", "implements", "the", "table", "model", "interface", ".", "The", "implementation", "is", "trivial", "with", "all", "of", "the", "event", "dispatching", "support", "provided", "by", "the", "superclass", ":", "the", "AbstractTableModel", ".", "@author", "Philip", "Milne", "@author", "Scott", "Violet" ]
@SuppressWarnings("serial") public class TreeTableModelAdapter extends AbstractTableModel { JTree tree; TreeTableModel treeTableModel; public TreeTableModelAdapter(TreeTableModel treeTableModel, JTree tree) { this.tree = tree; this.treeTableModel = treeTableModel; tree.addTreeExpansionListener(new TreeExpansionListener() { // Don't use fireTableRowsInserted() here; the selection model // would get updated twice. public void treeExpanded(TreeExpansionEvent event) { fireTableDataChanged(); } public void treeCollapsed(TreeExpansionEvent event) { fireTableDataChanged(); } }); // Install a TreeModelListener that can update the table when // tree changes. We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. treeTableModel.addTreeModelListener(new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } }); } // Wrappers, implementing TableModel interface. public int getColumnCount() { return treeTableModel.getColumnCount(); } public String getColumnName(int column) { return treeTableModel.getColumnName(column); } public Class getColumnClass(int column) { return treeTableModel.getColumnClass(column); } public int getRowCount() { return tree.getRowCount(); } protected Object nodeForRow(int row) { TreePath treePath = tree.getPathForRow(row); if (treePath == null) { return null; } return treePath.getLastPathComponent(); } public Object getValueAt(int row, int column) { return treeTableModel.getValueAt(nodeForRow(row), column); } public boolean isCellEditable(int row, int column) { return treeTableModel.isCellEditable(nodeForRow(row), column); } public void setValueAt(Object value, int row, int column) { treeTableModel.setValueAt(value, nodeForRow(row), column); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { TreePath[] selected = tree.getSelectionPaths(); fireTableDataChanged(); tree.setSelectionPaths(selected); } }); } }
[ "@", "SuppressWarnings", "(", "\"", "serial", "\"", ")", "public", "class", "TreeTableModelAdapter", "extends", "AbstractTableModel", "{", "JTree", "tree", ";", "TreeTableModel", "treeTableModel", ";", "public", "TreeTableModelAdapter", "(", "TreeTableModel", "treeTableModel", ",", "JTree", "tree", ")", "{", "this", ".", "tree", "=", "tree", ";", "this", ".", "treeTableModel", "=", "treeTableModel", ";", "tree", ".", "addTreeExpansionListener", "(", "new", "TreeExpansionListener", "(", ")", "{", "public", "void", "treeExpanded", "(", "TreeExpansionEvent", "event", ")", "{", "fireTableDataChanged", "(", ")", ";", "}", "public", "void", "treeCollapsed", "(", "TreeExpansionEvent", "event", ")", "{", "fireTableDataChanged", "(", ")", ";", "}", "}", ")", ";", "treeTableModel", ".", "addTreeModelListener", "(", "new", "TreeModelListener", "(", ")", "{", "public", "void", "treeNodesChanged", "(", "TreeModelEvent", "e", ")", "{", "delayedFireTableDataChanged", "(", ")", ";", "}", "public", "void", "treeNodesInserted", "(", "TreeModelEvent", "e", ")", "{", "delayedFireTableDataChanged", "(", ")", ";", "}", "public", "void", "treeNodesRemoved", "(", "TreeModelEvent", "e", ")", "{", "delayedFireTableDataChanged", "(", ")", ";", "}", "public", "void", "treeStructureChanged", "(", "TreeModelEvent", "e", ")", "{", "delayedFireTableDataChanged", "(", ")", ";", "}", "}", ")", ";", "}", "public", "int", "getColumnCount", "(", ")", "{", "return", "treeTableModel", ".", "getColumnCount", "(", ")", ";", "}", "public", "String", "getColumnName", "(", "int", "column", ")", "{", "return", "treeTableModel", ".", "getColumnName", "(", "column", ")", ";", "}", "public", "Class", "getColumnClass", "(", "int", "column", ")", "{", "return", "treeTableModel", ".", "getColumnClass", "(", "column", ")", ";", "}", "public", "int", "getRowCount", "(", ")", "{", "return", "tree", ".", "getRowCount", "(", ")", ";", "}", "protected", "Object", "nodeForRow", "(", "int", "row", ")", "{", "TreePath", "treePath", "=", "tree", ".", "getPathForRow", "(", "row", ")", ";", "if", "(", "treePath", "==", "null", ")", "{", "return", "null", ";", "}", "return", "treePath", ".", "getLastPathComponent", "(", ")", ";", "}", "public", "Object", "getValueAt", "(", "int", "row", ",", "int", "column", ")", "{", "return", "treeTableModel", ".", "getValueAt", "(", "nodeForRow", "(", "row", ")", ",", "column", ")", ";", "}", "public", "boolean", "isCellEditable", "(", "int", "row", ",", "int", "column", ")", "{", "return", "treeTableModel", ".", "isCellEditable", "(", "nodeForRow", "(", "row", ")", ",", "column", ")", ";", "}", "public", "void", "setValueAt", "(", "Object", "value", ",", "int", "row", ",", "int", "column", ")", "{", "treeTableModel", ".", "setValueAt", "(", "value", ",", "nodeForRow", "(", "row", ")", ",", "column", ")", ";", "}", "/**\n * Invokes fireTableDataChanged after all the pending events have been\n * processed. SwingUtilities.invokeLater is used to handle this.\n */", "protected", "void", "delayedFireTableDataChanged", "(", ")", "{", "SwingUtilities", ".", "invokeLater", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "TreePath", "[", "]", "selected", "=", "tree", ".", "getSelectionPaths", "(", ")", ";", "fireTableDataChanged", "(", ")", ";", "tree", ".", "setSelectionPaths", "(", "selected", ")", ";", "}", "}", ")", ";", "}", "}" ]
This is a wrapper class takes a TreeTableModel and implements the table model interface.
[ "This", "is", "a", "wrapper", "class", "takes", "a", "TreeTableModel", "and", "implements", "the", "table", "model", "interface", "." ]
[ "// Don't use fireTableRowsInserted() here; the selection model", "// would get updated twice. ", "// Install a TreeModelListener that can update the table when", "// tree changes. We use delayedFireTableDataChanged as we can", "// not be guaranteed the tree will have finished processing", "// the event before us.", "// Wrappers, implementing TableModel interface. " ]
[ { "param": "AbstractTableModel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractTableModel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b1f0f9fb35bc36f5752a8e8ec6f6593d6d06d59
HelloOO7/CTRMapStandardLibrary
src/ctrmap/stdlib/util/ParsingUtils.java
[ "Unlicense" ]
Java
ParsingUtils
/** * Various methods for converting Strings to common types. */
Various methods for converting Strings to common types.
[ "Various", "methods", "for", "converting", "Strings", "to", "common", "types", "." ]
public class ParsingUtils { /** * Parses a String representation of an integer, respecting Java-style radix prefixes. * Returns a user-specified value if the parsing fails. * @param str An input string, as specified in parseBasedInt(String). * @param defValue The value to return if the parsing is unsuccessful. * @return The parse result, or defValue. */ public static int parseBasedIntOrDefault(String str, int defValue){ try { return parseBasedInt(str); } catch (NumberFormatException ex){ return defValue; } } /** * Parses a String representation of an integer, respecting Java-style radix prefixes. * @param str A string with an unprefixed decimal number, a hexadecimal number prefixed with '0x' or a binary number prefixed with '0b'. * @return The integer value parsed from the string. * @throws NumberFormatException See Integer.parseInt */ public static int parseBasedInt(String str){ if (str.startsWith("0x")){ return Integer.parseUnsignedInt(str.substring(2), 16); } if (str.startsWith("-0x")){ return Integer.parseInt(str.substring(2), 16); } if (str.startsWith("0b")){ return Integer.parseInt(str.substring(2), 2); } return Integer.parseInt(str); } public static long parseBasedLong(String str){ if (str.startsWith("0x")){ return Long.parseUnsignedLong(str.substring(2), 16); } if (str.startsWith("-0x")){ return Long.parseLong(str.substring(2), 16); } if (str.startsWith("0b")){ return Long.parseLong(str.substring(2), 2); } return Long.parseLong(str); } }
[ "public", "class", "ParsingUtils", "{", "/**\n\t * Parses a String representation of an integer, respecting Java-style radix prefixes.\n\t * Returns a user-specified value if the parsing fails.\n\t * @param str An input string, as specified in parseBasedInt(String).\n\t * @param defValue The value to return if the parsing is unsuccessful.\n\t * @return The parse result, or defValue.\n\t */", "public", "static", "int", "parseBasedIntOrDefault", "(", "String", "str", ",", "int", "defValue", ")", "{", "try", "{", "return", "parseBasedInt", "(", "str", ")", ";", "}", "catch", "(", "NumberFormatException", "ex", ")", "{", "return", "defValue", ";", "}", "}", "/**\n\t * Parses a String representation of an integer, respecting Java-style radix prefixes.\n\t * @param str A string with an unprefixed decimal number, a hexadecimal number prefixed with '0x' or a binary number prefixed with '0b'.\n\t * @return The integer value parsed from the string.\n\t * @throws NumberFormatException See Integer.parseInt\n\t */", "public", "static", "int", "parseBasedInt", "(", "String", "str", ")", "{", "if", "(", "str", ".", "startsWith", "(", "\"", "0x", "\"", ")", ")", "{", "return", "Integer", ".", "parseUnsignedInt", "(", "str", ".", "substring", "(", "2", ")", ",", "16", ")", ";", "}", "if", "(", "str", ".", "startsWith", "(", "\"", "-0x", "\"", ")", ")", "{", "return", "Integer", ".", "parseInt", "(", "str", ".", "substring", "(", "2", ")", ",", "16", ")", ";", "}", "if", "(", "str", ".", "startsWith", "(", "\"", "0b", "\"", ")", ")", "{", "return", "Integer", ".", "parseInt", "(", "str", ".", "substring", "(", "2", ")", ",", "2", ")", ";", "}", "return", "Integer", ".", "parseInt", "(", "str", ")", ";", "}", "public", "static", "long", "parseBasedLong", "(", "String", "str", ")", "{", "if", "(", "str", ".", "startsWith", "(", "\"", "0x", "\"", ")", ")", "{", "return", "Long", ".", "parseUnsignedLong", "(", "str", ".", "substring", "(", "2", ")", ",", "16", ")", ";", "}", "if", "(", "str", ".", "startsWith", "(", "\"", "-0x", "\"", ")", ")", "{", "return", "Long", ".", "parseLong", "(", "str", ".", "substring", "(", "2", ")", ",", "16", ")", ";", "}", "if", "(", "str", ".", "startsWith", "(", "\"", "0b", "\"", ")", ")", "{", "return", "Long", ".", "parseLong", "(", "str", ".", "substring", "(", "2", ")", ",", "2", ")", ";", "}", "return", "Long", ".", "parseLong", "(", "str", ")", ";", "}", "}" ]
Various methods for converting Strings to common types.
[ "Various", "methods", "for", "converting", "Strings", "to", "common", "types", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b272cece17a3abcb8ea443da67109ddf65ec439
touxiong88/92_mediatek
packages/apps/RCSe/core/src/com/mediatek/rcse/emoticons/PageAdapter.java
[ "Apache-2.0" ]
Java
PageAdapter
/** * Defined the PageAdapter as the display adaptor for emotion icons */
Defined the PageAdapter as the display adaptor for emotion icons
[ "Defined", "the", "PageAdapter", "as", "the", "display", "adaptor", "for", "emotion", "icons" ]
public class PageAdapter extends BaseAdapter { private final Context mContext; private final List<Integer> mResIds; private final int mPage; private static final String TAG = "PageAdapter"; private final HashMap<Integer,OnClickListener> mListenerMap = new HashMap<Integer,OnClickListener>(); /** * OnEmotionItemSelectedListener listener list */ private OnEmotionItemSelectedListener mListener; /** * Defined a listener to notify all the observer the specify emotion item is selected */ public interface OnEmotionItemSelectedListener { void onEmotionItemSelectedListener(PageAdapter adapter, int position); } /** * Register the OnEmotionItemSelectedListener listener * * @param listener The listener to be registered */ public void registerListener(OnEmotionItemSelectedListener listener) { Logger.d(TAG, "registerListener()"); if (listener == null) { Logger.d(TAG, "registerListener() failed because listener is null"); return; } mListener = listener; } /** * Unregister the OnEmotionItemSelectedListener listener */ public void unregisterListener() { Logger.d(TAG, "unregisterListener()"); if (mListener != null) { mListener = null; } } public PageAdapter(Context context, List<Integer> list, int page) { mContext = context; mResIds = list; mPage = page; } @Override public int getCount() { return mResIds.size(); } @Override public Object getItem(int position) { return mResIds.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View currentView = null; if (convertView == null) { currentView = new ImageView(mContext); } else { currentView = convertView; } Integer integer = mResIds.get(position); ImageView imageView = (ImageView) currentView; imageView.setLayoutParams(new GridView.LayoutParams(ChatFragment.EMOTION_ICON_WIDTH, ChatFragment.EMOTION_ICON_HEIGHT)); imageView.setAdjustViewBounds(false); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(integer.intValue()); OnClickListener listener = mListenerMap.get(Integer.valueOf(position)); if (listener == null) { listener = new OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { int index = mPage * ChatFragment.ITEMS_PER_PAGE + position; mListener.onEmotionItemSelectedListener(PageAdapter.this, index); } } }; mListenerMap.put(Integer.valueOf(position), listener); } ((ImageView) currentView).setOnClickListener(listener); return currentView; } }
[ "public", "class", "PageAdapter", "extends", "BaseAdapter", "{", "private", "final", "Context", "mContext", ";", "private", "final", "List", "<", "Integer", ">", "mResIds", ";", "private", "final", "int", "mPage", ";", "private", "static", "final", "String", "TAG", "=", "\"", "PageAdapter", "\"", ";", "private", "final", "HashMap", "<", "Integer", ",", "OnClickListener", ">", "mListenerMap", "=", "new", "HashMap", "<", "Integer", ",", "OnClickListener", ">", "(", ")", ";", "/**\n * OnEmotionItemSelectedListener listener list\n */", "private", "OnEmotionItemSelectedListener", "mListener", ";", "/**\n * Defined a listener to notify all the observer the specify emotion item is selected\n */", "public", "interface", "OnEmotionItemSelectedListener", "{", "void", "onEmotionItemSelectedListener", "(", "PageAdapter", "adapter", ",", "int", "position", ")", ";", "}", "/**\n * Register the OnEmotionItemSelectedListener listener\n * \n * @param listener The listener to be registered\n */", "public", "void", "registerListener", "(", "OnEmotionItemSelectedListener", "listener", ")", "{", "Logger", ".", "d", "(", "TAG", ",", "\"", "registerListener()", "\"", ")", ";", "if", "(", "listener", "==", "null", ")", "{", "Logger", ".", "d", "(", "TAG", ",", "\"", "registerListener() failed because listener is null", "\"", ")", ";", "return", ";", "}", "mListener", "=", "listener", ";", "}", "/**\n * Unregister the OnEmotionItemSelectedListener listener\n */", "public", "void", "unregisterListener", "(", ")", "{", "Logger", ".", "d", "(", "TAG", ",", "\"", "unregisterListener()", "\"", ")", ";", "if", "(", "mListener", "!=", "null", ")", "{", "mListener", "=", "null", ";", "}", "}", "public", "PageAdapter", "(", "Context", "context", ",", "List", "<", "Integer", ">", "list", ",", "int", "page", ")", "{", "mContext", "=", "context", ";", "mResIds", "=", "list", ";", "mPage", "=", "page", ";", "}", "@", "Override", "public", "int", "getCount", "(", ")", "{", "return", "mResIds", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "Object", "getItem", "(", "int", "position", ")", "{", "return", "mResIds", ".", "get", "(", "position", ")", ";", "}", "@", "Override", "public", "long", "getItemId", "(", "int", "position", ")", "{", "return", "position", ";", "}", "@", "Override", "public", "View", "getView", "(", "final", "int", "position", ",", "View", "convertView", ",", "ViewGroup", "parent", ")", "{", "View", "currentView", "=", "null", ";", "if", "(", "convertView", "==", "null", ")", "{", "currentView", "=", "new", "ImageView", "(", "mContext", ")", ";", "}", "else", "{", "currentView", "=", "convertView", ";", "}", "Integer", "integer", "=", "mResIds", ".", "get", "(", "position", ")", ";", "ImageView", "imageView", "=", "(", "ImageView", ")", "currentView", ";", "imageView", ".", "setLayoutParams", "(", "new", "GridView", ".", "LayoutParams", "(", "ChatFragment", ".", "EMOTION_ICON_WIDTH", ",", "ChatFragment", ".", "EMOTION_ICON_HEIGHT", ")", ")", ";", "imageView", ".", "setAdjustViewBounds", "(", "false", ")", ";", "imageView", ".", "setScaleType", "(", "ImageView", ".", "ScaleType", ".", "CENTER", ")", ";", "imageView", ".", "setImageResource", "(", "integer", ".", "intValue", "(", ")", ")", ";", "OnClickListener", "listener", "=", "mListenerMap", ".", "get", "(", "Integer", ".", "valueOf", "(", "position", ")", ")", ";", "if", "(", "listener", "==", "null", ")", "{", "listener", "=", "new", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "if", "(", "mListener", "!=", "null", ")", "{", "int", "index", "=", "mPage", "*", "ChatFragment", ".", "ITEMS_PER_PAGE", "+", "position", ";", "mListener", ".", "onEmotionItemSelectedListener", "(", "PageAdapter", ".", "this", ",", "index", ")", ";", "}", "}", "}", ";", "mListenerMap", ".", "put", "(", "Integer", ".", "valueOf", "(", "position", ")", ",", "listener", ")", ";", "}", "(", "(", "ImageView", ")", "currentView", ")", ".", "setOnClickListener", "(", "listener", ")", ";", "return", "currentView", ";", "}", "}" ]
Defined the PageAdapter as the display adaptor for emotion icons
[ "Defined", "the", "PageAdapter", "as", "the", "display", "adaptor", "for", "emotion", "icons" ]
[]
[ { "param": "BaseAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b30494b2b7f54730bd2fc9628195a2cdbcaa2f1
mmonschau/reflectionLib
src/main/java/eu/mmonschau/reflection/ClassInstanceFactory.java
[ "Apache-2.0" ]
Java
ClassInstanceFactory
/** * Creates a new Instance of a class using a constructor and arguments * * @param <T> * the Class to create * * @see eu.mmonschau.reflection.ClassInstatiator#getInstanceFactory(Class, java.util.List) */
Creates a new Instance of a class using a constructor and arguments @param the Class to create
[ "Creates", "a", "new", "Instance", "of", "a", "class", "using", "a", "constructor", "and", "arguments", "@param", "the", "Class", "to", "create" ]
public class ClassInstanceFactory<T> implements ClassInstanceCreator<T> { private final java.lang.reflect.Constructor<T> constructor; private final Object[] args; @Override public T newInstance() { try { return this.constructor.newInstance(args); } catch (InstantiationException | IllegalAccessException | java.lang.reflect.InvocationTargetException e) { throw new RuntimeException(e); } } /** * Besic constuctor for constructor-calls * @param constructor the constructor * @param args args matching to the constructor */ ClassInstanceFactory(java.lang.reflect.Constructor<T> constructor, Object[] args) { this.constructor = constructor; this.args = args; } }
[ "public", "class", "ClassInstanceFactory", "<", "T", ">", "implements", "ClassInstanceCreator", "<", "T", ">", "{", "private", "final", "java", ".", "lang", ".", "reflect", ".", "Constructor", "<", "T", ">", "constructor", ";", "private", "final", "Object", "[", "]", "args", ";", "@", "Override", "public", "T", "newInstance", "(", ")", "{", "try", "{", "return", "this", ".", "constructor", ".", "newInstance", "(", "args", ")", ";", "}", "catch", "(", "InstantiationException", "|", "IllegalAccessException", "|", "java", ".", "lang", ".", "reflect", ".", "InvocationTargetException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "/**\n\t * Besic constuctor for constructor-calls\n\t * @param constructor the constructor\n\t * @param args args matching to the constructor\n\t */", "ClassInstanceFactory", "(", "java", ".", "lang", ".", "reflect", ".", "Constructor", "<", "T", ">", "constructor", ",", "Object", "[", "]", "args", ")", "{", "this", ".", "constructor", "=", "constructor", ";", "this", ".", "args", "=", "args", ";", "}", "}" ]
Creates a new Instance of a class using a constructor and arguments @param <T> the Class to create
[ "Creates", "a", "new", "Instance", "of", "a", "class", "using", "a", "constructor", "and", "arguments", "@param", "<T", ">", "the", "Class", "to", "create" ]
[]
[ { "param": "ClassInstanceCreator<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ClassInstanceCreator<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b307dfe2b96c74624be9c34530f47780c11e43f
bboyHan/openstack4j
core/src/main/java/org/openstack4j/openstack/octavia/domain/OctaviaMemberV2Update.java
[ "Apache-2.0" ]
Java
OctaviaMemberV2Update
/** * Entity for updating lbaas v2 members * * @author wei */
Entity for updating lbaas v2 members @author wei
[ "Entity", "for", "updating", "lbaas", "v2", "members", "@author", "wei" ]
@JsonRootName("member") @JsonIgnoreProperties(ignoreUnknown = true) public class OctaviaMemberV2Update implements MemberV2Update { private static final long serialVersionUID = 1L; /** * 1~100 */ @JsonProperty("weight") private Integer weight; @JsonProperty("admin_state_up") private boolean adminStateUp = true; @Override public boolean isAdminStateUp() { return adminStateUp; } @Override public Integer getWeight() { return weight; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("weight", weight) .add("adminStateUp", adminStateUp) .toString(); } public static class MemberV2UpdateConcreteBuilder implements MemberV2UpdateBuilder { private OctaviaMemberV2Update m; public MemberV2UpdateConcreteBuilder() { this(new OctaviaMemberV2Update()); } public MemberV2UpdateConcreteBuilder(OctaviaMemberV2Update m) { this.m = m; } /** * {@inheritDoc} */ @Override public MemberV2Update build() { return m; } /** * {@inheritDoc} */ @Override public MemberV2UpdateBuilder from(MemberV2Update in) { m = (OctaviaMemberV2Update) in; return this; } /** * {@inheritDoc} */ @Override public MemberV2UpdateBuilder adminStateUp(boolean adminStateUp) { m.adminStateUp = adminStateUp; return this; } /** * {@inheritDoc} */ @Override public MemberV2UpdateBuilder weight(Integer weight) { m.weight = weight; return this; } } @Override public MemberV2UpdateBuilder toBuilder() { return new MemberV2UpdateConcreteBuilder(this); } public static MemberV2UpdateBuilder builder() { return new MemberV2UpdateConcreteBuilder(); } }
[ "@", "JsonRootName", "(", "\"", "member", "\"", ")", "@", "JsonIgnoreProperties", "(", "ignoreUnknown", "=", "true", ")", "public", "class", "OctaviaMemberV2Update", "implements", "MemberV2Update", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\n * 1~100\n */", "@", "JsonProperty", "(", "\"", "weight", "\"", ")", "private", "Integer", "weight", ";", "@", "JsonProperty", "(", "\"", "admin_state_up", "\"", ")", "private", "boolean", "adminStateUp", "=", "true", ";", "@", "Override", "public", "boolean", "isAdminStateUp", "(", ")", "{", "return", "adminStateUp", ";", "}", "@", "Override", "public", "Integer", "getWeight", "(", ")", "{", "return", "weight", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "MoreObjects", ".", "toStringHelper", "(", "this", ")", ".", "add", "(", "\"", "weight", "\"", ",", "weight", ")", ".", "add", "(", "\"", "adminStateUp", "\"", ",", "adminStateUp", ")", ".", "toString", "(", ")", ";", "}", "public", "static", "class", "MemberV2UpdateConcreteBuilder", "implements", "MemberV2UpdateBuilder", "{", "private", "OctaviaMemberV2Update", "m", ";", "public", "MemberV2UpdateConcreteBuilder", "(", ")", "{", "this", "(", "new", "OctaviaMemberV2Update", "(", ")", ")", ";", "}", "public", "MemberV2UpdateConcreteBuilder", "(", "OctaviaMemberV2Update", "m", ")", "{", "this", ".", "m", "=", "m", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "MemberV2Update", "build", "(", ")", "{", "return", "m", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "MemberV2UpdateBuilder", "from", "(", "MemberV2Update", "in", ")", "{", "m", "=", "(", "OctaviaMemberV2Update", ")", "in", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "MemberV2UpdateBuilder", "adminStateUp", "(", "boolean", "adminStateUp", ")", "{", "m", ".", "adminStateUp", "=", "adminStateUp", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "MemberV2UpdateBuilder", "weight", "(", "Integer", "weight", ")", "{", "m", ".", "weight", "=", "weight", ";", "return", "this", ";", "}", "}", "@", "Override", "public", "MemberV2UpdateBuilder", "toBuilder", "(", ")", "{", "return", "new", "MemberV2UpdateConcreteBuilder", "(", "this", ")", ";", "}", "public", "static", "MemberV2UpdateBuilder", "builder", "(", ")", "{", "return", "new", "MemberV2UpdateConcreteBuilder", "(", ")", ";", "}", "}" ]
Entity for updating lbaas v2 members @author wei
[ "Entity", "for", "updating", "lbaas", "v2", "members", "@author", "wei" ]
[]
[ { "param": "MemberV2Update", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MemberV2Update", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b33f4aceea4a18b9133367447fde2ef589d1df6
weltam/idylfin
src/com/opengamma/financial/convention/StubCalculator.java
[ "ECL-2.0", "Apache-2.0" ]
Java
StubCalculator
/** * Utility to calculate the stub type. */
Utility to calculate the stub type.
[ "Utility", "to", "calculate", "the", "stub", "type", "." ]
public final class StubCalculator { /** * Restricted constructor. */ private StubCalculator() { } //------------------------------------------------------------------------- /** * Calculates the start stub type from a schedule and number of payments per year. * <p> * The {@code DateProvider[]} argument allows callers to pass in arrays of any class * that implements {@code DateProvider}, such as {@code LocalDate[]}. * * @param schedule the schedule, at least size 2, not null * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve * @return the stub type, not null */ public static StubType getStartStubType(final DateProvider[] schedule, final int paymentsPerYear) { return getStartStubType(schedule, paymentsPerYear, false); } /** * Calculates the start stub type from a schedule, number of payments per year and the end of month flag. * <p> * The {@code DateProvider[]} argument allows callers to pass in arrays of any class * that implements {@code DateProvider}, such as {@code LocalDate[]}. * * @param schedule the schedule, at least size 2, not null * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve * @param isEndOfMonthConvention whether to use end of month rules * @return the stub type, not null */ public static StubType getStartStubType(final DateProvider[] schedule, final double paymentsPerYear, final boolean isEndOfMonthConvention) { Validate.notNull(schedule, "schedule"); Validate.noNullElements(schedule, "schedule"); Validate.isTrue(paymentsPerYear > 0); Validate.isTrue(12 % paymentsPerYear == 0); final int months = (int) (12 / paymentsPerYear); final LocalDate first = LocalDate.of(schedule[0]); final LocalDate second = LocalDate.of(schedule[1]); LocalDate date; if (isEndOfMonthConvention && second.matches(CalendricalMatchers.lastDayOfMonth())) { date = second.minusMonths(months); date = date.with(DateAdjusters.lastDayOfMonth()); } else { date = second.minusMonths(months); } if (date.equals(first)) { return StubType.NONE; } if (date.isBefore(first)) { return StubType.SHORT_START; } return StubType.LONG_START; } //------------------------------------------------------------------------- /** * Calculates the end stub type from a schedule and number of payments per year. * <p> * The {@code DateProvider[]} argument allows callers to pass in arrays of any class * that implements {@code DateProvider}, such as {@code LocalDate[]}. * * @param schedule the schedule, at least size 2, not null * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve * @return the stub type, not null */ public static StubType getEndStubType(final DateProvider[] schedule, final int paymentsPerYear) { return getEndStubType(schedule, paymentsPerYear, false); } /** * Calculates the end stub type from a schedule, number of payments per year and the end of month flag. * <p> * The {@code DateProvider[]} argument allows callers to pass in arrays of any class * that implements {@code DateProvider}, such as {@code LocalDate[]}. * * @param schedule the schedule, at least size 2, not null * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve * @param isEndOfMonthConvention whether to use end of month rules * @return the stub type, not null */ public static StubType getEndStubType(final DateProvider[] schedule, final double paymentsPerYear, final boolean isEndOfMonthConvention) { Validate.notNull(schedule, "schedule"); Validate.noNullElements(schedule, "schedule"); Validate.isTrue(paymentsPerYear > 0); Validate.isTrue(12 % paymentsPerYear == 0); final int months = (int) (12 / paymentsPerYear); final int n = schedule.length; final LocalDate first = LocalDate.of(schedule[n - 2]); final LocalDate second = LocalDate.of(schedule[n - 1]); LocalDate date; if (isEndOfMonthConvention && first.matches(CalendricalMatchers.lastDayOfMonth())) { date = first.plusMonths(months); date = date.with(DateAdjusters.lastDayOfMonth()); } else { date = first.plusMonths(months); } if (date.equals(second)) { return StubType.NONE; } if (date.isAfter(second)) { return StubType.SHORT_END; } return StubType.LONG_END; } }
[ "public", "final", "class", "StubCalculator", "{", "/**\n * Restricted constructor.\n */", "private", "StubCalculator", "(", ")", "{", "}", "/**\n * Calculates the start stub type from a schedule and number of payments per year.\n * <p>\n * The {@code DateProvider[]} argument allows callers to pass in arrays of any class\n * that implements {@code DateProvider}, such as {@code LocalDate[]}.\n * \n * @param schedule the schedule, at least size 2, not null\n * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve\n * @return the stub type, not null\n */", "public", "static", "StubType", "getStartStubType", "(", "final", "DateProvider", "[", "]", "schedule", ",", "final", "int", "paymentsPerYear", ")", "{", "return", "getStartStubType", "(", "schedule", ",", "paymentsPerYear", ",", "false", ")", ";", "}", "/**\n * Calculates the start stub type from a schedule, number of payments per year and the end of month flag.\n * <p>\n * The {@code DateProvider[]} argument allows callers to pass in arrays of any class\n * that implements {@code DateProvider}, such as {@code LocalDate[]}.\n * \n * @param schedule the schedule, at least size 2, not null\n * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve\n * @param isEndOfMonthConvention whether to use end of month rules\n * @return the stub type, not null\n */", "public", "static", "StubType", "getStartStubType", "(", "final", "DateProvider", "[", "]", "schedule", ",", "final", "double", "paymentsPerYear", ",", "final", "boolean", "isEndOfMonthConvention", ")", "{", "Validate", ".", "notNull", "(", "schedule", ",", "\"", "schedule", "\"", ")", ";", "Validate", ".", "noNullElements", "(", "schedule", ",", "\"", "schedule", "\"", ")", ";", "Validate", ".", "isTrue", "(", "paymentsPerYear", ">", "0", ")", ";", "Validate", ".", "isTrue", "(", "12", "%", "paymentsPerYear", "==", "0", ")", ";", "final", "int", "months", "=", "(", "int", ")", "(", "12", "/", "paymentsPerYear", ")", ";", "final", "LocalDate", "first", "=", "LocalDate", ".", "of", "(", "schedule", "[", "0", "]", ")", ";", "final", "LocalDate", "second", "=", "LocalDate", ".", "of", "(", "schedule", "[", "1", "]", ")", ";", "LocalDate", "date", ";", "if", "(", "isEndOfMonthConvention", "&&", "second", ".", "matches", "(", "CalendricalMatchers", ".", "lastDayOfMonth", "(", ")", ")", ")", "{", "date", "=", "second", ".", "minusMonths", "(", "months", ")", ";", "date", "=", "date", ".", "with", "(", "DateAdjusters", ".", "lastDayOfMonth", "(", ")", ")", ";", "}", "else", "{", "date", "=", "second", ".", "minusMonths", "(", "months", ")", ";", "}", "if", "(", "date", ".", "equals", "(", "first", ")", ")", "{", "return", "StubType", ".", "NONE", ";", "}", "if", "(", "date", ".", "isBefore", "(", "first", ")", ")", "{", "return", "StubType", ".", "SHORT_START", ";", "}", "return", "StubType", ".", "LONG_START", ";", "}", "/**\n * Calculates the end stub type from a schedule and number of payments per year.\n * <p>\n * The {@code DateProvider[]} argument allows callers to pass in arrays of any class\n * that implements {@code DateProvider}, such as {@code LocalDate[]}.\n * \n * @param schedule the schedule, at least size 2, not null\n * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve\n * @return the stub type, not null\n */", "public", "static", "StubType", "getEndStubType", "(", "final", "DateProvider", "[", "]", "schedule", ",", "final", "int", "paymentsPerYear", ")", "{", "return", "getEndStubType", "(", "schedule", ",", "paymentsPerYear", ",", "false", ")", ";", "}", "/**\n * Calculates the end stub type from a schedule, number of payments per year and the end of month flag.\n * <p>\n * The {@code DateProvider[]} argument allows callers to pass in arrays of any class\n * that implements {@code DateProvider}, such as {@code LocalDate[]}.\n * \n * @param schedule the schedule, at least size 2, not null\n * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve\n * @param isEndOfMonthConvention whether to use end of month rules\n * @return the stub type, not null\n */", "public", "static", "StubType", "getEndStubType", "(", "final", "DateProvider", "[", "]", "schedule", ",", "final", "double", "paymentsPerYear", ",", "final", "boolean", "isEndOfMonthConvention", ")", "{", "Validate", ".", "notNull", "(", "schedule", ",", "\"", "schedule", "\"", ")", ";", "Validate", ".", "noNullElements", "(", "schedule", ",", "\"", "schedule", "\"", ")", ";", "Validate", ".", "isTrue", "(", "paymentsPerYear", ">", "0", ")", ";", "Validate", ".", "isTrue", "(", "12", "%", "paymentsPerYear", "==", "0", ")", ";", "final", "int", "months", "=", "(", "int", ")", "(", "12", "/", "paymentsPerYear", ")", ";", "final", "int", "n", "=", "schedule", ".", "length", ";", "final", "LocalDate", "first", "=", "LocalDate", ".", "of", "(", "schedule", "[", "n", "-", "2", "]", ")", ";", "final", "LocalDate", "second", "=", "LocalDate", ".", "of", "(", "schedule", "[", "n", "-", "1", "]", ")", ";", "LocalDate", "date", ";", "if", "(", "isEndOfMonthConvention", "&&", "first", ".", "matches", "(", "CalendricalMatchers", ".", "lastDayOfMonth", "(", ")", ")", ")", "{", "date", "=", "first", ".", "plusMonths", "(", "months", ")", ";", "date", "=", "date", ".", "with", "(", "DateAdjusters", ".", "lastDayOfMonth", "(", ")", ")", ";", "}", "else", "{", "date", "=", "first", ".", "plusMonths", "(", "months", ")", ";", "}", "if", "(", "date", ".", "equals", "(", "second", ")", ")", "{", "return", "StubType", ".", "NONE", ";", "}", "if", "(", "date", ".", "isAfter", "(", "second", ")", ")", "{", "return", "StubType", ".", "SHORT_END", ";", "}", "return", "StubType", ".", "LONG_END", ";", "}", "}" ]
Utility to calculate the stub type.
[ "Utility", "to", "calculate", "the", "stub", "type", "." ]
[ "//-------------------------------------------------------------------------", "//-------------------------------------------------------------------------" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b37d131804322438dbec5f9ab06c0d3f65547e7
tbass134/zype-android
app/src/main/java/com/zype/android/webapi/model/settings/ContentSettingsResponse.java
[ "MIT" ]
Java
ContentSettingsResponse
/** * Created by Evgeny Cherkasov on 21.11.2016. */
Created by Evgeny Cherkasov on 21.11.2016.
[ "Created", "by", "Evgeny", "Cherkasov", "on", "21", ".", "11", ".", "2016", "." ]
public class ContentSettingsResponse extends DataModel<ContentSettings> { public ContentSettingsResponse(ContentSettings contentSettings) { super(contentSettings); } }
[ "public", "class", "ContentSettingsResponse", "extends", "DataModel", "<", "ContentSettings", ">", "{", "public", "ContentSettingsResponse", "(", "ContentSettings", "contentSettings", ")", "{", "super", "(", "contentSettings", ")", ";", "}", "}" ]
Created by Evgeny Cherkasov on 21.11.2016.
[ "Created", "by", "Evgeny", "Cherkasov", "on", "21", ".", "11", ".", "2016", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b389ee72d6559d080675659f16444df0abfae6b
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/serialization/SimpleTupleDeserializer.java
[ "Apache-2.0" ]
Java
SimpleTupleDeserializer
/** * This Deserializer holds all the baseline code for deserializing Tuples. It is used by the more complex * {@link TupleDeserializer}. It is also used by a stateful Tuple field serializer {@link TupleFieldSerialization} and * finally it is also used by the stateful {@link TupleFile}. */
This Deserializer holds all the baseline code for deserializing Tuples. It is used by the more complex TupleDeserializer. It is also used by a stateful Tuple field serializer TupleFieldSerialization and finally it is also used by the stateful TupleFile.
[ "This", "Deserializer", "holds", "all", "the", "baseline", "code", "for", "deserializing", "Tuples", ".", "It", "is", "used", "by", "the", "more", "complex", "TupleDeserializer", ".", "It", "is", "also", "used", "by", "a", "stateful", "Tuple", "field", "serializer", "TupleFieldSerialization", "and", "finally", "it", "is", "also", "used", "by", "the", "stateful", "TupleFile", "." ]
@SuppressWarnings({ "rawtypes", "unchecked" }) public class SimpleTupleDeserializer implements Deserializer<ITuple> { private DataInputStream input; private final HadoopSerialization ser; private final Buffer tmpInputBuffer = new Buffer(); private final BitField nullsRelative = new BitField(); private final FlagsField nullsAbsolute = new FlagsField(); private final Configuration conf; private Deserializer[] deserializers; private Schema readSchema = null, targetSchema = null; private int[] backwardsCompatibiltyLookupVector = null; // Fields that are present in the target schema but not in the read schema private List<Field> newFields = new ArrayList<Field>(); // Constant that indicates a field of a Tuple is not being used private final static int UNUSED = -1; /** * Package-visibility constructor used by {@link TupleDeserializer} . For efficiency, a Schema is not pre-configured. * Read schemas are then passed dynamically in {@link #readFields(ITuple, Schema, Deserializer[])}. Note that this is * not the most intuitive way of using this class, but it is made for efficiency. */ SimpleTupleDeserializer(HadoopSerialization ser, Configuration conf) { this.ser = ser; this.conf = conf; } /** * Constructor with one Schema. This Schema will be used to read Tuples. */ public SimpleTupleDeserializer(Schema schemaToDeserialize, HadoopSerialization ser, Configuration conf) { this(schemaToDeserialize, schemaToDeserialize, ser, conf); } /** * Constructor with two schemas. In this case we deserialize one Schema but we write the final result into another one * (which should be backwards compatible). */ public SimpleTupleDeserializer(Schema readSchema, Schema targetSchema, HadoopSerialization ser, Configuration conf) { this(ser, conf); this.readSchema = readSchema; this.targetSchema = targetSchema; // calculate a lookup table for backwards compatibility // "UNUSED" will mean the field is not used anymore backwardsCompatibiltyLookupVector = new int[readSchema.getFields().size()]; for(int i = 0; i < readSchema.getFields().size(); i++) { backwardsCompatibiltyLookupVector[i] = UNUSED; Field field = readSchema.getFields().get(i); if(targetSchema.containsField(field.getName())) { backwardsCompatibiltyLookupVector[i] = targetSchema.getFieldPos(field.getName()); } } for(int i = 0; i < targetSchema.getFields().size(); i++) { Field field = targetSchema.getFields().get(i); if(!readSchema.containsField(field.getName())) { newFields.add(field); } } deserializers = SerializationInfo.getDeserializers(readSchema, targetSchema, conf); } @Override public void close() throws IOException { input.close(); } @Override public ITuple deserialize(ITuple tuple) throws IOException { if(tuple == null) { tuple = new Tuple(targetSchema); } readFields(tuple, deserializers); return tuple; } @Override public void open(InputStream input) throws IOException { if(input instanceof DataInputStream) { this.input = (DataInputStream) input; } else { this.input = new DataInputStream(input); } } /** * Read fields using the specified "readSchema" in the constructor. */ public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException { readFields(tuple, readSchema, customDeserializers); } /** * If the deserializer has been configured to use two schemas (read and target) then there is a lookup vector, otherwise * same schema is assumed. */ private int backwardsCompatibleIndex(int i) { return backwardsCompatibiltyLookupVector == null ? i : backwardsCompatibiltyLookupVector[i]; } // Private tuple that will be used to skip certain fields for backwards-compatibility private ITuple cachedReadTuple = null; /** * Private tuple that will be used to skip certain fields for backwards-compatibility. Because we save cached Objects * in the Tuple for deserializing custom Objects it is convenient to have such a Tuple event if no-one uses it * afterwards. */ private ITuple cachedReadTuple() { if(cachedReadTuple == null) { cachedReadTuple = new Tuple(readSchema); } return cachedReadTuple; } /** * Read fields using an ad-hoc Schema passed by parameter. This method is package-visibility since this is not the * standard way of using this Deserializer. This method is used by {@link TupleDeserializer}. */ void readFields(ITuple tuple, Schema schema, Deserializer[] customDeserializers) throws IOException { // Set default values / clean values if there are "new fields" for(Field field: newFields) { tuple.set(field.getName(), field.getDefaultValue()); } // If there are fields with nulls, read the bit field and set the values that are null if(schema.containsNullableFields()) { List<Integer> nullableFields = schema.getNullableFieldsIdx(); nullsAbsolute.ensureSize(schema.getFields().size()); nullsAbsolute.clear(nullableFields); nullsRelative.deser(input); for(int i = 0; i < nullableFields.size(); i++) { if(nullsRelative.isSet(i)) { int field = backwardsCompatibleIndex(nullableFields.get(i)); if(field != UNUSED) { tuple.set(field, null); } nullsAbsolute.flags[nullableFields.get(i)] = true; } } } // Field by field deserialization for(int index = 0; index < schema.getFields().size(); index++) { Deserializer customDeser = customDeserializers[index]; Field field = schema.getField(index); // Nulls control if(field.isNullable() && nullsAbsolute.flags[index]) { // Null field. Nothing to deserialize. continue; } /* * If we configured the Deserializer to use two Schemas, * this will give us the real index for the destination Tuple. * If it gives "UNUSED" it means the field being read is not used. * We will deal with this depending on wether we read a primitive field or * a complex data type. */ int idx = backwardsCompatibleIndex(index); switch(field.getType()) { case INT: int iVal = WritableUtils.readVInt(input); if(idx != UNUSED) { tuple.set(idx, iVal); } // If the primitive field is not used we just don't set it break; case LONG: long lVal = WritableUtils.readVLong(input); if(idx != UNUSED) { tuple.set(idx, lVal); } // If the primitive field is not used we just don't set it break; case DOUBLE: double dVal = input.readDouble(); if(idx != UNUSED) { tuple.set(idx, dVal); } // If the primitive field is not used we just don't set it break; case FLOAT: float fVal = input.readFloat(); if(idx != UNUSED) { tuple.set(idx, fVal); } // If the primitive field is not used we just don't set it break; case STRING: if(idx == UNUSED) { // The field is unused so we use a private cached Tuple for skipping its bytes readUtf8(input, cachedReadTuple(), index); } else { readUtf8(input, tuple, idx); } break; case BOOLEAN: byte b = input.readByte(); if(idx != UNUSED) { tuple.set(idx, (b != 0)); } // If the primitive field is not used we just don't set it break; case ENUM: if(idx == UNUSED) { // The field is unused so we use a private cached Tuple for skipping its bytes readEnum(input, cachedReadTuple(), field.getObjectClass(), index); } else { readEnum(input, tuple, field.getObjectClass(), idx); } break; case BYTES: if(idx == UNUSED) { // The field is unused so we use a private cached Tuple for skipping its bytes readBytes(input, cachedReadTuple(), index); } else { readBytes(input, tuple, idx); } break; case OBJECT: if(idx == UNUSED) { // The field is unused so we use a private cached Tuple for skipping its bytes readCustomObject(input, cachedReadTuple(), field.getObjectClass(), index, customDeser); } else { readCustomObject(input, tuple, field.getObjectClass(), idx, customDeser); } break; default: throw new IOException("Not supported type:" + field.getType()); } } } protected void readUtf8(DataInputStream input, ITuple tuple, int index) throws IOException { Object t = tuple.get(index); if(t == null || !(t instanceof Utf8)) { t = new Utf8(); tuple.set(index, t); } ((Utf8) t).readFields(input); } protected void readCustomObject(DataInputStream input, ITuple tuple, Class<?> expectedType, int index, Deserializer customDeser) throws IOException { int size = WritableUtils.readVInt(input); if(size >= 0) { Object object = tuple.get(index); if(customDeser != null) { customDeser.open(input); object = customDeser.deserialize(object); customDeser.close(); tuple.set(index, object); } else { if(object == null) { tuple.set(index, ReflectionUtils.newInstance(expectedType, conf)); } tmpInputBuffer.setSize(size); input.readFully(tmpInputBuffer.getBytes(), 0, size); Object ob = ser.deser(tuple.get(index), tmpInputBuffer.getBytes(), 0, size); tuple.set(index, ob); } } else { throw new IOException("Error deserializing, custom object serialized with negative length : " + size); } } public void readBytes(DataInputStream input, ITuple tuple, int index) throws IOException { int length = WritableUtils.readVInt(input); ByteBuffer old = (ByteBuffer) tuple.get(index); ByteBuffer result; if(old != null && length <= old.capacity()) { result = old; result.clear(); } else { result = ByteBuffer.allocate(length); tuple.set(index, result); } input.readFully(result.array(), result.position(), length); result.limit(length); } public DataInputStream getInput() { return input; } protected void readEnum(DataInputStream input, ITuple tuple, Class<?> fieldType, int index) throws IOException { int ordinal = WritableUtils.readVInt(input); try { Object[] enums = fieldType.getEnumConstants(); tuple.set(index, enums[ordinal]); } catch(ArrayIndexOutOfBoundsException e) { throw new IOException("Ordinal index out of bounds for " + fieldType + " ordinal=" + ordinal); } } /** * Helping class that keeps an array of flags. Used to know if a particular field is null or not. */ private static class FlagsField { public boolean[] flags = new boolean[0]; public void ensureSize(int size) { if(flags.length < size) { flags = Arrays.copyOf(flags, size); } } public void clear(List<Integer> flags) { for(Integer flag : flags) { this.flags[flag] = false; } } } }
[ "@", "SuppressWarnings", "(", "{", "\"", "rawtypes", "\"", ",", "\"", "unchecked", "\"", "}", ")", "public", "class", "SimpleTupleDeserializer", "implements", "Deserializer", "<", "ITuple", ">", "{", "private", "DataInputStream", "input", ";", "private", "final", "HadoopSerialization", "ser", ";", "private", "final", "Buffer", "tmpInputBuffer", "=", "new", "Buffer", "(", ")", ";", "private", "final", "BitField", "nullsRelative", "=", "new", "BitField", "(", ")", ";", "private", "final", "FlagsField", "nullsAbsolute", "=", "new", "FlagsField", "(", ")", ";", "private", "final", "Configuration", "conf", ";", "private", "Deserializer", "[", "]", "deserializers", ";", "private", "Schema", "readSchema", "=", "null", ",", "targetSchema", "=", "null", ";", "private", "int", "[", "]", "backwardsCompatibiltyLookupVector", "=", "null", ";", "private", "List", "<", "Field", ">", "newFields", "=", "new", "ArrayList", "<", "Field", ">", "(", ")", ";", "private", "final", "static", "int", "UNUSED", "=", "-", "1", ";", "/**\n\t * Package-visibility constructor used by {@link TupleDeserializer} . For efficiency, a Schema is not pre-configured.\n\t * Read schemas are then passed dynamically in {@link #readFields(ITuple, Schema, Deserializer[])}. Note that this is\n\t * not the most intuitive way of using this class, but it is made for efficiency.\n\t */", "SimpleTupleDeserializer", "(", "HadoopSerialization", "ser", ",", "Configuration", "conf", ")", "{", "this", ".", "ser", "=", "ser", ";", "this", ".", "conf", "=", "conf", ";", "}", "/**\n\t * Constructor with one Schema. This Schema will be used to read Tuples.\n\t */", "public", "SimpleTupleDeserializer", "(", "Schema", "schemaToDeserialize", ",", "HadoopSerialization", "ser", ",", "Configuration", "conf", ")", "{", "this", "(", "schemaToDeserialize", ",", "schemaToDeserialize", ",", "ser", ",", "conf", ")", ";", "}", "/**\n\t * Constructor with two schemas. In this case we deserialize one Schema but we write the final result into another one\n\t * (which should be backwards compatible).\n\t */", "public", "SimpleTupleDeserializer", "(", "Schema", "readSchema", ",", "Schema", "targetSchema", ",", "HadoopSerialization", "ser", ",", "Configuration", "conf", ")", "{", "this", "(", "ser", ",", "conf", ")", ";", "this", ".", "readSchema", "=", "readSchema", ";", "this", ".", "targetSchema", "=", "targetSchema", ";", "backwardsCompatibiltyLookupVector", "=", "new", "int", "[", "readSchema", ".", "getFields", "(", ")", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "readSchema", ".", "getFields", "(", ")", ".", "size", "(", ")", ";", "i", "++", ")", "{", "backwardsCompatibiltyLookupVector", "[", "i", "]", "=", "UNUSED", ";", "Field", "field", "=", "readSchema", ".", "getFields", "(", ")", ".", "get", "(", "i", ")", ";", "if", "(", "targetSchema", ".", "containsField", "(", "field", ".", "getName", "(", ")", ")", ")", "{", "backwardsCompatibiltyLookupVector", "[", "i", "]", "=", "targetSchema", ".", "getFieldPos", "(", "field", ".", "getName", "(", ")", ")", ";", "}", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "targetSchema", ".", "getFields", "(", ")", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Field", "field", "=", "targetSchema", ".", "getFields", "(", ")", ".", "get", "(", "i", ")", ";", "if", "(", "!", "readSchema", ".", "containsField", "(", "field", ".", "getName", "(", ")", ")", ")", "{", "newFields", ".", "add", "(", "field", ")", ";", "}", "}", "deserializers", "=", "SerializationInfo", ".", "getDeserializers", "(", "readSchema", ",", "targetSchema", ",", "conf", ")", ";", "}", "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "input", ".", "close", "(", ")", ";", "}", "@", "Override", "public", "ITuple", "deserialize", "(", "ITuple", "tuple", ")", "throws", "IOException", "{", "if", "(", "tuple", "==", "null", ")", "{", "tuple", "=", "new", "Tuple", "(", "targetSchema", ")", ";", "}", "readFields", "(", "tuple", ",", "deserializers", ")", ";", "return", "tuple", ";", "}", "@", "Override", "public", "void", "open", "(", "InputStream", "input", ")", "throws", "IOException", "{", "if", "(", "input", "instanceof", "DataInputStream", ")", "{", "this", ".", "input", "=", "(", "DataInputStream", ")", "input", ";", "}", "else", "{", "this", ".", "input", "=", "new", "DataInputStream", "(", "input", ")", ";", "}", "}", "/**\n\t * Read fields using the specified \"readSchema\" in the constructor.\n\t */", "public", "void", "readFields", "(", "ITuple", "tuple", ",", "Deserializer", "[", "]", "customDeserializers", ")", "throws", "IOException", "{", "readFields", "(", "tuple", ",", "readSchema", ",", "customDeserializers", ")", ";", "}", "/**\n\t * If the deserializer has been configured to use two schemas (read and target) then there is a lookup vector, otherwise\n\t * same schema is assumed.\n\t */", "private", "int", "backwardsCompatibleIndex", "(", "int", "i", ")", "{", "return", "backwardsCompatibiltyLookupVector", "==", "null", "?", "i", ":", "backwardsCompatibiltyLookupVector", "[", "i", "]", ";", "}", "private", "ITuple", "cachedReadTuple", "=", "null", ";", "/**\n\t * Private tuple that will be used to skip certain fields for backwards-compatibility. Because we save cached Objects\n\t * in the Tuple for deserializing custom Objects it is convenient to have such a Tuple event if no-one uses it\n\t * afterwards.\n\t */", "private", "ITuple", "cachedReadTuple", "(", ")", "{", "if", "(", "cachedReadTuple", "==", "null", ")", "{", "cachedReadTuple", "=", "new", "Tuple", "(", "readSchema", ")", ";", "}", "return", "cachedReadTuple", ";", "}", "/**\n\t * Read fields using an ad-hoc Schema passed by parameter. This method is package-visibility since this is not the\n\t * standard way of using this Deserializer. This method is used by {@link TupleDeserializer}.\n\t */", "void", "readFields", "(", "ITuple", "tuple", ",", "Schema", "schema", ",", "Deserializer", "[", "]", "customDeserializers", ")", "throws", "IOException", "{", "for", "(", "Field", "field", ":", "newFields", ")", "{", "tuple", ".", "set", "(", "field", ".", "getName", "(", ")", ",", "field", ".", "getDefaultValue", "(", ")", ")", ";", "}", "if", "(", "schema", ".", "containsNullableFields", "(", ")", ")", "{", "List", "<", "Integer", ">", "nullableFields", "=", "schema", ".", "getNullableFieldsIdx", "(", ")", ";", "nullsAbsolute", ".", "ensureSize", "(", "schema", ".", "getFields", "(", ")", ".", "size", "(", ")", ")", ";", "nullsAbsolute", ".", "clear", "(", "nullableFields", ")", ";", "nullsRelative", ".", "deser", "(", "input", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nullableFields", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "nullsRelative", ".", "isSet", "(", "i", ")", ")", "{", "int", "field", "=", "backwardsCompatibleIndex", "(", "nullableFields", ".", "get", "(", "i", ")", ")", ";", "if", "(", "field", "!=", "UNUSED", ")", "{", "tuple", ".", "set", "(", "field", ",", "null", ")", ";", "}", "nullsAbsolute", ".", "flags", "[", "nullableFields", ".", "get", "(", "i", ")", "]", "=", "true", ";", "}", "}", "}", "for", "(", "int", "index", "=", "0", ";", "index", "<", "schema", ".", "getFields", "(", ")", ".", "size", "(", ")", ";", "index", "++", ")", "{", "Deserializer", "customDeser", "=", "customDeserializers", "[", "index", "]", ";", "Field", "field", "=", "schema", ".", "getField", "(", "index", ")", ";", "if", "(", "field", ".", "isNullable", "(", ")", "&&", "nullsAbsolute", ".", "flags", "[", "index", "]", ")", "{", "continue", ";", "}", "/*\n\t\t\t * If we configured the Deserializer to use two Schemas,\n\t\t\t * this will give us the real index for the destination Tuple.\n\t\t\t * If it gives \"UNUSED\" it means the field being read is not used.\n\t\t\t * We will deal with this depending on wether we read a primitive field or \n\t\t\t * a complex data type.\n\t\t\t */", "int", "idx", "=", "backwardsCompatibleIndex", "(", "index", ")", ";", "switch", "(", "field", ".", "getType", "(", ")", ")", "{", "case", "INT", ":", "int", "iVal", "=", "WritableUtils", ".", "readVInt", "(", "input", ")", ";", "if", "(", "idx", "!=", "UNUSED", ")", "{", "tuple", ".", "set", "(", "idx", ",", "iVal", ")", ";", "}", "break", ";", "case", "LONG", ":", "long", "lVal", "=", "WritableUtils", ".", "readVLong", "(", "input", ")", ";", "if", "(", "idx", "!=", "UNUSED", ")", "{", "tuple", ".", "set", "(", "idx", ",", "lVal", ")", ";", "}", "break", ";", "case", "DOUBLE", ":", "double", "dVal", "=", "input", ".", "readDouble", "(", ")", ";", "if", "(", "idx", "!=", "UNUSED", ")", "{", "tuple", ".", "set", "(", "idx", ",", "dVal", ")", ";", "}", "break", ";", "case", "FLOAT", ":", "float", "fVal", "=", "input", ".", "readFloat", "(", ")", ";", "if", "(", "idx", "!=", "UNUSED", ")", "{", "tuple", ".", "set", "(", "idx", ",", "fVal", ")", ";", "}", "break", ";", "case", "STRING", ":", "if", "(", "idx", "==", "UNUSED", ")", "{", "readUtf8", "(", "input", ",", "cachedReadTuple", "(", ")", ",", "index", ")", ";", "}", "else", "{", "readUtf8", "(", "input", ",", "tuple", ",", "idx", ")", ";", "}", "break", ";", "case", "BOOLEAN", ":", "byte", "b", "=", "input", ".", "readByte", "(", ")", ";", "if", "(", "idx", "!=", "UNUSED", ")", "{", "tuple", ".", "set", "(", "idx", ",", "(", "b", "!=", "0", ")", ")", ";", "}", "break", ";", "case", "ENUM", ":", "if", "(", "idx", "==", "UNUSED", ")", "{", "readEnum", "(", "input", ",", "cachedReadTuple", "(", ")", ",", "field", ".", "getObjectClass", "(", ")", ",", "index", ")", ";", "}", "else", "{", "readEnum", "(", "input", ",", "tuple", ",", "field", ".", "getObjectClass", "(", ")", ",", "idx", ")", ";", "}", "break", ";", "case", "BYTES", ":", "if", "(", "idx", "==", "UNUSED", ")", "{", "readBytes", "(", "input", ",", "cachedReadTuple", "(", ")", ",", "index", ")", ";", "}", "else", "{", "readBytes", "(", "input", ",", "tuple", ",", "idx", ")", ";", "}", "break", ";", "case", "OBJECT", ":", "if", "(", "idx", "==", "UNUSED", ")", "{", "readCustomObject", "(", "input", ",", "cachedReadTuple", "(", ")", ",", "field", ".", "getObjectClass", "(", ")", ",", "index", ",", "customDeser", ")", ";", "}", "else", "{", "readCustomObject", "(", "input", ",", "tuple", ",", "field", ".", "getObjectClass", "(", ")", ",", "idx", ",", "customDeser", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "IOException", "(", "\"", "Not supported type:", "\"", "+", "field", ".", "getType", "(", ")", ")", ";", "}", "}", "}", "protected", "void", "readUtf8", "(", "DataInputStream", "input", ",", "ITuple", "tuple", ",", "int", "index", ")", "throws", "IOException", "{", "Object", "t", "=", "tuple", ".", "get", "(", "index", ")", ";", "if", "(", "t", "==", "null", "||", "!", "(", "t", "instanceof", "Utf8", ")", ")", "{", "t", "=", "new", "Utf8", "(", ")", ";", "tuple", ".", "set", "(", "index", ",", "t", ")", ";", "}", "(", "(", "Utf8", ")", "t", ")", ".", "readFields", "(", "input", ")", ";", "}", "protected", "void", "readCustomObject", "(", "DataInputStream", "input", ",", "ITuple", "tuple", ",", "Class", "<", "?", ">", "expectedType", ",", "int", "index", ",", "Deserializer", "customDeser", ")", "throws", "IOException", "{", "int", "size", "=", "WritableUtils", ".", "readVInt", "(", "input", ")", ";", "if", "(", "size", ">=", "0", ")", "{", "Object", "object", "=", "tuple", ".", "get", "(", "index", ")", ";", "if", "(", "customDeser", "!=", "null", ")", "{", "customDeser", ".", "open", "(", "input", ")", ";", "object", "=", "customDeser", ".", "deserialize", "(", "object", ")", ";", "customDeser", ".", "close", "(", ")", ";", "tuple", ".", "set", "(", "index", ",", "object", ")", ";", "}", "else", "{", "if", "(", "object", "==", "null", ")", "{", "tuple", ".", "set", "(", "index", ",", "ReflectionUtils", ".", "newInstance", "(", "expectedType", ",", "conf", ")", ")", ";", "}", "tmpInputBuffer", ".", "setSize", "(", "size", ")", ";", "input", ".", "readFully", "(", "tmpInputBuffer", ".", "getBytes", "(", ")", ",", "0", ",", "size", ")", ";", "Object", "ob", "=", "ser", ".", "deser", "(", "tuple", ".", "get", "(", "index", ")", ",", "tmpInputBuffer", ".", "getBytes", "(", ")", ",", "0", ",", "size", ")", ";", "tuple", ".", "set", "(", "index", ",", "ob", ")", ";", "}", "}", "else", "{", "throw", "new", "IOException", "(", "\"", "Error deserializing, custom object serialized with negative length : ", "\"", "+", "size", ")", ";", "}", "}", "public", "void", "readBytes", "(", "DataInputStream", "input", ",", "ITuple", "tuple", ",", "int", "index", ")", "throws", "IOException", "{", "int", "length", "=", "WritableUtils", ".", "readVInt", "(", "input", ")", ";", "ByteBuffer", "old", "=", "(", "ByteBuffer", ")", "tuple", ".", "get", "(", "index", ")", ";", "ByteBuffer", "result", ";", "if", "(", "old", "!=", "null", "&&", "length", "<=", "old", ".", "capacity", "(", ")", ")", "{", "result", "=", "old", ";", "result", ".", "clear", "(", ")", ";", "}", "else", "{", "result", "=", "ByteBuffer", ".", "allocate", "(", "length", ")", ";", "tuple", ".", "set", "(", "index", ",", "result", ")", ";", "}", "input", ".", "readFully", "(", "result", ".", "array", "(", ")", ",", "result", ".", "position", "(", ")", ",", "length", ")", ";", "result", ".", "limit", "(", "length", ")", ";", "}", "public", "DataInputStream", "getInput", "(", ")", "{", "return", "input", ";", "}", "protected", "void", "readEnum", "(", "DataInputStream", "input", ",", "ITuple", "tuple", ",", "Class", "<", "?", ">", "fieldType", ",", "int", "index", ")", "throws", "IOException", "{", "int", "ordinal", "=", "WritableUtils", ".", "readVInt", "(", "input", ")", ";", "try", "{", "Object", "[", "]", "enums", "=", "fieldType", ".", "getEnumConstants", "(", ")", ";", "tuple", ".", "set", "(", "index", ",", "enums", "[", "ordinal", "]", ")", ";", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "e", ")", "{", "throw", "new", "IOException", "(", "\"", "Ordinal index out of bounds for ", "\"", "+", "fieldType", "+", "\"", " ordinal=", "\"", "+", "ordinal", ")", ";", "}", "}", "/**\n\t * Helping class that keeps an array of flags. Used to know if a particular field is null or not.\n\t */", "private", "static", "class", "FlagsField", "{", "public", "boolean", "[", "]", "flags", "=", "new", "boolean", "[", "0", "]", ";", "public", "void", "ensureSize", "(", "int", "size", ")", "{", "if", "(", "flags", ".", "length", "<", "size", ")", "{", "flags", "=", "Arrays", ".", "copyOf", "(", "flags", ",", "size", ")", ";", "}", "}", "public", "void", "clear", "(", "List", "<", "Integer", ">", "flags", ")", "{", "for", "(", "Integer", "flag", ":", "flags", ")", "{", "this", ".", "flags", "[", "flag", "]", "=", "false", ";", "}", "}", "}", "}" ]
This Deserializer holds all the baseline code for deserializing Tuples.
[ "This", "Deserializer", "holds", "all", "the", "baseline", "code", "for", "deserializing", "Tuples", "." ]
[ "// Fields that are present in the target schema but not in the read schema", "// Constant that indicates a field of a Tuple is not being used", "// calculate a lookup table for backwards compatibility", "// \"UNUSED\" will mean the field is not used anymore", "// Private tuple that will be used to skip certain fields for backwards-compatibility", "// Set default values / clean values if there are \"new fields\"", "// If there are fields with nulls, read the bit field and set the values that are null", "// Field by field deserialization", "// Nulls control", "// Null field. Nothing to deserialize.", "// If the primitive field is not used we just don't set it", "// If the primitive field is not used we just don't set it", "// If the primitive field is not used we just don't set it", "// If the primitive field is not used we just don't set it", "// The field is unused so we use a private cached Tuple for skipping its bytes", "// If the primitive field is not used we just don't set it", "// The field is unused so we use a private cached Tuple for skipping its bytes", "// The field is unused so we use a private cached Tuple for skipping its bytes", "// The field is unused so we use a private cached Tuple for skipping its bytes" ]
[ { "param": "Deserializer<ITuple>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Deserializer<ITuple>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b389ee72d6559d080675659f16444df0abfae6b
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/serialization/SimpleTupleDeserializer.java
[ "Apache-2.0" ]
Java
FlagsField
/** * Helping class that keeps an array of flags. Used to know if a particular field is null or not. */
Helping class that keeps an array of flags. Used to know if a particular field is null or not.
[ "Helping", "class", "that", "keeps", "an", "array", "of", "flags", ".", "Used", "to", "know", "if", "a", "particular", "field", "is", "null", "or", "not", "." ]
private static class FlagsField { public boolean[] flags = new boolean[0]; public void ensureSize(int size) { if(flags.length < size) { flags = Arrays.copyOf(flags, size); } } public void clear(List<Integer> flags) { for(Integer flag : flags) { this.flags[flag] = false; } } }
[ "private", "static", "class", "FlagsField", "{", "public", "boolean", "[", "]", "flags", "=", "new", "boolean", "[", "0", "]", ";", "public", "void", "ensureSize", "(", "int", "size", ")", "{", "if", "(", "flags", ".", "length", "<", "size", ")", "{", "flags", "=", "Arrays", ".", "copyOf", "(", "flags", ",", "size", ")", ";", "}", "}", "public", "void", "clear", "(", "List", "<", "Integer", ">", "flags", ")", "{", "for", "(", "Integer", "flag", ":", "flags", ")", "{", "this", ".", "flags", "[", "flag", "]", "=", "false", ";", "}", "}", "}" ]
Helping class that keeps an array of flags.
[ "Helping", "class", "that", "keeps", "an", "array", "of", "flags", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b39ca1bcce87622c16f2337aef0d85b5f713fe2
johan-gorter/Instantlogic
instantlogic-fabric/src/main/java/org/instantlogic/fabric/util/AbstractDeductionContext.java
[ "MIT" ]
Java
AbstractDeductionContext
/** * Used to calculate deductions by keeping a list of selected instances. */
Used to calculate deductions by keeping a list of selected instances.
[ "Used", "to", "calculate", "deductions", "by", "keeping", "a", "list", "of", "selected", "instances", "." ]
public abstract class AbstractDeductionContext extends DeductionContext { protected final List<Instance> selectedInstances = new ArrayList<Instance>(); protected final List<String> parameterNames = new ArrayList<String>(); private final DeductionContext parent; public AbstractDeductionContext(DeductionContext parent) { this.parent = parent; } public Instance[] getSelectedInstances(Entity<?>[] entities) { Instance[] result = new Instance[entities.length]; for (int i=0;i<entities.length;i++) { result[i] = getSelectedInstance(entities[i]); } return result; } @SuppressWarnings("unchecked") @Override public <I extends Instance> I getSelectedInstance(Entity<I> entity) { for (int i=selectedInstances.size()-1;i>=0;i--) { Instance candidate = selectedInstances.get(i); if (entity == null || Entity.extendsFrom(candidate.getMetadata().getEntity(), entity)) { return (I)candidate; } } if (parent!=null) { return parent.getSelectedInstance(entity); } return null; } @SuppressWarnings("unchecked") @Override public <I extends Instance> I getSelectedInstance(Entity<I> entity, String parameterName) { for (int i=parameterNames.size()-1;i>=0;i--) { if (parameterNames.get(i).equals(parameterName)) { Instance candidate = selectedInstances.get(i); if (entity == null || Entity.extendsFrom(candidate.getMetadata().getEntity(), entity)) { return (I)candidate; } else { throw new RuntimeException("Parameter ["+parameterName+"] value was not of type ["+entity+"]"); } } } if (parent!=null) { return parent.getSelectedInstance(entity, parameterName); } return null; } public void pushSelectedInstance(Instance instance) { selectedInstances.add(instance); } public void pushSelectedInstance(Instance instance, String parameterName) { if (parameterNames.size()!=selectedInstances.size()) { throw new RuntimeException("Do not mix anonymous parameters with named ones"); } selectedInstances.add(instance); parameterNames.add(parameterName); } public Instance popSelectedInstance() { if (this.selectedInstances.size()==0) { throw new RuntimeException("Asymmetric push/pop"); } if (parameterNames.size()==selectedInstances.size()) { parameterNames.remove(parameterNames.size()-1); } return selectedInstances.remove(selectedInstances.size()-1); } public void popSelectedInstance(Instance instance) { Instance check = popSelectedInstance(); if (check!=instance) { throw new RuntimeException("Asymmetric push/pop"); } } public void addSelectedInstances(List<Instance> result) { ListIterator<Instance> iterator = selectedInstances.listIterator(selectedInstances.size()); while (iterator.hasPrevious()) { result.add(iterator.previous()); } if (parent!=null) { parent.addSelectedInstances(result); } } @Override public String printDiagnostics() { StringBuffer sb = new StringBuffer(getClass().getName()); sb.append("("); for (Instance i : selectedInstances) { sb.append(i.toString()); sb.append(","); } if (parent==null) { sb.setLength(sb.length()-1); } else { sb.append("parent: "); sb.append(parent.printDiagnostics()); } sb.append(")"); return sb.toString(); } }
[ "public", "abstract", "class", "AbstractDeductionContext", "extends", "DeductionContext", "{", "protected", "final", "List", "<", "Instance", ">", "selectedInstances", "=", "new", "ArrayList", "<", "Instance", ">", "(", ")", ";", "protected", "final", "List", "<", "String", ">", "parameterNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "private", "final", "DeductionContext", "parent", ";", "public", "AbstractDeductionContext", "(", "DeductionContext", "parent", ")", "{", "this", ".", "parent", "=", "parent", ";", "}", "public", "Instance", "[", "]", "getSelectedInstances", "(", "Entity", "<", "?", ">", "[", "]", "entities", ")", "{", "Instance", "[", "]", "result", "=", "new", "Instance", "[", "entities", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "entities", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "getSelectedInstance", "(", "entities", "[", "i", "]", ")", ";", "}", "return", "result", ";", "}", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "@", "Override", "public", "<", "I", "extends", "Instance", ">", "I", "getSelectedInstance", "(", "Entity", "<", "I", ">", "entity", ")", "{", "for", "(", "int", "i", "=", "selectedInstances", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "Instance", "candidate", "=", "selectedInstances", ".", "get", "(", "i", ")", ";", "if", "(", "entity", "==", "null", "||", "Entity", ".", "extendsFrom", "(", "candidate", ".", "getMetadata", "(", ")", ".", "getEntity", "(", ")", ",", "entity", ")", ")", "{", "return", "(", "I", ")", "candidate", ";", "}", "}", "if", "(", "parent", "!=", "null", ")", "{", "return", "parent", ".", "getSelectedInstance", "(", "entity", ")", ";", "}", "return", "null", ";", "}", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "@", "Override", "public", "<", "I", "extends", "Instance", ">", "I", "getSelectedInstance", "(", "Entity", "<", "I", ">", "entity", ",", "String", "parameterName", ")", "{", "for", "(", "int", "i", "=", "parameterNames", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "parameterNames", ".", "get", "(", "i", ")", ".", "equals", "(", "parameterName", ")", ")", "{", "Instance", "candidate", "=", "selectedInstances", ".", "get", "(", "i", ")", ";", "if", "(", "entity", "==", "null", "||", "Entity", ".", "extendsFrom", "(", "candidate", ".", "getMetadata", "(", ")", ".", "getEntity", "(", ")", ",", "entity", ")", ")", "{", "return", "(", "I", ")", "candidate", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"", "Parameter [", "\"", "+", "parameterName", "+", "\"", "] value was not of type [", "\"", "+", "entity", "+", "\"", "]", "\"", ")", ";", "}", "}", "}", "if", "(", "parent", "!=", "null", ")", "{", "return", "parent", ".", "getSelectedInstance", "(", "entity", ",", "parameterName", ")", ";", "}", "return", "null", ";", "}", "public", "void", "pushSelectedInstance", "(", "Instance", "instance", ")", "{", "selectedInstances", ".", "add", "(", "instance", ")", ";", "}", "public", "void", "pushSelectedInstance", "(", "Instance", "instance", ",", "String", "parameterName", ")", "{", "if", "(", "parameterNames", ".", "size", "(", ")", "!=", "selectedInstances", ".", "size", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Do not mix anonymous parameters with named ones", "\"", ")", ";", "}", "selectedInstances", ".", "add", "(", "instance", ")", ";", "parameterNames", ".", "add", "(", "parameterName", ")", ";", "}", "public", "Instance", "popSelectedInstance", "(", ")", "{", "if", "(", "this", ".", "selectedInstances", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Asymmetric push/pop", "\"", ")", ";", "}", "if", "(", "parameterNames", ".", "size", "(", ")", "==", "selectedInstances", ".", "size", "(", ")", ")", "{", "parameterNames", ".", "remove", "(", "parameterNames", ".", "size", "(", ")", "-", "1", ")", ";", "}", "return", "selectedInstances", ".", "remove", "(", "selectedInstances", ".", "size", "(", ")", "-", "1", ")", ";", "}", "public", "void", "popSelectedInstance", "(", "Instance", "instance", ")", "{", "Instance", "check", "=", "popSelectedInstance", "(", ")", ";", "if", "(", "check", "!=", "instance", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Asymmetric push/pop", "\"", ")", ";", "}", "}", "public", "void", "addSelectedInstances", "(", "List", "<", "Instance", ">", "result", ")", "{", "ListIterator", "<", "Instance", ">", "iterator", "=", "selectedInstances", ".", "listIterator", "(", "selectedInstances", ".", "size", "(", ")", ")", ";", "while", "(", "iterator", ".", "hasPrevious", "(", ")", ")", "{", "result", ".", "add", "(", "iterator", ".", "previous", "(", ")", ")", ";", "}", "if", "(", "parent", "!=", "null", ")", "{", "parent", ".", "addSelectedInstances", "(", "result", ")", ";", "}", "}", "@", "Override", "public", "String", "printDiagnostics", "(", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", "(", "\"", ")", ";", "for", "(", "Instance", "i", ":", "selectedInstances", ")", "{", "sb", ".", "append", "(", "i", ".", "toString", "(", ")", ")", ";", "sb", ".", "append", "(", "\"", ",", "\"", ")", ";", "}", "if", "(", "parent", "==", "null", ")", "{", "sb", ".", "setLength", "(", "sb", ".", "length", "(", ")", "-", "1", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"", "parent: ", "\"", ")", ";", "sb", ".", "append", "(", "parent", ".", "printDiagnostics", "(", ")", ")", ";", "}", "sb", ".", "append", "(", "\"", ")", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "}" ]
Used to calculate deductions by keeping a list of selected instances.
[ "Used", "to", "calculate", "deductions", "by", "keeping", "a", "list", "of", "selected", "instances", "." ]
[]
[ { "param": "DeductionContext", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DeductionContext", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b3d16b59cbdd9bd5d907f2273a2782ecbf51d9e
RenukaGurumurthy/Gooru-Core-API
gooru-core/src/main/java/org/ednovo/goorucore/application/serializer/JsonProcessor.java
[ "MIT" ]
Java
JsonProcessor
/** * @author Search Team * */
@author Search Team
[ "@author", "Search", "Team" ]
public class JsonProcessor { private static ObjectMapper mapper; /** * The static attributes and writers needed for serialization are * instantiated. This block of code is called when the class gets loaded. */ static { mapper = new ObjectMapper(); mapper.configure(MapperFeature.USE_ANNOTATIONS, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public static ObjectMapper getMapper() { return mapper; } }
[ "public", "class", "JsonProcessor", "{", "private", "static", "ObjectMapper", "mapper", ";", "/**\n\t * The static attributes and writers needed for serialization are\n\t * instantiated. This block of code is called when the class gets loaded.\n\t */", "static", "{", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "mapper", ".", "configure", "(", "MapperFeature", ".", "USE_ANNOTATIONS", ",", "true", ")", ";", "mapper", ".", "configure", "(", "DeserializationFeature", ".", "FAIL_ON_UNKNOWN_PROPERTIES", ",", "false", ")", ";", "}", "public", "static", "ObjectMapper", "getMapper", "(", ")", "{", "return", "mapper", ";", "}", "}" ]
@author Search Team
[ "@author", "Search", "Team" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b44d1b446f0d41a24bba41b431f17a96ef9b672
Incapture/OG-Platform
projects/OG-Core/src/main/java/com/opengamma/core/position/impl/ParallelPortfolioNodeTraverser.java
[ "Apache-2.0" ]
Java
ParallelPortfolioNodeTraverser
/** * A traverser that runs in parallel using a number of threads. The ordering is non-deterministic. */
A traverser that runs in parallel using a number of threads. The ordering is non-deterministic.
[ "A", "traverser", "that", "runs", "in", "parallel", "using", "a", "number", "of", "threads", ".", "The", "ordering", "is", "non", "-", "deterministic", "." ]
public class ParallelPortfolioNodeTraverser extends PortfolioNodeTraverser { private static final Logger s_logger = LoggerFactory.getLogger(ParallelPortfolioNodeTraverser.class); private final ExecutorService _executorService; /** * Creates a traverser. * * @param callback the callback to invoke, not null * @param executorService the executor service for parallel resolutions */ public ParallelPortfolioNodeTraverser(final PortfolioNodeTraversalCallback callback, final ExecutorService executorService) { super(callback); ArgumentChecker.notNull(executorService, "executorService"); _executorService = executorService; } protected ExecutorService getExecutorService() { return _executorService; } private final class Context { private final AtomicInteger _count = new AtomicInteger(); private final Queue<Runnable> _work = new ConcurrentLinkedQueue<Runnable>(); private final class NodeTraverser implements Runnable { private final NodeTraverser _parent; private final PortfolioNode _node; private final AtomicInteger _count = new AtomicInteger(); private volatile boolean _secondPass; public NodeTraverser(final PortfolioNode node, final NodeTraverser parent) { _node = node; _parent = parent; } @Override public void run() { getCallback().preOrderOperation(_node); final List<PortfolioNode> childNodes = _node.getChildNodes(); final List<Position> positions = _node.getPositions(); _count.addAndGet(childNodes.size() + positions.size()); for (final Position position : positions) { submit(new Runnable() { @Override public void run() { try { getCallback().preOrderOperation(position); } finally { childDone(); } } }); } for (final PortfolioNode node : childNodes) { submit(new NodeTraverser(node, this)); } } public void childDone() { if (_count.decrementAndGet() == 0) { if (_secondPass) { try { getCallback().postOrderOperation(_node); } finally { if (_parent != null) { _parent.childDone(); } } } else { _secondPass = true; final List<Position> positions = _node.getPositions(); if (positions.isEmpty()) { try { getCallback().postOrderOperation(_node); } finally { if (_parent != null) { _parent.childDone(); } } } else { _count.addAndGet(positions.size()); for (final Position position : positions) { submit(new Runnable() { @Override public void run() { try { getCallback().postOrderOperation(position); } finally { childDone(); } } }); } } } } } } private void submit(final Runnable runnable) { _count.incrementAndGet(); if (_work.isEmpty()) { synchronized (this) { if (_work.isEmpty()) { _work.add(runnable); notify(); // Don't submit a job - there will be the caller to waitForCompletion return; } else { _work.add(runnable); } } } else { _work.add(runnable); } getExecutorService().submit(new Runnable() { @Override public void run() { // The original thread might have raced ahead so there might not be work for us in the queue final Runnable underlying = _work.poll(); if (underlying != null) { try { underlying.run(); } catch (final Throwable t) { s_logger.error("Error running work item {}", t.getMessage()); s_logger.warn("Caught exception", t); } finally { if (_count.decrementAndGet() == 0) { // This was the last piece of work synchronized (Context.this) { Context.this.notify(); } } } } } }); } public void waitForCompletion() { try { do { Runnable work = _work.poll(); while (work != null) { try { work.run(); } catch (final Throwable t) { s_logger.error("Error running work item {}", t.getMessage()); s_logger.warn("Caught exception", t); } if (_count.decrementAndGet() == 0) { // This was the last piece of work - we're done return; } work = _work.poll(); } // Nothing in the queue but the background threads are busy synchronized (this) { if (_count.get() == 0) { // We're done return; } if (_work.isEmpty()) { wait(); } } } while (true); } catch (final InterruptedException e) { s_logger.info("Interrupted waiting for completion"); throw new OpenGammaRuntimeException("interrupted", e); } } } /** * Traverse the nodes notifying using the callback. * * @param portfolioNode the node to start from, null does nothing */ @Override public void traverse(final PortfolioNode portfolioNode) { if (portfolioNode == null) { return; } final Context context = new Context(); context.submit(context.new NodeTraverser(portfolioNode, null)); context.waitForCompletion(); } }
[ "public", "class", "ParallelPortfolioNodeTraverser", "extends", "PortfolioNodeTraverser", "{", "private", "static", "final", "Logger", "s_logger", "=", "LoggerFactory", ".", "getLogger", "(", "ParallelPortfolioNodeTraverser", ".", "class", ")", ";", "private", "final", "ExecutorService", "_executorService", ";", "/**\n * Creates a traverser.\n *\n * @param callback the callback to invoke, not null\n * @param executorService the executor service for parallel resolutions\n */", "public", "ParallelPortfolioNodeTraverser", "(", "final", "PortfolioNodeTraversalCallback", "callback", ",", "final", "ExecutorService", "executorService", ")", "{", "super", "(", "callback", ")", ";", "ArgumentChecker", ".", "notNull", "(", "executorService", ",", "\"", "executorService", "\"", ")", ";", "_executorService", "=", "executorService", ";", "}", "protected", "ExecutorService", "getExecutorService", "(", ")", "{", "return", "_executorService", ";", "}", "private", "final", "class", "Context", "{", "private", "final", "AtomicInteger", "_count", "=", "new", "AtomicInteger", "(", ")", ";", "private", "final", "Queue", "<", "Runnable", ">", "_work", "=", "new", "ConcurrentLinkedQueue", "<", "Runnable", ">", "(", ")", ";", "private", "final", "class", "NodeTraverser", "implements", "Runnable", "{", "private", "final", "NodeTraverser", "_parent", ";", "private", "final", "PortfolioNode", "_node", ";", "private", "final", "AtomicInteger", "_count", "=", "new", "AtomicInteger", "(", ")", ";", "private", "volatile", "boolean", "_secondPass", ";", "public", "NodeTraverser", "(", "final", "PortfolioNode", "node", ",", "final", "NodeTraverser", "parent", ")", "{", "_node", "=", "node", ";", "_parent", "=", "parent", ";", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "getCallback", "(", ")", ".", "preOrderOperation", "(", "_node", ")", ";", "final", "List", "<", "PortfolioNode", ">", "childNodes", "=", "_node", ".", "getChildNodes", "(", ")", ";", "final", "List", "<", "Position", ">", "positions", "=", "_node", ".", "getPositions", "(", ")", ";", "_count", ".", "addAndGet", "(", "childNodes", ".", "size", "(", ")", "+", "positions", ".", "size", "(", ")", ")", ";", "for", "(", "final", "Position", "position", ":", "positions", ")", "{", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "getCallback", "(", ")", ".", "preOrderOperation", "(", "position", ")", ";", "}", "finally", "{", "childDone", "(", ")", ";", "}", "}", "}", ")", ";", "}", "for", "(", "final", "PortfolioNode", "node", ":", "childNodes", ")", "{", "submit", "(", "new", "NodeTraverser", "(", "node", ",", "this", ")", ")", ";", "}", "}", "public", "void", "childDone", "(", ")", "{", "if", "(", "_count", ".", "decrementAndGet", "(", ")", "==", "0", ")", "{", "if", "(", "_secondPass", ")", "{", "try", "{", "getCallback", "(", ")", ".", "postOrderOperation", "(", "_node", ")", ";", "}", "finally", "{", "if", "(", "_parent", "!=", "null", ")", "{", "_parent", ".", "childDone", "(", ")", ";", "}", "}", "}", "else", "{", "_secondPass", "=", "true", ";", "final", "List", "<", "Position", ">", "positions", "=", "_node", ".", "getPositions", "(", ")", ";", "if", "(", "positions", ".", "isEmpty", "(", ")", ")", "{", "try", "{", "getCallback", "(", ")", ".", "postOrderOperation", "(", "_node", ")", ";", "}", "finally", "{", "if", "(", "_parent", "!=", "null", ")", "{", "_parent", ".", "childDone", "(", ")", ";", "}", "}", "}", "else", "{", "_count", ".", "addAndGet", "(", "positions", ".", "size", "(", ")", ")", ";", "for", "(", "final", "Position", "position", ":", "positions", ")", "{", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "getCallback", "(", ")", ".", "postOrderOperation", "(", "position", ")", ";", "}", "finally", "{", "childDone", "(", ")", ";", "}", "}", "}", ")", ";", "}", "}", "}", "}", "}", "}", "private", "void", "submit", "(", "final", "Runnable", "runnable", ")", "{", "_count", ".", "incrementAndGet", "(", ")", ";", "if", "(", "_work", ".", "isEmpty", "(", ")", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "_work", ".", "isEmpty", "(", ")", ")", "{", "_work", ".", "add", "(", "runnable", ")", ";", "notify", "(", ")", ";", "return", ";", "}", "else", "{", "_work", ".", "add", "(", "runnable", ")", ";", "}", "}", "}", "else", "{", "_work", ".", "add", "(", "runnable", ")", ";", "}", "getExecutorService", "(", ")", ".", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "final", "Runnable", "underlying", "=", "_work", ".", "poll", "(", ")", ";", "if", "(", "underlying", "!=", "null", ")", "{", "try", "{", "underlying", ".", "run", "(", ")", ";", "}", "catch", "(", "final", "Throwable", "t", ")", "{", "s_logger", ".", "error", "(", "\"", "Error running work item {}", "\"", ",", "t", ".", "getMessage", "(", ")", ")", ";", "s_logger", ".", "warn", "(", "\"", "Caught exception", "\"", ",", "t", ")", ";", "}", "finally", "{", "if", "(", "_count", ".", "decrementAndGet", "(", ")", "==", "0", ")", "{", "synchronized", "(", "Context", ".", "this", ")", "{", "Context", ".", "this", ".", "notify", "(", ")", ";", "}", "}", "}", "}", "}", "}", ")", ";", "}", "public", "void", "waitForCompletion", "(", ")", "{", "try", "{", "do", "{", "Runnable", "work", "=", "_work", ".", "poll", "(", ")", ";", "while", "(", "work", "!=", "null", ")", "{", "try", "{", "work", ".", "run", "(", ")", ";", "}", "catch", "(", "final", "Throwable", "t", ")", "{", "s_logger", ".", "error", "(", "\"", "Error running work item {}", "\"", ",", "t", ".", "getMessage", "(", ")", ")", ";", "s_logger", ".", "warn", "(", "\"", "Caught exception", "\"", ",", "t", ")", ";", "}", "if", "(", "_count", ".", "decrementAndGet", "(", ")", "==", "0", ")", "{", "return", ";", "}", "work", "=", "_work", ".", "poll", "(", ")", ";", "}", "synchronized", "(", "this", ")", "{", "if", "(", "_count", ".", "get", "(", ")", "==", "0", ")", "{", "return", ";", "}", "if", "(", "_work", ".", "isEmpty", "(", ")", ")", "{", "wait", "(", ")", ";", "}", "}", "}", "while", "(", "true", ")", ";", "}", "catch", "(", "final", "InterruptedException", "e", ")", "{", "s_logger", ".", "info", "(", "\"", "Interrupted waiting for completion", "\"", ")", ";", "throw", "new", "OpenGammaRuntimeException", "(", "\"", "interrupted", "\"", ",", "e", ")", ";", "}", "}", "}", "/**\n * Traverse the nodes notifying using the callback.\n *\n * @param portfolioNode the node to start from, null does nothing\n */", "@", "Override", "public", "void", "traverse", "(", "final", "PortfolioNode", "portfolioNode", ")", "{", "if", "(", "portfolioNode", "==", "null", ")", "{", "return", ";", "}", "final", "Context", "context", "=", "new", "Context", "(", ")", ";", "context", ".", "submit", "(", "context", ".", "new", "NodeTraverser", "(", "portfolioNode", ",", "null", ")", ")", ";", "context", ".", "waitForCompletion", "(", ")", ";", "}", "}" ]
A traverser that runs in parallel using a number of threads.
[ "A", "traverser", "that", "runs", "in", "parallel", "using", "a", "number", "of", "threads", "." ]
[ "// Don't submit a job - there will be the caller to waitForCompletion", "// The original thread might have raced ahead so there might not be work for us in the queue", "// This was the last piece of work", "// This was the last piece of work - we're done", "// Nothing in the queue but the background threads are busy", "// We're done" ]
[ { "param": "PortfolioNodeTraverser", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PortfolioNodeTraverser", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b476c94ef8ffd6863632f497eb45a51597d4521
Qianzf/JavaWeb
src/main/java/com/senchuuhi/iweb/auto/entity/AxeArticleExample.java
[ "MIT" ]
Java
GeneratedCriteria
/** * This class was generated by MyBatis Generator. * This class corresponds to the database table axe_article * * @mbg.generated */
This class was generated by MyBatis Generator. This class corresponds to the database table axe_article
[ "This", "class", "was", "generated", "by", "MyBatis", "Generator", ".", "This", "class", "corresponds", "to", "the", "database", "table", "axe_article" ]
protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andArticleNameIsNull() { addCriterion("article_name is null"); return (Criteria) this; } public Criteria andArticleNameIsNotNull() { addCriterion("article_name is not null"); return (Criteria) this; } public Criteria andArticleNameEqualTo(String value) { addCriterion("article_name =", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameNotEqualTo(String value) { addCriterion("article_name <>", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameGreaterThan(String value) { addCriterion("article_name >", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameGreaterThanOrEqualTo(String value) { addCriterion("article_name >=", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameLessThan(String value) { addCriterion("article_name <", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameLessThanOrEqualTo(String value) { addCriterion("article_name <=", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameLike(String value) { addCriterion("article_name like", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameNotLike(String value) { addCriterion("article_name not like", value, "articleName"); return (Criteria) this; } public Criteria andArticleNameIn(List<String> values) { addCriterion("article_name in", values, "articleName"); return (Criteria) this; } public Criteria andArticleNameNotIn(List<String> values) { addCriterion("article_name not in", values, "articleName"); return (Criteria) this; } public Criteria andArticleNameBetween(String value1, String value2) { addCriterion("article_name between", value1, value2, "articleName"); return (Criteria) this; } public Criteria andArticleNameNotBetween(String value1, String value2) { addCriterion("article_name not between", value1, value2, "articleName"); return (Criteria) this; } public Criteria andArticleAuthorIsNull() { addCriterion("article_author is null"); return (Criteria) this; } public Criteria andArticleAuthorIsNotNull() { addCriterion("article_author is not null"); return (Criteria) this; } public Criteria andArticleAuthorEqualTo(String value) { addCriterion("article_author =", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorNotEqualTo(String value) { addCriterion("article_author <>", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorGreaterThan(String value) { addCriterion("article_author >", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorGreaterThanOrEqualTo(String value) { addCriterion("article_author >=", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorLessThan(String value) { addCriterion("article_author <", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorLessThanOrEqualTo(String value) { addCriterion("article_author <=", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorLike(String value) { addCriterion("article_author like", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorNotLike(String value) { addCriterion("article_author not like", value, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorIn(List<String> values) { addCriterion("article_author in", values, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorNotIn(List<String> values) { addCriterion("article_author not in", values, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorBetween(String value1, String value2) { addCriterion("article_author between", value1, value2, "articleAuthor"); return (Criteria) this; } public Criteria andArticleAuthorNotBetween(String value1, String value2) { addCriterion("article_author not between", value1, value2, "articleAuthor"); return (Criteria) this; } public Criteria andArticleContentIsNull() { addCriterion("article_content is null"); return (Criteria) this; } public Criteria andArticleContentIsNotNull() { addCriterion("article_content is not null"); return (Criteria) this; } public Criteria andArticleContentEqualTo(String value) { addCriterion("article_content =", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentNotEqualTo(String value) { addCriterion("article_content <>", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentGreaterThan(String value) { addCriterion("article_content >", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentGreaterThanOrEqualTo(String value) { addCriterion("article_content >=", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentLessThan(String value) { addCriterion("article_content <", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentLessThanOrEqualTo(String value) { addCriterion("article_content <=", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentLike(String value) { addCriterion("article_content like", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentNotLike(String value) { addCriterion("article_content not like", value, "articleContent"); return (Criteria) this; } public Criteria andArticleContentIn(List<String> values) { addCriterion("article_content in", values, "articleContent"); return (Criteria) this; } public Criteria andArticleContentNotIn(List<String> values) { addCriterion("article_content not in", values, "articleContent"); return (Criteria) this; } public Criteria andArticleContentBetween(String value1, String value2) { addCriterion("article_content between", value1, value2, "articleContent"); return (Criteria) this; } public Criteria andArticleContentNotBetween(String value1, String value2) { addCriterion("article_content not between", value1, value2, "articleContent"); return (Criteria) this; } public Criteria andArticleSourceIsNull() { addCriterion("article_source is null"); return (Criteria) this; } public Criteria andArticleSourceIsNotNull() { addCriterion("article_source is not null"); return (Criteria) this; } public Criteria andArticleSourceEqualTo(String value) { addCriterion("article_source =", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceNotEqualTo(String value) { addCriterion("article_source <>", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceGreaterThan(String value) { addCriterion("article_source >", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceGreaterThanOrEqualTo(String value) { addCriterion("article_source >=", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceLessThan(String value) { addCriterion("article_source <", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceLessThanOrEqualTo(String value) { addCriterion("article_source <=", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceLike(String value) { addCriterion("article_source like", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceNotLike(String value) { addCriterion("article_source not like", value, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceIn(List<String> values) { addCriterion("article_source in", values, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceNotIn(List<String> values) { addCriterion("article_source not in", values, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceBetween(String value1, String value2) { addCriterion("article_source between", value1, value2, "articleSource"); return (Criteria) this; } public Criteria andArticleSourceNotBetween(String value1, String value2) { addCriterion("article_source not between", value1, value2, "articleSource"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreatorIsNull() { addCriterion("creator is null"); return (Criteria) this; } public Criteria andCreatorIsNotNull() { addCriterion("creator is not null"); return (Criteria) this; } public Criteria andCreatorEqualTo(String value) { addCriterion("creator =", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotEqualTo(String value) { addCriterion("creator <>", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThan(String value) { addCriterion("creator >", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThanOrEqualTo(String value) { addCriterion("creator >=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThan(String value) { addCriterion("creator <", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThanOrEqualTo(String value) { addCriterion("creator <=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLike(String value) { addCriterion("creator like", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotLike(String value) { addCriterion("creator not like", value, "creator"); return (Criteria) this; } public Criteria andCreatorIn(List<String> values) { addCriterion("creator in", values, "creator"); return (Criteria) this; } public Criteria andCreatorNotIn(List<String> values) { addCriterion("creator not in", values, "creator"); return (Criteria) this; } public Criteria andCreatorBetween(String value1, String value2) { addCriterion("creator between", value1, value2, "creator"); return (Criteria) this; } public Criteria andCreatorNotBetween(String value1, String value2) { addCriterion("creator not between", value1, value2, "creator"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdaterIsNull() { addCriterion("updater is null"); return (Criteria) this; } public Criteria andUpdaterIsNotNull() { addCriterion("updater is not null"); return (Criteria) this; } public Criteria andUpdaterEqualTo(String value) { addCriterion("updater =", value, "updater"); return (Criteria) this; } public Criteria andUpdaterNotEqualTo(String value) { addCriterion("updater <>", value, "updater"); return (Criteria) this; } public Criteria andUpdaterGreaterThan(String value) { addCriterion("updater >", value, "updater"); return (Criteria) this; } public Criteria andUpdaterGreaterThanOrEqualTo(String value) { addCriterion("updater >=", value, "updater"); return (Criteria) this; } public Criteria andUpdaterLessThan(String value) { addCriterion("updater <", value, "updater"); return (Criteria) this; } public Criteria andUpdaterLessThanOrEqualTo(String value) { addCriterion("updater <=", value, "updater"); return (Criteria) this; } public Criteria andUpdaterLike(String value) { addCriterion("updater like", value, "updater"); return (Criteria) this; } public Criteria andUpdaterNotLike(String value) { addCriterion("updater not like", value, "updater"); return (Criteria) this; } public Criteria andUpdaterIn(List<String> values) { addCriterion("updater in", values, "updater"); return (Criteria) this; } public Criteria andUpdaterNotIn(List<String> values) { addCriterion("updater not in", values, "updater"); return (Criteria) this; } public Criteria andUpdaterBetween(String value1, String value2) { addCriterion("updater between", value1, value2, "updater"); return (Criteria) this; } public Criteria andUpdaterNotBetween(String value1, String value2) { addCriterion("updater not between", value1, value2, "updater"); return (Criteria) this; } public Criteria andDeleteFlagIsNull() { addCriterion("delete_flag is null"); return (Criteria) this; } public Criteria andDeleteFlagIsNotNull() { addCriterion("delete_flag is not null"); return (Criteria) this; } public Criteria andDeleteFlagEqualTo(Short value) { addCriterion("delete_flag =", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotEqualTo(Short value) { addCriterion("delete_flag <>", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThan(Short value) { addCriterion("delete_flag >", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagGreaterThanOrEqualTo(Short value) { addCriterion("delete_flag >=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThan(Short value) { addCriterion("delete_flag <", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagLessThanOrEqualTo(Short value) { addCriterion("delete_flag <=", value, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagIn(List<Short> values) { addCriterion("delete_flag in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotIn(List<Short> values) { addCriterion("delete_flag not in", values, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagBetween(Short value1, Short value2) { addCriterion("delete_flag between", value1, value2, "deleteFlag"); return (Criteria) this; } public Criteria andDeleteFlagNotBetween(Short value1, Short value2) { addCriterion("delete_flag not between", value1, value2, "deleteFlag"); return (Criteria) this; } }
[ "protected", "abstract", "static", "class", "GeneratedCriteria", "{", "protected", "List", "<", "Criterion", ">", "criteria", ";", "protected", "GeneratedCriteria", "(", ")", "{", "super", "(", ")", ";", "criteria", "=", "new", "ArrayList", "<", "Criterion", ">", "(", ")", ";", "}", "public", "boolean", "isValid", "(", ")", "{", "return", "criteria", ".", "size", "(", ")", ">", "0", ";", "}", "public", "List", "<", "Criterion", ">", "getAllCriteria", "(", ")", "{", "return", "criteria", ";", "}", "public", "List", "<", "Criterion", ">", "getCriteria", "(", ")", "{", "return", "criteria", ";", "}", "protected", "void", "addCriterion", "(", "String", "condition", ")", "{", "if", "(", "condition", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Value for condition cannot be null", "\"", ")", ";", "}", "criteria", ".", "add", "(", "new", "Criterion", "(", "condition", ")", ")", ";", "}", "protected", "void", "addCriterion", "(", "String", "condition", ",", "Object", "value", ",", "String", "property", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Value for ", "\"", "+", "property", "+", "\"", " cannot be null", "\"", ")", ";", "}", "criteria", ".", "add", "(", "new", "Criterion", "(", "condition", ",", "value", ")", ")", ";", "}", "protected", "void", "addCriterion", "(", "String", "condition", ",", "Object", "value1", ",", "Object", "value2", ",", "String", "property", ")", "{", "if", "(", "value1", "==", "null", "||", "value2", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Between values for ", "\"", "+", "property", "+", "\"", " cannot be null", "\"", ")", ";", "}", "criteria", ".", "add", "(", "new", "Criterion", "(", "condition", ",", "value1", ",", "value2", ")", ")", ";", "}", "public", "Criteria", "andIdIsNull", "(", ")", "{", "addCriterion", "(", "\"", "id is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "id is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdEqualTo", "(", "Integer", "value", ")", "{", "addCriterion", "(", "\"", "id =", "\"", ",", "value", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdNotEqualTo", "(", "Integer", "value", ")", "{", "addCriterion", "(", "\"", "id <>", "\"", ",", "value", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdGreaterThan", "(", "Integer", "value", ")", "{", "addCriterion", "(", "\"", "id >", "\"", ",", "value", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdGreaterThanOrEqualTo", "(", "Integer", "value", ")", "{", "addCriterion", "(", "\"", "id >=", "\"", ",", "value", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdLessThan", "(", "Integer", "value", ")", "{", "addCriterion", "(", "\"", "id <", "\"", ",", "value", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdLessThanOrEqualTo", "(", "Integer", "value", ")", "{", "addCriterion", "(", "\"", "id <=", "\"", ",", "value", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdIn", "(", "List", "<", "Integer", ">", "values", ")", "{", "addCriterion", "(", "\"", "id in", "\"", ",", "values", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdNotIn", "(", "List", "<", "Integer", ">", "values", ")", "{", "addCriterion", "(", "\"", "id not in", "\"", ",", "values", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdBetween", "(", "Integer", "value1", ",", "Integer", "value2", ")", "{", "addCriterion", "(", "\"", "id between", "\"", ",", "value1", ",", "value2", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andIdNotBetween", "(", "Integer", "value1", ",", "Integer", "value2", ")", "{", "addCriterion", "(", "\"", "id not between", "\"", ",", "value1", ",", "value2", ",", "\"", "id", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameIsNull", "(", ")", "{", "addCriterion", "(", "\"", "article_name is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "article_name is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name =", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameNotEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name <>", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameGreaterThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name >", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameGreaterThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name >=", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameLessThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name <", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameLessThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name <=", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name like", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameNotLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_name not like", "\"", ",", "value", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_name in", "\"", ",", "values", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameNotIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_name not in", "\"", ",", "values", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_name between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleNameNotBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_name not between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleName", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorIsNull", "(", ")", "{", "addCriterion", "(", "\"", "article_author is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "article_author is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author =", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorNotEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author <>", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorGreaterThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author >", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorGreaterThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author >=", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorLessThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author <", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorLessThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author <=", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author like", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorNotLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_author not like", "\"", ",", "value", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_author in", "\"", ",", "values", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorNotIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_author not in", "\"", ",", "values", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_author between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleAuthorNotBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_author not between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleAuthor", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentIsNull", "(", ")", "{", "addCriterion", "(", "\"", "article_content is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "article_content is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content =", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentNotEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content <>", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentGreaterThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content >", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentGreaterThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content >=", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentLessThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content <", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentLessThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content <=", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content like", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentNotLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_content not like", "\"", ",", "value", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_content in", "\"", ",", "values", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentNotIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_content not in", "\"", ",", "values", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_content between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleContentNotBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_content not between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleContent", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceIsNull", "(", ")", "{", "addCriterion", "(", "\"", "article_source is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "article_source is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source =", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceNotEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source <>", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceGreaterThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source >", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceGreaterThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source >=", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceLessThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source <", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceLessThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source <=", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source like", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceNotLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "article_source not like", "\"", ",", "value", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_source in", "\"", ",", "values", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceNotIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "article_source not in", "\"", ",", "values", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_source between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andArticleSourceNotBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "article_source not between", "\"", ",", "value1", ",", "value2", ",", "\"", "articleSource", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeIsNull", "(", ")", "{", "addCriterion", "(", "\"", "create_time is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "create_time is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "create_time =", "\"", ",", "value", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeNotEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "create_time <>", "\"", ",", "value", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeGreaterThan", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "create_time >", "\"", ",", "value", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeGreaterThanOrEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "create_time >=", "\"", ",", "value", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeLessThan", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "create_time <", "\"", ",", "value", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeLessThanOrEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "create_time <=", "\"", ",", "value", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeIn", "(", "List", "<", "Date", ">", "values", ")", "{", "addCriterion", "(", "\"", "create_time in", "\"", ",", "values", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeNotIn", "(", "List", "<", "Date", ">", "values", ")", "{", "addCriterion", "(", "\"", "create_time not in", "\"", ",", "values", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeBetween", "(", "Date", "value1", ",", "Date", "value2", ")", "{", "addCriterion", "(", "\"", "create_time between", "\"", ",", "value1", ",", "value2", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreateTimeNotBetween", "(", "Date", "value1", ",", "Date", "value2", ")", "{", "addCriterion", "(", "\"", "create_time not between", "\"", ",", "value1", ",", "value2", ",", "\"", "createTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorIsNull", "(", ")", "{", "addCriterion", "(", "\"", "creator is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "creator is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator =", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorNotEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator <>", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorGreaterThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator >", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorGreaterThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator >=", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorLessThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator <", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorLessThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator <=", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator like", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorNotLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "creator not like", "\"", ",", "value", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "creator in", "\"", ",", "values", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorNotIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "creator not in", "\"", ",", "values", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "creator between", "\"", ",", "value1", ",", "value2", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andCreatorNotBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "creator not between", "\"", ",", "value1", ",", "value2", ",", "\"", "creator", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeIsNull", "(", ")", "{", "addCriterion", "(", "\"", "update_time is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "update_time is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "update_time =", "\"", ",", "value", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeNotEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "update_time <>", "\"", ",", "value", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeGreaterThan", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "update_time >", "\"", ",", "value", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeGreaterThanOrEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "update_time >=", "\"", ",", "value", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeLessThan", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "update_time <", "\"", ",", "value", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeLessThanOrEqualTo", "(", "Date", "value", ")", "{", "addCriterion", "(", "\"", "update_time <=", "\"", ",", "value", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeIn", "(", "List", "<", "Date", ">", "values", ")", "{", "addCriterion", "(", "\"", "update_time in", "\"", ",", "values", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeNotIn", "(", "List", "<", "Date", ">", "values", ")", "{", "addCriterion", "(", "\"", "update_time not in", "\"", ",", "values", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeBetween", "(", "Date", "value1", ",", "Date", "value2", ")", "{", "addCriterion", "(", "\"", "update_time between", "\"", ",", "value1", ",", "value2", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdateTimeNotBetween", "(", "Date", "value1", ",", "Date", "value2", ")", "{", "addCriterion", "(", "\"", "update_time not between", "\"", ",", "value1", ",", "value2", ",", "\"", "updateTime", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterIsNull", "(", ")", "{", "addCriterion", "(", "\"", "updater is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "updater is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater =", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterNotEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater <>", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterGreaterThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater >", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterGreaterThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater >=", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterLessThan", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater <", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterLessThanOrEqualTo", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater <=", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater like", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterNotLike", "(", "String", "value", ")", "{", "addCriterion", "(", "\"", "updater not like", "\"", ",", "value", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "updater in", "\"", ",", "values", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterNotIn", "(", "List", "<", "String", ">", "values", ")", "{", "addCriterion", "(", "\"", "updater not in", "\"", ",", "values", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "updater between", "\"", ",", "value1", ",", "value2", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andUpdaterNotBetween", "(", "String", "value1", ",", "String", "value2", ")", "{", "addCriterion", "(", "\"", "updater not between", "\"", ",", "value1", ",", "value2", ",", "\"", "updater", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagIsNull", "(", ")", "{", "addCriterion", "(", "\"", "delete_flag is null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagIsNotNull", "(", ")", "{", "addCriterion", "(", "\"", "delete_flag is not null", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagEqualTo", "(", "Short", "value", ")", "{", "addCriterion", "(", "\"", "delete_flag =", "\"", ",", "value", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagNotEqualTo", "(", "Short", "value", ")", "{", "addCriterion", "(", "\"", "delete_flag <>", "\"", ",", "value", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagGreaterThan", "(", "Short", "value", ")", "{", "addCriterion", "(", "\"", "delete_flag >", "\"", ",", "value", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagGreaterThanOrEqualTo", "(", "Short", "value", ")", "{", "addCriterion", "(", "\"", "delete_flag >=", "\"", ",", "value", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagLessThan", "(", "Short", "value", ")", "{", "addCriterion", "(", "\"", "delete_flag <", "\"", ",", "value", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagLessThanOrEqualTo", "(", "Short", "value", ")", "{", "addCriterion", "(", "\"", "delete_flag <=", "\"", ",", "value", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagIn", "(", "List", "<", "Short", ">", "values", ")", "{", "addCriterion", "(", "\"", "delete_flag in", "\"", ",", "values", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagNotIn", "(", "List", "<", "Short", ">", "values", ")", "{", "addCriterion", "(", "\"", "delete_flag not in", "\"", ",", "values", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagBetween", "(", "Short", "value1", ",", "Short", "value2", ")", "{", "addCriterion", "(", "\"", "delete_flag between", "\"", ",", "value1", ",", "value2", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "public", "Criteria", "andDeleteFlagNotBetween", "(", "Short", "value1", ",", "Short", "value2", ")", "{", "addCriterion", "(", "\"", "delete_flag not between", "\"", ",", "value1", ",", "value2", ",", "\"", "deleteFlag", "\"", ")", ";", "return", "(", "Criteria", ")", "this", ";", "}", "}" ]
This class was generated by MyBatis Generator.
[ "This", "class", "was", "generated", "by", "MyBatis", "Generator", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b476c94ef8ffd6863632f497eb45a51597d4521
Qianzf/JavaWeb
src/main/java/com/senchuuhi/iweb/auto/entity/AxeArticleExample.java
[ "MIT" ]
Java
Criteria
/** * This class was generated by MyBatis Generator. * This class corresponds to the database table axe_article * * @mbg.generated do_not_delete_during_merge */
This class was generated by MyBatis Generator. This class corresponds to the database table axe_article
[ "This", "class", "was", "generated", "by", "MyBatis", "Generator", ".", "This", "class", "corresponds", "to", "the", "database", "table", "axe_article" ]
public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } }
[ "public", "static", "class", "Criteria", "extends", "GeneratedCriteria", "{", "protected", "Criteria", "(", ")", "{", "super", "(", ")", ";", "}", "}" ]
This class was generated by MyBatis Generator.
[ "This", "class", "was", "generated", "by", "MyBatis", "Generator", "." ]
[]
[ { "param": "GeneratedCriteria", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GeneratedCriteria", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b476c94ef8ffd6863632f497eb45a51597d4521
Qianzf/JavaWeb
src/main/java/com/senchuuhi/iweb/auto/entity/AxeArticleExample.java
[ "MIT" ]
Java
Criterion
/** * This class was generated by MyBatis Generator. * This class corresponds to the database table axe_article * * @mbg.generated */
This class was generated by MyBatis Generator. This class corresponds to the database table axe_article
[ "This", "class", "was", "generated", "by", "MyBatis", "Generator", ".", "This", "class", "corresponds", "to", "the", "database", "table", "axe_article" ]
public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } }
[ "public", "static", "class", "Criterion", "{", "private", "String", "condition", ";", "private", "Object", "value", ";", "private", "Object", "secondValue", ";", "private", "boolean", "noValue", ";", "private", "boolean", "singleValue", ";", "private", "boolean", "betweenValue", ";", "private", "boolean", "listValue", ";", "private", "String", "typeHandler", ";", "public", "String", "getCondition", "(", ")", "{", "return", "condition", ";", "}", "public", "Object", "getValue", "(", ")", "{", "return", "value", ";", "}", "public", "Object", "getSecondValue", "(", ")", "{", "return", "secondValue", ";", "}", "public", "boolean", "isNoValue", "(", ")", "{", "return", "noValue", ";", "}", "public", "boolean", "isSingleValue", "(", ")", "{", "return", "singleValue", ";", "}", "public", "boolean", "isBetweenValue", "(", ")", "{", "return", "betweenValue", ";", "}", "public", "boolean", "isListValue", "(", ")", "{", "return", "listValue", ";", "}", "public", "String", "getTypeHandler", "(", ")", "{", "return", "typeHandler", ";", "}", "protected", "Criterion", "(", "String", "condition", ")", "{", "super", "(", ")", ";", "this", ".", "condition", "=", "condition", ";", "this", ".", "typeHandler", "=", "null", ";", "this", ".", "noValue", "=", "true", ";", "}", "protected", "Criterion", "(", "String", "condition", ",", "Object", "value", ",", "String", "typeHandler", ")", "{", "super", "(", ")", ";", "this", ".", "condition", "=", "condition", ";", "this", ".", "value", "=", "value", ";", "this", ".", "typeHandler", "=", "typeHandler", ";", "if", "(", "value", "instanceof", "List", "<", "?", ">", ")", "{", "this", ".", "listValue", "=", "true", ";", "}", "else", "{", "this", ".", "singleValue", "=", "true", ";", "}", "}", "protected", "Criterion", "(", "String", "condition", ",", "Object", "value", ")", "{", "this", "(", "condition", ",", "value", ",", "null", ")", ";", "}", "protected", "Criterion", "(", "String", "condition", ",", "Object", "value", ",", "Object", "secondValue", ",", "String", "typeHandler", ")", "{", "super", "(", ")", ";", "this", ".", "condition", "=", "condition", ";", "this", ".", "value", "=", "value", ";", "this", ".", "secondValue", "=", "secondValue", ";", "this", ".", "typeHandler", "=", "typeHandler", ";", "this", ".", "betweenValue", "=", "true", ";", "}", "protected", "Criterion", "(", "String", "condition", ",", "Object", "value", ",", "Object", "secondValue", ")", "{", "this", "(", "condition", ",", "value", ",", "secondValue", ",", "null", ")", ";", "}", "}" ]
This class was generated by MyBatis Generator.
[ "This", "class", "was", "generated", "by", "MyBatis", "Generator", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b49bc183ae1a19f0cd0650d559479a48c837d23
danielbraithwt/University
Undergraduate/SWEN221/Assignment 3/src/assignment3/chessview/moves/PawnPromotion.java
[ "MIT" ]
Java
PawnPromotion
/** * This represents a pawn promotion. * @author djp * */
This represents a pawn promotion. @author djp
[ "This", "represents", "a", "pawn", "promotion", ".", "@author", "djp" ]
public class PawnPromotion implements MultiPieceMove { private Piece promotion; private SinglePieceMove move; public PawnPromotion(SinglePieceMove move, Piece promotion) { this.promotion = promotion; this.move = move; } public boolean isWhite() { return move.isWhite(); } public boolean isValid(Board board) { if (!move.isValid(board)) { return false; } if (!(move.piece instanceof Pawn) || (promotion instanceof Pawn)) { return false; } if (promotion == null || promotion.isWhite() != move.piece.isWhite()) { return false; } if (move.isWhite() && move.newPosition.row() == 8) { return true; } else if (!move.isWhite() && move.newPosition.row() == 1) { return true; } return false; } public void apply(Board board) { move.apply(board); board.setPieceAt(move.newPosition, promotion); } public String toString() { return super.toString() + "=" + SinglePieceMove.pieceChar(promotion); } }
[ "public", "class", "PawnPromotion", "implements", "MultiPieceMove", "{", "private", "Piece", "promotion", ";", "private", "SinglePieceMove", "move", ";", "public", "PawnPromotion", "(", "SinglePieceMove", "move", ",", "Piece", "promotion", ")", "{", "this", ".", "promotion", "=", "promotion", ";", "this", ".", "move", "=", "move", ";", "}", "public", "boolean", "isWhite", "(", ")", "{", "return", "move", ".", "isWhite", "(", ")", ";", "}", "public", "boolean", "isValid", "(", "Board", "board", ")", "{", "if", "(", "!", "move", ".", "isValid", "(", "board", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "(", "move", ".", "piece", "instanceof", "Pawn", ")", "||", "(", "promotion", "instanceof", "Pawn", ")", ")", "{", "return", "false", ";", "}", "if", "(", "promotion", "==", "null", "||", "promotion", ".", "isWhite", "(", ")", "!=", "move", ".", "piece", ".", "isWhite", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "move", ".", "isWhite", "(", ")", "&&", "move", ".", "newPosition", ".", "row", "(", ")", "==", "8", ")", "{", "return", "true", ";", "}", "else", "if", "(", "!", "move", ".", "isWhite", "(", ")", "&&", "move", ".", "newPosition", ".", "row", "(", ")", "==", "1", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "public", "void", "apply", "(", "Board", "board", ")", "{", "move", ".", "apply", "(", "board", ")", ";", "board", ".", "setPieceAt", "(", "move", ".", "newPosition", ",", "promotion", ")", ";", "}", "public", "String", "toString", "(", ")", "{", "return", "super", ".", "toString", "(", ")", "+", "\"", "=", "\"", "+", "SinglePieceMove", ".", "pieceChar", "(", "promotion", ")", ";", "}", "}" ]
This represents a pawn promotion.
[ "This", "represents", "a", "pawn", "promotion", "." ]
[]
[ { "param": "MultiPieceMove", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MultiPieceMove", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b4b7689f8970d13eea68a7f04bf4a99414be45f
Jenessacordero/CodeU-Spring-2018
src/main/java/codeu/model/store/basic/UserActionStore.java
[ "Apache-2.0" ]
Java
UserActionStore
/** * Store class that uses in-memory data structures to hold values and automatically loads from and * saves to PersistentStorageAgent. It's a singleton so all servlet classes can access the same * instance. */
Store class that uses in-memory data structures to hold values and automatically loads from and saves to PersistentStorageAgent. It's a singleton so all servlet classes can access the same instance.
[ "Store", "class", "that", "uses", "in", "-", "memory", "data", "structures", "to", "hold", "values", "and", "automatically", "loads", "from", "and", "saves", "to", "PersistentStorageAgent", ".", "It", "'", "s", "a", "singleton", "so", "all", "servlet", "classes", "can", "access", "the", "same", "instance", "." ]
public class UserActionStore { /** Singleton instance of UserActionStore. */ private static UserActionStore instance; /** * Returns the singleton instance of MessageStore that should be shared between all servlet * classes. Do not call this function from a test; use getTestInstance() instead. */ public static UserActionStore getInstance() { if (instance == null) { instance = new UserActionStore(PersistentStorageAgent.getInstance()); } return instance; } /** * Instance getter function used for testing. Supply a mock for PersistentStorageAgent. * * @param persistentStorageAgent a mock used for testing */ public static UserActionStore getTestInstance(PersistentStorageAgent persistentStorageAgent) { return new UserActionStore(persistentStorageAgent); } /** * The PersistentStorageAgent responsible for loading UserActions from and saving UserActions to * Datastore. */ private PersistentStorageAgent persistentStorageAgent; /** The in-memory list of UserActions. */ private List<UserAction> userActions; public List<UserAction> returnAllUserActions() { return userActions; } /** This class is a singleton, so its constructor is private. Call getInstance() instead. */ private UserActionStore(PersistentStorageAgent persistentStorageAgent) { this.persistentStorageAgent = persistentStorageAgent; userActions = new ArrayList<>(); } /** Add a new userAction to the current set of UserActions known to the application. */ public void addUserAction(UserAction userAction) { userActions.add(0, userAction); persistentStorageAgent.writeThrough(userAction); } /** Return set of UserActions by User. * @return */ public List<UserAction> returnUserActionsByUser(UUID user) { List<UserAction> userActionsByUser = new ArrayList<>(); for (UserAction userAction : userActions) { if (userAction.getUserId().equals(user)) { userActionsByUser.add(userAction); } } return userActionsByUser; } /** Sets the List of UserActions stored by this UserActionStore. */ public void setUserActions(List<UserAction> userActions) { this.userActions = userActions; } }
[ "public", "class", "UserActionStore", "{", "/** Singleton instance of UserActionStore. */", "private", "static", "UserActionStore", "instance", ";", "/**\n * Returns the singleton instance of MessageStore that should be shared between all servlet\n * classes. Do not call this function from a test; use getTestInstance() instead.\n */", "public", "static", "UserActionStore", "getInstance", "(", ")", "{", "if", "(", "instance", "==", "null", ")", "{", "instance", "=", "new", "UserActionStore", "(", "PersistentStorageAgent", ".", "getInstance", "(", ")", ")", ";", "}", "return", "instance", ";", "}", "/**\n * Instance getter function used for testing. Supply a mock for PersistentStorageAgent.\n *\n * @param persistentStorageAgent a mock used for testing\n */", "public", "static", "UserActionStore", "getTestInstance", "(", "PersistentStorageAgent", "persistentStorageAgent", ")", "{", "return", "new", "UserActionStore", "(", "persistentStorageAgent", ")", ";", "}", "/**\n * The PersistentStorageAgent responsible for loading UserActions from and saving UserActions to\n * Datastore.\n */", "private", "PersistentStorageAgent", "persistentStorageAgent", ";", "/** The in-memory list of UserActions. */", "private", "List", "<", "UserAction", ">", "userActions", ";", "public", "List", "<", "UserAction", ">", "returnAllUserActions", "(", ")", "{", "return", "userActions", ";", "}", "/** This class is a singleton, so its constructor is private. Call getInstance() instead. */", "private", "UserActionStore", "(", "PersistentStorageAgent", "persistentStorageAgent", ")", "{", "this", ".", "persistentStorageAgent", "=", "persistentStorageAgent", ";", "userActions", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "/** Add a new userAction to the current set of UserActions known to the application. */", "public", "void", "addUserAction", "(", "UserAction", "userAction", ")", "{", "userActions", ".", "add", "(", "0", ",", "userAction", ")", ";", "persistentStorageAgent", ".", "writeThrough", "(", "userAction", ")", ";", "}", "/** Return set of UserActions by User. \n * @return */", "public", "List", "<", "UserAction", ">", "returnUserActionsByUser", "(", "UUID", "user", ")", "{", "List", "<", "UserAction", ">", "userActionsByUser", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "UserAction", "userAction", ":", "userActions", ")", "{", "if", "(", "userAction", ".", "getUserId", "(", ")", ".", "equals", "(", "user", ")", ")", "{", "userActionsByUser", ".", "add", "(", "userAction", ")", ";", "}", "}", "return", "userActionsByUser", ";", "}", "/** Sets the List of UserActions stored by this UserActionStore. */", "public", "void", "setUserActions", "(", "List", "<", "UserAction", ">", "userActions", ")", "{", "this", ".", "userActions", "=", "userActions", ";", "}", "}" ]
Store class that uses in-memory data structures to hold values and automatically loads from and saves to PersistentStorageAgent.
[ "Store", "class", "that", "uses", "in", "-", "memory", "data", "structures", "to", "hold", "values", "and", "automatically", "loads", "from", "and", "saves", "to", "PersistentStorageAgent", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b5286738a701bdfb9e3fbb1113ae8bcb27eac1d
joehni/PicoContainer1
gems/src/test/org/picocontainer/gems/util/MulticasterTestCase.java
[ "BSD-3-Clause" ]
Java
MulticasterTestCase
/** * @author Aslak Helles&oslash;y * @version $Revision$ */
@author Aslak Hellesøy @version $Revision$
[ "@author", "Aslak", "Hellesøy", "@version", "$Revision$" ]
public class MulticasterTestCase extends TestCase { public void testOrderOfInstantiationShouldBeDependencyOrder() throws Exception { DefaultPicoContainer pico = new DefaultPicoContainer(); pico.registerComponentImplementation("recording", StringBuffer.class); pico.registerComponentImplementation(RecordingLifecycle.Four.class); pico.registerComponentImplementation(RecordingLifecycle.Two.class); pico.registerComponentImplementation(RecordingLifecycle.One.class); pico.registerComponentImplementation(RecordingLifecycle.Three.class); ProxyFactory proxyFactory = new StandardProxyFactory(); Startable startable = (Startable) Multicaster.object(pico, true, proxyFactory); Startable stoppable = (Startable) Multicaster.object(pico, false, proxyFactory); Disposable disposable = (Disposable) Multicaster.object(pico, false, proxyFactory); startable.start(); stoppable.stop(); disposable.dispose(); assertEquals("<One<Two<Three<FourFour>Three>Two>One>!Four!Three!Two!One", pico.getComponentInstance("recording").toString()); } }
[ "public", "class", "MulticasterTestCase", "extends", "TestCase", "{", "public", "void", "testOrderOfInstantiationShouldBeDependencyOrder", "(", ")", "throws", "Exception", "{", "DefaultPicoContainer", "pico", "=", "new", "DefaultPicoContainer", "(", ")", ";", "pico", ".", "registerComponentImplementation", "(", "\"", "recording", "\"", ",", "StringBuffer", ".", "class", ")", ";", "pico", ".", "registerComponentImplementation", "(", "RecordingLifecycle", ".", "Four", ".", "class", ")", ";", "pico", ".", "registerComponentImplementation", "(", "RecordingLifecycle", ".", "Two", ".", "class", ")", ";", "pico", ".", "registerComponentImplementation", "(", "RecordingLifecycle", ".", "One", ".", "class", ")", ";", "pico", ".", "registerComponentImplementation", "(", "RecordingLifecycle", ".", "Three", ".", "class", ")", ";", "ProxyFactory", "proxyFactory", "=", "new", "StandardProxyFactory", "(", ")", ";", "Startable", "startable", "=", "(", "Startable", ")", "Multicaster", ".", "object", "(", "pico", ",", "true", ",", "proxyFactory", ")", ";", "Startable", "stoppable", "=", "(", "Startable", ")", "Multicaster", ".", "object", "(", "pico", ",", "false", ",", "proxyFactory", ")", ";", "Disposable", "disposable", "=", "(", "Disposable", ")", "Multicaster", ".", "object", "(", "pico", ",", "false", ",", "proxyFactory", ")", ";", "startable", ".", "start", "(", ")", ";", "stoppable", ".", "stop", "(", ")", ";", "disposable", ".", "dispose", "(", ")", ";", "assertEquals", "(", "\"", "<One<Two<Three<FourFour>Three>Two>One>!Four!Three!Two!One", "\"", ",", "pico", ".", "getComponentInstance", "(", "\"", "recording", "\"", ")", ".", "toString", "(", ")", ")", ";", "}", "}" ]
@author Aslak Helles&oslash;y @version $Revision$
[ "@author", "Aslak", "Helles&oslash", ";", "y", "@version", "$Revision$" ]
[]
[ { "param": "TestCase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TestCase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b53183c9ab23f73a41f0b490f44d24ae1d0ab9d
X-com/Rotmg-Packet-Reader
src/main/java/packets/incoming/TradeStartPacket.java
[ "MIT" ]
Java
TradeStartPacket
/** * Received when a new active trade has been initiated */
Received when a new active trade has been initiated
[ "Received", "when", "a", "new", "active", "trade", "has", "been", "initiated" ]
public class TradeStartPacket extends Packet { /** * A description of the player's inventory. Items 0-3 are the hotbar items, * and 4-19 are the 8 inventory slots and 8 backpack slots */ public TradeItem[] clientItems; /** * The trade partner's name. */ public String partnerName; /** * A description of the trade partner's inventory. Items 0-3 are the * hotbar items, and 4-19 are the 8 inventory slots and 8 backpack slots */ public TradeItem[] partnerItems; /** * Unknown int */ public int unknownInt; @Override public void deserialize(BufferReader buffer) throws Exception { clientItems = new TradeItem[buffer.readShort()]; for (int i = 0; i < clientItems.length; i++) { clientItems[i] = new TradeItem().deserialize(buffer); } partnerName = buffer.readString(); partnerItems = new TradeItem[buffer.readShort()]; for (int i = 0; i < partnerItems.length; i++) { partnerItems[i] = new TradeItem().deserialize(buffer); } unknownInt = buffer.readInt(); } }
[ "public", "class", "TradeStartPacket", "extends", "Packet", "{", "/**\n * A description of the player's inventory. Items 0-3 are the hotbar items,\n * and 4-19 are the 8 inventory slots and 8 backpack slots\n */", "public", "TradeItem", "[", "]", "clientItems", ";", "/**\n * The trade partner's name.\n */", "public", "String", "partnerName", ";", "/**\n * A description of the trade partner's inventory. Items 0-3 are the\n * hotbar items, and 4-19 are the 8 inventory slots and 8 backpack slots\n */", "public", "TradeItem", "[", "]", "partnerItems", ";", "/**\n * Unknown int\n */", "public", "int", "unknownInt", ";", "@", "Override", "public", "void", "deserialize", "(", "BufferReader", "buffer", ")", "throws", "Exception", "{", "clientItems", "=", "new", "TradeItem", "[", "buffer", ".", "readShort", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "clientItems", ".", "length", ";", "i", "++", ")", "{", "clientItems", "[", "i", "]", "=", "new", "TradeItem", "(", ")", ".", "deserialize", "(", "buffer", ")", ";", "}", "partnerName", "=", "buffer", ".", "readString", "(", ")", ";", "partnerItems", "=", "new", "TradeItem", "[", "buffer", ".", "readShort", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "partnerItems", ".", "length", ";", "i", "++", ")", "{", "partnerItems", "[", "i", "]", "=", "new", "TradeItem", "(", ")", ".", "deserialize", "(", "buffer", ")", ";", "}", "unknownInt", "=", "buffer", ".", "readInt", "(", ")", ";", "}", "}" ]
Received when a new active trade has been initiated
[ "Received", "when", "a", "new", "active", "trade", "has", "been", "initiated" ]
[]
[ { "param": "Packet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Packet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b56af18f4a5c6fce8bf5b409a983c03206e9687
juhaku/juhakudb
app/src/main/java/db/juhaku/juhakudb/core/android/transaction/StoreTransactionTemplate.java
[ "MIT" ]
Java
StoreTransactionTemplate
/** * Created by juha on 20/05/16. * * <p>Store operation transaction template is used when one or multiple items are being stored * to database. All operations will cascade if items contains other entities.</p> * * @author juha * * @since 1.0.2 */
Created by juha on 20/05/16. Store operation transaction template is used when one or multiple items are being stored to database. All operations will cascade if items contains other entities. @author juha
[ "Created", "by", "juha", "on", "20", "/", "05", "/", "16", ".", "Store", "operation", "transaction", "template", "is", "used", "when", "one", "or", "multiple", "items", "are", "being", "stored", "to", "database", ".", "All", "operations", "will", "cascade", "if", "items", "contains", "other", "entities", ".", "@author", "juha" ]
public class StoreTransactionTemplate<T> extends TransactionTemplate { private Collection<T> items; public void setItems(Collection<T> items) { this.items = new ArrayList<>(items); // transform collection of items to a list. } @Override void onTransaction() { store(items, null); setResult(items); commit(); } /** * Store given items to database. All store operations will be cascaded to referenced tables if * given items has child entities. * * @param items {@link Collection} of items to store. * @param parent Object parent entity that is being used to make foreign key relation to parent table. * * @since 1.2.0 * * @hide */ private void store(Collection<T> items, Object parent) { for (T item : items) { cascadeStoreBefore(item); ContentValues values = getConverter().entityToContentValues(item); // If parent is specified add parent id to content values as it references to child. if (parent != null) { values.put(resolveReverseJoinColumnName(item.getClass(), parent.getClass()), ReflectionUtils.getIdFieldValue(parent).toString()); } Long id = insertOrReplace(resolveTableName(item.getClass()), values); // If storing was successful populate object with the database row id. if (id > -1) { ReflectionUtils.setFieldValue(ReflectionUtils.findIdField(item.getClass()), item, id); cascadeStoreAfter(item); } else { // Some general logging if storing fails. Log.v(getClass().getName(), "Failed to store item: " + item + " to database!"); } } } /** * Store cascade before the actual item is being stored. This stores items that the item itself * should refer to when being stored. * * @param item T item that is being cascade stored. * * @since 1.2.0 * * @hide */ private void cascadeStoreBefore(T item) { for (Field field : item.getClass().getDeclaredFields()) { Object value = ReflectionUtils.getFieldValue(item, field); /* * If field has foreign key relation it should be stored before the actual item is being * stored. */ if (field.isAnnotationPresent(ManyToOne.class) || (field.isAnnotationPresent(OneToOne.class) && StringUtils.isBlank(field.getAnnotation(OneToOne.class).mappedBy()))) { // Check that there is actually something to store. if (value != null) { store((Collection<T>) toCollection(value), null); } } } } /** * Store cascade after the item was stored to database. This stores items that are referenced * by the item itself. * * @param item T item that is being cascade stored. * * @since 1.2.0 * * @hide */ private void cascadeStoreAfter(T item) { for (Field field : item.getClass().getDeclaredFields()) { Object value = ReflectionUtils.getFieldValue(item, field); /* * If field has primary key relation referenced item will be stored after the actual item * is being stored. */ if (field.isAnnotationPresent(ManyToMany.class) || field.isAnnotationPresent(OneToMany.class) || (field.isAnnotationPresent(OneToOne.class) && !StringUtils.isBlank(field.getAnnotation(OneToOne.class).mappedBy()))) { // Check that there is actually something to store. if (value != null) { if (field.isAnnotationPresent(ManyToMany.class)) { store((Collection<T>) toCollection(value), null); // Update middle table reference for many to many relations. storeMiddleTable(item, (Collection<T>) value); } else { store((Collection<T>) toCollection(value), item); } } } } } /** * Store middle table joins for given item. This is special processing that is being * executed after both join parties are stored to database. First existing references is being * deleted and then newly coming references is being stored to database for the item. * * <p>References is being created for given item from given collection of items.</p> * * @param item T item from table item. * @param items {@link Collection} of to table items. * * @since 1.2.0 * * @hide */ private void storeMiddleTable(final T item, Collection<T> items) { final Schema middleTable = findMiddleTable(item.getClass(), items.iterator().next().getClass()); /* * Delete existing references by id. */ Query where = getProcessor().createWhere(null, new Filter() { @Override public void filter(Root root, PredicateBuilder builder) { String middleTableJoinColumn = null; for (Reference reference : middleTable.getReferences()) { if (reference.getReferenceTableName().equals(resolveTableName(item.getClass()))) { middleTableJoinColumn = reference.getColumnName(); } } builder.eq(middleTableJoinColumn, ReflectionUtils.getIdFieldValue(item)); } }); getDb().delete(middleTable.getName(), where.getSql(), where.getArgs()); String fromTable = resolveTableName(item.getClass()); /* * Store middle table references. */ for (T joinItem : items) { // Create content value for each join item as each item represents one row in database. ContentValues values = new ContentValues(); for (Reference reference : middleTable.getReferences()) { Object value; /* * Determine which id is being used to to which reference. If reference table equals * from table get id of the from item otherwise use to id. */ if (reference.getReferenceTableName().equals(fromTable)) { value = ReflectionUtils.getIdFieldValue(item).toString(); } else { value = ReflectionUtils.getIdFieldValue(joinItem); } values.put(reference.getColumnName(), value.toString()); } insertOrReplace(middleTable.getName(), values); } } /** * Find middle table by model class and reference model class. * @param model Entity class that join is made from. * @param joinModel Entity class that join is made to. * * @return Schema found middle table or null if not found. * * @since 1.2.0 * * @hide */ private Schema findMiddleTable(Class<?> model, Class<?> joinModel) { String tableName = resolveTableName(model); String joinTable = resolveTableName(joinModel); Schema middleTable; if ((middleTable = getSchema().getElement(tableName.concat("_").concat(joinTable))) == null) { middleTable = getSchema().getElement(joinTable.concat("_").concat(tableName)); } return middleTable; } /** * Inserts or replaces given content values in given table. If SQL was executed successfully the * id of database row will be returned. If execution fails -1 will be returned. * * @param tableName String name of the table to store content values to. * @param values {@link ContentValues} that is being stored to given table. * @return Long id of stored row in database table or -1 if storing will fail. * * @since 1.2.0 * * @hide */ private Long insertOrReplace(String tableName, ContentValues values) { return getDb().replace(tableName, null, values); } /** * Maps given value to collection if value itself is not assignable from collection. * @param value Object value to map. * @return Collection containing given value or if value is collection then itself will be returned. * * @since 1.2.0 * * @hide */ private static <T> Collection<T> toCollection(T value) { if (Collection.class.isAssignableFrom(value.getClass())) { return (Collection<T>) value; } else { return Arrays.asList(value); } } /** * Resolves reverse join column name from given model class's table. Reverse join column name * is returned if reverse join table name is same as provided reverse join model. * * <p>Column is resolved by looking it for from {@link Schema} in order to maintain integrity.</p> * * @param model Instance of {@link Class} of model class of table where the join is made from. * @param reverseModel Instance of {@link Class} of reverse join model of table where the join is made to. * @return String reverse join column name from join table if found. * * @since 1.2.0 * * @hide */ private String resolveReverseJoinColumnName(Class<?> model, Class<?> reverseModel) { Schema table = getSchema().getElement(resolveTableName(model)); if (table != null) { String reverseJoinTableName = resolveTableName(reverseModel); for (Reference reference : table.getReferences()) { if (reference.getReferenceTableName().equals(reverseJoinTableName)) { return reference.getColumnName(); } } } return null; } }
[ "public", "class", "StoreTransactionTemplate", "<", "T", ">", "extends", "TransactionTemplate", "{", "private", "Collection", "<", "T", ">", "items", ";", "public", "void", "setItems", "(", "Collection", "<", "T", ">", "items", ")", "{", "this", ".", "items", "=", "new", "ArrayList", "<", ">", "(", "items", ")", ";", "}", "@", "Override", "void", "onTransaction", "(", ")", "{", "store", "(", "items", ",", "null", ")", ";", "setResult", "(", "items", ")", ";", "commit", "(", ")", ";", "}", "/**\n * Store given items to database. All store operations will be cascaded to referenced tables if\n * given items has child entities.\n *\n * @param items {@link Collection} of items to store.\n * @param parent Object parent entity that is being used to make foreign key relation to parent table.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "void", "store", "(", "Collection", "<", "T", ">", "items", ",", "Object", "parent", ")", "{", "for", "(", "T", "item", ":", "items", ")", "{", "cascadeStoreBefore", "(", "item", ")", ";", "ContentValues", "values", "=", "getConverter", "(", ")", ".", "entityToContentValues", "(", "item", ")", ";", "if", "(", "parent", "!=", "null", ")", "{", "values", ".", "put", "(", "resolveReverseJoinColumnName", "(", "item", ".", "getClass", "(", ")", ",", "parent", ".", "getClass", "(", ")", ")", ",", "ReflectionUtils", ".", "getIdFieldValue", "(", "parent", ")", ".", "toString", "(", ")", ")", ";", "}", "Long", "id", "=", "insertOrReplace", "(", "resolveTableName", "(", "item", ".", "getClass", "(", ")", ")", ",", "values", ")", ";", "if", "(", "id", ">", "-", "1", ")", "{", "ReflectionUtils", ".", "setFieldValue", "(", "ReflectionUtils", ".", "findIdField", "(", "item", ".", "getClass", "(", ")", ")", ",", "item", ",", "id", ")", ";", "cascadeStoreAfter", "(", "item", ")", ";", "}", "else", "{", "Log", ".", "v", "(", "getClass", "(", ")", ".", "getName", "(", ")", ",", "\"", "Failed to store item: ", "\"", "+", "item", "+", "\"", " to database!", "\"", ")", ";", "}", "}", "}", "/**\n * Store cascade before the actual item is being stored. This stores items that the item itself\n * should refer to when being stored.\n *\n * @param item T item that is being cascade stored.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "void", "cascadeStoreBefore", "(", "T", "item", ")", "{", "for", "(", "Field", "field", ":", "item", ".", "getClass", "(", ")", ".", "getDeclaredFields", "(", ")", ")", "{", "Object", "value", "=", "ReflectionUtils", ".", "getFieldValue", "(", "item", ",", "field", ")", ";", "/*\n * If field has foreign key relation it should be stored before the actual item is being\n * stored.\n */", "if", "(", "field", ".", "isAnnotationPresent", "(", "ManyToOne", ".", "class", ")", "||", "(", "field", ".", "isAnnotationPresent", "(", "OneToOne", ".", "class", ")", "&&", "StringUtils", ".", "isBlank", "(", "field", ".", "getAnnotation", "(", "OneToOne", ".", "class", ")", ".", "mappedBy", "(", ")", ")", ")", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "store", "(", "(", "Collection", "<", "T", ">", ")", "toCollection", "(", "value", ")", ",", "null", ")", ";", "}", "}", "}", "}", "/**\n * Store cascade after the item was stored to database. This stores items that are referenced\n * by the item itself.\n *\n * @param item T item that is being cascade stored.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "void", "cascadeStoreAfter", "(", "T", "item", ")", "{", "for", "(", "Field", "field", ":", "item", ".", "getClass", "(", ")", ".", "getDeclaredFields", "(", ")", ")", "{", "Object", "value", "=", "ReflectionUtils", ".", "getFieldValue", "(", "item", ",", "field", ")", ";", "/*\n * If field has primary key relation referenced item will be stored after the actual item\n * is being stored.\n */", "if", "(", "field", ".", "isAnnotationPresent", "(", "ManyToMany", ".", "class", ")", "||", "field", ".", "isAnnotationPresent", "(", "OneToMany", ".", "class", ")", "||", "(", "field", ".", "isAnnotationPresent", "(", "OneToOne", ".", "class", ")", "&&", "!", "StringUtils", ".", "isBlank", "(", "field", ".", "getAnnotation", "(", "OneToOne", ".", "class", ")", ".", "mappedBy", "(", ")", ")", ")", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "field", ".", "isAnnotationPresent", "(", "ManyToMany", ".", "class", ")", ")", "{", "store", "(", "(", "Collection", "<", "T", ">", ")", "toCollection", "(", "value", ")", ",", "null", ")", ";", "storeMiddleTable", "(", "item", ",", "(", "Collection", "<", "T", ">", ")", "value", ")", ";", "}", "else", "{", "store", "(", "(", "Collection", "<", "T", ">", ")", "toCollection", "(", "value", ")", ",", "item", ")", ";", "}", "}", "}", "}", "}", "/**\n * Store middle table joins for given item. This is special processing that is being\n * executed after both join parties are stored to database. First existing references is being\n * deleted and then newly coming references is being stored to database for the item.\n *\n * <p>References is being created for given item from given collection of items.</p>\n *\n * @param item T item from table item.\n * @param items {@link Collection} of to table items.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "void", "storeMiddleTable", "(", "final", "T", "item", ",", "Collection", "<", "T", ">", "items", ")", "{", "final", "Schema", "middleTable", "=", "findMiddleTable", "(", "item", ".", "getClass", "(", ")", ",", "items", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getClass", "(", ")", ")", ";", "/*\n * Delete existing references by id.\n */", "Query", "where", "=", "getProcessor", "(", ")", ".", "createWhere", "(", "null", ",", "new", "Filter", "(", ")", "{", "@", "Override", "public", "void", "filter", "(", "Root", "root", ",", "PredicateBuilder", "builder", ")", "{", "String", "middleTableJoinColumn", "=", "null", ";", "for", "(", "Reference", "reference", ":", "middleTable", ".", "getReferences", "(", ")", ")", "{", "if", "(", "reference", ".", "getReferenceTableName", "(", ")", ".", "equals", "(", "resolveTableName", "(", "item", ".", "getClass", "(", ")", ")", ")", ")", "{", "middleTableJoinColumn", "=", "reference", ".", "getColumnName", "(", ")", ";", "}", "}", "builder", ".", "eq", "(", "middleTableJoinColumn", ",", "ReflectionUtils", ".", "getIdFieldValue", "(", "item", ")", ")", ";", "}", "}", ")", ";", "getDb", "(", ")", ".", "delete", "(", "middleTable", ".", "getName", "(", ")", ",", "where", ".", "getSql", "(", ")", ",", "where", ".", "getArgs", "(", ")", ")", ";", "String", "fromTable", "=", "resolveTableName", "(", "item", ".", "getClass", "(", ")", ")", ";", "/*\n * Store middle table references.\n */", "for", "(", "T", "joinItem", ":", "items", ")", "{", "ContentValues", "values", "=", "new", "ContentValues", "(", ")", ";", "for", "(", "Reference", "reference", ":", "middleTable", ".", "getReferences", "(", ")", ")", "{", "Object", "value", ";", "/*\n * Determine which id is being used to to which reference. If reference table equals\n * from table get id of the from item otherwise use to id.\n */", "if", "(", "reference", ".", "getReferenceTableName", "(", ")", ".", "equals", "(", "fromTable", ")", ")", "{", "value", "=", "ReflectionUtils", ".", "getIdFieldValue", "(", "item", ")", ".", "toString", "(", ")", ";", "}", "else", "{", "value", "=", "ReflectionUtils", ".", "getIdFieldValue", "(", "joinItem", ")", ";", "}", "values", ".", "put", "(", "reference", ".", "getColumnName", "(", ")", ",", "value", ".", "toString", "(", ")", ")", ";", "}", "insertOrReplace", "(", "middleTable", ".", "getName", "(", ")", ",", "values", ")", ";", "}", "}", "/**\n * Find middle table by model class and reference model class.\n * @param model Entity class that join is made from.\n * @param joinModel Entity class that join is made to.\n *\n * @return Schema found middle table or null if not found.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "Schema", "findMiddleTable", "(", "Class", "<", "?", ">", "model", ",", "Class", "<", "?", ">", "joinModel", ")", "{", "String", "tableName", "=", "resolveTableName", "(", "model", ")", ";", "String", "joinTable", "=", "resolveTableName", "(", "joinModel", ")", ";", "Schema", "middleTable", ";", "if", "(", "(", "middleTable", "=", "getSchema", "(", ")", ".", "getElement", "(", "tableName", ".", "concat", "(", "\"", "_", "\"", ")", ".", "concat", "(", "joinTable", ")", ")", ")", "==", "null", ")", "{", "middleTable", "=", "getSchema", "(", ")", ".", "getElement", "(", "joinTable", ".", "concat", "(", "\"", "_", "\"", ")", ".", "concat", "(", "tableName", ")", ")", ";", "}", "return", "middleTable", ";", "}", "/**\n * Inserts or replaces given content values in given table. If SQL was executed successfully the\n * id of database row will be returned. If execution fails -1 will be returned.\n *\n * @param tableName String name of the table to store content values to.\n * @param values {@link ContentValues} that is being stored to given table.\n * @return Long id of stored row in database table or -1 if storing will fail.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "Long", "insertOrReplace", "(", "String", "tableName", ",", "ContentValues", "values", ")", "{", "return", "getDb", "(", ")", ".", "replace", "(", "tableName", ",", "null", ",", "values", ")", ";", "}", "/**\n * Maps given value to collection if value itself is not assignable from collection.\n * @param value Object value to map.\n * @return Collection containing given value or if value is collection then itself will be returned.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "static", "<", "T", ">", "Collection", "<", "T", ">", "toCollection", "(", "T", "value", ")", "{", "if", "(", "Collection", ".", "class", ".", "isAssignableFrom", "(", "value", ".", "getClass", "(", ")", ")", ")", "{", "return", "(", "Collection", "<", "T", ">", ")", "value", ";", "}", "else", "{", "return", "Arrays", ".", "asList", "(", "value", ")", ";", "}", "}", "/**\n * Resolves reverse join column name from given model class's table. Reverse join column name\n * is returned if reverse join table name is same as provided reverse join model.\n *\n * <p>Column is resolved by looking it for from {@link Schema} in order to maintain integrity.</p>\n *\n * @param model Instance of {@link Class} of model class of table where the join is made from.\n * @param reverseModel Instance of {@link Class} of reverse join model of table where the join is made to.\n * @return String reverse join column name from join table if found.\n *\n * @since 1.2.0\n *\n * @hide\n */", "private", "String", "resolveReverseJoinColumnName", "(", "Class", "<", "?", ">", "model", ",", "Class", "<", "?", ">", "reverseModel", ")", "{", "Schema", "table", "=", "getSchema", "(", ")", ".", "getElement", "(", "resolveTableName", "(", "model", ")", ")", ";", "if", "(", "table", "!=", "null", ")", "{", "String", "reverseJoinTableName", "=", "resolveTableName", "(", "reverseModel", ")", ";", "for", "(", "Reference", "reference", ":", "table", ".", "getReferences", "(", ")", ")", "{", "if", "(", "reference", ".", "getReferenceTableName", "(", ")", ".", "equals", "(", "reverseJoinTableName", ")", ")", "{", "return", "reference", ".", "getColumnName", "(", ")", ";", "}", "}", "}", "return", "null", ";", "}", "}" ]
Created by juha on 20/05/16.
[ "Created", "by", "juha", "on", "20", "/", "05", "/", "16", "." ]
[ "// transform collection of items to a list.", "// If parent is specified add parent id to content values as it references to child.", "// If storing was successful populate object with the database row id.", "// Some general logging if storing fails.", "// Check that there is actually something to store.", "// Check that there is actually something to store.", "// Update middle table reference for many to many relations.", "// Create content value for each join item as each item represents one row in database." ]
[ { "param": "TransactionTemplate", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TransactionTemplate", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b5947e09e180921c8454422d3d92c24e1e88ffc
iservport/helianto
helianto-document/src/main/java/org/helianto/document/test/DocumentTestSupport.java
[ "Apache-2.0" ]
Java
DocumentTestSupport
/** * Document test support. * * @author Mauricio Fernandes de Castro */
Document test support. @author Mauricio Fernandes de Castro
[ "Document", "test", "support", ".", "@author", "Mauricio", "Fernandes", "de", "Castro" ]
public class DocumentTestSupport { private static int testKey = 0; /** * Create sample. */ public static <T extends Document> T create(Class<T> clazz) { Entity entity = EntityTestSupport.createEntity(); return DocumentTestSupport.create(clazz, entity); } /** * Create sample. * * @param entity */ public static <T extends Document> T create(Class<T> clazz, Entity entity) { try { T sample = clazz.newInstance(); sample.setEntity(entity); sample.setDocCode(""+testKey++); return sample; } catch (Exception e) { throw new RuntimeException("Test sample not created."); } } }
[ "public", "class", "DocumentTestSupport", "{", "private", "static", "int", "testKey", "=", "0", ";", "/**\n\t * Create sample.\n\t */", "public", "static", "<", "T", "extends", "Document", ">", "T", "create", "(", "Class", "<", "T", ">", "clazz", ")", "{", "Entity", "entity", "=", "EntityTestSupport", ".", "createEntity", "(", ")", ";", "return", "DocumentTestSupport", ".", "create", "(", "clazz", ",", "entity", ")", ";", "}", "/**\n\t * Create sample.\n\t * \n\t * @param entity\n\t */", "public", "static", "<", "T", "extends", "Document", ">", "T", "create", "(", "Class", "<", "T", ">", "clazz", ",", "Entity", "entity", ")", "{", "try", "{", "T", "sample", "=", "clazz", ".", "newInstance", "(", ")", ";", "sample", ".", "setEntity", "(", "entity", ")", ";", "sample", ".", "setDocCode", "(", "\"", "\"", "+", "testKey", "++", ")", ";", "return", "sample", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Test sample not created.", "\"", ")", ";", "}", "}", "}" ]
Document test support.
[ "Document", "test", "support", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b5f2bb3c61bbc69f593217f0cdc328f5da2baf9
fernando-romulo-silva/myStudies
java/jee/1z0-900-JEE7-certification/src/main/java/br/com/fernando/myExamCloud/secureJavaEE7Applications/Question17.java
[ "Apache-2.0" ]
Java
FooServlet
// A is correct because of:
A is correct because of.
[ "A", "is", "correct", "because", "of", "." ]
@ServletSecurity(httpMethodConstraints = { // Two separate @HttpMethodConstraints @HttpMethodConstraint(value = "GET", rolesAllowed = { "MANAGER", "WORKER" }), // @HttpMethodConstraint(value = "POST", rolesAllowed = "SALES") // }) @WebServlet(name = "MyFooServlet", urlPatterns = { "/thatFoo" }) public class FooServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
[ "@", "ServletSecurity", "(", "httpMethodConstraints", "=", "{", "@", "HttpMethodConstraint", "(", "value", "=", "\"", "GET", "\"", ",", "rolesAllowed", "=", "{", "\"", "MANAGER", "\"", ",", "\"", "WORKER", "\"", "}", ")", ",", "@", "HttpMethodConstraint", "(", "value", "=", "\"", "POST", "\"", ",", "rolesAllowed", "=", "\"", "SALES", "\"", ")", "}", ")", "@", "WebServlet", "(", "name", "=", "\"", "MyFooServlet", "\"", ",", "urlPatterns", "=", "{", "\"", "/thatFoo", "\"", "}", ")", "public", "class", "FooServlet", "extends", "HttpServlet", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "Override", "protected", "void", "doGet", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "}", "@", "Override", "protected", "void", "doPost", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ")", "throws", "ServletException", ",", "IOException", "{", "}", "}" ]
A is correct because of:
[ "A", "is", "correct", "because", "of", ":" ]
[ "// Two separate @HttpMethodConstraints", "//", "//" ]
[ { "param": "HttpServlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpServlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b6144307eb58f6f2a5516736c19c35d1e2416ac
remi0s/TypeOfMood
app/java/src/typeofmood/ime/latin/LatinIME.java
[ "Apache-2.0" ]
Java
LatinIME
/** * Input method implementation for Qwerty'ish keyboard. */
Input method implementation for Qwerty'ish keyboard.
[ "Input", "method", "implementation", "for", "Qwerty", "'", "ish", "keyboard", "." ]
public class LatinIME extends InputMethodService implements KeyboardActionListener, SuggestionStripView.Listener, SuggestionStripViewAccessor, DictionaryFacilitator.DictionaryInitializationListener, PermissionsManager.PermissionsResultCallback { //azure info public static String storageContainer = ""; public static String storageConnectionString = ""; public static KeyboardDynamics sessionData=null; //remi0s private static NotificationHelper mNotificationHelper; private static NotificationCompat.Builder nb; // private static NotificationHelperPhysical mNotificationHelperPhysical ; public static String currentMood="undefined"; public static String currentPhysicalState="undefined"; public static long latestNotificationTime; public static Date latestNotificationTimeTemp; public static Date latestSendTimeTemp; public static Date StopDateTimeTemp; public static Boolean laterPressed=false; public static Boolean isLongPressedFlag=false; public static DatabaseHelper myDB; public static String userID; public static ArrayList<Double>rawX=new ArrayList<Double>(); public static ArrayList<Double>rawY=new ArrayList<Double>(); public static double densX; public static double densY; public static int user_sessions=1; public static long user_min_flight=3000; public static long user_max_flight=0; public static float user_mean_flight=0; public static long user_min_hold=3000; public static long user_max_hold=0; public static float user_mean_hold=0; public static int sessionsCounter=0; static final String TAG = LatinIME.class.getSimpleName(); private static final boolean TRACE = false; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; private static final int PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT = 2; private static final int PENDING_IMS_CALLBACK_DURATION_MILLIS = 800; static final long DELAY_WAIT_FOR_DICTIONARY_LOAD_MILLIS = TimeUnit.SECONDS.toMillis(2); static final long DELAY_DEALLOCATE_MEMORY_MILLIS = TimeUnit.SECONDS.toMillis(10); /** * The name of the scheme used by the Package Manager to warn of a new package installation, * replacement or removal. */ private static final String SCHEME_PACKAGE = "package"; final Settings mSettings; private final DictionaryFacilitator mDictionaryFacilitator = DictionaryFacilitatorProvider.getDictionaryFacilitator( false /* isNeededForSpellChecking */); final InputLogic mInputLogic = new InputLogic(this /* LatinIME */, this /* SuggestionStripViewAccessor */, mDictionaryFacilitator); // We expect to have only one decoder in almost all cases, hence the default capacity of 1. // If it turns out we need several, it will get grown seamlessly. final SparseArray<HardwareEventDecoder> mHardwareEventDecoders = new SparseArray<>(1); // TODO: Move these {@link View}s to {@link KeyboardSwitcher}. private View mInputView; private InsetsUpdater mInsetsUpdater; private SuggestionStripView mSuggestionStripView; private RichInputMethodManager mRichImm; @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher; private final SubtypeState mSubtypeState = new SubtypeState(); private EmojiAltPhysicalKeyDetector mEmojiAltPhysicalKeyDetector; private StatsUtilsManager mStatsUtilsManager; // Working variable for {@link #startShowingInputView()} and // {@link #onEvaluateInputViewShown()}. private boolean mIsExecutingStartShowingInputView; // Object for reacting to adding/removing a dictionary pack. private final BroadcastReceiver mDictionaryPackInstallReceiver = new DictionaryPackInstallBroadcastReceiver(this); private final BroadcastReceiver mDictionaryDumpBroadcastReceiver = new DictionaryDumpBroadcastReceiver(this); private AlertDialog mOptionsDialog; private final boolean mIsHardwareAcceleratedDrawingEnabled; private GestureConsumer mGestureConsumer = GestureConsumer.NULL_GESTURE_CONSUMER; public final UIHandler mHandler = new UIHandler(this); public static final class UIHandler extends LeakGuardHandlerWrapper<LatinIME> { private static final int MSG_UPDATE_SHIFT_STATE = 0; private static final int MSG_PENDING_IMS_CALLBACK = 1; private static final int MSG_UPDATE_SUGGESTION_STRIP = 2; private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3; private static final int MSG_RESUME_SUGGESTIONS = 4; private static final int MSG_REOPEN_DICTIONARIES = 5; private static final int MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED = 6; private static final int MSG_RESET_CACHES = 7; private static final int MSG_WAIT_FOR_DICTIONARY_LOAD = 8; private static final int MSG_DEALLOCATE_MEMORY = 9; private static final int MSG_RESUME_SUGGESTIONS_FOR_START_INPUT = 10; private static final int MSG_SWITCH_LANGUAGE_AUTOMATICALLY = 11; // Update this when adding new messages private static final int MSG_LAST = MSG_SWITCH_LANGUAGE_AUTOMATICALLY; private static final int ARG1_NOT_GESTURE_INPUT = 0; private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1; private static final int ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT = 2; private static final int ARG2_UNUSED = 0; private static final int ARG1_TRUE = 1; private int mDelayInMillisecondsToUpdateSuggestions; private int mDelayInMillisecondsToUpdateShiftState; public UIHandler(@Nonnull final LatinIME ownerInstance) { super(ownerInstance); } public void onCreate() { final LatinIME latinIme = getOwnerInstance(); if (latinIme == null) { return; } final Resources res = latinIme.getResources(); mDelayInMillisecondsToUpdateSuggestions = res.getInteger( R.integer.config_delay_in_milliseconds_to_update_suggestions); mDelayInMillisecondsToUpdateShiftState = res.getInteger( R.integer.config_delay_in_milliseconds_to_update_shift_state); } @Override public void handleMessage(final Message msg) { final LatinIME latinIme = getOwnerInstance(); if (latinIme == null) { return; } final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher; switch (msg.what) { case MSG_UPDATE_SUGGESTION_STRIP: cancelUpdateSuggestionStrip(); latinIme.mInputLogic.performUpdateSuggestionStripSync( latinIme.mSettings.getCurrent(), msg.arg1 /* inputStyle */); break; case MSG_UPDATE_SHIFT_STATE: switcher.requestUpdatingShiftState(latinIme.getCurrentAutoCapsState(), latinIme.getCurrentRecapitalizeState()); break; case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP: if (msg.arg1 == ARG1_NOT_GESTURE_INPUT) { final SuggestedWords suggestedWords = (SuggestedWords) msg.obj; latinIme.showSuggestionStrip(suggestedWords); } else { latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords) msg.obj, msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT); } break; case MSG_RESUME_SUGGESTIONS: latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor( latinIme.mSettings.getCurrent(), false /* forStartInput */, latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId()); break; case MSG_RESUME_SUGGESTIONS_FOR_START_INPUT: latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor( latinIme.mSettings.getCurrent(), true /* forStartInput */, latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId()); break; case MSG_REOPEN_DICTIONARIES: // We need to re-evaluate the currently composing word in case the script has // changed. postWaitForDictionaryLoad(); latinIme.resetDictionaryFacilitatorIfNecessary(); break; case MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED: final SuggestedWords suggestedWords = (SuggestedWords) msg.obj; latinIme.mInputLogic.onUpdateTailBatchInputCompleted( latinIme.mSettings.getCurrent(), suggestedWords, latinIme.mKeyboardSwitcher); latinIme.onTailBatchInputResultShown(suggestedWords); break; case MSG_RESET_CACHES: final SettingsValues settingsValues = latinIme.mSettings.getCurrent(); if (latinIme.mInputLogic.retryResetCachesAndReturnSuccess( msg.arg1 == ARG1_TRUE /* tryResumeSuggestions */, msg.arg2 /* remainingTries */, this /* handler */)) { // If we were able to reset the caches, then we can reload the keyboard. // Otherwise, we'll do it when we can. latinIme.mKeyboardSwitcher.loadKeyboard(latinIme.getCurrentInputEditorInfo(), settingsValues, latinIme.getCurrentAutoCapsState(), latinIme.getCurrentRecapitalizeState()); } break; case MSG_WAIT_FOR_DICTIONARY_LOAD: Log.i(TAG, "Timeout waiting for dictionary load"); break; case MSG_DEALLOCATE_MEMORY: latinIme.deallocateMemory(); break; case MSG_SWITCH_LANGUAGE_AUTOMATICALLY: latinIme.switchLanguage((InputMethodSubtype)msg.obj); break; } } public void postUpdateSuggestionStrip(final int inputStyle) { sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP, inputStyle, 0 /* ignored */), mDelayInMillisecondsToUpdateSuggestions); } public void postReopenDictionaries() { sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES)); } private void postResumeSuggestionsInternal(final boolean shouldDelay, final boolean forStartInput) { final LatinIME latinIme = getOwnerInstance(); if (latinIme == null) { return; } if (!latinIme.mSettings.getCurrent().isSuggestionsEnabledPerUserSettings()) { return; } removeMessages(MSG_RESUME_SUGGESTIONS); removeMessages(MSG_RESUME_SUGGESTIONS_FOR_START_INPUT); final int message = forStartInput ? MSG_RESUME_SUGGESTIONS_FOR_START_INPUT : MSG_RESUME_SUGGESTIONS; if (shouldDelay) { sendMessageDelayed(obtainMessage(message), mDelayInMillisecondsToUpdateSuggestions); } else { sendMessage(obtainMessage(message)); } } public void postResumeSuggestions(final boolean shouldDelay) { postResumeSuggestionsInternal(shouldDelay, false /* forStartInput */); } public void postResumeSuggestionsForStartInput(final boolean shouldDelay) { postResumeSuggestionsInternal(shouldDelay, true /* forStartInput */); } public void postResetCaches(final boolean tryResumeSuggestions, final int remainingTries) { removeMessages(MSG_RESET_CACHES); sendMessage(obtainMessage(MSG_RESET_CACHES, tryResumeSuggestions ? 1 : 0, remainingTries, null)); } public void postWaitForDictionaryLoad() { sendMessageDelayed(obtainMessage(MSG_WAIT_FOR_DICTIONARY_LOAD), DELAY_WAIT_FOR_DICTIONARY_LOAD_MILLIS); } public void cancelWaitForDictionaryLoad() { removeMessages(MSG_WAIT_FOR_DICTIONARY_LOAD); } public boolean hasPendingWaitForDictionaryLoad() { return hasMessages(MSG_WAIT_FOR_DICTIONARY_LOAD); } public void cancelUpdateSuggestionStrip() { removeMessages(MSG_UPDATE_SUGGESTION_STRIP); } public boolean hasPendingUpdateSuggestions() { return hasMessages(MSG_UPDATE_SUGGESTION_STRIP); } public boolean hasPendingReopenDictionaries() { return hasMessages(MSG_REOPEN_DICTIONARIES); } public void postUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayInMillisecondsToUpdateShiftState); } public void postDeallocateMemory() { sendMessageDelayed(obtainMessage(MSG_DEALLOCATE_MEMORY), DELAY_DEALLOCATE_MEMORY_MILLIS); } public void cancelDeallocateMemory() { removeMessages(MSG_DEALLOCATE_MEMORY); } public boolean hasPendingDeallocateMemory() { return hasMessages(MSG_DEALLOCATE_MEMORY); } @UsedForTesting public void removeAllMessages() { for (int i = 0; i <= MSG_LAST; ++i) { removeMessages(i); } } public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, final boolean dismissGestureFloatingPreviewText) { removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); final int arg1 = dismissGestureFloatingPreviewText ? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT : ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT; obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, ARG2_UNUSED, suggestedWords).sendToTarget(); } public void showSuggestionStrip(final SuggestedWords suggestedWords) { removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, ARG1_NOT_GESTURE_INPUT, ARG2_UNUSED, suggestedWords).sendToTarget(); } public void showTailBatchInputResult(final SuggestedWords suggestedWords) { obtainMessage(MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED, suggestedWords).sendToTarget(); } public void postSwitchLanguage(final InputMethodSubtype subtype) { obtainMessage(MSG_SWITCH_LANGUAGE_AUTOMATICALLY, subtype).sendToTarget(); } // Working variables for the following methods. private boolean mIsOrientationChanging; private boolean mPendingSuccessiveImsCallback; private boolean mHasPendingStartInput; private boolean mHasPendingFinishInputView; private boolean mHasPendingFinishInput; private EditorInfo mAppliedEditorInfo; public void startOrientationChanging() { removeMessages(MSG_PENDING_IMS_CALLBACK); resetPendingImsCallback(); mIsOrientationChanging = true; final LatinIME latinIme = getOwnerInstance(); if (latinIme == null) { return; } if (latinIme.isInputViewShown()) { latinIme.mKeyboardSwitcher.saveKeyboardState(); } } private void resetPendingImsCallback() { mHasPendingFinishInputView = false; mHasPendingFinishInput = false; mHasPendingStartInput = false; } private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo, boolean restarting) { if (mHasPendingFinishInputView) { latinIme.onFinishInputViewInternal(mHasPendingFinishInput); } if (mHasPendingFinishInput) { latinIme.onFinishInputInternal(); } if (mHasPendingStartInput) { latinIme.onStartInputInternal(editorInfo, restarting); } resetPendingImsCallback(); } public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the second onStartInput after orientation changed. mHasPendingStartInput = true; } else { if (mIsOrientationChanging && restarting) { // This is the first onStartInput after orientation changed. mIsOrientationChanging = false; mPendingSuccessiveImsCallback = true; } final LatinIME latinIme = getOwnerInstance(); if (latinIme != null) { executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputInternal(editorInfo, restarting); } } } public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK) && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) { // Typically this is the second onStartInputView after orientation changed. resetPendingImsCallback(); } else { if (mPendingSuccessiveImsCallback) { // This is the first onStartInputView after orientation changed. mPendingSuccessiveImsCallback = false; resetPendingImsCallback(); sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK), PENDING_IMS_CALLBACK_DURATION_MILLIS); } final LatinIME latinIme = getOwnerInstance(); if (latinIme != null) { executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputViewInternal(editorInfo, restarting); mAppliedEditorInfo = editorInfo; } cancelDeallocateMemory(); } } public void onFinishInputView(final boolean finishingInput) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInputView after orientation changed. mHasPendingFinishInputView = true; } else { final LatinIME latinIme = getOwnerInstance(); if (latinIme != null) { latinIme.onFinishInputViewInternal(finishingInput); mAppliedEditorInfo = null; } if (!hasPendingDeallocateMemory()) { postDeallocateMemory(); } } } public void onFinishInput() { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInput after orientation changed. mHasPendingFinishInput = true; } else { final LatinIME latinIme = getOwnerInstance(); if (latinIme != null) { executePendingImsCallback(latinIme, null, false); latinIme.onFinishInputInternal(); } } } } static final class SubtypeState { private InputMethodSubtype mLastActiveSubtype; private boolean mCurrentSubtypeHasBeenUsed; public void setCurrentSubtypeHasBeenUsed() { mCurrentSubtypeHasBeenUsed = true; } public void switchSubtype(final IBinder token, final RichInputMethodManager richImm) { final InputMethodSubtype currentSubtype = richImm.getInputMethodManager() .getCurrentInputMethodSubtype(); final InputMethodSubtype lastActiveSubtype = mLastActiveSubtype; final boolean currentSubtypeHasBeenUsed = mCurrentSubtypeHasBeenUsed; if (currentSubtypeHasBeenUsed) { mLastActiveSubtype = currentSubtype; mCurrentSubtypeHasBeenUsed = false; } if (currentSubtypeHasBeenUsed && richImm.checkIfSubtypeBelongsToThisImeAndEnabled(lastActiveSubtype) && !currentSubtype.equals(lastActiveSubtype)) { richImm.setInputMethodAndSubtype(token, lastActiveSubtype); return; } richImm.switchToNextInputMethod(token, true /* onlyCurrentIme */); } } // Loading the native library eagerly to avoid unexpected UnsatisfiedLinkError at the initial // JNI call as much as possible. static { JniUtils.loadNativeLibrary(); } public LatinIME() { super(); mSettings = Settings.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mStatsUtilsManager = StatsUtilsManager.getInstance(); mIsHardwareAcceleratedDrawingEnabled = InputMethodServiceCompatUtils.enableHardwareAcceleration(this); Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled); } @Override public void onCreate() { storageContainer=getConfigValue(this, "storageContainer"); storageConnectionString=getConfigValue(this, "storageConnectionString"); densX=getResources().getDisplayMetrics().xdpi; densY=getResources().getDisplayMetrics().ydpi; myDB = new DatabaseHelper(this); //remi0s mNotificationHelper=new NotificationHelper(this); nb=new NotificationCompat.Builder(getApplicationContext(),"TypeOfMoodChannelID"); userID=android.provider.Settings.System.getString(this.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);//remi0s Settings.init(this); DebugFlags.init(PreferenceManager.getDefaultSharedPreferences(this)); RichInputMethodManager.init(this); mRichImm = RichInputMethodManager.getInstance(); KeyboardSwitcher.init(this); AudioAndHapticFeedbackManager.init(this); AccessibilityUtils.init(this); mStatsUtilsManager.onCreate(this /* context */, mDictionaryFacilitator); super.onCreate(); mHandler.onCreate(); // TODO: Resolve mutual dependencies of {@link #loadSettings()} and // {@link #resetDictionaryFacilitatorIfNecessary()}. loadSettings(); resetDictionaryFacilitatorIfNecessary(); // Register to receive ringer mode change. final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mRingerModeChangeReceiver, filter); // Register to receive installation and removal of a dictionary pack. final IntentFilter packageFilter = new IntentFilter(); packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); packageFilter.addDataScheme(SCHEME_PACKAGE); registerReceiver(mDictionaryPackInstallReceiver, packageFilter); final IntentFilter newDictFilter = new IntentFilter(); newDictFilter.addAction(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION); registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); final IntentFilter dictDumpFilter = new IntentFilter(); dictDumpFilter.addAction(DictionaryDumpBroadcastReceiver.DICTIONARY_DUMP_INTENT_ACTION); registerReceiver(mDictionaryDumpBroadcastReceiver, dictDumpFilter); StatsUtils.onCreate(mSettings.getCurrent(), mRichImm); } // Has to be package-visible for unit tests @UsedForTesting void loadSettings() { final Locale locale = mRichImm.getCurrentSubtypeLocale(); final EditorInfo editorInfo = getCurrentInputEditorInfo(); final InputAttributes inputAttributes = new InputAttributes( editorInfo, isFullscreenMode(), getPackageName()); mSettings.loadSettings(this, locale, inputAttributes); final SettingsValues currentSettingsValues = mSettings.getCurrent(); AudioAndHapticFeedbackManager.getInstance().onSettingsChanged(currentSettingsValues); // This method is called on startup and language switch, before the new layout has // been displayed. Opening dictionaries never affects responsivity as dictionaries are // asynchronously loaded. if (!mHandler.hasPendingReopenDictionaries()) { resetDictionaryFacilitator(locale); } refreshPersonalizationDictionarySession(currentSettingsValues); resetDictionaryFacilitatorIfNecessary(); mStatsUtilsManager.onLoadSettings(this /* context */, currentSettingsValues); } private void refreshPersonalizationDictionarySession( final SettingsValues currentSettingsValues) { if (!currentSettingsValues.mUsePersonalizedDicts) { // Remove user history dictionaries. PersonalizationHelper.removeAllUserHistoryDictionaries(this); mDictionaryFacilitator.clearUserHistoryDictionary(this); } } // Note that this method is called from a non-UI thread. @Override public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) { final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable); } if (mHandler.hasPendingWaitForDictionaryLoad()) { mHandler.cancelWaitForDictionaryLoad(); mHandler.postResumeSuggestions(false /* shouldDelay */); } } void resetDictionaryFacilitatorIfNecessary() { final Locale subtypeSwitcherLocale = mRichImm.getCurrentSubtypeLocale(); final Locale subtypeLocale; if (subtypeSwitcherLocale == null) { // This happens in very rare corner cases - for example, immediately after a switch // to LatinIME has been requested, about a frame later another switch happens. In this // case, we are about to go down but we still don't know it, however the system tells // us there is no current subtype. Log.e(TAG, "System is reporting no current subtype."); subtypeLocale = getResources().getConfiguration().locale; } else { subtypeLocale = subtypeSwitcherLocale; } if (mDictionaryFacilitator.isForLocale(subtypeLocale) && mDictionaryFacilitator.isForAccount(mSettings.getCurrent().mAccount)) { return; } resetDictionaryFacilitator(subtypeLocale); } /** * Reset the facilitator by loading dictionaries for the given locale and * the current settings values. * * @param locale the locale */ // TODO: make sure the current settings always have the right locales, and read from them. private void resetDictionaryFacilitator(final Locale locale) { final SettingsValues settingsValues = mSettings.getCurrent(); mDictionaryFacilitator.resetDictionaries(this /* context */, locale, settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, false /* forceReloadMainDictionary */, settingsValues.mAccount, "" /* dictNamePrefix */, this /* DictionaryInitializationListener */); if (settingsValues.mAutoCorrectionEnabledPerUserSettings) { mInputLogic.mSuggest.setAutoCorrectionThreshold( settingsValues.mAutoCorrectionThreshold); } mInputLogic.mSuggest.setPlausibilityThreshold(settingsValues.mPlausibilityThreshold); } /** * Reset suggest by loading the main dictionary of the current locale. */ /* package private */ void resetSuggestMainDict() { final SettingsValues settingsValues = mSettings.getCurrent(); mDictionaryFacilitator.resetDictionaries(this /* context */, mDictionaryFacilitator.getLocale(), settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, true /* forceReloadMainDictionary */, settingsValues.mAccount, "" /* dictNamePrefix */, this /* DictionaryInitializationListener */); } @Override public void onDestroy() { mDictionaryFacilitator.closeDictionaries(); mSettings.onDestroy(); unregisterReceiver(mRingerModeChangeReceiver); unregisterReceiver(mDictionaryPackInstallReceiver); unregisterReceiver(mDictionaryDumpBroadcastReceiver); mStatsUtilsManager.onDestroy(this /* context */); if(myDB!=null){ myDB.close(); } super.onDestroy(); } @UsedForTesting public void recycle() { unregisterReceiver(mDictionaryPackInstallReceiver); unregisterReceiver(mDictionaryDumpBroadcastReceiver); unregisterReceiver(mRingerModeChangeReceiver); mInputLogic.recycle(); } private boolean isImeSuppressedByHardwareKeyboard() { final KeyboardSwitcher switcher = KeyboardSwitcher.getInstance(); return !onEvaluateInputViewShown() && switcher.isImeSuppressedByHardwareKeyboard( mSettings.getCurrent(), switcher.getKeyboardSwitchState()); } @Override public void onConfigurationChanged(final Configuration conf) { SettingsValues settingsValues = mSettings.getCurrent(); if (settingsValues.mDisplayOrientation != conf.orientation) { mHandler.startOrientationChanging(); mInputLogic.onOrientationChange(mSettings.getCurrent()); } if (settingsValues.mHasHardwareKeyboard != Settings.readHasHardwareKeyboard(conf)) { // If the state of having a hardware keyboard changed, then we want to reload the // settings to adjust for that. // TODO: we should probably do this unconditionally here, rather than only when we // have a change in hardware keyboard configuration. loadSettings(); settingsValues = mSettings.getCurrent(); if (isImeSuppressedByHardwareKeyboard()) { // We call cleanupInternalStateForFinishInput() because it's the right thing to do; // however, it seems at the moment the framework is passing us a seemingly valid // but actually non-functional InputConnection object. So if this bug ever gets // fixed we'll be able to remove the composition, but until it is this code is // actually not doing much. cleanupInternalStateForFinishInput(); } } super.onConfigurationChanged(conf); } @Override public View onCreateInputView() { StatsUtils.onCreateInputView(); return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled); } @Override public void setInputView(final View view) { super.setInputView(view); mInputView = view; mInsetsUpdater = ViewOutlineProviderCompatUtils.setInsetsOutlineProvider(view); updateSoftInputWindowLayoutParameters(); mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view); if (hasSuggestionStripView()) { mSuggestionStripView.setListener(this, view); } } @Override public void setCandidatesView(final View view) { // To ensure that CandidatesView will never be set. } @Override public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { mHandler.onStartInput(editorInfo, restarting); } @Override public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { mHandler.onStartInputView(editorInfo, restarting); mStatsUtilsManager.onStartInputView(); } @Override public void onFinishInputView(final boolean finishingInput) { if (sessionData != null) { sessionData.StopDateTime = System.currentTimeMillis(); // } //store data DataStoreAsyncTaskParams params = new DataStoreAsyncTaskParams(sessionData,rawX,rawY); DataStoreAsyncTask task = new DataStoreAsyncTask(getApplicationContext()); task.execute(params); rawX.clear(); rawY.clear(); sessionData= null; } StatsUtils.onFinishInputView(); mHandler.onFinishInputView(finishingInput); mStatsUtilsManager.onFinishInputView(); mGestureConsumer = GestureConsumer.NULL_GESTURE_CONSUMER; } @Override public void onFinishInput() { mHandler.onFinishInput(); } @Override public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) { // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() // is not guaranteed. It may even be called at the same time on a different thread. InputMethodSubtype oldSubtype = mRichImm.getCurrentSubtype().getRawSubtype(); StatsUtils.onSubtypeChanged(oldSubtype, subtype); mRichImm.onSubtypeChanged(subtype); mInputLogic.onSubtypeChanged(SubtypeLocaleUtils.getCombiningRulesExtraValue(subtype), mSettings.getCurrent()); loadKeyboard(); } void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInput(editorInfo, restarting); // If the primary hint language does not match the current subtype language, then try // to switch to the primary hint language. // TODO: Support all the locales in EditorInfo#hintLocales. final Locale primaryHintLocale = EditorInfoCompatUtils.getPrimaryHintLocale(editorInfo); if (primaryHintLocale == null) { return; } final InputMethodSubtype newSubtype = mRichImm.findSubtypeByLocale(primaryHintLocale); if (newSubtype == null || newSubtype.equals(mRichImm.getCurrentSubtype().getRawSubtype())) { return; } mHandler.postSwitchLanguage(newSubtype); } @SuppressWarnings("deprecation") void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInputView(editorInfo, restarting); mDictionaryFacilitator.onStartInput(); // Switch to the null consumer to handle cases leading to early exit below, for which we // also wouldn't be consuming gesture data. mGestureConsumer = GestureConsumer.NULL_GESTURE_CONSUMER; mRichImm.refreshSubtypeCaches(); final KeyboardSwitcher switcher = mKeyboardSwitcher; switcher.updateKeyboardTheme(); final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); // If we are starting input in a different text field from before, we'll have to reload // settings, so currentSettingsValues can't be final. SettingsValues currentSettingsValues = mSettings.getCurrent(); if (editorInfo == null) { Log.e(TAG, "Null EditorInfo in onStartInputView()"); if (DebugFlags.DEBUG_ENABLED) { throw new NullPointerException("Null EditorInfo in onStartInputView()"); } return; } if (DebugFlags.DEBUG_ENABLED) { Log.d(TAG, "onStartInputView: editorInfo:" + String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions)); Log.d(TAG, "All caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) + ", sentence caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) + ", word caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); } Log.i(TAG, "Starting input. Cursor position = " + editorInfo.initialSelStart + "," + editorInfo.initialSelEnd); // TODO: Consolidate these checks with {@link InputAttributes}. if (InputAttributes.inPrivateImeOptions(null, Constants.ImeOption.NO_MICROPHONE_COMPAT, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use " + getPackageName() + "." + Constants.ImeOption.NO_MICROPHONE + " instead"); } if (InputAttributes.inPrivateImeOptions(getPackageName(), Constants.ImeOption.FORCE_ASCII, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); } // In landscape mode, this method gets called without the input view being created. if (mainKeyboardView == null) { return; } // Update to a gesture consumer with the current editor and IME state. mGestureConsumer = GestureConsumer.newInstance(editorInfo, mInputLogic.getPrivateCommandPerformer(), mRichImm.getCurrentSubtypeLocale(), switcher.getKeyboard()); // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); } final boolean inputTypeChanged = !currentSettingsValues.isSameInputType(editorInfo); final boolean isDifferentTextField = !restarting || inputTypeChanged; StatsUtils.onStartInputView(editorInfo.inputType, Settings.getInstance().getCurrent().mDisplayOrientation, !isDifferentTextField); // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); // ALERT: settings have not been reloaded and there is a chance they may be stale. // In the practice, if it is, we should have gotten onConfigurationChanged so it should // be fine, but this is horribly confusing and must be fixed AS SOON AS POSSIBLE. // In some cases the input connection has not been reset yet and we can't access it. In // this case we will need to call loadKeyboard() later, when it's accessible, so that we // can go into the correct mode, so we need to do some housekeeping here. final boolean needToCallLoadKeyboardLater; final Suggest suggest = mInputLogic.mSuggest; if (!isImeSuppressedByHardwareKeyboard()) { // The app calling setText() has the effect of clearing the composing // span, so we should reset our state unconditionally, even if restarting is true. // We also tell the input logic about the combining rules for the current subtype, so // it can adjust its combiners if needed. mInputLogic.startInput(mRichImm.getCombiningRulesExtraValueOfCurrentSubtype(), currentSettingsValues); resetDictionaryFacilitatorIfNecessary(); // TODO[IL]: Can the following be moved to InputLogic#startInput? if (!mInputLogic.mConnection.resetCachesUponCursorMoveAndReturnSuccess( editorInfo.initialSelStart, editorInfo.initialSelEnd, false /* shouldFinishComposition */)) { // Sometimes, while rotating, for some reason the framework tells the app we are not // connected to it and that means we can't refresh the cache. In this case, schedule // a refresh later. // We try resetting the caches up to 5 times before giving up. mHandler.postResetCaches(isDifferentTextField, 5 /* remainingTries */); // mLastSelection{Start,End} are reset later in this method, no need to do it here needToCallLoadKeyboardLater = true; } else { // When rotating, and when input is starting again in a field from where the focus // didn't move (the keyboard having been closed with the back key), // initialSelStart and initialSelEnd sometimes are lying. Make a best effort to // work around this bug. mInputLogic.mConnection.tryFixLyingCursorPosition(); mHandler.postResumeSuggestionsForStartInput(true /* shouldDelay */); needToCallLoadKeyboardLater = false; } } else { // If we have a hardware keyboard we don't need to call loadKeyboard later anyway. needToCallLoadKeyboardLater = false; } if (isDifferentTextField || !currentSettingsValues.hasSameOrientation(getResources().getConfiguration())) { loadSettings(); } if (isDifferentTextField) { mainKeyboardView.closing(); currentSettingsValues = mSettings.getCurrent(); if (currentSettingsValues.mAutoCorrectionEnabledPerUserSettings) { suggest.setAutoCorrectionThreshold( currentSettingsValues.mAutoCorrectionThreshold); } suggest.setPlausibilityThreshold(currentSettingsValues.mPlausibilityThreshold); switcher.loadKeyboard(editorInfo, currentSettingsValues, getCurrentAutoCapsState(), getCurrentRecapitalizeState()); if (needToCallLoadKeyboardLater) { // If we need to call loadKeyboard again later, we need to save its state now. The // later call will be done in #retryResetCaches. switcher.saveKeyboardState(); } } else if (restarting) { // TODO: Come up with a more comprehensive way to reset the keyboard layout when // a keyboard layout set doesn't get reloaded in this method. switcher.resetKeyboardStateToAlphabet(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); // In apps like Talk, we come here when the text is sent and the field gets emptied and // we need to re-evaluate the shift state, but not the whole layout which would be // disruptive. // Space state must be updated before calling updateShiftState switcher.requestUpdatingShiftState(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } // This will set the punctuation suggestions if next word suggestion is off; // otherwise it will clear the suggestion strip. setNeutralSuggestionStrip(); mHandler.cancelUpdateSuggestionStrip(); mainKeyboardView.setMainDictionaryAvailability( mDictionaryFacilitator.hasAtLeastOneInitializedMainDictionary()); mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn, currentSettingsValues.mKeyPreviewPopupDismissDelay); mainKeyboardView.setSlidingKeyInputPreviewEnabled( currentSettingsValues.mSlidingKeyInputPreviewEnabled); mainKeyboardView.setGestureHandlingEnabledByUser( currentSettingsValues.mGestureInputEnabled, currentSettingsValues.mGestureTrailEnabled, currentSettingsValues.mGestureFloatingPreviewTextEnabled); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); } @Override public void onWindowShown() { super.onWindowShown(); setNavigationBarVisibility(isInputViewShown()); } @Override public void onWindowHidden() { super.onWindowHidden(); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.closing(); } setNavigationBarVisibility(false); } void onFinishInputInternal() { super.onFinishInput(); mDictionaryFacilitator.onFinishInput(this); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.closing(); } } void onFinishInputViewInternal(final boolean finishingInput) { super.onFinishInputView(finishingInput); cleanupInternalStateForFinishInput(); } private void cleanupInternalStateForFinishInput() { // Remove pending messages related to update suggestions mHandler.cancelUpdateSuggestionStrip(); // Should do the following in onFinishInputInternal but until JB MR2 it's not called :( mInputLogic.finishInput(); } protected void deallocateMemory() { mKeyboardSwitcher.deallocateMemory(); } @Override public void onUpdateSelection(final int oldSelStart, final int oldSelEnd, final int newSelStart, final int newSelEnd, final int composingSpanStart, final int composingSpanEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart, composingSpanEnd); if (DebugFlags.DEBUG_ENABLED) { Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd + ", cs=" + composingSpanStart + ", ce=" + composingSpanEnd); } // This call happens whether our view is displayed or not, but if it's not then we should // not attempt recorrection. This is true even with a hardware keyboard connected: if the // view is not displayed we have no means of showing suggestions anyway, and if it is then // we want to show suggestions anyway. final SettingsValues settingsValues = mSettings.getCurrent(); if (isInputViewShown() && mInputLogic.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, settingsValues)) { mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } } /** * This is called when the user has clicked on the extracted text view, * when running in fullscreen mode. The default implementation hides * the suggestions view when this happens, but only if the extracted text * editor has a vertical scroll bar because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedTextClicked() { if (mSettings.getCurrent().needsToLookupSuggestions()) { return; } super.onExtractedTextClicked(); } /** * This is called when the user has performed a cursor movement in the * extracted text view, when it is running in fullscreen mode. The default * implementation hides the suggestions view when a vertical movement * happens, but only if the extracted text editor has a vertical scroll bar * because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedCursorMovement(final int dx, final int dy) { if (mSettings.getCurrent().needsToLookupSuggestions()) { return; } super.onExtractedCursorMovement(dx, dy); } @Override public void hideWindow() { mKeyboardSwitcher.onHideWindow(); if (TRACE) Debug.stopMethodTracing(); if (isShowingOptionDialog()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } super.hideWindow(); } @Override public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) { if (DebugFlags.DEBUG_ENABLED) { Log.i(TAG, "Received completions:"); if (applicationSpecifiedCompletions != null) { for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); } } } if (!mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) { return; } // If we have an update request in flight, we need to cancel it so it does not override // these completions. mHandler.cancelUpdateSuggestionStrip(); if (applicationSpecifiedCompletions == null) { setNeutralSuggestionStrip(); return; } final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords = SuggestedWords.getFromApplicationSpecifiedCompletions( applicationSpecifiedCompletions); final SuggestedWords suggestedWords = new SuggestedWords(applicationSuggestedWords, null /* rawSuggestions */, null /* typedWord */, false /* typedWordValid */, false /* willAutoCorrect */, false /* isObsoleteSuggestions */, SuggestedWords.INPUT_STYLE_APPLICATION_SPECIFIED /* inputStyle */, SuggestedWords.NOT_A_SEQUENCE_NUMBER); // When in fullscreen mode, show completions generated by the application forcibly setSuggestedWords(suggestedWords); } @Override public void onComputeInsets(final InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); // This method may be called before {@link #setInputView(View)}. if (mInputView == null) { return; } final SettingsValues settingsValues = mSettings.getCurrent(); final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView(); if (visibleKeyboardView == null || !hasSuggestionStripView()) { return; } final int inputHeight = mInputView.getHeight(); if (isImeSuppressedByHardwareKeyboard() && !visibleKeyboardView.isShown()) { // If there is a hardware keyboard and a visible software keyboard view has been hidden, // no visual element will be shown on the screen. outInsets.contentTopInsets = inputHeight; outInsets.visibleTopInsets = inputHeight; mInsetsUpdater.setInsets(outInsets); return; } final int suggestionsHeight = (!mKeyboardSwitcher.isShowingEmojiPalettes() && mSuggestionStripView.getVisibility() == View.VISIBLE) ? mSuggestionStripView.getHeight() : 0; final int visibleTopY = inputHeight - visibleKeyboardView.getHeight() - suggestionsHeight; mSuggestionStripView.setMoreSuggestionsHeight(visibleTopY); // Need to set expanded touchable region only if a keyboard view is being shown. if (visibleKeyboardView.isShown()) { final int touchLeft = 0; final int touchTop = mKeyboardSwitcher.isShowingMoreKeysPanel() ? 0 : visibleTopY; final int touchRight = visibleKeyboardView.getWidth(); final int touchBottom = inputHeight // Extend touchable region below the keyboard. + EXTENDED_TOUCHABLE_REGION_HEIGHT; outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; outInsets.touchableRegion.set(touchLeft, touchTop, touchRight, touchBottom); } outInsets.contentTopInsets = visibleTopY; outInsets.visibleTopInsets = visibleTopY; mInsetsUpdater.setInsets(outInsets); } public void startShowingInputView(final boolean needsToLoadKeyboard) { mIsExecutingStartShowingInputView = true; // This {@link #showWindow(boolean)} will eventually call back // {@link #onEvaluateInputViewShown()}. showWindow(true /* showInput */); mIsExecutingStartShowingInputView = false; if (needsToLoadKeyboard) { loadKeyboard(); } } public void stopShowingInputView() { showWindow(false /* showInput */); } @Override public boolean onShowInputRequested(final int flags, final boolean configChange) { //Collect Data remi0s if (sessionData == null && userHaveAgreed()) { sessionData = new KeyboardDynamics(); final SettingsValues settingsValues = mSettings.getCurrent(); final String packageName = getCurrentInputEditorInfo().packageName; String appName; PackageManager packageManager= getApplicationContext().getPackageManager(); try { appName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)); }catch (Exception e){ appName="undefined"; } sessionData.StartDateTime = System.currentTimeMillis(); sessionData.CurrentAppName=appName; sessionData.IsSoundOn=settingsValues.mSoundOn; sessionData.IsVibrationOn=settingsValues.mVibrateOn; sessionData.IsShowPopupOn=settingsValues.mKeyPreviewPopupOn; //notification onShowNotificationAsync task = new onShowNotificationAsync(getApplicationContext()); task.execute(); } if (isImeSuppressedByHardwareKeyboard()) { return true; } return super.onShowInputRequested(flags, configChange); } @Override public boolean onEvaluateInputViewShown() { if (mIsExecutingStartShowingInputView) { return true; } return super.onEvaluateInputViewShown(); } @Override public boolean onEvaluateFullscreenMode() { final SettingsValues settingsValues = mSettings.getCurrent(); if (isImeSuppressedByHardwareKeyboard()) { // If there is a hardware keyboard, disable full screen mode. return false; } // Reread resource value here, because this method is called by the framework as needed. final boolean isFullscreenModeAllowed = Settings.readUseFullscreenMode(getResources()); if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) { // TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI // implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI // without NO_FULLSCREEN doesn't work as expected. Because of this we need this // hack for now. Let's get rid of this once the framework gets fixed. final EditorInfo ei = getCurrentInputEditorInfo(); return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0)); } return false; } @Override public void updateFullscreenMode() { super.updateFullscreenMode(); updateSoftInputWindowLayoutParameters(); } private void updateSoftInputWindowLayoutParameters() { // Override layout parameters to expand {@link SoftInputWindow} to the entire screen. // See {@link InputMethodService#setinputView(View)} and // {@link SoftInputWindow#updateWidthHeight(WindowManager.LayoutParams)}. final Window window = getWindow().getWindow(); ViewLayoutUtils.updateLayoutHeightOf(window, LayoutParams.MATCH_PARENT); // This method may be called before {@link #setInputView(View)}. if (mInputView != null) { // In non-fullscreen mode, {@link InputView} and its parent inputArea should expand to // the entire screen and be placed at the bottom of {@link SoftInputWindow}. // In fullscreen mode, these shouldn't expand to the entire screen and should be // coexistent with {@link #mExtractedArea} above. // See {@link InputMethodService#setInputView(View) and // com.ime.internal.R.layout.input_method.xml. final int layoutHeight = isFullscreenMode() ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT; final View inputArea = window.findViewById(android.R.id.inputArea); ViewLayoutUtils.updateLayoutHeightOf(inputArea, layoutHeight); ViewLayoutUtils.updateLayoutGravityOf(inputArea, Gravity.BOTTOM); ViewLayoutUtils.updateLayoutHeightOf(mInputView, layoutHeight); } } int getCurrentAutoCapsState() { return mInputLogic.getCurrentAutoCapsState(mSettings.getCurrent()); } int getCurrentRecapitalizeState() { return mInputLogic.getCurrentRecapitalizeState(); } /** * @param codePoints code points to get coordinates for. * @return x,y coordinates for this keyboard, as a flattened array. */ public int[] getCoordinatesForCurrentKeyboard(final int[] codePoints) { final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); if (null == keyboard) { return CoordinateUtils.newCoordinateArray(codePoints.length, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); } return keyboard.getCoordinates(codePoints); } // Callback for the {@link SuggestionStripView}, to call when the important notice strip is // pressed. @Override public void showImportantNoticeContents() { PermissionsManager.get(this).requestPermissions( this /* PermissionsResultCallback */, null /* activity */, permission.READ_CONTACTS); } @Override public void onRequestPermissionsResult(boolean allGranted) { ImportantNoticeUtils.updateContactsNoticeShown(this /* context */); setNeutralSuggestionStrip(); } public void displaySettingsDialog() { if (isShowingOptionDialog()) { return; } showSubtypeSelectorAndSettings(); } @Override public boolean onCustomRequest(final int requestCode) { if (isShowingOptionDialog()) return false; switch (requestCode) { case Constants.CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER: if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(false /* include aux subtypes */)) { mRichImm.getInputMethodManager().showInputMethodPicker(); return true; } return false; } return false; } private boolean isShowingOptionDialog() { return mOptionsDialog != null && mOptionsDialog.isShowing(); } public void switchLanguage(final InputMethodSubtype subtype) { final IBinder token = getWindow().getWindow().getAttributes().token; mRichImm.setInputMethodAndSubtype(token, subtype); } // TODO: Revise the language switch key behavior to make it much smarter and more reasonable. public void switchToNextSubtype() { final IBinder token = getWindow().getWindow().getAttributes().token; if (shouldSwitchToOtherInputMethods()) { mRichImm.switchToNextInputMethod(token, true /* onlyCurrentIme */); //remi0s return; } mSubtypeState.switchSubtype(token, mRichImm); } // TODO: Instead of checking for alphabetic keyboard here, separate keycodes for // alphabetic shift and shift while in symbol layout and get rid of this method. private int getCodePointForKeyboard(final int codePoint) { if (Constants.CODE_SHIFT == codePoint) { final Keyboard currentKeyboard = mKeyboardSwitcher.getKeyboard(); if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) { return codePoint; } return Constants.CODE_SYMBOL_SHIFT; } return codePoint; } // Implementation of {@link KeyboardActionListener}. @Override public void onCodeInput(final int codePoint, final int x, final int y, final boolean isKeyRepeat) { // TODO: this processing does not belong inside LatinIME, the caller should be doing this. final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); // x and y include some padding, but everything down the line (especially native // code) needs the coordinates in the keyboard frame. // TODO: We should reconsider which coordinate system should be used to represent // keyboard event. Also we should pull this up -- LatinIME has no business doing // this transformation, it should be done already before calling onEvent. final int keyX = mainKeyboardView.getKeyX(x); final int keyY = mainKeyboardView.getKeyY(y); final Event event = createSoftwareKeypressEvent(getCodePointForKeyboard(codePoint), keyX, keyY, isKeyRepeat); onEvent(event); } // This method is public for testability of LatinIME, but also in the future it should // completely replace #onCodeInput. public void onEvent(@Nonnull final Event event) { if (Constants.CODE_SHORTCUT == event.mKeyCode) { mRichImm.switchToShortcutIme(this); } final InputTransaction completeInputTransaction = mInputLogic.onCodeInput(mSettings.getCurrent(), event, mKeyboardSwitcher.getKeyboardShiftMode(), mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler); updateStateAfterInputTransaction(completeInputTransaction); mKeyboardSwitcher.onEvent(event, getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } // A helper method to split the code point and the key code. Ultimately, they should not be // squashed into the same variable, and this method should be removed. // public for testing, as we don't want to copy the same logic into test code @Nonnull public static Event createSoftwareKeypressEvent(final int keyCodeOrCodePoint, final int keyX, final int keyY, final boolean isKeyRepeat) { final int keyCode; final int codePoint; if (keyCodeOrCodePoint <= 0) { keyCode = keyCodeOrCodePoint; codePoint = Event.NOT_A_CODE_POINT; } else { keyCode = Event.NOT_A_KEY_CODE; codePoint = keyCodeOrCodePoint; } return Event.createSoftwareKeypressEvent(codePoint, keyCode, keyX, keyY, isKeyRepeat); } // Called from PointerTracker through the KeyboardActionListener interface @Override public void onTextInput(final String rawText) { // TODO: have the keyboard pass the correct key code when we need it. final Event event = Event.createSoftwareTextEvent(rawText, Constants.CODE_OUTPUT_TEXT); final InputTransaction completeInputTransaction = mInputLogic.onTextInput(mSettings.getCurrent(), event, mKeyboardSwitcher.getKeyboardShiftMode(), mHandler); updateStateAfterInputTransaction(completeInputTransaction); mKeyboardSwitcher.onEvent(event, getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } @Override public void onStartBatchInput() { mInputLogic.onStartBatchInput(mSettings.getCurrent(), mKeyboardSwitcher, mHandler); mGestureConsumer.onGestureStarted( mRichImm.getCurrentSubtypeLocale(), mKeyboardSwitcher.getKeyboard()); } @Override public void onUpdateBatchInput(final InputPointers batchPointers) { mInputLogic.onUpdateBatchInput(batchPointers); } @Override public void onEndBatchInput(final InputPointers batchPointers) { mInputLogic.onEndBatchInput(batchPointers); mGestureConsumer.onGestureCompleted(batchPointers); } @Override public void onCancelBatchInput() { mInputLogic.onCancelBatchInput(mHandler); mGestureConsumer.onGestureCanceled(); } /** * To be called after the InputLogic has gotten a chance to act on the suggested words by the * IME for the full gesture, possibly updating the TextView to reflect the first suggestion. * <p> * This method must be run on the UI Thread. * @param suggestedWords suggested words by the IME for the full gesture. */ public void onTailBatchInputResultShown(final SuggestedWords suggestedWords) { mGestureConsumer.onImeSuggestionsProcessed(suggestedWords, mInputLogic.getComposingStart(), mInputLogic.getComposingLength(), mDictionaryFacilitator); } // This method must run on the UI Thread. void showGesturePreviewAndSuggestionStrip(@Nonnull final SuggestedWords suggestedWords, final boolean dismissGestureFloatingPreviewText) { showSuggestionStrip(suggestedWords); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); mainKeyboardView.showGestureFloatingPreviewText(suggestedWords, dismissGestureFloatingPreviewText /* dismissDelayed */); } // Called from PointerTracker through the KeyboardActionListener interface @Override public void onFinishSlidingInput() { // User finished sliding input. mKeyboardSwitcher.onFinishSlidingInput(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } // Called from PointerTracker through the KeyboardActionListener interface @Override public void onCancelInput() { // User released a finger outside any key // Nothing to do so far. } public boolean hasSuggestionStripView() { return null != mSuggestionStripView; } private void setSuggestedWords(final SuggestedWords suggestedWords) { final SettingsValues currentSettingsValues = mSettings.getCurrent(); mInputLogic.setSuggestedWords(suggestedWords); // TODO: Modify this when we support suggestions with hard keyboard if (!hasSuggestionStripView()) { return; } if (!onEvaluateInputViewShown()) { return; } final boolean shouldShowImportantNotice = ImportantNoticeUtils.shouldShowImportantNotice(this, currentSettingsValues); final boolean shouldShowSuggestionCandidates = currentSettingsValues.mInputAttributes.mShouldShowSuggestions && currentSettingsValues.isSuggestionsEnabledPerUserSettings(); final boolean shouldShowSuggestionsStripUnlessPassword = shouldShowImportantNotice || currentSettingsValues.mShowsVoiceInputKey || shouldShowSuggestionCandidates || currentSettingsValues.isApplicationSpecifiedCompletionsOn(); final boolean shouldShowSuggestionsStrip = shouldShowSuggestionsStripUnlessPassword && !currentSettingsValues.mInputAttributes.mIsPasswordField; mSuggestionStripView.updateVisibility(shouldShowSuggestionsStrip, isFullscreenMode()); if (!shouldShowSuggestionsStrip) { return; } final boolean isEmptyApplicationSpecifiedCompletions = currentSettingsValues.isApplicationSpecifiedCompletionsOn() && suggestedWords.isEmpty(); final boolean noSuggestionsFromDictionaries = suggestedWords.isEmpty() || suggestedWords.isPunctuationSuggestions() || isEmptyApplicationSpecifiedCompletions; final boolean isBeginningOfSentencePrediction = (suggestedWords.mInputStyle == SuggestedWords.INPUT_STYLE_BEGINNING_OF_SENTENCE_PREDICTION); final boolean noSuggestionsToOverrideImportantNotice = noSuggestionsFromDictionaries || isBeginningOfSentencePrediction; if (shouldShowImportantNotice && noSuggestionsToOverrideImportantNotice) { if (mSuggestionStripView.maybeShowImportantNoticeTitle()) { return; } } if (currentSettingsValues.isSuggestionsEnabledPerUserSettings() || currentSettingsValues.isApplicationSpecifiedCompletionsOn() // We should clear the contextual strip if there is no suggestion from dictionaries. || noSuggestionsFromDictionaries) { mSuggestionStripView.setSuggestions(suggestedWords, mRichImm.getCurrentSubtype().isRtlSubtype()); } } // TODO[IL]: Move this out of LatinIME. public void getSuggestedWords(final int inputStyle, final int sequenceNumber, final Suggest.OnGetSuggestedWordsCallback callback) { final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); if (keyboard == null) { callback.onGetSuggestedWords(SuggestedWords.getEmptyInstance()); return; } mInputLogic.getSuggestedWords(mSettings.getCurrent(), keyboard, mKeyboardSwitcher.getKeyboardShiftMode(), inputStyle, sequenceNumber, callback); } @Override public void showSuggestionStrip(final SuggestedWords suggestedWords) { if (suggestedWords.isEmpty()) { setNeutralSuggestionStrip(); } else { setSuggestedWords(suggestedWords); } // Cache the auto-correction in accessibility code so we can speak it if the user // touches a key that will insert it. AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords); } // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} // interface @Override public void pickSuggestionManually(final SuggestedWords.SuggestedWordInfo suggestionInfo) { final InputTransaction completeInputTransaction = mInputLogic.onPickSuggestionManually( mSettings.getCurrent(), suggestionInfo, mKeyboardSwitcher.getKeyboardShiftMode(), mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler); updateStateAfterInputTransaction(completeInputTransaction); } // This will show either an empty suggestion strip (if prediction is enabled) or // punctuation suggestions (if it's disabled). @Override public void setNeutralSuggestionStrip() { final SettingsValues currentSettings = mSettings.getCurrent(); final SuggestedWords neutralSuggestions = currentSettings.mBigramPredictionEnabled ? SuggestedWords.getEmptyInstance() : currentSettings.mSpacingAndPunctuations.mSuggestPuncList; setSuggestedWords(neutralSuggestions); } // Outside LatinIME, only used by the {@link InputTestsBase} test suite. @UsedForTesting void loadKeyboard() { // Since we are switching languages, the most urgent thing is to let the keyboard graphics // update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on // the screen. Anything we do right now will delay this, so wait until the next frame // before we do the rest, like reopening dictionaries and updating suggestions. So we // post a message. mHandler.postReopenDictionaries(); loadSettings(); if (mKeyboardSwitcher.getMainKeyboardView() != null) { // Reload keyboard because the current language has been changed. mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent(), getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } } /** * After an input transaction has been executed, some state must be updated. This includes * the shift state of the keyboard and suggestions. This method looks at the finished * inputTransaction to find out what is necessary and updates the state accordingly. * @param inputTransaction The transaction that has been executed. */ private void updateStateAfterInputTransaction(final InputTransaction inputTransaction) { switch (inputTransaction.getRequiredShiftUpdate()) { case InputTransaction.SHIFT_UPDATE_LATER: mHandler.postUpdateShiftState(); break; case InputTransaction.SHIFT_UPDATE_NOW: mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); break; default: // SHIFT_NO_UPDATE } if (inputTransaction.requiresUpdateSuggestions()) { final int inputStyle; if (inputTransaction.mEvent.isSuggestionStripPress()) { // Suggestion strip press: no input. inputStyle = SuggestedWords.INPUT_STYLE_NONE; } else if (inputTransaction.mEvent.isGesture()) { inputStyle = SuggestedWords.INPUT_STYLE_TAIL_BATCH; } else { inputStyle = SuggestedWords.INPUT_STYLE_TYPING; } mHandler.postUpdateSuggestionStrip(inputStyle); } if (inputTransaction.didAffectContents()) { mSubtypeState.setCurrentSubtypeHasBeenUsed(); } } private void hapticAndAudioFeedback(final int code, final int repeatCount) { final MainKeyboardView keyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (keyboardView != null && keyboardView.isInDraggingFinger()) { // No need to feedback while finger is dragging. return; } if (repeatCount > 0) { if (code == Constants.CODE_DELETE && !mInputLogic.mConnection.canDeleteCharacters()) { // No need to feedback when repeat delete key will have no effect. return; } // TODO: Use event time that the last feedback has been generated instead of relying on // a repeat count to thin out feedback. if (repeatCount % PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT == 0) { return; } } final AudioAndHapticFeedbackManager feedbackManager = AudioAndHapticFeedbackManager.getInstance(); if (repeatCount == 0) { // TODO: Reconsider how to perform haptic feedback when repeating key. feedbackManager.performHapticFeedback(keyboardView); } feedbackManager.performAudioFeedback(code); } // Callback of the {@link KeyboardActionListener}. This is called when a key is depressed; // release matching call is {@link #onReleaseKey(int,boolean)} below. @Override public void onPressKey(final int primaryCode, final int repeatCount, final boolean isSinglePointer) { if(primaryCode==Constants.CODE_DELETE && sessionData!=null){ sessionData.NumDels+=1; } mKeyboardSwitcher.onPressKey(primaryCode, isSinglePointer, getCurrentAutoCapsState(), getCurrentRecapitalizeState()); hapticAndAudioFeedback(primaryCode, repeatCount); } // Callback of the {@link KeyboardActionListener}. This is called when a key is released; // press matching call is {@link #onPressKey(int,int,boolean)} above. @Override public void onReleaseKey(final int primaryCode, final boolean withSliding) { mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding, getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } private HardwareEventDecoder getHardwareKeyEventDecoder(final int deviceId) { final HardwareEventDecoder decoder = mHardwareEventDecoders.get(deviceId); if (null != decoder) return decoder; // TODO: create the decoder according to the specification final HardwareEventDecoder newDecoder = new HardwareKeyboardEventDecoder(deviceId); mHardwareEventDecoders.put(deviceId, newDecoder); return newDecoder; } // Hooks for hardware keyboard @Override public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) { if (mEmojiAltPhysicalKeyDetector == null) { mEmojiAltPhysicalKeyDetector = new EmojiAltPhysicalKeyDetector( getApplicationContext().getResources()); } mEmojiAltPhysicalKeyDetector.onKeyDown(keyEvent); if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { return super.onKeyDown(keyCode, keyEvent); } final Event event = getHardwareKeyEventDecoder( keyEvent.getDeviceId()).decodeHardwareKey(keyEvent); // If the event is not handled by LatinIME, we just pass it to the parent implementation. // If it's handled, we return true because we did handle it. if (event.isHandled()) { mInputLogic.onCodeInput(mSettings.getCurrent(), event, mKeyboardSwitcher.getKeyboardShiftMode(), // TODO: this is not necessarily correct for a hardware keyboard right now mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler); return true; } return super.onKeyDown(keyCode, keyEvent); } @Override public boolean onKeyUp(final int keyCode, final KeyEvent keyEvent) { if (mEmojiAltPhysicalKeyDetector == null) { mEmojiAltPhysicalKeyDetector = new EmojiAltPhysicalKeyDetector( getApplicationContext().getResources()); } mEmojiAltPhysicalKeyDetector.onKeyUp(keyEvent); if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { return super.onKeyUp(keyCode, keyEvent); } final long keyIdentifier = keyEvent.getDeviceId() << 32 + keyEvent.getKeyCode(); if (mInputLogic.mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) { return true; } return super.onKeyUp(keyCode, keyEvent); } // onKeyDown and onKeyUp are the main events we are interested in. There are two more events // related to handling of hardware key events that we may want to implement in the future: // boolean onKeyLongPress(final int keyCode, final KeyEvent event); // boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event); // receive ringer mode change. private final BroadcastReceiver mRingerModeChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { AudioAndHapticFeedbackManager.getInstance().onRingerModeChanged(); } } }; void launchSettings(final String extraEntryValue) { mInputLogic.commitTyped(mSettings.getCurrent(), LastComposedWord.NOT_A_SEPARATOR); requestHideSelf(0); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.closing(); } final Intent intent = new Intent(); intent.setClass(LatinIME.this, SettingsActivity.class); intent.setFlags(FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(SettingsActivity.EXTRA_SHOW_HOME_AS_UP, false); intent.putExtra(SettingsActivity.EXTRA_ENTRY_KEY, extraEntryValue); startActivity(intent); } private void showSubtypeSelectorAndSettings() { final CharSequence title = getString(R.string.english_ime_input_options); // TODO: Should use new string "Select active input modes". final CharSequence languageSelectionTitle = getString(R.string.language_selection_title); final CharSequence[] items = new CharSequence[] { languageSelectionTitle, getString(ApplicationUtils.getActivityTitleResId(this, SettingsActivity.class)) }; final String imeId = mRichImm.getInputMethodIdOfThisIme(); final OnClickListener listener = new OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: // final Intent intent = IntentUtils.getInputLanguageSelectionIntent( // imeId, // FLAG_ACTIVITY_NEW_TASK // | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED //remi0s commented // | Intent.FLAG_ACTIVITY_CLEAR_TOP); // intent.putExtra(Intent.EXTRA_TITLE, languageSelectionTitle); // startActivity(intent); final InputMethodInfo imi = UncachedInputMethodManagerUtils.getInputMethodInfoOf(getPackageName(), mRichImm.getInputMethodManager()); //remi0s fixed bug if (imi == null) { return; } final Intent intent = new Intent(); intent.setAction(android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra(android.provider.Settings.EXTRA_INPUT_METHOD_ID, imi.getId()); startActivity(intent); break; case 1: launchSettings(SettingsActivity.EXTRA_ENTRY_VALUE_LONG_PRESS_COMMA); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder( DialogUtils.getPlatformDialogThemeContext(this)); builder.setItems(items, listener).setTitle(title); final AlertDialog dialog = builder.create(); dialog.setCancelable(true /* cancelable */); dialog.setCanceledOnTouchOutside(true /* cancelable */); showOptionDialog(dialog); } // TODO: Move this method out of {@link LatinIME}. private void showOptionDialog(final AlertDialog dialog) { final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken(); if (windowToken == null) { return; } final Window window = dialog.getWindow(); final WindowManager.LayoutParams lp = window.getAttributes(); lp.token = windowToken; lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog = dialog; dialog.show(); } @UsedForTesting SuggestedWords getSuggestedWordsForTest() { // You may not use this method for anything else than debug return DebugFlags.DEBUG_ENABLED ? mInputLogic.mSuggestedWords : null; } // DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME. @UsedForTesting void waitForLoadingDictionaries(final long timeout, final TimeUnit unit) throws InterruptedException { mDictionaryFacilitator.waitForLoadingDictionariesForTesting(timeout, unit); } // DO NOT USE THIS for any other purpose than testing. This can break the keyboard badly. @UsedForTesting void replaceDictionariesForTest(final Locale locale) { final SettingsValues settingsValues = mSettings.getCurrent(); mDictionaryFacilitator.resetDictionaries(this, locale, settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, false /* forceReloadMainDictionary */, settingsValues.mAccount, "", /* dictionaryNamePrefix */ this /* DictionaryInitializationListener */); } // DO NOT USE THIS for any other purpose than testing. @UsedForTesting void clearPersonalizedDictionariesForTest() { mDictionaryFacilitator.clearUserHistoryDictionary(this); } @UsedForTesting List<InputMethodSubtype> getEnabledSubtypesForTest() { return (mRichImm != null) ? mRichImm.getMyEnabledInputMethodSubtypeList( true /* allowsImplicitlySelectedSubtypes */) : new ArrayList<InputMethodSubtype>(); } public void dumpDictionaryForDebug(final String dictName) { if (!mDictionaryFacilitator.isActive()) { resetDictionaryFacilitatorIfNecessary(); } mDictionaryFacilitator.dumpDictionaryForDebug(dictName); } public void debugDumpStateAndCrashWithException(final String context) { final SettingsValues settingsValues = mSettings.getCurrent(); final StringBuilder s = new StringBuilder(settingsValues.toString()); s.append("\nAttributes : ").append(settingsValues.mInputAttributes) .append("\nContext : ").append(context); throw new RuntimeException(s.toString()); } @Override protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); p.println(" VersionCode = " + ApplicationUtils.getVersionCode(this)); p.println(" VersionName = " + ApplicationUtils.getVersionName(this)); final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; p.println(" Keyboard mode = " + keyboardMode); final SettingsValues settingsValues = mSettings.getCurrent(); p.println(settingsValues.dump()); p.println(mDictionaryFacilitator.dump(this /* context */)); // TODO: Dump all settings values } public boolean shouldSwitchToOtherInputMethods() { // TODO: Revisit here to reorganize the settings. Probably we can/should use different // strategy once the implementation of // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well. final boolean fallbackValue = mSettings.getCurrent().mIncludesOtherImesInLanguageSwitchList; final IBinder token = getWindow().getWindow().getAttributes().token; if (token == null) { return fallbackValue; } // return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue); return false; //remi0s to block changing to other keyboards } public boolean shouldShowLanguageSwitchKey() { // TODO: Revisit here to reorganize the settings. Probably we can/should use different // strategy once the implementation of // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well. final boolean fallbackValue = mSettings.getCurrent().isLanguageSwitchKeyEnabled(); final IBinder token = getWindow().getWindow().getAttributes().token; if (token == null) { return fallbackValue; } return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue); } private void setNavigationBarVisibility(final boolean visible) { if (BuildCompatUtils.EFFECTIVE_SDK_INT > Build.VERSION_CODES.M) { // For N and later, IMEs can specify Color.TRANSPARENT to make the navigation bar // transparent. For other colors the system uses the default color. getWindow().getWindow().setNavigationBarColor( visible ? Color.BLACK : Color.TRANSPARENT); } } private void CreateAlertDialogWithRadioButtonGroup() { Intent intent = new Intent(getApplicationContext(), ChooseMood.class); intent.setFlags(FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private static boolean AddData(String sessionDataString,Context context) { boolean insertData=myDB.addData(sessionDataString); if(insertData==false) { Toast.makeText(context, "Something went wrong in database", Toast.LENGTH_LONG).show(); } return insertData; } public static boolean isConnected(Context context){ ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE); try { NetworkInfo networkInfo = null; if (connMgr != null) { networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } // NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; }catch (Exception e){ return false; } } // public static class HttpAsyncTask extends AsyncTask<String, Void, String> { // String result=""; // @Override // protected String doInBackground(String... params) { // String prefs_id=params[0]; // String prefs_age=params[1]; // String prefs_gender=params[2]; // String prefs_health=params[3]; // ArrayList<KeyboardPayload> notSendData = new ArrayList<>(); // Cursor data = myDB.getNotSendContents(); // try { // if (data.getCount() != 0) { // while (data.moveToNext()) { // KeyboardPayload payload=new KeyboardPayload(); // payload.DocID=data.getString(0);//DocID // payload.DateData=data.getString(1); //DateTime //// payload.UserID=data.getString(2); //UserID // payload.SessionData= data.getString(2); //SessionData // notSendData.add(payload); // } // result=upload(notSendData,prefs_id,prefs_age,prefs_gender,prefs_health, storageConnectionString, storageContainer);//POST(urls[0],notSendData); // }else{ // Log.d("SQL","I'm in do in background 0 data"); // } // } finally { // data.close(); // } // // // // return result; // } // // onPostExecute displays the results of the AsyncTask. // @Override // protected void onPostExecute(String result) { // Log.d("SQL","Tried to send data with result: "+result); //// Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show(); // } // } // public static String oldPOST(String url,ArrayList<KeyboardPayload> payload){ // InputStream inputStream = null; // String result = ""; // // // try { // // 1. create HttpClient // HttpClient httpclient = new DefaultHttpClient(); // // // 2. make POST request to the given URL // HttpPost httpPost = new HttpPost(url); // // String json = ""; // // if((!pref_ID.isEmpty() && !pref_age.isEmpty() && !pref_gender.isEmpty() && !pref_health.isEmpty())){ // // for(int i = 0; i < payload.size(); i++) { //payload.size() // // // 3. build jsonObject // // // // // JSONObject jsonObject = new JSONObject(); // jsonObject.accumulate("DOC_ID", payload.get(i).DocID); // jsonObject.accumulate("USER_ID",pref_ID); // jsonObject.accumulate("USER_AGE", pref_age); // jsonObject.accumulate("USER_GENDER", pref_gender); // jsonObject.accumulate("USER_PHQ9", pref_health); // jsonObject.accumulate("DATE_DATA", payload.get(i).DateData); // jsonObject.accumulate("SESSION_DATA", payload.get(i).SessionData); // // // // 4. convert JSONObject to JSON to String // json = jsonObject.toString(); // // Log.d("server","Json to be sent:\n"+json); // // // // ** Alternative way to convert Person object to JSON string usin Jackson Lib // // ObjectMapper mapper = new ObjectMapper(); // // json = mapper.writeValueAsString(person); //// Gson gson = new Gson(); //// json = gson.toJson(payload.get(i), KeyboardPayload.class); // // // 5. set json to StringEntity // StringEntity se = new StringEntity(json); // // // 6. set httpPost Entity // httpPost.setEntity(se); // // // 7. Set some headers to inform server about the type of the content // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // // // 8. Execute POST request to the given URL // HttpResponse httpResponse = httpclient.execute(httpPost); // // // 9. receive response as inputStream // inputStream = httpResponse.getEntity().getContent(); // // // // // // 10. convert inputstream to string // if(inputStream != null) { // result = convertInputStreamToString(inputStream); // Log.d("SQL","I'm at inputstream"); // myDB.setSend(payload.get(i).DocID); // Log.d("SQL","Data Sent!"); // } // else { // result = "Did not work!"; // } // // } // } // // // // // } catch (Exception e) { // Log.d("InputStream", e.getLocalizedMessage()); // } // // // 11. return result // return result; // } protected static String upload(ArrayList<KeyboardPayload> payload,Context context){ String result = ""; SharedPreferences pref =context.getSharedPreferences("user_info", Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); String prefs_age= pref.getString("Age", ""); String prefs_id= pref.getString("ID", ""); String prefs_gender= pref.getString("Gender", ""); String prefs_health= pref.getString("Health", ""); String pref_phq9_item_1=pref.getString("PHQ9_item_1", ""); String pref_phq9_item_2=pref.getString("PHQ9_item_2", ""); String pref_phq9_item_3=pref.getString("PHQ9_item_3", ""); String pref_phq9_item_4=pref.getString("PHQ9_item_4", ""); String pref_phq9_item_5=pref.getString("PHQ9_item_5", ""); String pref_phq9_item_6=pref.getString("PHQ9_item_6", ""); String pref_phq9_item_7=pref.getString("PHQ9_item_7", ""); String pref_phq9_item_8=pref.getString("PHQ9_item_8", ""); String pref_phq9_item_9=pref.getString("PHQ9_item_9", ""); String pref_education = pref.getString("Education", ""); String pref_usage = pref.getString("Usage", ""); String pref_income = pref.getString("Income", ""); String pref_medication= pref.getString("Medication", ""); long users_max_flight= pref.getLong("MaxFlight", 0); long users_min_flight= pref.getLong("MinFlight", 3000); float users_mean_flight= pref.getFloat("MeanFlight", 0); long users_max_hold= pref.getLong("MaxHold", 0); long users_min_hold= pref.getLong("MinHold", 3000); float users_mean_hold= pref.getFloat("MeanHold", 0); editor.apply(); String storagesContainer=getConfigValue(context, "storageContainer"); String storagesConnectionString=getConfigValue(context, "storageConnectionString"); String country =getUserCountry(context); try { if((!prefs_id.isEmpty() && !prefs_age.isEmpty() && !prefs_gender.isEmpty() && !prefs_health.isEmpty())){ for(int i = 0; i < payload.size(); i++) { //payload.size() // 3. build jsonObject JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("DOC_ID", payload.get(i).DocID); jsonObject.accumulate("USER_ID", prefs_id); jsonObject.accumulate("USER_COUNTRY", country); jsonObject.accumulate("USER_AGE", prefs_age); jsonObject.accumulate("USER_GENDER", prefs_gender); jsonObject.accumulate("USER_EDUCATION", pref_education); jsonObject.accumulate("USER_PHONE_USAGE", pref_usage); jsonObject.accumulate("USER_INCOME", pref_income); jsonObject.accumulate("USER_MEDICATION", pref_medication); jsonObject.accumulate("USER_PHQ9", prefs_health); jsonObject.accumulate("USER_PHQ9_ITEM_1", pref_phq9_item_1); jsonObject.accumulate("USER_PHQ9_ITEM_2", pref_phq9_item_2); jsonObject.accumulate("USER_PHQ9_ITEM_3", pref_phq9_item_3); jsonObject.accumulate("USER_PHQ9_ITEM_4", pref_phq9_item_4); jsonObject.accumulate("USER_PHQ9_ITEM_5", pref_phq9_item_5); jsonObject.accumulate("USER_PHQ9_ITEM_6", pref_phq9_item_6); jsonObject.accumulate("USER_PHQ9_ITEM_7", pref_phq9_item_7); jsonObject.accumulate("USER_PHQ9_ITEM_8", pref_phq9_item_8); jsonObject.accumulate("USER_PHQ9_ITEM_9", pref_phq9_item_9); jsonObject.accumulate("USER_MAX_FLIGHT", users_max_flight); jsonObject.accumulate("USER_MIN_FLIGHT", users_min_flight); jsonObject.accumulate("USER_MEAN_FLIGHT", users_mean_flight); jsonObject.accumulate("USER_MAX_HOLD", users_max_hold); jsonObject.accumulate("USER_MIN_HOLD", users_min_hold); jsonObject.accumulate("USER_MEAN_HOLD", users_mean_hold); // jsonObject.accumulate("DATE_DATA", payload.get(i).DateData); // jsonObject.accumulate("SESSION_DATA", payload.get(i).SessionData); // 4. convert JSONObject to JSON to String // Retrieve storage account from connection-string. CloudStorageAccount storageAccount = CloudStorageAccount.parse(storagesConnectionString); // Create the blob client. CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); // Retrieve reference to a previously created container. CloudBlobContainer container = blobClient.getContainerReference(storagesContainer); // Create or overwrite the blob (with the name "example.jpeg") with contents from a local file. String formattedDate=new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date()); String formattedDateData=""; try{ Date date =new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss", Locale.US).parse(payload.get(i).DateData); jsonObject.accumulate("DATE_DATA", payload.get(i).DateData); formattedDate = new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(date); }catch (Exception e) { try { Date tempDate = new Date(payload.get(i).DateData); formattedDate = new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(tempDate); formattedDateData= new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss", Locale.US).format(tempDate); jsonObject.accumulate("DATE_DATA", formattedDateData); }catch (Exception a){ Log.d("dateError", "Even that failed"); } } jsonObject.accumulate("DATE_SEND", new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss", Locale.US).format(new Date())); jsonObject.accumulate("SESSION_DATA", payload.get(i).SessionData); String blobName=prefs_id+"/"+formattedDate+"/"+payload.get(i).DocID+".json"; CloudBlockBlob blob = container.getBlockBlobReference(blobName); blob.uploadText(jsonObject.toString()); result="success"; myDB.setSend(payload.get(i).DocID); } } } catch (Exception e) { // Output the stack trace. result="failed"; e.printStackTrace(); Log.d("Upload", e.getLocalizedMessage()); } return result; } private static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } // private Boolean isPasswordGivenCorrect () { //// SharedPreferences pref =getSharedPreferences("user_info", Context.MODE_PRIVATE); //// SharedPreferences.Editor editor = pref.edit(); //// String pref_password= pref.getString("Password", ""); //// editor.apply(); //// //return (pref_password.equals(getConfigValue(getApplicationContext(), "password"))); //// return true; //// } private Boolean userHaveAgreed(){ SharedPreferences pref =getSharedPreferences("user_info", Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); boolean pref_terms= pref.getBoolean("TermsAgreement", false); editor.apply(); return pref_terms; } public static String getConfigValue(Context context, String name) { Resources resources = context.getResources(); try { InputStream rawResource = resources.openRawResource(R.raw.config); Properties properties = new Properties(); properties.load(rawResource); return properties.getProperty(name); } catch (Resources.NotFoundException e) { Log.e(TAG, "Unable to find the config file: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "Failed to open config file."); } return null; } private static class DataStoreAsyncTask extends AsyncTask<DataStoreAsyncTaskParams, Void, String> { WeakReference<Context> weakContext; private DataStoreAsyncTask (Context context){ weakContext = new WeakReference<Context>(context); } @Override protected String doInBackground(DataStoreAsyncTaskParams... args) { Boolean result=false; KeyboardDynamics sessionDataTemp; sessionDataTemp=args[0].data; ArrayList<Double> xTemp=new ArrayList<Double>(args[0].x); ArrayList<Double> yTemp=new ArrayList<Double>(args[0].y); if (sessionDataTemp != null) { // sessionDataTemp.StopDateTime = System.currentTimeMillis(); StopDateTimeTemp=new Date(sessionDataTemp.StopDateTime); sessionDataTemp.CurrentMood = currentMood; sessionDataTemp.CurrentPhysicalState=currentPhysicalState; sessionDataTemp.LatestNotification=latestNotificationTime; int notificationFlag = 0; if (latestNotificationTime != 0) { long minutesPassed = TimeUnit.MINUTES.convert(StopDateTimeTemp.getTime() - latestNotificationTimeTemp.getTime(), TimeUnit.MILLISECONDS); if(laterPressed && minutesPassed>=120){ sessionDataTemp.CurrentMood =currentMood+" TIMEOUT"; sessionDataTemp.CurrentPhysicalState=currentPhysicalState+" TIMEOUT"; notificationFlag = 1; laterPressed=false; }else if (minutesPassed >= 120 || (sessionsCounter>=30 && minutesPassed>=90)) { notificationFlag = 1; sessionDataTemp.CurrentMood = currentMood + " TIMEOUT"; sessionDataTemp.CurrentPhysicalState = currentPhysicalState + " TIMEOUT"; }else{ notificationFlag = 0; } } else { notificationFlag = 1; sessionDataTemp.CurrentMood = "undefined"; sessionDataTemp.CurrentPhysicalState="undefined"; } if (notificationFlag == 1 && sessionDataTemp.DownTime.size() > 5) { String title = "TypeOfMood"; String message = "Please Expand to describe your mood!"; sessionsCounter=0; // mNotificationHelperPhysical = new NotificationHelperPhysical(weakContext.get()); // NotificationCompat.Builder nbPhysical = mNotificationHelperPhysical.getTypeOfMoodNotification(title, message); // mNotificationHelperPhysical.getManager().notify(mNotificationHelperPhysical.notification_id, nbPhysical.build()); // mNotificationHelper = new NotificationHelper(weakContext.get()); nb = mNotificationHelper.getTypeOfMoodNotification(title, message,nb); mNotificationHelper.getManager().notify(mNotificationHelper.notification_id, nb.build()); // CreateAlertDialogWithRadioButtonGroup(); } if (sessionDataTemp.DownTime.size() >= 5){ long min_flight=3000; long max_flight=0; float average_flight=0; int num_flight=0; ArrayList<Long>flight_time=new ArrayList<Long>(); long min_hold=3000; long max_hold=0; float average_hold=0; int num_hold=0; ArrayList<Long>hold_time=new ArrayList<Long>(); double dist=0; double dx=0,dy=0; for(int i=0;i<xTemp.size()-1;i++){ dx=(xTemp.get(i)-xTemp.get(i+1)); dy=(yTemp.get(i)-yTemp.get(i+1)); dx=dx/densX * 25.4f; dy=dy/densY * 25.4f; dist=Math.hypot(dx,dy); sessionDataTemp.Distance.add(dist); flight_time.add(sessionDataTemp.DownTime.get(i+1)-sessionDataTemp.UpTime.get(i)); //flight time long temp=flight_time.get(flight_time.size()-1); if (temp<min_flight && temp>0){ min_flight=temp; } if (temp>max_flight && temp<3000){ max_flight=temp; } if (temp>0 && temp<3000){ num_flight=num_flight+1; average_flight=(average_flight+temp); } //hold time if(sessionDataTemp.IsLongPress.get(i)!=1){ hold_time.add(sessionDataTemp.UpTime.get(i)-sessionDataTemp.DownTime.get(i)); long temp2=hold_time.get(hold_time.size()-1); if (temp2<min_hold){ min_hold=temp2; } if (temp2>max_hold){ max_hold=temp2; } num_hold=num_hold+1; average_hold=(average_hold+temp2); } }//end for i size downtime average_hold=average_hold/num_hold; average_flight=average_flight/num_flight; SharedPreferences pref =weakContext.get().getSharedPreferences("user_info", Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); user_sessions= pref.getInt("Sessions_counter", 1); user_max_flight= pref.getLong("MaxFlight", 0); user_min_flight= pref.getLong("MinFlight", 3000); user_mean_flight= pref.getFloat("MeanFlight", 0); user_max_hold= pref.getLong("MaxHold", 0); user_min_hold= pref.getLong("MinHold", 3000); user_mean_hold= pref.getFloat("MeanHold", 0); //flight time if (min_flight<user_min_flight){ editor.putLong("MinFlight",min_flight ); } if (max_flight>user_max_flight){ editor.putLong("MaxFlight",max_flight ); } float temp_average=(user_mean_flight*user_sessions+average_flight)/(user_sessions+1); editor.putFloat("MeanFlight", temp_average); //hold time if (min_hold<user_min_hold){ editor.putLong("MinHold",min_hold ); } if (max_hold>user_max_hold){ editor.putLong("MaxHold",max_hold ); } //if not all was longpressed if(average_hold>0){ temp_average=(user_mean_hold*user_sessions+average_hold)/(user_sessions+1); editor.putFloat("MeanHold",temp_average ); } int temp_sessions=user_sessions+1; editor.putInt("Sessions_counter",temp_sessions ); editor.apply(); //save data Gson gson = new GsonBuilder().serializeNulls().create(); String sessionDataString = gson.toJson(sessionDataTemp, KeyboardDynamics.class); // Log.d("Json", "Json string: " + sessionDataString); result=AddData(sessionDataString,weakContext.get()); sessionsCounter=sessionsCounter+1; //send data long sendMinutesPassed; if(latestSendTimeTemp!=null){ sendMinutesPassed= TimeUnit.MINUTES.convert((new Date(System.currentTimeMillis())).getTime()-latestSendTimeTemp.getTime() , TimeUnit.MILLISECONDS); }else{ sendMinutesPassed=61; } String send_result="not yet "+sendMinutesPassed; if(isConnected(weakContext.get() ) && (sendMinutesPassed>=15)){ latestSendTimeTemp=new Date(System.currentTimeMillis()); DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss"); editor = pref.edit(); editor.putString("latest_send_date",dateFormat.format(latestSendTimeTemp)); editor.apply(); ArrayList<KeyboardPayload> notSendData = new ArrayList<>(); Cursor data = myDB.getNotSendContents(); try { if (data.getCount() != 0) { while (data.moveToNext()) { KeyboardPayload payload=new KeyboardPayload(); payload.DocID=data.getString(0);//DocID payload.DateData=data.getString(1); //DateTime // payload.UserID=data.getString(2); //UserID payload.SessionData= data.getString(2); //SessionData notSendData.add(payload); } String locale =getUserCountry(weakContext.get()); Log.d("country",locale); send_result=upload(notSendData,weakContext.get());//POST(urls[0],notSendData); }else{ Log.d("Upload","I'm in do in background 0 data"); } } finally { data.close(); } } Log.w("Upload","Tried to send data with result: "+send_result); } } if(result){ return "success"; }else{ return "failure"; } } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { // Log.d("SQL","Tried to save data with result: "+result); // Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show(); } } private static class DataStoreAsyncTaskParams { KeyboardDynamics data; ArrayList<Double> x; ArrayList<Double> y; // String prefs_id; // String prefs_age; // String prefs_gender; // String prefs_health; // String storageConnectionString; // String storageContainer; DataStoreAsyncTaskParams(KeyboardDynamics data, ArrayList<Double> x, ArrayList<Double> y) { this.data = data; this.x = new ArrayList<Double>(x); this.y = new ArrayList<Double>(y); // this.prefs_id=prefs_id; // this.prefs_age=prefs_age; // this.prefs_gender=prefs_gender; // this.prefs_health=prefs_health; // this.storageConnectionString=storageConnectionString; // this.storageContainer=storageContainer; } } private static class onShowNotificationAsync extends AsyncTask<Void, Void, String> { WeakReference<Context> weakContext; private onShowNotificationAsync (Context context){ weakContext = new WeakReference<Context>(context); } @Override protected String doInBackground(Void... params) { //notification int notificationFlag = 0; Date StartDateTimeTemp=new Date(System.currentTimeMillis()); if (latestNotificationTime != 0) { long minutesPassed = TimeUnit.MINUTES.convert(StartDateTimeTemp.getTime() - latestNotificationTimeTemp.getTime(), TimeUnit.MILLISECONDS); if(laterPressed && minutesPassed>=120){ // sessionData.CurrentMood =currentMood+" TIMEOUT"; // sessionData.CurrentPhysicalState=currentPhysicalState+" TIMEOUT"; notificationFlag = 1; laterPressed=false; }else if(minutesPassed >= 120 || (sessionsCounter>=30 && minutesPassed>=90)){ notificationFlag = 1; // sessionData.CurrentMood = currentMood + " TIMEOUT"; // sessionData.CurrentPhysicalState = currentPhysicalState + " TIMEOUT"; }else{ notificationFlag = 0; } } else { notificationFlag = 1; // sessionData.CurrentMood = "undefined"; // sessionData.CurrentPhysicalState="undefined"; } if (notificationFlag == 1 ) { String title = "TypeOfMood"; String message = "Please Expand to describe your mood!"; sessionsCounter=0; // mNotificationHelperPhysical = new NotificationHelperPhysical(weakContext.get()); // NotificationCompat.Builder nbPhysical = mNotificationHelperPhysical.getTypeOfMoodNotification(title, message); // mNotificationHelperPhysical.getManager().notify(mNotificationHelperPhysical.notification_id, nbPhysical.build()); nb = mNotificationHelper.getTypeOfMoodNotification(title, message,nb); mNotificationHelper.getManager().notify(mNotificationHelper.notification_id, nb.build()); // CreateAlertDialogWithRadioButtonGroup(); } return "success"; } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { // Log.d("SQL","Tried to save data with result: "+result); // Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show(); } } public static String getUserCountry(Context context) { try { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final String simCountry = tm.getSimCountryIso(); if (simCountry != null && simCountry.length() == 2) { // SIM country code is available return simCountry.toUpperCase(Locale.US); } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable) String networkCountry = tm.getNetworkCountryIso(); if (networkCountry != null && networkCountry.length() == 2) { // network country code is available return networkCountry.toUpperCase(Locale.US); } } } catch (Exception e) { } return "undefined"; } }
[ "public", "class", "LatinIME", "extends", "InputMethodService", "implements", "KeyboardActionListener", ",", "SuggestionStripView", ".", "Listener", ",", "SuggestionStripViewAccessor", ",", "DictionaryFacilitator", ".", "DictionaryInitializationListener", ",", "PermissionsManager", ".", "PermissionsResultCallback", "{", "public", "static", "String", "storageContainer", "=", "\"", "\"", ";", "public", "static", "String", "storageConnectionString", "=", "\"", "\"", ";", "public", "static", "KeyboardDynamics", "sessionData", "=", "null", ";", "private", "static", "NotificationHelper", "mNotificationHelper", ";", "private", "static", "NotificationCompat", ".", "Builder", "nb", ";", "public", "static", "String", "currentMood", "=", "\"", "undefined", "\"", ";", "public", "static", "String", "currentPhysicalState", "=", "\"", "undefined", "\"", ";", "public", "static", "long", "latestNotificationTime", ";", "public", "static", "Date", "latestNotificationTimeTemp", ";", "public", "static", "Date", "latestSendTimeTemp", ";", "public", "static", "Date", "StopDateTimeTemp", ";", "public", "static", "Boolean", "laterPressed", "=", "false", ";", "public", "static", "Boolean", "isLongPressedFlag", "=", "false", ";", "public", "static", "DatabaseHelper", "myDB", ";", "public", "static", "String", "userID", ";", "public", "static", "ArrayList", "<", "Double", ">", "rawX", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "public", "static", "ArrayList", "<", "Double", ">", "rawY", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "public", "static", "double", "densX", ";", "public", "static", "double", "densY", ";", "public", "static", "int", "user_sessions", "=", "1", ";", "public", "static", "long", "user_min_flight", "=", "3000", ";", "public", "static", "long", "user_max_flight", "=", "0", ";", "public", "static", "float", "user_mean_flight", "=", "0", ";", "public", "static", "long", "user_min_hold", "=", "3000", ";", "public", "static", "long", "user_max_hold", "=", "0", ";", "public", "static", "float", "user_mean_hold", "=", "0", ";", "public", "static", "int", "sessionsCounter", "=", "0", ";", "static", "final", "String", "TAG", "=", "LatinIME", ".", "class", ".", "getSimpleName", "(", ")", ";", "private", "static", "final", "boolean", "TRACE", "=", "false", ";", "private", "static", "final", "int", "EXTENDED_TOUCHABLE_REGION_HEIGHT", "=", "100", ";", "private", "static", "final", "int", "PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT", "=", "2", ";", "private", "static", "final", "int", "PENDING_IMS_CALLBACK_DURATION_MILLIS", "=", "800", ";", "static", "final", "long", "DELAY_WAIT_FOR_DICTIONARY_LOAD_MILLIS", "=", "TimeUnit", ".", "SECONDS", ".", "toMillis", "(", "2", ")", ";", "static", "final", "long", "DELAY_DEALLOCATE_MEMORY_MILLIS", "=", "TimeUnit", ".", "SECONDS", ".", "toMillis", "(", "10", ")", ";", "/**\n * The name of the scheme used by the Package Manager to warn of a new package installation,\n * replacement or removal.\n */", "private", "static", "final", "String", "SCHEME_PACKAGE", "=", "\"", "package", "\"", ";", "final", "Settings", "mSettings", ";", "private", "final", "DictionaryFacilitator", "mDictionaryFacilitator", "=", "DictionaryFacilitatorProvider", ".", "getDictionaryFacilitator", "(", "false", "/* isNeededForSpellChecking */", ")", ";", "final", "InputLogic", "mInputLogic", "=", "new", "InputLogic", "(", "this", "/* LatinIME */", ",", "this", "/* SuggestionStripViewAccessor */", ",", "mDictionaryFacilitator", ")", ";", "final", "SparseArray", "<", "HardwareEventDecoder", ">", "mHardwareEventDecoders", "=", "new", "SparseArray", "<", ">", "(", "1", ")", ";", "private", "View", "mInputView", ";", "private", "InsetsUpdater", "mInsetsUpdater", ";", "private", "SuggestionStripView", "mSuggestionStripView", ";", "private", "RichInputMethodManager", "mRichImm", ";", "@", "UsedForTesting", "final", "KeyboardSwitcher", "mKeyboardSwitcher", ";", "private", "final", "SubtypeState", "mSubtypeState", "=", "new", "SubtypeState", "(", ")", ";", "private", "EmojiAltPhysicalKeyDetector", "mEmojiAltPhysicalKeyDetector", ";", "private", "StatsUtilsManager", "mStatsUtilsManager", ";", "private", "boolean", "mIsExecutingStartShowingInputView", ";", "private", "final", "BroadcastReceiver", "mDictionaryPackInstallReceiver", "=", "new", "DictionaryPackInstallBroadcastReceiver", "(", "this", ")", ";", "private", "final", "BroadcastReceiver", "mDictionaryDumpBroadcastReceiver", "=", "new", "DictionaryDumpBroadcastReceiver", "(", "this", ")", ";", "private", "AlertDialog", "mOptionsDialog", ";", "private", "final", "boolean", "mIsHardwareAcceleratedDrawingEnabled", ";", "private", "GestureConsumer", "mGestureConsumer", "=", "GestureConsumer", ".", "NULL_GESTURE_CONSUMER", ";", "public", "final", "UIHandler", "mHandler", "=", "new", "UIHandler", "(", "this", ")", ";", "public", "static", "final", "class", "UIHandler", "extends", "LeakGuardHandlerWrapper", "<", "LatinIME", ">", "{", "private", "static", "final", "int", "MSG_UPDATE_SHIFT_STATE", "=", "0", ";", "private", "static", "final", "int", "MSG_PENDING_IMS_CALLBACK", "=", "1", ";", "private", "static", "final", "int", "MSG_UPDATE_SUGGESTION_STRIP", "=", "2", ";", "private", "static", "final", "int", "MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP", "=", "3", ";", "private", "static", "final", "int", "MSG_RESUME_SUGGESTIONS", "=", "4", ";", "private", "static", "final", "int", "MSG_REOPEN_DICTIONARIES", "=", "5", ";", "private", "static", "final", "int", "MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED", "=", "6", ";", "private", "static", "final", "int", "MSG_RESET_CACHES", "=", "7", ";", "private", "static", "final", "int", "MSG_WAIT_FOR_DICTIONARY_LOAD", "=", "8", ";", "private", "static", "final", "int", "MSG_DEALLOCATE_MEMORY", "=", "9", ";", "private", "static", "final", "int", "MSG_RESUME_SUGGESTIONS_FOR_START_INPUT", "=", "10", ";", "private", "static", "final", "int", "MSG_SWITCH_LANGUAGE_AUTOMATICALLY", "=", "11", ";", "private", "static", "final", "int", "MSG_LAST", "=", "MSG_SWITCH_LANGUAGE_AUTOMATICALLY", ";", "private", "static", "final", "int", "ARG1_NOT_GESTURE_INPUT", "=", "0", ";", "private", "static", "final", "int", "ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT", "=", "1", ";", "private", "static", "final", "int", "ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT", "=", "2", ";", "private", "static", "final", "int", "ARG2_UNUSED", "=", "0", ";", "private", "static", "final", "int", "ARG1_TRUE", "=", "1", ";", "private", "int", "mDelayInMillisecondsToUpdateSuggestions", ";", "private", "int", "mDelayInMillisecondsToUpdateShiftState", ";", "public", "UIHandler", "(", "@", "Nonnull", "final", "LatinIME", "ownerInstance", ")", "{", "super", "(", "ownerInstance", ")", ";", "}", "public", "void", "onCreate", "(", ")", "{", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "==", "null", ")", "{", "return", ";", "}", "final", "Resources", "res", "=", "latinIme", ".", "getResources", "(", ")", ";", "mDelayInMillisecondsToUpdateSuggestions", "=", "res", ".", "getInteger", "(", "R", ".", "integer", ".", "config_delay_in_milliseconds_to_update_suggestions", ")", ";", "mDelayInMillisecondsToUpdateShiftState", "=", "res", ".", "getInteger", "(", "R", ".", "integer", ".", "config_delay_in_milliseconds_to_update_shift_state", ")", ";", "}", "@", "Override", "public", "void", "handleMessage", "(", "final", "Message", "msg", ")", "{", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "==", "null", ")", "{", "return", ";", "}", "final", "KeyboardSwitcher", "switcher", "=", "latinIme", ".", "mKeyboardSwitcher", ";", "switch", "(", "msg", ".", "what", ")", "{", "case", "MSG_UPDATE_SUGGESTION_STRIP", ":", "cancelUpdateSuggestionStrip", "(", ")", ";", "latinIme", ".", "mInputLogic", ".", "performUpdateSuggestionStripSync", "(", "latinIme", ".", "mSettings", ".", "getCurrent", "(", ")", ",", "msg", ".", "arg1", "/* inputStyle */", ")", ";", "break", ";", "case", "MSG_UPDATE_SHIFT_STATE", ":", "switcher", ".", "requestUpdatingShiftState", "(", "latinIme", ".", "getCurrentAutoCapsState", "(", ")", ",", "latinIme", ".", "getCurrentRecapitalizeState", "(", ")", ")", ";", "break", ";", "case", "MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP", ":", "if", "(", "msg", ".", "arg1", "==", "ARG1_NOT_GESTURE_INPUT", ")", "{", "final", "SuggestedWords", "suggestedWords", "=", "(", "SuggestedWords", ")", "msg", ".", "obj", ";", "latinIme", ".", "showSuggestionStrip", "(", "suggestedWords", ")", ";", "}", "else", "{", "latinIme", ".", "showGesturePreviewAndSuggestionStrip", "(", "(", "SuggestedWords", ")", "msg", ".", "obj", ",", "msg", ".", "arg1", "==", "ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT", ")", ";", "}", "break", ";", "case", "MSG_RESUME_SUGGESTIONS", ":", "latinIme", ".", "mInputLogic", ".", "restartSuggestionsOnWordTouchedByCursor", "(", "latinIme", ".", "mSettings", ".", "getCurrent", "(", ")", ",", "false", "/* forStartInput */", ",", "latinIme", ".", "mKeyboardSwitcher", ".", "getCurrentKeyboardScriptId", "(", ")", ")", ";", "break", ";", "case", "MSG_RESUME_SUGGESTIONS_FOR_START_INPUT", ":", "latinIme", ".", "mInputLogic", ".", "restartSuggestionsOnWordTouchedByCursor", "(", "latinIme", ".", "mSettings", ".", "getCurrent", "(", ")", ",", "true", "/* forStartInput */", ",", "latinIme", ".", "mKeyboardSwitcher", ".", "getCurrentKeyboardScriptId", "(", ")", ")", ";", "break", ";", "case", "MSG_REOPEN_DICTIONARIES", ":", "postWaitForDictionaryLoad", "(", ")", ";", "latinIme", ".", "resetDictionaryFacilitatorIfNecessary", "(", ")", ";", "break", ";", "case", "MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED", ":", "final", "SuggestedWords", "suggestedWords", "=", "(", "SuggestedWords", ")", "msg", ".", "obj", ";", "latinIme", ".", "mInputLogic", ".", "onUpdateTailBatchInputCompleted", "(", "latinIme", ".", "mSettings", ".", "getCurrent", "(", ")", ",", "suggestedWords", ",", "latinIme", ".", "mKeyboardSwitcher", ")", ";", "latinIme", ".", "onTailBatchInputResultShown", "(", "suggestedWords", ")", ";", "break", ";", "case", "MSG_RESET_CACHES", ":", "final", "SettingsValues", "settingsValues", "=", "latinIme", ".", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "latinIme", ".", "mInputLogic", ".", "retryResetCachesAndReturnSuccess", "(", "msg", ".", "arg1", "==", "ARG1_TRUE", "/* tryResumeSuggestions */", ",", "msg", ".", "arg2", "/* remainingTries */", ",", "this", "/* handler */", ")", ")", "{", "latinIme", ".", "mKeyboardSwitcher", ".", "loadKeyboard", "(", "latinIme", ".", "getCurrentInputEditorInfo", "(", ")", ",", "settingsValues", ",", "latinIme", ".", "getCurrentAutoCapsState", "(", ")", ",", "latinIme", ".", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "break", ";", "case", "MSG_WAIT_FOR_DICTIONARY_LOAD", ":", "Log", ".", "i", "(", "TAG", ",", "\"", "Timeout waiting for dictionary load", "\"", ")", ";", "break", ";", "case", "MSG_DEALLOCATE_MEMORY", ":", "latinIme", ".", "deallocateMemory", "(", ")", ";", "break", ";", "case", "MSG_SWITCH_LANGUAGE_AUTOMATICALLY", ":", "latinIme", ".", "switchLanguage", "(", "(", "InputMethodSubtype", ")", "msg", ".", "obj", ")", ";", "break", ";", "}", "}", "public", "void", "postUpdateSuggestionStrip", "(", "final", "int", "inputStyle", ")", "{", "sendMessageDelayed", "(", "obtainMessage", "(", "MSG_UPDATE_SUGGESTION_STRIP", ",", "inputStyle", ",", "0", "/* ignored */", ")", ",", "mDelayInMillisecondsToUpdateSuggestions", ")", ";", "}", "public", "void", "postReopenDictionaries", "(", ")", "{", "sendMessage", "(", "obtainMessage", "(", "MSG_REOPEN_DICTIONARIES", ")", ")", ";", "}", "private", "void", "postResumeSuggestionsInternal", "(", "final", "boolean", "shouldDelay", ",", "final", "boolean", "forStartInput", ")", "{", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "latinIme", ".", "mSettings", ".", "getCurrent", "(", ")", ".", "isSuggestionsEnabledPerUserSettings", "(", ")", ")", "{", "return", ";", "}", "removeMessages", "(", "MSG_RESUME_SUGGESTIONS", ")", ";", "removeMessages", "(", "MSG_RESUME_SUGGESTIONS_FOR_START_INPUT", ")", ";", "final", "int", "message", "=", "forStartInput", "?", "MSG_RESUME_SUGGESTIONS_FOR_START_INPUT", ":", "MSG_RESUME_SUGGESTIONS", ";", "if", "(", "shouldDelay", ")", "{", "sendMessageDelayed", "(", "obtainMessage", "(", "message", ")", ",", "mDelayInMillisecondsToUpdateSuggestions", ")", ";", "}", "else", "{", "sendMessage", "(", "obtainMessage", "(", "message", ")", ")", ";", "}", "}", "public", "void", "postResumeSuggestions", "(", "final", "boolean", "shouldDelay", ")", "{", "postResumeSuggestionsInternal", "(", "shouldDelay", ",", "false", "/* forStartInput */", ")", ";", "}", "public", "void", "postResumeSuggestionsForStartInput", "(", "final", "boolean", "shouldDelay", ")", "{", "postResumeSuggestionsInternal", "(", "shouldDelay", ",", "true", "/* forStartInput */", ")", ";", "}", "public", "void", "postResetCaches", "(", "final", "boolean", "tryResumeSuggestions", ",", "final", "int", "remainingTries", ")", "{", "removeMessages", "(", "MSG_RESET_CACHES", ")", ";", "sendMessage", "(", "obtainMessage", "(", "MSG_RESET_CACHES", ",", "tryResumeSuggestions", "?", "1", ":", "0", ",", "remainingTries", ",", "null", ")", ")", ";", "}", "public", "void", "postWaitForDictionaryLoad", "(", ")", "{", "sendMessageDelayed", "(", "obtainMessage", "(", "MSG_WAIT_FOR_DICTIONARY_LOAD", ")", ",", "DELAY_WAIT_FOR_DICTIONARY_LOAD_MILLIS", ")", ";", "}", "public", "void", "cancelWaitForDictionaryLoad", "(", ")", "{", "removeMessages", "(", "MSG_WAIT_FOR_DICTIONARY_LOAD", ")", ";", "}", "public", "boolean", "hasPendingWaitForDictionaryLoad", "(", ")", "{", "return", "hasMessages", "(", "MSG_WAIT_FOR_DICTIONARY_LOAD", ")", ";", "}", "public", "void", "cancelUpdateSuggestionStrip", "(", ")", "{", "removeMessages", "(", "MSG_UPDATE_SUGGESTION_STRIP", ")", ";", "}", "public", "boolean", "hasPendingUpdateSuggestions", "(", ")", "{", "return", "hasMessages", "(", "MSG_UPDATE_SUGGESTION_STRIP", ")", ";", "}", "public", "boolean", "hasPendingReopenDictionaries", "(", ")", "{", "return", "hasMessages", "(", "MSG_REOPEN_DICTIONARIES", ")", ";", "}", "public", "void", "postUpdateShiftState", "(", ")", "{", "removeMessages", "(", "MSG_UPDATE_SHIFT_STATE", ")", ";", "sendMessageDelayed", "(", "obtainMessage", "(", "MSG_UPDATE_SHIFT_STATE", ")", ",", "mDelayInMillisecondsToUpdateShiftState", ")", ";", "}", "public", "void", "postDeallocateMemory", "(", ")", "{", "sendMessageDelayed", "(", "obtainMessage", "(", "MSG_DEALLOCATE_MEMORY", ")", ",", "DELAY_DEALLOCATE_MEMORY_MILLIS", ")", ";", "}", "public", "void", "cancelDeallocateMemory", "(", ")", "{", "removeMessages", "(", "MSG_DEALLOCATE_MEMORY", ")", ";", "}", "public", "boolean", "hasPendingDeallocateMemory", "(", ")", "{", "return", "hasMessages", "(", "MSG_DEALLOCATE_MEMORY", ")", ";", "}", "@", "UsedForTesting", "public", "void", "removeAllMessages", "(", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "MSG_LAST", ";", "++", "i", ")", "{", "removeMessages", "(", "i", ")", ";", "}", "}", "public", "void", "showGesturePreviewAndSuggestionStrip", "(", "final", "SuggestedWords", "suggestedWords", ",", "final", "boolean", "dismissGestureFloatingPreviewText", ")", "{", "removeMessages", "(", "MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP", ")", ";", "final", "int", "arg1", "=", "dismissGestureFloatingPreviewText", "?", "ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT", ":", "ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT", ";", "obtainMessage", "(", "MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP", ",", "arg1", ",", "ARG2_UNUSED", ",", "suggestedWords", ")", ".", "sendToTarget", "(", ")", ";", "}", "public", "void", "showSuggestionStrip", "(", "final", "SuggestedWords", "suggestedWords", ")", "{", "removeMessages", "(", "MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP", ")", ";", "obtainMessage", "(", "MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP", ",", "ARG1_NOT_GESTURE_INPUT", ",", "ARG2_UNUSED", ",", "suggestedWords", ")", ".", "sendToTarget", "(", ")", ";", "}", "public", "void", "showTailBatchInputResult", "(", "final", "SuggestedWords", "suggestedWords", ")", "{", "obtainMessage", "(", "MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED", ",", "suggestedWords", ")", ".", "sendToTarget", "(", ")", ";", "}", "public", "void", "postSwitchLanguage", "(", "final", "InputMethodSubtype", "subtype", ")", "{", "obtainMessage", "(", "MSG_SWITCH_LANGUAGE_AUTOMATICALLY", ",", "subtype", ")", ".", "sendToTarget", "(", ")", ";", "}", "private", "boolean", "mIsOrientationChanging", ";", "private", "boolean", "mPendingSuccessiveImsCallback", ";", "private", "boolean", "mHasPendingStartInput", ";", "private", "boolean", "mHasPendingFinishInputView", ";", "private", "boolean", "mHasPendingFinishInput", ";", "private", "EditorInfo", "mAppliedEditorInfo", ";", "public", "void", "startOrientationChanging", "(", ")", "{", "removeMessages", "(", "MSG_PENDING_IMS_CALLBACK", ")", ";", "resetPendingImsCallback", "(", ")", ";", "mIsOrientationChanging", "=", "true", ";", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "==", "null", ")", "{", "return", ";", "}", "if", "(", "latinIme", ".", "isInputViewShown", "(", ")", ")", "{", "latinIme", ".", "mKeyboardSwitcher", ".", "saveKeyboardState", "(", ")", ";", "}", "}", "private", "void", "resetPendingImsCallback", "(", ")", "{", "mHasPendingFinishInputView", "=", "false", ";", "mHasPendingFinishInput", "=", "false", ";", "mHasPendingStartInput", "=", "false", ";", "}", "private", "void", "executePendingImsCallback", "(", "final", "LatinIME", "latinIme", ",", "final", "EditorInfo", "editorInfo", ",", "boolean", "restarting", ")", "{", "if", "(", "mHasPendingFinishInputView", ")", "{", "latinIme", ".", "onFinishInputViewInternal", "(", "mHasPendingFinishInput", ")", ";", "}", "if", "(", "mHasPendingFinishInput", ")", "{", "latinIme", ".", "onFinishInputInternal", "(", ")", ";", "}", "if", "(", "mHasPendingStartInput", ")", "{", "latinIme", ".", "onStartInputInternal", "(", "editorInfo", ",", "restarting", ")", ";", "}", "resetPendingImsCallback", "(", ")", ";", "}", "public", "void", "onStartInput", "(", "final", "EditorInfo", "editorInfo", ",", "final", "boolean", "restarting", ")", "{", "if", "(", "hasMessages", "(", "MSG_PENDING_IMS_CALLBACK", ")", ")", "{", "mHasPendingStartInput", "=", "true", ";", "}", "else", "{", "if", "(", "mIsOrientationChanging", "&&", "restarting", ")", "{", "mIsOrientationChanging", "=", "false", ";", "mPendingSuccessiveImsCallback", "=", "true", ";", "}", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "!=", "null", ")", "{", "executePendingImsCallback", "(", "latinIme", ",", "editorInfo", ",", "restarting", ")", ";", "latinIme", ".", "onStartInputInternal", "(", "editorInfo", ",", "restarting", ")", ";", "}", "}", "}", "public", "void", "onStartInputView", "(", "final", "EditorInfo", "editorInfo", ",", "final", "boolean", "restarting", ")", "{", "if", "(", "hasMessages", "(", "MSG_PENDING_IMS_CALLBACK", ")", "&&", "KeyboardId", ".", "equivalentEditorInfoForKeyboard", "(", "editorInfo", ",", "mAppliedEditorInfo", ")", ")", "{", "resetPendingImsCallback", "(", ")", ";", "}", "else", "{", "if", "(", "mPendingSuccessiveImsCallback", ")", "{", "mPendingSuccessiveImsCallback", "=", "false", ";", "resetPendingImsCallback", "(", ")", ";", "sendMessageDelayed", "(", "obtainMessage", "(", "MSG_PENDING_IMS_CALLBACK", ")", ",", "PENDING_IMS_CALLBACK_DURATION_MILLIS", ")", ";", "}", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "!=", "null", ")", "{", "executePendingImsCallback", "(", "latinIme", ",", "editorInfo", ",", "restarting", ")", ";", "latinIme", ".", "onStartInputViewInternal", "(", "editorInfo", ",", "restarting", ")", ";", "mAppliedEditorInfo", "=", "editorInfo", ";", "}", "cancelDeallocateMemory", "(", ")", ";", "}", "}", "public", "void", "onFinishInputView", "(", "final", "boolean", "finishingInput", ")", "{", "if", "(", "hasMessages", "(", "MSG_PENDING_IMS_CALLBACK", ")", ")", "{", "mHasPendingFinishInputView", "=", "true", ";", "}", "else", "{", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "!=", "null", ")", "{", "latinIme", ".", "onFinishInputViewInternal", "(", "finishingInput", ")", ";", "mAppliedEditorInfo", "=", "null", ";", "}", "if", "(", "!", "hasPendingDeallocateMemory", "(", ")", ")", "{", "postDeallocateMemory", "(", ")", ";", "}", "}", "}", "public", "void", "onFinishInput", "(", ")", "{", "if", "(", "hasMessages", "(", "MSG_PENDING_IMS_CALLBACK", ")", ")", "{", "mHasPendingFinishInput", "=", "true", ";", "}", "else", "{", "final", "LatinIME", "latinIme", "=", "getOwnerInstance", "(", ")", ";", "if", "(", "latinIme", "!=", "null", ")", "{", "executePendingImsCallback", "(", "latinIme", ",", "null", ",", "false", ")", ";", "latinIme", ".", "onFinishInputInternal", "(", ")", ";", "}", "}", "}", "}", "static", "final", "class", "SubtypeState", "{", "private", "InputMethodSubtype", "mLastActiveSubtype", ";", "private", "boolean", "mCurrentSubtypeHasBeenUsed", ";", "public", "void", "setCurrentSubtypeHasBeenUsed", "(", ")", "{", "mCurrentSubtypeHasBeenUsed", "=", "true", ";", "}", "public", "void", "switchSubtype", "(", "final", "IBinder", "token", ",", "final", "RichInputMethodManager", "richImm", ")", "{", "final", "InputMethodSubtype", "currentSubtype", "=", "richImm", ".", "getInputMethodManager", "(", ")", ".", "getCurrentInputMethodSubtype", "(", ")", ";", "final", "InputMethodSubtype", "lastActiveSubtype", "=", "mLastActiveSubtype", ";", "final", "boolean", "currentSubtypeHasBeenUsed", "=", "mCurrentSubtypeHasBeenUsed", ";", "if", "(", "currentSubtypeHasBeenUsed", ")", "{", "mLastActiveSubtype", "=", "currentSubtype", ";", "mCurrentSubtypeHasBeenUsed", "=", "false", ";", "}", "if", "(", "currentSubtypeHasBeenUsed", "&&", "richImm", ".", "checkIfSubtypeBelongsToThisImeAndEnabled", "(", "lastActiveSubtype", ")", "&&", "!", "currentSubtype", ".", "equals", "(", "lastActiveSubtype", ")", ")", "{", "richImm", ".", "setInputMethodAndSubtype", "(", "token", ",", "lastActiveSubtype", ")", ";", "return", ";", "}", "richImm", ".", "switchToNextInputMethod", "(", "token", ",", "true", "/* onlyCurrentIme */", ")", ";", "}", "}", "static", "{", "JniUtils", ".", "loadNativeLibrary", "(", ")", ";", "}", "public", "LatinIME", "(", ")", "{", "super", "(", ")", ";", "mSettings", "=", "Settings", ".", "getInstance", "(", ")", ";", "mKeyboardSwitcher", "=", "KeyboardSwitcher", ".", "getInstance", "(", ")", ";", "mStatsUtilsManager", "=", "StatsUtilsManager", ".", "getInstance", "(", ")", ";", "mIsHardwareAcceleratedDrawingEnabled", "=", "InputMethodServiceCompatUtils", ".", "enableHardwareAcceleration", "(", "this", ")", ";", "Log", ".", "i", "(", "TAG", ",", "\"", "Hardware accelerated drawing: ", "\"", "+", "mIsHardwareAcceleratedDrawingEnabled", ")", ";", "}", "@", "Override", "public", "void", "onCreate", "(", ")", "{", "storageContainer", "=", "getConfigValue", "(", "this", ",", "\"", "storageContainer", "\"", ")", ";", "storageConnectionString", "=", "getConfigValue", "(", "this", ",", "\"", "storageConnectionString", "\"", ")", ";", "densX", "=", "getResources", "(", ")", ".", "getDisplayMetrics", "(", ")", ".", "xdpi", ";", "densY", "=", "getResources", "(", ")", ".", "getDisplayMetrics", "(", ")", ".", "ydpi", ";", "myDB", "=", "new", "DatabaseHelper", "(", "this", ")", ";", "mNotificationHelper", "=", "new", "NotificationHelper", "(", "this", ")", ";", "nb", "=", "new", "NotificationCompat", ".", "Builder", "(", "getApplicationContext", "(", ")", ",", "\"", "TypeOfMoodChannelID", "\"", ")", ";", "userID", "=", "android", ".", "provider", ".", "Settings", ".", "System", ".", "getString", "(", "this", ".", "getContentResolver", "(", ")", ",", "android", ".", "provider", ".", "Settings", ".", "Secure", ".", "ANDROID_ID", ")", ";", "Settings", ".", "init", "(", "this", ")", ";", "DebugFlags", ".", "init", "(", "PreferenceManager", ".", "getDefaultSharedPreferences", "(", "this", ")", ")", ";", "RichInputMethodManager", ".", "init", "(", "this", ")", ";", "mRichImm", "=", "RichInputMethodManager", ".", "getInstance", "(", ")", ";", "KeyboardSwitcher", ".", "init", "(", "this", ")", ";", "AudioAndHapticFeedbackManager", ".", "init", "(", "this", ")", ";", "AccessibilityUtils", ".", "init", "(", "this", ")", ";", "mStatsUtilsManager", ".", "onCreate", "(", "this", "/* context */", ",", "mDictionaryFacilitator", ")", ";", "super", ".", "onCreate", "(", ")", ";", "mHandler", ".", "onCreate", "(", ")", ";", "loadSettings", "(", ")", ";", "resetDictionaryFacilitatorIfNecessary", "(", ")", ";", "final", "IntentFilter", "filter", "=", "new", "IntentFilter", "(", ")", ";", "filter", ".", "addAction", "(", "AudioManager", ".", "RINGER_MODE_CHANGED_ACTION", ")", ";", "registerReceiver", "(", "mRingerModeChangeReceiver", ",", "filter", ")", ";", "final", "IntentFilter", "packageFilter", "=", "new", "IntentFilter", "(", ")", ";", "packageFilter", ".", "addAction", "(", "Intent", ".", "ACTION_PACKAGE_ADDED", ")", ";", "packageFilter", ".", "addAction", "(", "Intent", ".", "ACTION_PACKAGE_REMOVED", ")", ";", "packageFilter", ".", "addDataScheme", "(", "SCHEME_PACKAGE", ")", ";", "registerReceiver", "(", "mDictionaryPackInstallReceiver", ",", "packageFilter", ")", ";", "final", "IntentFilter", "newDictFilter", "=", "new", "IntentFilter", "(", ")", ";", "newDictFilter", ".", "addAction", "(", "DictionaryPackConstants", ".", "NEW_DICTIONARY_INTENT_ACTION", ")", ";", "registerReceiver", "(", "mDictionaryPackInstallReceiver", ",", "newDictFilter", ")", ";", "final", "IntentFilter", "dictDumpFilter", "=", "new", "IntentFilter", "(", ")", ";", "dictDumpFilter", ".", "addAction", "(", "DictionaryDumpBroadcastReceiver", ".", "DICTIONARY_DUMP_INTENT_ACTION", ")", ";", "registerReceiver", "(", "mDictionaryDumpBroadcastReceiver", ",", "dictDumpFilter", ")", ";", "StatsUtils", ".", "onCreate", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "mRichImm", ")", ";", "}", "@", "UsedForTesting", "void", "loadSettings", "(", ")", "{", "final", "Locale", "locale", "=", "mRichImm", ".", "getCurrentSubtypeLocale", "(", ")", ";", "final", "EditorInfo", "editorInfo", "=", "getCurrentInputEditorInfo", "(", ")", ";", "final", "InputAttributes", "inputAttributes", "=", "new", "InputAttributes", "(", "editorInfo", ",", "isFullscreenMode", "(", ")", ",", "getPackageName", "(", ")", ")", ";", "mSettings", ".", "loadSettings", "(", "this", ",", "locale", ",", "inputAttributes", ")", ";", "final", "SettingsValues", "currentSettingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "AudioAndHapticFeedbackManager", ".", "getInstance", "(", ")", ".", "onSettingsChanged", "(", "currentSettingsValues", ")", ";", "if", "(", "!", "mHandler", ".", "hasPendingReopenDictionaries", "(", ")", ")", "{", "resetDictionaryFacilitator", "(", "locale", ")", ";", "}", "refreshPersonalizationDictionarySession", "(", "currentSettingsValues", ")", ";", "resetDictionaryFacilitatorIfNecessary", "(", ")", ";", "mStatsUtilsManager", ".", "onLoadSettings", "(", "this", "/* context */", ",", "currentSettingsValues", ")", ";", "}", "private", "void", "refreshPersonalizationDictionarySession", "(", "final", "SettingsValues", "currentSettingsValues", ")", "{", "if", "(", "!", "currentSettingsValues", ".", "mUsePersonalizedDicts", ")", "{", "PersonalizationHelper", ".", "removeAllUserHistoryDictionaries", "(", "this", ")", ";", "mDictionaryFacilitator", ".", "clearUserHistoryDictionary", "(", "this", ")", ";", "}", "}", "@", "Override", "public", "void", "onUpdateMainDictionaryAvailability", "(", "final", "boolean", "isMainDictionaryAvailable", ")", "{", "final", "MainKeyboardView", "mainKeyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "if", "(", "mainKeyboardView", "!=", "null", ")", "{", "mainKeyboardView", ".", "setMainDictionaryAvailability", "(", "isMainDictionaryAvailable", ")", ";", "}", "if", "(", "mHandler", ".", "hasPendingWaitForDictionaryLoad", "(", ")", ")", "{", "mHandler", ".", "cancelWaitForDictionaryLoad", "(", ")", ";", "mHandler", ".", "postResumeSuggestions", "(", "false", "/* shouldDelay */", ")", ";", "}", "}", "void", "resetDictionaryFacilitatorIfNecessary", "(", ")", "{", "final", "Locale", "subtypeSwitcherLocale", "=", "mRichImm", ".", "getCurrentSubtypeLocale", "(", ")", ";", "final", "Locale", "subtypeLocale", ";", "if", "(", "subtypeSwitcherLocale", "==", "null", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "System is reporting no current subtype.", "\"", ")", ";", "subtypeLocale", "=", "getResources", "(", ")", ".", "getConfiguration", "(", ")", ".", "locale", ";", "}", "else", "{", "subtypeLocale", "=", "subtypeSwitcherLocale", ";", "}", "if", "(", "mDictionaryFacilitator", ".", "isForLocale", "(", "subtypeLocale", ")", "&&", "mDictionaryFacilitator", ".", "isForAccount", "(", "mSettings", ".", "getCurrent", "(", ")", ".", "mAccount", ")", ")", "{", "return", ";", "}", "resetDictionaryFacilitator", "(", "subtypeLocale", ")", ";", "}", "/**\n * Reset the facilitator by loading dictionaries for the given locale and\n * the current settings values.\n *\n * @param locale the locale\n */", "private", "void", "resetDictionaryFacilitator", "(", "final", "Locale", "locale", ")", "{", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "mDictionaryFacilitator", ".", "resetDictionaries", "(", "this", "/* context */", ",", "locale", ",", "settingsValues", ".", "mUseContactsDict", ",", "settingsValues", ".", "mUsePersonalizedDicts", ",", "false", "/* forceReloadMainDictionary */", ",", "settingsValues", ".", "mAccount", ",", "\"", "\"", "/* dictNamePrefix */", ",", "this", "/* DictionaryInitializationListener */", ")", ";", "if", "(", "settingsValues", ".", "mAutoCorrectionEnabledPerUserSettings", ")", "{", "mInputLogic", ".", "mSuggest", ".", "setAutoCorrectionThreshold", "(", "settingsValues", ".", "mAutoCorrectionThreshold", ")", ";", "}", "mInputLogic", ".", "mSuggest", ".", "setPlausibilityThreshold", "(", "settingsValues", ".", "mPlausibilityThreshold", ")", ";", "}", "/**\n * Reset suggest by loading the main dictionary of the current locale.\n */", "/* package private */", "void", "resetSuggestMainDict", "(", ")", "{", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "mDictionaryFacilitator", ".", "resetDictionaries", "(", "this", "/* context */", ",", "mDictionaryFacilitator", ".", "getLocale", "(", ")", ",", "settingsValues", ".", "mUseContactsDict", ",", "settingsValues", ".", "mUsePersonalizedDicts", ",", "true", "/* forceReloadMainDictionary */", ",", "settingsValues", ".", "mAccount", ",", "\"", "\"", "/* dictNamePrefix */", ",", "this", "/* DictionaryInitializationListener */", ")", ";", "}", "@", "Override", "public", "void", "onDestroy", "(", ")", "{", "mDictionaryFacilitator", ".", "closeDictionaries", "(", ")", ";", "mSettings", ".", "onDestroy", "(", ")", ";", "unregisterReceiver", "(", "mRingerModeChangeReceiver", ")", ";", "unregisterReceiver", "(", "mDictionaryPackInstallReceiver", ")", ";", "unregisterReceiver", "(", "mDictionaryDumpBroadcastReceiver", ")", ";", "mStatsUtilsManager", ".", "onDestroy", "(", "this", "/* context */", ")", ";", "if", "(", "myDB", "!=", "null", ")", "{", "myDB", ".", "close", "(", ")", ";", "}", "super", ".", "onDestroy", "(", ")", ";", "}", "@", "UsedForTesting", "public", "void", "recycle", "(", ")", "{", "unregisterReceiver", "(", "mDictionaryPackInstallReceiver", ")", ";", "unregisterReceiver", "(", "mDictionaryDumpBroadcastReceiver", ")", ";", "unregisterReceiver", "(", "mRingerModeChangeReceiver", ")", ";", "mInputLogic", ".", "recycle", "(", ")", ";", "}", "private", "boolean", "isImeSuppressedByHardwareKeyboard", "(", ")", "{", "final", "KeyboardSwitcher", "switcher", "=", "KeyboardSwitcher", ".", "getInstance", "(", ")", ";", "return", "!", "onEvaluateInputViewShown", "(", ")", "&&", "switcher", ".", "isImeSuppressedByHardwareKeyboard", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "switcher", ".", "getKeyboardSwitchState", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onConfigurationChanged", "(", "final", "Configuration", "conf", ")", "{", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "settingsValues", ".", "mDisplayOrientation", "!=", "conf", ".", "orientation", ")", "{", "mHandler", ".", "startOrientationChanging", "(", ")", ";", "mInputLogic", ".", "onOrientationChange", "(", "mSettings", ".", "getCurrent", "(", ")", ")", ";", "}", "if", "(", "settingsValues", ".", "mHasHardwareKeyboard", "!=", "Settings", ".", "readHasHardwareKeyboard", "(", "conf", ")", ")", "{", "loadSettings", "(", ")", ";", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "isImeSuppressedByHardwareKeyboard", "(", ")", ")", "{", "cleanupInternalStateForFinishInput", "(", ")", ";", "}", "}", "super", ".", "onConfigurationChanged", "(", "conf", ")", ";", "}", "@", "Override", "public", "View", "onCreateInputView", "(", ")", "{", "StatsUtils", ".", "onCreateInputView", "(", ")", ";", "return", "mKeyboardSwitcher", ".", "onCreateInputView", "(", "mIsHardwareAcceleratedDrawingEnabled", ")", ";", "}", "@", "Override", "public", "void", "setInputView", "(", "final", "View", "view", ")", "{", "super", ".", "setInputView", "(", "view", ")", ";", "mInputView", "=", "view", ";", "mInsetsUpdater", "=", "ViewOutlineProviderCompatUtils", ".", "setInsetsOutlineProvider", "(", "view", ")", ";", "updateSoftInputWindowLayoutParameters", "(", ")", ";", "mSuggestionStripView", "=", "(", "SuggestionStripView", ")", "view", ".", "findViewById", "(", "R", ".", "id", ".", "suggestion_strip_view", ")", ";", "if", "(", "hasSuggestionStripView", "(", ")", ")", "{", "mSuggestionStripView", ".", "setListener", "(", "this", ",", "view", ")", ";", "}", "}", "@", "Override", "public", "void", "setCandidatesView", "(", "final", "View", "view", ")", "{", "}", "@", "Override", "public", "void", "onStartInput", "(", "final", "EditorInfo", "editorInfo", ",", "final", "boolean", "restarting", ")", "{", "mHandler", ".", "onStartInput", "(", "editorInfo", ",", "restarting", ")", ";", "}", "@", "Override", "public", "void", "onStartInputView", "(", "final", "EditorInfo", "editorInfo", ",", "final", "boolean", "restarting", ")", "{", "mHandler", ".", "onStartInputView", "(", "editorInfo", ",", "restarting", ")", ";", "mStatsUtilsManager", ".", "onStartInputView", "(", ")", ";", "}", "@", "Override", "public", "void", "onFinishInputView", "(", "final", "boolean", "finishingInput", ")", "{", "if", "(", "sessionData", "!=", "null", ")", "{", "sessionData", ".", "StopDateTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "DataStoreAsyncTaskParams", "params", "=", "new", "DataStoreAsyncTaskParams", "(", "sessionData", ",", "rawX", ",", "rawY", ")", ";", "DataStoreAsyncTask", "task", "=", "new", "DataStoreAsyncTask", "(", "getApplicationContext", "(", ")", ")", ";", "task", ".", "execute", "(", "params", ")", ";", "rawX", ".", "clear", "(", ")", ";", "rawY", ".", "clear", "(", ")", ";", "sessionData", "=", "null", ";", "}", "StatsUtils", ".", "onFinishInputView", "(", ")", ";", "mHandler", ".", "onFinishInputView", "(", "finishingInput", ")", ";", "mStatsUtilsManager", ".", "onFinishInputView", "(", ")", ";", "mGestureConsumer", "=", "GestureConsumer", ".", "NULL_GESTURE_CONSUMER", ";", "}", "@", "Override", "public", "void", "onFinishInput", "(", ")", "{", "mHandler", ".", "onFinishInput", "(", ")", ";", "}", "@", "Override", "public", "void", "onCurrentInputMethodSubtypeChanged", "(", "final", "InputMethodSubtype", "subtype", ")", "{", "InputMethodSubtype", "oldSubtype", "=", "mRichImm", ".", "getCurrentSubtype", "(", ")", ".", "getRawSubtype", "(", ")", ";", "StatsUtils", ".", "onSubtypeChanged", "(", "oldSubtype", ",", "subtype", ")", ";", "mRichImm", ".", "onSubtypeChanged", "(", "subtype", ")", ";", "mInputLogic", ".", "onSubtypeChanged", "(", "SubtypeLocaleUtils", ".", "getCombiningRulesExtraValue", "(", "subtype", ")", ",", "mSettings", ".", "getCurrent", "(", ")", ")", ";", "loadKeyboard", "(", ")", ";", "}", "void", "onStartInputInternal", "(", "final", "EditorInfo", "editorInfo", ",", "final", "boolean", "restarting", ")", "{", "super", ".", "onStartInput", "(", "editorInfo", ",", "restarting", ")", ";", "final", "Locale", "primaryHintLocale", "=", "EditorInfoCompatUtils", ".", "getPrimaryHintLocale", "(", "editorInfo", ")", ";", "if", "(", "primaryHintLocale", "==", "null", ")", "{", "return", ";", "}", "final", "InputMethodSubtype", "newSubtype", "=", "mRichImm", ".", "findSubtypeByLocale", "(", "primaryHintLocale", ")", ";", "if", "(", "newSubtype", "==", "null", "||", "newSubtype", ".", "equals", "(", "mRichImm", ".", "getCurrentSubtype", "(", ")", ".", "getRawSubtype", "(", ")", ")", ")", "{", "return", ";", "}", "mHandler", ".", "postSwitchLanguage", "(", "newSubtype", ")", ";", "}", "@", "SuppressWarnings", "(", "\"", "deprecation", "\"", ")", "void", "onStartInputViewInternal", "(", "final", "EditorInfo", "editorInfo", ",", "final", "boolean", "restarting", ")", "{", "super", ".", "onStartInputView", "(", "editorInfo", ",", "restarting", ")", ";", "mDictionaryFacilitator", ".", "onStartInput", "(", ")", ";", "mGestureConsumer", "=", "GestureConsumer", ".", "NULL_GESTURE_CONSUMER", ";", "mRichImm", ".", "refreshSubtypeCaches", "(", ")", ";", "final", "KeyboardSwitcher", "switcher", "=", "mKeyboardSwitcher", ";", "switcher", ".", "updateKeyboardTheme", "(", ")", ";", "final", "MainKeyboardView", "mainKeyboardView", "=", "switcher", ".", "getMainKeyboardView", "(", ")", ";", "SettingsValues", "currentSettingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "editorInfo", "==", "null", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "Null EditorInfo in onStartInputView()", "\"", ")", ";", "if", "(", "DebugFlags", ".", "DEBUG_ENABLED", ")", "{", "throw", "new", "NullPointerException", "(", "\"", "Null EditorInfo in onStartInputView()", "\"", ")", ";", "}", "return", ";", "}", "if", "(", "DebugFlags", ".", "DEBUG_ENABLED", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"", "onStartInputView: editorInfo:", "\"", "+", "String", ".", "format", "(", "\"", "inputType=0x%08x imeOptions=0x%08x", "\"", ",", "editorInfo", ".", "inputType", ",", "editorInfo", ".", "imeOptions", ")", ")", ";", "Log", ".", "d", "(", "TAG", ",", "\"", "All caps = ", "\"", "+", "(", "(", "editorInfo", ".", "inputType", "&", "InputType", ".", "TYPE_TEXT_FLAG_CAP_CHARACTERS", ")", "!=", "0", ")", "+", "\"", ", sentence caps = ", "\"", "+", "(", "(", "editorInfo", ".", "inputType", "&", "InputType", ".", "TYPE_TEXT_FLAG_CAP_SENTENCES", ")", "!=", "0", ")", "+", "\"", ", word caps = ", "\"", "+", "(", "(", "editorInfo", ".", "inputType", "&", "InputType", ".", "TYPE_TEXT_FLAG_CAP_WORDS", ")", "!=", "0", ")", ")", ";", "}", "Log", ".", "i", "(", "TAG", ",", "\"", "Starting input. Cursor position = ", "\"", "+", "editorInfo", ".", "initialSelStart", "+", "\"", ",", "\"", "+", "editorInfo", ".", "initialSelEnd", ")", ";", "if", "(", "InputAttributes", ".", "inPrivateImeOptions", "(", "null", ",", "Constants", ".", "ImeOption", ".", "NO_MICROPHONE_COMPAT", ",", "editorInfo", ")", ")", "{", "Log", ".", "w", "(", "TAG", ",", "\"", "Deprecated private IME option specified: ", "\"", "+", "editorInfo", ".", "privateImeOptions", ")", ";", "Log", ".", "w", "(", "TAG", ",", "\"", "Use ", "\"", "+", "getPackageName", "(", ")", "+", "\"", ".", "\"", "+", "Constants", ".", "ImeOption", ".", "NO_MICROPHONE", "+", "\"", " instead", "\"", ")", ";", "}", "if", "(", "InputAttributes", ".", "inPrivateImeOptions", "(", "getPackageName", "(", ")", ",", "Constants", ".", "ImeOption", ".", "FORCE_ASCII", ",", "editorInfo", ")", ")", "{", "Log", ".", "w", "(", "TAG", ",", "\"", "Deprecated private IME option specified: ", "\"", "+", "editorInfo", ".", "privateImeOptions", ")", ";", "Log", ".", "w", "(", "TAG", ",", "\"", "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead", "\"", ")", ";", "}", "if", "(", "mainKeyboardView", "==", "null", ")", "{", "return", ";", "}", "mGestureConsumer", "=", "GestureConsumer", ".", "newInstance", "(", "editorInfo", ",", "mInputLogic", ".", "getPrivateCommandPerformer", "(", ")", ",", "mRichImm", ".", "getCurrentSubtypeLocale", "(", ")", ",", "switcher", ".", "getKeyboard", "(", ")", ")", ";", "final", "AccessibilityUtils", "accessUtils", "=", "AccessibilityUtils", ".", "getInstance", "(", ")", ";", "if", "(", "accessUtils", ".", "isTouchExplorationEnabled", "(", ")", ")", "{", "accessUtils", ".", "onStartInputViewInternal", "(", "mainKeyboardView", ",", "editorInfo", ",", "restarting", ")", ";", "}", "final", "boolean", "inputTypeChanged", "=", "!", "currentSettingsValues", ".", "isSameInputType", "(", "editorInfo", ")", ";", "final", "boolean", "isDifferentTextField", "=", "!", "restarting", "||", "inputTypeChanged", ";", "StatsUtils", ".", "onStartInputView", "(", "editorInfo", ".", "inputType", ",", "Settings", ".", "getInstance", "(", ")", ".", "getCurrent", "(", ")", ".", "mDisplayOrientation", ",", "!", "isDifferentTextField", ")", ";", "updateFullscreenMode", "(", ")", ";", "final", "boolean", "needToCallLoadKeyboardLater", ";", "final", "Suggest", "suggest", "=", "mInputLogic", ".", "mSuggest", ";", "if", "(", "!", "isImeSuppressedByHardwareKeyboard", "(", ")", ")", "{", "mInputLogic", ".", "startInput", "(", "mRichImm", ".", "getCombiningRulesExtraValueOfCurrentSubtype", "(", ")", ",", "currentSettingsValues", ")", ";", "resetDictionaryFacilitatorIfNecessary", "(", ")", ";", "if", "(", "!", "mInputLogic", ".", "mConnection", ".", "resetCachesUponCursorMoveAndReturnSuccess", "(", "editorInfo", ".", "initialSelStart", ",", "editorInfo", ".", "initialSelEnd", ",", "false", "/* shouldFinishComposition */", ")", ")", "{", "mHandler", ".", "postResetCaches", "(", "isDifferentTextField", ",", "5", "/* remainingTries */", ")", ";", "needToCallLoadKeyboardLater", "=", "true", ";", "}", "else", "{", "mInputLogic", ".", "mConnection", ".", "tryFixLyingCursorPosition", "(", ")", ";", "mHandler", ".", "postResumeSuggestionsForStartInput", "(", "true", "/* shouldDelay */", ")", ";", "needToCallLoadKeyboardLater", "=", "false", ";", "}", "}", "else", "{", "needToCallLoadKeyboardLater", "=", "false", ";", "}", "if", "(", "isDifferentTextField", "||", "!", "currentSettingsValues", ".", "hasSameOrientation", "(", "getResources", "(", ")", ".", "getConfiguration", "(", ")", ")", ")", "{", "loadSettings", "(", ")", ";", "}", "if", "(", "isDifferentTextField", ")", "{", "mainKeyboardView", ".", "closing", "(", ")", ";", "currentSettingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "currentSettingsValues", ".", "mAutoCorrectionEnabledPerUserSettings", ")", "{", "suggest", ".", "setAutoCorrectionThreshold", "(", "currentSettingsValues", ".", "mAutoCorrectionThreshold", ")", ";", "}", "suggest", ".", "setPlausibilityThreshold", "(", "currentSettingsValues", ".", "mPlausibilityThreshold", ")", ";", "switcher", ".", "loadKeyboard", "(", "editorInfo", ",", "currentSettingsValues", ",", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "if", "(", "needToCallLoadKeyboardLater", ")", "{", "switcher", ".", "saveKeyboardState", "(", ")", ";", "}", "}", "else", "if", "(", "restarting", ")", "{", "switcher", ".", "resetKeyboardStateToAlphabet", "(", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "switcher", ".", "requestUpdatingShiftState", "(", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "setNeutralSuggestionStrip", "(", ")", ";", "mHandler", ".", "cancelUpdateSuggestionStrip", "(", ")", ";", "mainKeyboardView", ".", "setMainDictionaryAvailability", "(", "mDictionaryFacilitator", ".", "hasAtLeastOneInitializedMainDictionary", "(", ")", ")", ";", "mainKeyboardView", ".", "setKeyPreviewPopupEnabled", "(", "currentSettingsValues", ".", "mKeyPreviewPopupOn", ",", "currentSettingsValues", ".", "mKeyPreviewPopupDismissDelay", ")", ";", "mainKeyboardView", ".", "setSlidingKeyInputPreviewEnabled", "(", "currentSettingsValues", ".", "mSlidingKeyInputPreviewEnabled", ")", ";", "mainKeyboardView", ".", "setGestureHandlingEnabledByUser", "(", "currentSettingsValues", ".", "mGestureInputEnabled", ",", "currentSettingsValues", ".", "mGestureTrailEnabled", ",", "currentSettingsValues", ".", "mGestureFloatingPreviewTextEnabled", ")", ";", "if", "(", "TRACE", ")", "Debug", ".", "startMethodTracing", "(", "\"", "/data/trace/latinime", "\"", ")", ";", "}", "@", "Override", "public", "void", "onWindowShown", "(", ")", "{", "super", ".", "onWindowShown", "(", ")", ";", "setNavigationBarVisibility", "(", "isInputViewShown", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onWindowHidden", "(", ")", "{", "super", ".", "onWindowHidden", "(", ")", ";", "final", "MainKeyboardView", "mainKeyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "if", "(", "mainKeyboardView", "!=", "null", ")", "{", "mainKeyboardView", ".", "closing", "(", ")", ";", "}", "setNavigationBarVisibility", "(", "false", ")", ";", "}", "void", "onFinishInputInternal", "(", ")", "{", "super", ".", "onFinishInput", "(", ")", ";", "mDictionaryFacilitator", ".", "onFinishInput", "(", "this", ")", ";", "final", "MainKeyboardView", "mainKeyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "if", "(", "mainKeyboardView", "!=", "null", ")", "{", "mainKeyboardView", ".", "closing", "(", ")", ";", "}", "}", "void", "onFinishInputViewInternal", "(", "final", "boolean", "finishingInput", ")", "{", "super", ".", "onFinishInputView", "(", "finishingInput", ")", ";", "cleanupInternalStateForFinishInput", "(", ")", ";", "}", "private", "void", "cleanupInternalStateForFinishInput", "(", ")", "{", "mHandler", ".", "cancelUpdateSuggestionStrip", "(", ")", ";", "mInputLogic", ".", "finishInput", "(", ")", ";", "}", "protected", "void", "deallocateMemory", "(", ")", "{", "mKeyboardSwitcher", ".", "deallocateMemory", "(", ")", ";", "}", "@", "Override", "public", "void", "onUpdateSelection", "(", "final", "int", "oldSelStart", ",", "final", "int", "oldSelEnd", ",", "final", "int", "newSelStart", ",", "final", "int", "newSelEnd", ",", "final", "int", "composingSpanStart", ",", "final", "int", "composingSpanEnd", ")", "{", "super", ".", "onUpdateSelection", "(", "oldSelStart", ",", "oldSelEnd", ",", "newSelStart", ",", "newSelEnd", ",", "composingSpanStart", ",", "composingSpanEnd", ")", ";", "if", "(", "DebugFlags", ".", "DEBUG_ENABLED", ")", "{", "Log", ".", "i", "(", "TAG", ",", "\"", "onUpdateSelection: oss=", "\"", "+", "oldSelStart", "+", "\"", ", ose=", "\"", "+", "oldSelEnd", "+", "\"", ", nss=", "\"", "+", "newSelStart", "+", "\"", ", nse=", "\"", "+", "newSelEnd", "+", "\"", ", cs=", "\"", "+", "composingSpanStart", "+", "\"", ", ce=", "\"", "+", "composingSpanEnd", ")", ";", "}", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "isInputViewShown", "(", ")", "&&", "mInputLogic", ".", "onUpdateSelection", "(", "oldSelStart", ",", "oldSelEnd", ",", "newSelStart", ",", "newSelEnd", ",", "settingsValues", ")", ")", "{", "mKeyboardSwitcher", ".", "requestUpdatingShiftState", "(", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "}", "/**\n * This is called when the user has clicked on the extracted text view,\n * when running in fullscreen mode. The default implementation hides\n * the suggestions view when this happens, but only if the extracted text\n * editor has a vertical scroll bar because its text doesn't fit.\n * Here we override the behavior due to the possibility that a re-correction could\n * cause the suggestions strip to disappear and re-appear.\n */", "@", "Override", "public", "void", "onExtractedTextClicked", "(", ")", "{", "if", "(", "mSettings", ".", "getCurrent", "(", ")", ".", "needsToLookupSuggestions", "(", ")", ")", "{", "return", ";", "}", "super", ".", "onExtractedTextClicked", "(", ")", ";", "}", "/**\n * This is called when the user has performed a cursor movement in the\n * extracted text view, when it is running in fullscreen mode. The default\n * implementation hides the suggestions view when a vertical movement\n * happens, but only if the extracted text editor has a vertical scroll bar\n * because its text doesn't fit.\n * Here we override the behavior due to the possibility that a re-correction could\n * cause the suggestions strip to disappear and re-appear.\n */", "@", "Override", "public", "void", "onExtractedCursorMovement", "(", "final", "int", "dx", ",", "final", "int", "dy", ")", "{", "if", "(", "mSettings", ".", "getCurrent", "(", ")", ".", "needsToLookupSuggestions", "(", ")", ")", "{", "return", ";", "}", "super", ".", "onExtractedCursorMovement", "(", "dx", ",", "dy", ")", ";", "}", "@", "Override", "public", "void", "hideWindow", "(", ")", "{", "mKeyboardSwitcher", ".", "onHideWindow", "(", ")", ";", "if", "(", "TRACE", ")", "Debug", ".", "stopMethodTracing", "(", ")", ";", "if", "(", "isShowingOptionDialog", "(", ")", ")", "{", "mOptionsDialog", ".", "dismiss", "(", ")", ";", "mOptionsDialog", "=", "null", ";", "}", "super", ".", "hideWindow", "(", ")", ";", "}", "@", "Override", "public", "void", "onDisplayCompletions", "(", "final", "CompletionInfo", "[", "]", "applicationSpecifiedCompletions", ")", "{", "if", "(", "DebugFlags", ".", "DEBUG_ENABLED", ")", "{", "Log", ".", "i", "(", "TAG", ",", "\"", "Received completions:", "\"", ")", ";", "if", "(", "applicationSpecifiedCompletions", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "applicationSpecifiedCompletions", ".", "length", ";", "i", "++", ")", "{", "Log", ".", "i", "(", "TAG", ",", "\"", " #", "\"", "+", "i", "+", "\"", ": ", "\"", "+", "applicationSpecifiedCompletions", "[", "i", "]", ")", ";", "}", "}", "}", "if", "(", "!", "mSettings", ".", "getCurrent", "(", ")", ".", "isApplicationSpecifiedCompletionsOn", "(", ")", ")", "{", "return", ";", "}", "mHandler", ".", "cancelUpdateSuggestionStrip", "(", ")", ";", "if", "(", "applicationSpecifiedCompletions", "==", "null", ")", "{", "setNeutralSuggestionStrip", "(", ")", ";", "return", ";", "}", "final", "ArrayList", "<", "SuggestedWords", ".", "SuggestedWordInfo", ">", "applicationSuggestedWords", "=", "SuggestedWords", ".", "getFromApplicationSpecifiedCompletions", "(", "applicationSpecifiedCompletions", ")", ";", "final", "SuggestedWords", "suggestedWords", "=", "new", "SuggestedWords", "(", "applicationSuggestedWords", ",", "null", "/* rawSuggestions */", ",", "null", "/* typedWord */", ",", "false", "/* typedWordValid */", ",", "false", "/* willAutoCorrect */", ",", "false", "/* isObsoleteSuggestions */", ",", "SuggestedWords", ".", "INPUT_STYLE_APPLICATION_SPECIFIED", "/* inputStyle */", ",", "SuggestedWords", ".", "NOT_A_SEQUENCE_NUMBER", ")", ";", "setSuggestedWords", "(", "suggestedWords", ")", ";", "}", "@", "Override", "public", "void", "onComputeInsets", "(", "final", "InputMethodService", ".", "Insets", "outInsets", ")", "{", "super", ".", "onComputeInsets", "(", "outInsets", ")", ";", "if", "(", "mInputView", "==", "null", ")", "{", "return", ";", "}", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "final", "View", "visibleKeyboardView", "=", "mKeyboardSwitcher", ".", "getVisibleKeyboardView", "(", ")", ";", "if", "(", "visibleKeyboardView", "==", "null", "||", "!", "hasSuggestionStripView", "(", ")", ")", "{", "return", ";", "}", "final", "int", "inputHeight", "=", "mInputView", ".", "getHeight", "(", ")", ";", "if", "(", "isImeSuppressedByHardwareKeyboard", "(", ")", "&&", "!", "visibleKeyboardView", ".", "isShown", "(", ")", ")", "{", "outInsets", ".", "contentTopInsets", "=", "inputHeight", ";", "outInsets", ".", "visibleTopInsets", "=", "inputHeight", ";", "mInsetsUpdater", ".", "setInsets", "(", "outInsets", ")", ";", "return", ";", "}", "final", "int", "suggestionsHeight", "=", "(", "!", "mKeyboardSwitcher", ".", "isShowingEmojiPalettes", "(", ")", "&&", "mSuggestionStripView", ".", "getVisibility", "(", ")", "==", "View", ".", "VISIBLE", ")", "?", "mSuggestionStripView", ".", "getHeight", "(", ")", ":", "0", ";", "final", "int", "visibleTopY", "=", "inputHeight", "-", "visibleKeyboardView", ".", "getHeight", "(", ")", "-", "suggestionsHeight", ";", "mSuggestionStripView", ".", "setMoreSuggestionsHeight", "(", "visibleTopY", ")", ";", "if", "(", "visibleKeyboardView", ".", "isShown", "(", ")", ")", "{", "final", "int", "touchLeft", "=", "0", ";", "final", "int", "touchTop", "=", "mKeyboardSwitcher", ".", "isShowingMoreKeysPanel", "(", ")", "?", "0", ":", "visibleTopY", ";", "final", "int", "touchRight", "=", "visibleKeyboardView", ".", "getWidth", "(", ")", ";", "final", "int", "touchBottom", "=", "inputHeight", "+", "EXTENDED_TOUCHABLE_REGION_HEIGHT", ";", "outInsets", ".", "touchableInsets", "=", "InputMethodService", ".", "Insets", ".", "TOUCHABLE_INSETS_REGION", ";", "outInsets", ".", "touchableRegion", ".", "set", "(", "touchLeft", ",", "touchTop", ",", "touchRight", ",", "touchBottom", ")", ";", "}", "outInsets", ".", "contentTopInsets", "=", "visibleTopY", ";", "outInsets", ".", "visibleTopInsets", "=", "visibleTopY", ";", "mInsetsUpdater", ".", "setInsets", "(", "outInsets", ")", ";", "}", "public", "void", "startShowingInputView", "(", "final", "boolean", "needsToLoadKeyboard", ")", "{", "mIsExecutingStartShowingInputView", "=", "true", ";", "showWindow", "(", "true", "/* showInput */", ")", ";", "mIsExecutingStartShowingInputView", "=", "false", ";", "if", "(", "needsToLoadKeyboard", ")", "{", "loadKeyboard", "(", ")", ";", "}", "}", "public", "void", "stopShowingInputView", "(", ")", "{", "showWindow", "(", "false", "/* showInput */", ")", ";", "}", "@", "Override", "public", "boolean", "onShowInputRequested", "(", "final", "int", "flags", ",", "final", "boolean", "configChange", ")", "{", "if", "(", "sessionData", "==", "null", "&&", "userHaveAgreed", "(", ")", ")", "{", "sessionData", "=", "new", "KeyboardDynamics", "(", ")", ";", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "final", "String", "packageName", "=", "getCurrentInputEditorInfo", "(", ")", ".", "packageName", ";", "String", "appName", ";", "PackageManager", "packageManager", "=", "getApplicationContext", "(", ")", ".", "getPackageManager", "(", ")", ";", "try", "{", "appName", "=", "(", "String", ")", "packageManager", ".", "getApplicationLabel", "(", "packageManager", ".", "getApplicationInfo", "(", "packageName", ",", "PackageManager", ".", "GET_META_DATA", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "appName", "=", "\"", "undefined", "\"", ";", "}", "sessionData", ".", "StartDateTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "sessionData", ".", "CurrentAppName", "=", "appName", ";", "sessionData", ".", "IsSoundOn", "=", "settingsValues", ".", "mSoundOn", ";", "sessionData", ".", "IsVibrationOn", "=", "settingsValues", ".", "mVibrateOn", ";", "sessionData", ".", "IsShowPopupOn", "=", "settingsValues", ".", "mKeyPreviewPopupOn", ";", "onShowNotificationAsync", "task", "=", "new", "onShowNotificationAsync", "(", "getApplicationContext", "(", ")", ")", ";", "task", ".", "execute", "(", ")", ";", "}", "if", "(", "isImeSuppressedByHardwareKeyboard", "(", ")", ")", "{", "return", "true", ";", "}", "return", "super", ".", "onShowInputRequested", "(", "flags", ",", "configChange", ")", ";", "}", "@", "Override", "public", "boolean", "onEvaluateInputViewShown", "(", ")", "{", "if", "(", "mIsExecutingStartShowingInputView", ")", "{", "return", "true", ";", "}", "return", "super", ".", "onEvaluateInputViewShown", "(", ")", ";", "}", "@", "Override", "public", "boolean", "onEvaluateFullscreenMode", "(", ")", "{", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "if", "(", "isImeSuppressedByHardwareKeyboard", "(", ")", ")", "{", "return", "false", ";", "}", "final", "boolean", "isFullscreenModeAllowed", "=", "Settings", ".", "readUseFullscreenMode", "(", "getResources", "(", ")", ")", ";", "if", "(", "super", ".", "onEvaluateFullscreenMode", "(", ")", "&&", "isFullscreenModeAllowed", ")", "{", "final", "EditorInfo", "ei", "=", "getCurrentInputEditorInfo", "(", ")", ";", "return", "!", "(", "ei", "!=", "null", "&&", "(", "(", "ei", ".", "imeOptions", "&", "EditorInfo", ".", "IME_FLAG_NO_EXTRACT_UI", ")", "!=", "0", ")", ")", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "void", "updateFullscreenMode", "(", ")", "{", "super", ".", "updateFullscreenMode", "(", ")", ";", "updateSoftInputWindowLayoutParameters", "(", ")", ";", "}", "private", "void", "updateSoftInputWindowLayoutParameters", "(", ")", "{", "final", "Window", "window", "=", "getWindow", "(", ")", ".", "getWindow", "(", ")", ";", "ViewLayoutUtils", ".", "updateLayoutHeightOf", "(", "window", ",", "LayoutParams", ".", "MATCH_PARENT", ")", ";", "if", "(", "mInputView", "!=", "null", ")", "{", "final", "int", "layoutHeight", "=", "isFullscreenMode", "(", ")", "?", "LayoutParams", ".", "WRAP_CONTENT", ":", "LayoutParams", ".", "MATCH_PARENT", ";", "final", "View", "inputArea", "=", "window", ".", "findViewById", "(", "android", ".", "R", ".", "id", ".", "inputArea", ")", ";", "ViewLayoutUtils", ".", "updateLayoutHeightOf", "(", "inputArea", ",", "layoutHeight", ")", ";", "ViewLayoutUtils", ".", "updateLayoutGravityOf", "(", "inputArea", ",", "Gravity", ".", "BOTTOM", ")", ";", "ViewLayoutUtils", ".", "updateLayoutHeightOf", "(", "mInputView", ",", "layoutHeight", ")", ";", "}", "}", "int", "getCurrentAutoCapsState", "(", ")", "{", "return", "mInputLogic", ".", "getCurrentAutoCapsState", "(", "mSettings", ".", "getCurrent", "(", ")", ")", ";", "}", "int", "getCurrentRecapitalizeState", "(", ")", "{", "return", "mInputLogic", ".", "getCurrentRecapitalizeState", "(", ")", ";", "}", "/**\n * @param codePoints code points to get coordinates for.\n * @return x,y coordinates for this keyboard, as a flattened array.\n */", "public", "int", "[", "]", "getCoordinatesForCurrentKeyboard", "(", "final", "int", "[", "]", "codePoints", ")", "{", "final", "Keyboard", "keyboard", "=", "mKeyboardSwitcher", ".", "getKeyboard", "(", ")", ";", "if", "(", "null", "==", "keyboard", ")", "{", "return", "CoordinateUtils", ".", "newCoordinateArray", "(", "codePoints", ".", "length", ",", "Constants", ".", "NOT_A_COORDINATE", ",", "Constants", ".", "NOT_A_COORDINATE", ")", ";", "}", "return", "keyboard", ".", "getCoordinates", "(", "codePoints", ")", ";", "}", "@", "Override", "public", "void", "showImportantNoticeContents", "(", ")", "{", "PermissionsManager", ".", "get", "(", "this", ")", ".", "requestPermissions", "(", "this", "/* PermissionsResultCallback */", ",", "null", "/* activity */", ",", "permission", ".", "READ_CONTACTS", ")", ";", "}", "@", "Override", "public", "void", "onRequestPermissionsResult", "(", "boolean", "allGranted", ")", "{", "ImportantNoticeUtils", ".", "updateContactsNoticeShown", "(", "this", "/* context */", ")", ";", "setNeutralSuggestionStrip", "(", ")", ";", "}", "public", "void", "displaySettingsDialog", "(", ")", "{", "if", "(", "isShowingOptionDialog", "(", ")", ")", "{", "return", ";", "}", "showSubtypeSelectorAndSettings", "(", ")", ";", "}", "@", "Override", "public", "boolean", "onCustomRequest", "(", "final", "int", "requestCode", ")", "{", "if", "(", "isShowingOptionDialog", "(", ")", ")", "return", "false", ";", "switch", "(", "requestCode", ")", "{", "case", "Constants", ".", "CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER", ":", "if", "(", "mRichImm", ".", "hasMultipleEnabledIMEsOrSubtypes", "(", "false", "/* include aux subtypes */", ")", ")", "{", "mRichImm", ".", "getInputMethodManager", "(", ")", ".", "showInputMethodPicker", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "return", "false", ";", "}", "private", "boolean", "isShowingOptionDialog", "(", ")", "{", "return", "mOptionsDialog", "!=", "null", "&&", "mOptionsDialog", ".", "isShowing", "(", ")", ";", "}", "public", "void", "switchLanguage", "(", "final", "InputMethodSubtype", "subtype", ")", "{", "final", "IBinder", "token", "=", "getWindow", "(", ")", ".", "getWindow", "(", ")", ".", "getAttributes", "(", ")", ".", "token", ";", "mRichImm", ".", "setInputMethodAndSubtype", "(", "token", ",", "subtype", ")", ";", "}", "public", "void", "switchToNextSubtype", "(", ")", "{", "final", "IBinder", "token", "=", "getWindow", "(", ")", ".", "getWindow", "(", ")", ".", "getAttributes", "(", ")", ".", "token", ";", "if", "(", "shouldSwitchToOtherInputMethods", "(", ")", ")", "{", "mRichImm", ".", "switchToNextInputMethod", "(", "token", ",", "true", "/* onlyCurrentIme */", ")", ";", "return", ";", "}", "mSubtypeState", ".", "switchSubtype", "(", "token", ",", "mRichImm", ")", ";", "}", "private", "int", "getCodePointForKeyboard", "(", "final", "int", "codePoint", ")", "{", "if", "(", "Constants", ".", "CODE_SHIFT", "==", "codePoint", ")", "{", "final", "Keyboard", "currentKeyboard", "=", "mKeyboardSwitcher", ".", "getKeyboard", "(", ")", ";", "if", "(", "null", "!=", "currentKeyboard", "&&", "currentKeyboard", ".", "mId", ".", "isAlphabetKeyboard", "(", ")", ")", "{", "return", "codePoint", ";", "}", "return", "Constants", ".", "CODE_SYMBOL_SHIFT", ";", "}", "return", "codePoint", ";", "}", "@", "Override", "public", "void", "onCodeInput", "(", "final", "int", "codePoint", ",", "final", "int", "x", ",", "final", "int", "y", ",", "final", "boolean", "isKeyRepeat", ")", "{", "final", "MainKeyboardView", "mainKeyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "final", "int", "keyX", "=", "mainKeyboardView", ".", "getKeyX", "(", "x", ")", ";", "final", "int", "keyY", "=", "mainKeyboardView", ".", "getKeyY", "(", "y", ")", ";", "final", "Event", "event", "=", "createSoftwareKeypressEvent", "(", "getCodePointForKeyboard", "(", "codePoint", ")", ",", "keyX", ",", "keyY", ",", "isKeyRepeat", ")", ";", "onEvent", "(", "event", ")", ";", "}", "public", "void", "onEvent", "(", "@", "Nonnull", "final", "Event", "event", ")", "{", "if", "(", "Constants", ".", "CODE_SHORTCUT", "==", "event", ".", "mKeyCode", ")", "{", "mRichImm", ".", "switchToShortcutIme", "(", "this", ")", ";", "}", "final", "InputTransaction", "completeInputTransaction", "=", "mInputLogic", ".", "onCodeInput", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "event", ",", "mKeyboardSwitcher", ".", "getKeyboardShiftMode", "(", ")", ",", "mKeyboardSwitcher", ".", "getCurrentKeyboardScriptId", "(", ")", ",", "mHandler", ")", ";", "updateStateAfterInputTransaction", "(", "completeInputTransaction", ")", ";", "mKeyboardSwitcher", ".", "onEvent", "(", "event", ",", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "@", "Nonnull", "public", "static", "Event", "createSoftwareKeypressEvent", "(", "final", "int", "keyCodeOrCodePoint", ",", "final", "int", "keyX", ",", "final", "int", "keyY", ",", "final", "boolean", "isKeyRepeat", ")", "{", "final", "int", "keyCode", ";", "final", "int", "codePoint", ";", "if", "(", "keyCodeOrCodePoint", "<=", "0", ")", "{", "keyCode", "=", "keyCodeOrCodePoint", ";", "codePoint", "=", "Event", ".", "NOT_A_CODE_POINT", ";", "}", "else", "{", "keyCode", "=", "Event", ".", "NOT_A_KEY_CODE", ";", "codePoint", "=", "keyCodeOrCodePoint", ";", "}", "return", "Event", ".", "createSoftwareKeypressEvent", "(", "codePoint", ",", "keyCode", ",", "keyX", ",", "keyY", ",", "isKeyRepeat", ")", ";", "}", "@", "Override", "public", "void", "onTextInput", "(", "final", "String", "rawText", ")", "{", "final", "Event", "event", "=", "Event", ".", "createSoftwareTextEvent", "(", "rawText", ",", "Constants", ".", "CODE_OUTPUT_TEXT", ")", ";", "final", "InputTransaction", "completeInputTransaction", "=", "mInputLogic", ".", "onTextInput", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "event", ",", "mKeyboardSwitcher", ".", "getKeyboardShiftMode", "(", ")", ",", "mHandler", ")", ";", "updateStateAfterInputTransaction", "(", "completeInputTransaction", ")", ";", "mKeyboardSwitcher", ".", "onEvent", "(", "event", ",", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onStartBatchInput", "(", ")", "{", "mInputLogic", ".", "onStartBatchInput", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "mKeyboardSwitcher", ",", "mHandler", ")", ";", "mGestureConsumer", ".", "onGestureStarted", "(", "mRichImm", ".", "getCurrentSubtypeLocale", "(", ")", ",", "mKeyboardSwitcher", ".", "getKeyboard", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onUpdateBatchInput", "(", "final", "InputPointers", "batchPointers", ")", "{", "mInputLogic", ".", "onUpdateBatchInput", "(", "batchPointers", ")", ";", "}", "@", "Override", "public", "void", "onEndBatchInput", "(", "final", "InputPointers", "batchPointers", ")", "{", "mInputLogic", ".", "onEndBatchInput", "(", "batchPointers", ")", ";", "mGestureConsumer", ".", "onGestureCompleted", "(", "batchPointers", ")", ";", "}", "@", "Override", "public", "void", "onCancelBatchInput", "(", ")", "{", "mInputLogic", ".", "onCancelBatchInput", "(", "mHandler", ")", ";", "mGestureConsumer", ".", "onGestureCanceled", "(", ")", ";", "}", "/**\n * To be called after the InputLogic has gotten a chance to act on the suggested words by the\n * IME for the full gesture, possibly updating the TextView to reflect the first suggestion.\n * <p>\n * This method must be run on the UI Thread.\n * @param suggestedWords suggested words by the IME for the full gesture.\n */", "public", "void", "onTailBatchInputResultShown", "(", "final", "SuggestedWords", "suggestedWords", ")", "{", "mGestureConsumer", ".", "onImeSuggestionsProcessed", "(", "suggestedWords", ",", "mInputLogic", ".", "getComposingStart", "(", ")", ",", "mInputLogic", ".", "getComposingLength", "(", ")", ",", "mDictionaryFacilitator", ")", ";", "}", "void", "showGesturePreviewAndSuggestionStrip", "(", "@", "Nonnull", "final", "SuggestedWords", "suggestedWords", ",", "final", "boolean", "dismissGestureFloatingPreviewText", ")", "{", "showSuggestionStrip", "(", "suggestedWords", ")", ";", "final", "MainKeyboardView", "mainKeyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "mainKeyboardView", ".", "showGestureFloatingPreviewText", "(", "suggestedWords", ",", "dismissGestureFloatingPreviewText", "/* dismissDelayed */", ")", ";", "}", "@", "Override", "public", "void", "onFinishSlidingInput", "(", ")", "{", "mKeyboardSwitcher", ".", "onFinishSlidingInput", "(", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onCancelInput", "(", ")", "{", "}", "public", "boolean", "hasSuggestionStripView", "(", ")", "{", "return", "null", "!=", "mSuggestionStripView", ";", "}", "private", "void", "setSuggestedWords", "(", "final", "SuggestedWords", "suggestedWords", ")", "{", "final", "SettingsValues", "currentSettingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "mInputLogic", ".", "setSuggestedWords", "(", "suggestedWords", ")", ";", "if", "(", "!", "hasSuggestionStripView", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "onEvaluateInputViewShown", "(", ")", ")", "{", "return", ";", "}", "final", "boolean", "shouldShowImportantNotice", "=", "ImportantNoticeUtils", ".", "shouldShowImportantNotice", "(", "this", ",", "currentSettingsValues", ")", ";", "final", "boolean", "shouldShowSuggestionCandidates", "=", "currentSettingsValues", ".", "mInputAttributes", ".", "mShouldShowSuggestions", "&&", "currentSettingsValues", ".", "isSuggestionsEnabledPerUserSettings", "(", ")", ";", "final", "boolean", "shouldShowSuggestionsStripUnlessPassword", "=", "shouldShowImportantNotice", "||", "currentSettingsValues", ".", "mShowsVoiceInputKey", "||", "shouldShowSuggestionCandidates", "||", "currentSettingsValues", ".", "isApplicationSpecifiedCompletionsOn", "(", ")", ";", "final", "boolean", "shouldShowSuggestionsStrip", "=", "shouldShowSuggestionsStripUnlessPassword", "&&", "!", "currentSettingsValues", ".", "mInputAttributes", ".", "mIsPasswordField", ";", "mSuggestionStripView", ".", "updateVisibility", "(", "shouldShowSuggestionsStrip", ",", "isFullscreenMode", "(", ")", ")", ";", "if", "(", "!", "shouldShowSuggestionsStrip", ")", "{", "return", ";", "}", "final", "boolean", "isEmptyApplicationSpecifiedCompletions", "=", "currentSettingsValues", ".", "isApplicationSpecifiedCompletionsOn", "(", ")", "&&", "suggestedWords", ".", "isEmpty", "(", ")", ";", "final", "boolean", "noSuggestionsFromDictionaries", "=", "suggestedWords", ".", "isEmpty", "(", ")", "||", "suggestedWords", ".", "isPunctuationSuggestions", "(", ")", "||", "isEmptyApplicationSpecifiedCompletions", ";", "final", "boolean", "isBeginningOfSentencePrediction", "=", "(", "suggestedWords", ".", "mInputStyle", "==", "SuggestedWords", ".", "INPUT_STYLE_BEGINNING_OF_SENTENCE_PREDICTION", ")", ";", "final", "boolean", "noSuggestionsToOverrideImportantNotice", "=", "noSuggestionsFromDictionaries", "||", "isBeginningOfSentencePrediction", ";", "if", "(", "shouldShowImportantNotice", "&&", "noSuggestionsToOverrideImportantNotice", ")", "{", "if", "(", "mSuggestionStripView", ".", "maybeShowImportantNoticeTitle", "(", ")", ")", "{", "return", ";", "}", "}", "if", "(", "currentSettingsValues", ".", "isSuggestionsEnabledPerUserSettings", "(", ")", "||", "currentSettingsValues", ".", "isApplicationSpecifiedCompletionsOn", "(", ")", "||", "noSuggestionsFromDictionaries", ")", "{", "mSuggestionStripView", ".", "setSuggestions", "(", "suggestedWords", ",", "mRichImm", ".", "getCurrentSubtype", "(", ")", ".", "isRtlSubtype", "(", ")", ")", ";", "}", "}", "public", "void", "getSuggestedWords", "(", "final", "int", "inputStyle", ",", "final", "int", "sequenceNumber", ",", "final", "Suggest", ".", "OnGetSuggestedWordsCallback", "callback", ")", "{", "final", "Keyboard", "keyboard", "=", "mKeyboardSwitcher", ".", "getKeyboard", "(", ")", ";", "if", "(", "keyboard", "==", "null", ")", "{", "callback", ".", "onGetSuggestedWords", "(", "SuggestedWords", ".", "getEmptyInstance", "(", ")", ")", ";", "return", ";", "}", "mInputLogic", ".", "getSuggestedWords", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "keyboard", ",", "mKeyboardSwitcher", ".", "getKeyboardShiftMode", "(", ")", ",", "inputStyle", ",", "sequenceNumber", ",", "callback", ")", ";", "}", "@", "Override", "public", "void", "showSuggestionStrip", "(", "final", "SuggestedWords", "suggestedWords", ")", "{", "if", "(", "suggestedWords", ".", "isEmpty", "(", ")", ")", "{", "setNeutralSuggestionStrip", "(", ")", ";", "}", "else", "{", "setSuggestedWords", "(", "suggestedWords", ")", ";", "}", "AccessibilityUtils", ".", "getInstance", "(", ")", ".", "setAutoCorrection", "(", "suggestedWords", ")", ";", "}", "@", "Override", "public", "void", "pickSuggestionManually", "(", "final", "SuggestedWords", ".", "SuggestedWordInfo", "suggestionInfo", ")", "{", "final", "InputTransaction", "completeInputTransaction", "=", "mInputLogic", ".", "onPickSuggestionManually", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "suggestionInfo", ",", "mKeyboardSwitcher", ".", "getKeyboardShiftMode", "(", ")", ",", "mKeyboardSwitcher", ".", "getCurrentKeyboardScriptId", "(", ")", ",", "mHandler", ")", ";", "updateStateAfterInputTransaction", "(", "completeInputTransaction", ")", ";", "}", "@", "Override", "public", "void", "setNeutralSuggestionStrip", "(", ")", "{", "final", "SettingsValues", "currentSettings", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "final", "SuggestedWords", "neutralSuggestions", "=", "currentSettings", ".", "mBigramPredictionEnabled", "?", "SuggestedWords", ".", "getEmptyInstance", "(", ")", ":", "currentSettings", ".", "mSpacingAndPunctuations", ".", "mSuggestPuncList", ";", "setSuggestedWords", "(", "neutralSuggestions", ")", ";", "}", "@", "UsedForTesting", "void", "loadKeyboard", "(", ")", "{", "mHandler", ".", "postReopenDictionaries", "(", ")", ";", "loadSettings", "(", ")", ";", "if", "(", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", "!=", "null", ")", "{", "mKeyboardSwitcher", ".", "loadKeyboard", "(", "getCurrentInputEditorInfo", "(", ")", ",", "mSettings", ".", "getCurrent", "(", ")", ",", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "}", "/**\n * After an input transaction has been executed, some state must be updated. This includes\n * the shift state of the keyboard and suggestions. This method looks at the finished\n * inputTransaction to find out what is necessary and updates the state accordingly.\n * @param inputTransaction The transaction that has been executed.\n */", "private", "void", "updateStateAfterInputTransaction", "(", "final", "InputTransaction", "inputTransaction", ")", "{", "switch", "(", "inputTransaction", ".", "getRequiredShiftUpdate", "(", ")", ")", "{", "case", "InputTransaction", ".", "SHIFT_UPDATE_LATER", ":", "mHandler", ".", "postUpdateShiftState", "(", ")", ";", "break", ";", "case", "InputTransaction", ".", "SHIFT_UPDATE_NOW", ":", "mKeyboardSwitcher", ".", "requestUpdatingShiftState", "(", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "break", ";", "default", ":", "}", "if", "(", "inputTransaction", ".", "requiresUpdateSuggestions", "(", ")", ")", "{", "final", "int", "inputStyle", ";", "if", "(", "inputTransaction", ".", "mEvent", ".", "isSuggestionStripPress", "(", ")", ")", "{", "inputStyle", "=", "SuggestedWords", ".", "INPUT_STYLE_NONE", ";", "}", "else", "if", "(", "inputTransaction", ".", "mEvent", ".", "isGesture", "(", ")", ")", "{", "inputStyle", "=", "SuggestedWords", ".", "INPUT_STYLE_TAIL_BATCH", ";", "}", "else", "{", "inputStyle", "=", "SuggestedWords", ".", "INPUT_STYLE_TYPING", ";", "}", "mHandler", ".", "postUpdateSuggestionStrip", "(", "inputStyle", ")", ";", "}", "if", "(", "inputTransaction", ".", "didAffectContents", "(", ")", ")", "{", "mSubtypeState", ".", "setCurrentSubtypeHasBeenUsed", "(", ")", ";", "}", "}", "private", "void", "hapticAndAudioFeedback", "(", "final", "int", "code", ",", "final", "int", "repeatCount", ")", "{", "final", "MainKeyboardView", "keyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "if", "(", "keyboardView", "!=", "null", "&&", "keyboardView", ".", "isInDraggingFinger", "(", ")", ")", "{", "return", ";", "}", "if", "(", "repeatCount", ">", "0", ")", "{", "if", "(", "code", "==", "Constants", ".", "CODE_DELETE", "&&", "!", "mInputLogic", ".", "mConnection", ".", "canDeleteCharacters", "(", ")", ")", "{", "return", ";", "}", "if", "(", "repeatCount", "%", "PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT", "==", "0", ")", "{", "return", ";", "}", "}", "final", "AudioAndHapticFeedbackManager", "feedbackManager", "=", "AudioAndHapticFeedbackManager", ".", "getInstance", "(", ")", ";", "if", "(", "repeatCount", "==", "0", ")", "{", "feedbackManager", ".", "performHapticFeedback", "(", "keyboardView", ")", ";", "}", "feedbackManager", ".", "performAudioFeedback", "(", "code", ")", ";", "}", "@", "Override", "public", "void", "onPressKey", "(", "final", "int", "primaryCode", ",", "final", "int", "repeatCount", ",", "final", "boolean", "isSinglePointer", ")", "{", "if", "(", "primaryCode", "==", "Constants", ".", "CODE_DELETE", "&&", "sessionData", "!=", "null", ")", "{", "sessionData", ".", "NumDels", "+=", "1", ";", "}", "mKeyboardSwitcher", ".", "onPressKey", "(", "primaryCode", ",", "isSinglePointer", ",", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "hapticAndAudioFeedback", "(", "primaryCode", ",", "repeatCount", ")", ";", "}", "@", "Override", "public", "void", "onReleaseKey", "(", "final", "int", "primaryCode", ",", "final", "boolean", "withSliding", ")", "{", "mKeyboardSwitcher", ".", "onReleaseKey", "(", "primaryCode", ",", "withSliding", ",", "getCurrentAutoCapsState", "(", ")", ",", "getCurrentRecapitalizeState", "(", ")", ")", ";", "}", "private", "HardwareEventDecoder", "getHardwareKeyEventDecoder", "(", "final", "int", "deviceId", ")", "{", "final", "HardwareEventDecoder", "decoder", "=", "mHardwareEventDecoders", ".", "get", "(", "deviceId", ")", ";", "if", "(", "null", "!=", "decoder", ")", "return", "decoder", ";", "final", "HardwareEventDecoder", "newDecoder", "=", "new", "HardwareKeyboardEventDecoder", "(", "deviceId", ")", ";", "mHardwareEventDecoders", ".", "put", "(", "deviceId", ",", "newDecoder", ")", ";", "return", "newDecoder", ";", "}", "@", "Override", "public", "boolean", "onKeyDown", "(", "final", "int", "keyCode", ",", "final", "KeyEvent", "keyEvent", ")", "{", "if", "(", "mEmojiAltPhysicalKeyDetector", "==", "null", ")", "{", "mEmojiAltPhysicalKeyDetector", "=", "new", "EmojiAltPhysicalKeyDetector", "(", "getApplicationContext", "(", ")", ".", "getResources", "(", ")", ")", ";", "}", "mEmojiAltPhysicalKeyDetector", ".", "onKeyDown", "(", "keyEvent", ")", ";", "if", "(", "!", "ProductionFlags", ".", "IS_HARDWARE_KEYBOARD_SUPPORTED", ")", "{", "return", "super", ".", "onKeyDown", "(", "keyCode", ",", "keyEvent", ")", ";", "}", "final", "Event", "event", "=", "getHardwareKeyEventDecoder", "(", "keyEvent", ".", "getDeviceId", "(", ")", ")", ".", "decodeHardwareKey", "(", "keyEvent", ")", ";", "if", "(", "event", ".", "isHandled", "(", ")", ")", "{", "mInputLogic", ".", "onCodeInput", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "event", ",", "mKeyboardSwitcher", ".", "getKeyboardShiftMode", "(", ")", ",", "mKeyboardSwitcher", ".", "getCurrentKeyboardScriptId", "(", ")", ",", "mHandler", ")", ";", "return", "true", ";", "}", "return", "super", ".", "onKeyDown", "(", "keyCode", ",", "keyEvent", ")", ";", "}", "@", "Override", "public", "boolean", "onKeyUp", "(", "final", "int", "keyCode", ",", "final", "KeyEvent", "keyEvent", ")", "{", "if", "(", "mEmojiAltPhysicalKeyDetector", "==", "null", ")", "{", "mEmojiAltPhysicalKeyDetector", "=", "new", "EmojiAltPhysicalKeyDetector", "(", "getApplicationContext", "(", ")", ".", "getResources", "(", ")", ")", ";", "}", "mEmojiAltPhysicalKeyDetector", ".", "onKeyUp", "(", "keyEvent", ")", ";", "if", "(", "!", "ProductionFlags", ".", "IS_HARDWARE_KEYBOARD_SUPPORTED", ")", "{", "return", "super", ".", "onKeyUp", "(", "keyCode", ",", "keyEvent", ")", ";", "}", "final", "long", "keyIdentifier", "=", "keyEvent", ".", "getDeviceId", "(", ")", "<<", "32", "+", "keyEvent", ".", "getKeyCode", "(", ")", ";", "if", "(", "mInputLogic", ".", "mCurrentlyPressedHardwareKeys", ".", "remove", "(", "keyIdentifier", ")", ")", "{", "return", "true", ";", "}", "return", "super", ".", "onKeyUp", "(", "keyCode", ",", "keyEvent", ")", ";", "}", "private", "final", "BroadcastReceiver", "mRingerModeChangeReceiver", "=", "new", "BroadcastReceiver", "(", ")", "{", "@", "Override", "public", "void", "onReceive", "(", "final", "Context", "context", ",", "final", "Intent", "intent", ")", "{", "final", "String", "action", "=", "intent", ".", "getAction", "(", ")", ";", "if", "(", "action", ".", "equals", "(", "AudioManager", ".", "RINGER_MODE_CHANGED_ACTION", ")", ")", "{", "AudioAndHapticFeedbackManager", ".", "getInstance", "(", ")", ".", "onRingerModeChanged", "(", ")", ";", "}", "}", "}", ";", "void", "launchSettings", "(", "final", "String", "extraEntryValue", ")", "{", "mInputLogic", ".", "commitTyped", "(", "mSettings", ".", "getCurrent", "(", ")", ",", "LastComposedWord", ".", "NOT_A_SEPARATOR", ")", ";", "requestHideSelf", "(", "0", ")", ";", "final", "MainKeyboardView", "mainKeyboardView", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ";", "if", "(", "mainKeyboardView", "!=", "null", ")", "{", "mainKeyboardView", ".", "closing", "(", ")", ";", "}", "final", "Intent", "intent", "=", "new", "Intent", "(", ")", ";", "intent", ".", "setClass", "(", "LatinIME", ".", "this", ",", "SettingsActivity", ".", "class", ")", ";", "intent", ".", "setFlags", "(", "FLAG_ACTIVITY_NEW_TASK", "|", "Intent", ".", "FLAG_ACTIVITY_RESET_TASK_IF_NEEDED", "|", "Intent", ".", "FLAG_ACTIVITY_CLEAR_TOP", ")", ";", "intent", ".", "putExtra", "(", "SettingsActivity", ".", "EXTRA_SHOW_HOME_AS_UP", ",", "false", ")", ";", "intent", ".", "putExtra", "(", "SettingsActivity", ".", "EXTRA_ENTRY_KEY", ",", "extraEntryValue", ")", ";", "startActivity", "(", "intent", ")", ";", "}", "private", "void", "showSubtypeSelectorAndSettings", "(", ")", "{", "final", "CharSequence", "title", "=", "getString", "(", "R", ".", "string", ".", "english_ime_input_options", ")", ";", "final", "CharSequence", "languageSelectionTitle", "=", "getString", "(", "R", ".", "string", ".", "language_selection_title", ")", ";", "final", "CharSequence", "[", "]", "items", "=", "new", "CharSequence", "[", "]", "{", "languageSelectionTitle", ",", "getString", "(", "ApplicationUtils", ".", "getActivityTitleResId", "(", "this", ",", "SettingsActivity", ".", "class", ")", ")", "}", ";", "final", "String", "imeId", "=", "mRichImm", ".", "getInputMethodIdOfThisIme", "(", ")", ";", "final", "OnClickListener", "listener", "=", "new", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "DialogInterface", "di", ",", "int", "position", ")", "{", "di", ".", "dismiss", "(", ")", ";", "switch", "(", "position", ")", "{", "case", "0", ":", "final", "InputMethodInfo", "imi", "=", "UncachedInputMethodManagerUtils", ".", "getInputMethodInfoOf", "(", "getPackageName", "(", ")", ",", "mRichImm", ".", "getInputMethodManager", "(", ")", ")", ";", "if", "(", "imi", "==", "null", ")", "{", "return", ";", "}", "final", "Intent", "intent", "=", "new", "Intent", "(", ")", ";", "intent", ".", "setAction", "(", "android", ".", "provider", ".", "Settings", ".", "ACTION_INPUT_METHOD_SUBTYPE_SETTINGS", ")", ";", "intent", ".", "addCategory", "(", "Intent", ".", "CATEGORY_DEFAULT", ")", ";", "intent", ".", "putExtra", "(", "android", ".", "provider", ".", "Settings", ".", "EXTRA_INPUT_METHOD_ID", ",", "imi", ".", "getId", "(", ")", ")", ";", "startActivity", "(", "intent", ")", ";", "break", ";", "case", "1", ":", "launchSettings", "(", "SettingsActivity", ".", "EXTRA_ENTRY_VALUE_LONG_PRESS_COMMA", ")", ";", "break", ";", "}", "}", "}", ";", "final", "AlertDialog", ".", "Builder", "builder", "=", "new", "AlertDialog", ".", "Builder", "(", "DialogUtils", ".", "getPlatformDialogThemeContext", "(", "this", ")", ")", ";", "builder", ".", "setItems", "(", "items", ",", "listener", ")", ".", "setTitle", "(", "title", ")", ";", "final", "AlertDialog", "dialog", "=", "builder", ".", "create", "(", ")", ";", "dialog", ".", "setCancelable", "(", "true", "/* cancelable */", ")", ";", "dialog", ".", "setCanceledOnTouchOutside", "(", "true", "/* cancelable */", ")", ";", "showOptionDialog", "(", "dialog", ")", ";", "}", "private", "void", "showOptionDialog", "(", "final", "AlertDialog", "dialog", ")", "{", "final", "IBinder", "windowToken", "=", "mKeyboardSwitcher", ".", "getMainKeyboardView", "(", ")", ".", "getWindowToken", "(", ")", ";", "if", "(", "windowToken", "==", "null", ")", "{", "return", ";", "}", "final", "Window", "window", "=", "dialog", ".", "getWindow", "(", ")", ";", "final", "WindowManager", ".", "LayoutParams", "lp", "=", "window", ".", "getAttributes", "(", ")", ";", "lp", ".", "token", "=", "windowToken", ";", "lp", ".", "type", "=", "WindowManager", ".", "LayoutParams", ".", "TYPE_APPLICATION_ATTACHED_DIALOG", ";", "window", ".", "setAttributes", "(", "lp", ")", ";", "window", ".", "addFlags", "(", "WindowManager", ".", "LayoutParams", ".", "FLAG_ALT_FOCUSABLE_IM", ")", ";", "mOptionsDialog", "=", "dialog", ";", "dialog", ".", "show", "(", ")", ";", "}", "@", "UsedForTesting", "SuggestedWords", "getSuggestedWordsForTest", "(", ")", "{", "return", "DebugFlags", ".", "DEBUG_ENABLED", "?", "mInputLogic", ".", "mSuggestedWords", ":", "null", ";", "}", "@", "UsedForTesting", "void", "waitForLoadingDictionaries", "(", "final", "long", "timeout", ",", "final", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "mDictionaryFacilitator", ".", "waitForLoadingDictionariesForTesting", "(", "timeout", ",", "unit", ")", ";", "}", "@", "UsedForTesting", "void", "replaceDictionariesForTest", "(", "final", "Locale", "locale", ")", "{", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "mDictionaryFacilitator", ".", "resetDictionaries", "(", "this", ",", "locale", ",", "settingsValues", ".", "mUseContactsDict", ",", "settingsValues", ".", "mUsePersonalizedDicts", ",", "false", "/* forceReloadMainDictionary */", ",", "settingsValues", ".", "mAccount", ",", "\"", "\"", ",", "/* dictionaryNamePrefix */", "this", "/* DictionaryInitializationListener */", ")", ";", "}", "@", "UsedForTesting", "void", "clearPersonalizedDictionariesForTest", "(", ")", "{", "mDictionaryFacilitator", ".", "clearUserHistoryDictionary", "(", "this", ")", ";", "}", "@", "UsedForTesting", "List", "<", "InputMethodSubtype", ">", "getEnabledSubtypesForTest", "(", ")", "{", "return", "(", "mRichImm", "!=", "null", ")", "?", "mRichImm", ".", "getMyEnabledInputMethodSubtypeList", "(", "true", "/* allowsImplicitlySelectedSubtypes */", ")", ":", "new", "ArrayList", "<", "InputMethodSubtype", ">", "(", ")", ";", "}", "public", "void", "dumpDictionaryForDebug", "(", "final", "String", "dictName", ")", "{", "if", "(", "!", "mDictionaryFacilitator", ".", "isActive", "(", ")", ")", "{", "resetDictionaryFacilitatorIfNecessary", "(", ")", ";", "}", "mDictionaryFacilitator", ".", "dumpDictionaryForDebug", "(", "dictName", ")", ";", "}", "public", "void", "debugDumpStateAndCrashWithException", "(", "final", "String", "context", ")", "{", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "final", "StringBuilder", "s", "=", "new", "StringBuilder", "(", "settingsValues", ".", "toString", "(", ")", ")", ";", "s", ".", "append", "(", "\"", "\\n", "Attributes : ", "\"", ")", ".", "append", "(", "settingsValues", ".", "mInputAttributes", ")", ".", "append", "(", "\"", "\\n", "Context : ", "\"", ")", ".", "append", "(", "context", ")", ";", "throw", "new", "RuntimeException", "(", "s", ".", "toString", "(", ")", ")", ";", "}", "@", "Override", "protected", "void", "dump", "(", "final", "FileDescriptor", "fd", ",", "final", "PrintWriter", "fout", ",", "final", "String", "[", "]", "args", ")", "{", "super", ".", "dump", "(", "fd", ",", "fout", ",", "args", ")", ";", "final", "Printer", "p", "=", "new", "PrintWriterPrinter", "(", "fout", ")", ";", "p", ".", "println", "(", "\"", "LatinIME state :", "\"", ")", ";", "p", ".", "println", "(", "\"", " VersionCode = ", "\"", "+", "ApplicationUtils", ".", "getVersionCode", "(", "this", ")", ")", ";", "p", ".", "println", "(", "\"", " VersionName = ", "\"", "+", "ApplicationUtils", ".", "getVersionName", "(", "this", ")", ")", ";", "final", "Keyboard", "keyboard", "=", "mKeyboardSwitcher", ".", "getKeyboard", "(", ")", ";", "final", "int", "keyboardMode", "=", "keyboard", "!=", "null", "?", "keyboard", ".", "mId", ".", "mMode", ":", "-", "1", ";", "p", ".", "println", "(", "\"", " Keyboard mode = ", "\"", "+", "keyboardMode", ")", ";", "final", "SettingsValues", "settingsValues", "=", "mSettings", ".", "getCurrent", "(", ")", ";", "p", ".", "println", "(", "settingsValues", ".", "dump", "(", ")", ")", ";", "p", ".", "println", "(", "mDictionaryFacilitator", ".", "dump", "(", "this", "/* context */", ")", ")", ";", "}", "public", "boolean", "shouldSwitchToOtherInputMethods", "(", ")", "{", "final", "boolean", "fallbackValue", "=", "mSettings", ".", "getCurrent", "(", ")", ".", "mIncludesOtherImesInLanguageSwitchList", ";", "final", "IBinder", "token", "=", "getWindow", "(", ")", ".", "getWindow", "(", ")", ".", "getAttributes", "(", ")", ".", "token", ";", "if", "(", "token", "==", "null", ")", "{", "return", "fallbackValue", ";", "}", "return", "false", ";", "}", "public", "boolean", "shouldShowLanguageSwitchKey", "(", ")", "{", "final", "boolean", "fallbackValue", "=", "mSettings", ".", "getCurrent", "(", ")", ".", "isLanguageSwitchKeyEnabled", "(", ")", ";", "final", "IBinder", "token", "=", "getWindow", "(", ")", ".", "getWindow", "(", ")", ".", "getAttributes", "(", ")", ".", "token", ";", "if", "(", "token", "==", "null", ")", "{", "return", "fallbackValue", ";", "}", "return", "mRichImm", ".", "shouldOfferSwitchingToNextInputMethod", "(", "token", ",", "fallbackValue", ")", ";", "}", "private", "void", "setNavigationBarVisibility", "(", "final", "boolean", "visible", ")", "{", "if", "(", "BuildCompatUtils", ".", "EFFECTIVE_SDK_INT", ">", "Build", ".", "VERSION_CODES", ".", "M", ")", "{", "getWindow", "(", ")", ".", "getWindow", "(", ")", ".", "setNavigationBarColor", "(", "visible", "?", "Color", ".", "BLACK", ":", "Color", ".", "TRANSPARENT", ")", ";", "}", "}", "private", "void", "CreateAlertDialogWithRadioButtonGroup", "(", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "getApplicationContext", "(", ")", ",", "ChooseMood", ".", "class", ")", ";", "intent", ".", "setFlags", "(", "FLAG_ACTIVITY_NEW_TASK", ")", ";", "startActivity", "(", "intent", ")", ";", "}", "private", "static", "boolean", "AddData", "(", "String", "sessionDataString", ",", "Context", "context", ")", "{", "boolean", "insertData", "=", "myDB", ".", "addData", "(", "sessionDataString", ")", ";", "if", "(", "insertData", "==", "false", ")", "{", "Toast", ".", "makeText", "(", "context", ",", "\"", "Something went wrong in database", "\"", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "}", "return", "insertData", ";", "}", "public", "static", "boolean", "isConnected", "(", "Context", "context", ")", "{", "ConnectivityManager", "connMgr", "=", "(", "ConnectivityManager", ")", "context", ".", "getSystemService", "(", "Activity", ".", "CONNECTIVITY_SERVICE", ")", ";", "try", "{", "NetworkInfo", "networkInfo", "=", "null", ";", "if", "(", "connMgr", "!=", "null", ")", "{", "networkInfo", "=", "connMgr", ".", "getNetworkInfo", "(", "ConnectivityManager", ".", "TYPE_WIFI", ")", ";", "}", "if", "(", "networkInfo", "!=", "null", "&&", "networkInfo", ".", "isConnected", "(", ")", ")", "return", "true", ";", "else", "return", "false", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "}", "protected", "static", "String", "upload", "(", "ArrayList", "<", "KeyboardPayload", ">", "payload", ",", "Context", "context", ")", "{", "String", "result", "=", "\"", "\"", ";", "SharedPreferences", "pref", "=", "context", ".", "getSharedPreferences", "(", "\"", "user_info", "\"", ",", "Context", ".", "MODE_PRIVATE", ")", ";", "SharedPreferences", ".", "Editor", "editor", "=", "pref", ".", "edit", "(", ")", ";", "String", "prefs_age", "=", "pref", ".", "getString", "(", "\"", "Age", "\"", ",", "\"", "\"", ")", ";", "String", "prefs_id", "=", "pref", ".", "getString", "(", "\"", "ID", "\"", ",", "\"", "\"", ")", ";", "String", "prefs_gender", "=", "pref", ".", "getString", "(", "\"", "Gender", "\"", ",", "\"", "\"", ")", ";", "String", "prefs_health", "=", "pref", ".", "getString", "(", "\"", "Health", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_1", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_1", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_2", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_2", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_3", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_3", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_4", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_4", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_5", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_5", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_6", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_6", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_7", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_7", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_8", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_8", "\"", ",", "\"", "\"", ")", ";", "String", "pref_phq9_item_9", "=", "pref", ".", "getString", "(", "\"", "PHQ9_item_9", "\"", ",", "\"", "\"", ")", ";", "String", "pref_education", "=", "pref", ".", "getString", "(", "\"", "Education", "\"", ",", "\"", "\"", ")", ";", "String", "pref_usage", "=", "pref", ".", "getString", "(", "\"", "Usage", "\"", ",", "\"", "\"", ")", ";", "String", "pref_income", "=", "pref", ".", "getString", "(", "\"", "Income", "\"", ",", "\"", "\"", ")", ";", "String", "pref_medication", "=", "pref", ".", "getString", "(", "\"", "Medication", "\"", ",", "\"", "\"", ")", ";", "long", "users_max_flight", "=", "pref", ".", "getLong", "(", "\"", "MaxFlight", "\"", ",", "0", ")", ";", "long", "users_min_flight", "=", "pref", ".", "getLong", "(", "\"", "MinFlight", "\"", ",", "3000", ")", ";", "float", "users_mean_flight", "=", "pref", ".", "getFloat", "(", "\"", "MeanFlight", "\"", ",", "0", ")", ";", "long", "users_max_hold", "=", "pref", ".", "getLong", "(", "\"", "MaxHold", "\"", ",", "0", ")", ";", "long", "users_min_hold", "=", "pref", ".", "getLong", "(", "\"", "MinHold", "\"", ",", "3000", ")", ";", "float", "users_mean_hold", "=", "pref", ".", "getFloat", "(", "\"", "MeanHold", "\"", ",", "0", ")", ";", "editor", ".", "apply", "(", ")", ";", "String", "storagesContainer", "=", "getConfigValue", "(", "context", ",", "\"", "storageContainer", "\"", ")", ";", "String", "storagesConnectionString", "=", "getConfigValue", "(", "context", ",", "\"", "storageConnectionString", "\"", ")", ";", "String", "country", "=", "getUserCountry", "(", "context", ")", ";", "try", "{", "if", "(", "(", "!", "prefs_id", ".", "isEmpty", "(", ")", "&&", "!", "prefs_age", ".", "isEmpty", "(", ")", "&&", "!", "prefs_gender", ".", "isEmpty", "(", ")", "&&", "!", "prefs_health", ".", "isEmpty", "(", ")", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "payload", ".", "size", "(", ")", ";", "i", "++", ")", "{", "JSONObject", "jsonObject", "=", "new", "JSONObject", "(", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "DOC_ID", "\"", ",", "payload", ".", "get", "(", "i", ")", ".", "DocID", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_ID", "\"", ",", "prefs_id", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_COUNTRY", "\"", ",", "country", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_AGE", "\"", ",", "prefs_age", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_GENDER", "\"", ",", "prefs_gender", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_EDUCATION", "\"", ",", "pref_education", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHONE_USAGE", "\"", ",", "pref_usage", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_INCOME", "\"", ",", "pref_income", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MEDICATION", "\"", ",", "pref_medication", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9", "\"", ",", "prefs_health", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_1", "\"", ",", "pref_phq9_item_1", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_2", "\"", ",", "pref_phq9_item_2", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_3", "\"", ",", "pref_phq9_item_3", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_4", "\"", ",", "pref_phq9_item_4", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_5", "\"", ",", "pref_phq9_item_5", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_6", "\"", ",", "pref_phq9_item_6", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_7", "\"", ",", "pref_phq9_item_7", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_8", "\"", ",", "pref_phq9_item_8", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_PHQ9_ITEM_9", "\"", ",", "pref_phq9_item_9", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MAX_FLIGHT", "\"", ",", "users_max_flight", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MIN_FLIGHT", "\"", ",", "users_min_flight", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MEAN_FLIGHT", "\"", ",", "users_mean_flight", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MAX_HOLD", "\"", ",", "users_max_hold", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MIN_HOLD", "\"", ",", "users_min_hold", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "USER_MEAN_HOLD", "\"", ",", "users_mean_hold", ")", ";", "CloudStorageAccount", "storageAccount", "=", "CloudStorageAccount", ".", "parse", "(", "storagesConnectionString", ")", ";", "CloudBlobClient", "blobClient", "=", "storageAccount", ".", "createCloudBlobClient", "(", ")", ";", "CloudBlobContainer", "container", "=", "blobClient", ".", "getContainerReference", "(", "storagesContainer", ")", ";", "String", "formattedDate", "=", "new", "SimpleDateFormat", "(", "\"", "yyyy-MM-dd", "\"", ",", "Locale", ".", "US", ")", ".", "format", "(", "new", "Date", "(", ")", ")", ";", "String", "formattedDateData", "=", "\"", "\"", ";", "try", "{", "Date", "date", "=", "new", "SimpleDateFormat", "(", "\"", "yyyy-MM-dd, hh:mm:ss", "\"", ",", "Locale", ".", "US", ")", ".", "parse", "(", "payload", ".", "get", "(", "i", ")", ".", "DateData", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "DATE_DATA", "\"", ",", "payload", ".", "get", "(", "i", ")", ".", "DateData", ")", ";", "formattedDate", "=", "new", "SimpleDateFormat", "(", "\"", "yyyy-MM-dd", "\"", ",", "Locale", ".", "US", ")", ".", "format", "(", "date", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "try", "{", "Date", "tempDate", "=", "new", "Date", "(", "payload", ".", "get", "(", "i", ")", ".", "DateData", ")", ";", "formattedDate", "=", "new", "SimpleDateFormat", "(", "\"", "yyyy-MM-dd", "\"", ",", "Locale", ".", "US", ")", ".", "format", "(", "tempDate", ")", ";", "formattedDateData", "=", "new", "SimpleDateFormat", "(", "\"", "yyyy-MM-dd, hh:mm:ss", "\"", ",", "Locale", ".", "US", ")", ".", "format", "(", "tempDate", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "DATE_DATA", "\"", ",", "formattedDateData", ")", ";", "}", "catch", "(", "Exception", "a", ")", "{", "Log", ".", "d", "(", "\"", "dateError", "\"", ",", "\"", "Even that failed", "\"", ")", ";", "}", "}", "jsonObject", ".", "accumulate", "(", "\"", "DATE_SEND", "\"", ",", "new", "SimpleDateFormat", "(", "\"", "yyyy-MM-dd, hh:mm:ss", "\"", ",", "Locale", ".", "US", ")", ".", "format", "(", "new", "Date", "(", ")", ")", ")", ";", "jsonObject", ".", "accumulate", "(", "\"", "SESSION_DATA", "\"", ",", "payload", ".", "get", "(", "i", ")", ".", "SessionData", ")", ";", "String", "blobName", "=", "prefs_id", "+", "\"", "/", "\"", "+", "formattedDate", "+", "\"", "/", "\"", "+", "payload", ".", "get", "(", "i", ")", ".", "DocID", "+", "\"", ".json", "\"", ";", "CloudBlockBlob", "blob", "=", "container", ".", "getBlockBlobReference", "(", "blobName", ")", ";", "blob", ".", "uploadText", "(", "jsonObject", ".", "toString", "(", ")", ")", ";", "result", "=", "\"", "success", "\"", ";", "myDB", ".", "setSend", "(", "payload", ".", "get", "(", "i", ")", ".", "DocID", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "result", "=", "\"", "failed", "\"", ";", "e", ".", "printStackTrace", "(", ")", ";", "Log", ".", "d", "(", "\"", "Upload", "\"", ",", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "return", "result", ";", "}", "private", "static", "String", "convertInputStreamToString", "(", "InputStream", "inputStream", ")", "throws", "IOException", "{", "BufferedReader", "bufferedReader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "inputStream", ")", ")", ";", "String", "line", "=", "\"", "\"", ";", "String", "result", "=", "\"", "\"", ";", "while", "(", "(", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "result", "+=", "line", ";", "inputStream", ".", "close", "(", ")", ";", "return", "result", ";", "}", "private", "Boolean", "userHaveAgreed", "(", ")", "{", "SharedPreferences", "pref", "=", "getSharedPreferences", "(", "\"", "user_info", "\"", ",", "Context", ".", "MODE_PRIVATE", ")", ";", "SharedPreferences", ".", "Editor", "editor", "=", "pref", ".", "edit", "(", ")", ";", "boolean", "pref_terms", "=", "pref", ".", "getBoolean", "(", "\"", "TermsAgreement", "\"", ",", "false", ")", ";", "editor", ".", "apply", "(", ")", ";", "return", "pref_terms", ";", "}", "public", "static", "String", "getConfigValue", "(", "Context", "context", ",", "String", "name", ")", "{", "Resources", "resources", "=", "context", ".", "getResources", "(", ")", ";", "try", "{", "InputStream", "rawResource", "=", "resources", ".", "openRawResource", "(", "R", ".", "raw", ".", "config", ")", ";", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "properties", ".", "load", "(", "rawResource", ")", ";", "return", "properties", ".", "getProperty", "(", "name", ")", ";", "}", "catch", "(", "Resources", ".", "NotFoundException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "Unable to find the config file: ", "\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "Failed to open config file.", "\"", ")", ";", "}", "return", "null", ";", "}", "private", "static", "class", "DataStoreAsyncTask", "extends", "AsyncTask", "<", "DataStoreAsyncTaskParams", ",", "Void", ",", "String", ">", "{", "WeakReference", "<", "Context", ">", "weakContext", ";", "private", "DataStoreAsyncTask", "(", "Context", "context", ")", "{", "weakContext", "=", "new", "WeakReference", "<", "Context", ">", "(", "context", ")", ";", "}", "@", "Override", "protected", "String", "doInBackground", "(", "DataStoreAsyncTaskParams", "...", "args", ")", "{", "Boolean", "result", "=", "false", ";", "KeyboardDynamics", "sessionDataTemp", ";", "sessionDataTemp", "=", "args", "[", "0", "]", ".", "data", ";", "ArrayList", "<", "Double", ">", "xTemp", "=", "new", "ArrayList", "<", "Double", ">", "(", "args", "[", "0", "]", ".", "x", ")", ";", "ArrayList", "<", "Double", ">", "yTemp", "=", "new", "ArrayList", "<", "Double", ">", "(", "args", "[", "0", "]", ".", "y", ")", ";", "if", "(", "sessionDataTemp", "!=", "null", ")", "{", "StopDateTimeTemp", "=", "new", "Date", "(", "sessionDataTemp", ".", "StopDateTime", ")", ";", "sessionDataTemp", ".", "CurrentMood", "=", "currentMood", ";", "sessionDataTemp", ".", "CurrentPhysicalState", "=", "currentPhysicalState", ";", "sessionDataTemp", ".", "LatestNotification", "=", "latestNotificationTime", ";", "int", "notificationFlag", "=", "0", ";", "if", "(", "latestNotificationTime", "!=", "0", ")", "{", "long", "minutesPassed", "=", "TimeUnit", ".", "MINUTES", ".", "convert", "(", "StopDateTimeTemp", ".", "getTime", "(", ")", "-", "latestNotificationTimeTemp", ".", "getTime", "(", ")", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "if", "(", "laterPressed", "&&", "minutesPassed", ">=", "120", ")", "{", "sessionDataTemp", ".", "CurrentMood", "=", "currentMood", "+", "\"", " TIMEOUT", "\"", ";", "sessionDataTemp", ".", "CurrentPhysicalState", "=", "currentPhysicalState", "+", "\"", " TIMEOUT", "\"", ";", "notificationFlag", "=", "1", ";", "laterPressed", "=", "false", ";", "}", "else", "if", "(", "minutesPassed", ">=", "120", "||", "(", "sessionsCounter", ">=", "30", "&&", "minutesPassed", ">=", "90", ")", ")", "{", "notificationFlag", "=", "1", ";", "sessionDataTemp", ".", "CurrentMood", "=", "currentMood", "+", "\"", " TIMEOUT", "\"", ";", "sessionDataTemp", ".", "CurrentPhysicalState", "=", "currentPhysicalState", "+", "\"", " TIMEOUT", "\"", ";", "}", "else", "{", "notificationFlag", "=", "0", ";", "}", "}", "else", "{", "notificationFlag", "=", "1", ";", "sessionDataTemp", ".", "CurrentMood", "=", "\"", "undefined", "\"", ";", "sessionDataTemp", ".", "CurrentPhysicalState", "=", "\"", "undefined", "\"", ";", "}", "if", "(", "notificationFlag", "==", "1", "&&", "sessionDataTemp", ".", "DownTime", ".", "size", "(", ")", ">", "5", ")", "{", "String", "title", "=", "\"", "TypeOfMood", "\"", ";", "String", "message", "=", "\"", "Please Expand to describe your mood!", "\"", ";", "sessionsCounter", "=", "0", ";", "nb", "=", "mNotificationHelper", ".", "getTypeOfMoodNotification", "(", "title", ",", "message", ",", "nb", ")", ";", "mNotificationHelper", ".", "getManager", "(", ")", ".", "notify", "(", "mNotificationHelper", ".", "notification_id", ",", "nb", ".", "build", "(", ")", ")", ";", "}", "if", "(", "sessionDataTemp", ".", "DownTime", ".", "size", "(", ")", ">=", "5", ")", "{", "long", "min_flight", "=", "3000", ";", "long", "max_flight", "=", "0", ";", "float", "average_flight", "=", "0", ";", "int", "num_flight", "=", "0", ";", "ArrayList", "<", "Long", ">", "flight_time", "=", "new", "ArrayList", "<", "Long", ">", "(", ")", ";", "long", "min_hold", "=", "3000", ";", "long", "max_hold", "=", "0", ";", "float", "average_hold", "=", "0", ";", "int", "num_hold", "=", "0", ";", "ArrayList", "<", "Long", ">", "hold_time", "=", "new", "ArrayList", "<", "Long", ">", "(", ")", ";", "double", "dist", "=", "0", ";", "double", "dx", "=", "0", ",", "dy", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "xTemp", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "dx", "=", "(", "xTemp", ".", "get", "(", "i", ")", "-", "xTemp", ".", "get", "(", "i", "+", "1", ")", ")", ";", "dy", "=", "(", "yTemp", ".", "get", "(", "i", ")", "-", "yTemp", ".", "get", "(", "i", "+", "1", ")", ")", ";", "dx", "=", "dx", "/", "densX", "*", "25.4f", ";", "dy", "=", "dy", "/", "densY", "*", "25.4f", ";", "dist", "=", "Math", ".", "hypot", "(", "dx", ",", "dy", ")", ";", "sessionDataTemp", ".", "Distance", ".", "add", "(", "dist", ")", ";", "flight_time", ".", "add", "(", "sessionDataTemp", ".", "DownTime", ".", "get", "(", "i", "+", "1", ")", "-", "sessionDataTemp", ".", "UpTime", ".", "get", "(", "i", ")", ")", ";", "long", "temp", "=", "flight_time", ".", "get", "(", "flight_time", ".", "size", "(", ")", "-", "1", ")", ";", "if", "(", "temp", "<", "min_flight", "&&", "temp", ">", "0", ")", "{", "min_flight", "=", "temp", ";", "}", "if", "(", "temp", ">", "max_flight", "&&", "temp", "<", "3000", ")", "{", "max_flight", "=", "temp", ";", "}", "if", "(", "temp", ">", "0", "&&", "temp", "<", "3000", ")", "{", "num_flight", "=", "num_flight", "+", "1", ";", "average_flight", "=", "(", "average_flight", "+", "temp", ")", ";", "}", "if", "(", "sessionDataTemp", ".", "IsLongPress", ".", "get", "(", "i", ")", "!=", "1", ")", "{", "hold_time", ".", "add", "(", "sessionDataTemp", ".", "UpTime", ".", "get", "(", "i", ")", "-", "sessionDataTemp", ".", "DownTime", ".", "get", "(", "i", ")", ")", ";", "long", "temp2", "=", "hold_time", ".", "get", "(", "hold_time", ".", "size", "(", ")", "-", "1", ")", ";", "if", "(", "temp2", "<", "min_hold", ")", "{", "min_hold", "=", "temp2", ";", "}", "if", "(", "temp2", ">", "max_hold", ")", "{", "max_hold", "=", "temp2", ";", "}", "num_hold", "=", "num_hold", "+", "1", ";", "average_hold", "=", "(", "average_hold", "+", "temp2", ")", ";", "}", "}", "average_hold", "=", "average_hold", "/", "num_hold", ";", "average_flight", "=", "average_flight", "/", "num_flight", ";", "SharedPreferences", "pref", "=", "weakContext", ".", "get", "(", ")", ".", "getSharedPreferences", "(", "\"", "user_info", "\"", ",", "Context", ".", "MODE_PRIVATE", ")", ";", "SharedPreferences", ".", "Editor", "editor", "=", "pref", ".", "edit", "(", ")", ";", "user_sessions", "=", "pref", ".", "getInt", "(", "\"", "Sessions_counter", "\"", ",", "1", ")", ";", "user_max_flight", "=", "pref", ".", "getLong", "(", "\"", "MaxFlight", "\"", ",", "0", ")", ";", "user_min_flight", "=", "pref", ".", "getLong", "(", "\"", "MinFlight", "\"", ",", "3000", ")", ";", "user_mean_flight", "=", "pref", ".", "getFloat", "(", "\"", "MeanFlight", "\"", ",", "0", ")", ";", "user_max_hold", "=", "pref", ".", "getLong", "(", "\"", "MaxHold", "\"", ",", "0", ")", ";", "user_min_hold", "=", "pref", ".", "getLong", "(", "\"", "MinHold", "\"", ",", "3000", ")", ";", "user_mean_hold", "=", "pref", ".", "getFloat", "(", "\"", "MeanHold", "\"", ",", "0", ")", ";", "if", "(", "min_flight", "<", "user_min_flight", ")", "{", "editor", ".", "putLong", "(", "\"", "MinFlight", "\"", ",", "min_flight", ")", ";", "}", "if", "(", "max_flight", ">", "user_max_flight", ")", "{", "editor", ".", "putLong", "(", "\"", "MaxFlight", "\"", ",", "max_flight", ")", ";", "}", "float", "temp_average", "=", "(", "user_mean_flight", "*", "user_sessions", "+", "average_flight", ")", "/", "(", "user_sessions", "+", "1", ")", ";", "editor", ".", "putFloat", "(", "\"", "MeanFlight", "\"", ",", "temp_average", ")", ";", "if", "(", "min_hold", "<", "user_min_hold", ")", "{", "editor", ".", "putLong", "(", "\"", "MinHold", "\"", ",", "min_hold", ")", ";", "}", "if", "(", "max_hold", ">", "user_max_hold", ")", "{", "editor", ".", "putLong", "(", "\"", "MaxHold", "\"", ",", "max_hold", ")", ";", "}", "if", "(", "average_hold", ">", "0", ")", "{", "temp_average", "=", "(", "user_mean_hold", "*", "user_sessions", "+", "average_hold", ")", "/", "(", "user_sessions", "+", "1", ")", ";", "editor", ".", "putFloat", "(", "\"", "MeanHold", "\"", ",", "temp_average", ")", ";", "}", "int", "temp_sessions", "=", "user_sessions", "+", "1", ";", "editor", ".", "putInt", "(", "\"", "Sessions_counter", "\"", ",", "temp_sessions", ")", ";", "editor", ".", "apply", "(", ")", ";", "Gson", "gson", "=", "new", "GsonBuilder", "(", ")", ".", "serializeNulls", "(", ")", ".", "create", "(", ")", ";", "String", "sessionDataString", "=", "gson", ".", "toJson", "(", "sessionDataTemp", ",", "KeyboardDynamics", ".", "class", ")", ";", "result", "=", "AddData", "(", "sessionDataString", ",", "weakContext", ".", "get", "(", ")", ")", ";", "sessionsCounter", "=", "sessionsCounter", "+", "1", ";", "long", "sendMinutesPassed", ";", "if", "(", "latestSendTimeTemp", "!=", "null", ")", "{", "sendMinutesPassed", "=", "TimeUnit", ".", "MINUTES", ".", "convert", "(", "(", "new", "Date", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ")", ".", "getTime", "(", ")", "-", "latestSendTimeTemp", ".", "getTime", "(", ")", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "else", "{", "sendMinutesPassed", "=", "61", ";", "}", "String", "send_result", "=", "\"", "not yet ", "\"", "+", "sendMinutesPassed", ";", "if", "(", "isConnected", "(", "weakContext", ".", "get", "(", ")", ")", "&&", "(", "sendMinutesPassed", ">=", "15", ")", ")", "{", "latestSendTimeTemp", "=", "new", "Date", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "DateFormat", "dateFormat", "=", "new", "SimpleDateFormat", "(", "\"", "EEE, d MMM yyyy HH:mm:ss", "\"", ")", ";", "editor", "=", "pref", ".", "edit", "(", ")", ";", "editor", ".", "putString", "(", "\"", "latest_send_date", "\"", ",", "dateFormat", ".", "format", "(", "latestSendTimeTemp", ")", ")", ";", "editor", ".", "apply", "(", ")", ";", "ArrayList", "<", "KeyboardPayload", ">", "notSendData", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "Cursor", "data", "=", "myDB", ".", "getNotSendContents", "(", ")", ";", "try", "{", "if", "(", "data", ".", "getCount", "(", ")", "!=", "0", ")", "{", "while", "(", "data", ".", "moveToNext", "(", ")", ")", "{", "KeyboardPayload", "payload", "=", "new", "KeyboardPayload", "(", ")", ";", "payload", ".", "DocID", "=", "data", ".", "getString", "(", "0", ")", ";", "payload", ".", "DateData", "=", "data", ".", "getString", "(", "1", ")", ";", "payload", ".", "SessionData", "=", "data", ".", "getString", "(", "2", ")", ";", "notSendData", ".", "add", "(", "payload", ")", ";", "}", "String", "locale", "=", "getUserCountry", "(", "weakContext", ".", "get", "(", ")", ")", ";", "Log", ".", "d", "(", "\"", "country", "\"", ",", "locale", ")", ";", "send_result", "=", "upload", "(", "notSendData", ",", "weakContext", ".", "get", "(", ")", ")", ";", "}", "else", "{", "Log", ".", "d", "(", "\"", "Upload", "\"", ",", "\"", "I'm in do in background 0 data", "\"", ")", ";", "}", "}", "finally", "{", "data", ".", "close", "(", ")", ";", "}", "}", "Log", ".", "w", "(", "\"", "Upload", "\"", ",", "\"", "Tried to send data with result: ", "\"", "+", "send_result", ")", ";", "}", "}", "if", "(", "result", ")", "{", "return", "\"", "success", "\"", ";", "}", "else", "{", "return", "\"", "failure", "\"", ";", "}", "}", "@", "Override", "protected", "void", "onPostExecute", "(", "String", "result", ")", "{", "}", "}", "private", "static", "class", "DataStoreAsyncTaskParams", "{", "KeyboardDynamics", "data", ";", "ArrayList", "<", "Double", ">", "x", ";", "ArrayList", "<", "Double", ">", "y", ";", "DataStoreAsyncTaskParams", "(", "KeyboardDynamics", "data", ",", "ArrayList", "<", "Double", ">", "x", ",", "ArrayList", "<", "Double", ">", "y", ")", "{", "this", ".", "data", "=", "data", ";", "this", ".", "x", "=", "new", "ArrayList", "<", "Double", ">", "(", "x", ")", ";", "this", ".", "y", "=", "new", "ArrayList", "<", "Double", ">", "(", "y", ")", ";", "}", "}", "private", "static", "class", "onShowNotificationAsync", "extends", "AsyncTask", "<", "Void", ",", "Void", ",", "String", ">", "{", "WeakReference", "<", "Context", ">", "weakContext", ";", "private", "onShowNotificationAsync", "(", "Context", "context", ")", "{", "weakContext", "=", "new", "WeakReference", "<", "Context", ">", "(", "context", ")", ";", "}", "@", "Override", "protected", "String", "doInBackground", "(", "Void", "...", "params", ")", "{", "int", "notificationFlag", "=", "0", ";", "Date", "StartDateTimeTemp", "=", "new", "Date", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "if", "(", "latestNotificationTime", "!=", "0", ")", "{", "long", "minutesPassed", "=", "TimeUnit", ".", "MINUTES", ".", "convert", "(", "StartDateTimeTemp", ".", "getTime", "(", ")", "-", "latestNotificationTimeTemp", ".", "getTime", "(", ")", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "if", "(", "laterPressed", "&&", "minutesPassed", ">=", "120", ")", "{", "notificationFlag", "=", "1", ";", "laterPressed", "=", "false", ";", "}", "else", "if", "(", "minutesPassed", ">=", "120", "||", "(", "sessionsCounter", ">=", "30", "&&", "minutesPassed", ">=", "90", ")", ")", "{", "notificationFlag", "=", "1", ";", "}", "else", "{", "notificationFlag", "=", "0", ";", "}", "}", "else", "{", "notificationFlag", "=", "1", ";", "}", "if", "(", "notificationFlag", "==", "1", ")", "{", "String", "title", "=", "\"", "TypeOfMood", "\"", ";", "String", "message", "=", "\"", "Please Expand to describe your mood!", "\"", ";", "sessionsCounter", "=", "0", ";", "nb", "=", "mNotificationHelper", ".", "getTypeOfMoodNotification", "(", "title", ",", "message", ",", "nb", ")", ";", "mNotificationHelper", ".", "getManager", "(", ")", ".", "notify", "(", "mNotificationHelper", ".", "notification_id", ",", "nb", ".", "build", "(", ")", ")", ";", "}", "return", "\"", "success", "\"", ";", "}", "@", "Override", "protected", "void", "onPostExecute", "(", "String", "result", ")", "{", "}", "}", "public", "static", "String", "getUserCountry", "(", "Context", "context", ")", "{", "try", "{", "final", "TelephonyManager", "tm", "=", "(", "TelephonyManager", ")", "context", ".", "getSystemService", "(", "Context", ".", "TELEPHONY_SERVICE", ")", ";", "final", "String", "simCountry", "=", "tm", ".", "getSimCountryIso", "(", ")", ";", "if", "(", "simCountry", "!=", "null", "&&", "simCountry", ".", "length", "(", ")", "==", "2", ")", "{", "return", "simCountry", ".", "toUpperCase", "(", "Locale", ".", "US", ")", ";", "}", "else", "if", "(", "tm", ".", "getPhoneType", "(", ")", "!=", "TelephonyManager", ".", "PHONE_TYPE_CDMA", ")", "{", "String", "networkCountry", "=", "tm", ".", "getNetworkCountryIso", "(", ")", ";", "if", "(", "networkCountry", "!=", "null", "&&", "networkCountry", ".", "length", "(", ")", "==", "2", ")", "{", "return", "networkCountry", ".", "toUpperCase", "(", "Locale", ".", "US", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "}", "return", "\"", "undefined", "\"", ";", "}", "}" ]
Input method implementation for Qwerty'ish keyboard.
[ "Input", "method", "implementation", "for", "Qwerty", "'", "ish", "keyboard", "." ]
[ "//azure info", "//remi0s", "// private static NotificationHelperPhysical mNotificationHelperPhysical ;", "// We expect to have only one decoder in almost all cases, hence the default capacity of 1.", "// If it turns out we need several, it will get grown seamlessly.", "// TODO: Move these {@link View}s to {@link KeyboardSwitcher}.", "// Working variable for {@link #startShowingInputView()} and", "// {@link #onEvaluateInputViewShown()}.", "// Object for reacting to adding/removing a dictionary pack.", "// Update this when adding new messages", "// We need to re-evaluate the currently composing word in case the script has", "// changed.", "// If we were able to reset the caches, then we can reload the keyboard.", "// Otherwise, we'll do it when we can.", "// Working variables for the following methods.", "// Typically this is the second onStartInput after orientation changed.", "// This is the first onStartInput after orientation changed.", "// Typically this is the second onStartInputView after orientation changed.", "// This is the first onStartInputView after orientation changed.", "// Typically this is the first onFinishInputView after orientation changed.", "// Typically this is the first onFinishInput after orientation changed.", "// Loading the native library eagerly to avoid unexpected UnsatisfiedLinkError at the initial", "// JNI call as much as possible.", "//remi0s", "//remi0s", "// TODO: Resolve mutual dependencies of {@link #loadSettings()} and", "// {@link #resetDictionaryFacilitatorIfNecessary()}.", "// Register to receive ringer mode change.", "// Register to receive installation and removal of a dictionary pack.", "// Has to be package-visible for unit tests", "// This method is called on startup and language switch, before the new layout has", "// been displayed. Opening dictionaries never affects responsivity as dictionaries are", "// asynchronously loaded.", "// Remove user history dictionaries.", "// Note that this method is called from a non-UI thread.", "// This happens in very rare corner cases - for example, immediately after a switch", "// to LatinIME has been requested, about a frame later another switch happens. In this", "// case, we are about to go down but we still don't know it, however the system tells", "// us there is no current subtype.", "// TODO: make sure the current settings always have the right locales, and read from them.", "// If the state of having a hardware keyboard changed, then we want to reload the", "// settings to adjust for that.", "// TODO: we should probably do this unconditionally here, rather than only when we", "// have a change in hardware keyboard configuration.", "// We call cleanupInternalStateForFinishInput() because it's the right thing to do;", "// however, it seems at the moment the framework is passing us a seemingly valid", "// but actually non-functional InputConnection object. So if this bug ever gets", "// fixed we'll be able to remove the composition, but until it is this code is", "// actually not doing much.", "// To ensure that CandidatesView will never be set.", "// }", "//store data", "// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()", "// is not guaranteed. It may even be called at the same time on a different thread.", "// If the primary hint language does not match the current subtype language, then try", "// to switch to the primary hint language.", "// TODO: Support all the locales in EditorInfo#hintLocales.", "// Switch to the null consumer to handle cases leading to early exit below, for which we", "// also wouldn't be consuming gesture data.", "// If we are starting input in a different text field from before, we'll have to reload", "// settings, so currentSettingsValues can't be final.", "// TODO: Consolidate these checks with {@link InputAttributes}.", "// In landscape mode, this method gets called without the input view being created.", "// Update to a gesture consumer with the current editor and IME state.", "// Forward this event to the accessibility utilities, if enabled.", "// The EditorInfo might have a flag that affects fullscreen mode.", "// Note: This call should be done by InputMethodService?", "// ALERT: settings have not been reloaded and there is a chance they may be stale.", "// In the practice, if it is, we should have gotten onConfigurationChanged so it should", "// be fine, but this is horribly confusing and must be fixed AS SOON AS POSSIBLE.", "// In some cases the input connection has not been reset yet and we can't access it. In", "// this case we will need to call loadKeyboard() later, when it's accessible, so that we", "// can go into the correct mode, so we need to do some housekeeping here.", "// The app calling setText() has the effect of clearing the composing", "// span, so we should reset our state unconditionally, even if restarting is true.", "// We also tell the input logic about the combining rules for the current subtype, so", "// it can adjust its combiners if needed.", "// TODO[IL]: Can the following be moved to InputLogic#startInput?", "// Sometimes, while rotating, for some reason the framework tells the app we are not", "// connected to it and that means we can't refresh the cache. In this case, schedule", "// a refresh later.", "// We try resetting the caches up to 5 times before giving up.", "// mLastSelection{Start,End} are reset later in this method, no need to do it here", "// When rotating, and when input is starting again in a field from where the focus", "// didn't move (the keyboard having been closed with the back key),", "// initialSelStart and initialSelEnd sometimes are lying. Make a best effort to", "// work around this bug.", "// If we have a hardware keyboard we don't need to call loadKeyboard later anyway.", "// If we need to call loadKeyboard again later, we need to save its state now. The", "// later call will be done in #retryResetCaches.", "// TODO: Come up with a more comprehensive way to reset the keyboard layout when", "// a keyboard layout set doesn't get reloaded in this method.", "// In apps like Talk, we come here when the text is sent and the field gets emptied and", "// we need to re-evaluate the shift state, but not the whole layout which would be", "// disruptive.", "// Space state must be updated before calling updateShiftState", "// This will set the punctuation suggestions if next word suggestion is off;", "// otherwise it will clear the suggestion strip.", "// Remove pending messages related to update suggestions", "// Should do the following in onFinishInputInternal but until JB MR2 it's not called :(", "// This call happens whether our view is displayed or not, but if it's not then we should", "// not attempt recorrection. This is true even with a hardware keyboard connected: if the", "// view is not displayed we have no means of showing suggestions anyway, and if it is then", "// we want to show suggestions anyway.", "// If we have an update request in flight, we need to cancel it so it does not override", "// these completions.", "// When in fullscreen mode, show completions generated by the application forcibly", "// This method may be called before {@link #setInputView(View)}.", "// If there is a hardware keyboard and a visible software keyboard view has been hidden,", "// no visual element will be shown on the screen.", "// Need to set expanded touchable region only if a keyboard view is being shown.", "// Extend touchable region below the keyboard.", "// This {@link #showWindow(boolean)} will eventually call back", "// {@link #onEvaluateInputViewShown()}.", "//Collect Data remi0s", "//notification", "// If there is a hardware keyboard, disable full screen mode.", "// Reread resource value here, because this method is called by the framework as needed.", "// TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI", "// implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI", "// without NO_FULLSCREEN doesn't work as expected. Because of this we need this", "// hack for now. Let's get rid of this once the framework gets fixed.", "// Override layout parameters to expand {@link SoftInputWindow} to the entire screen.", "// See {@link InputMethodService#setinputView(View)} and", "// {@link SoftInputWindow#updateWidthHeight(WindowManager.LayoutParams)}.", "// This method may be called before {@link #setInputView(View)}.", "// In non-fullscreen mode, {@link InputView} and its parent inputArea should expand to", "// the entire screen and be placed at the bottom of {@link SoftInputWindow}.", "// In fullscreen mode, these shouldn't expand to the entire screen and should be", "// coexistent with {@link #mExtractedArea} above.", "// See {@link InputMethodService#setInputView(View) and", "// com.ime.internal.R.layout.input_method.xml.", "// Callback for the {@link SuggestionStripView}, to call when the important notice strip is", "// pressed.", "// TODO: Revise the language switch key behavior to make it much smarter and more reasonable.", "//remi0s", "// TODO: Instead of checking for alphabetic keyboard here, separate keycodes for", "// alphabetic shift and shift while in symbol layout and get rid of this method.", "// Implementation of {@link KeyboardActionListener}.", "// TODO: this processing does not belong inside LatinIME, the caller should be doing this.", "// x and y include some padding, but everything down the line (especially native", "// code) needs the coordinates in the keyboard frame.", "// TODO: We should reconsider which coordinate system should be used to represent", "// keyboard event. Also we should pull this up -- LatinIME has no business doing", "// this transformation, it should be done already before calling onEvent.", "// This method is public for testability of LatinIME, but also in the future it should", "// completely replace #onCodeInput.", "// A helper method to split the code point and the key code. Ultimately, they should not be", "// squashed into the same variable, and this method should be removed.", "// public for testing, as we don't want to copy the same logic into test code", "// Called from PointerTracker through the KeyboardActionListener interface", "// TODO: have the keyboard pass the correct key code when we need it.", "// This method must run on the UI Thread.", "// Called from PointerTracker through the KeyboardActionListener interface", "// User finished sliding input.", "// Called from PointerTracker through the KeyboardActionListener interface", "// User released a finger outside any key", "// Nothing to do so far.", "// TODO: Modify this when we support suggestions with hard keyboard", "// We should clear the contextual strip if there is no suggestion from dictionaries.", "// TODO[IL]: Move this out of LatinIME.", "// Cache the auto-correction in accessibility code so we can speak it if the user", "// touches a key that will insert it.", "// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}", "// interface", "// This will show either an empty suggestion strip (if prediction is enabled) or", "// punctuation suggestions (if it's disabled).", "// Outside LatinIME, only used by the {@link InputTestsBase} test suite.", "// Since we are switching languages, the most urgent thing is to let the keyboard graphics", "// update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on", "// the screen. Anything we do right now will delay this, so wait until the next frame", "// before we do the rest, like reopening dictionaries and updating suggestions. So we", "// post a message.", "// Reload keyboard because the current language has been changed.", "// SHIFT_NO_UPDATE", "// Suggestion strip press: no input.", "// No need to feedback while finger is dragging.", "// No need to feedback when repeat delete key will have no effect.", "// TODO: Use event time that the last feedback has been generated instead of relying on", "// a repeat count to thin out feedback.", "// TODO: Reconsider how to perform haptic feedback when repeating key.", "// Callback of the {@link KeyboardActionListener}. This is called when a key is depressed;", "// release matching call is {@link #onReleaseKey(int,boolean)} below.", "// Callback of the {@link KeyboardActionListener}. This is called when a key is released;", "// press matching call is {@link #onPressKey(int,int,boolean)} above.", "// TODO: create the decoder according to the specification", "// Hooks for hardware keyboard", "// If the event is not handled by LatinIME, we just pass it to the parent implementation.", "// If it's handled, we return true because we did handle it.", "// TODO: this is not necessarily correct for a hardware keyboard right now", "// onKeyDown and onKeyUp are the main events we are interested in. There are two more events", "// related to handling of hardware key events that we may want to implement in the future:", "// boolean onKeyLongPress(final int keyCode, final KeyEvent event);", "// boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event);", "// receive ringer mode change.", "// TODO: Should use new string \"Select active input modes\".", "// final Intent intent = IntentUtils.getInputLanguageSelectionIntent(", "// imeId,", "// FLAG_ACTIVITY_NEW_TASK", "// | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED //remi0s commented", "// | Intent.FLAG_ACTIVITY_CLEAR_TOP);", "// intent.putExtra(Intent.EXTRA_TITLE, languageSelectionTitle);", "// startActivity(intent);", "//remi0s fixed bug", "// TODO: Move this method out of {@link LatinIME}.", "// You may not use this method for anything else than debug", "// DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME.", "// DO NOT USE THIS for any other purpose than testing. This can break the keyboard badly.", "// DO NOT USE THIS for any other purpose than testing.", "// TODO: Dump all settings values", "// TODO: Revisit here to reorganize the settings. Probably we can/should use different", "// strategy once the implementation of", "// {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well.", "// return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue);", "//remi0s to block changing to other keyboards", "// TODO: Revisit here to reorganize the settings. Probably we can/should use different", "// strategy once the implementation of", "// {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well.", "// For N and later, IMEs can specify Color.TRANSPARENT to make the navigation bar", "// transparent. For other colors the system uses the default color.", "// NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();", "// public static class HttpAsyncTask extends AsyncTask<String, Void, String> {", "// String result=\"\";", "// @Override", "// protected String doInBackground(String... params) {", "// String prefs_id=params[0];", "// String prefs_age=params[1];", "// String prefs_gender=params[2];", "// String prefs_health=params[3];", "// ArrayList<KeyboardPayload> notSendData = new ArrayList<>();", "// Cursor data = myDB.getNotSendContents();", "// try {", "// if (data.getCount() != 0) {", "// while (data.moveToNext()) {", "// KeyboardPayload payload=new KeyboardPayload();", "// payload.DocID=data.getString(0);//DocID", "// payload.DateData=data.getString(1); //DateTime", "//// payload.UserID=data.getString(2); //UserID", "// payload.SessionData= data.getString(2); //SessionData", "// notSendData.add(payload);", "// }", "// result=upload(notSendData,prefs_id,prefs_age,prefs_gender,prefs_health, storageConnectionString, storageContainer);//POST(urls[0],notSendData);", "// }else{", "// Log.d(\"SQL\",\"I'm in do in background 0 data\");", "// }", "// } finally {", "// data.close();", "// }", "//", "//", "//", "// return result;", "// }", "// // onPostExecute displays the results of the AsyncTask.", "// @Override", "// protected void onPostExecute(String result) {", "// Log.d(\"SQL\",\"Tried to send data with result: \"+result);", "//// Toast.makeText(getBaseContext(), \"Data Sent!\", Toast.LENGTH_LONG).show();", "// }", "// }", "// public static String oldPOST(String url,ArrayList<KeyboardPayload> payload){", "// InputStream inputStream = null;", "// String result = \"\";", "//", "//", "// try {", "// // 1. create HttpClient", "// HttpClient httpclient = new DefaultHttpClient();", "//", "// // 2. make POST request to the given URL", "// HttpPost httpPost = new HttpPost(url);", "//", "// String json = \"\";", "//", "// if((!pref_ID.isEmpty() && !pref_age.isEmpty() && !pref_gender.isEmpty() && !pref_health.isEmpty())){", "//", "// for(int i = 0; i < payload.size(); i++) { //payload.size()", "//", "// // 3. build jsonObject", "//", "//", "//", "//", "// JSONObject jsonObject = new JSONObject();", "// jsonObject.accumulate(\"DOC_ID\", payload.get(i).DocID);", "// jsonObject.accumulate(\"USER_ID\",pref_ID);", "// jsonObject.accumulate(\"USER_AGE\", pref_age);", "// jsonObject.accumulate(\"USER_GENDER\", pref_gender);", "// jsonObject.accumulate(\"USER_PHQ9\", pref_health);", "// jsonObject.accumulate(\"DATE_DATA\", payload.get(i).DateData);", "// jsonObject.accumulate(\"SESSION_DATA\", payload.get(i).SessionData);", "//", "//", "// // 4. convert JSONObject to JSON to String", "// json = jsonObject.toString();", "//", "// Log.d(\"server\",\"Json to be sent:\\n\"+json);", "//", "//", "// // ** Alternative way to convert Person object to JSON string usin Jackson Lib", "// // ObjectMapper mapper = new ObjectMapper();", "// // json = mapper.writeValueAsString(person);", "//// Gson gson = new Gson();", "//// json = gson.toJson(payload.get(i), KeyboardPayload.class);", "//", "// // 5. set json to StringEntity", "// StringEntity se = new StringEntity(json);", "//", "// // 6. set httpPost Entity", "// httpPost.setEntity(se);", "//", "// // 7. Set some headers to inform server about the type of the content", "// httpPost.setHeader(\"Accept\", \"application/json\");", "// httpPost.setHeader(\"Content-type\", \"application/json\");", "//", "// // 8. Execute POST request to the given URL", "// HttpResponse httpResponse = httpclient.execute(httpPost);", "//", "// // 9. receive response as inputStream", "// inputStream = httpResponse.getEntity().getContent();", "//", "//", "//", "//", "// // 10. convert inputstream to string", "// if(inputStream != null) {", "// result = convertInputStreamToString(inputStream);", "// Log.d(\"SQL\",\"I'm at inputstream\");", "// myDB.setSend(payload.get(i).DocID);", "// Log.d(\"SQL\",\"Data Sent!\");", "// }", "// else {", "// result = \"Did not work!\";", "// }", "//", "// }", "// }", "//", "//", "//", "//", "// } catch (Exception e) {", "// Log.d(\"InputStream\", e.getLocalizedMessage());", "// }", "//", "// // 11. return result", "// return result;", "// }", "//payload.size()", "// 3. build jsonObject", "// jsonObject.accumulate(\"DATE_DATA\", payload.get(i).DateData);", "// jsonObject.accumulate(\"SESSION_DATA\", payload.get(i).SessionData);", "// 4. convert JSONObject to JSON to String", "// Retrieve storage account from connection-string.", "// Create the blob client.", "// Retrieve reference to a previously created container.", "// Create or overwrite the blob (with the name \"example.jpeg\") with contents from a local file.", "// Output the stack trace.", "// private Boolean isPasswordGivenCorrect () {", "//// SharedPreferences pref =getSharedPreferences(\"user_info\", Context.MODE_PRIVATE);", "//// SharedPreferences.Editor editor = pref.edit();", "//// String pref_password= pref.getString(\"Password\", \"\");", "//// editor.apply();", "//// //return (pref_password.equals(getConfigValue(getApplicationContext(), \"password\")));", "//// return true;", "//// }", "// sessionDataTemp.StopDateTime = System.currentTimeMillis();", "// mNotificationHelperPhysical = new NotificationHelperPhysical(weakContext.get());", "// NotificationCompat.Builder nbPhysical = mNotificationHelperPhysical.getTypeOfMoodNotification(title, message);", "// mNotificationHelperPhysical.getManager().notify(mNotificationHelperPhysical.notification_id, nbPhysical.build());", "// mNotificationHelper = new NotificationHelper(weakContext.get());", "// CreateAlertDialogWithRadioButtonGroup();", "//flight time", "//hold time", "//end for i size downtime", "//flight time", "//hold time", "//if not all was longpressed", "//save data", "// Log.d(\"Json\", \"Json string: \" + sessionDataString);", "//send data", "//DocID", "//DateTime", "// payload.UserID=data.getString(2); //UserID", "//SessionData", "//POST(urls[0],notSendData);", "// onPostExecute displays the results of the AsyncTask.", "// Log.d(\"SQL\",\"Tried to save data with result: \"+result);", "// Toast.makeText(getBaseContext(), \"Data Sent!\", Toast.LENGTH_LONG).show();", "// String prefs_id;", "// String prefs_age;", "// String prefs_gender;", "// String prefs_health;", "// String storageConnectionString;", "// String storageContainer;", "// this.prefs_id=prefs_id;", "// this.prefs_age=prefs_age;", "// this.prefs_gender=prefs_gender;", "// this.prefs_health=prefs_health;", "// this.storageConnectionString=storageConnectionString;", "// this.storageContainer=storageContainer;", "//notification", "// sessionData.CurrentMood =currentMood+\" TIMEOUT\";", "// sessionData.CurrentPhysicalState=currentPhysicalState+\" TIMEOUT\";", "// sessionData.CurrentMood = currentMood + \" TIMEOUT\";", "// sessionData.CurrentPhysicalState = currentPhysicalState + \" TIMEOUT\";", "// sessionData.CurrentMood = \"undefined\";", "// sessionData.CurrentPhysicalState=\"undefined\";", "// mNotificationHelperPhysical = new NotificationHelperPhysical(weakContext.get());", "// NotificationCompat.Builder nbPhysical = mNotificationHelperPhysical.getTypeOfMoodNotification(title, message);", "// mNotificationHelperPhysical.getManager().notify(mNotificationHelperPhysical.notification_id, nbPhysical.build());", "// CreateAlertDialogWithRadioButtonGroup();", "// onPostExecute displays the results of the AsyncTask.", "// Log.d(\"SQL\",\"Tried to save data with result: \"+result);", "// Toast.makeText(getBaseContext(), \"Data Sent!\", Toast.LENGTH_LONG).show();", "// SIM country code is available", "// device is not 3G (would be unreliable)", "// network country code is available" ]
[ { "param": "InputMethodService", "type": null }, { "param": "KeyboardActionListener,\n SuggestionStripView.Listener, SuggestionStripViewAccessor,\n DictionaryFacilitator.DictionaryInitializationListener,\n PermissionsManager.PermissionsResultCallback", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "InputMethodService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "KeyboardActionListener,\n SuggestionStripView.Listener, SuggestionStripViewAccessor,\n DictionaryFacilitator.DictionaryInitializationListener,\n PermissionsManager.PermissionsResultCallback", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b65798cc8c996cc96a09b43d379490901b08f30
Intuitio-OU/datatools-server
src/main/java/com/conveyal/datatools/manager/controllers/api/ProjectController.java
[ "MIT" ]
Java
ProjectController
/** * Created by demory on 3/14/16. */
Created by demory on 3/14/16.
[ "Created", "by", "demory", "on", "3", "/", "14", "/", "16", "." ]
@SuppressWarnings({"unused", "ThrowableNotThrown"}) public class ProjectController { public static JsonManager<Project> json = new JsonManager<>(Project.class, JsonViews.UserInterface.class); public static final Logger LOG = LoggerFactory.getLogger(ProjectController.class); private static ObjectMapper mapper = new ObjectMapper(); private static Collection<Project> getAllProjects(Request req, Response res) throws JsonProcessingException { Auth0UserProfile userProfile = req.attribute("user"); return Project.getAll().stream() .filter(p -> req.pathInfo().matches(publicPath) || userProfile.hasProject(p.id, p.organizationId)) .map(p -> requestProject(req, p, "view")) .collect(Collectors.toList()); } private static Project getProject(Request req, Response res) { return requestProjectById(req, "view"); } private static Project createProject(Request req, Response res) { Project p = new Project(); try { applyJsonToProject(p, req.body()); p.save(); } catch (Exception e) { e.printStackTrace(); halt(400, SparkUtils.formatJSON("Error saving new project")); } return p; } private static Project updateProject(Request req, Response res) throws IOException { Project p = requestProjectById(req, "manage"); try { applyJsonToProject(p, req.body()); p.save(); } catch (Exception e) { e.printStackTrace(); halt(400, SparkUtils.formatJSON("Error saving project")); } return p; } private static Project deleteProject(Request req, Response res) throws IOException { Project p = requestProjectById(req, "manage"); p.delete(); return p; } public static Boolean fetch(Request req, Response res) { Auth0UserProfile userProfile = req.attribute("user"); Project p = requestProjectById(req, "manage"); FetchProjectFeedsJob fetchProjectFeedsJob = new FetchProjectFeedsJob(p, userProfile.getUser_id()); // this is runnable because sometimes we schedule the task for a later time, but here we call it immediately // because it is short lived and just cues more work fetchProjectFeedsJob.run(); return true; } private static void applyJsonToProject(Project p, String json) throws IOException { JsonNode node = mapper.readTree(json); boolean updateFetchSchedule = false; Iterator<Map.Entry<String, JsonNode>> fieldsIter = node.fields(); while (fieldsIter.hasNext()) { Map.Entry<String, JsonNode> entry = fieldsIter.next(); if(entry.getKey().equals("name")) { p.name = entry.getValue().asText(); } else if(entry.getKey().equals("defaultLocationLat")) { p.defaultLocationLat = entry.getValue().asDouble(); LOG.info("updating default lat"); } else if(entry.getKey().equals("defaultLocationLon")) { p.defaultLocationLon = entry.getValue().asDouble(); LOG.info("updating default lon"); } else if(entry.getKey().equals("north")) { p.north = entry.getValue().asDouble(); } else if(entry.getKey().equals("south")) { p.south = entry.getValue().asDouble(); } else if(entry.getKey().equals("east")) { p.east = entry.getValue().asDouble(); } else if(entry.getKey().equals("west")) { p.west = entry.getValue().asDouble(); } else if(entry.getKey().equals("organizationId")) { p.organizationId = entry.getValue().asText(); } else if(entry.getKey().equals("osmNorth")) { p.osmNorth = entry.getValue().asDouble(); } else if(entry.getKey().equals("osmSouth")) { p.osmSouth = entry.getValue().asDouble(); } else if(entry.getKey().equals("osmEast")) { p.osmEast = entry.getValue().asDouble(); } else if(entry.getKey().equals("osmWest")) { p.osmWest = entry.getValue().asDouble(); } else if(entry.getKey().equals("useCustomOsmBounds")) { p.useCustomOsmBounds = entry.getValue().asBoolean(); } else if(entry.getKey().equals("defaultLanguage")) { p.defaultLanguage = entry.getValue().asText(); } else if(entry.getKey().equals("defaultTimeZone")) { p.defaultTimeZone = entry.getValue().asText(); } else if(entry.getKey().equals("autoFetchHour")) { p.autoFetchHour = entry.getValue().asInt(); updateFetchSchedule = true; } else if(entry.getKey().equals("autoFetchMinute")) { p.autoFetchMinute = entry.getValue().asInt(); updateFetchSchedule = true; } else if(entry.getKey().equals("autoFetchFeeds")) { p.autoFetchFeeds = entry.getValue().asBoolean(); updateFetchSchedule = true; } // NOTE: the below keys require the full objects to be included in the request json, // otherwise the missing fields/sub-classes will be set to null else if(entry.getKey().equals("otpServers")) { p.otpServers = mapper.readValue(String.valueOf(entry.getValue()), new TypeReference<List<OtpServer>>(){}); } else if (entry.getKey().equals("buildConfig")) { p.buildConfig = mapper.treeToValue(entry.getValue(), OtpBuildConfig.class); } else if (entry.getKey().equals("routerConfig")) { p.routerConfig = mapper.treeToValue(entry.getValue(), OtpRouterConfig.class); } } if (updateFetchSchedule) { // If auto fetch flag is turned on if (p.autoFetchFeeds){ int interval = 1; // once per day interval DataManager.autoFetchMap.put(p.id, scheduleAutoFeedFetch(p.id, p.autoFetchHour, p.autoFetchMinute, interval, p.defaultTimeZone)); } // otherwise, cancel any existing task for this id else{ cancelAutoFetch(p.id); } } } /** * Helper function returns feed source if user has permission for specified action. * @param req spark Request object from API request * @param action action type (either "view" or "manage") * @return requested project */ private static Project requestProjectById(Request req, String action) { String id = req.params("id"); if (id == null) { halt(SparkUtils.formatJSON("Please specify id param", 400)); } return requestProject(req, Project.get(id), action); } private static Project requestProject(Request req, Project p, String action) { Auth0UserProfile userProfile = req.attribute("user"); boolean publicFilter = req.pathInfo().matches(publicPath); // check for null project if (p == null) { halt(400, SparkUtils.formatJSON("Project ID does not exist", 400)); return null; } boolean authorized; switch (action) { // TODO: limit create action to app/org admins? // case "create": // authorized = userProfile.canAdministerOrganization(p.organizationId); // break; case "manage": authorized = userProfile.canAdministerProject(p.id, p.organizationId); break; case "view": // request only authorized if not via public path and user can view authorized = !publicFilter && userProfile.hasProject(p.id, p.organizationId); break; default: authorized = false; break; } // if requesting all projects via public route, include public feed sources if (publicFilter){ p.feedSources = p.getProjectFeedSources().stream() .filter(fs -> fs.isPublic) .collect(Collectors.toList()); } else { p.feedSources = null; if (!authorized) { halt(403, SparkUtils.formatJSON("User not authorized to perform action on project", 403)); return null; } } // if we make it here, user has permission and it's a valid project return p; } private static boolean downloadMergedFeed(Request req, Response res) throws IOException { Project project = requestProjectById(req, "view"); Auth0UserProfile userProfile = req.attribute("user"); // TODO: make this an authenticated call? MergeProjectFeedsJob mergeProjectFeedsJob = new MergeProjectFeedsJob(project, userProfile.getUser_id()); DataManager.heavyExecutor.execute(mergeProjectFeedsJob); return true; } /** * Returns credentials that a client may use to then download a feed version. Functionality * changes depending on whether application.data.use_s3_storage config property is true. */ public static Object getFeedDownloadCredentials(Request req, Response res) { Project project = requestProjectById(req, "view"); // if storing feeds on s3, return temporary s3 credentials for that zip file if (DataManager.useS3) { return getS3Credentials(DataManager.awsRole, DataManager.feedBucket, "project/" + project.id + ".zip", Statement.Effect.Allow, S3Actions.GetObject, 900); } else { // when feeds are stored locally, single-use download token will still be used FeedDownloadToken token = new FeedDownloadToken(project); token.save(); return token; } } private static boolean deployPublic(Request req, Response res) { Auth0UserProfile userProfile = req.attribute("user"); String id = req.params("id"); if (id == null) { halt(400, "must provide project id!"); } Project p = Project.get(id); if (p == null) halt(400, "no such project!"); // run as sync job; if it gets too slow change to async new MakePublicJob(p, userProfile.getUser_id()).run(); return true; } private static Project thirdPartySync(Request req, Response res) throws Exception { Auth0UserProfile userProfile = req.attribute("user"); String id = req.params("id"); Project proj = Project.get(id); String syncType = req.params("type"); if (!userProfile.canAdministerProject(proj.id, proj.organizationId)) halt(403); LOG.info("syncing with third party " + syncType); if(DataManager.feedResources.containsKey(syncType)) { DataManager.feedResources.get(syncType).importFeedsForProject(proj, req.headers("Authorization")); return proj; } halt(404); return null; } public static ScheduledFuture scheduleAutoFeedFetch (String id, int hour, int minute, int intervalInDays, String timezoneId){ TimeUnit minutes = TimeUnit.MINUTES; try { // First cancel any already scheduled auto fetch task for this project id. cancelAutoFetch(id); Project p = Project.get(id); if (p == null) return null; ZoneId timezone; try { timezone = ZoneId.of(timezoneId); }catch(Exception e){ timezone = ZoneId.of("America/New_York"); } LOG.info("Scheduling auto-fetch for projectID: {}", p.id); // NOW in default timezone ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), timezone); // SCHEDULED START TIME ZonedDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(hour, minute)).atZone(timezone); LOG.info("Now: {}", now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); LOG.info("Scheduled start time: {}", startTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); // Get diff between start time and current time long diffInMinutes = (startTime.toEpochSecond() - now.toEpochSecond()) / 60; long delayInMinutes; if ( diffInMinutes >= 0 ){ delayInMinutes = diffInMinutes; // delay in minutes } else{ delayInMinutes = 24 * 60 + diffInMinutes; // wait for one day plus difference (which is negative) } LOG.info("Auto fetch begins in {} hours and runs every {} hours", String.valueOf(delayInMinutes / 60.0), TimeUnit.DAYS.toHours(intervalInDays)); // system is defined as owner because owner field must not be null FetchProjectFeedsJob fetchProjectFeedsJob = new FetchProjectFeedsJob(p, "system"); return DataManager.scheduler.scheduleAtFixedRate(fetchProjectFeedsJob, delayInMinutes, TimeUnit.DAYS.toMinutes(intervalInDays), minutes); } catch (Exception e) { e.printStackTrace(); return null; } } private static void cancelAutoFetch(String id){ Project p = Project.get(id); if ( p != null && DataManager.autoFetchMap.get(p.id) != null) { LOG.info("Cancelling auto-fetch for projectID: {}", p.id); DataManager.autoFetchMap.get(p.id).cancel(true); } } public static void register (String apiPrefix) { get(apiPrefix + "secure/project/:id", ProjectController::getProject, json::write); get(apiPrefix + "secure/project", ProjectController::getAllProjects, json::write); post(apiPrefix + "secure/project", ProjectController::createProject, json::write); put(apiPrefix + "secure/project/:id", ProjectController::updateProject, json::write); delete(apiPrefix + "secure/project/:id", ProjectController::deleteProject, json::write); get(apiPrefix + "secure/project/:id/thirdPartySync/:type", ProjectController::thirdPartySync, json::write); post(apiPrefix + "secure/project/:id/fetch", ProjectController::fetch, json::write); post(apiPrefix + "secure/project/:id/deployPublic", ProjectController::deployPublic, json::write); get(apiPrefix + "secure/project/:id/download", ProjectController::downloadMergedFeed); get(apiPrefix + "secure/project/:id/downloadtoken", ProjectController::getFeedDownloadCredentials, json::write); get(apiPrefix + "public/project/:id", ProjectController::getProject, json::write); get(apiPrefix + "public/project", ProjectController::getAllProjects, json::write); get(apiPrefix + "downloadprojectfeed/:token", ProjectController::downloadMergedFeedWithToken); } private static Object downloadMergedFeedWithToken(Request req, Response res) { FeedDownloadToken token = FeedDownloadToken.get(req.params("token")); if(token == null || !token.isValid()) { halt(400, "Feed download token not valid"); } Project project = token.getProject(); token.delete(); String fileName = project.id + ".zip"; return downloadFile(FeedVersion.feedStore.getFeed(fileName), fileName, res); } }
[ "@", "SuppressWarnings", "(", "{", "\"", "unused", "\"", ",", "\"", "ThrowableNotThrown", "\"", "}", ")", "public", "class", "ProjectController", "{", "public", "static", "JsonManager", "<", "Project", ">", "json", "=", "new", "JsonManager", "<", ">", "(", "Project", ".", "class", ",", "JsonViews", ".", "UserInterface", ".", "class", ")", ";", "public", "static", "final", "Logger", "LOG", "=", "LoggerFactory", ".", "getLogger", "(", "ProjectController", ".", "class", ")", ";", "private", "static", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "private", "static", "Collection", "<", "Project", ">", "getAllProjects", "(", "Request", "req", ",", "Response", "res", ")", "throws", "JsonProcessingException", "{", "Auth0UserProfile", "userProfile", "=", "req", ".", "attribute", "(", "\"", "user", "\"", ")", ";", "return", "Project", ".", "getAll", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "p", "->", "req", ".", "pathInfo", "(", ")", ".", "matches", "(", "publicPath", ")", "||", "userProfile", ".", "hasProject", "(", "p", ".", "id", ",", "p", ".", "organizationId", ")", ")", ".", "map", "(", "p", "->", "requestProject", "(", "req", ",", "p", ",", "\"", "view", "\"", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "private", "static", "Project", "getProject", "(", "Request", "req", ",", "Response", "res", ")", "{", "return", "requestProjectById", "(", "req", ",", "\"", "view", "\"", ")", ";", "}", "private", "static", "Project", "createProject", "(", "Request", "req", ",", "Response", "res", ")", "{", "Project", "p", "=", "new", "Project", "(", ")", ";", "try", "{", "applyJsonToProject", "(", "p", ",", "req", ".", "body", "(", ")", ")", ";", "p", ".", "save", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "halt", "(", "400", ",", "SparkUtils", ".", "formatJSON", "(", "\"", "Error saving new project", "\"", ")", ")", ";", "}", "return", "p", ";", "}", "private", "static", "Project", "updateProject", "(", "Request", "req", ",", "Response", "res", ")", "throws", "IOException", "{", "Project", "p", "=", "requestProjectById", "(", "req", ",", "\"", "manage", "\"", ")", ";", "try", "{", "applyJsonToProject", "(", "p", ",", "req", ".", "body", "(", ")", ")", ";", "p", ".", "save", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "halt", "(", "400", ",", "SparkUtils", ".", "formatJSON", "(", "\"", "Error saving project", "\"", ")", ")", ";", "}", "return", "p", ";", "}", "private", "static", "Project", "deleteProject", "(", "Request", "req", ",", "Response", "res", ")", "throws", "IOException", "{", "Project", "p", "=", "requestProjectById", "(", "req", ",", "\"", "manage", "\"", ")", ";", "p", ".", "delete", "(", ")", ";", "return", "p", ";", "}", "public", "static", "Boolean", "fetch", "(", "Request", "req", ",", "Response", "res", ")", "{", "Auth0UserProfile", "userProfile", "=", "req", ".", "attribute", "(", "\"", "user", "\"", ")", ";", "Project", "p", "=", "requestProjectById", "(", "req", ",", "\"", "manage", "\"", ")", ";", "FetchProjectFeedsJob", "fetchProjectFeedsJob", "=", "new", "FetchProjectFeedsJob", "(", "p", ",", "userProfile", ".", "getUser_id", "(", ")", ")", ";", "fetchProjectFeedsJob", ".", "run", "(", ")", ";", "return", "true", ";", "}", "private", "static", "void", "applyJsonToProject", "(", "Project", "p", ",", "String", "json", ")", "throws", "IOException", "{", "JsonNode", "node", "=", "mapper", ".", "readTree", "(", "json", ")", ";", "boolean", "updateFetchSchedule", "=", "false", ";", "Iterator", "<", "Map", ".", "Entry", "<", "String", ",", "JsonNode", ">", ">", "fieldsIter", "=", "node", ".", "fields", "(", ")", ";", "while", "(", "fieldsIter", ".", "hasNext", "(", ")", ")", "{", "Map", ".", "Entry", "<", "String", ",", "JsonNode", ">", "entry", "=", "fieldsIter", ".", "next", "(", ")", ";", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "name", "\"", ")", ")", "{", "p", ".", "name", "=", "entry", ".", "getValue", "(", ")", ".", "asText", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "defaultLocationLat", "\"", ")", ")", "{", "p", ".", "defaultLocationLat", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "LOG", ".", "info", "(", "\"", "updating default lat", "\"", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "defaultLocationLon", "\"", ")", ")", "{", "p", ".", "defaultLocationLon", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "LOG", ".", "info", "(", "\"", "updating default lon", "\"", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "north", "\"", ")", ")", "{", "p", ".", "north", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "south", "\"", ")", ")", "{", "p", ".", "south", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "east", "\"", ")", ")", "{", "p", ".", "east", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "west", "\"", ")", ")", "{", "p", ".", "west", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "organizationId", "\"", ")", ")", "{", "p", ".", "organizationId", "=", "entry", ".", "getValue", "(", ")", ".", "asText", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "osmNorth", "\"", ")", ")", "{", "p", ".", "osmNorth", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "osmSouth", "\"", ")", ")", "{", "p", ".", "osmSouth", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "osmEast", "\"", ")", ")", "{", "p", ".", "osmEast", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "osmWest", "\"", ")", ")", "{", "p", ".", "osmWest", "=", "entry", ".", "getValue", "(", ")", ".", "asDouble", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "useCustomOsmBounds", "\"", ")", ")", "{", "p", ".", "useCustomOsmBounds", "=", "entry", ".", "getValue", "(", ")", ".", "asBoolean", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "defaultLanguage", "\"", ")", ")", "{", "p", ".", "defaultLanguage", "=", "entry", ".", "getValue", "(", ")", ".", "asText", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "defaultTimeZone", "\"", ")", ")", "{", "p", ".", "defaultTimeZone", "=", "entry", ".", "getValue", "(", ")", ".", "asText", "(", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "autoFetchHour", "\"", ")", ")", "{", "p", ".", "autoFetchHour", "=", "entry", ".", "getValue", "(", ")", ".", "asInt", "(", ")", ";", "updateFetchSchedule", "=", "true", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "autoFetchMinute", "\"", ")", ")", "{", "p", ".", "autoFetchMinute", "=", "entry", ".", "getValue", "(", ")", ".", "asInt", "(", ")", ";", "updateFetchSchedule", "=", "true", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "autoFetchFeeds", "\"", ")", ")", "{", "p", ".", "autoFetchFeeds", "=", "entry", ".", "getValue", "(", ")", ".", "asBoolean", "(", ")", ";", "updateFetchSchedule", "=", "true", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "otpServers", "\"", ")", ")", "{", "p", ".", "otpServers", "=", "mapper", ".", "readValue", "(", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ",", "new", "TypeReference", "<", "List", "<", "OtpServer", ">", ">", "(", ")", "{", "}", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "buildConfig", "\"", ")", ")", "{", "p", ".", "buildConfig", "=", "mapper", ".", "treeToValue", "(", "entry", ".", "getValue", "(", ")", ",", "OtpBuildConfig", ".", "class", ")", ";", "}", "else", "if", "(", "entry", ".", "getKey", "(", ")", ".", "equals", "(", "\"", "routerConfig", "\"", ")", ")", "{", "p", ".", "routerConfig", "=", "mapper", ".", "treeToValue", "(", "entry", ".", "getValue", "(", ")", ",", "OtpRouterConfig", ".", "class", ")", ";", "}", "}", "if", "(", "updateFetchSchedule", ")", "{", "if", "(", "p", ".", "autoFetchFeeds", ")", "{", "int", "interval", "=", "1", ";", "DataManager", ".", "autoFetchMap", ".", "put", "(", "p", ".", "id", ",", "scheduleAutoFeedFetch", "(", "p", ".", "id", ",", "p", ".", "autoFetchHour", ",", "p", ".", "autoFetchMinute", ",", "interval", ",", "p", ".", "defaultTimeZone", ")", ")", ";", "}", "else", "{", "cancelAutoFetch", "(", "p", ".", "id", ")", ";", "}", "}", "}", "/**\n * Helper function returns feed source if user has permission for specified action.\n * @param req spark Request object from API request\n * @param action action type (either \"view\" or \"manage\")\n * @return requested project\n */", "private", "static", "Project", "requestProjectById", "(", "Request", "req", ",", "String", "action", ")", "{", "String", "id", "=", "req", ".", "params", "(", "\"", "id", "\"", ")", ";", "if", "(", "id", "==", "null", ")", "{", "halt", "(", "SparkUtils", ".", "formatJSON", "(", "\"", "Please specify id param", "\"", ",", "400", ")", ")", ";", "}", "return", "requestProject", "(", "req", ",", "Project", ".", "get", "(", "id", ")", ",", "action", ")", ";", "}", "private", "static", "Project", "requestProject", "(", "Request", "req", ",", "Project", "p", ",", "String", "action", ")", "{", "Auth0UserProfile", "userProfile", "=", "req", ".", "attribute", "(", "\"", "user", "\"", ")", ";", "boolean", "publicFilter", "=", "req", ".", "pathInfo", "(", ")", ".", "matches", "(", "publicPath", ")", ";", "if", "(", "p", "==", "null", ")", "{", "halt", "(", "400", ",", "SparkUtils", ".", "formatJSON", "(", "\"", "Project ID does not exist", "\"", ",", "400", ")", ")", ";", "return", "null", ";", "}", "boolean", "authorized", ";", "switch", "(", "action", ")", "{", "case", "\"", "manage", "\"", ":", "authorized", "=", "userProfile", ".", "canAdministerProject", "(", "p", ".", "id", ",", "p", ".", "organizationId", ")", ";", "break", ";", "case", "\"", "view", "\"", ":", "authorized", "=", "!", "publicFilter", "&&", "userProfile", ".", "hasProject", "(", "p", ".", "id", ",", "p", ".", "organizationId", ")", ";", "break", ";", "default", ":", "authorized", "=", "false", ";", "break", ";", "}", "if", "(", "publicFilter", ")", "{", "p", ".", "feedSources", "=", "p", ".", "getProjectFeedSources", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "fs", "->", "fs", ".", "isPublic", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "else", "{", "p", ".", "feedSources", "=", "null", ";", "if", "(", "!", "authorized", ")", "{", "halt", "(", "403", ",", "SparkUtils", ".", "formatJSON", "(", "\"", "User not authorized to perform action on project", "\"", ",", "403", ")", ")", ";", "return", "null", ";", "}", "}", "return", "p", ";", "}", "private", "static", "boolean", "downloadMergedFeed", "(", "Request", "req", ",", "Response", "res", ")", "throws", "IOException", "{", "Project", "project", "=", "requestProjectById", "(", "req", ",", "\"", "view", "\"", ")", ";", "Auth0UserProfile", "userProfile", "=", "req", ".", "attribute", "(", "\"", "user", "\"", ")", ";", "MergeProjectFeedsJob", "mergeProjectFeedsJob", "=", "new", "MergeProjectFeedsJob", "(", "project", ",", "userProfile", ".", "getUser_id", "(", ")", ")", ";", "DataManager", ".", "heavyExecutor", ".", "execute", "(", "mergeProjectFeedsJob", ")", ";", "return", "true", ";", "}", "/**\n * Returns credentials that a client may use to then download a feed version. Functionality\n * changes depending on whether application.data.use_s3_storage config property is true.\n */", "public", "static", "Object", "getFeedDownloadCredentials", "(", "Request", "req", ",", "Response", "res", ")", "{", "Project", "project", "=", "requestProjectById", "(", "req", ",", "\"", "view", "\"", ")", ";", "if", "(", "DataManager", ".", "useS3", ")", "{", "return", "getS3Credentials", "(", "DataManager", ".", "awsRole", ",", "DataManager", ".", "feedBucket", ",", "\"", "project/", "\"", "+", "project", ".", "id", "+", "\"", ".zip", "\"", ",", "Statement", ".", "Effect", ".", "Allow", ",", "S3Actions", ".", "GetObject", ",", "900", ")", ";", "}", "else", "{", "FeedDownloadToken", "token", "=", "new", "FeedDownloadToken", "(", "project", ")", ";", "token", ".", "save", "(", ")", ";", "return", "token", ";", "}", "}", "private", "static", "boolean", "deployPublic", "(", "Request", "req", ",", "Response", "res", ")", "{", "Auth0UserProfile", "userProfile", "=", "req", ".", "attribute", "(", "\"", "user", "\"", ")", ";", "String", "id", "=", "req", ".", "params", "(", "\"", "id", "\"", ")", ";", "if", "(", "id", "==", "null", ")", "{", "halt", "(", "400", ",", "\"", "must provide project id!", "\"", ")", ";", "}", "Project", "p", "=", "Project", ".", "get", "(", "id", ")", ";", "if", "(", "p", "==", "null", ")", "halt", "(", "400", ",", "\"", "no such project!", "\"", ")", ";", "new", "MakePublicJob", "(", "p", ",", "userProfile", ".", "getUser_id", "(", ")", ")", ".", "run", "(", ")", ";", "return", "true", ";", "}", "private", "static", "Project", "thirdPartySync", "(", "Request", "req", ",", "Response", "res", ")", "throws", "Exception", "{", "Auth0UserProfile", "userProfile", "=", "req", ".", "attribute", "(", "\"", "user", "\"", ")", ";", "String", "id", "=", "req", ".", "params", "(", "\"", "id", "\"", ")", ";", "Project", "proj", "=", "Project", ".", "get", "(", "id", ")", ";", "String", "syncType", "=", "req", ".", "params", "(", "\"", "type", "\"", ")", ";", "if", "(", "!", "userProfile", ".", "canAdministerProject", "(", "proj", ".", "id", ",", "proj", ".", "organizationId", ")", ")", "halt", "(", "403", ")", ";", "LOG", ".", "info", "(", "\"", "syncing with third party ", "\"", "+", "syncType", ")", ";", "if", "(", "DataManager", ".", "feedResources", ".", "containsKey", "(", "syncType", ")", ")", "{", "DataManager", ".", "feedResources", ".", "get", "(", "syncType", ")", ".", "importFeedsForProject", "(", "proj", ",", "req", ".", "headers", "(", "\"", "Authorization", "\"", ")", ")", ";", "return", "proj", ";", "}", "halt", "(", "404", ")", ";", "return", "null", ";", "}", "public", "static", "ScheduledFuture", "scheduleAutoFeedFetch", "(", "String", "id", ",", "int", "hour", ",", "int", "minute", ",", "int", "intervalInDays", ",", "String", "timezoneId", ")", "{", "TimeUnit", "minutes", "=", "TimeUnit", ".", "MINUTES", ";", "try", "{", "cancelAutoFetch", "(", "id", ")", ";", "Project", "p", "=", "Project", ".", "get", "(", "id", ")", ";", "if", "(", "p", "==", "null", ")", "return", "null", ";", "ZoneId", "timezone", ";", "try", "{", "timezone", "=", "ZoneId", ".", "of", "(", "timezoneId", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "timezone", "=", "ZoneId", ".", "of", "(", "\"", "America/New_York", "\"", ")", ";", "}", "LOG", ".", "info", "(", "\"", "Scheduling auto-fetch for projectID: {}", "\"", ",", "p", ".", "id", ")", ";", "ZonedDateTime", "now", "=", "ZonedDateTime", ".", "ofInstant", "(", "Instant", ".", "now", "(", ")", ",", "timezone", ")", ";", "ZonedDateTime", "startTime", "=", "LocalDateTime", ".", "of", "(", "LocalDate", ".", "now", "(", ")", ",", "LocalTime", ".", "of", "(", "hour", ",", "minute", ")", ")", ".", "atZone", "(", "timezone", ")", ";", "LOG", ".", "info", "(", "\"", "Now: {}", "\"", ",", "now", ".", "format", "(", "DateTimeFormatter", ".", "ISO_ZONED_DATE_TIME", ")", ")", ";", "LOG", ".", "info", "(", "\"", "Scheduled start time: {}", "\"", ",", "startTime", ".", "format", "(", "DateTimeFormatter", ".", "ISO_ZONED_DATE_TIME", ")", ")", ";", "long", "diffInMinutes", "=", "(", "startTime", ".", "toEpochSecond", "(", ")", "-", "now", ".", "toEpochSecond", "(", ")", ")", "/", "60", ";", "long", "delayInMinutes", ";", "if", "(", "diffInMinutes", ">=", "0", ")", "{", "delayInMinutes", "=", "diffInMinutes", ";", "}", "else", "{", "delayInMinutes", "=", "24", "*", "60", "+", "diffInMinutes", ";", "}", "LOG", ".", "info", "(", "\"", "Auto fetch begins in {} hours and runs every {} hours", "\"", ",", "String", ".", "valueOf", "(", "delayInMinutes", "/", "60.0", ")", ",", "TimeUnit", ".", "DAYS", ".", "toHours", "(", "intervalInDays", ")", ")", ";", "FetchProjectFeedsJob", "fetchProjectFeedsJob", "=", "new", "FetchProjectFeedsJob", "(", "p", ",", "\"", "system", "\"", ")", ";", "return", "DataManager", ".", "scheduler", ".", "scheduleAtFixedRate", "(", "fetchProjectFeedsJob", ",", "delayInMinutes", ",", "TimeUnit", ".", "DAYS", ".", "toMinutes", "(", "intervalInDays", ")", ",", "minutes", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "return", "null", ";", "}", "}", "private", "static", "void", "cancelAutoFetch", "(", "String", "id", ")", "{", "Project", "p", "=", "Project", ".", "get", "(", "id", ")", ";", "if", "(", "p", "!=", "null", "&&", "DataManager", ".", "autoFetchMap", ".", "get", "(", "p", ".", "id", ")", "!=", "null", ")", "{", "LOG", ".", "info", "(", "\"", "Cancelling auto-fetch for projectID: {}", "\"", ",", "p", ".", "id", ")", ";", "DataManager", ".", "autoFetchMap", ".", "get", "(", "p", ".", "id", ")", ".", "cancel", "(", "true", ")", ";", "}", "}", "public", "static", "void", "register", "(", "String", "apiPrefix", ")", "{", "get", "(", "apiPrefix", "+", "\"", "secure/project/:id", "\"", ",", "ProjectController", "::", "getProject", ",", "json", "::", "write", ")", ";", "get", "(", "apiPrefix", "+", "\"", "secure/project", "\"", ",", "ProjectController", "::", "getAllProjects", ",", "json", "::", "write", ")", ";", "post", "(", "apiPrefix", "+", "\"", "secure/project", "\"", ",", "ProjectController", "::", "createProject", ",", "json", "::", "write", ")", ";", "put", "(", "apiPrefix", "+", "\"", "secure/project/:id", "\"", ",", "ProjectController", "::", "updateProject", ",", "json", "::", "write", ")", ";", "delete", "(", "apiPrefix", "+", "\"", "secure/project/:id", "\"", ",", "ProjectController", "::", "deleteProject", ",", "json", "::", "write", ")", ";", "get", "(", "apiPrefix", "+", "\"", "secure/project/:id/thirdPartySync/:type", "\"", ",", "ProjectController", "::", "thirdPartySync", ",", "json", "::", "write", ")", ";", "post", "(", "apiPrefix", "+", "\"", "secure/project/:id/fetch", "\"", ",", "ProjectController", "::", "fetch", ",", "json", "::", "write", ")", ";", "post", "(", "apiPrefix", "+", "\"", "secure/project/:id/deployPublic", "\"", ",", "ProjectController", "::", "deployPublic", ",", "json", "::", "write", ")", ";", "get", "(", "apiPrefix", "+", "\"", "secure/project/:id/download", "\"", ",", "ProjectController", "::", "downloadMergedFeed", ")", ";", "get", "(", "apiPrefix", "+", "\"", "secure/project/:id/downloadtoken", "\"", ",", "ProjectController", "::", "getFeedDownloadCredentials", ",", "json", "::", "write", ")", ";", "get", "(", "apiPrefix", "+", "\"", "public/project/:id", "\"", ",", "ProjectController", "::", "getProject", ",", "json", "::", "write", ")", ";", "get", "(", "apiPrefix", "+", "\"", "public/project", "\"", ",", "ProjectController", "::", "getAllProjects", ",", "json", "::", "write", ")", ";", "get", "(", "apiPrefix", "+", "\"", "downloadprojectfeed/:token", "\"", ",", "ProjectController", "::", "downloadMergedFeedWithToken", ")", ";", "}", "private", "static", "Object", "downloadMergedFeedWithToken", "(", "Request", "req", ",", "Response", "res", ")", "{", "FeedDownloadToken", "token", "=", "FeedDownloadToken", ".", "get", "(", "req", ".", "params", "(", "\"", "token", "\"", ")", ")", ";", "if", "(", "token", "==", "null", "||", "!", "token", ".", "isValid", "(", ")", ")", "{", "halt", "(", "400", ",", "\"", "Feed download token not valid", "\"", ")", ";", "}", "Project", "project", "=", "token", ".", "getProject", "(", ")", ";", "token", ".", "delete", "(", ")", ";", "String", "fileName", "=", "project", ".", "id", "+", "\"", ".zip", "\"", ";", "return", "downloadFile", "(", "FeedVersion", ".", "feedStore", ".", "getFeed", "(", "fileName", ")", ",", "fileName", ",", "res", ")", ";", "}", "}" ]
Created by demory on 3/14/16.
[ "Created", "by", "demory", "on", "3", "/", "14", "/", "16", "." ]
[ "// this is runnable because sometimes we schedule the task for a later time, but here we call it immediately", "// because it is short lived and just cues more work", "// NOTE: the below keys require the full objects to be included in the request json,", "// otherwise the missing fields/sub-classes will be set to null", "// If auto fetch flag is turned on", "// once per day interval", "// otherwise, cancel any existing task for this id", "// check for null project", "// TODO: limit create action to app/org admins?", "// case \"create\":", "// authorized = userProfile.canAdministerOrganization(p.organizationId);", "// break;", "// request only authorized if not via public path and user can view", "// if requesting all projects via public route, include public feed sources", "// if we make it here, user has permission and it's a valid project", "// TODO: make this an authenticated call?", "// if storing feeds on s3, return temporary s3 credentials for that zip file", "// when feeds are stored locally, single-use download token will still be used", "// run as sync job; if it gets too slow change to async", "// First cancel any already scheduled auto fetch task for this project id.", "// NOW in default timezone", "// SCHEDULED START TIME", "// Get diff between start time and current time", "// delay in minutes", "// wait for one day plus difference (which is negative)", "// system is defined as owner because owner field must not be null" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b69ac4451d0492261d6408f5e77498f8d46465a
ancazapuc9/PagerTabIndicator
app/src/main/java/com/hold1/pagertabsdemo/fragments/AdaptersFragment.java
[ "Apache-2.0" ]
Java
AdaptersFragment
/** * Created by Cristian Holdunu on 08/11/2017. */
Created by Cristian Holdunu on 08/11/2017.
[ "Created", "by", "Cristian", "Holdunu", "on", "08", "/", "11", "/", "2017", "." ]
public class AdaptersFragment extends Fragment implements FragmentPresenter { private PagerTabsIndicator tabsIndicator; @BindView(R.id.tabs_text) View tabsText; @BindView(R.id.tabs_image) View tabsImage; @BindView(R.id.tabs_web) View tabsWeb; @BindView(R.id.tabs_custom) View tabsCustom; @BindView(R.id.tabs_custom_anim) View tabsCustomAnim; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.adapters_fragment, null); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); tabsIndicator = ((MainActivity) getActivity()).getTabsIndicator(); if (tabsIndicator == null) return; ButterKnife.bind(this, view); tabsText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) getActivity()).changeTabAdapter(MainActivity.TabAdapterType.TEXT); } }); tabsImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) getActivity()).changeTabAdapter(MainActivity.TabAdapterType.IMAGE); } }); tabsWeb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) getActivity()).changeTabAdapter(MainActivity.TabAdapterType.WEB); } }); tabsCustom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) getActivity()).changeTabAdapter(MainActivity.TabAdapterType.CUSTOM); } }); tabsCustomAnim.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity) getActivity()).changeTabAdapter(MainActivity.TabAdapterType.CUSTOM_ANIM); } }); } @Override public String getTabName() { return "Adapters"; } @Override public int getTabImage() { return R.drawable.ic_adapter; } @Override public String getTabImageUrl() { return "https://s3-us-west-2.amazonaws.com/anaface-pictures/ic_adapter.png"; } }
[ "public", "class", "AdaptersFragment", "extends", "Fragment", "implements", "FragmentPresenter", "{", "private", "PagerTabsIndicator", "tabsIndicator", ";", "@", "BindView", "(", "R", ".", "id", ".", "tabs_text", ")", "View", "tabsText", ";", "@", "BindView", "(", "R", ".", "id", ".", "tabs_image", ")", "View", "tabsImage", ";", "@", "BindView", "(", "R", ".", "id", ".", "tabs_web", ")", "View", "tabsWeb", ";", "@", "BindView", "(", "R", ".", "id", ".", "tabs_custom", ")", "View", "tabsCustom", ";", "@", "BindView", "(", "R", ".", "id", ".", "tabs_custom_anim", ")", "View", "tabsCustomAnim", ";", "@", "Nullable", "@", "Override", "public", "View", "onCreateView", "(", "LayoutInflater", "inflater", ",", "@", "Nullable", "ViewGroup", "container", ",", "Bundle", "savedInstanceState", ")", "{", "View", "view", "=", "inflater", ".", "inflate", "(", "R", ".", "layout", ".", "adapters_fragment", ",", "null", ")", ";", "return", "view", ";", "}", "@", "Override", "public", "void", "onViewCreated", "(", "View", "view", ",", "@", "Nullable", "Bundle", "savedInstanceState", ")", "{", "super", ".", "onViewCreated", "(", "view", ",", "savedInstanceState", ")", ";", "tabsIndicator", "=", "(", "(", "MainActivity", ")", "getActivity", "(", ")", ")", ".", "getTabsIndicator", "(", ")", ";", "if", "(", "tabsIndicator", "==", "null", ")", "return", ";", "ButterKnife", ".", "bind", "(", "this", ",", "view", ")", ";", "tabsText", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "(", "(", "MainActivity", ")", "getActivity", "(", ")", ")", ".", "changeTabAdapter", "(", "MainActivity", ".", "TabAdapterType", ".", "TEXT", ")", ";", "}", "}", ")", ";", "tabsImage", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "(", "(", "MainActivity", ")", "getActivity", "(", ")", ")", ".", "changeTabAdapter", "(", "MainActivity", ".", "TabAdapterType", ".", "IMAGE", ")", ";", "}", "}", ")", ";", "tabsWeb", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "(", "(", "MainActivity", ")", "getActivity", "(", ")", ")", ".", "changeTabAdapter", "(", "MainActivity", ".", "TabAdapterType", ".", "WEB", ")", ";", "}", "}", ")", ";", "tabsCustom", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "(", "(", "MainActivity", ")", "getActivity", "(", ")", ")", ".", "changeTabAdapter", "(", "MainActivity", ".", "TabAdapterType", ".", "CUSTOM", ")", ";", "}", "}", ")", ";", "tabsCustomAnim", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")", "{", "(", "(", "MainActivity", ")", "getActivity", "(", ")", ")", ".", "changeTabAdapter", "(", "MainActivity", ".", "TabAdapterType", ".", "CUSTOM_ANIM", ")", ";", "}", "}", ")", ";", "}", "@", "Override", "public", "String", "getTabName", "(", ")", "{", "return", "\"", "Adapters", "\"", ";", "}", "@", "Override", "public", "int", "getTabImage", "(", ")", "{", "return", "R", ".", "drawable", ".", "ic_adapter", ";", "}", "@", "Override", "public", "String", "getTabImageUrl", "(", ")", "{", "return", "\"", "https://s3-us-west-2.amazonaws.com/anaface-pictures/ic_adapter.png", "\"", ";", "}", "}" ]
Created by Cristian Holdunu on 08/11/2017.
[ "Created", "by", "Cristian", "Holdunu", "on", "08", "/", "11", "/", "2017", "." ]
[]
[ { "param": "Fragment", "type": null }, { "param": "FragmentPresenter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Fragment", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "FragmentPresenter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b6ab22313cc164bafed548b28ce51daecde8961
hao44le/CS473HW4-Galago-3.10
core/src/main/java/org/lemurproject/galago/core/index/ExtractIndexDocumentNumbers.java
[ "BSD-3-Clause" ]
Java
ExtractIndexDocumentNumbers
/** * <p> Numbers documents using an existing index.</p> * * <p>The point of this class is to find the small identifier * that is already associated with each document. * NumberedDocuments are generated. * </p> * * @author sjh */
Numbers documents using an existing index. The point of this class is to find the small identifier that is already associated with each document. @author sjh
[ "Numbers", "documents", "using", "an", "existing", "index", ".", "The", "point", "of", "this", "class", "is", "to", "find", "the", "small", "identifier", "that", "is", "already", "associated", "with", "each", "document", ".", "@author", "sjh" ]
@Verified @InputClass(className = "org.lemurproject.galago.core.parse.Document") @OutputClass(className = "org.lemurproject.galago.core.parse.Document") public class ExtractIndexDocumentNumbers extends StandardStep<Document, Document> { private final DiskNameReverseReader.KeyIterator namesIterator; public ExtractIndexDocumentNumbers(TupleFlowParameters parameters) throws IOException { String namesPath = parameters.getJSON().getString("indexPath") + File.separator + "names.reverse"; namesIterator = ((DiskNameReverseReader) DiskIndex.openIndexPart(namesPath)).getIterator(); } @Override public void process(Document doc) throws IOException { // it's possible that documents already have numbers - if so, leave them be. if (doc.identifier < 0) { try { namesIterator.findKey(ByteUtil.fromString(doc.name)); doc.identifier = namesIterator.getCurrentIdentifier(); } catch (Exception e) { throw new IOException("Can not find document number for document: " + doc.name); } } processor.process(doc); } }
[ "@", "Verified", "@", "InputClass", "(", "className", "=", "\"", "org.lemurproject.galago.core.parse.Document", "\"", ")", "@", "OutputClass", "(", "className", "=", "\"", "org.lemurproject.galago.core.parse.Document", "\"", ")", "public", "class", "ExtractIndexDocumentNumbers", "extends", "StandardStep", "<", "Document", ",", "Document", ">", "{", "private", "final", "DiskNameReverseReader", ".", "KeyIterator", "namesIterator", ";", "public", "ExtractIndexDocumentNumbers", "(", "TupleFlowParameters", "parameters", ")", "throws", "IOException", "{", "String", "namesPath", "=", "parameters", ".", "getJSON", "(", ")", ".", "getString", "(", "\"", "indexPath", "\"", ")", "+", "File", ".", "separator", "+", "\"", "names.reverse", "\"", ";", "namesIterator", "=", "(", "(", "DiskNameReverseReader", ")", "DiskIndex", ".", "openIndexPart", "(", "namesPath", ")", ")", ".", "getIterator", "(", ")", ";", "}", "@", "Override", "public", "void", "process", "(", "Document", "doc", ")", "throws", "IOException", "{", "if", "(", "doc", ".", "identifier", "<", "0", ")", "{", "try", "{", "namesIterator", ".", "findKey", "(", "ByteUtil", ".", "fromString", "(", "doc", ".", "name", ")", ")", ";", "doc", ".", "identifier", "=", "namesIterator", ".", "getCurrentIdentifier", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IOException", "(", "\"", "Can not find document number for document: ", "\"", "+", "doc", ".", "name", ")", ";", "}", "}", "processor", ".", "process", "(", "doc", ")", ";", "}", "}" ]
<p> Numbers documents using an existing index.</p> <p>The point of this class is to find the small identifier that is already associated with each document.
[ "<p", ">", "Numbers", "documents", "using", "an", "existing", "index", ".", "<", "/", "p", ">", "<p", ">", "The", "point", "of", "this", "class", "is", "to", "find", "the", "small", "identifier", "that", "is", "already", "associated", "with", "each", "document", "." ]
[ "// it's possible that documents already have numbers - if so, leave them be." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b6e6e0c9afb19c996f867450ac6984458c17bad
Scrappers-glitch/SS-Editor
src/main/java/com/ss/editor/ui/dialog/factory/control/SpatialAssetResourcePropertyControl.java
[ "Apache-2.0" ]
Java
SpatialAssetResourcePropertyControl
/** * The controller to edit spatial values from asset. * * @author JavaSaBr */
The controller to edit spatial values from asset.
[ "The", "controller", "to", "edit", "spatial", "values", "from", "asset", "." ]
public class SpatialAssetResourcePropertyControl<T extends Spatial> extends AssetResourcePropertyEditorControl<T> { @NotNull private static final Array<String> EXTENSIONS = ArrayFactory.newArray(String.class); static { EXTENSIONS.add(FileExtensions.JME_OBJECT); } public SpatialAssetResourcePropertyControl(@NotNull final VarTable vars, @NotNull final PropertyDefinition definition, @NotNull final Runnable validationCallback) { super(vars, definition, validationCallback); } @NotNull @Override protected Array<String> getExtensions() { return EXTENSIONS; } @Override protected void processSelect(@NotNull final Path file) { final AssetManager assetManager = EDITOR.getAssetManager(); final Path assetFile = notNull(getAssetFile(file)); final ModelKey modelKey = new ModelKey(toAssetPath(assetFile)); final T spatial = findResource(assetManager, modelKey); setPropertyValue(unsafeCast(spatial)); super.processSelect(file); } /** * Finds a resource rom asset folder by the model key. * * @param assetManager the asset manager. * @param modelKey the model key. * @return the target resource. */ @Nullable protected T findResource(@NotNull final AssetManager assetManager, @NotNull final ModelKey modelKey) { return unsafeCast(assetManager.loadModel(modelKey)); } @Override protected void reload() { final T model = getPropertyValue(); final Spatial root = model == null ? null : findParent(model, spatial -> spatial.getKey() != null); final AssetKey key = root == null ? null : root.getKey(); final Label resourceLabel = getResourceLabel(); resourceLabel.setText(key == null ? NOT_SELECTED : key.getName() + "[" + model.getName() + "]"); super.reload(); } }
[ "public", "class", "SpatialAssetResourcePropertyControl", "<", "T", "extends", "Spatial", ">", "extends", "AssetResourcePropertyEditorControl", "<", "T", ">", "{", "@", "NotNull", "private", "static", "final", "Array", "<", "String", ">", "EXTENSIONS", "=", "ArrayFactory", ".", "newArray", "(", "String", ".", "class", ")", ";", "static", "{", "EXTENSIONS", ".", "add", "(", "FileExtensions", ".", "JME_OBJECT", ")", ";", "}", "public", "SpatialAssetResourcePropertyControl", "(", "@", "NotNull", "final", "VarTable", "vars", ",", "@", "NotNull", "final", "PropertyDefinition", "definition", ",", "@", "NotNull", "final", "Runnable", "validationCallback", ")", "{", "super", "(", "vars", ",", "definition", ",", "validationCallback", ")", ";", "}", "@", "NotNull", "@", "Override", "protected", "Array", "<", "String", ">", "getExtensions", "(", ")", "{", "return", "EXTENSIONS", ";", "}", "@", "Override", "protected", "void", "processSelect", "(", "@", "NotNull", "final", "Path", "file", ")", "{", "final", "AssetManager", "assetManager", "=", "EDITOR", ".", "getAssetManager", "(", ")", ";", "final", "Path", "assetFile", "=", "notNull", "(", "getAssetFile", "(", "file", ")", ")", ";", "final", "ModelKey", "modelKey", "=", "new", "ModelKey", "(", "toAssetPath", "(", "assetFile", ")", ")", ";", "final", "T", "spatial", "=", "findResource", "(", "assetManager", ",", "modelKey", ")", ";", "setPropertyValue", "(", "unsafeCast", "(", "spatial", ")", ")", ";", "super", ".", "processSelect", "(", "file", ")", ";", "}", "/**\n * Finds a resource rom asset folder by the model key.\n *\n * @param assetManager the asset manager.\n * @param modelKey the model key.\n * @return the target resource.\n */", "@", "Nullable", "protected", "T", "findResource", "(", "@", "NotNull", "final", "AssetManager", "assetManager", ",", "@", "NotNull", "final", "ModelKey", "modelKey", ")", "{", "return", "unsafeCast", "(", "assetManager", ".", "loadModel", "(", "modelKey", ")", ")", ";", "}", "@", "Override", "protected", "void", "reload", "(", ")", "{", "final", "T", "model", "=", "getPropertyValue", "(", ")", ";", "final", "Spatial", "root", "=", "model", "==", "null", "?", "null", ":", "findParent", "(", "model", ",", "spatial", "->", "spatial", ".", "getKey", "(", ")", "!=", "null", ")", ";", "final", "AssetKey", "key", "=", "root", "==", "null", "?", "null", ":", "root", ".", "getKey", "(", ")", ";", "final", "Label", "resourceLabel", "=", "getResourceLabel", "(", ")", ";", "resourceLabel", ".", "setText", "(", "key", "==", "null", "?", "NOT_SELECTED", ":", "key", ".", "getName", "(", ")", "+", "\"", "[", "\"", "+", "model", ".", "getName", "(", ")", "+", "\"", "]", "\"", ")", ";", "super", ".", "reload", "(", ")", ";", "}", "}" ]
The controller to edit spatial values from asset.
[ "The", "controller", "to", "edit", "spatial", "values", "from", "asset", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8b7aa18d47e5deb0001c823bd8a51c81363a7dcd
cpnatwork/hydra_dev
sys-src/hydra-gui/src/main/java/org/hydra/ui/gui/HydraMenu.java
[ "Apache-2.0" ]
Java
HydraMenu
/** * Encapsulates the menu of the Hydra GUI, which provides a user selectable * method for employing the commands. * * @since 0.2 * @version 0.2 * @author Scott A. Hady */
Encapsulates the menu of the Hydra GUI, which provides a user selectable method for employing the commands.
[ "Encapsulates", "the", "menu", "of", "the", "Hydra", "GUI", "which", "provides", "a", "user", "selectable", "method", "for", "employing", "the", "commands", "." ]
public class HydraMenu extends JMenuBar { /** The Constant serialVersionUID. */ public static final long serialVersionUID = 02L; /** The commands. */ private final CommandSet commands; /** * Specialized constructor that injects the set of commands to use. * * @param useCommands * CommandSet. */ public HydraMenu(final CommandSet useCommands) { super(); this.commands = useCommands; this.initialize(); } /** * Initialize each of the menu items and associate them to the appropriate * command in the command set. */ protected void initialize() { this.initializeFileMenu(); this.initializeEditMenu(); this.initializeNavigationMenu(); this.initializeHelpMenu(); } /** * Initialize the 'File' Menu. */ protected void initializeFileMenu() { final JMenu fileMenu = new JMenu("File"); this.add(fileMenu); // Status final JMenuItem sysStatusItem = new JMenuItem(); sysStatusItem.setAction(this.commands.findById(CmdStatus.DEFAULT_ID)); sysStatusItem.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); fileMenu.add(sysStatusItem); // Log final JMenuItem sysLogItem = new JMenuItem(); sysLogItem.setAction(this.commands.findById(CmdLog.DEFAULT_ID)); sysLogItem.setAccelerator(KeyStroke.getKeyStroke('L', InputEvent.CTRL_DOWN_MASK)); fileMenu.add(sysLogItem); // Separator fileMenu.add(new JSeparator()); // Exit final JMenuItem exitItem = new JMenuItem("Exit"); exitItem.setAction(this.commands.findById(CmdExit.DEFAULT_ID)); exitItem.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); fileMenu.add(exitItem); } /** * Initialize the 'Edit' Menu. */ protected void initializeEditMenu() { final JMenu editMenu = new JMenu("Edit"); this.add(editMenu); // History Mouse Mode final JMenu mouseModeSubMenu = new JMenu("History Mouse Mode"); editMenu.add(mouseModeSubMenu); // Transforming final JMenuItem transformingItem = new JMenuItem( this.commands.findById("GUICmdGraphMouseMode.Transforming")); transformingItem.setAccelerator(KeyStroke.getKeyStroke('T', InputEvent.ALT_DOWN_MASK)); mouseModeSubMenu.add(transformingItem); // Picking final JMenuItem pickingItem = new JMenuItem( this.commands.findById("GUICmdGraphMouseMode.Picking")); pickingItem.setAccelerator(KeyStroke.getKeyStroke('P', InputEvent.ALT_DOWN_MASK)); mouseModeSubMenu.add(pickingItem); } /** * Initialize the 'Navigation' menu. */ protected void initializeNavigationMenu() { final JMenu navigationMenu = new JMenu("Navigation"); this.add(navigationMenu); // Revert to Picked final JMenuItem revertPickedItem = new JMenuItem(); revertPickedItem.setAction(this.commands .findById(GUICmdGraphRevert.DEFAULT_ID)); revertPickedItem.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.ALT_DOWN_MASK)); navigationMenu.add(revertPickedItem); } /** * Initialize the 'Help' menu. */ protected void initializeHelpMenu() { final JMenu helpMenu = new JMenu("Help"); this.add(helpMenu); // Help final JMenuItem sysHelpItem = new JMenuItem(); sysHelpItem.setAction(this.commands.findById(CmdHelp.DEFAULT_ID)); sysHelpItem.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); helpMenu.add(sysHelpItem); } }
[ "public", "class", "HydraMenu", "extends", "JMenuBar", "{", "/** The Constant serialVersionUID. */", "public", "static", "final", "long", "serialVersionUID", "=", "02L", ";", "/** The commands. */", "private", "final", "CommandSet", "commands", ";", "/**\n\t * Specialized constructor that injects the set of commands to use.\n\t *\n\t * @param useCommands\n\t * CommandSet.\n\t */", "public", "HydraMenu", "(", "final", "CommandSet", "useCommands", ")", "{", "super", "(", ")", ";", "this", ".", "commands", "=", "useCommands", ";", "this", ".", "initialize", "(", ")", ";", "}", "/**\n\t * Initialize each of the menu items and associate them to the appropriate\n\t * command in the command set.\n\t */", "protected", "void", "initialize", "(", ")", "{", "this", ".", "initializeFileMenu", "(", ")", ";", "this", ".", "initializeEditMenu", "(", ")", ";", "this", ".", "initializeNavigationMenu", "(", ")", ";", "this", ".", "initializeHelpMenu", "(", ")", ";", "}", "/**\n\t * Initialize the 'File' Menu.\n\t */", "protected", "void", "initializeFileMenu", "(", ")", "{", "final", "JMenu", "fileMenu", "=", "new", "JMenu", "(", "\"", "File", "\"", ")", ";", "this", ".", "add", "(", "fileMenu", ")", ";", "final", "JMenuItem", "sysStatusItem", "=", "new", "JMenuItem", "(", ")", ";", "sysStatusItem", ".", "setAction", "(", "this", ".", "commands", ".", "findById", "(", "CmdStatus", ".", "DEFAULT_ID", ")", ")", ";", "sysStatusItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'S'", ",", "InputEvent", ".", "CTRL_DOWN_MASK", ")", ")", ";", "fileMenu", ".", "add", "(", "sysStatusItem", ")", ";", "final", "JMenuItem", "sysLogItem", "=", "new", "JMenuItem", "(", ")", ";", "sysLogItem", ".", "setAction", "(", "this", ".", "commands", ".", "findById", "(", "CmdLog", ".", "DEFAULT_ID", ")", ")", ";", "sysLogItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'L'", ",", "InputEvent", ".", "CTRL_DOWN_MASK", ")", ")", ";", "fileMenu", ".", "add", "(", "sysLogItem", ")", ";", "fileMenu", ".", "add", "(", "new", "JSeparator", "(", ")", ")", ";", "final", "JMenuItem", "exitItem", "=", "new", "JMenuItem", "(", "\"", "Exit", "\"", ")", ";", "exitItem", ".", "setAction", "(", "this", ".", "commands", ".", "findById", "(", "CmdExit", ".", "DEFAULT_ID", ")", ")", ";", "exitItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'Q'", ",", "InputEvent", ".", "CTRL_DOWN_MASK", ")", ")", ";", "fileMenu", ".", "add", "(", "exitItem", ")", ";", "}", "/**\n\t * Initialize the 'Edit' Menu.\n\t */", "protected", "void", "initializeEditMenu", "(", ")", "{", "final", "JMenu", "editMenu", "=", "new", "JMenu", "(", "\"", "Edit", "\"", ")", ";", "this", ".", "add", "(", "editMenu", ")", ";", "final", "JMenu", "mouseModeSubMenu", "=", "new", "JMenu", "(", "\"", "History Mouse Mode", "\"", ")", ";", "editMenu", ".", "add", "(", "mouseModeSubMenu", ")", ";", "final", "JMenuItem", "transformingItem", "=", "new", "JMenuItem", "(", "this", ".", "commands", ".", "findById", "(", "\"", "GUICmdGraphMouseMode.Transforming", "\"", ")", ")", ";", "transformingItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'T'", ",", "InputEvent", ".", "ALT_DOWN_MASK", ")", ")", ";", "mouseModeSubMenu", ".", "add", "(", "transformingItem", ")", ";", "final", "JMenuItem", "pickingItem", "=", "new", "JMenuItem", "(", "this", ".", "commands", ".", "findById", "(", "\"", "GUICmdGraphMouseMode.Picking", "\"", ")", ")", ";", "pickingItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'P'", ",", "InputEvent", ".", "ALT_DOWN_MASK", ")", ")", ";", "mouseModeSubMenu", ".", "add", "(", "pickingItem", ")", ";", "}", "/**\n\t * Initialize the 'Navigation' menu.\n\t */", "protected", "void", "initializeNavigationMenu", "(", ")", "{", "final", "JMenu", "navigationMenu", "=", "new", "JMenu", "(", "\"", "Navigation", "\"", ")", ";", "this", ".", "add", "(", "navigationMenu", ")", ";", "final", "JMenuItem", "revertPickedItem", "=", "new", "JMenuItem", "(", ")", ";", "revertPickedItem", ".", "setAction", "(", "this", ".", "commands", ".", "findById", "(", "GUICmdGraphRevert", ".", "DEFAULT_ID", ")", ")", ";", "revertPickedItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'R'", ",", "InputEvent", ".", "ALT_DOWN_MASK", ")", ")", ";", "navigationMenu", ".", "add", "(", "revertPickedItem", ")", ";", "}", "/**\n\t * Initialize the 'Help' menu.\n\t */", "protected", "void", "initializeHelpMenu", "(", ")", "{", "final", "JMenu", "helpMenu", "=", "new", "JMenu", "(", "\"", "Help", "\"", ")", ";", "this", ".", "add", "(", "helpMenu", ")", ";", "final", "JMenuItem", "sysHelpItem", "=", "new", "JMenuItem", "(", ")", ";", "sysHelpItem", ".", "setAction", "(", "this", ".", "commands", ".", "findById", "(", "CmdHelp", ".", "DEFAULT_ID", ")", ")", ";", "sysHelpItem", ".", "setAccelerator", "(", "KeyStroke", ".", "getKeyStroke", "(", "'H'", ",", "InputEvent", ".", "CTRL_DOWN_MASK", ")", ")", ";", "helpMenu", ".", "add", "(", "sysHelpItem", ")", ";", "}", "}" ]
Encapsulates the menu of the Hydra GUI, which provides a user selectable method for employing the commands.
[ "Encapsulates", "the", "menu", "of", "the", "Hydra", "GUI", "which", "provides", "a", "user", "selectable", "method", "for", "employing", "the", "commands", "." ]
[ "// Status", "// Log", "// Separator", "// Exit", "// History Mouse Mode", "// Transforming", "// Picking", "// Revert to Picked", "// Help" ]
[ { "param": "JMenuBar", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JMenuBar", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }