Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

In this page you can find the example usage for java.util ArrayList remove.

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java

private ArrayList<FOV> generateSpiral1(int noFOV, String wellString) {

    // cover whole well in a rectangle; remove those outwith well bounds;
    // finally trim to #fov. Deals with asymmetric FOV
    ArrayList<FOV> spiralFOVs = new ArrayList<FOV>();
    FOV fov = new FOV(wellString, pp_, 0);
    double[] centrexy = { fov.getX(), fov.getY() };
    //        double[] DXY = {sap_.getFLIMFOVSize()[0], sap_.getFLIMFOVSize()[1]};
    double[] DXY = { parent_.globalFOVset_.getWidth_(), parent_.globalFOVset_.getHeight_() };
    int[][] dir = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
    double[] dxy = new double[2];
    int stepsInCurrentDir;

    spiralFOVs.add(fov);/*from   w  w  w.  j  a  va 2 s .c  o m*/
    int fovind = 1;
    int dirind = 0;
    while (fovind < noFOV & dirind < 100) { // just in case we have a runaway case...

        stepsInCurrentDir = (int) Math.ceil((double) (dirind) / 2);

        dxy[0] = dir[dirind % 4][0] * DXY[0];
        dxy[1] = dir[dirind % 4][1] * DXY[1];
        for (int j = 0; j < stepsInCurrentDir; j++) {
            centrexy[0] += dxy[0];
            centrexy[1] += dxy[1];
            fov = new FOV(centrexy[0], centrexy[1], 0, wellString, pp_);
            if (fov.isValid()) {
                spiralFOVs.add(fov);
                fovind++;
            }
        }
        dirind++;
        //    System.out.print("Dirind = " + dirind + "\n");
    }
    // trim, a bit hacky but works
    int currsize = spiralFOVs.size();
    for (int j = currsize - 1; j > noFOV - 1; j--) {
        spiralFOVs.remove(j);
    }
    return spiralFOVs;
}

From source file:de.sourcestream.movieDB.controller.CastDetails.java

/**
 * This method calculates what icons do we have.
 *
 * @param homeIcon    the first icon//from   ww  w  .  j  a  va2s  .  c  o m
 * @param galleryIcon the second icon
 */
public void adjustIconsPos(CircledImageView homeIcon, CircledImageView galleryIcon) {
    int iconCount[] = { homeIconCheck, galleryIconCheck };
    ArrayList<CircledImageView> circledImageViews = new ArrayList<>();
    circledImageViews.add(homeIcon);
    circledImageViews.add(galleryIcon);

    for (int i = 0; i < iconCount.length; i++) {
        if (iconCount[i] == 1)
            circledImageViews.get(circledImageViews.size() - 1).setVisibility(View.INVISIBLE);
        else {
            CircledImageView temp = circledImageViews.get(0);
            switch (i) {
            case 0:
                temp.setOnClickListener(onHomeIconClick);
                temp.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.ic_home_white_24dp));
                temp.setTag(homeIconUrl);
                break;
            case 1:
                temp.setOnClickListener(onGalleryIconClick);
                temp.setImageDrawable(
                        ContextCompat.getDrawable(activity, R.drawable.ic_photo_camera_white_24dp));
                break;

            }
            circledImageViews.remove(0);
        }

    }

}

From source file:Game.Engine.java

@Override
public void invalidated(Observable observable) {
    if (observable instanceof InteractionCase) {
        InteractionCase invalidated = (InteractionCase) observable;
        // Check interaction-flow! interaction closes, it gets notified. 
        JSONObject finishbehaviour = invalidated.getFinishBehaviour();

        ArrayList<Card> selectedCardsFromThisInteractionCase = invalidated.getSelected();
        ArrayList<String> selectedIdentifiersFromThisInteractionCase = invalidated.getIds();
        ArrayList<String> selectedCardNamesFromThisInteractionCase = new ArrayList<>();

        for (int index = 0; index < selectedIdentifiersFromThisInteractionCase.size(); index++) {
            String thisIdentifier = selectedIdentifiersFromThisInteractionCase.get(index);
            // Check if the identifier's first character is a digit.
            // If this is the case, it means the identifier is long-parseable
            // If the identifier is a long, it comes out of the hand of the victim.
            // Identifiers from victims hands get "other" notitifier in front. 
            if (Character.isDigit(thisIdentifier.charAt(0))) {
                selectedIdentifiersFromThisInteractionCase.remove(index);
                selectedIdentifiersFromThisInteractionCase.add(index, "other_" + thisIdentifier);
            }//from  w  w  w.  jav  a2 s .  co  m
            Card linkedToThisIdentifier = selectedCardsFromThisInteractionCase.get(index);
            selectedCardNamesFromThisInteractionCase.add(linkedToThisIdentifier.name);

        }

        // Handle behaviour: 

        JSONObject handlebehaviour = invalidated.getFinishBehaviour();

        if (handlebehaviour.getString("showToInitiator").equals(((Boolean) true).toString())) {
            if (invalidated.getInitiator().getFutureInteraction() == null) {
                System.out.println(
                        "---> Tried to show interactionresult to initiator, but his futureInteraction == null");
            } else {
                // Switch victim and initiator positions in indexFor function, since we are swicthing roles in the interaction.
                System.out.println("---> showing interactinoresult to initiator, containing "
                        + selectedCardNamesFromThisInteractionCase.size() + " entries with ids:");
                ArrayList<String> copy_for_injection = new ArrayList<>();
                for (String s : selectedIdentifiersFromThisInteractionCase)
                    copy_for_injection
                            .add(s + "_" + myIndexFor(invalidated.getVictim(), invalidated.getInitiator()));
                selectedIdentifiersFromThisInteractionCase = copy_for_injection;
                for (String s : selectedIdentifiersFromThisInteractionCase)
                    System.out.println(s);
                invalidated.getInitiator().getFutureInteraction()
                        .setStartBehaviour(JSONUtilities.JSON.update_client_confirmation_model(
                                myIndexFor(invalidated.getVictim(), invalidated.getInitiator()),
                                JSONUtilities.JSON.make_player_public_stats(invalidated.getVictim(),
                                        server.getClient(invalidated.getVictim().getSession()).getNickname(),
                                        copy_for_injection, selectedCardNamesFromThisInteractionCase,
                                        (selectedCardNamesFromThisInteractionCase.isEmpty())),
                                invalidated.getInitiator().getFutureInteraction().getStartBehaviour()));
                for (int ix = 0; ix < invalidated.selectedSpecials.size(); ix++) {
                    Card c = invalidated.selectedSpecials.get(ix);
                    String id = copy_for_injection.get(ix) + "_" + ix;
                    invalidated.getInitiator().getFutureInteraction().preloadedCards.add(c);
                    invalidated.getInitiator().getFutureInteraction().fromPreviousInteraction.put(id, c);
                }

            }
        }

        if (handlebehaviour.getString("moveSomething").equals(((Boolean) true).toString())) {
            String from = handlebehaviour.getString("pullFrom");
            String to = handlebehaviour.getString("addTo");
            String foreach = handlebehaviour.getString("iterative_action");

            System.out.println("handling a pull from " + from + " to " + to + " with foreach " + foreach);
            if (from.equals("hand_victim") && to.equals("top_of_deck_victim")) {
                for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                    System.out.println("Identifier is " + selectedIdentifiersFromThisInteractionCase.get(ix));
                    if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("other")) {
                        Long victimCardID = Long
                                .parseLong(selectedIdentifiersFromThisInteractionCase.get(ix).split("_")[1]);
                        Card lost = invalidated.getVictim()
                                .loseCard(selectedCardNamesFromThisInteractionCase.get(ix), victimCardID);
                        invalidated.getVictim().deck.addTopOfDeck(lost);
                        server.sendOne(
                                JSONUtilities.JSON.make_client_lose(lost.getName(), victimCardID.toString()),
                                invalidated.getVictim().getSession());
                        make_client_update_deck(invalidated.getVictim());
                        if (!foreach.equals("none")) {
                            System.out.println("uncatched foreach");
                        }
                    }
                }
            } else if (from.equals("none") && (to.equals("hand_victim"))) {
                for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                    if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("other")) {
                        Card thecard = selectedCardsFromThisInteractionCase.get(ix);
                        invalidated.getVictim().hand.add(thecard);

                        JSONObject obj = JSONUtilities.JSON.make_client_print(
                                "Adventurer gave you a : " + selectedCardNamesFromThisInteractionCase.get(ix));
                        server.getClient(invalidated.getVictim().getSession()).write(obj);

                        JSONObject act = JSONUtilities.JSON
                                .make_client_gain(selectedCardNamesFromThisInteractionCase.get(ix));
                        server.getClient(invalidated.getVictim().getSession()).write(act);
                        make_client_update_deck(invalidated.getVictim());
                        make_client_update_discardpile(invalidated.getVictim());
                    }
                }
            } else if (from.equals("hand_victim") && (to.equals("discardpile_victim"))) {
                for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                    if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("other")) {
                        System.out.println("Discarding from hand: id "
                                + selectedIdentifiersFromThisInteractionCase.get(ix));
                        Long victimCardID = Long
                                .parseLong(selectedIdentifiersFromThisInteractionCase.get(ix).split("_")[1]);
                        Card lost = invalidated.getVictim()
                                .loseCard(selectedCardNamesFromThisInteractionCase.get(ix), victimCardID);
                        invalidated.getVictim().deck.used.add(lost);
                        server.sendOne(
                                JSONUtilities.JSON.make_client_lose(lost.getName(), victimCardID.toString()),
                                invalidated.getVictim().getSession());
                        if (foreach.equals("draw_card")) {
                            // This is the cellar branch of this function
                            give_card_to_player_hand(invalidated.getVictim().getSession());

                        } else if (foreach.equals("none")) {
                            // This is the militia branch of this function
                            System.out.println("militiabranch taken");
                        }
                        make_client_update_deck(invalidated.getVictim());
                        make_client_update_discardpile(invalidated.getVictim());
                    }
                }
            } else if (from.equals("deck_victim") && (to.equals("discardpile_victim"))) {
                if (foreach.equals("until_deck_discarded")) {
                    // Its (probably) a chancellor deckdiscard!
                    if (selectedCardNamesFromThisInteractionCase.isEmpty()) {
                        // Do nothing! The chancellor was not selected, if it even is a chancellor.

                    } else {
                        if (selectedCardNamesFromThisInteractionCase.get(0).equals("chancellor")) {
                            invalidated.getVictim().deck.reshuffle();
                            make_client_update_deck(invalidated.getVictim());
                            make_client_update_discardpile(invalidated.getVictim());
                            server.sendAll(JSONUtilities.JSON
                                    .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                            + " reshuffeled his/her deck with a chancellor."));
                        } else {
                            System.out.println(
                                    "Non implemented branch of behaviour tree was reached, should not happen");
                        }
                    }
                }
            } else if (from.equals("hand_victim") && (to.equals("trashpile"))) {
                if (foreach.equals("none")) {
                    for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                        if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("other")) {
                            System.out.println(
                                    "Chappeling id " + selectedIdentifiersFromThisInteractionCase.get(ix));
                            Long victimCardID = Long.parseLong(
                                    selectedIdentifiersFromThisInteractionCase.get(ix).split("_")[1]);
                            Card lost = invalidated.getVictim()
                                    .loseCard(selectedCardNamesFromThisInteractionCase.get(ix), victimCardID);
                            env.trashpile.add(lost);
                            server.sendOne(JSONUtilities.JSON.make_client_lose(lost.getName(),
                                    victimCardID.toString()), invalidated.getVictim().getSession());
                            server.sendAll(JSONUtilities.JSON
                                    .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                            + " trashed a " + lost.getName()));
                        }
                    }
                    server.sendAll(JSONUtilities.JSON.make_client_update_environment("trashpile",
                            env.trashpile.size()));
                    server.sendAll(JSONUtilities.JSON
                            .make_client_update_trashpile(env.trashpile.get(env.trashpile.size() - 1)));
                } else if (foreach.equals("gain_treasure_costing_up_to_3_more")) {
                    // Its a mine
                    for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                        if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("other")) {
                            System.out.println(
                                    "Trashing id " + selectedIdentifiersFromThisInteractionCase.get(ix));
                            Long victimCardID = Long.parseLong(
                                    selectedIdentifiersFromThisInteractionCase.get(ix).split("_")[1]);
                            Card lost = invalidated.getVictim()
                                    .loseCard(selectedCardNamesFromThisInteractionCase.get(ix), victimCardID);
                            env.trashpile.add(lost);
                            ArrayList<String> identifiers = new ArrayList<>();
                            ArrayList<String> cardnames = new ArrayList<>();
                            for (Card c : env.getAllBuyablesAsCards(lost.getCost() + 3)) {
                                if (c instanceof TreasureCard) {
                                    invalidated.getVictim().getFutureInteraction().preloadedCards.add(c);
                                    invalidated.getVictim().getFutureInteraction().allowedIds
                                            .add("environment");
                                    invalidated.getVictim().getFutureInteraction().enableEnvTreasure();
                                }
                            }
                            invalidated.getVictim().getFutureInteraction()
                                    .setStartBehaviour(JSONUtilities.JSON.make_client_confirmation_model_mine(
                                            invalidated.getVictim(), invalidated.getInitiator(),
                                            invalidated.getVictim().getFutureInteraction()));
                            invalidated.getVictim().getFutureInteraction().setMaxCost(lost.getCost() + 3);
                            invalidated.getVictim().getFutureInteraction().setMinCost(0);
                            invalidated.getVictim().getFutureInteraction().setMinAmount(1);
                            invalidated.getVictim().getFutureInteraction().setMaxAmount(1);

                            //invalidated.getVictim().getFutureInteraction().setStartBehaviour(JSONUtilities.JSON.update_client_confirmation_model(0, JSONUtilities.JSON.make_player_public_stats( invalidated.getVictim(),server.getClient(invalidated.getVictim().getSession()).getNickname(), identifiers, cardnames, false), invalidated.getInitiator().getFutureInteraction().getStartBehaviour()));

                            server.sendOne(JSONUtilities.JSON.make_client_lose(lost.getName(),
                                    victimCardID.toString()), invalidated.getVictim().getSession());
                            server.sendAll(JSONUtilities.JSON
                                    .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                            + " trashed a " + lost.getName()));

                        }
                    }
                    server.sendAll(JSONUtilities.JSON.make_client_update_environment("trashpile",
                            env.trashpile.size()));
                    server.sendAll(JSONUtilities.JSON
                            .make_client_update_trashpile(env.trashpile.get(env.trashpile.size() - 1)));

                } else if (foreach.equals("gain3moneythisturn")) {
                    Long victimCardID = Long
                            .parseLong(selectedIdentifiersFromThisInteractionCase.get(0).split("_")[1]);
                    Card lost = invalidated.getVictim()
                            .loseCard(selectedCardNamesFromThisInteractionCase.get(0), victimCardID);
                    env.trashpile.add(lost);
                    this.money += 3;
                    server.sendOne(JSONUtilities.JSON.make_client_lose(lost.getName(), victimCardID.toString()),
                            invalidated.getVictim().getSession());
                    server.sendAll(JSONUtilities.JSON.make_client_update_environment("trashpile",
                            env.trashpile.size()));
                    server.sendAll(JSONUtilities.JSON
                            .make_client_update_trashpile(env.trashpile.get(env.trashpile.size() - 1)));
                    server.sendAll(JSONUtilities.JSON.make_client_turninfo(actions, purchases, money));
                    server.sendAll(JSONUtilities.JSON
                            .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                    + " trashed a " + lost.getName()));

                } else if (foreach.equals("gain_anything_costing_up_to_2_more")) {
                    // Its a remodel
                    for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                        if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("other")) {
                            System.out.println(
                                    "Trashing id " + selectedIdentifiersFromThisInteractionCase.get(ix));
                            Long victimCardID = Long.parseLong(
                                    selectedIdentifiersFromThisInteractionCase.get(ix).split("_")[1]);
                            Card lost = invalidated.getVictim()
                                    .loseCard(selectedCardNamesFromThisInteractionCase.get(ix), victimCardID);
                            env.trashpile.add(lost);
                            ArrayList<String> identifiers = new ArrayList<>();
                            ArrayList<String> cardnames = new ArrayList<>();
                            for (Card c : env.getAllBuyablesAsCards(lost.getCost() + 2)) {
                                invalidated.getVictim().getFutureInteraction().preloadedCards.add(c);
                                invalidated.getVictim().getFutureInteraction().allowedIds.add("environment");
                                invalidated.getVictim().getFutureInteraction().enable_environment();
                            }
                            invalidated.getVictim().getFutureInteraction().setStartBehaviour(
                                    JSONUtilities.JSON.make_client_confirmation_model_remodel(
                                            invalidated.getVictim(), invalidated.getInitiator(),
                                            invalidated.getVictim().getFutureInteraction()));
                            invalidated.getVictim().getFutureInteraction().setMaxCost(lost.getCost() + 2);
                            invalidated.getVictim().getFutureInteraction().setMinCost(0);
                            invalidated.getVictim().getFutureInteraction().setMinAmount(1);
                            invalidated.getVictim().getFutureInteraction().setMaxAmount(1);

                            //invalidated.getVictim().getFutureInteraction().setStartBehaviour(JSONUtilities.JSON.update_client_confirmation_model(0, JSONUtilities.JSON.make_player_public_stats( invalidated.getVictim(),server.getClient(invalidated.getVictim().getSession()).getNickname(), identifiers, cardnames, false), invalidated.getInitiator().getFutureInteraction().getStartBehaviour()));

                            server.sendOne(JSONUtilities.JSON.make_client_lose(lost.getName(),
                                    victimCardID.toString()), invalidated.getVictim().getSession());
                            server.sendAll(JSONUtilities.JSON
                                    .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                            + " trashed a " + lost.getName()));

                        }
                    }
                    server.sendAll(JSONUtilities.JSON.make_client_update_environment("trashpile",
                            env.trashpile.size()));
                    server.sendAll(JSONUtilities.JSON
                            .make_client_update_trashpile(env.trashpile.get(env.trashpile.size() - 1)));

                }
            } else if (from.equals("environment") && to.equals("discardpile_victim")) {
                // Its probably a feast, or some feast-ish card
                if (foreach.equals("trash_my_tablecard")) {
                    for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                        if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("env")) {
                            System.out.println(
                                    "Feast used on " + selectedCardNamesFromThisInteractionCase.get(ix));
                            Card bought = env.environment_buy(selectedCardNamesFromThisInteractionCase.get(ix));
                            invalidated.getVictim().deck.used.add(bought);

                            // Trash the feast from the table. 
                            Card feasttrash = env.tablecards.get(env.tablecards.size() - 1);
                            env.tablecards.remove(env.tablecards.size() - 1);
                            env.trashpile.add(feasttrash);
                            //todododododod                // Update clients for tablecards and trashpile!!! todo

                            make_client_update_discardpile(invalidated.getVictim());
                            make_clients_update_environment(bought.getName());
                            make_clients_update_environment("trashpile");

                            server.sendAll(JSONUtilities.JSON
                                    .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                            + " gained a " + bought.getName() + " with feast."));

                        }
                    }
                } else if (foreach.equals("none")) {
                    for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                        if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("env")) {
                            System.out.println("Remodel/workshop used on "
                                    + selectedCardNamesFromThisInteractionCase.get(ix));
                            Card bought = env.environment_buy(selectedCardNamesFromThisInteractionCase.get(ix));
                            invalidated.getVictim().deck.used.add(bought);

                            make_client_update_discardpile(invalidated.getVictim());
                            make_clients_update_environment(bought.getName());

                            server.sendAll(JSONUtilities.JSON
                                    .make_client_print(server.getNickname(invalidated.getVictim().getSession())
                                            + " gained a " + bought.getName() + "."));

                        }
                    }
                }
            } else if (from.equals("environment") && (to.equals("hand_victim"))) {
                if (foreach.equals("none")) {
                    for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                        if (selectedIdentifiersFromThisInteractionCase.get(ix).startsWith("env")) {
                            Card gained = env.environment_buy(selectedCardNamesFromThisInteractionCase.get(ix));
                            invalidated.getVictim().hand.add(gained);
                            server.sendOne(JSONUtilities.JSON.make_client_gain(gained.getName()),
                                    invalidated.getVictim().getSession());
                            server.sendAll(JSONUtilities.JSON.make_client_update_environment(gained.getName(),
                                    env.environment_library.get(gained.getName()).size()));
                        }
                    }

                }
            } else if (from.equals("interaction") && (to.equals("hand_victim"))) {
                for (int ix = 0; ix < selectedIdentifiersFromThisInteractionCase.size(); ix++) {
                    Card thecard = selectedCardsFromThisInteractionCase.get(ix);
                    invalidated.getVictim().hand.add(thecard);

                    JSONObject obj = JSONUtilities.JSON.make_client_print(
                            "Library gave you a : " + selectedCardNamesFromThisInteractionCase.get(ix));
                    server.getClient(invalidated.getVictim().getSession()).write(obj);

                    JSONObject act = JSONUtilities.JSON
                            .make_client_gain(selectedCardNamesFromThisInteractionCase.get(ix));
                    server.getClient(invalidated.getVictim().getSession()).write(act);
                    make_client_update_deck(invalidated.getVictim());
                    make_client_update_discardpile(invalidated.getVictim());
                }
            } else if (from.equals("interaction") && (to.equals("throneroomqueue"))) {
                Card thecard = selectedCardsFromThisInteractionCase.get(0);
                env.throneRoomQueue.offer(thecard);
                env.throneRoomQueue.offer(thecard);
                invalidated.getVictim().loseCard(thecard.getName(),
                        Long.parseLong(selectedIdentifiersFromThisInteractionCase.get(0).split("_")[1]));
                env.tablecards.add(thecard);
                server.sendOne(
                        JSONUtilities.JSON.make_client_lose(thecard.getName(),
                                ((selectedIdentifiersFromThisInteractionCase.get(0).split("_")[1]))),
                        invalidated.getVictim().getSession());
                server.sendAll(JSONUtilities.JSON
                        .make_client_print(server.getNickname(invalidated.getVictim().getSession()) + " lost a "
                                + thecard.getName()));
                server.sendAll(JSONUtilities.JSON.make_client_refresh_tableview());

            } else if (from.equals("interaction") && (to.equals("top_deck_victim"))) {
                if (foreach.equals("if_selected_then_discardpile_victim")) {
                    HashMap<String, Card> mapping = new HashMap<>();
                    System.out.println("spying on " + invalidated.preloadedCards.size() + " cards");
                    System.out.println("however, there are " + invalidated.selectedSpecials.size()
                            + " selected specials.");
                    System.out.println("also " + invalidated.selectedIds.size() + " selected ids, and "
                            + invalidated.allowedIds.size() + " allowed ids");

                    // Allowed : other_2, other_3
                    // selectedIds : other_0_0, other_1_1 -> door naar volgende interactie
                    // preloadedCards : other_0, other_1 -> deze moeten eigenlijk de specials zijn
                    // selectedSpecials : other_0, other_1 -> preloadedcards moeten discarded worden op basis van

                    for (int ix = 0; ix < invalidated.preloadedCards.size(); ix++) {
                        if (ix >= invalidated.allowedIds.size())
                            continue;
                        if (ix >= players.keySet().size())
                            continue;
                        int indexforvictim = ix;
                        Player p = indexForMe(invalidated.getInitiator(), ix);
                        System.out
                                .println("got player " + server.getNickname(p.getSession()) + " from indexFor("
                                        + server.getNickname(invalidated.getInitiator().getSession()) + " , "
                                        + ix + ");");
                        String searchID = "other_" + indexforvictim;
                        boolean isSelected = false;
                        Card card = invalidated.preloadedCards.get(ix);
                        String theid = searchID;
                        for (int ixix = 0; ixix < invalidated.selectedIds.size(); ixix++) {
                            Card c = invalidated.selectedSpecials.get(ixix);
                            String id = invalidated.selectedIds.get(ixix);

                            if (id.startsWith(searchID)) {
                                // Card is selected
                                isSelected = true;
                                card = c;
                                invalidated.selectedSpecials.remove(ixix);
                                invalidated.selectedIds.remove(ixix);
                                break;
                            }
                        }

                        if (isSelected) {
                            p.deck.used.add(card);
                            System.out.println("ADDED " + card.getName() + " TO DISCARDPILE OF "
                                    + server.getNickname(p.getSession()));
                        } else {
                            p.deck.addTopOfDeck(card);
                            System.out.println("ADDED " + card.getName() + " TO TOP OF DECK OF "
                                    + server.getNickname(p.getSession()));
                        }

                        make_client_update_deck(p);
                        make_client_update_discardpile(p);

                    }
                }
            } else if (from.equals("interaction") && to.equals("discardpile_victim")) {
                if (foreach.equals("none")) {
                    // WITCH
                    System.out.println("Witching on " + invalidated.preloadedCards.size() + " cards");
                    System.out.println("however, there are " + invalidated.selectedSpecials.size()
                            + " selected specials.");
                    System.out.println("also " + invalidated.selectedIds.size() + " selected ids, and "
                            + invalidated.allowedIds.size() + " allowed ids");
                    ArrayList<String> newSelectedIds = new ArrayList<>();
                    for (int ix = 0; ix < invalidated.selectedIds.size(); ix++) {
                        Card c = invalidated.selectedSpecials.get(ix);
                        String id = invalidated.selectedIds.get(ix);
                        invalidated.getVictim().deck.used.add(c);
                        make_client_update_discardpile(invalidated.getVictim());
                    }
                    make_clients_update_cursepile();

                } else if (foreach.equals("if_not_selected")) {
                    HashMap<String, Card> mapping = new HashMap<>();
                    System.out.println("thieving on " + invalidated.preloadedCards.size() + " cards");
                    System.out.println("however, there are " + invalidated.selectedSpecials.size()
                            + " selected specials.");
                    System.out.println("also " + invalidated.selectedIds.size() + " selected ids, and "
                            + invalidated.allowedIds.size() + " allowed ids");
                    ArrayList<String> newSelectedIds = new ArrayList<>();

                    for (String s : invalidated.selectedIds)
                        System.out.println("selected id : " + s);
                    for (Card c : invalidated.selectedSpecials)
                        System.out.println("selected card : " + c.getName());
                    for (Card c : invalidated.preloadedCards)
                        System.out.println("preloadedcard name : " + c.getName());
                    for (String s : invalidated.allowedIds)
                        System.out.println("allowed id : " + s);
                    for (String s : invalidated.fromPreviousInteraction.keySet())
                        System.out.println("fromprevious : " + s + " - "
                                + invalidated.fromPreviousInteraction.get(s).getName());
                    HashMap<String, Card> to_next_interaction = new HashMap<>();
                    for (String previd : invalidated.fromPreviousInteraction.keySet()) {
                        Card linked = invalidated.fromPreviousInteraction.get(previd);
                        int indexlinked = Integer.parseInt(previd.split("_")[1]);
                        Player victimlinked = indexForMe(invalidated.getInitiator(), indexlinked);
                        boolean isSelected = false;
                        for (int ix = 0; ix < invalidated.selectedSpecials.size(); ix++) {
                            Card selected = invalidated.selectedSpecials.get(ix);
                            String selectid = invalidated.selectedIds.get(ix);
                            int selectedindexlinked = Integer.parseInt(selectid.split("_")[1]);
                            Player victimselectedlinked = indexForMe(invalidated.getInitiator(),
                                    selectedindexlinked);
                            if (indexlinked == selectedindexlinked) {
                                if (linked.getName().equals(selected.getName())) {
                                    // linked is selected from id victimlinked
                                    isSelected = true;
                                    invalidated.selectedSpecials.remove(ix);
                                    invalidated.selectedIds.remove(ix);
                                    break;
                                }
                            }

                        }
                        if (isSelected) {

                            to_next_interaction.put(previd, linked);
                        } else {
                            victimlinked.deck.used.add(linked);
                            make_client_update_discardpile(victimlinked);
                        }
                    }
                    invalidated.selectedIds.clear();
                    invalidated.selectedSpecials.clear();
                    for (String s : to_next_interaction.keySet()) {
                        invalidated.selectedIds.add(s);
                        invalidated.selectedSpecials.add(to_next_interaction.get(s));
                    }
                }
            } else if (from.equals("interaction") && (to.equals("trashpile"))) {
                if (foreach.equals("if_selected_then_gain")) {
                    System.out.println("thieving on " + invalidated.preloadedCards.size() + " cards");
                    System.out.println("however, there are " + invalidated.selectedSpecials.size()
                            + " selected specials.");
                    System.out.println("also " + invalidated.selectedIds.size() + " selected ids, and "
                            + invalidated.allowedIds.size() + " allowed ids");

                    for (String previd : invalidated.fromPreviousInteraction.keySet()) {
                        Card linked = invalidated.fromPreviousInteraction.get(previd);
                        int indexlinked = Integer.parseInt(previd.split("_")[1]);
                        Player victimlinked = indexForMe(invalidated.getInitiator(), indexlinked);

                        for (int ix = 0; ix < invalidated.selectedSpecials.size(); ix++) {
                            Card selected = invalidated.selectedSpecials.get(ix);
                            String selectid = invalidated.selectedIds.get(ix);
                            int selectedindexlinked = Integer.parseInt(selectid.split("_")[0]);
                            Player victimselectedlinked = indexForMe(invalidated.getInitiator(),
                                    selectedindexlinked);
                            if (indexlinked == selectedindexlinked) {
                                if (linked.getName().equals(selected.getName())) {
                                    // linked is selected from id victimlinked
                                }
                            }
                        }
                    }

                    ArrayList<String> selectedIdReal = new ArrayList<>();
                    for (String s : invalidated.selectedIds) {
                        System.out.println("selectedid : " + s);
                        selectedIdReal.add(s.split("_")[0] + "_" + s.split("_")[1]);
                    }
                    invalidated.selectedIds = selectedIdReal;
                    // IDCA IS UNIQUE
                    ArrayList<String> notselectedcardids = new ArrayList<>();
                    ArrayList<Card> notselectedcards = new ArrayList<>();

                    for (int ix = 0; ix < invalidated.preloadedCards.size(); ix++) {
                        Card ca = invalidated.preloadedCards.get(ix);
                        if (ix >= invalidated.allowedIds.size())
                            continue;
                        String idca = invalidated.allowedIds.get(ix);
                        boolean isselected = false;
                        for (int ixi = 0; ixi < invalidated.selectedIds.size(); ixi++) {
                            String idselected = invalidated.selectedIds.get(ixi);
                            if (idselected.equals(idca)) {
                                isselected = true;
                                break;
                            }
                        }
                        if (!isselected) {
                            notselectedcardids.add(idca);
                            notselectedcards.add(ca);
                        }
                    }
                    for (int ix = 0; ix < notselectedcards.size(); ix++) {
                        Card notselectedcard = notselectedcards.get(ix);
                        String notselectedcardid = notselectedcardids.get(ix);
                        String indexforvictim = notselectedcardid.split("_")[1];
                        Player victim = indexForMe(invalidated.getInitiator(),
                                Integer.parseInt(indexforvictim));
                        env.trashpile.add(notselectedcard);
                        make_clients_update_environment("trashpile");
                        System.out.println("trashed a " + notselectedcard.getName());
                    }

                    for (int ix = 0; ix < invalidated.selectedSpecials.size(); ix++) {
                        Card selectedcard = invalidated.selectedSpecials.get(ix);
                        String selectedcardid = invalidated.selectedIds.get(ix);
                        String indexforvictim = selectedcardid.split("_")[1];
                        Player victim = invalidated.getInitiator();
                        victim.deck.used.add(selectedcard);
                        make_client_update_discardpile(victim);
                        System.out.println("discarded a " + selectedcard.getName() + " to player["
                                + victim.getSession() + "] discardpile");
                    }
                }
            }
            // MoveSomething currently moves everything. 

            // hand_victim
            // top_of_deck_victim

        }

        boolean allDone = true;
        for (Player p : players.values()) {
            if ((p.getCurrentInteraction() != null) && (!p.getCurrentInteraction().isConfirmed()))
                allDone = false;
        }

        if (allDone) {
            // Check if initiator needs another interaction!
            // If not, check if he has other actions. Because if not, enterBuyPhase. 
            System.out.println("Flushing interactioncases to next stage");

            for (Player p : players.values()) {
                p.setInteraction(null);
            }
            // Not now, to test flow. 
            boolean futures = false;
            for (Player p : players.values()) {
                if (p.getFutureInteraction() != null)
                    futures = true;
                if (p.hasIterativeInteractionFactory())
                    futures = true;
            }
            System.out.println("Found a future!");
            // Flush futures to current if there are any, and send them.
            if (futures) {
                for (Player p : players.values()) {
                    if (p.getFutureInteraction() == null) {
                        if (!p.hasIterativeInteractionFactory()) {
                            // this player has no iterative interaction factory
                        } else {
                            p.setInteraction(p.getIterativeInteraction(invalidated, env));
                            p.getCurrentInteraction().addListener(this);
                            server.sendOne(p.getCurrentInteraction().getStartBehaviour(), p.getSession());
                        }
                    } else {
                        p.setInteraction(p.getFutureInteraction());
                        p.setFutureInteraction(null);
                        if (p.getCurrentInteraction() != null) {
                            p.getCurrentInteraction().addListener(this);
                            server.sendOne(p.getCurrentInteraction().getStartBehaviour(), p.getSession());
                        }
                    }
                }
            } else {
                interactionmode = false;

                if (!env.throneRoomQueue.isEmpty()) {
                    handleAction(env.throneRoomQueue.poll(), players.get(playerOrder.get(current_turn)));
                } else if (!invalidated.getInitiator().hasActionCard() || this.actions == 0)
                    enterBuyPhase();
                else {
                    highlight_actions(players.get(playerOrder.get(current_turn)));
                }
            }

        }
        // All interactions closed? Make an initiator interactioncase maybe?
        // Check finishbehaviour!
    }
}

From source file:com.anjalimacwan.fragment.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else//w  ww.j  a v  a 2s.  c  o m
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final ArrayList<String> cab = new ArrayList<>(numOfNotes);

        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                // Respond to clicks on the actions in the CAB
                switch (item.getItemId()) {
                case R.id.action_export:
                    mode.finish(); // Action picked, so close the CAB
                    listener.exportNote(cab.toArray());
                    return true;
                case R.id.action_delete:
                    mode.finish(); // Action picked, so close the CAB
                    listener.deleteNote(cab.toArray());
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                listener.hideFab();

                // Inflate the menu for the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_menu, menu);

                // Clear any old values from cab array
                cab.clear();

                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                listener.showFab();
            }

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Add/remove filenames to cab array as they are checked/unchecked
                if (checked) {
                    if (sortBy.equals("date"))
                        cab.add(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.add(finalListByName[position]);
                } else {
                    if (sortBy.equals("date"))
                        cab.remove(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.remove(finalListByName[position]);
                }

                // Update the title in CAB
                if (cab.size() == 0)
                    mode.setTitle("");
                else
                    mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }
        });
    }

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:com.sec.ose.osi.ui.frm.main.manage.JPanManageMain.java

public void loadFromCache() {
    UEAnalysisPanel ueAnalysisPanel = (UEAnalysisPanel) mCache
            .getUIEntity(UICache.UE_SELECTED_PROJECT_INFO_IN_ANALYSIS);
    ueProjectAnalysisSetting = (UEProjectAnalysisSetting) mCache.getUIEntity(UICache.UE_MONITOR_INTERVAL);

    if (ueAnalysisPanel != null) {
        ArrayList<UEProtexProjectInfo> list = ueAnalysisPanel.getAllElements();
        ArrayList<OSIProjectInfo> cacheProjectsList = new ArrayList<OSIProjectInfo>();
        StringBuffer analysisTargetProject = new StringBuffer();
        for (UEProtexProjectInfo projectInfo : list) {

            String projectName = projectInfo.getProjectName();

            boolean isExisted = UISDKInterfaceManager.getSDKInterface().isExistedProjectName(projectName, null);
            if (isExisted == false) {
                log.debug("add project to analysis table: " + projectName + " - not existed");
                continue;
            }//from  w  ww. j av a 2s  .  c  o  m
            log.debug("add project to analysis table: " + projectName);
            if (projectInfo.isAnalysisProject()) {
                analysisTargetProject.append("[" + projectInfo.getProjectName() + "] ");
            }

            OSIProjectInfo pInfo = UISDKInterfaceManager.getSDKInterface().getProjectInfoByName(projectName);
            if (pInfo != null) {
                cacheProjectsList.add(pInfo);
                pInfo.setManaged(true);
                pInfo.setProjectAnalysisInfo(projectInfo.isAnalysisProject());
                pInfo = ProjectAPIWrapper.loadAnalysisInfo(pInfo);
            }
        }

        if (analysisTargetProject.length() > 0) {
            writeConsoleWithTime("Current analysis target project : " + analysisTargetProject.toString());
        } else {
            writeConsoleWithTime("There is no analysis target project.");
        }

        /** Load Project advanced infomation **/
        while (cacheProjectsList.size() > 0) {
            for (int i = cacheProjectsList.size() - 1; i >= 0; i--) {
                if (cacheProjectsList.get(i).isLoaded()) {
                    cacheProjectsList.get(i).getProjectAnalysisInfo()
                            .setAnalysisStatus(cacheProjectsList.get(i).isAnalyzed());
                    setTableViewProperty(cacheProjectsList.get(i));
                    cacheProjectsList.remove(i);
                }
            }
        }

        setProjectTableModelList();
        managedProjectTableModel.checkAnalyzeAll(jTablePjtList);
    }

    setProjectAnalysisSetting(ueProjectAnalysisSetting);
}

From source file:edu.mit.media.funf.probe.Probe.java

/**
 * Updates request list with items in queue, replacing duplicate pending intents for this probe.
 * @param requests/* ww w.jav  a 2  s  . com*/
 */
private void updateRequests(boolean removeRunOnce) {
    assert requestsIntent != null;
    boolean hasChanges = false;
    ArrayList<Intent> requests = requestsIntent.getParcelableArrayListExtra(INTERNAL_REQUESTS_KEY);
    if (requests == null) {
        hasChanges = true;
        requests = new ArrayList<Intent>();
    }

    // Remove run once requests
    Parameter periodParam = Parameter.getAvailableParameter(getAvailableParameters(), Parameter.Builtin.PERIOD);
    if (periodParam != null && removeRunOnce) {
        for (Intent request : requests) {
            ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);
            List<Bundle> runOnceDataRequests = new ArrayList<Bundle>();
            for (Bundle dataRequest : dataRequests) {
                long periodValue = Utils.getLong(dataRequest, Parameter.Builtin.PERIOD.name,
                        (Long) periodParam.getValue());
                if (periodValue == 0L) {
                    Log.d(TAG, "Removing run once dataRequest: " + dataRequest);
                    runOnceDataRequests.add(dataRequest);
                }
            }
            dataRequests.removeAll(runOnceDataRequests);
            if (dataRequests.isEmpty()) {
                deadRequests.add(request);
            } else {
                request.putExtra(REQUESTS_KEY, dataRequests);
            }
        }
    }

    // Remove all requests that we aren't able to (or supposed to) send to anymore
    if (!deadRequests.isEmpty()) {
        hasChanges = true;
        for (Intent deadRequest = deadRequests.poll(); deadRequest != null; deadRequest = deadRequests.poll()) {
            Log.d(TAG, "Removing dead request: " + deadRequest);
            requests.remove(deadRequest);
        }
    }
    // Add any pending requests
    if (!pendingRequests.isEmpty()) {
        hasChanges = true;
        Map<PendingIntent, Intent> existingCallbacksToRequests = new HashMap<PendingIntent, Intent>();
        for (Intent existingRequest : requests) {
            PendingIntent callback = existingRequest.getParcelableExtra(CALLBACK_KEY);
            existingCallbacksToRequests.put(callback, existingRequest);
        }
        for (Intent request = pendingRequests.poll(); request != null; request = pendingRequests.poll()) {
            PendingIntent callback = request.getParcelableExtra(CALLBACK_KEY);
            if (packageHasRequiredPermissions(this, callback.getTargetPackage(), getRequiredPermissions())) {
                existingCallbacksToRequests.containsKey(callback);
                int existingRequestIndex = requests.indexOf(existingCallbacksToRequests.get(callback));
                ArrayList<Bundle> dataRequests = Utils.getArrayList(request.getExtras(), REQUESTS_KEY);
                Log.d(TAG, "Adding pending intent with data requests: " + dataRequests);
                if (existingRequestIndex >= 0) {
                    if (dataRequests == null || dataRequests.isEmpty()) {
                        Log.d(TAG, "Adding pending intent, removing because empty or null");
                        requests.remove(existingRequestIndex);
                    } else {
                        requests.set(existingRequestIndex, request);
                    }
                } else {
                    if (dataRequests != null && !dataRequests.isEmpty()) { // Only add requests with nonempty data requests
                        Log.d(TAG, "Adding new pending intent: " + request);
                        requests.add(request);
                    }
                }
            } else {
                Log.w(TAG, "Package '" + callback.getTargetPackage()
                        + "' does not have the required permissions to get data from this probe.");
            }
        }
    }

    if (hasChanges) {
        requestsIntent.putExtra(INTERNAL_REQUESTS_KEY, requests);
        updateInternalRequestsPendingIntent();
    }
}

From source file:com.twineworks.kettle.ruby.step.RubyStepSyntaxHighlighter.java

void highlight(String title, StyledTextComp wText) {
    // set up lexer process
    script = wText.getText();//from   w  w  w  .jav  a  2 s .  c  om
    StyledText canvas = wText.getStyledText();
    initBytes();
    initLexer(title);

    // remember bounds of current token
    int leftTokenBorder = 0;
    int rightTokenBorder = 0;
    int token = 0;
    int previousToken = 0;
    int lastCommentEnd = 0;

    ArrayList<StyleRange> ranges = new ArrayList<>(200);
    ArrayList<Integer> intRanges = new ArrayList<>(400);

    try {

        boolean keepParsing = true;

        while (keepParsing) {

            /* take care of comments, which are stripped out by the lexer */
            int[] upcomingComment = null;
            while ((rightTokenBorder >= lastCommentEnd || rightTokenBorder == 0)
                    && (upcomingComment = getUpcomingCommentPos(rightTokenBorder)) != null) {
                leftTokenBorder = upcomingComment[0];
                rightTokenBorder = leftTokenBorder + upcomingComment[1];
                lastCommentEnd = rightTokenBorder;
                //          System.out.println("Found comment -> [" + leftTokenBorder + "," + rightTokenBorder + "]");
                ranges.add(tokenToStyleRange(TOKEN_COMMENT, null, previousToken));

                int start = charOffset(leftTokenBorder);
                int count = charOffset(rightTokenBorder) - start;

                intRanges.add(start);
                intRanges.add(count);
            }

            /* read language syntax */
            int oldOffset = lexerOffset();
            previousToken = token;
            token = lexer.nextToken();
            keepParsing = !lexer.eofp;

            if (token > 0 && token != 10) {

                Object v = lexer.value();

                leftTokenBorder = oldOffset;
                if (leftTokenBorder < lastCommentEnd && lexerOffset() > lastCommentEnd) {
                    leftTokenBorder = lastCommentEnd;
                }
                rightTokenBorder = lexerOffset();

                //          System.out.println("Found token " + token + " -> " + lexer.value() + " [" + leftTokenBorder + "," + rightTokenBorder + "]");

                ranges.add(tokenToStyleRange(token, v, previousToken));
                int start = charOffset(leftTokenBorder);
                int count = charOffset(rightTokenBorder) - start;
                intRanges.add(start);
                intRanges.add(count);
            }

        }

        // don't mind anything that might go wrong during parsing
    } catch (SyntaxException e) {
        // apply the latest style to the rest of the file in case there is a syntax error
        if (ranges.size() > 0) {
            ranges.remove(ranges.size() - 1);
            intRanges.remove(intRanges.size() - 1);
            intRanges.remove(intRanges.size() - 1);
        }
        ranges.add(tokenToStyleRange(token, null, previousToken));
        int start = charOffset(leftTokenBorder);
        intRanges.add(start);
        intRanges.add(script.length() - start);

    } catch (Exception ignored) {
        // the lexer will sometimes throw a non-syntax exception when confronted with malformed input
        //      ignored.printStackTrace();
    }

    // don't mind swt errors in case some unforeseen input brought the style ranges out of order
    try {
        canvas.setStyleRanges(ArrayUtils.toPrimitive(intRanges.toArray(new Integer[0])),
                ranges.toArray(new StyleRange[0]));
    } catch (Exception e) {
        //      e.printStackTrace();
    }

}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

public void deDuplicate(ArrayList<ShortFeedItem> items) {
    int i = 1;/*from w  ww.java 2s .c o  m*/

    while (i < items.size()) {
        ShortFeedItem cur = items.get(i);
        ShortFeedItem prev = items.get(i - 1);

        boolean remove = false;

        if (cur.mLink.equals(prev.mLink)) {
            remove = true;
        } else if (cur.mTitle.equals(prev.mTitle)) {
            try {
                URI currentURI = new URI(cur.mLink);
                URI prevURI = new URI(prev.mLink);

                if (currentURI.getHost().equals(prevURI.getHost())) {
                    if (mLog.d())
                        mLog.d("removing duplicate from display because of title and host match");
                    remove = true;
                }
            } catch (URISyntaxException exc) {
                if (mLog.e())
                    mLog.e("deDuplicateArray error parsing links", exc);
            }
        }

        if (remove) {
            if (mLog.d())
                mLog.d("removing duplicate from display, link is " + cur.mLink);
            items.remove(i);
        } else {
            ++i;
        }
    }
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

/**
 * Remove series from the list where the names are the same, but one entry has a null or empty position.
 * eg. the followig list should be processed as indicated:
 * /*from   w ww.  j  a  v  a 2 s  . c om*/
 * fred(5)
 * fred <-- delete
 * bill <-- delete
 * bill <-- delete
 * bill(1)
 * 
 * @param list
 */
public static boolean pruneSeriesList(ArrayList<Series> list) {
    ArrayList<Series> toDelete = new ArrayList<Series>();
    Hashtable<String, Series> index = new Hashtable<String, Series>();

    for (Series s : list) {
        final boolean emptyNum = s.num == null || s.num.trim().equals("");
        final String lcName = s.name.trim().toLowerCase();
        final boolean inNames = index.containsKey(lcName);
        if (!inNames) {
            // Just add and continue
            index.put(lcName, s);
        } else {
            // See if we can purge either
            if (emptyNum) {
                // Always delete series with empty numbers if an equally or more specific one exists
                toDelete.add(s);
            } else {
                // See if the one in 'index' also has a num
                Series orig = index.get(lcName);
                if (orig.num == null || orig.num.trim().equals("")) {
                    // Replace with this one, and mark orig for delete
                    index.put(lcName, s);
                    toDelete.add(orig);
                } else {
                    // Both have numbers. See if they are the same.
                    if (s.num.trim().toLowerCase().equals(orig.num.trim().toLowerCase())) {
                        // Same exact series, delete this one
                        toDelete.add(s);
                    } else {
                        // Nothing to do: this is a different series position                     
                    }
                }
            }
        }
    }

    for (Series s : toDelete)
        list.remove(s);

    return (toDelete.size() > 0);

}

From source file:net.i2cat.csade.life2.backoffice.bl.StatisticsManager.java

public String getDatosProfiles() {
    ObjStats[] st = null;//w  ww. j  ava  2  s  .  co m
    ArrayList<Pair> datos = new ArrayList<Pair>();
    HashMap<Integer, Pair> hm = new HashMap<Integer, Pair>();
    Pair p;
    try {
        String sql = "SELECT t2.role as idStat,count(*) as Event,\"\" as User_login,null as dTime,0 as duration,\"\" as lat,\"\" as lon,\"\" as device,\"\" as query,0 as lng  FROM (SELECT s.*,u.role FROM Stat AS s INNER JOIN user_profile AS u ON s.User_login=u.Login AND s.event="
                + StatsDAO.LOGIN_EVENT + " ) AS t2 GROUP BY (role)";
        st = sd.listStatsSQL(sql);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServiceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (int i = 0; i < st.length; i++) {
        if (!hm.containsKey(new Integer(st[i].getIdStat()))) {
            datos.add(new Pair(PlatformUser.roleNames[st[i].getIdStat()], st[i].getIEvent()));
            hm.put(new Integer(st[i].getIdStat()),
                    new Pair(PlatformUser.roleNames[st[i].getIdStat()], st[i].getIEvent()));
        } else {
            Pair anterior = hm.get(new Integer(st[i].getIdStat()));
            datos.remove(anterior);
            anterior = new Pair(PlatformUser.roleNames[st[i].getIdStat()],
                    anterior.getValue() + st[i].getIEvent());
            datos.add(anterior);
            hm.put(new Integer(st[i].getIdStat()), anterior);
        }
    }
    return datos.toString();
}