Example usage for java.util HashSet toArray

List of usage examples for java.util HashSet toArray

Introduction

In this page you can find the example usage for java.util HashSet toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:fastcall.FastCallSNP.java

private void updateTaxaBamPathMap(File[] bams) {
    String bamDirS = bams[0].getParent();
    String[] existingBam = new String[bams.length];
    for (int i = 0; i < bams.length; i++)
        existingBam[i] = bams[i].getName();
    Arrays.sort(existingBam);/*  w  w w  . j a v  a2s  . com*/
    HashSet<String> existingTaxaSet = new HashSet();
    HashMap<String, String[]> updatedTaxaBamMap = new HashMap();
    int cnt = 0;
    ArrayList<String> pathList = new ArrayList();
    for (int i = 0; i < taxaNames.length; i++) {
        String[] bamNames = taxaBamPathMap.get(taxaNames[i]);
        ArrayList<String> bamPathList = new ArrayList();
        for (int j = 0; j < bamNames.length; j++) {
            int index = Arrays.binarySearch(existingBam, bamNames[j]);
            if (index < 0)
                continue;
            String path = new File(bamDirS, bamNames[j]).getAbsolutePath();
            bamPathList.add(path);
            pathList.add(path);
            existingTaxaSet.add(taxaNames[i]);
        }
        if (bamPathList.isEmpty())
            continue;
        bamNames = bamPathList.toArray(new String[bamPathList.size()]);
        Arrays.sort(bamNames);
        updatedTaxaBamMap.put(taxaNames[i], bamNames);
        cnt += bamNames.length;
    }
    String[] updatedTaxaNames = existingTaxaSet.toArray(new String[existingTaxaSet.size()]);
    Arrays.sort(updatedTaxaNames);
    taxaNames = updatedTaxaNames;
    taxaBamPathMap = updatedTaxaBamMap;
    this.bamPaths = pathList.toArray(new String[pathList.size()]);
    Arrays.sort(bamPaths);
    System.out.println("Actual taxa number:\t" + String.valueOf(taxaNames.length));
    System.out.println("Actual bam file number:\t" + String.valueOf(cnt));
    System.out.println();
}

From source file:de.juwimm.cms.remote.UserServiceSpringImpl.java

/**
 * @see de.juwimm.cms.remote.UserServiceSpring#getAllUsers4OwnSites()
 *///from  www  .  j  av a  2  s.c om
@Override
protected UserValue[] handleGetAllUsers4OwnSites() throws Exception {
    UserValue[] itarr = null;
    SiteValue[] mySites = this.getAllSites4CurrentUser();
    HashSet<UserValue> userSet = new HashSet<UserValue>();
    try {
        for (int i = (mySites.length - 1); i >= 0; i--) {
            Collection users = super.getUserHbmDao().findAll(mySites[i].getSiteId());
            Iterator it = users.iterator();
            while (it.hasNext()) {
                UserHbm user = (UserHbm) it.next();
                if (!user.isMasterRoot()) {
                    userSet.add(user.getUserValue());
                }
            }
        }
    } catch (Exception e) {
        log.error("Error occured", e);
    }
    itarr = userSet.toArray(new UserValue[0]);
    return itarr;
}

From source file:org.sakaiproject.evaluation.logic.EvalEmailsLogicImpl.java

public String[] sendEmailMessages(String message, String subject, Long evaluationId, String[] groupIds,
        String includeConstant) {
    EvalUtils.validateEmailIncludeConstant(includeConstant);
    LOG.debug(/* w w  w . j  a  v a 2s. c o  m*/
            "message:" + message + ", evaluationId: " + evaluationId + ", includeConstant: " + includeConstant);

    EvalEvaluation eval = getEvaluationOrFail(evaluationId);
    String from = getFromEmailOrFail(eval);

    // get the associated eval groups for this evaluation
    // NOTE: this only returns the groups that should get emails, there is no need to do an additional check
    // to see if the instructor has opted in in this case -AZ
    Map<Long, List<EvalGroup>> evalGroupIds = evaluationService
            .getEvalGroupsForEval(new Long[] { evaluationId }, false, null);

    // only one possible map key so we can assume evaluationId
    List<EvalGroup> groups = evalGroupIds.get(evaluationId);
    LOG.debug("Found " + groups.size() + " groups for available evaluation: " + evaluationId);

    List<String> sentEmails = new ArrayList<>();
    // loop through groups and send emails to correct users in each
    for (int i = 0; i < groups.size(); i++) {
        EvalGroup group = (EvalGroup) groups.get(i);
        if (EvalConstants.GROUP_TYPE_INVALID.equals(group.type)) {
            continue; // skip processing for invalid groups
        }
        if (org.apache.commons.lang.ArrayUtils.isNotEmpty(groupIds)) {
            if (!ArrayUtils.contains(groupIds, group.evalGroupId)) {
                continue;
            }
        }
        String evalGroupId = group.evalGroupId;

        String[] limitGroupIds = null;
        if (evalGroupId != null) {
            limitGroupIds = new String[] { evalGroupId };
        }

        HashSet<String> userIdsSet = new HashSet<>();
        List<EvalAssignUser> participants = evaluationService.getParticipantsForEval(evaluationId, null,
                limitGroupIds, null, null, includeConstant, null);
        for (EvalAssignUser evalAssignUser : participants) {
            userIdsSet.add(evalAssignUser.getUserId());
        }

        //Set<String> userIdsSet = evaluationService.getUserIdsTakingEvalInGroup(evaluationId, evalGroupId, includeConstant);
        if (userIdsSet.size() > 0) {
            // turn the set into an array
            String[] toUserIds = (String[]) userIdsSet.toArray(new String[] {});
            LOG.debug("Found " + toUserIds.length + " users (" + toUserIds + ") to send "
                    + EvalConstants.EMAIL_TEMPLATE_REMINDER + " notification to for available evaluation ("
                    + evaluationId + ") and group (" + group.evalGroupId + ")");

            // replace the text of the template with real values
            Map<String, String> replacementValues = new HashMap<>();
            replacementValues.put("HelpdeskEmail", from);

            // send the actual emails for this evalGroupId
            String[] emailAddresses = sendUsersEmails(from, toUserIds, subject, message);
            LOG.info("Sent evaluation reminder message to " + emailAddresses.length
                    + " users (attempted to send to " + toUserIds.length + ")");
            // store sent emails to return
            sentEmails.addAll(Arrays.asList(emailAddresses));
            commonLogic.registerEntityEvent(EVENT_EMAIL_REMINDER, eval);
        }
    }

    return (String[]) sentEmails.toArray(new String[] {});
}

From source file:org.hyperic.hq.measurement.server.session.AvailabilityManagerImpl.java

@SuppressWarnings("unchecked")
/**/*from ww w . j a va2s  .  com*/
 * get AvailabilityDataRLEs for the given DataPoints' Measurement IDs, with endData within the last 7 days.
 * If several AvailabilityDataRLEs exist for the same Measurement, they are listed in ascending order.
 * @param outOfOrderAvail
 * @param updateList
 * @return
 */
private Map<Integer, TreeSet<AvailabilityDataRLE>> createCurrAvails(final List<DataPoint> outOfOrderAvail,
        final List<DataPoint> updateList) {
    Map<Integer, TreeSet<AvailabilityDataRLE>> currAvails = null;
    final StopWatch watch = new StopWatch();
    try {
        if (outOfOrderAvail.size() == 0 && updateList.size() == 0) {
            currAvails = Collections.EMPTY_MAP;
        }
        long now = TimingVoodoo.roundDownTime(System.currentTimeMillis(), 60000);
        HashSet<Integer> mids = getMidsWithinAllowedDataWindow(updateList, now);
        mids.addAll(getMidsWithinAllowedDataWindow(outOfOrderAvail, now));
        if (mids.size() <= 0) {
            currAvails = Collections.EMPTY_MAP;

        }
        Integer[] mIds = (Integer[]) mids.toArray(new Integer[0]);
        currAvails = availabilityDataDAO.getHistoricalAvailMap(mIds, now - MAX_DATA_BACKLOG_TIME, false);
        return currAvails;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("AvailabilityInserter setCurrAvails: " + watch + ", size=" + currAvails.size());
        }
    }
}

From source file:net.countercraft.movecraft.async.rotation.RotationTask.java

@Override
public void excecute() {

    int waterLine = 0;

    int[][][] hb = getCraft().getHitBox();
    if (hb == null)
        return;// w w  w.  j  a  v  a 2  s  .  com

    // Determine craft borders
    int minY = 65535;
    int maxY = -65535;
    for (int[][] i1 : hb) {
        for (int[] i2 : i1) {
            if (i2 != null) {
                if (i2[0] < minY) {
                    minY = i2[0];
                }
                if (i2[1] > maxY) {
                    maxY = i2[1];
                }
            }
        }
    }
    Integer maxX = getCraft().getMinX() + hb.length;
    Integer maxZ = getCraft().getMinZ() + hb[0].length; // safe because if the first x array doesn't have a z array, then it wouldn't be the first x array
    minX = getCraft().getMinX();
    minZ = getCraft().getMinZ();

    int distX = maxX - minX;
    int distZ = maxZ - minZ;

    Player craftPilot = CraftManager.getInstance().getPlayerFromCraft(getCraft());

    if (getCraft().getDisabled() && (!getCraft().getSinking())) {
        failed = true;
        failMessage = String.format(I18nSupport.getInternationalisedString("Craft is disabled!"));
    }

    // blockedByWater=false means an ocean-going vessel
    boolean waterCraft = !getCraft().getType().blockedByWater();

    if (waterCraft) {
        // next figure out the water level by examining blocks next to the outer boundaries of the craft
        for (int posY = maxY; (posY >= minY) && (waterLine == 0); posY--) {
            int posX;
            int posZ;
            posZ = getCraft().getMinZ() - 1;
            for (posX = getCraft().getMinX() - 1; (posX <= maxX + 1) && (waterLine == 0); posX++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
            posZ = maxZ + 1;
            for (posX = getCraft().getMinX() - 1; (posX <= maxX + 1) && (waterLine == 0); posX++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
            posX = getCraft().getMinX() - 1;
            for (posZ = getCraft().getMinZ(); (posZ <= maxZ) && (waterLine == 0); posZ++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
            posX = maxX + 1;
            for (posZ = getCraft().getMinZ(); (posZ <= maxZ) && (waterLine == 0); posZ++) {
                if (w.getBlockAt(posX, posY, posZ).getTypeId() == 9) {
                    waterLine = posY;
                }
            }
        }

        // now add all the air blocks found within the crafts borders below the waterline to the craft blocks so they will be rotated
        HashSet<MovecraftLocation> newHSBlockList = new HashSet<MovecraftLocation>(Arrays.asList(blockList));
        for (int posY = waterLine; posY >= minY; posY--) {
            for (int posX = getCraft().getMinX(); posX <= maxX; posX++) {
                for (int posZ = getCraft().getMinZ(); posZ <= maxZ; posZ++) {
                    if (w.getBlockAt(posX, posY, posZ).getTypeId() == 0) {
                        MovecraftLocation l = new MovecraftLocation(posX, posY, posZ);
                        newHSBlockList.add(l);
                    }
                }
            }
        }
        blockList = newHSBlockList.toArray(new MovecraftLocation[newHSBlockList.size()]);
    }

    // check for fuel, burn some from a furnace if needed. Blocks of coal are supported, in addition to coal and charcoal
    double fuelBurnRate = getCraft().getType().getFuelBurnRate();
    if (fuelBurnRate != 0.0 && getCraft().getSinking() == false) {
        if (getCraft().getBurningFuel() < fuelBurnRate) {
            Block fuelHolder = null;
            for (MovecraftLocation bTest : blockList) {
                Block b = getCraft().getW().getBlockAt(bTest.getX(), bTest.getY(), bTest.getZ());
                if (b.getTypeId() == 61) {
                    InventoryHolder inventoryHolder = (InventoryHolder) b.getState();
                    if (inventoryHolder.getInventory().contains(263)
                            || inventoryHolder.getInventory().contains(173)) {
                        fuelHolder = b;
                    }
                }
            }
            if (fuelHolder == null) {
                failed = true;
                failMessage = String.format(
                        I18nSupport.getInternationalisedString("Translation - Failed Craft out of fuel"));
            } else {
                InventoryHolder inventoryHolder = (InventoryHolder) fuelHolder.getState();
                if (inventoryHolder.getInventory().contains(263)) {
                    ItemStack iStack = inventoryHolder.getInventory()
                            .getItem(inventoryHolder.getInventory().first(263));
                    int amount = iStack.getAmount();
                    if (amount == 1) {
                        inventoryHolder.getInventory().remove(iStack);
                    } else {
                        iStack.setAmount(amount - 1);
                    }
                    getCraft().setBurningFuel(getCraft().getBurningFuel() + 7.0);
                } else {
                    ItemStack iStack = inventoryHolder.getInventory()
                            .getItem(inventoryHolder.getInventory().first(173));
                    int amount = iStack.getAmount();
                    if (amount == 1) {
                        inventoryHolder.getInventory().remove(iStack);
                    } else {
                        iStack.setAmount(amount - 1);
                    }
                    getCraft().setBurningFuel(getCraft().getBurningFuel() + 79.0);

                }
            }
        } else {
            getCraft().setBurningFuel(getCraft().getBurningFuel() - fuelBurnRate);
        }
    }

    // Rotate the block set
    MovecraftLocation[] centeredBlockList = new MovecraftLocation[blockList.length];
    MovecraftLocation[] originalBlockList = blockList.clone();
    HashSet<MovecraftLocation> existingBlockSet = new HashSet<MovecraftLocation>(
            Arrays.asList(originalBlockList));
    Set<MapUpdateCommand> mapUpdates = new HashSet<MapUpdateCommand>();
    HashSet<EntityUpdateCommand> entityUpdateSet = new HashSet<EntityUpdateCommand>();

    boolean townyEnabled = Movecraft.getInstance().getTownyPlugin() != null;
    Set<TownBlock> townBlockSet = new HashSet<TownBlock>();
    TownyWorld townyWorld = null;
    TownyWorldHeightLimits townyWorldHeightLimits = null;

    if (townyEnabled && Settings.TownyBlockMoveOnSwitchPerm) {
        townyWorld = TownyUtils.getTownyWorld(getCraft().getW());
        if (townyWorld != null) {
            townyEnabled = townyWorld.isUsingTowny();
            if (townyEnabled)
                townyWorldHeightLimits = TownyUtils.getWorldLimits(getCraft().getW());
        }
    } else {
        townyEnabled = false;
    }

    // if a subcraft, find the parent craft. If not a subcraft, it is it's own parent
    Craft[] craftsInWorld = CraftManager.getInstance().getCraftsInWorld(getCraft().getW());
    Craft parentCraft = getCraft();
    for (Craft craft : craftsInWorld) {
        if (BlockUtils.arrayContainsOverlap(craft.getBlockList(), originalBlockList) && craft != getCraft()) {
            // found a parent craft
            //            if(craft.isNotProcessing()==false) {
            //               failed=true;
            //               failMessage = String.format( I18nSupport.getInternationalisedString( "Parent Craft is busy" ));
            //               return;
            //            } else {
            //               craft.setProcessing(true); // prevent the parent craft from moving or updating until the subcraft is done
            parentCraft = craft;
            //            }
        }
    }

    int craftMinY = 0;
    int craftMaxY = 0;
    // make the centered block list
    for (int i = 0; i < blockList.length; i++) {
        centeredBlockList[i] = blockList[i].subtract(originPoint);

    }

    for (int i = 0; i < blockList.length; i++) {

        blockList[i] = MathUtils.rotateVec(rotation, centeredBlockList[i]).add(originPoint);
        int typeID = w.getBlockTypeIdAt(blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());

        Material testMaterial = w.getBlockAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                originalBlockList[i].getZ()).getType();

        if (testMaterial.equals(Material.CHEST) || testMaterial.equals(Material.TRAPPED_CHEST)) {
            if (!checkChests(testMaterial, blockList[i], existingBlockSet)) {
                //prevent chests collision
                failed = true;
                failMessage = String
                        .format(I18nSupport.getInternationalisedString("Rotation - Craft is obstructed")
                                + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                break;
            }
        }
        Location plugLoc = new Location(w, blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
        if (craftPilot != null) {
            // See if they are permitted to build in the area, if WorldGuard integration is turned on
            if (Movecraft.getInstance().getWorldGuardPlugin() != null
                    && Settings.WorldGuardBlockMoveOnBuildPerm) {
                if (Movecraft.getInstance().getWorldGuardPlugin().canBuild(craftPilot, plugLoc) == false) {
                    failed = true;
                    failMessage = String.format(I18nSupport.getInternationalisedString(
                            "Rotation - Player is not permitted to build in this WorldGuard region")
                            + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                    break;
                }
            }
        }

        Player p;
        if (craftPilot == null) {
            p = getCraft().getNotificationPlayer();
        } else {
            p = craftPilot;
        }
        if (p != null) {
            if (Movecraft.getInstance().getWorldGuardPlugin() != null
                    && Movecraft.getInstance().getWGCustomFlagsPlugin() != null
                    && Settings.WGCustomFlagsUsePilotFlag) {
                LocalPlayer lp = Movecraft.getInstance().getWorldGuardPlugin().wrapPlayer(p);
                WGCustomFlagsUtils WGCFU = new WGCustomFlagsUtils();
                if (!WGCFU.validateFlag(plugLoc, Movecraft.FLAG_ROTATE, lp)) {
                    failed = true;
                    failMessage = String.format(
                            I18nSupport.getInternationalisedString("WGCustomFlags - Rotation Failed")
                                    + " @ %d,%d,%d",
                            blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                    break;
                }
            }

            if (townyEnabled) {
                TownBlock townBlock = TownyUtils.getTownBlock(plugLoc);
                if (townBlock != null && !townBlockSet.contains(townBlock)) {
                    if (TownyUtils.validateCraftMoveEvent(p, plugLoc, townyWorld)) {
                        townBlockSet.add(townBlock);
                    } else {
                        int y = plugLoc.getBlockY();
                        boolean oChange = false;
                        if (craftMinY > y) {
                            craftMinY = y;
                            oChange = true;
                        }
                        if (craftMaxY < y) {
                            craftMaxY = y;
                            oChange = true;
                        }
                        if (oChange) {
                            Town town = TownyUtils.getTown(townBlock);
                            if (town != null) {
                                Location locSpawn = TownyUtils.getTownSpawn(townBlock);
                                if (locSpawn != null) {
                                    if (!townyWorldHeightLimits.validate(y, locSpawn.getBlockY())) {
                                        failed = true;
                                    }
                                } else {
                                    failed = true;
                                }
                                if (failed) {
                                    if (Movecraft.getInstance().getWorldGuardPlugin() != null
                                            && Movecraft.getInstance().getWGCustomFlagsPlugin() != null
                                            && Settings.WGCustomFlagsUsePilotFlag) {
                                        LocalPlayer lp = Movecraft.getInstance().getWorldGuardPlugin()
                                                .wrapPlayer(p);
                                        ApplicableRegionSet regions = Movecraft.getInstance()
                                                .getWorldGuardPlugin().getRegionManager(plugLoc.getWorld())
                                                .getApplicableRegions(plugLoc);
                                        if (regions.size() != 0) {
                                            WGCustomFlagsUtils WGCFU = new WGCustomFlagsUtils();
                                            if (WGCFU.validateFlag(plugLoc, Movecraft.FLAG_ROTATE, lp)) {
                                                failed = false;
                                            }
                                        }
                                    }
                                }
                                if (failed) {
                                    failMessage = String.format(
                                            I18nSupport.getInternationalisedString("Towny - Rotation Failed")
                                                    + " %s @ %d,%d,%d",
                                            town.getName(), blockList[i].getX(), blockList[i].getY(),
                                            blockList[i].getZ());
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!waterCraft) {
            if ((typeID != 0 && typeID != 34) && !existingBlockSet.contains(blockList[i])) {
                failed = true;
                failMessage = String
                        .format(I18nSupport.getInternationalisedString("Rotation - Craft is obstructed")
                                + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                break;
            } else {
                int id = w.getBlockTypeIdAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ());
                byte data = w.getBlockAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ()).getData();
                int currentID = w.getBlockTypeIdAt(blockList[i].getX(), blockList[i].getY(),
                        blockList[i].getZ());
                byte currentData = w.getBlockAt(blockList[i].getX(), blockList[i].getY(), blockList[i].getZ())
                        .getData();
                if (BlockUtils.blockRequiresRotation(id)) {
                    data = BlockUtils.rotate(data, id, rotation);
                }
                mapUpdates.add(new MapUpdateCommand(originalBlockList[i], currentID, currentData, blockList[i],
                        id, data, rotation, parentCraft));
            }
        } else {
            // allow watercraft to rotate through water
            if ((typeID != 0 && typeID != 9 && typeID != 34) && !existingBlockSet.contains(blockList[i])) {
                failed = true;
                failMessage = String
                        .format(I18nSupport.getInternationalisedString("Rotation - Craft is obstructed")
                                + " @ %d,%d,%d", blockList[i].getX(), blockList[i].getY(), blockList[i].getZ());
                break;
            } else {
                int id = w.getBlockTypeIdAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ());
                byte data = w.getBlockAt(originalBlockList[i].getX(), originalBlockList[i].getY(),
                        originalBlockList[i].getZ()).getData();
                int currentID = w.getBlockTypeIdAt(blockList[i].getX(), blockList[i].getY(),
                        blockList[i].getZ());
                byte currentData = w.getBlockAt(blockList[i].getX(), blockList[i].getY(), blockList[i].getZ())
                        .getData();
                if (BlockUtils.blockRequiresRotation(id)) {
                    data = BlockUtils.rotate(data, id, rotation);
                }
                mapUpdates.add(new MapUpdateCommand(originalBlockList[i], currentID, currentData, blockList[i],
                        id, data, rotation, parentCraft));
            }
        }

    }

    if (!failed) {
        //rotate entities in the craft
        Location tOP = new Location(getCraft().getW(), originPoint.getX(), originPoint.getY(),
                originPoint.getZ());

        List<Entity> eList = null;
        int numTries = 0;

        while ((eList == null) && (numTries < 100)) {
            try {
                eList = getCraft().getW().getEntities();
            } catch (java.util.ConcurrentModificationException e) {
                numTries++;
            }
        }
        Iterator<Entity> i = getCraft().getW().getEntities().iterator();
        while (i.hasNext()) {
            Entity pTest = i.next();
            //            if ( MathUtils.playerIsWithinBoundingPolygon( getCraft().getHitBox(), getCraft().getMinX(), getCraft().getMinZ(), MathUtils.bukkit2MovecraftLoc( pTest.getLocation() ) ) ) {
            if (MathUtils.locIsNearCraftFast(getCraft(), MathUtils.bukkit2MovecraftLoc(pTest.getLocation()))) {
                if (pTest.getType() != org.bukkit.entity.EntityType.DROPPED_ITEM) {
                    // Player is onboard this craft
                    tOP.setX(tOP.getBlockX() + 0.5);
                    tOP.setZ(tOP.getBlockZ() + 0.5);
                    Location playerLoc = pTest.getLocation();
                    // direct control no longer locks the player in place                  
                    //                  if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) {
                    //                     playerLoc.setX(getCraft().getPilotLockedX());
                    //                     playerLoc.setY(getCraft().getPilotLockedY());
                    //                     playerLoc.setZ(getCraft().getPilotLockedZ());
                    //                     }
                    Location adjustedPLoc = playerLoc.subtract(tOP);

                    double[] rotatedCoords = MathUtils.rotateVecNoRound(rotation, adjustedPLoc.getX(),
                            adjustedPLoc.getZ());
                    Location rotatedPloc = new Location(getCraft().getW(), rotatedCoords[0], playerLoc.getY(),
                            rotatedCoords[1]);
                    Location newPLoc = rotatedPloc.add(tOP);

                    newPLoc.setPitch(playerLoc.getPitch());
                    float newYaw = playerLoc.getYaw();
                    if (rotation == Rotation.CLOCKWISE) {
                        newYaw = newYaw + 90.0F;
                        if (newYaw >= 360.0F) {
                            newYaw = newYaw - 360.0F;
                        }
                    }
                    if (rotation == Rotation.ANTICLOCKWISE) {
                        newYaw = newYaw - 90;
                        if (newYaw < 0.0F) {
                            newYaw = newYaw + 360.0F;
                        }
                    }
                    newPLoc.setYaw(newYaw);

                    //                  if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) {
                    //                     getCraft().setPilotLockedX(newPLoc.getX());
                    //                     getCraft().setPilotLockedY(newPLoc.getY());
                    //                     getCraft().setPilotLockedZ(newPLoc.getZ());
                    //                     }
                    EntityUpdateCommand eUp = new EntityUpdateCommand(pTest.getLocation().clone(), newPLoc,
                            pTest);
                    entityUpdateSet.add(eUp);
                    //                  if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) {
                    //                     getCraft().setPilotLockedX(newPLoc.getX());
                    //                     getCraft().setPilotLockedY(newPLoc.getY());
                    //                     getCraft().setPilotLockedZ(newPLoc.getZ());
                    //                  }
                } else {
                    //   pTest.remove();   removed to test cleaner fragile item removal
                }
            }

        }

        /*         //update player spawn locations if they spawned where the ship used to be
                 for(Player p : Movecraft.getInstance().getServer().getOnlinePlayers()) {
                    if(p.getBedSpawnLocation()!=null) {
                       if( MathUtils.playerIsWithinBoundingPolygon( getCraft().getHitBox(), getCraft().getMinX(), getCraft().getMinZ(), MathUtils.bukkit2MovecraftLoc( p.getBedSpawnLocation() ) ) ) {
          Location spawnLoc = p.getBedSpawnLocation();
          Location adjustedPLoc = spawnLoc.subtract( tOP ); 
                
          double[] rotatedCoords = MathUtils.rotateVecNoRound( rotation, adjustedPLoc.getX(), adjustedPLoc.getZ() );
          Location rotatedPloc = new Location( getCraft().getW(), rotatedCoords[0], spawnLoc.getY(), rotatedCoords[1] );
          Location newBedSpawn = rotatedPloc.add( tOP );
                
          p.setBedSpawnLocation(newBedSpawn, true);
                       }
                    }
                 }*/

        // Calculate air changes
        List<MovecraftLocation> airLocation = ListUtils.subtract(Arrays.asList(originalBlockList),
                Arrays.asList(blockList));

        for (MovecraftLocation l1 : airLocation) {
            if (waterCraft) {
                // if its below the waterline, fill in with water. Otherwise fill in with air.
                if (l1.getY() <= waterLine) {
                    mapUpdates.add(new MapUpdateCommand(l1, 9, (byte) 0, parentCraft));
                } else {
                    mapUpdates.add(new MapUpdateCommand(l1, 0, (byte) 0, parentCraft));
                }
            } else {
                mapUpdates.add(new MapUpdateCommand(l1, 0, (byte) 0, parentCraft));
            }
        }

        // rotate scheduled block changes
        HashMap<MapUpdateCommand, Long> newScheduledBlockChanges = new HashMap<MapUpdateCommand, Long>();
        HashMap<MapUpdateCommand, Long> oldScheduledBlockChanges = getCraft().getScheduledBlockChanges();
        for (MapUpdateCommand muc : oldScheduledBlockChanges.keySet()) {
            MovecraftLocation newLoc = muc.getNewBlockLocation();
            newLoc = newLoc.subtract(originPoint);
            newLoc = MathUtils.rotateVec(rotation, newLoc).add(originPoint);
            Long newTime = System.currentTimeMillis() + 5000;
            MapUpdateCommand newMuc = new MapUpdateCommand(newLoc, muc.getTypeID(), muc.getDataID(),
                    parentCraft);
            newScheduledBlockChanges.put(newMuc, newTime);
        }
        this.scheduledBlockChanges = newScheduledBlockChanges;

        MapUpdateCommand[] updateArray = mapUpdates.toArray(new MapUpdateCommand[1]);
        //            MapUpdateManager.getInstance().sortUpdates(updateArray);
        this.updates = updateArray;
        this.entityUpdates = entityUpdateSet.toArray(new EntityUpdateCommand[1]);

        maxX = null;
        maxZ = null;
        minX = null;
        minZ = null;

        for (MovecraftLocation l : blockList) {
            if (maxX == null || l.getX() > maxX) {
                maxX = l.getX();
            }
            if (maxZ == null || l.getZ() > maxZ) {
                maxZ = l.getZ();
            }
            if (minX == null || l.getX() < minX) {
                minX = l.getX();
            }
            if (minZ == null || l.getZ() < minZ) {
                minZ = l.getZ();
            }
        }

        // Rerun the polygonal bounding formula for the newly formed craft
        int sizeX, sizeZ;
        sizeX = (maxX - minX) + 1;
        sizeZ = (maxZ - minZ) + 1;

        int[][][] polygonalBox = new int[sizeX][][];

        for (MovecraftLocation l : blockList) {
            if (polygonalBox[l.getX() - minX] == null) {
                polygonalBox[l.getX() - minX] = new int[sizeZ][];
            }

            if (polygonalBox[l.getX() - minX][l.getZ() - minZ] == null) {

                polygonalBox[l.getX() - minX][l.getZ() - minZ] = new int[2];
                polygonalBox[l.getX() - minX][l.getZ() - minZ][0] = l.getY();
                polygonalBox[l.getX() - minX][l.getZ() - minZ][1] = l.getY();

            } else {
                minY = polygonalBox[l.getX() - minX][l.getZ() - minZ][0];
                maxY = polygonalBox[l.getX() - minX][l.getZ() - minZ][1];

                if (l.getY() < minY) {
                    polygonalBox[l.getX() - minX][l.getZ() - minZ][0] = l.getY();
                }
                if (l.getY() > maxY) {
                    polygonalBox[l.getX() - minX][l.getZ() - minZ][1] = l.getY();
                }

            }

        }

        this.hitbox = polygonalBox;
        if (getCraft().getCruising()) {
            if (rotation == Rotation.ANTICLOCKWISE) {
                // ship faces west
                if (getCraft().getCruiseDirection() == 0x5) {
                    getCraft().setCruiseDirection((byte) 0x2);
                } else
                // ship faces east
                if (getCraft().getCruiseDirection() == 0x4) {
                    getCraft().setCruiseDirection((byte) 0x3);
                } else
                // ship faces north
                if (getCraft().getCruiseDirection() == 0x2) {
                    getCraft().setCruiseDirection((byte) 0x4);
                } else
                // ship faces south
                if (getCraft().getCruiseDirection() == 0x3) {
                    getCraft().setCruiseDirection((byte) 0x5);
                }
            } else if (rotation == Rotation.CLOCKWISE) {
                // ship faces west
                if (getCraft().getCruiseDirection() == 0x5) {
                    getCraft().setCruiseDirection((byte) 0x3);
                } else
                // ship faces east
                if (getCraft().getCruiseDirection() == 0x4) {
                    getCraft().setCruiseDirection((byte) 0x2);
                } else
                // ship faces north
                if (getCraft().getCruiseDirection() == 0x2) {
                    getCraft().setCruiseDirection((byte) 0x5);
                } else
                // ship faces south
                if (getCraft().getCruiseDirection() == 0x3) {
                    getCraft().setCruiseDirection((byte) 0x4);
                }
            }
        }

        // if you rotated a subcraft, update the parent with the new blocks
        if (this.isSubCraft) {
            // also find the furthest extent from center and notify the player of the new direction
            int farthestX = 0;
            int farthestZ = 0;
            for (MovecraftLocation loc : blockList) {
                if (Math.abs(loc.getX() - originPoint.getX()) > Math.abs(farthestX))
                    farthestX = loc.getX() - originPoint.getX();
                if (Math.abs(loc.getZ() - originPoint.getZ()) > Math.abs(farthestZ))
                    farthestZ = loc.getZ() - originPoint.getZ();
            }
            if (Math.abs(farthestX) > Math.abs(farthestZ)) {
                if (farthestX > 0) {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces East");
                } else {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces West");
                }
            } else {
                if (farthestZ > 0) {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces South");
                } else {
                    if (getCraft().getNotificationPlayer() != null)
                        getCraft().getNotificationPlayer().sendMessage("The farthest extent now faces North");
                }
            }

            craftsInWorld = CraftManager.getInstance().getCraftsInWorld(getCraft().getW());
            for (Craft craft : craftsInWorld) {
                if (BlockUtils.arrayContainsOverlap(craft.getBlockList(), originalBlockList)
                        && craft != getCraft()) {
                    List<MovecraftLocation> parentBlockList = ListUtils
                            .subtract(Arrays.asList(craft.getBlockList()), Arrays.asList(originalBlockList));
                    parentBlockList.addAll(Arrays.asList(blockList));
                    craft.setBlockList(parentBlockList.toArray(new MovecraftLocation[1]));

                    // Rerun the polygonal bounding formula for the parent craft
                    Integer parentMaxX = null;
                    Integer parentMaxZ = null;
                    Integer parentMinX = null;
                    Integer parentMinZ = null;
                    for (MovecraftLocation l : parentBlockList) {
                        if (parentMaxX == null || l.getX() > parentMaxX) {
                            parentMaxX = l.getX();
                        }
                        if (parentMaxZ == null || l.getZ() > parentMaxZ) {
                            parentMaxZ = l.getZ();
                        }
                        if (parentMinX == null || l.getX() < parentMinX) {
                            parentMinX = l.getX();
                        }
                        if (parentMinZ == null || l.getZ() < parentMinZ) {
                            parentMinZ = l.getZ();
                        }
                    }
                    int parentSizeX, parentSizeZ;
                    parentSizeX = (parentMaxX - parentMinX) + 1;
                    parentSizeZ = (parentMaxZ - parentMinZ) + 1;
                    int[][][] parentPolygonalBox = new int[parentSizeX][][];
                    for (MovecraftLocation l : parentBlockList) {
                        if (parentPolygonalBox[l.getX() - parentMinX] == null) {
                            parentPolygonalBox[l.getX() - parentMinX] = new int[parentSizeZ][];
                        }
                        if (parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ] == null) {
                            parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ] = new int[2];
                            parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][0] = l.getY();
                            parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][1] = l.getY();
                        } else {
                            int parentMinY = parentPolygonalBox[l.getX() - parentMinX][l.getZ()
                                    - parentMinZ][0];
                            int parentMaxY = parentPolygonalBox[l.getX() - parentMinX][l.getZ()
                                    - parentMinZ][1];

                            if (l.getY() < parentMinY) {
                                parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][0] = l.getY();
                            }
                            if (l.getY() > parentMaxY) {
                                parentPolygonalBox[l.getX() - parentMinX][l.getZ() - parentMinZ][1] = l.getY();
                            }
                        }
                    }
                    craft.setMinX(parentMinX);
                    craft.setMinZ(parentMinZ);
                    craft.setHitBox(parentPolygonalBox);
                }
            }
        }

    } else { // this else is for "if(!failed)"
        if (this.isSubCraft) {
            if (parentCraft != getCraft()) {
                parentCraft.setProcessing(false);
            }
        }
    }
}

From source file:free.yhc.feeder.ChannelListFragment.java

@Override
public void onResume() {
    super.onResume();
    //logI("==> ChannelListActivity : onResume");
    // NOTE/* ww  w. j  av  a2 s. co m*/
    // Case to think about
    // - new update task is registered between 'registerManagerEventListener' and 'getUpdateState'
    // - then, this task will be binded twice.
    // => This leads to over head operation (ex. refreshing list two times continuously etc.)
    //    But, this doesn't issue logical error. So, I can get along with this case.
    //
    // If 'registerManagerEventListener' is below 'getUpdateState',
    //   we may miss binding some updating task!
    mRtt.registerRegisterEventListener(this, new RTTaskRegisterListener());

    HashSet<Long> updatedCids = new HashSet<Long>();
    for (long cid : mDbWatcher.getUpdatedChannels())
        updatedCids.add(cid);

    HashSet<Long> myUpdatedCids = new HashSet<Long>();
    // Check channel state and bind it.
    // Why here? Not 'onStart'.
    // See comments in 'onPause()'
    try {
        mDbp.getDelayedChannelUpdate();
        Cursor c = mDbp.queryChannel(mCatId, ColumnChannel.ID);
        if (c.moveToFirst()) {
            do {
                long cid = c.getLong(0);
                if (updatedCids.contains(cid))
                    myUpdatedCids.add(cid);

                if (RTTask.TaskState.IDLE != mRtt.getState(cid, RTTask.Action.UPDATE))
                    mRtt.bind(cid, RTTask.Action.UPDATE, this, new UpdateBGTaskListener(cid));
                long[] ids = mRtt.getItemsDownloading(cid);
                for (long id : ids)
                    mRtt.bind(id, RTTask.Action.DOWNLOAD, this, new DownloadBGTaskListener(cid));
            } while (c.moveToNext());
        }
        c.close();
    } finally {
        mDbp.putDelayedChannelUpdate();
    }

    // NOTE
    // Channel may be added or deleted.
    // And channel operation is only allowed on current selected list
    //   according to use case.
    if (mDbWatcher.isChannelTableUpdated() && myUpdatedCids.size() > 0) {
        refreshListAsync();
    } else
        refreshListItem(Utils.convertArrayLongTolong(myUpdatedCids.toArray(new Long[0])));

    // We don't need to worry about item table change.
    // Because, if item is newly inserted, that means some of channel is updated.
    // And that channel will be updated according to DB changes.

    mDbWatcher.unregister();
    mDbWatcher.reset();
}

From source file:phonegraph.PhoneGraph.java

public void CreateGraphGT(String filename, int k) {
    try {//from www  .j  av  a  2 s . c  om
        FileReader fileReader = new FileReader(filename);
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        int count = 0;
        HashSet<Integer> nodes = new HashSet<Integer>(10000);
        while ((line = bufferedReader.readLine()) != null) {
            //ignore the prefix for phone and uri
            JSONObject documentInfo = (JSONObject) new JSONParser().parse(line);
            JSONArray phones = (JSONArray) documentInfo.get("high_precision_phone");
            //JSONObject rawdata = (JSONObject)documentInfo.get("crawl_data");
            if (phones != null) {
                for (int i = 0; i < phones.size(); i++) {
                    JSONObject o = (JSONObject) phones.get(i);
                    JSONArray a = (JSONArray) o.get("result");
                    for (int j = 0; j < a.size(); j++) {
                        JSONObject entity = (JSONObject) a.get(j);
                        String phone = (String) entity.get("value");
                        if (phonemaps.containsKey(phone) == true) {
                            int id = phonemaps.get(phone);
                            nodes.add(id);
                        }
                    }
                }

            }
            JSONArray emails = (JSONArray) documentInfo.get("high_precision_email");
            if (emails != null) {
                for (int i = 0; i < emails.size(); i++) {
                    JSONObject o = (JSONObject) emails.get(i);
                    JSONArray a = (JSONArray) o.get("result");
                    for (int j = 0; j < a.size(); j++) {
                        JSONObject entity = (JSONObject) a.get(j);
                        String email = (String) entity.get("value");
                        if (phonemaps.containsKey(email) == true) {
                            int id = phonemaps.get(email);
                            nodes.add(id);
                        }
                    }
                }
            }
            if (nodes.size() < k) {
                Integer[] arr = nodes.toArray(new Integer[nodes.size()]);
                for (int i = 0; i < arr.length; i++) {
                    for (int j = (i + 1); j < arr.length; j++) {
                        IntPair o = new IntPair(arr[i], arr[j]);
                        if (arr[i] > arr[j]) {
                            o.setKey(arr[j]);
                            o.setValue(arr[i]);
                        }
                        if (this.edges.containsKey(o) == false) {
                            this.edges.put(o, 1);
                        } else {
                            int freq = this.edges.get(o);
                            this.edges.put(o, freq + 1);
                        }
                    }
                }
            }
            nodes.clear();
            count++;
            if (count % 100 == 0) {
                System.out.println(count);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(PhoneGraph.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(PhoneGraph.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.gcaldaemon.gui.config.MainConfig.java

public final String[] getCalendarURLs(AccountInfo account, boolean loadFromGoogle) throws Exception {
    if (account == null || account.username == null) {
        return new String[0];
    }// ww w  .j  a  va 2s .  com
    HashSet set = new HashSet();
    String[] urls = null;
    int i;
    if (loadFromGoogle) {
        Request request = new Request();
        request.username = account.username;
        request.password = account.password;
        urls = GCalUtilities.getCalendarURLs(request, getWorkDirectory());
        urlMap.put(account.username, urls);
    } else {
        urls = (String[]) urlMap.get(account.username);
    }
    if (urls != null) {
        for (i = 0; i < urls.length; i++) {
            set.add(urls[i]);
        }
    }
    FileSync[] configs = getFileSyncConfigs();
    FileSync config;
    for (i = 0; i < configs.length; i++) {
        config = configs[i];
        if (account.username.equals(config.username)) {
            if (config.privateIcalUrl != null && config.privateIcalUrl.endsWith(".ics")
                    && !containsURL(set, config.privateIcalUrl)) {
                set.add(config.privateIcalUrl);
            }
        }
    }
    String[] array = new String[set.size()];
    set.toArray(array);
    Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
    return array;
}

From source file:it.acubelab.smaph.SmaphAnnotator.java

@Override
public HashSet<ScoredAnnotation> solveSa2W(String query) throws AnnotationException {
    if (debugger != null)
        debugger.addProcessedQuery(query);

    HashSet<ScoredAnnotation> annotations = new HashSet<>();
    try {/*  ww  w .j a v a  2 s  .  c  o  m*/

        /** Search the query on bing */
        List<Pair<String, Integer>> bingBoldsAndRankNS = null;
        List<String> urls = null;
        List<String> relatedSearchRes = null;
        Triple<Integer, Double, JSONObject> resCountAndWebTotalNS = null;
        int resultsCount = -1;
        double webTotalNS = Double.NaN;
        List<String> filteredBolds = null;
        HashMap<Integer, Integer> rankToIdNS = null;
        HashMap<Integer, HashSet<String>> rankToBoldsNS = null;
        List<Pair<String, Vector<Pair<Integer, Integer>>>> snippetsToBolds = null;
        if (includeSourceAnnotator || includeSourceWikiSearch || includeSourceRelatedSearch
                || includeSourceNormalSearch) {
            bingBoldsAndRankNS = new Vector<>();
            urls = new Vector<>();
            relatedSearchRes = new Vector<>();
            snippetsToBolds = new Vector<>();
            resCountAndWebTotalNS = takeBingData(query, bingBoldsAndRankNS, urls, relatedSearchRes,
                    snippetsToBolds, Integer.MAX_VALUE, false);
            resultsCount = resCountAndWebTotalNS.getLeft();
            webTotalNS = resCountAndWebTotalNS.getMiddle();
            filteredBolds = boldFilter.filterBolds(query, bingBoldsAndRankNS, resultsCount);
            rankToIdNS = urlsToRankID(urls);
            rankToBoldsNS = new HashMap<>();
            SmaphUtils.mapRankToBoldsLC(bingBoldsAndRankNS, rankToBoldsNS, null);

            if (debugger != null) {
                debugger.addBoldPositionEditDistance(query, bingBoldsAndRankNS);
                debugger.addSnippets(query, snippetsToBolds);
                debugger.addBoldFilterOutput(query, filteredBolds);
                debugger.addSource2SearchResult(query, rankToIdNS, urls);
                debugger.addBingResponseNormalSearch(query, resCountAndWebTotalNS.getRight());
            }
        }

        /** Do the WikipediaSearch on bing. */
        List<String> wikiSearchUrls = new Vector<>();
        List<Pair<String, Integer>> bingBoldsAndRankWS = new Vector<>();
        HashMap<String, Pair<Integer, Integer>> annTitlesToIdAndRankWS = null;
        Triple<Integer, Double, JSONObject> resCountAndWebTotalWS = null;
        HashMap<Integer, HashSet<String>> rankToBoldsWS = null;
        double webTotalWS = Double.NaN;
        if (includeSourceWikiSearch | includeSourceNormalSearch) {
            resCountAndWebTotalWS = takeBingData(query, bingBoldsAndRankWS, wikiSearchUrls, null, null,
                    topKWikiSearch, true);
            webTotalWS = resCountAndWebTotalWS.getMiddle();
            HashMap<Integer, Integer> rankToIdWikiSearch = urlsToRankID(wikiSearchUrls);
            rankToBoldsWS = new HashMap<>();
            SmaphUtils.mapRankToBoldsLC(bingBoldsAndRankWS, rankToBoldsWS, null);
            if (debugger != null) {
                debugger.addSource3SearchResult(query, rankToIdWikiSearch, wikiSearchUrls);
                debugger.addBingResponseWikiSearch(query, resCountAndWebTotalWS.getRight());

            }
            annTitlesToIdAndRankWS = adjustTitles(rankToIdWikiSearch);
        }

        /** Do the RelatedSearch on bing */
        String relatedSearch = null;
        List<String> relatedSearchUrls = null;
        List<Pair<String, Integer>> bingBoldsAndRankRS = null;
        HashMap<Integer, Integer> rankToIdRelatedSearch = null;
        HashMap<String, Pair<Integer, Integer>> annTitlesToIdAndRankRS = null;
        double webTotalRelatedSearch = Double.NaN;
        HashMap<Integer, HashSet<String>> rankToBoldsRS = null;
        if (includeSourceRelatedSearch) {
            relatedSearch = getRelatedSearch(relatedSearchRes, query);
            relatedSearchUrls = new Vector<>();
            bingBoldsAndRankRS = new Vector<>();
            Triple<Integer, Double, JSONObject> resCountAndWebTotalRS = takeBingData(query, bingBoldsAndRankRS,
                    relatedSearchUrls, null, null, topKRelatedSearch, false);
            webTotalRelatedSearch = resCountAndWebTotalRS.getMiddle();
            rankToIdRelatedSearch = urlsToRankID(relatedSearchUrls);
            annTitlesToIdAndRankRS = adjustTitles(rankToIdRelatedSearch);
            rankToBoldsRS = new HashMap<>();
            SmaphUtils.mapRankToBoldsLC(bingBoldsAndRankRS, rankToBoldsRS, null);

        }

        /** Annotate bolds on the annotator */
        Pair<HashMap<String, HashMap<String, Double>>, HashMap<String, Annotation>> infoAndAnnotations = null;
        HashMap<String, Annotation> spotToAnnotation = null;
        HashMap<String, HashMap<String, Double>> additionalInfo = null;
        Pair<String, HashSet<Mention>> annInput = null;
        if (includeSourceAnnotator) {
            annInput = concatenateBolds(filteredBolds);
            infoAndAnnotations = disambiguateBolds(annInput.first, annInput.second);
            spotToAnnotation = infoAndAnnotations.second;
            additionalInfo = infoAndAnnotations.first;

            if (debugger != null)
                debugger.addReturnedAnnotation(query, spotToAnnotation);
        }

        HashMap<String[], Tag> boldsToAcceptedEntity = new HashMap<>();

        // Filter and add annotations found by the disambiguator
        if (includeSourceAnnotator) {
            for (String bold : filteredBolds) {
                if (spotToAnnotation.containsKey(bold)) {
                    Annotation ann = spotToAnnotation.get(bold);
                    HashMap<String, Double> ESFeatures = generateEntitySelectionFeaturesAnnotator(query,
                            resultsCount, ann, annInput, bingBoldsAndRankNS, additionalInfo);
                    boolean accept = entityFilter.filterEntity(ESFeatures);
                    if (accept)
                        boldsToAcceptedEntity.put(new String[] { bold }, new Tag(ann.getConcept()));
                    if (debugger != null) {
                        HashSet<String> bolds = new HashSet<>();
                        bolds.add(bold);
                        debugger.addQueryCandidateBolds(query, "Source 1", ann.getConcept(), bolds);
                        debugger.addEntityFeaturesS1(query, bold, ann.getConcept(), ESFeatures, accept);
                        if (accept)
                            debugger.addResult(query, ann.getConcept());
                    }
                }
            }
        }

        // Filter and add entities found in the normal search
        if (includeSourceNormalSearch) {
            for (int rank : rankToIdNS.keySet()) {
                int wid = rankToIdNS.get(rank);
                HashMap<String, Double> ESFeatures = generateEntitySelectionFeaturesSearch(query, wid, rank,
                        webTotalNS, webTotalWS, bingBoldsAndRankNS, 2);
                HashSet<String> bolds = rankToBoldsNS.get(rank);
                boolean accept = entityFilter.filterEntity(ESFeatures);
                if (accept)
                    boldsToAcceptedEntity.put(bolds.toArray(new String[] {}), new Tag(wid));
                if (debugger != null) {
                    debugger.addQueryCandidateBolds(query, "Source 2", wid, bolds);
                    debugger.addEntityFeaturesS2(query, wid, ESFeatures, accept);
                    if (accept)
                        debugger.addResult(query, wid);
                }
            }
        }

        // Filter and add entities found in the WikipediaSearch
        if (includeSourceWikiSearch) {
            for (String annotatedTitleWS : annTitlesToIdAndRankWS.keySet()) {
                int wid = annTitlesToIdAndRankWS.get(annotatedTitleWS).first;
                int rank = annTitlesToIdAndRankWS.get(annotatedTitleWS).second;
                HashMap<String, Double> ESFeatures = generateEntitySelectionFeaturesSearch(query, wid, rank,
                        webTotalNS, webTotalWS, bingBoldsAndRankWS, 3);

                HashSet<String> bolds = rankToBoldsWS.get(rank);
                boolean accept = entityFilter.filterEntity(ESFeatures);
                if (accept)
                    boldsToAcceptedEntity.put(bolds.toArray(new String[] {}), new Tag(wid));
                if (debugger != null) {
                    debugger.addQueryCandidateBolds(query, "Source 3", wid, bolds);
                    debugger.addEntityFeaturesS3(query, wid, ESFeatures, accept);
                    if (accept)
                        debugger.addResult(query, wid);

                }
            }
        }

        // Filter and add entities found in the RelatedSearch
        if (includeSourceRelatedSearch) {
            for (String annotatedTitleRS : annTitlesToIdAndRankRS.keySet()) {
                int wid = annTitlesToIdAndRankRS.get(annotatedTitleRS).first;
                int rank = annTitlesToIdAndRankRS.get(annotatedTitleRS).second;
                HashMap<String, Double> ESFeatures = generateEntitySelectionFeaturesSearch(relatedSearch, wid,
                        rank, webTotalNS, webTotalRelatedSearch, bingBoldsAndRankRS, 5);

                HashSet<String> bolds = rankToBoldsRS.get(rank);
                boolean accept = entityFilter.filterEntity(ESFeatures);
                if (accept)
                    boldsToAcceptedEntity.put(bolds.toArray(new String[] {}), new Tag(wid));
            }
        }

        /** Link entities back to query mentions */

        annotations = linkBack.linkBack(query, boldsToAcceptedEntity);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    SmaphAnnotatorDebugger.out.printf("*** END :%s ***%n", query);

    return annotations;

}

From source file:org.mule.devkit.doclet.ClassInfo.java

public ClassInfo[] getInterfaces() {
    if (mInterfaces == null) {
        if (checkLevel()) {
            HashSet<ClassInfo> interfaces = new HashSet<ClassInfo>();
            ClassInfo superclass = mRealSuperclass;
            while (superclass != null && !superclass.checkLevel()) {
                gatherHiddenInterfaces(superclass, interfaces);
                superclass = superclass.mRealSuperclass;
            }/*w w  w . j av a 2s.  co m*/
            gatherHiddenInterfaces(this, interfaces);
            mInterfaces = interfaces.toArray(new ClassInfo[interfaces.size()]);
        } else {
            // put something here in case someone uses it
            mInterfaces = new ClassInfo[mRealInterfaces.size()];
            mRealInterfaces.toArray(mInterfaces);
        }
        Arrays.sort(mInterfaces, ClassInfo.qualifiedComparator);
    }
    return mInterfaces;
}