List of usage examples for java.util ArrayList size
int size
To view the source code for java.util ArrayList size.
Click Source Link
From source file:com.bigdata.dastor.tools.DastorAdminCli.java
public static void main(String[] args) throws IOException, InterruptedException, ParseException { ArrayList<String> cmdArgList = new ArrayList<String>(); DastorAdminCli nodeCmd = DastorAdminCli.initCli(args, cmdArgList); String[] arguments = cmdArgList.toArray(new String[cmdArgList.size()]); int ret = nodeCmd.executeCommand(arguments); System.exit(ret);/*from w ww .j a v a2 s. c o m*/ }
From source file:biomine.nodeimportancecompression.ImportanceCompressionReport.java
public static void main(String[] args) throws IOException, java.text.ParseException { opts.addOption("algorithm", true, "Used algorithm for compression. Possible values are 'brute-force', " + "'brute-force-edges','brute-force-merges','randomized','randomized-merges'," + "'randomized-edges'," + "'fast-brute-force'," + "'fast-brute-force-merges','fast-brute-force-merge-edges'. Default is 'brute-force'."); opts.addOption("query", true, "Query nodes ids, separated by comma."); opts.addOption("queryfile", true, "Read query nodes from file."); opts.addOption("ratio", true, "Goal ratio"); opts.addOption("importancefile", true, "Read importances straight from file"); opts.addOption("keepedges", false, "Don't remove edges during merges"); opts.addOption("connectivity", false, "Compute and output connectivities in edge oriented case"); opts.addOption("paths", false, "Do path oriented compression"); opts.addOption("edges", false, "Do edge oriented compression"); // opts.addOption( "a", double sigma = 1.0; CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/*from w w w .ja v a2s.c o m*/ try { cmd = parser.parse(opts, args); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } String queryStr = cmd.getOptionValue("query"); String[] queryNodeIDs = {}; double[] queryNodeIMP = {}; if (queryStr != null) { queryNodeIDs = queryStr.split(","); queryNodeIMP = new double[queryNodeIDs.length]; for (int i = 0; i < queryNodeIDs.length; i++) { String s = queryNodeIDs[i]; String[] es = s.split("="); queryNodeIMP[i] = 1; if (es.length == 2) { queryNodeIDs[i] = es[0]; queryNodeIMP[i] = Double.parseDouble(es[1]); } else if (es.length > 2) { System.out.println("Too many '=' in querynode specification: " + s); } } } String queryFile = cmd.getOptionValue("queryfile"); Map<String, Double> queryNodes = Collections.EMPTY_MAP; if (queryFile != null) { File in = new File(queryFile); BufferedReader read = new BufferedReader(new FileReader(in)); queryNodes = readMap(read); read.close(); } String impfile = cmd.getOptionValue("importancefile"); Map<String, Double> importances = null; if (impfile != null) { File in = new File(impfile); BufferedReader read = new BufferedReader(new FileReader(in)); importances = readMap(read); read.close(); } String algoStr = cmd.getOptionValue("algorithm"); CompressionAlgorithm algo = null; if (algoStr == null || algoStr.equals("brute-force")) { algo = new BruteForceCompression(); } else if (algoStr.equals("brute-force-edges")) { algo = new BruteForceCompressionOnlyEdges(); } else if (algoStr.equals("brute-force-merges")) { algo = new BruteForceCompressionOnlyMerges(); } else if (algoStr.equals("fast-brute-force-merges")) { //algo = new FastBruteForceCompressionOnlyMerges(); algo = new FastBruteForceCompression(true, false); } else if (algoStr.equals("fast-brute-force-edges")) { algo = new FastBruteForceCompression(false, true); //algo = new FastBruteForceCompressionOnlyEdges(); } else if (algoStr.equals("fast-brute-force")) { algo = new FastBruteForceCompression(true, true); } else if (algoStr.equals("randomized-edges")) { algo = new RandomizedCompressionOnlyEdges(); //modified } else if (algoStr.equals("randomized")) { algo = new RandomizedCompression(); } else if (algoStr.equals("randomized-merges")) { algo = new RandomizedCompressionOnlyMerges(); } else { System.out.println("Unsupported algorithm: " + algoStr); printHelp(); } String ratioStr = cmd.getOptionValue("ratio"); double ratio = 0; if (ratioStr != null) { ratio = Double.parseDouble(ratioStr); } else { System.out.println("Goal ratio not specified"); printHelp(); } String infile = null; if (cmd.getArgs().length != 0) { infile = cmd.getArgs()[0]; } else { printHelp(); } BMGraph bmg = BMGraphUtils.readBMGraph(new File(infile)); HashMap<BMNode, Double> queryBMNodes = new HashMap<BMNode, Double>(); for (String id : queryNodes.keySet()) { queryBMNodes.put(bmg.getNode(id), queryNodes.get(id)); } long startMillis = System.currentTimeMillis(); ImportanceGraphWrapper wrap = QueryImportance.queryImportanceGraph(bmg, queryBMNodes); if (importances != null) { for (String id : importances.keySet()) { wrap.setImportance(bmg.getNode(id), importances.get(id)); } } ImportanceMerger merger = null; if (cmd.hasOption("edges")) { merger = new ImportanceMergerEdges(wrap.getImportanceGraph()); } else if (cmd.hasOption("paths")) { merger = new ImportanceMergerPaths(wrap.getImportanceGraph()); } else { System.out.println("Specify either 'paths' or 'edges'."); System.exit(1); } if (cmd.hasOption("keepedges")) { merger.setKeepEdges(true); } algo.compress(merger, ratio); long endMillis = System.currentTimeMillis(); // write importance { BufferedWriter wr = new BufferedWriter(new FileWriter("importance.txt", false)); for (BMNode nod : bmg.getNodes()) { wr.write(nod + " " + wrap.getImportance(nod) + "\n"); } wr.close(); } // write sum of all pairs of node importance added by Fang /* { BufferedWriter wr = new BufferedWriter(new FileWriter("sum_of_all_pairs_importance.txt", true)); ImportanceGraph orig = wrap.getImportanceGraph(); double sum = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { for (int j = i+1; j <= orig.getMaxNodeId(); j++) { sum = sum+ wrap.getImportance(i)* wrap.getImportance(j); } } wr.write(""+sum); wr.write("\n"); wr.close(); } */ // write uncompressed edges { BufferedWriter wr = new BufferedWriter(new FileWriter("edges.txt", false)); ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); for (int i = 0; i <= orig.getMaxNodeId(); i++) { String iname = wrap.intToNode(i).toString(); HashSet<Integer> ne = new HashSet<Integer>(); ne.addAll(orig.getNeighbors(i)); ne.addAll(ucom.getNeighbors(i)); for (int j : ne) { if (i < j) continue; String jname = wrap.intToNode(j).toString(); double a = orig.getEdgeWeight(i, j); double b = ucom.getEdgeWeight(i, j); wr.write(iname + " " + jname + " " + a + " " + b + " " + Math.abs(a - b)); wr.write("\n"); } } wr.close(); } // write distance { // BufferedWriter wr = new BufferedWriter(new // FileWriter("distance.txt",false)); BufferedWriter wr = new BufferedWriter(new FileWriter("distance.txt", true)); //modified by Fang ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); double error = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { HashSet<Integer> ne = new HashSet<Integer>(); ne.addAll(orig.getNeighbors(i)); ne.addAll(ucom.getNeighbors(i)); for (int j : ne) { if (i <= j) continue; double a = orig.getEdgeWeight(i, j); double b = ucom.getEdgeWeight(i, j); error += (a - b) * (a - b) * wrap.getImportance(i) * wrap.getImportance(j); // modify by Fang: multiply imp(u)imp(v) } } error = Math.sqrt(error); //////////error = Math.sqrt(error / 2); // modified by Fang: the error of each // edge is counted twice wr.write("" + error); wr.write("\n"); wr.close(); } // write sizes { ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph comp = merger.getCurrentGraph(); // BufferedWriter wr = new BufferedWriter(new // FileWriter("sizes.txt",false)); BufferedWriter wr = new BufferedWriter(new FileWriter("sizes.txt", true)); //modified by Fang wr.write(orig.getNodeCount() + " " + orig.getEdgeCount() + " " + comp.getNodeCount() + " " + comp.getEdgeCount()); wr.write("\n"); wr.close(); } //write time { System.out.println("writing time"); BufferedWriter wr = new BufferedWriter(new FileWriter("time.txt", true)); //modified by Fang double secs = (endMillis - startMillis) * 0.001; wr.write("" + secs + "\n"); wr.close(); } //write change of connectivity for edge-oriented case // added by Fang { if (cmd.hasOption("connectivity")) { BufferedWriter wr = new BufferedWriter(new FileWriter("connectivity.txt", true)); ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); double diff = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { ProbDijkstra pdori = new ProbDijkstra(orig, i); ProbDijkstra pducom = new ProbDijkstra(ucom, i); for (int j = i + 1; j <= orig.getMaxNodeId(); j++) { double oriconn = pdori.getProbTo(j); double ucomconn = pducom.getProbTo(j); diff = diff + (oriconn - ucomconn) * (oriconn - ucomconn) * wrap.getImportance(i) * wrap.getImportance(j); } } diff = Math.sqrt(diff); wr.write("" + diff); wr.write("\n"); wr.close(); } } //write output graph { BMGraph output = bmg;//new BMGraph(bmg); int no = 0; BMNode[] nodes = new BMNode[merger.getGroups().size()]; for (ArrayList<Integer> gr : merger.getGroups()) { BMNode bmgroup = new BMNode("Group", "" + (no + 1)); bmgroup.setAttributes(new HashMap<String, String>()); bmgroup.put("autoedges", "0"); nodes[no] = bmgroup; no++; if (gr.size() == 0) continue; for (int x : gr) { BMNode nod = output.getNode(wrap.intToNode(x).toString()); BMEdge belongs = new BMEdge(nod, bmgroup, "belongs_to"); output.ensureHasEdge(belongs); } output.ensureHasNode(bmgroup); } for (int i = 0; i < nodes.length; i++) { for (int x : merger.getCurrentGraph().getNeighbors(i)) { if (x == i) { nodes[x].put("selfedge", "" + merger.getCurrentGraph().getEdgeWeight(i, x)); //ge.put("goodness", ""+merger.getCurrentGraph().getEdgeWeight(i, x)); continue; } BMEdge ge = new BMEdge(nodes[x], nodes[i], "groupedge"); ge.setAttributes(new HashMap<String, String>()); ge.put("goodness", "" + merger.getCurrentGraph().getEdgeWeight(i, x)); output.ensureHasEdge(ge); } } System.out.println(output.getGroupNodes()); BMGraphUtils.writeBMGraph(output, "output.bmg"); } }
From source file:test.jackson.JacksonNsgiDiscover.java
public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE))); DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr, DiscoveryContextAvailabilityRequest.class); // System.out.println(objectMapper.writeValueAsString(dcar)); System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue()); LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue(); // Association assocObject = objectMapper.convertValue(shapeHMap, Association.class); // System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute()); Shape shape = objectMapper.convertValue(shapeHMap, Shape.class); System.out.println("Deserialized Class: " + shape.getClass().getSimpleName()); System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude()); System.out.println("VALUE: " + shape.getCircle()); if (!(shape.getCircle() == null)) System.out.println("This is null"); Polygon polygon = shape.getPolygon(); int vertexSize = polygon.getVertices().size(); Coordinate[] coords = new Coordinate[vertexSize]; final ArrayList<Coordinate> points = new ArrayList<>(); for (int i = 0; i < vertexSize; i++) { Vertex vertex = polygon.getVertices().get(i); points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()))); coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())); }/*from w w w .j ava 2s .co m*/ points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()), Double.valueOf(polygon.getVertices().get(0).getLongitude()))); final GeometryFactory gf = new GeometryFactory(); final Coordinate target = new Coordinate(49, -0.6); final Point point = gf.createPoint(target); Geometry shapeGm = gf.createPolygon( new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf), null); // Geometry shapeGm = gf.createPolygon(coords); System.out.println(point.within(shapeGm)); // System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName()); // String assocJson = objectMapper.writeValueAsString(association); // Value assocObject = objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class); // System.out.println(association.values().toString()); // System.out.println(assocJson); }
From source file:Batch.java
static public void main(String[] args) { Connection conn = null;//from www . j av a 2s . c om try { ArrayList breakable = new ArrayList(); PreparedStatement stmt; Iterator users; ResultSet rs; Class.forName(args[0]).newInstance(); conn = DriverManager.getConnection(args[1], args[2], args[3]); stmt = conn.prepareStatement("SELECT user_id, password " + "FROM user"); rs = stmt.executeQuery(); while (rs.next()) { String uid = rs.getString(1); String pw = rs.getString(2); // Assume PasswordCracker is some class that provides // a single static method called crack() that attempts // to run password cracking routines on the password // if( PasswordCracker.crack(uid, pw) ) { // breakable.add(uid); // } } stmt.close(); if (breakable.size() < 1) { return; } stmt = conn.prepareStatement("UPDATE user " + "SET bad_password = 'Y' " + "WHERE uid = ?"); users = breakable.iterator(); while (users.hasNext()) { String uid = (String) users.next(); stmt.setString(1, uid); stmt.addBatch(); } stmt.executeBatch(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { } } } }
From source file:eu.crisis_economics.utilities.EmpiricalDistribution.java
public static void main(String[] args) { System.out.println("testing EmpiricalDistribution type.."); {// w ww .j a va2 s .c om System.out.println("EmpiricalDistribution test 1.."); EmpiricalDistribution memory = new EmpiricalDistribution(10); for (int i = 0; i < 10; ++i) { memory.add(i); Assert.assertEquals(memory.size(), i + 1); Assert.assertEquals(memory.maxSize(), 10); Assert.assertEquals(memory.getMaxRecordedValue(), (double) i); Assert.assertEquals(memory.getMinRecordedValue(), 0.); } Assert.assertEquals(4.5, memory.meanOverHistory(), 1.e-12); for (int i = 0; i < 10; ++i) { Assert.assertEquals(i, memory.numRecordsLessThan(i)); Assert.assertEquals(i, memory.numRecordsNotLessThan(10 - i)); Assert.assertEquals(1 - i / 10., memory.estimateProbabilityNotLessThan(i), 1.e-12); } for (int i = 0; i < 10; ++i) { // re-write memory memory.add(i); Assert.assertEquals(memory.size(), 10); } Assert.assertEquals(4.5, memory.meanOverHistory(), 1.e-12); for (int i = 0; i < 10; ++i) { Assert.assertEquals(i, memory.numRecordsLessThan(i)); Assert.assertEquals(i, memory.numRecordsNotLessThan(10 - i)); Assert.assertEquals(1 - i / 10., memory.estimateProbabilityNotLessThan(i), 1.e-12); } for (int i = 0; i < 10; ++i) { // re-write memory memory.add(i * 10); Assert.assertEquals(memory.size(), 10); Assert.assertEquals(memory.getMaxRecordedValue(), i == 0 ? 9. : (double) 10 * i); Assert.assertEquals(memory.getMinRecordedValue(), 0.); } Assert.assertEquals(4.5 * 10, memory.meanOverHistory(), 1.e-12); for (int i = 0; i < 100; ++i) { int roundDown = (i + 9) / 10; Assert.assertEquals(roundDown, memory.numRecordsLessThan(i)); Assert.assertEquals(roundDown, memory.size() - memory.numRecordsNotLessThan(i)); Assert.assertEquals(1 - roundDown / 10., memory.estimateProbabilityNotLessThan(i), 1.e-12); } memory.flush(); for (int i = 0; i < 10; ++i) { Assert.assertEquals(memory.size(), i); memory.add(0); Assert.assertEquals(0, memory.numRecordsLessThan(0)); Assert.assertEquals(i + 1, memory.numRecordsLessThan(1)); Assert.assertEquals(memory.getMaxRecordedValue(), 0.); Assert.assertEquals(memory.getMinRecordedValue(), 0.); } System.out.println(memory); } { MersenneTwisterFast random = Simulation.getSimState().random; for (int i = 0; i < 100; ++i) { if (i % 10 == 0) System.out.println("EmpiricalDistribution test " + (i + 1) + ".."); int memorySize = random.nextInt(100) + 1; EmpiricalDistribution memory = new EmpiricalDistribution(memorySize); double queryValue = random.nextDouble(); ArrayList<Double> lessThanQueryValue = new ArrayList<Double>(), notLessThanQueryValue = new ArrayList<Double>(); for (int j = 0; j < 2 * memorySize; ++j) { double insertValue = random.nextDouble(); memory.add(insertValue); if (j >= memorySize) { if (insertValue < queryValue) lessThanQueryValue.add(insertValue); else notLessThanQueryValue.add(insertValue); } } Assert.assertEquals(memory.numRecordsLessThan(queryValue), lessThanQueryValue.size()); Assert.assertEquals(memory.numRecordsNotLessThan(queryValue), notLessThanQueryValue.size()); Assert.assertEquals(memory.estimateProbabilityNotLessThan(queryValue), notLessThanQueryValue.size() / (double) memorySize); System.out.println(memory); System.out.flush(); } } System.out.println("EmpiricalDistribution tests pass"); System.out.flush(); }
From source file:com.sociesc.findasmartphonespark.Main.java
public static void main(String[] args) { String apiPrefix = "api/v1/"; //setIpAddress("192.168.56.1"); setPort(9010);// w w w.ja v a 2 s . c o m try { Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados"); DatabaseUtils.seedDatabase(); } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } Dao<User> userDao = new Dao(User.class); get(apiPrefix + "/hello/:name", (request, response) -> { ObjectMapper objectMapper = new ObjectMapper(); /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>(); for (int i = 0; i < 10; i++) { AccessPoint ap = new AccessPoint(); ap.setBSSID("AP" + i); ap.setSSID("00:00:00:0" + i); ap.setRSSI(-50 + i); ap.setSala("Sala" + i); arrayAp.add(ap); //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI()); } String retornoJson = rwJson.writeJson(arrayAp);*/ //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol"))); ArrayList<AccessPoint> arrayAp = null; try { arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return arrayAp.get(0).getBSSID(); //return "Hello: " + request.params(":name"); //return arrayAp[0].get; }); post(apiPrefix + "/findUser/:data", (request, response) -> { String userId = request.params(":data"); ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString()); /*JsonObject json = new JsonObject(); try { json = JsonObject.readFrom(request.params(":data")); } catch (Exception ex) { System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); }*/ try { for (int i = 0; i < aps.size(); i++) { System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID() + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala()); } } catch (Exception ex) { System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); //json.add("error", ex.getMessage()); response.status(500); return ex.getMessage(); } return userId.toString(); }); /*post(apiPrefix + "/findUser/", (request, response) ->{ JsonObject json = new JsonObject(); // Informaes do roteador/AP String[] BSSID; // basic service set identifier - nome da conexo String[] SSID; // service set identifier - identificador nico da conexo int[] RSSI; // received signal strength indicator - potencia do sinal (-87 a -32) String sala; String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject wifiJson = reqJson.get("wifi").asObject(); System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size()); RSSI = new int[wifiJson.size()]; BSSID = new String[wifiJson.size()]; SSID = new String[wifiJson.size()]; try{ for (int i = 0; i < wifiJson.size(); i++) { // recebe informaes das conexes encontradas BSSID[i] = wifiJson.get("BSSID").asString(); SSID[i] = wifiJson.get("SSID").asString(); RSSI[i] = wifiJson.get("RSSI").asInt(); } return json.toString(); }catch(Exception ex){ System.out.println("erro no json:\n" + ex.getMessage()); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); });*/ get(apiPrefix + "/users", (request, response) -> { JsonObject json = new JsonObject(); request.params(); try { List<User> users = userDao.findAll(); JsonArray usersJson = new JsonArray(); for (User u : users) { JsonObject uJson = new JsonObject(); uJson.add("id", u.getId()); uJson.add("name", u.getName()); uJson.add("email", u.getEmail()); usersJson.add(uJson); } json.add("users", usersJson); } catch (SQLException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); /*get(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try{ User user = userDao.findById(userId); if(user == null){ json.add("error", "user not found"); response.status(404); return json.toString(); } JsonObject userJson = new JsonObject(); userJson.add("id", user.getId()); userJson.add("name", user.getName()); userJson.add("email", user.getEmail()); json.add("user", userJson); return json.toString(); }catch(Exception ex){ Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); });*/ delete(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try { userDao.removeById(userId); json.add("message", "user removed"); response.status(200); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); put(apiPrefix + "/users/:id", (request, response) -> { Long userId = Long.parseLong(request.params(":id")); JsonObject json = new JsonObject(); try { String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject userJson = reqJson.get("user").asObject(); String name = userJson.get("name") != null ? userJson.get("name").asString() : null; String email = userJson.get("email") != null ? userJson.get("email").asString() : null; String password = userJson.get("password") != null ? userJson.get("password").asString() : null; User user = userDao.findById(userId); if (name != null) user.setName(name); if (email != null) user.setEmail(email); if (password != null) { String passwordDigest = DatabaseUtils.criptPass(password); user.setPasswordDigest(passwordDigest); } userDao.update(user); JsonObject resUserJson = new JsonObject(); resUserJson.add("id", user.getId()); resUserJson.add("name", user.getName()); resUserJson.add("email", user.getEmail()); json.add("user", resUserJson); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); post(apiPrefix + "/users", (request, response) -> { JsonObject json = new JsonObject(); try { String jsonBody = request.body(); JsonObject reqJson = JsonObject.readFrom(jsonBody); JsonObject userJson = reqJson.get("user").asObject(); User user = new User(); user.setName(userJson.get("name").asString()); user.setEmail(userJson.get("email").asString()); user.setPasswordDigest(DatabaseUtils.criptPass("tempPass")); userDao.create(user); JsonObject resUserJson = new JsonObject(); resUserJson.add("id", user.getId()); resUserJson.add("name", user.getName()); resUserJson.add("email", user.getEmail()); resUserJson.add("passwordDigest", user.getPasswordDigest()); json.add("user", resUserJson); return json.toString(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); json.add("error", ex.getMessage()); response.status(500); } return json.toString(); }); }
From source file:ch.epfl.lsir.xin.test.UserAverageTest.java
/** * @param args//from w w w . j a va2s . co m */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//UserAverage"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File(".//conf//UserAverage.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.flush(); double totalMAE = 0; double totalRMSE = 0; int F = 5; logger.println(F + "- folder cross validation."); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { logger.println("Folder: " + folder); System.out.println("Folder: " + folder); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } trainRatingMatrix.calculateGlobalAverage(); RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a recommendation model based on user average method."); UserAverage algo = new UserAverage(trainRatingMatrix); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); double RMSE = 0; double MAE = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()), itemIDIndexMapping.get(rating.getItemID())); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE + " RMSE: " + RMSE); logger.flush(); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.flush(); logger.close(); //MAE: 0.8353035962363073 RMSE: 1.0422971886952053 (MovieLens 100k) }
From source file:ch.epfl.lsir.xin.test.GlobalMeanTest.java
/** * @param args/*from w ww .j a v a 2 s. c om*/ */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//GlobalMean"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File("conf//GlobalMean.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); double totalMAE = 0; double totalRMSE = 0; int F = 5; logger.println(F + "- folder cross validation."); logger.flush(); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { System.out.println("Folder: " + folder); logger.println("Folder: " + folder); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a recommendation model based on global average method."); GlobalAverage algo = new GlobalAverage(trainRatingMatrix); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); double RMSE = 0; double MAE = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(rating.getUserID(), rating.getItemID()); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); // System.out.println("MAE: " + MAE + " RMSE: " + RMSE); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE + " RMSE: " + RMSE); logger.flush(); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.flush(); logger.close(); //MAE: 0.9338607074893257 RMSE: 1.1170971131112037 (MovieLens1M) //MAE: 0.9446876509332618 RMSE: 1.1256517870920375 (MovieLens100K) }
From source file:ch.epfl.lsir.xin.test.ItemAverageTest.java
/** * @param args/*ww w. j a va 2 s . c o m*/ */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//ItemAverage"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File(".//conf//ItemAverage.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); logger.flush(); double totalMAE = 0; double totalRMSE = 0; int F = 5; logger.println(F + "- folder cross validation."); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { logger.println("Folder: " + folder); logger.flush(); System.out.println("Folder: " + folder); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } trainRatingMatrix.calculateGlobalAverage(); RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a recommendation model based on item average method."); ItemAverage algo = new ItemAverage(trainRatingMatrix); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); double RMSE = 0; double MAE = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()), itemIDIndexMapping.get(rating.getItemID())); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE + " RMSE: " + RMSE); logger.flush(); // System.out.println("MAE: " + MAE + " RMSE: " + RMSE); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.flush(); //MAE: 0.8173633324758338 RMSE: 1.0251973503888645 (MovieLens 100K) }
From source file:ISMAGS.CommandLineInterface.java
public static void main(String[] args) throws IOException { String folder = null, files = null, motifspec = null, output = null; Options opts = new Options(); opts.addOption("folder", true, "Folder name"); opts.addOption("linkfiles", true, "Link files seperated by spaces (format: linktype[char] directed[d/u] filename)"); opts.addOption("motif", true, "Motif description by two strings (format: linktypes)"); opts.addOption("output", true, "Output file name"); CommandLineParser parser = new PosixParser(); try {/* w w w .j a v a 2 s . c o m*/ CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("folder")) { folder = cmd.getOptionValue("folder"); } if (cmd.hasOption("linkfiles")) { files = cmd.getOptionValue("linkfiles"); } if (cmd.hasOption("motif")) { motifspec = cmd.getOptionValue("motif"); } if (cmd.hasOption("output")) { output = cmd.getOptionValue("output"); } } catch (ParseException e) { Die("Error: Parsing error"); } if (print) { printBanner(folder, files, motifspec, output); } if (folder == null || files == null || motifspec == null || output == null) { Die("Error: not all options are provided"); } else { ArrayList<String> linkfiles = new ArrayList<String>(); ArrayList<String> linkTypes = new ArrayList<String>(); ArrayList<String> sourcenetworks = new ArrayList<String>(); ArrayList<String> destinationnetworks = new ArrayList<String>(); ArrayList<Boolean> directed = new ArrayList<Boolean>(); StringTokenizer st = new StringTokenizer(files, " "); while (st.hasMoreTokens()) { linkTypes.add(st.nextToken()); directed.add(st.nextToken().equals("d")); sourcenetworks.add(st.nextToken()); destinationnetworks.add(st.nextToken()); linkfiles.add(folder + st.nextToken()); } ArrayList<LinkType> allLinkTypes = new ArrayList<LinkType>(); HashMap<Character, LinkType> typeTranslation = new HashMap<Character, LinkType>(); for (int i = 0; i < linkTypes.size(); i++) { String n = linkTypes.get(i); char nn = n.charAt(0); LinkType t = typeTranslation.get(nn); if (t == null) { t = new LinkType(directed.get(i), n, i, nn, sourcenetworks.get(i), destinationnetworks.get(i)); } allLinkTypes.add(t); typeTranslation.put(nn, t); } if (print) { System.out.println("Reading network.."); } Network network = Network.readNetworkFromFiles(linkfiles, allLinkTypes); Motif motif = getMotif(motifspec, typeTranslation); if (print) { System.out.println("Starting the search.."); } MotifFinder mf = new MotifFinder(network); long tijd = System.nanoTime(); Set<MotifInstance> motifs = mf.findMotif(motif, false); tijd = System.nanoTime() - tijd; if (print) { System.out.println("Completed search in " + tijd / 1000000 + " milliseconds"); } if (print) { System.out.println("Found " + motifs.size() + " instances of " + motifspec + " motif"); } if (print) { System.out.println("Writing instances to file: " + output); } printMotifs(motifs, output); if (print) { System.out.println("Done."); } // Set<MotifInstance> motifs=null; // MotifFinder mf=null; // System.out.println("Starting the search.."); // long tstart = System.nanoTime(); // for (int i = 0; i < it; i++) { // // mf = new MotifFinder(network, allLinkTypes, true); // motifs = mf.findMotif(motif); // } // // long tend = System.nanoTime(); // double time_in_ms = (tend - tstart) / 1000000.0; // System.out.println("Found " + mf.totalFound + " motifs, " + time_in_ms + " ms"); //// System.out.println("Evaluated " + mf.totalNrMappedNodes+ " search nodes"); //// System.out.println("Found " + motifs.size() + " motifs, " + time_in_ms + " ms"); // printMotifs(motifs, output); } }