List of usage examples for java.util List subList
List<E> subList(int fromIndex, int toIndex);
From source file:com.liferay.events.global.mobile.Utils.java
public static String getJSONLikenessDescription(EventContact me, EventContact targetContact) throws JSONException { JSONArray result = JSONFactoryUtil.createJSONArray(); Map<String, Double> desires1 = getJSONWordWeightsFromString(me.getDesires()); Map<String, Double> desires2 = getJSONWordWeightsFromString(targetContact.getDesires()); Map<String, Double> expertise1 = getJSONWordWeightsFromString(me.getExpertise()); Map<String, Double> expertise2 = getJSONWordWeightsFromString(targetContact.getExpertise()); // how many of my desires do they have expertise in? Set<String> common1 = new HashSet<String>(desires1.keySet()); common1.retainAll(expertise2.keySet()); // how many of my expertises do they desire? Set<String> common2 = new HashSet<String>(desires2.keySet()); common2.retainAll(expertise1.keySet()); if (common1.size() > 0) { JSONObject bit = JSONFactoryUtil.createJSONObject(); List<String> myNeeds = new ArrayList<String>(common1); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(targetContact.getGivenName()); args.put(StringUtils.join(myNeeds.size() > 5 ? myNeeds.subList(0, 5) : myNeeds, " " + StringPool.SLASH + " ")); bit.put("key", "HAS_EXPERTISE_IN_MY_AREAS"); bit.put("args", args); result.put(bit);/*from ww w . ja va 2 s .c o m*/ } if (common2.size() > 0) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); List<String> myExpertise = new ArrayList<String>(common2); args.put(targetContact.getGivenName()); args.put(StringUtils.join(myExpertise.size() > 5 ? myExpertise.subList(0, 5) : myExpertise, " " + StringPool.SLASH + " ")); bit.put("key", "HAS_NEEDS_IN_MY_AREAS"); bit.put("args", args); result.put(bit); } double industrySimilarity = getJaroWinklerDistance(me.getIndustry(), targetContact.getIndustry()); double jobTitleSimilarity = getJaroWinklerDistance(me.getJobTitle(), targetContact.getJobTitle()); double locationDistance; if (me.getLat() == 0 || me.getLng() == 0 || targetContact.getLat() == 0 || targetContact.getLng() == 0) { locationDistance = 100000; } else { locationDistance = getDistanceBetween(me.getLat(), me.getLng(), targetContact.getLat(), targetContact.getLng()); } double locationSimilarity = 1.0 - (locationDistance / 1000.0); if (locationSimilarity < 0) locationSimilarity = 0; if (locationSimilarity > .5 && me.getCountry().equals(targetContact.getCountry())) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(targetContact.getGivenName()); args.put(targetContact.getCity()); bit.put("key", "IS_NEARBY"); bit.put("args", args); result.put(bit); } else if (me.getCountry().equals(targetContact.getCountry())) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(targetContact.getGivenName()); bit.put("key", "LIVES_WORKS_IN_COUNTRY"); bit.put("args", args); result.put(bit); } if (industrySimilarity > .7) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(targetContact.getGivenName()); args.put(targetContact.getIndustry()); bit.put("key", "SIMILAR_INDUSTRY"); bit.put("args", args); result.put(bit); } if (jobTitleSimilarity > .7) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(targetContact.getGivenName()); args.put(targetContact.getJobTitle()); bit.put("key", "SIMILAR_JOB"); bit.put("args", args); result.put(bit); } JSONArray words1o = JSONFactoryUtil.createJSONArray(me.getInterests()); JSONArray words2o = JSONFactoryUtil.createJSONArray(targetContact.getInterests()); List<String> words1 = new ArrayList<String>(); List<String> words2 = new ArrayList<String>(); final Map<String, Integer> count1 = new HashMap<String, Integer>(); final Map<String, Integer> count2 = new HashMap<String, Integer>(); final Map<String, Double> weight1 = new HashMap<String, Double>(); final Map<String, Double> weight2 = new HashMap<String, Double>(); for (int i = 0; i < words1o.length(); i++) { JSONObject o = words1o.getJSONObject(i); String word = o.getString("word"); int count = o.getInt("count"); double weight = o.getDouble("weight"); words1.add(word); count1.put(word, count); weight1.put(word, weight); } for (int i = 0; i < words2o.length(); i++) { JSONObject o = words2o.getJSONObject(i); String word = o.getString("word"); int count = o.getInt("count"); double weight = o.getDouble("weight"); words2.add(word); count2.put(word, count); weight2.put(word, weight); } Set<String> commonWords = new HashSet<String>(words1); commonWords.retainAll(words2); List<String> sortedCommon = new SortedArrayList<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return (int) Math.floor( ((((double) count1.get(o2) * weight1.get(o2)) + ((double) count2.get(o2) * weight2.get(o2))) - (((double) count1.get(o1) * weight1.get(o1)) + ((double) count2.get(o1) * weight2.get(o1))))); } }); sortedCommon.addAll(commonWords); if (!sortedCommon.isEmpty()) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(StringUtils.join(sortedCommon.size() > 5 ? sortedCommon.subList(0, 5) : sortedCommon, " / ")); bit.put("key", "SIMILAR_SKILLS_INTERESTS"); bit.put("args", args); result.put(bit); } if (result.length() <= 0) { List<String> sortedTargetWords = new SortedArrayList<String>(new Comparator<String>() { @Override public int compare(String a, String b) { return (int) Math.floor(((weight2.get(b) * (double) count2.get(b)) - (weight2.get(a) * (double) count2.get(a)))); } }); sortedTargetWords.addAll(words2); if (!sortedTargetWords.isEmpty()) { JSONObject bit = JSONFactoryUtil.createJSONObject(); JSONArray args = JSONFactoryUtil.createJSONArray(); args.put(StringUtils.join( sortedTargetWords.size() > 3 ? sortedTargetWords.subList(0, 3) : sortedTargetWords, " / ")); bit.put("key", "MIGHT_BE_INTERESTED"); bit.put("args", args); result.put(bit); } } return result.toString(); }
From source file:com.cloudfoundry.samples.spring.HomeController.java
@RequestMapping(value = "/", method = RequestMethod.GET) public String home(Model model) { FacebookProfile user = facebook.userOperations().getUserProfile(); model.addAttribute("user", user); List<Reference> friends = facebook.friendOperations().getFriends(); model.addAttribute("friends", friends.subList(0, 4)); List<Photo> photos = facebook.mediaOperations().getPhotos(user.getId(), 0, 16); model.addAttribute("photos", photos); List<Page> likes = facebook.likeOperations().getPagesLiked(); model.addAttribute("likes", likes.subList(0, 4)); return "home"; }
From source file:com.netflix.spinnaker.orca.kato.pipeline.ParallelDeployClusterExtractor.java
@Override public void updateStageClusters(Map stage, List<Map> replacements) { List<Map> clusters = (List<Map>) stage.get("clusters"); stage.put("clusters", new ArrayList<>(replacements.subList(0, clusters.size()))); replacements.removeAll((List<Map>) stage.get("clusters")); }
From source file:org.kuali.mobility.socialmedia.controllers.TwitterController.java
@RequestMapping(method = RequestMethod.GET) public String getList(Model uiModel) { List<String> feeds = new ArrayList<String>(); feeds.add("IndianaUniv"); feeds.add("citybloomington"); feeds.add("idsnews"); feeds.add("theheraldtimes"); feeds.add("IUBloomington"); feeds.add("IUPUI"); // feeds.add("indiananews"); feeds.add("IDS_Opinion"); feeds.add("IUPUI_Prepared"); feeds.add("IU_Health"); feeds.add("IUBookstore"); feeds.add("kinseyinstitute"); feeds.add("UITSNEWS"); List<Tweet> tweets = twitterService.retrieveCombinedFeeds(feeds); uiModel.addAttribute("tweets", tweets.subList(0, 25)); return "socialmedia/list"; }
From source file:com.beoui.geocell.GeocellManager.java
public static final <T> List<T> proximitySearch(Point center, int maxResults, double maxDistance, Class<T> entityClass, GeocellQuery baseQuery, GeocellQueryEngine queryEngine, int maxGeocellResolution) { List<EntityLocationComparableTuple<T>> results = new ArrayList<EntityLocationComparableTuple<T>>(); Validate.isTrue(maxGeocellResolution < MAX_GEOCELL_RESOLUTION + 1, "Invalid max resolution parameter. Must be inferior to ", MAX_GEOCELL_RESOLUTION); // The current search geocell containing the lat,lon. String curContainingGeocell = GeocellUtils.compute(center, maxGeocellResolution); // Set of already searched cells Set<String> searchedCells = new HashSet<String>(); /*//from ww w.j a v a 2s. com * The currently-being-searched geocells. * NOTES: * Start with max possible. * Must always be of the same resolution. * Must always form a rectangular region. * One of these must be equal to the cur_containing_geocell. */ List<String> curGeocells = new ArrayList<String>(); curGeocells.add(curContainingGeocell); double closestPossibleNextResultDist = 0; /* * Assumes both a and b are lists of (entity, dist) tuples, *sorted by dist*. * NOTE: This is an in-place merge, and there are guaranteed no duplicates in the resulting list. */ int noDirection[] = { 0, 0 }; List<Tuple<int[], Double>> sortedEdgesDistances = Arrays.asList(new Tuple<int[], Double>(noDirection, 0d)); while (!curGeocells.isEmpty()) { closestPossibleNextResultDist = sortedEdgesDistances.get(0).getSecond(); if (maxDistance > 0 && closestPossibleNextResultDist > maxDistance) { break; } Set<String> curTempUnique = new HashSet<String>(curGeocells); curTempUnique.removeAll(searchedCells); List<String> curGeocellsUnique = new ArrayList<String>(curTempUnique); List<T> newResultEntities = queryEngine.query(baseQuery, curGeocellsUnique, entityClass); logger.log(Level.FINE, "fetch complete for: " + StringUtils.join(curGeocellsUnique, ", ")); searchedCells.addAll(curGeocells); // Begin storing distance from the search result entity to the // search center along with the search result itself, in a tuple. List<EntityLocationComparableTuple<T>> newResults = new ArrayList<EntityLocationComparableTuple<T>>(); for (T entity : newResultEntities) { newResults.add(new EntityLocationComparableTuple<T>(entity, GeocellUtils.distance(center, GeocellUtils.getLocation(entity)))); } // TODO (Alex) we can optimize here. Sort is needed only if new_results.size() > max_results. Collections.sort(newResults); newResults = newResults.subList(0, Math.min(maxResults, newResults.size())); // Merge new_results into results for (EntityLocationComparableTuple<T> tuple : newResults) { // contains method will check if entity in tuple have same key if (!results.contains(tuple)) { results.add(tuple); } } Collections.sort(results); results = results.subList(0, Math.min(maxResults, results.size())); sortedEdgesDistances = GeocellUtils.distanceSortedEdges(curGeocells, center); if (results.size() == 0 || curGeocells.size() == 4) { /* Either no results (in which case we optimize by not looking at adjacents, go straight to the parent) or we've searched 4 adjacent geocells, in which case we should now search the parents of those geocells.*/ curContainingGeocell = curContainingGeocell.substring(0, Math.max(curContainingGeocell.length() - 1, 0)); if (curContainingGeocell.length() == 0) { break; // Done with search, we've searched everywhere. } List<String> oldCurGeocells = new ArrayList<String>(curGeocells); curGeocells.clear(); for (String cell : oldCurGeocells) { if (cell.length() > 0) { String newCell = cell.substring(0, cell.length() - 1); if (!curGeocells.contains(newCell)) { curGeocells.add(newCell); } } } if (curGeocells.size() == 0) { break; // Done with search, we've searched everywhere. } } else if (curGeocells.size() == 1) { // Get adjacent in one direction. // TODO(romannurik): Watch for +/- 90 degree latitude edge case geocells. int nearestEdge[] = sortedEdgesDistances.get(0).getFirst(); curGeocells.add(GeocellUtils.adjacent(curGeocells.get(0), nearestEdge)); } else if (curGeocells.size() == 2) { // Get adjacents in perpendicular direction. int nearestEdge[] = GeocellUtils.distanceSortedEdges(Arrays.asList(curContainingGeocell), center) .get(0).getFirst(); int[] perpendicularNearestEdge = { 0, 0 }; if (nearestEdge[0] == 0) { // Was vertical, perpendicular is horizontal. for (Tuple<int[], Double> edgeDistance : sortedEdgesDistances) { if (edgeDistance.getFirst()[0] != 0) { perpendicularNearestEdge = edgeDistance.getFirst(); break; } } } else { // Was horizontal, perpendicular is vertical. for (Tuple<int[], Double> edgeDistance : sortedEdgesDistances) { if (edgeDistance.getFirst()[0] == 0) { perpendicularNearestEdge = edgeDistance.getFirst(); break; } } } List<String> tempCells = new ArrayList<String>(); for (String cell : curGeocells) { tempCells.add(GeocellUtils.adjacent(cell, perpendicularNearestEdge)); } curGeocells.addAll(tempCells); } // We don't have enough items yet, keep searching. if (results.size() < maxResults) { logger.log(Level.FINE, results.size() + " results found but want " + maxResults + " results, continuing search."); continue; } logger.log(Level.FINE, results.size() + " results found."); // If the currently max_results'th closest item is closer than any // of the next test geocells, we're done searching. double currentFarthestReturnableResultDist = GeocellUtils.distance(center, GeocellUtils.getLocation(results.get(maxResults - 1).getFirst())); if (closestPossibleNextResultDist >= currentFarthestReturnableResultDist) { logger.log(Level.FINE, "DONE next result at least " + closestPossibleNextResultDist + " away, current farthest is " + currentFarthestReturnableResultDist + " dist"); break; } logger.log(Level.FINE, "next result at least " + closestPossibleNextResultDist + " away, current farthest is " + currentFarthestReturnableResultDist + " dist"); } List<T> result = new ArrayList<T>(); for (Tuple<T, Double> entry : results.subList(0, Math.min(maxResults, results.size()))) { if (maxDistance == 0 || entry.getSecond() < maxDistance) { result.add(entry.getFirst()); } else { logger.info("Discarding result " + entry.getFirst() + " because distance " + entry.getSecond() + "m > max distance " + maxDistance + "m"); } } logger.log(Level.INFO, "Proximity query looked in " + searchedCells.size() + " geocells and found " + result.size() + " results."); return result; }
From source file:com.venilnoronha.dzone.feed.cleanup.Cleaner.java
private <T> int clean(int itemsToKeep, String dateField, MongoRepository<T, String> repo) { int deleted = 0; long itemsCount = repo.count(); if (itemsCount > itemsToKeep) { List<T> items = repo.findAll(new Sort(Direction.DESC, dateField)); List<T> toDelete = items.subList(itemsToKeep, items.size()); repo.delete(toDelete);//from w w w . j a v a 2 s .c o m deleted = toDelete.size(); } return deleted; }
From source file:org.LexGrid.LexBIG.caCore.webservice.LexEVSWSQueryImpl.java
public List getAssociation(Object source, String associationName, int startIndex) throws Exception { List<Object> results = applicationService.getAssociation(source, associationName); return results.subList(startIndex, results.size()); }
From source file:net.gbmb.collector.example.WebdavTempStorage.java
@Override public void dropCollection(String cid) throws IOException { String target = String.format("%s/%s/%s/", host, root, cid); if (client.exists(target)) { List<DavResource> found = client.list(target); for (DavResource res : found.subList(1, found.size())) { client.delete(String.format("%s/%s", host, res.getPath())); }/*from w w w . ja va 2 s . c o m*/ client.delete(target); } }
From source file:net.dv8tion.jda.core.requests.restaction.order.RoleOrderAction.java
/** * Creates a new RoleOrderAction instance * * @param guild// w w w . jav a2s .co m * The target {@link net.dv8tion.jda.core.entities.Guild Guild} of which * to change the {@link net.dv8tion.jda.core.entities.Role Role} order * @param useDiscordOrder * Defines the ordering of the OrderAction. If {@code true}, the OrderAction will be in the ordering * defined by Discord for roles, which is Descending. This means that the highest role appears at index {@code 0} * and the lowest role at index {@code n - 1}. Providing {@code false} will result in the ordering being * in ascending order, with the lower role at index {@code 0} and the highest at index {@code n - 1}. * <br>As a note: {@link net.dv8tion.jda.core.entities.Member#getRoles() Member.getRoles()} * and {@link net.dv8tion.jda.core.entities.Guild#getRoles() Guild.getRoles()} are both in descending order. */ public RoleOrderAction(Guild guild, boolean useDiscordOrder) { super(guild.getJDA(), !useDiscordOrder, Route.Guilds.MODIFY_ROLES.compile(guild.getId())); this.guild = guild; List<Role> roles = guild.getRoles(); roles = roles.subList(0, roles.size() - 1); //Don't include the @everyone role. if (useDiscordOrder) { //Add roles to orderList in reverse due to role position ordering being descending // Top role starts at roles.size() - 1, bottom is 0. for (int i = roles.size() - 1; i >= 0; i--) this.orderList.add(roles.get(i)); } else { //If not using discord ordering, we are ascending, so we add from first to last. // We add first to last because the roles provided from getRoles() are in ascending order already // with the highest role at index 0. this.orderList.addAll(roles); } }
From source file:info.magnolia.jcr.util.NodeUtil.java
/** * Gets the siblings after this node with certain type. * @param node node from which will be siblings retrieved * @param nodeTypeName requested type of siblings nodes * @return list of siblings after the given Node (the given node is excluded) *///ww w. jav a2s . c o m public static Iterable<Node> getSiblingsAfter(Node node, String nodeTypeName) throws RepositoryException { Node parent = node.getParent(); List<Node> allSiblings = NodeUtil.asList(NodeUtil.getNodes(parent)); int fromIndex = 0; for (Node sibling : allSiblings) { fromIndex++; if (NodeUtil.isSame(node, sibling)) { break; } } List<Node> sameTypeSiblings = new ArrayList<Node>(); for (Node sibling : allSiblings.subList(fromIndex, allSiblings.size())) { if (isNodeType(sibling, nodeTypeName)) { sameTypeSiblings.add(sibling); } } return sameTypeSiblings; }